@ancha-labs/cli 0.4.8 → 0.4.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/ancha.mjs +1218 -936
- package/lib/assets/SKILL.md +1 -1
- package/lib/assets/docs/cloud.md +5 -1
- package/lib/assets/docs/compare.md +1 -1
- package/lib/assets/docs/explain.md +1 -1
- package/lib/assets/docs/run.md +8 -4
- package/lib/assets/docs/setup.md +1 -1
- package/lib/assets/harbor/companion.mjs +9 -5
- package/lib/assets/ui/app.js +802 -217
- package/lib/assets/ui/style.css +244 -1
- package/lib/worker.mjs +38 -17
- package/lib/world-server.mjs +9 -5
- package/package.json +1 -1
package/lib/assets/ui/app.js
CHANGED
|
@@ -182,9 +182,9 @@ function sandboxOverview(s, o) {
|
|
|
182
182
|
const scene = { ...s.scene, twins: s.tools };
|
|
183
183
|
return `<section class="panel sandbox-map"><div class="row between"><h2>Tools & connections</h2>${s.setupOpen ? button("Manage tools", "configure-tools") : ""}</div>${s.tools?.length ? routes(scene, o) : empty("No tools added")}</section><section class="panel setup-panel"><div><span class="section-label">Scenario</span><h2>${s.key ? h(title(s.scene)) : "No scenario loaded"}</h2>${s.key ? `<a data-nav href="/scenarios/${encodeURIComponent(s.key)}">View scenario \u2192</a>` : ""}</div>${!s.key && s.setupOpen ? button("Load scenario", "load-scenario", "", "primary") : s.key ? `<div class="row"><span class="muted small">Paused \xB7 ${clock(o.simMs)}</span>${button("Next 30 seconds \u2192", "advance", "30000", "primary")}</div>` : ""}</section>${s.key ? `<div class="overview-footer">${button("Inspect activity & data", "inspect")}</div>` : ""}`;
|
|
184
184
|
}
|
|
185
|
-
function toolDataPanel(
|
|
186
|
-
const tables =
|
|
187
|
-
const calls =
|
|
185
|
+
function toolDataPanel(view2, selected = "") {
|
|
186
|
+
const tables = view2.tables ?? [], active = tables.find((t) => t.title === selected) ?? tables[0];
|
|
187
|
+
const calls = view2.conversations ?? [];
|
|
188
188
|
return `${tables.length > 1 ? `<div class="resource-tabs" aria-label="Records">${tables.map((t) => button(t.title, "resource", t.title, t === active ? "active" : "")).join("")}</div>` : ""}${active ? `<div class="row between"><h2>${h(active.title)}</h2><span class="small muted">${countLabel(active.total, "record")}</span></div>${table(active.rows, active.columns)}${active.rows.length < active.total ? `<p class="hint">Showing ${active.rows.length} of ${active.total} records.</p>` : ""}` : empty("No records yet.")}${calls.length && (!active || active.title === "Calls") ? `<div class="transcript-list">${calls.map((c, i) => `<div class="relationship-row"><span>${h(c.title)}</span>${button(c.messages.length ? "Read transcript" : c.status === "processing" ? "Processing" : "Unavailable", "conversation", String(i), "link")}</div>`).join("")}</div>` : ""}`;
|
|
189
189
|
}
|
|
190
190
|
function sandboxActivity(o) {
|
|
@@ -298,10 +298,10 @@ function ruleText(reason, name) {
|
|
|
298
298
|
const rule = /^rule (\d+): (.*)$/s.exec(text2);
|
|
299
299
|
if (!rule) return text2;
|
|
300
300
|
const [, number, condition] = rule;
|
|
301
|
-
const json3 = (
|
|
302
|
-
if (Array.isArray(
|
|
303
|
-
for (const [key, joiner] of [["all", " and "], ["any", " or "]]) if (Array.isArray(
|
|
304
|
-
const parts =
|
|
301
|
+
const json3 = (when2) => {
|
|
302
|
+
if (Array.isArray(when2?.fact) && when2.fact.length === 3 && COMPARE[when2.fact[1]] && typeof when2.fact[2] === "number") return `${factLabel(when2.fact[0], name)} ${COMPARE[when2.fact[1]]} ${when2.fact[2]}`;
|
|
303
|
+
for (const [key, joiner] of [["all", " and "], ["any", " or "]]) if (Array.isArray(when2?.[key])) {
|
|
304
|
+
const parts = when2[key].map(json3);
|
|
305
305
|
return parts.length && parts.every(Boolean) ? parts.join(joiner) : void 0;
|
|
306
306
|
}
|
|
307
307
|
return void 0;
|
|
@@ -365,8 +365,8 @@ function peopleSection(world) {
|
|
|
365
365
|
const persons = list(world.people ?? world.configuration?.people);
|
|
366
366
|
if (!persons.length) return "";
|
|
367
367
|
return `<section class="world-people"><div class="ww-section-heading"><h2>People</h2><span>${persons.length}</span></div><div class="world-people-list">${persons.map((person2) => {
|
|
368
|
-
const
|
|
369
|
-
return `<article class="world-person"><strong>${h(String(person2.name ?? person2.ref ?? "Person"))}</strong><span class="muted">${h(String(person2.role ?? ""))}</span><span>${
|
|
368
|
+
const facts2 = list(person2.knows).length, decides = list(person2.decides).map((decision) => String(decision.id));
|
|
369
|
+
return `<article class="world-person"><strong>${h(String(person2.name ?? person2.ref ?? "Person"))}</strong><span class="muted">${h(String(person2.role ?? ""))}</span><span>${facts2} ${facts2 === 1 ? "fact" : "facts"}${decides.length ? ` \xB7 decides ${h(decides.join(", "))}` : ""}</span></article>`;
|
|
370
370
|
}).join("")}</div></section>`;
|
|
371
371
|
}
|
|
372
372
|
|
|
@@ -436,7 +436,6 @@ var navTabs = (items, selected) => `<nav class="tabs" aria-label="Page sections"
|
|
|
436
436
|
|
|
437
437
|
// frontend/src/playground.ts
|
|
438
438
|
var attemptLabel = (state) => ({ queued: "Queued", starting: "Starting container\u2026", running: "Running", completed: "Completed", stopped: "Stopped", error: "Error" })[state] ?? "Unavailable";
|
|
439
|
-
var attemptBadge = (state) => badge(attemptLabel(state), state === "error" ? "bad" : state === "completed" ? "good" : ["running", "starting"].includes(state) ? "accent" : "");
|
|
440
439
|
var terminal = (state) => ["completed", "stopped", "error"].includes(state);
|
|
441
440
|
var ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : { 1: "st", 2: "nd", 3: "rd" }[n % 10] ?? "th"}`;
|
|
442
441
|
function queueLabel(queue) {
|
|
@@ -477,13 +476,6 @@ function readableResponse(response) {
|
|
|
477
476
|
function timeLimit(ms) {
|
|
478
477
|
return ms < 6e4 ? `${Math.ceil(ms / 1e3)} sec` : `${Number((ms / 6e4).toFixed(1))} min`;
|
|
479
478
|
}
|
|
480
|
-
function batchHistory(batches) {
|
|
481
|
-
if (!batches.length) return '<p class="quiet-empty">No runs yet.</p>';
|
|
482
|
-
return `<div class="batch-history">${batches.map((batch) => {
|
|
483
|
-
const counts = batchCounts(batch), tasks = batch.tasks ?? [], name = shortPrompt(batch.groupName || batch.test?.name || tasks[0]?.title || tasks[0]?.prompt) || "Untitled task";
|
|
484
|
-
return `<a class="batch-history-row" href="/playgrounds/${encodeURIComponent(batch.id)}" data-nav><div><strong>${h(name)}</strong>${!batch.groupName && !batch.test?.name && tasks.length > 1 ? `<span class="history-more">+${tasks.length - 1} ${tasks.length === 2 ? "task" : "tasks"}</span>` : ""}<small>${h(appTime(batch.createdAt) || "Date unavailable")}</small></div>${attemptBadge(batch.status)}<span class="muted">${terminal(batch.status) ? counts.total + " trials" : batch.status === "queued" && batch.queue ? h(queueLabel(batch.queue)) : counts.finished + " / " + counts.total + " finished"}</span><span aria-hidden="true">\u2192</span></a>`;
|
|
485
|
-
}).join("")}</div>`;
|
|
486
|
-
}
|
|
487
479
|
function taskFields(tasks) {
|
|
488
480
|
return tasks.map((task, index) => `<section class="task-editor" data-task-id="${h(task.id)}"><div class="task-heading"><h2>Task ${index + 1}</h2>${tasks.length > 1 ? button("Remove", "remove-task", task.id, "link") : ""}</div><label class="sr-only" for="task-${index}">Task ${index + 1}</label><textarea id="task-${index}" name="prompt" rows="3" required maxlength="20000" placeholder="What should your agent do?">${h(task.prompt)}</textarea><div class="task-options"><label>Trials<input name="attempts" type="number" min="1" max="100" value="${h(task.attempts ?? 1)}" required></label><label>Time limit <span class="muted">minutes</span><input name="minutes" type="number" min="0.016666666666666666" max="60" step="any" value="${h((task.timeoutMs ?? 3e5) / 6e4)}" required></label></div></section>`).join("");
|
|
489
481
|
}
|
|
@@ -510,6 +502,285 @@ function responseView(attempt) {
|
|
|
510
502
|
return `<p class="quiet-empty">${terminal(attempt.status) ? "No final response was captured." : "No final response yet."}</p>`;
|
|
511
503
|
}
|
|
512
504
|
|
|
505
|
+
// frontend/src/ui.ts
|
|
506
|
+
var STATUS = {
|
|
507
|
+
passed: { label: "Passed", path: "M5.2 8.3l1.9 1.9 3.8-4.2" },
|
|
508
|
+
failed: { label: "Failed", path: "M5.8 5.8l4.4 4.4M10.2 5.8l-4.4 4.4" },
|
|
509
|
+
invalid: { label: "Invalid", path: "M8 4.8v3.6M8 10.9v.2" },
|
|
510
|
+
skipped: { label: "Skipped", path: "M5.6 8h4.8" },
|
|
511
|
+
running: { label: "Running", path: "M8 8h.01", dash: "30 10" },
|
|
512
|
+
queued: { label: "Queued", path: "M8 5v3.2l2 1.3" },
|
|
513
|
+
stopped: { label: "Stopped", path: "M6.3 6.3h3.4v3.4H6.3z" },
|
|
514
|
+
error: { label: "Error", path: "M8 4.8v3.6M8 10.9v.2" },
|
|
515
|
+
ungraded: { label: "Not graded", path: "M5.6 8h4.8" }
|
|
516
|
+
};
|
|
517
|
+
var statusLabel = (kind) => STATUS[kind].label;
|
|
518
|
+
function glyph(kind, size = 16, label2) {
|
|
519
|
+
const s = STATUS[kind];
|
|
520
|
+
return `<svg class="c-glyph c-${kind}" width="${size}" height="${size}" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" ${label2 ? `role="img" aria-label="${h(label2)}"` : 'aria-hidden="true"'}><circle cx="8" cy="8" r="6.4"${s.dash ? ` stroke-dasharray="${s.dash}"` : ""}/><path d="${s.path}"/></svg>`;
|
|
521
|
+
}
|
|
522
|
+
var statusMark = (kind, label2 = statusLabel(kind)) => `<span class="c-status c-${kind}">${glyph(kind)}<span>${h(label2)}</span></span>`;
|
|
523
|
+
var statusPill = (kind, label2 = statusLabel(kind)) => `<span class="c-pill c-${kind}">${glyph(kind, 15)}${h(label2)}</span>`;
|
|
524
|
+
var tag = (text2, tone = "neutral") => `<span class="c-tag c-tone-${tone}">${h(text2)}</span>`;
|
|
525
|
+
var COPY = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5.5A1.5 1.5 0 0 1 6.5 4H15"/></svg>';
|
|
526
|
+
var copyButton = (value, label2) => `<button type="button" class="c-copy" data-action="copy-text" data-value="${h(value)}" aria-label="${h(label2)}" title="${h(label2)}">${COPY}</button>`;
|
|
527
|
+
var copyCommand = (command) => `<div class="c-command"><code>${h(command)}</code>${copyButton(command, "Copy command")}</div>`;
|
|
528
|
+
function shortId(id, keep = 8) {
|
|
529
|
+
const prefix = /^[a-z]+_/.exec(id)?.[0] ?? "";
|
|
530
|
+
return id.length > prefix.length + keep + 2 ? `${prefix}\u2026${id.slice(-keep)}` : id;
|
|
531
|
+
}
|
|
532
|
+
var facts = (items, label2 = "Facts") => `<dl class="c-facts" aria-label="${h(label2)}">${items.map((f) => `<div><dt>${h(f.label)}</dt><dd class="c-fact-value${f.mono ? " mono" : ""}"${f.title ? ` title="${h(f.title)}"` : ""}>${f.html ?? h(f.value)}</dd>${f.sub ? `<dd class="c-fact-sub">${h(f.sub)}</dd>` : ""}</div>`).join("")}</dl>`;
|
|
533
|
+
var strip = (states, label2) => `<span class="c-strip${states.length > 12 ? " dense" : ""}" role="img" aria-label="${h(label2)}">${states.map((s) => `<i class="c-seg ${h(s)}"></i>`).join("")}</span>`;
|
|
534
|
+
var stateCard = (title2, bodyHtml = "", actionHtml = "", kind = "empty") => `<section class="c-state c-state-${h(kind)}"><strong>${h(title2)}</strong>${bodyHtml ? `<p>${bodyHtml}</p>` : ""}${actionHtml}</section>`;
|
|
535
|
+
var skeletonRows = (count) => `<div class="c-skeleton" aria-busy="true" aria-label="Loading">${Array.from({ length: count }, () => "<div><i></i><i></i><i></i></div>").join("")}</div>`;
|
|
536
|
+
var MINUTE = 6e4;
|
|
537
|
+
var HOUR2 = 36e5;
|
|
538
|
+
var DAY2 = 864e5;
|
|
539
|
+
var timeOf = (value) => {
|
|
540
|
+
const ms = typeof value === "number" ? value : Date.parse(String(value ?? ""));
|
|
541
|
+
return Number.isFinite(ms) ? ms : NaN;
|
|
542
|
+
};
|
|
543
|
+
var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
544
|
+
function utcDay(value) {
|
|
545
|
+
const ms = timeOf(value);
|
|
546
|
+
if (!Number.isFinite(ms)) return "";
|
|
547
|
+
const d = new Date(ms);
|
|
548
|
+
return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}`;
|
|
549
|
+
}
|
|
550
|
+
function utcClock(value) {
|
|
551
|
+
const ms = timeOf(value);
|
|
552
|
+
return Number.isFinite(ms) ? `${new Date(ms).toISOString().slice(11, 19)} UTC` : "";
|
|
553
|
+
}
|
|
554
|
+
function utc(value) {
|
|
555
|
+
const day = utcDay(value);
|
|
556
|
+
return day ? `${day}, ${utcClock(value)}` : "";
|
|
557
|
+
}
|
|
558
|
+
function ago(value, now = Date.now()) {
|
|
559
|
+
const ms = timeOf(value);
|
|
560
|
+
if (!Number.isFinite(ms)) return "";
|
|
561
|
+
const since = now - ms;
|
|
562
|
+
if (since < 45e3) return "just now";
|
|
563
|
+
if (since < HOUR2) return `${Math.max(1, Math.round(since / MINUTE))} min ago`;
|
|
564
|
+
if (since < DAY2) return `${Math.round(since / HOUR2)} h ago`;
|
|
565
|
+
return utcDay(ms);
|
|
566
|
+
}
|
|
567
|
+
var when = (value, now = Date.now()) => {
|
|
568
|
+
const text2 = ago(value, now);
|
|
569
|
+
return text2 ? `<time datetime="${h(new Date(timeOf(value)).toISOString())}" title="${h(utc(value))}">${h(text2)}</time>` : "";
|
|
570
|
+
};
|
|
571
|
+
function duration(ms) {
|
|
572
|
+
const n = Number(ms);
|
|
573
|
+
if (ms === null || ms === void 0 || !Number.isFinite(n) || n < 0) return "\u2014";
|
|
574
|
+
if (n < 1e4) return `${(n / 1e3).toFixed(1)} s`;
|
|
575
|
+
const s = Math.round(n / 1e3);
|
|
576
|
+
if (s < 60) return `${s} s`;
|
|
577
|
+
if (s < 3600) return `${Math.floor(s / 60)} m ${String(s % 60).padStart(2, "0")} s`;
|
|
578
|
+
return `${Math.floor(s / 3600)} h ${String(Math.floor(s / 60) % 60).padStart(2, "0")} m`;
|
|
579
|
+
}
|
|
580
|
+
function median(values, at2 = 0.5) {
|
|
581
|
+
const sorted = values.filter(Number.isFinite).sort((a, b) => a - b);
|
|
582
|
+
return sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * at2 + 0.5))] : void 0;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// frontend/src/runs-page.ts
|
|
586
|
+
var SOURCES = { console: "Console", cli: "CLI", ci: "CI", cloud: "Cloud" };
|
|
587
|
+
var RANGES = { "24h": ["24 h", 864e5], "7d": ["7 d", 7 * 864e5], "30d": ["30 d", 30 * 864e5] };
|
|
588
|
+
var PAGE = 25;
|
|
589
|
+
function originLabel(origin) {
|
|
590
|
+
if (!origin?.source) return "";
|
|
591
|
+
const commit = origin.commit ? `${String(origin.commit).slice(0, 7)}${origin.dirty ? " + changes" : ""}` : "";
|
|
592
|
+
const target = String(origin.target ?? "").toLowerCase();
|
|
593
|
+
return [SOURCES[origin.source] ?? String(origin.source), target === origin.source ? "" : target, commit].filter(Boolean).join(" \xB7 ");
|
|
594
|
+
}
|
|
595
|
+
function whereKey(origin) {
|
|
596
|
+
const source = String(origin?.source ?? ""), target = String(origin?.target ?? "");
|
|
597
|
+
return source === "cloud" || target === "cloud" ? "cloud" : source === "ci" ? "ci" : target === "docker" ? "docker" : target === "hosted" ? "hosted" : source === "console" || !source ? "console" : "local";
|
|
598
|
+
}
|
|
599
|
+
var WHERE = { cloud: "Cloud", ci: "CI", local: "Local", docker: "Docker", hosted: "Hosted", console: "Console" };
|
|
600
|
+
function whereLabel(origin) {
|
|
601
|
+
const commit = origin?.commit ? `${String(origin.commit).slice(0, 7)}${origin.dirty ? " + changes" : ""}` : "";
|
|
602
|
+
return [WHERE[whereKey(origin)], commit].filter(Boolean).join(" \xB7 ");
|
|
603
|
+
}
|
|
604
|
+
function runCounts(run) {
|
|
605
|
+
const summary = run.summary, tasks = run.tasks ?? [], attempts = run.attempts ?? [];
|
|
606
|
+
const verified = summary?.verdictVersion === 2 ? summary.counts : void 0;
|
|
607
|
+
const declared = tasks.length && tasks.every((task) => Number.isSafeInteger(task.attempts) && task.attempts > 0) ? tasks.reduce((sum2, task) => sum2 + task.attempts, 0) : void 0;
|
|
608
|
+
const requested = verified?.requested ?? declared;
|
|
609
|
+
const passed = verified?.passed ?? attempts.filter((a) => a.outcome === "passed").length;
|
|
610
|
+
const invalid = verified?.invalid ?? attempts.filter((a) => a.outcome === "invalid").length;
|
|
611
|
+
const skipped = verified?.skipped ?? attempts.filter((a) => a.outcome === "skipped").length;
|
|
612
|
+
const failed = attempts.filter((a) => a.outcome === "failed").length;
|
|
613
|
+
const graded = typeof summary?.pass_rate === "number" || attempts.some((a) => ["passed", "failed"].includes(a.outcome));
|
|
614
|
+
return { requested, total: requested ?? attempts.length, passed, failed, invalid, skipped, graded, finished: batchCounts(run).finished };
|
|
615
|
+
}
|
|
616
|
+
function runStatus(run) {
|
|
617
|
+
if (run.status === "queued") return "queued";
|
|
618
|
+
if (!terminal(run.status)) return "running";
|
|
619
|
+
const c = runCounts(run);
|
|
620
|
+
if (run.status === "stopped" && !c.graded) return "stopped";
|
|
621
|
+
if (run.status === "error" && !c.graded) return "error";
|
|
622
|
+
if (!c.graded) return c.invalid ? "invalid" : c.skipped && c.skipped === c.total ? "skipped" : "ungraded";
|
|
623
|
+
if (run.verdict === "pass" || run.verdict === "fail") return run.verdict === "pass" ? "passed" : "failed";
|
|
624
|
+
return c.passed === c.total ? "passed" : "failed";
|
|
625
|
+
}
|
|
626
|
+
function runTitle(run) {
|
|
627
|
+
const tasks = run.tasks ?? [];
|
|
628
|
+
if (run.groupName) return String(run.groupName);
|
|
629
|
+
if (tasks.length === 1) return shortPrompt(tasks[0].prompt) || String(tasks[0].title || batchTitle(run));
|
|
630
|
+
return tasks.length ? `${tasks.length} tests` : batchTitle(run);
|
|
631
|
+
}
|
|
632
|
+
var cliRun = (run) => ["cli", "ci", "cloud", "pytest"].includes(run.origin?.source);
|
|
633
|
+
function runRef(run) {
|
|
634
|
+
const tasks = run.tasks ?? [];
|
|
635
|
+
const test = tasks.length === 1 ? cliRun(run) ? String(tasks[0].id) : String(run.test?.name ?? "") : tasks.length > 1 ? `${tasks.length} tests` : "";
|
|
636
|
+
return [shortId(String(run.id)), test].filter(Boolean).join(" \xB7 ");
|
|
637
|
+
}
|
|
638
|
+
function productionTag(reproduction) {
|
|
639
|
+
const rows3 = Array.isArray(reproduction) ? reproduction.filter((r) => r && typeof r === "object") : [];
|
|
640
|
+
if (!rows3.length) return "";
|
|
641
|
+
const count = (verdict) => rows3.filter((r) => r.verdict === verdict).length;
|
|
642
|
+
const again = count("reproduced") + count("partly") + count("crashed"), fixed = count("not-reproduced"), differs = count("differs");
|
|
643
|
+
if (rows3.length === 1) {
|
|
644
|
+
const [text2, tone] = { reproduced: ["Same failure", "fail"], partly: ["Partly the same", "fail"], crashed: ["Agent crashed", "fail"], "not-reproduced": ["Fixed", "pass"], matches: ["Matches production", "pass"], differs: ["New failure", "warn"], unknown: ["Production ungraded", "neutral"], ungraded: ["Not compared", "neutral"] }[String(rows3[0].verdict)] ?? ["Not compared", "neutral"];
|
|
645
|
+
return tag(text2, tone);
|
|
646
|
+
}
|
|
647
|
+
if (again) return tag(`${again} of ${rows3.length} fail again`, "fail");
|
|
648
|
+
if (differs) return tag(`${differs} new ${differs === 1 ? "failure" : "failures"}`, "warn");
|
|
649
|
+
if (fixed) return tag(`${fixed} of ${rows3.length} fixed`, "pass");
|
|
650
|
+
return count("matches") === rows3.length ? tag("Matches production", "pass") : tag("Not compared", "neutral");
|
|
651
|
+
}
|
|
652
|
+
function baselineNote(run) {
|
|
653
|
+
const comparison = run.comparison;
|
|
654
|
+
if (!comparison || !Array.isArray(comparison.scenes)) return void 0;
|
|
655
|
+
const name = comparison.baselineRunId ? `vs ${shortId(String(comparison.baselineRunId))}` : "vs baseline";
|
|
656
|
+
if (comparison.scenes.length === 1) {
|
|
657
|
+
const delta = Math.round(Number(comparison.scenes[0].delta) * 100);
|
|
658
|
+
if (Number.isFinite(delta)) return { text: delta ? `${delta > 0 ? "+" : "\u2212"}${Math.abs(delta)} pts ${name}` : `no change ${name}`, tone: delta > 0 ? "pass" : delta < 0 ? "fail" : "neutral" };
|
|
659
|
+
}
|
|
660
|
+
return comparison.regressed ? { text: `regressed ${name}`, tone: "fail" } : { text: `held ${name}`, tone: "neutral" };
|
|
661
|
+
}
|
|
662
|
+
function attemptStates(run) {
|
|
663
|
+
const attempts = run.attempts ?? [], c = runCounts(run);
|
|
664
|
+
const states = attempts.map((a) => ["passed", "failed", "invalid", "skipped"].includes(a.outcome) ? a.outcome : ["running", "starting"].includes(a.status) ? "running" : a.status === "queued" ? "queued" : terminal(a.status) ? "done" : "queued");
|
|
665
|
+
while (states.length < c.total) states.push("queued");
|
|
666
|
+
return states;
|
|
667
|
+
}
|
|
668
|
+
function runMs(run, now) {
|
|
669
|
+
const start = timeOf(run.createdAt), end = timeOf(run.finishedAt);
|
|
670
|
+
if (!Number.isFinite(start)) return void 0;
|
|
671
|
+
if (Number.isFinite(end)) return end - start;
|
|
672
|
+
return terminal(run.status) ? void 0 : now - start;
|
|
673
|
+
}
|
|
674
|
+
function view(run, now) {
|
|
675
|
+
return { run, status: runStatus(run), title: runTitle(run), agent: String(run.agentName ?? run.entries?.[0]?.agentName ?? ""), where: whereKey(run.origin), ms: runMs(run, now) };
|
|
676
|
+
}
|
|
677
|
+
function rateCell(row2) {
|
|
678
|
+
const run = row2.run, c = runCounts(run);
|
|
679
|
+
if (row2.status === "queued") return `<strong>\u2014</strong><span class="c-note">${h(queueLabel(run.queue) || "queued")}</span>`;
|
|
680
|
+
if (row2.status === "running") return `<strong>\u2014</strong><span class="c-note">graded as they finish</span>`;
|
|
681
|
+
if (!c.graded) return `<strong>\u2014</strong><span class="c-note${c.invalid ? " c-tone-warn" : ""}">${h(c.invalid ? `${c.invalid} invalid` : c.skipped ? `${c.skipped} skipped` : "no checks")}</span>`;
|
|
682
|
+
const rate = c.requested ? `${Math.round(c.passed / c.requested * 100)}%` : "\u2014";
|
|
683
|
+
const notes = [c.requested ? "" : "Unverified rate \xB7 rerun", c.invalid ? `${c.invalid} invalid` : "", c.skipped ? `${c.skipped} skipped` : ""].filter(Boolean);
|
|
684
|
+
const baseline = baselineNote(run);
|
|
685
|
+
const note = baseline && !notes.length ? `<span class="c-note c-tone-${baseline.tone}">${h(baseline.text)}</span>` : notes.length ? `<span class="c-note${c.invalid ? " c-tone-warn" : ""}">${h(notes.join(" \xB7 "))}</span>` : "";
|
|
686
|
+
return `<strong>${h(rate)}</strong>${note}`;
|
|
687
|
+
}
|
|
688
|
+
function startedCell(row2, now) {
|
|
689
|
+
const run = row2.run, ms = row2.ms;
|
|
690
|
+
const length = row2.status === "queued" ? "queued" : !terminal(run.status) ? `${duration(ms)} so far` : duration(ms);
|
|
691
|
+
return `${when(run.createdAt, now)}<span class="c-note">${h(length)}</span>`;
|
|
692
|
+
}
|
|
693
|
+
function row(item, now) {
|
|
694
|
+
const run = item.run, c = runCounts(run), states = attemptStates(run);
|
|
695
|
+
const counted = `${c.finished} / ${c.total}`, label2 = `${counted} attempts finished${c.graded ? `, ${c.passed} passed` : ""}${c.invalid ? `, ${c.invalid} invalid` : ""}`;
|
|
696
|
+
return `<a class="rt-row" href="/playgrounds/${encodeURIComponent(String(run.id))}" data-nav><span class="rt-result">${statusMark(item.status)}</span><span class="rt-test"><span class="rt-title" title="${h(item.title)}">${h(item.title)}</span><span class="rt-ref mono">${h(runRef(run))}</span></span><span class="rt-agent"><span class="rt-agent-name">${h(item.agent || "\u2014")}</span><span class="c-note">${h(whereLabel(run.origin))}</span></span><span class="rt-attempts">${strip(states, label2)}<span class="c-note">${h(counted)}</span></span><span class="rt-passed">${rateCell(item)}</span><span class="rt-prod">${productionTag(run.reproduction) || '<span class="c-note">\u2014</span>'}</span><span class="rt-started">${startedCell(item, now)}</span></a>`;
|
|
697
|
+
}
|
|
698
|
+
function runsTable(runs, options = {}) {
|
|
699
|
+
const now = options.now ?? Date.now();
|
|
700
|
+
return `<div class="rt-scroll"><div class="rt" aria-label="Runs"><div class="rt-head" aria-hidden="true"><span>Result</span><span>Test</span><span>Agent</span><span>Attempts</span><span class="num">Passed</span><span>vs production</span><span class="num">Started</span></div>${runs.map((run) => row(view(run, now), now)).join("")}</div></div>`;
|
|
701
|
+
}
|
|
702
|
+
function failingTests(rows3) {
|
|
703
|
+
const seen = /* @__PURE__ */ new Set(), failing = [];
|
|
704
|
+
for (const item of rows3) {
|
|
705
|
+
if (!terminal(item.run.status)) continue;
|
|
706
|
+
const attempts = item.run.attempts ?? [];
|
|
707
|
+
for (const task of item.run.tasks ?? []) {
|
|
708
|
+
const key = `${item.run.test?.id ?? ""}:${task.id}`;
|
|
709
|
+
if (seen.has(key)) continue;
|
|
710
|
+
seen.add(key);
|
|
711
|
+
if (attempts.some((a) => a.taskId === task.id && a.outcome === "failed")) failing.push([shortPrompt(task.prompt) || String(task.title || task.id), item.agent]);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
return failing;
|
|
715
|
+
}
|
|
716
|
+
function stats(rows3, range, now) {
|
|
717
|
+
const done = rows3.filter((r) => terminal(r.run.status));
|
|
718
|
+
const passedRuns = rows3.filter((r) => r.status === "passed").length, failedRuns = rows3.filter((r) => r.status === "failed").length;
|
|
719
|
+
const counts = done.map((r) => runCounts(r.run)).filter((c) => c.graded && c.requested);
|
|
720
|
+
const requested = counts.reduce((n, c) => n + c.requested, 0), passed = counts.reduce((n, c) => n + c.passed, 0);
|
|
721
|
+
const failing = failingTests(rows3);
|
|
722
|
+
const times = done.map((r) => r.ms).filter((ms) => ms !== void 0);
|
|
723
|
+
const cell2 = (label2, value, sub, tone = "") => `<div class="rs-cell"><span>${h(label2)}</span><strong${tone ? ` class="c-tone-${tone}"` : ""}>${h(value)}</strong><small>${h(sub)}</small></div>`;
|
|
724
|
+
return `<section class="rs-strip" aria-label="Summary of the runs shown">` + cell2("Runs", String(rows3.length), `${passedRuns} passed \xB7 ${failedRuns} failed \xB7 ${rows3.length - passedRuns - failedRuns} other`) + cell2("Attempts passed", requested ? `${Math.round(passed / requested * 100)}%` : "\u2014", requested ? `${passed} of ${requested} attempts` : "no graded attempts") + cell2("Tests failing now", String(failing.length), failing.length ? failing[0].filter(Boolean).join(" \xB7 ") : "none", failing.length ? "fail" : "") + cell2("Median run time", duration(median(times)), times.length > 1 ? `p90 ${duration(median(times, 0.9))}` : times.length ? "one run" : "no finished runs") + perDay(rows3, range, now) + "</section>";
|
|
725
|
+
}
|
|
726
|
+
function perDay(rows3, range, now) {
|
|
727
|
+
const hourly = range === "24h", size = hourly ? 36e5 : 864e5;
|
|
728
|
+
const startOfBucket = (ms) => {
|
|
729
|
+
const d = new Date(ms);
|
|
730
|
+
return hourly ? Math.floor(ms / size) * size : Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
|
|
731
|
+
};
|
|
732
|
+
const count = hourly ? 24 : range === "7d" ? 7 : 30, last = startOfBucket(now);
|
|
733
|
+
const buckets = Array.from({ length: count }, (_, i) => ({ at: last - (count - 1 - i) * size, passed: 0, failed: 0, other: 0 }));
|
|
734
|
+
for (const item of rows3) {
|
|
735
|
+
const at2 = timeOf(item.run.createdAt), bucket = Number.isFinite(at2) ? buckets.find((b) => b.at === startOfBucket(at2)) : void 0;
|
|
736
|
+
if (bucket) bucket[item.status === "passed" ? "passed" : item.status === "failed" ? "failed" : "other"] += 1;
|
|
737
|
+
}
|
|
738
|
+
const W = 10, H = 52, most = Math.max(1, ...buckets.map((b) => b.passed + b.failed + b.other));
|
|
739
|
+
const name = (b) => hourly ? `${new Date(b.at).toISOString().slice(11, 16)} UTC` : utcDay(b.at);
|
|
740
|
+
const bars = buckets.map((b, i) => {
|
|
741
|
+
let y = H;
|
|
742
|
+
const parts = ["passed", "failed", "other"].map((kind) => {
|
|
743
|
+
if (!b[kind]) return "";
|
|
744
|
+
const height = Math.max(2, Math.round(b[kind] / most * H));
|
|
745
|
+
y -= height;
|
|
746
|
+
return `<rect class="${kind}" x="${i * W + 1}" y="${y}" width="${W - 2}" height="${height}"/>`;
|
|
747
|
+
}).join("");
|
|
748
|
+
return parts ? `<g><title>${h(`${name(b)}: ${b.passed} passed, ${b.failed} failed, ${b.other} other`)}</title>${parts}</g>` : "";
|
|
749
|
+
}).join("");
|
|
750
|
+
const total = buckets.reduce((n, b) => n + b.passed + b.failed + b.other, 0), span = hourly ? "the last 24 hours" : `the last ${count} days`;
|
|
751
|
+
const labels = count === 7 ? buckets.map(name) : [name(buckets[0]), name(buckets[Math.floor(count / 2)]), name(buckets[count - 1])];
|
|
752
|
+
return `<div class="rs-cell rs-days"><div class="rs-days-head"><span>${hourly ? "Runs per hour" : "Runs per day"}</span><span class="rs-legend"><i class="passed"></i>Passed<i class="failed"></i>Failed<i class="other"></i>Other</span></div><svg class="rs-chart" viewBox="0 0 ${count * W} ${H}" preserveAspectRatio="none" role="img" aria-label="${h(`${total} ${total === 1 ? "run" : "runs"} over ${span}`)}"><line class="axis" x1="0" y1="${H - 0.5}" x2="${count * W}" y2="${H - 0.5}"/>${bars}</svg><div class="rs-labels${count === 7 ? " even" : ""}">${labels.map((label2) => `<span>${h(label2)}</span>`).join("")}</div></div>`;
|
|
753
|
+
}
|
|
754
|
+
function filterUrl(filters, change) {
|
|
755
|
+
const next = { ...filters, ...change }, params = new URLSearchParams();
|
|
756
|
+
for (const key of ["q", "range", "agent", "result", "where", "commit", "source", "target", "limit"]) if (next[key] !== void 0 && next[key] !== "" && !(key === "limit" && Number(next[key]) === PAGE)) params.set(key, String(next[key]));
|
|
757
|
+
return "/playgrounds" + (params.size ? "?" + params : "");
|
|
758
|
+
}
|
|
759
|
+
var RESULT_ORDER = ["passed", "failed", "invalid", "skipped", "running", "queued", "stopped", "error", "ungraded"];
|
|
760
|
+
function runsPage(runs, filters, options = {}) {
|
|
761
|
+
const now = options.now ?? Date.now(), range = RANGES[filters.range ?? ""] ? filters.range : "";
|
|
762
|
+
const head2 = (meta2) => `<header class="page-head runs-head"><div><h1>Runs</h1>${meta2 ? `<p class="page-meta">${h(meta2)}</p>` : ""}</div><div class="actions"><nav class="c-segmented" aria-label="Time range">${[["", "All"], ...Object.entries(RANGES).map(([key, [label2]]) => [key, label2])].map(([key, label2]) => `<a href="${h(filterUrl(filters, { range: key, limit: void 0 }))}" data-nav${key === range ? ' aria-current="page"' : ""}>${h(label2)}</a>`).join("")}</nav>${copyCommand("ancha run --on cloud")}</div></header>`;
|
|
763
|
+
if (!runs.length) return head2("") + stateCard("No runs yet", options.emptyHtml ?? "Runs from the CLI, CI and this console land here. Run your first test in the cloud:", copyCommand("ancha run --on cloud"));
|
|
764
|
+
const all = runs.map((run) => view(run, now)).sort((a, b) => timeOf(b.run.createdAt) - timeOf(a.run.createdAt) || String(b.run.id).localeCompare(String(a.run.id)));
|
|
765
|
+
const inRange = range ? all.filter((item) => now - timeOf(item.run.createdAt) <= RANGES[range][1]) : all;
|
|
766
|
+
const values = (pick, chosen) => [...new Set([...all.map(pick), chosen].filter((v) => Boolean(v)))];
|
|
767
|
+
const query = String(filters.q ?? "").trim().toLowerCase();
|
|
768
|
+
const matches = (item) => !query || [item.title, item.run.id, item.agent, item.run.test?.name, ...(item.run.tasks ?? []).flatMap((t) => [t.id, t.title, t.prompt])].some((v) => String(v ?? "").toLowerCase().includes(query));
|
|
769
|
+
const shown = inRange.filter((item) => matches(item) && (!filters.agent || item.agent === filters.agent || item.run.agentId === filters.agent || item.run.entries?.some((entry) => entry.agentId === filters.agent)) && (!filters.result || item.status === filters.result) && (!filters.where || item.where === filters.where) && (!filters.commit || item.run.origin?.commit === filters.commit) && (!filters.source || item.run.origin?.source === filters.source) && (!filters.target || item.run.origin?.target === filters.target));
|
|
770
|
+
const select = (name, label2, choices, all2 = "All") => `<label class="c-select"><span>${h(label2)}</span><select name="${name}" data-run-filter><option value="">${h(all2)}</option>${choices.map(([value, text2]) => `<option value="${h(value)}" ${filters[name] === value ? "selected" : ""}>${h(text2)}</option>`).join("")}</select></label>`;
|
|
771
|
+
const commits = values((item) => item.run.origin?.commit, filters.commit);
|
|
772
|
+
const named2 = filters.agent ? all.find((item) => item.run.agentId === filters.agent)?.agent : void 0;
|
|
773
|
+
const agentChoices = values((item) => item.agent, named2 ? void 0 : filters.agent).map((v) => [v === named2 ? filters.agent : v, v]);
|
|
774
|
+
const legacy = ["source", "target", "range"].filter((key) => filters[key]).map((key) => `<input type="hidden" name="${key}" value="${h(filters[key])}">`).join("");
|
|
775
|
+
const bar = `<form class="runs-filters" aria-label="Filter runs" role="search">${legacy}<label class="c-search"><span class="sr-only">Search runs</span><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="6.5"/><path d="M20 20l-4.2-4.2"/></svg><input type="search" name="q" value="${h(filters.q ?? "")}" placeholder="Search by request, test or run id" data-run-search></label>` + select("agent", "Agent", agentChoices) + select("result", "Result", RESULT_ORDER.filter((kind) => all.some((item) => item.status === kind) || filters.result === kind).map((kind) => [kind, statusLabel(kind)])) + select("where", "Where", values((item) => item.where, filters.where).map((v) => [v, WHERE[v] ?? v])) + (commits.length ? select("commit", "Commit", commits.map((v) => [v, v.slice(0, 7)]), "Any") : "") + "</form>";
|
|
776
|
+
const meta = range ? `${inRange.length} in the last ${RANGES[range][0].replace(" h", " hours").replace(" d", " days")}` : `${all.length} ${all.length === 1 ? "run" : "runs"}`;
|
|
777
|
+
const filtered = Boolean(query || filters.agent || filters.result || filters.where || filters.commit || filters.source || filters.target);
|
|
778
|
+
if (!shown.length) return head2(meta) + stats(shown, range, now) + bar + stateCard(filtered ? "No runs match these filters" : "No runs in this range", filtered ? h([query && `\u201C${filters.q}\u201D`, filters.agent && `Agent: ${named2 ?? filters.agent}`, filters.result && `Result: ${RESULT_ORDER.includes(filters.result) ? statusLabel(filters.result) : filters.result}`, filters.where && `Where: ${WHERE[filters.where] ?? filters.where}`, filters.commit && `Commit: ${filters.commit.slice(0, 7)}`].filter(Boolean).join(" \xB7 ")) : "", `<a class="button-link" href="${h(filtered ? filterUrl({ range: filters.range }, {}) : filterUrl(filters, { range: "" }))}" data-nav>${filtered ? "Clear filters" : "Show all runs"}</a>`, "filtered");
|
|
779
|
+
const limit = Math.max(PAGE, Number(filters.limit) || PAGE), page = shown.slice(0, limit);
|
|
780
|
+
const more = shown.length > page.length ? `<a class="button-link" href="${h(filterUrl(filters, { limit: limit + PAGE }))}" data-nav>Load ${Math.min(PAGE, shown.length - page.length)} more</a>` : "";
|
|
781
|
+
return head2(meta) + stats(shown, range, now) + bar + runsTable(page.map((item) => item.run), { now }) + `<div class="rt-foot"><span class="c-note">${page.length} of ${shown.length} ${shown.length === 1 ? "run" : "runs"}, newest first</span>${more}</div>`;
|
|
782
|
+
}
|
|
783
|
+
|
|
513
784
|
// frontend/src/experience.ts
|
|
514
785
|
var list2 = (value) => Array.isArray(value) ? value.filter((v) => v && typeof v === "object") : [];
|
|
515
786
|
var text = (value) => typeof value === "string" ? value : typeof value === "number" || typeof value === "boolean" ? String(value) : "";
|
|
@@ -556,8 +827,7 @@ function cell(value) {
|
|
|
556
827
|
const raw = readable(value), date = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2}))?$/.exec(raw);
|
|
557
828
|
const ms = date ? Date.parse(date[1] ? raw : `${raw}T00:00:00Z`) : NaN;
|
|
558
829
|
if (!Number.isFinite(ms)) return raw;
|
|
559
|
-
|
|
560
|
-
return d.getUTCHours() || d.getUTCMinutes() ? `${day}, ${d.toISOString().slice(11, 16)}` : `${day}, ${d.getUTCFullYear()}`;
|
|
830
|
+
return date?.[1] ? utc(ms) : `${new Date(ms).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" })}, ${new Date(ms).getUTCFullYear()}`;
|
|
561
831
|
}
|
|
562
832
|
function messageText(value) {
|
|
563
833
|
const raw = readable(value);
|
|
@@ -659,13 +929,13 @@ function pagerdutyView(o, options) {
|
|
|
659
929
|
}).join("") || empty2("No incidents in the captured data.")}</section>`;
|
|
660
930
|
}
|
|
661
931
|
function files(s, sha, prefix = "", visited = /* @__PURE__ */ new Set()) {
|
|
662
|
-
const
|
|
663
|
-
if (!key || visited.has(key)) return
|
|
932
|
+
const result = /* @__PURE__ */ new Map(), key = text(sha);
|
|
933
|
+
if (!key || visited.has(key)) return result;
|
|
664
934
|
visited.add(key);
|
|
665
935
|
const tree = list2(s.trees).find((t) => same(t.sha, key));
|
|
666
936
|
for (const e of list2(tree?.entries)) {
|
|
667
937
|
if (e.type === "tree") {
|
|
668
|
-
for (const [path2, content2] of files(s, e.sha, prefix + text(e.path) + "/", new Set(visited)))
|
|
938
|
+
for (const [path2, content2] of files(s, e.sha, prefix + text(e.path) + "/", new Set(visited))) result.set(path2, content2);
|
|
669
939
|
continue;
|
|
670
940
|
}
|
|
671
941
|
const blob = list2(s.blobs).find((b) => same(b.sha, e.sha));
|
|
@@ -678,9 +948,9 @@ function files(s, sha, prefix = "", visited = /* @__PURE__ */ new Set()) {
|
|
|
678
948
|
continue;
|
|
679
949
|
}
|
|
680
950
|
}
|
|
681
|
-
|
|
951
|
+
result.set(prefix + text(e.path), content);
|
|
682
952
|
}
|
|
683
|
-
return
|
|
953
|
+
return result;
|
|
684
954
|
}
|
|
685
955
|
function filesAt(s, sha, visited = /* @__PURE__ */ new Set()) {
|
|
686
956
|
const key = text(sha);
|
|
@@ -741,11 +1011,17 @@ function recordsView(observation2, tool, options = {}) {
|
|
|
741
1011
|
return projectedTool(observation2, tool, options);
|
|
742
1012
|
}
|
|
743
1013
|
function projectedTool(o, tool, options) {
|
|
744
|
-
const
|
|
745
|
-
if (!
|
|
1014
|
+
const view2 = o.toolViews?.[tool], tables = list2(view2?.tables), conversations = list2(view2?.conversations), active = tables.find((t) => t.title === options.resource) ?? tables[0];
|
|
1015
|
+
if (!view2) return stateCard("No records in this capture", `Select another tool to browse its records.`);
|
|
746
1016
|
const selected = options.conversation == null ? null : conversations[Number(options.conversation)];
|
|
747
|
-
if (selected) return `<section class="tool-surface">${heading(selected.title, toolName(tool))}${nav("Back to records", options.baseHref || "", { view: "tools", tool, conversation: null }, "back-link")}<div class="messages">${list2(selected.messages).map((m) => `<article class="message"><span class="avatar" aria-hidden="true">${h(text(m.speaker).slice(0, 2).toUpperCase())}</span><div><strong>${h(m.speaker)}</strong>${messageText(m.text)}</div></article>`).join("") || empty2(selected.status === "processing" ? "The transcript is still processing." : "No transcript was captured.")}</div></section>`;
|
|
748
|
-
|
|
1017
|
+
if (selected) return `<section class="tool-surface records-surface">${heading(selected.title, toolName(tool))}${nav("Back to records", options.baseHref || "", { view: "tools", tool, conversation: null }, "back-link")}<div class="messages">${list2(selected.messages).map((m) => `<article class="message"><span class="avatar" aria-hidden="true">${h(text(m.speaker).slice(0, 2).toUpperCase())}</span><div><strong>${h(m.speaker)}</strong>${messageText(m.text)}</div></article>`).join("") || empty2(selected.status === "processing" ? "The transcript is still processing." : "No transcript was captured.")}</div></section>`;
|
|
1018
|
+
const columns = active?.columns ?? [], records2 = list2(active?.rows);
|
|
1019
|
+
const identifier = (key) => /(?:^|[_-])(id|key|uuid|ref|sha)(?:$|[_-])/i.test(key) || /(?:Id|Key|Uuid|Sha)$/.test(key);
|
|
1020
|
+
const numeric = (key) => records2.some((row2) => typeof row2[key] === "number") && records2.every((row2) => row2[key] == null || typeof row2[key] === "number");
|
|
1021
|
+
return `<section class="tool-surface records-surface">${options.embedded ? "" : heading(toolName(tool))}${tables.length ? `<nav class="tool-nav records-collections" aria-label="Record collections">${tables.map((t) => `<a data-nav class="${t === active ? "active" : ""}" ${t === active ? 'aria-current="page"' : ""} href="${h(href(options.baseHref || "", { view: "tools", tool, resource: t.title, conversation: null }))}"><span>${h(t.title)}</span><span class="records-count">${h(t.total)}</span></a>`).join("")}</nav>` : ""}${active ? `<div class="tool-section-title"><h3>${h(active.title)}</h3><span class="muted">${Number(active.total)} records</span></div><div class="table-wrap records-grid" role="region" aria-label="${h(active.title)} records" tabindex="0"><table><thead class="records-frozen-head"><tr>${columns.map((key) => `<th scope="col" class="${numeric(key) ? "num" : ""}"><code>${h(key)}</code></th>`).join("")}</tr></thead><tbody>${records2.map((row2) => `<tr>${columns.map((key) => {
|
|
1022
|
+
const value = cell(row2[key]) || "\u2014", mono2 = identifier(key), raw = text(row2[key]);
|
|
1023
|
+
return `<td class="${mono2 ? "mono " : ""}${typeof row2[key] === "number" ? "num" : ""}"><div class="records-cell"><span class="records-value" title="${h(raw || value)}">${h(value)}</span>${mono2 && raw ? copyButton(raw, "Copy " + key) : ""}</div></td>`;
|
|
1024
|
+
}).join("")}</tr>`).join("")}</tbody></table>${!records2.length ? stateCard("No records in this collection", "Select another collection to browse its records.") : ""}</div>${active.rows.length < active.total ? `<p class="muted small">Showing ${active.rows.length} of ${active.total} records.</p>` : ""}` : stateCard("No records in this capture")}${conversations.length ? `<div class="transcript-list">${conversations.map((c, index) => nav(c.title, options.baseHref || "", { view: "tools", tool, conversation: index }, "transcript-link")).join("")}</div>` : ""}</section>`;
|
|
749
1025
|
}
|
|
750
1026
|
var actionNames = {
|
|
751
1027
|
"conversations.list": "Listed Slack channels",
|
|
@@ -786,10 +1062,12 @@ function actionLabel(t) {
|
|
|
786
1062
|
if (/\/deployments(?:\/|$)/.test(p)) return method === "GET" ? "Read deployments" : "Updated a deployment";
|
|
787
1063
|
if (p === "console.manual_action") return "Manual workspace action";
|
|
788
1064
|
if (t.note) return readable(t.note);
|
|
1065
|
+
if (t.service === "tools" && /^\/tools\/[^/]+$/.test(p)) return `Called ${p.slice("/tools/".length)}`;
|
|
1066
|
+
if (t.service === "agent" && p === "/done") return "Agent ended its turn";
|
|
789
1067
|
return method === "GET" || method === "HEAD" ? `Read ${toolName(text(t.service))} data` : `Called ${toolName(text(t.service))}`;
|
|
790
1068
|
}
|
|
791
1069
|
function traceDescription(t) {
|
|
792
|
-
const path2 = text(t.path),
|
|
1070
|
+
const path2 = text(t.path), result = [];
|
|
793
1071
|
if (t.service === "slack" && /(?:chat\.(?:postMessage|update)|actor)/.test(path2)) {
|
|
794
1072
|
const body2 = t.response?.message?.text ?? t.response?.text ?? t.request?.text;
|
|
795
1073
|
if (typeof body2 === "string") return messageText(body2);
|
|
@@ -797,21 +1075,27 @@ function traceDescription(t) {
|
|
|
797
1075
|
if (t.service === "datadog" && /\/api\/v1\/query/.test(path2)) {
|
|
798
1076
|
for (const s of list2(t.response?.series).slice(0, 4)) {
|
|
799
1077
|
const values = Array.isArray(s.pointlist) ? s.pointlist.filter((p) => Array.isArray(p) && Number.isFinite(p[1])) : [];
|
|
800
|
-
|
|
1078
|
+
result.push(`${text(s.metric || s.expression) || "Metric"}${values.length ? ` \xB7 latest returned value ${values.at(-1)[1]}` : " \xB7 no samples returned"}`);
|
|
801
1079
|
}
|
|
802
1080
|
}
|
|
803
|
-
if (path2.includes("/logs/events/search") && Array.isArray(t.response?.data))
|
|
1081
|
+
if (path2.includes("/logs/events/search") && Array.isArray(t.response?.data)) result.push(`${t.response.data.length} log entries returned`);
|
|
804
1082
|
if (t.service === "github") {
|
|
805
|
-
if (typeof t.request?.title === "string")
|
|
806
|
-
if (typeof t.response?.title === "string" && t.response.title !== t.request?.title)
|
|
807
|
-
if (typeof t.response?.message === "string")
|
|
1083
|
+
if (typeof t.request?.title === "string") result.push(t.request.title);
|
|
1084
|
+
if (typeof t.response?.title === "string" && t.response.title !== t.request?.title) result.push(t.response.title);
|
|
1085
|
+
if (typeof t.response?.message === "string") result.push(t.response.message);
|
|
808
1086
|
const filename = path2.match(/\/contents\/([^?]+)/)?.[1];
|
|
809
|
-
if (filename)
|
|
1087
|
+
if (filename) result.push(filename);
|
|
1088
|
+
}
|
|
1089
|
+
if (t.service === "tools") {
|
|
1090
|
+
const fields2 = (value, count) => value && typeof value === "object" && !Array.isArray(value) ? Object.entries(value).filter(([, v]) => v === null || ["string", "number", "boolean"].includes(typeof v)).slice(0, count).map(([k, v]) => `${k}: ${String(v).slice(0, 60)}`).join(", ") : "";
|
|
1091
|
+
const args = fields2(t.request?.args, 3), answer = fields2(t.response?.result, 4);
|
|
1092
|
+
if (args) result.push(args);
|
|
1093
|
+
if (answer) result.push(`returned ${answer}`);
|
|
810
1094
|
}
|
|
811
|
-
if (t.gap)
|
|
812
|
-
if (t.issue?.message)
|
|
813
|
-
else if (Number(t.status) >= 400)
|
|
814
|
-
return
|
|
1095
|
+
if (t.gap) result.push("This request could not be handled by the mocked tool.");
|
|
1096
|
+
if (t.issue?.message) result.push(readable(t.issue.message));
|
|
1097
|
+
else if (Number(t.status) >= 400) result.push(`HTTP ${Number(t.status)}${typeof t.response?.error === "string" ? " \xB7 " + readable(t.response.error) : ""}`);
|
|
1098
|
+
return result.length ? `<p>${result.map(h).join(" \xB7 ")}</p>` : "";
|
|
815
1099
|
}
|
|
816
1100
|
function readCall(t) {
|
|
817
1101
|
const method = text(t.method).toUpperCase(), path2 = text(t.path).split("?")[0] ?? "";
|
|
@@ -913,44 +1197,6 @@ function attemptResult(observation2, scene, selectedCheck, baseHref = "") {
|
|
|
913
1197
|
}).join("")}</nav><section class="selected-evidence" aria-label="Selected outcome evidence"><header class="tool-title"><h3>${h(checkLabel(scene, selected))}</h3>${pill(selectedState.label, selectedState.tone)}</header>${selected.error ? `<p class="error">${h(readable(selected.error))}</p>` : selected.status === "skipped" ? `<p>${h(readable(selected.warning) || "This check was not evaluated.")}</p>` : ""}<div class="evidence-surface">${checkEvidence(observation2, scene, selected, baseHref)}</div></section></div>`;
|
|
914
1198
|
}
|
|
915
1199
|
|
|
916
|
-
// frontend/src/runs-page.ts
|
|
917
|
-
var SOURCES = { console: "Console", cli: "CLI", ci: "CI", cloud: "Cloud" };
|
|
918
|
-
var TARGETS = { local: "Local", docker: "Docker", hosted: "Hosted", cloud: "Cloud" };
|
|
919
|
-
function originLabel(origin) {
|
|
920
|
-
if (!origin?.source) return "";
|
|
921
|
-
const commit = origin.commit ? `${String(origin.commit).slice(0, 7)}${origin.dirty ? " + changes" : ""}` : "";
|
|
922
|
-
const target = String(origin.target ?? "").toLowerCase();
|
|
923
|
-
return [SOURCES[origin.source] ?? String(origin.source), target === origin.source ? "" : target, commit].filter(Boolean).join(" \xB7 ");
|
|
924
|
-
}
|
|
925
|
-
function result(run) {
|
|
926
|
-
const counts = batchCounts(run), summary = run.summary;
|
|
927
|
-
if (!terminal(run.status)) return run.status === "queued" && run.queue ? queueLabel(run.queue) : `${counts.finished} / ${counts.total} finished`;
|
|
928
|
-
const tasks = run.tasks ?? [], attempts = run.attempts ?? [];
|
|
929
|
-
const verified = summary?.verdictVersion === 2 ? summary.counts : void 0;
|
|
930
|
-
const requested = verified?.requested ?? (tasks.length && tasks.every((task) => Number.isSafeInteger(task.attempts) && task.attempts > 0) ? tasks.reduce((sum2, task) => sum2 + task.attempts, 0) : void 0);
|
|
931
|
-
const passed = verified?.passed ?? attempts.filter((attempt) => attempt.outcome === "passed").length;
|
|
932
|
-
const invalid = verified?.invalid ?? attempts.filter((attempt) => attempt.outcome === "invalid").length;
|
|
933
|
-
const skipped = verified?.skipped ?? attempts.filter((attempt) => attempt.outcome === "skipped").length;
|
|
934
|
-
const graded = typeof summary?.pass_rate === "number" || attempts.some((attempt) => ["passed", "failed"].includes(attempt.outcome));
|
|
935
|
-
const detail = `${invalid ? ` \xB7 ${invalid} invalid` : ""}${skipped ? ` \xB7 ${skipped} skipped` : ""}`;
|
|
936
|
-
if (graded) return `${requested ? `${Math.round(passed / requested * 100)}% passed` : "Unverified rate \xB7 rerun"}${detail}`;
|
|
937
|
-
return `${requested ?? counts.total} ${(requested ?? counts.total) === 1 ? "attempt" : "attempts"}${detail}`;
|
|
938
|
-
}
|
|
939
|
-
function row(run) {
|
|
940
|
-
const when = appTime(run.createdAt);
|
|
941
|
-
const about = [run.agentName, run.world?.name].filter(Boolean).join(" \xB7 "), meta = [when, originLabel(run.origin)].filter(Boolean).join(" \xB7 ");
|
|
942
|
-
return `<a class="batch-history-row runs-row" href="/playgrounds/${encodeURIComponent(run.id)}" data-nav><div><strong>${h(shortPrompt(batchTitle(run)))}</strong>${about ? `<small>${h(about)}</small>` : ""}${meta ? `<small>${h(meta)}</small>` : ""}</div>${attemptBadge(run.status)}<span class="muted">${h(result(run))}</span><span aria-hidden="true">\u2192</span></a>`;
|
|
943
|
-
}
|
|
944
|
-
function runsPage(runs, filters, options = {}) {
|
|
945
|
-
if (!runs.length) return `<p class="quiet-empty">${options.emptyHtml ?? "No runs yet. Runs started here, with the CLI or in CI appear here."}</p>`;
|
|
946
|
-
const values = (key) => [...new Set([...runs.map((run) => run.origin?.[key]), filters[key]].filter(Boolean).map(String))];
|
|
947
|
-
const select = (name, label2, options2) => `<label><span>${label2}</span><select name="${name}" data-run-filter><option value="">All</option>${options2.map(([value, text2]) => `<option value="${h(value)}" ${filters[name] === value ? "selected" : ""}>${h(text2)}</option>`).join("")}</select></label>`;
|
|
948
|
-
const commits = values("commit");
|
|
949
|
-
const bar = `<form class="runs-filters" aria-label="Filter runs">${select("source", "Source", values("source").map((v) => [v, SOURCES[v] ?? v]))}${select("target", "Target", values("target").map((v) => [v, TARGETS[v] ?? v]))}${commits.length ? select("commit", "Commit", commits.map((v) => [v, v.slice(0, 7)])) : ""}</form>`;
|
|
950
|
-
const shown = runs.filter((run) => (!filters.source || run.origin?.source === filters.source) && (!filters.target || run.origin?.target === filters.target) && (!filters.commit || run.origin?.commit === filters.commit));
|
|
951
|
-
return bar + (shown.length ? `<div class="batch-history runs-list">${shown.map(row).join("")}</div>` : '<p class="quiet-empty">No runs match these filters.</p>');
|
|
952
|
-
}
|
|
953
|
-
|
|
954
1200
|
// frontend/src/attempt-workspace.ts
|
|
955
1201
|
var readOnlyRun = (batch) => batch.origin?.stored === true || batch.origin?.mirrored === true || ["cli", "ci", "pytest"].includes(batch.origin?.source);
|
|
956
1202
|
var records = (value) => Array.isArray(value) ? value.filter((item) => item && typeof item === "object") : [];
|
|
@@ -1015,7 +1261,6 @@ function executionSummary(attempts, requested = attempts.length) {
|
|
|
1015
1261
|
};
|
|
1016
1262
|
}
|
|
1017
1263
|
var percent = (part, whole) => whole ? `${Math.round(part / whole * 100)}%` : "\u2014";
|
|
1018
|
-
var duration = (ms) => ms === void 0 ? "\u2014" : ms < 1e4 ? `${(ms / 1e3).toFixed(1)}s` : ms < 12e4 ? `${Math.round(ms / 1e3)}s` : `${Math.round(ms / 6e4)}m`;
|
|
1019
1264
|
var medianTime = (attempts) => duration(executionSummary(attempts).medianMs);
|
|
1020
1265
|
var hasChecks = (tasks) => Array.isArray(tasks) && tasks.some((task) => Array.isArray(task?.checks) && task.checks.length > 0);
|
|
1021
1266
|
function summaryWidgets(attempts, checked = false, requested = attempts.length) {
|
|
@@ -1057,10 +1302,6 @@ function outcomeBadge(attempt) {
|
|
|
1057
1302
|
const outcome = attemptOutcome(attempt);
|
|
1058
1303
|
return `<span class="aw-outcome ${outcome.tone}">${h(outcome.label)}</span>`;
|
|
1059
1304
|
}
|
|
1060
|
-
function railMark(attempt) {
|
|
1061
|
-
const outcome = attemptOutcome(attempt), label2 = outcome.key === "ungraded" ? attemptLabel(String(attempt.status ?? "")) : outcome.label;
|
|
1062
|
-
return `<span class="aw-rail-mark ${outcome.tone} execution-${h(String(attempt.status ?? ""))}" title="${h(label2)}" aria-label="${h(label2)}">${attemptMark(attempt)}</span>`;
|
|
1063
|
-
}
|
|
1064
1305
|
function sentence(text2) {
|
|
1065
1306
|
const value = String(text2 ?? "");
|
|
1066
1307
|
if (!/^\s*[[{]/.test(value)) return value;
|
|
@@ -1071,15 +1312,6 @@ function sentence(text2) {
|
|
|
1071
1312
|
return value;
|
|
1072
1313
|
}
|
|
1073
1314
|
}
|
|
1074
|
-
function checksView(attempt, jump = () => void 0) {
|
|
1075
|
-
const checks2 = records(attempt.checks);
|
|
1076
|
-
if (!checks2.length) return "";
|
|
1077
|
-
const passed = checks2.filter((c) => c.passed).length;
|
|
1078
|
-
return `<section class="aw-checks"><h3>Checks <span>${passed} of ${checks2.length} passed</span></h3><ul>${checks2.map((c) => {
|
|
1079
|
-
const href2 = c.passed ? void 0 : jump(String(c.id));
|
|
1080
|
-
return `<li class="${c.passed ? "pass" : "fail"}"><span class="aw-check-mark" aria-hidden="true">${c.passed ? "\u2713" : "\u2717"}</span><div><strong>${h(c.id)}</strong>${sentence(c.expected) ? `<p>${h(sentence(c.expected))}</p>` : ""}<p class="muted">${h(c.error ? `Error: ${c.error}` : c.actual)}</p>${href2 ? navLink("See in the conversation", href2, "aw-check-jump") : ""}</div></li>`;
|
|
1081
|
-
}).join("")}</ul></section>`;
|
|
1082
|
-
}
|
|
1083
1315
|
function widgets(attempts, tasks) {
|
|
1084
1316
|
return summaryWidgets(attempts, hasChecks(tasks), tasks.reduce((sum2, task) => sum2 + (Number(task.attempts) || attempts.filter((attempt) => attempt.taskId === task.id).length), 0));
|
|
1085
1317
|
}
|
|
@@ -1125,11 +1357,17 @@ function runMeta(batch, attempts, tasks) {
|
|
|
1125
1357
|
const parts = [batch.agentName ?? batch.test?.agentName, `${attempts.length} attempt${attempts.length === 1 ? "" : "s"}`, `${tasks.length} task${tasks.length === 1 ? "" : "s"}`, appTime(batch.createdAt), originLabel(batch.origin)].filter(Boolean);
|
|
1126
1358
|
return `<p class="aw-meta">${status ? `<span class="aw-run-state ${h(status)}">${h(attemptLabel(status))}</span>` : ""}${parts.map((p) => `<span>${h(String(p))}</span>`).join("")}</p>`;
|
|
1127
1359
|
}
|
|
1360
|
+
function savedResult(batch) {
|
|
1361
|
+
const reproduction = records(batch.reproduction);
|
|
1362
|
+
const verdict = batch.summary?.graded === false ? "Ungraded" : batch.verdict === "pass" ? "Pass" : batch.verdict === "fail" ? "Fail" : "";
|
|
1363
|
+
if (!verdict && !reproduction.length) return "";
|
|
1364
|
+
return `<section class="aw-task-section" aria-label="Run result">${verdict ? `<p>Verdict: <strong>${h(verdict)}</strong>${batch.exitCode === void 0 ? "" : ` \xB7 Exit ${h(batch.exitCode)}`}</p>` : ""}${reproduction.length ? `<p>Production: ${reproduction.map((r) => `<code>${h(r.sceneId)}</code> ${h(String(r.verdict).replaceAll("-", " "))}`).join(" \xB7 ")}</p>` : ""}</section>`;
|
|
1365
|
+
}
|
|
1128
1366
|
function renderRunOverview(batch, actionsHtml = "", options = {}) {
|
|
1129
1367
|
const groups = entrySections(batch), allTasks = groups.flatMap((group) => group.tasks), selected = options.task ? allTasks.find((task) => task.id === options.task) : void 0;
|
|
1130
1368
|
const title2 = selected ? taskDisplayName(selected, allTasks.indexOf(selected)) : batch.world?.name ?? batch.configuration?.name ?? batch.test?.world?.name ?? batch.groupName ?? "World";
|
|
1131
1369
|
const overviewAttempts = selected ? records(batch.attempts).filter((a) => a.taskId === selected.id) : records(batch.attempts);
|
|
1132
|
-
return `<div class="aw-overview"><header class="aw-header"><div><h1>${h(title2)}</h1>${runMeta(batch, overviewAttempts, selected ? [selected] : allTasks)}</div><div class="aw-actions">${actionsHtml}</div></header>${queueLine(batch)}${errorMessage(batch.error)}${widgets(overviewAttempts, selected ? [selected] : allTasks)}${groups.map(({ entry, tasks, attempts }) => {
|
|
1370
|
+
return `<div class="aw-overview"><header class="aw-header"><div><h1>${h(title2)}</h1>${runMeta(batch, overviewAttempts, selected ? [selected] : allTasks)}</div><div class="aw-actions">${actionsHtml}</div></header>${queueLine(batch)}${errorMessage(batch.error)}${savedResult(batch)}${widgets(overviewAttempts, selected ? [selected] : allTasks)}${groups.map(({ entry, tasks, attempts }) => {
|
|
1133
1371
|
const shown = selected ? tasks.filter((t) => t.id === selected.id) : tasks;
|
|
1134
1372
|
if (!shown.length) return "";
|
|
1135
1373
|
return `<section class="aw-task-section">${groups.length > 1 ? `<header class="aw-entry-header"><h2>${h(entry?.agentName ?? entry?.name ?? "Agent")}</h2><span>${h(entry?.world?.name ?? entry?.test?.world?.name ?? "")}</span></header>` : ""}<div class="aw-section-heading"><h2>${selected ? "Attempts" : "Tasks"}</h2>${!selected ? `<span>${tasks.length}</span>` : ""}</div>${selected ? `<section class="aw-task-description"><p>${h(selected.prompt)}</p></section>` : ""}<div class="aw-task-table"><div class="aw-table-head" aria-hidden="true"><span>Task</span><span>Result</span><span>Attempts</span><span>Median</span><span></span></div>${shown.map((task) => {
|
|
@@ -1242,26 +1480,166 @@ function managedResponse(attempt) {
|
|
|
1242
1480
|
}
|
|
1243
1481
|
return original.replace(/<div class="response-text">[\s\S]*?<\/div>/, () => `<div class="aw-markdown">${safeMarkdown(text2)}</div>`);
|
|
1244
1482
|
}
|
|
1483
|
+
function attemptKind(attempt) {
|
|
1484
|
+
const outcome = attemptOutcome(attempt).key;
|
|
1485
|
+
if (outcome !== "ungraded") return outcome;
|
|
1486
|
+
return attempt.status === "queued" ? "queued" : ["starting", "running"].includes(attempt.status) ? "running" : attempt.status === "error" ? "error" : attempt.status === "stopped" ? "stopped" : "ungraded";
|
|
1487
|
+
}
|
|
1488
|
+
function taskKind(attempts) {
|
|
1489
|
+
const kinds = attempts.map(attemptKind);
|
|
1490
|
+
return ["running", "queued", "failed", "invalid", "error", "passed", "stopped", "skipped"].find((kind) => kinds.includes(kind)) ?? "ungraded";
|
|
1491
|
+
}
|
|
1492
|
+
function defaultAttempt(batch, taskId) {
|
|
1493
|
+
const attempts = records(batch.attempts).filter((a) => !taskId || a.taskId === taskId);
|
|
1494
|
+
return attempts.find((a) => a.outcome === "failed") ?? attempts.find((a) => a.outcome === "invalid") ?? attempts.find((a) => ["completed", "error", "stopped"].includes(a.status)) ?? attempts[0];
|
|
1495
|
+
}
|
|
1496
|
+
var cliRun2 = (batch) => ["cli", "ci", "cloud", "pytest"].includes(batch.origin?.source);
|
|
1497
|
+
var reproductionOf = (batch, task) => records(batch.reproduction).find((r) => r.sceneId === task.id);
|
|
1498
|
+
var firstFailure = (attempt) => records(attempt.checks).find((c) => c.required !== false && !c.passed && !c.error && c.status !== "skipped");
|
|
1499
|
+
function runHeader(batch, task, attempts, attempt, actionsHtml) {
|
|
1500
|
+
const id = String(batch.id), trace = reproductionOf(batch, task)?.trace;
|
|
1501
|
+
const crumbs = `<nav class="rd-crumbs" aria-label="Breadcrumb">${navLink("Runs", "/playgrounds")}<span aria-hidden="true">/</span><code title="${h(id)}">${h(shortId(id, 12))}</code>${copyButton(id, "Copy run id")}</nav>`;
|
|
1502
|
+
const kicker = cliRun2(batch) ? `Test <code>${h(task.id)}</code>${trace ? `, made from production trace <code title="${h(trace)}">${h(String(trace).slice(0, 8))}</code>` : ""}` : h(batch.world?.name ?? batch.configuration?.name ?? batch.test?.world?.name ?? batch.groupName ?? "World");
|
|
1503
|
+
const prompt = String(task.prompt ?? "").trim(), long = prompt.length > 160;
|
|
1504
|
+
const title2 = prompt ? `\u201C${long ? `${prompt.slice(0, 157).trimEnd()}\u2026` : prompt}\u201D` : taskDisplayName(task, 0);
|
|
1505
|
+
const c = runCounts(batch), note = baselineNote(batch), failure = firstFailure(attempt);
|
|
1506
|
+
const verdict = `<div class="rd-verdict">${statusPill(runStatus(batch))}${c.graded ? `<span class="rd-rate">${c.passed} of ${c.total} attempts passed</span>` : ""}${productionTag(batch.reproduction)}${note ? `<span class="c-note c-tone-${note.tone}">${h(note.text)}</span>` : ""}</div>`;
|
|
1507
|
+
const reason = failure ? `<p class="rd-reason"><code>${h(failure.id)}</code> ${h(failure.explanation || sentence(failure.actual) || failure.actual)}</p>` : "";
|
|
1508
|
+
return `<div class="rd-top">${crumbs}<div class="rd-top-actions">${cliRun2(batch) ? copyCommand(`ancha explain ${id}`) : ""}${actionsHtml ? `<div class="aw-actions">${actionsHtml}</div>` : ""}</div></div>
|
|
1509
|
+
<header class="rd-head"><span class="rd-kicker">${kicker}</span><h1 title="${h(prompt)}">${h(title2)}</h1>${long ? `<details class="rd-request"><summary>The whole request</summary><p>${h(prompt)}</p></details>` : ""}${verdict}${reason}</header>`;
|
|
1510
|
+
}
|
|
1511
|
+
function runFacts(batch, attempts) {
|
|
1512
|
+
const durations = attempts.map(attemptMs).filter((ms) => ms !== void 0).sort((a, b) => a - b);
|
|
1513
|
+
const total = timeOf(batch.finishedAt) - timeOf(batch.startedAt ?? batch.createdAt), calls = attempts.reduce((sum2, a) => sum2 + (Number(a.toolCalls) || 0), 0);
|
|
1514
|
+
const commit = batch.origin?.commit ? `${String(batch.origin.commit).slice(0, 7)}${batch.origin.dirty ? " + changes" : ""}` : "";
|
|
1515
|
+
const atOnce = Number(batch.concurrency) || 0, cloud = whereKey(batch.origin) === "cloud";
|
|
1516
|
+
const items = [
|
|
1517
|
+
{ label: "Agent", value: String(batch.agentName ?? batch.test?.agentName ?? "\u2014") },
|
|
1518
|
+
{ label: "Where", value: whereLabel(batch.origin).split(" \xB7 ")[0] || "Console", ...cloud && atOnce ? { sub: `${atOnce} at once, a machine each` } : {} },
|
|
1519
|
+
...commit ? [{ label: "Commit", value: commit, mono: true }] : [],
|
|
1520
|
+
{ label: "Started", value: utcClock(batch.createdAt) || "\u2014", sub: [utcDay(batch.createdAt), ago(batch.createdAt)].filter(Boolean).join(" \xB7 "), title: utc(batch.createdAt) },
|
|
1521
|
+
{ label: "Duration", value: Number.isFinite(total) && total >= 0 ? duration(total) : "\u2014", ...durations.length > 1 ? { sub: duration(durations[0]) === duration(durations.at(-1)) ? `attempts ${duration(durations[0])} each` : `attempts ${duration(durations[0])} to ${duration(durations.at(-1))}` } : durations.length ? { sub: `attempt ${duration(durations[0])}` } : {} },
|
|
1522
|
+
{ label: "Tool calls", value: String(calls), ...attempts.length ? { sub: `${Number((calls / attempts.length).toFixed(1))} per attempt` } : {} },
|
|
1523
|
+
...batch.origin?.source ? [{ label: "Started by", value: originLabel({ source: batch.origin.source }) }] : []
|
|
1524
|
+
];
|
|
1525
|
+
return facts(items, "Run facts");
|
|
1526
|
+
}
|
|
1527
|
+
function rail(batch, tasks, allAttempts, task, attempt, view2) {
|
|
1528
|
+
const testLink = (t, i) => {
|
|
1529
|
+
const own = allAttempts.filter((a) => a.taskId === t.id), passed = own.filter((a) => a.outcome === "passed").length;
|
|
1530
|
+
const label2 = `${own.length} attempts: ${own.map((a) => statusLabel(attemptKind(a))).join(", ")}`;
|
|
1531
|
+
return `<a data-nav class="rd-test${t.id === task.id ? " selected" : ""}"${t.id === task.id ? ' aria-current="true"' : ""} href="${h(taskHref(batch, t))}"><span class="rd-test-title">${glyph(taskKind(own))}<span>${h(shortPrompt(t.prompt) || taskDisplayName(t, i))}</span></span><span class="rd-test-meta">${cliRun2(batch) ? `<code>${h(t.id)}</code>` : ""}${strip(own.map(attemptKind), label2)}<span class="num">${passed} / ${own.length}</span></span></a>`;
|
|
1532
|
+
};
|
|
1533
|
+
const attemptsOfTask = allAttempts.filter((a) => a.taskId === task.id);
|
|
1534
|
+
return `<aside class="rd-rail" aria-label="Tests and attempts"><section><h2 class="rd-rail-title">Tests \xB7 ${tasks.length}</h2>${tasks.map(testLink).join("")}</section><section><h2 class="rd-rail-title">Attempts</h2><nav aria-label="Attempts">${attemptsOfTask.map((a) => `<a data-nav class="rd-attempt${a.id === attempt.id ? " selected" : ""}"${a.id === attempt.id ? ' aria-current="page"' : ""} href="${h(taskHref(batch, task, { attempt: a.id, ...view2 === "evidence" ? {} : { view: view2 } }))}">${glyph(attemptKind(a), 16, statusLabel(attemptKind(a)))}<span>Attempt ${h(a.number)}</span><span class="rd-attempt-time">${a.status === "starting" ? `<span data-since="${startingSince(a)}">${elapsedLabel(startingSince(a))}</span>` : h(attemptMs(a) === void 0 ? "" : duration(attemptMs(a)))}</span></a>`).join("")}</nav></section></aside>`;
|
|
1535
|
+
}
|
|
1536
|
+
function checksSection(attempt, callHref, jump) {
|
|
1537
|
+
const checks2 = records(attempt.checks);
|
|
1538
|
+
if (!checks2.length) return "";
|
|
1539
|
+
const skipped = (c) => c.status === "skipped" && !c.error;
|
|
1540
|
+
const evaluated = checks2.filter((c) => !skipped(c)), passed = evaluated.filter((c) => c.passed).length, deciding = checks2.filter((c) => c.required !== false).length;
|
|
1541
|
+
const counts = [`${deciding} ${deciding === 1 ? "decides" : "decide"} the result`, checks2.length - deciding && `${checks2.length - deciding} optional`, `${passed} of ${evaluated.length} passed`, checks2.length - evaluated.length && `${checks2.length - evaluated.length} not evaluated`].filter(Boolean).join(" \xB7 ");
|
|
1542
|
+
return `<section class="rd-section rd-checks" aria-label="Checks"><div class="rd-section-head"><h3>Checks</h3><span>${h(counts)}</span></div>${checks2.map((c) => {
|
|
1543
|
+
const kind = c.error ? "error" : skipped(c) ? "skipped" : c.passed ? "passed" : "failed";
|
|
1544
|
+
const role = c.required === false ? tag("Optional") : kind === "failed" ? tag("Decides the result", "fail") : "";
|
|
1545
|
+
const detail = c.error ? `Error: ${c.error}` : kind === "skipped" ? `Not evaluated \xB7 ${c.explanation || c.warning || c.actual}` : [sentence(c.expected) && `Expected ${sentence(c.expected)}`, c.explanation || c.actual].filter(Boolean).join(". ");
|
|
1546
|
+
const evidence = Array.isArray(c.evidence) ? c.evidence.filter(Number.isSafeInteger) : [];
|
|
1547
|
+
const links = evidence.length ? evidence.slice(0, 3).map((seq) => navLink(`Call ${seq}`, callHref(seq))).join(" ") : c.kind === "judge" && kind !== "skipped" ? '<span class="rd-whole">Whole run</span>' : "";
|
|
1548
|
+
const person2 = kind === "failed" ? jump(String(c.id)) : void 0;
|
|
1549
|
+
return `<div class="rd-check ${kind}">${glyph(kind, 16, statusLabel(kind))}<div class="rd-check-body"><div class="rd-check-name"><code>${h(c.id)}</code>${tag(c.kind === "judge" ? "Judge" : "Rule")}${role}</div>${detail ? `<p>${h(detail)}</p>` : ""}${person2 ? navLink("See in the conversation", person2, "aw-check-jump") : ""}</div><div class="rd-check-links">${links}</div></div>`;
|
|
1550
|
+
}).join("")}</section>`;
|
|
1551
|
+
}
|
|
1552
|
+
function callName(t) {
|
|
1553
|
+
const path2 = String(t.path ?? "").split("?")[0] ?? "";
|
|
1554
|
+
if (t.service === "tools" && path2.startsWith("/tools/")) return path2.slice("/tools/".length);
|
|
1555
|
+
if (t.service === "agent" && path2 === "/done") return "done";
|
|
1556
|
+
return `${toolName(String(t.service ?? ""))} \xB7 ${String(t.method ?? "")} ${path2}`.trim();
|
|
1557
|
+
}
|
|
1558
|
+
function fieldsOf(value, limit = 60) {
|
|
1559
|
+
const out = [];
|
|
1560
|
+
const walk = (v, path2) => {
|
|
1561
|
+
if (out.length >= limit) return;
|
|
1562
|
+
if (v && typeof v === "object" && Object.keys(v).length) {
|
|
1563
|
+
for (const [key, child] of Object.entries(v)) walk(child, Array.isArray(v) ? `${path2}[${key}]` : path2 ? `${path2}.${key}` : key);
|
|
1564
|
+
return;
|
|
1565
|
+
}
|
|
1566
|
+
out.push([path2, v === null ? "null" : v === void 0 ? "" : typeof v === "object" ? Array.isArray(v) ? "no items" : "no fields" : String(v)]);
|
|
1567
|
+
};
|
|
1568
|
+
walk(value, "");
|
|
1569
|
+
return out;
|
|
1570
|
+
}
|
|
1571
|
+
function gist(value, count = 3) {
|
|
1572
|
+
if (value === void 0 || value === null || value === "") return "";
|
|
1573
|
+
if (!(typeof value === "object")) return String(value).replace(/\s+/g, " ").slice(0, 120);
|
|
1574
|
+
const fields2 = fieldsOf(value, count + 1).filter(([, v]) => v !== "");
|
|
1575
|
+
return fields2.slice(0, count).map(([k, v]) => `${k}: ${v.length > 40 ? `${v.slice(0, 39)}\u2026` : v}`).join(", ") + (fields2.length > count ? ", \u2026" : "");
|
|
1576
|
+
}
|
|
1577
|
+
var fieldList = (value) => {
|
|
1578
|
+
const fields2 = fieldsOf(value);
|
|
1579
|
+
if (!fields2.length || fields2.length === 1 && !fields2[0][0] && !fields2[0][1]) return '<p class="muted">Empty</p>';
|
|
1580
|
+
if (fields2.length === 1 && !fields2[0][0]) return `<p class="rd-text">${h(fields2[0][1])}</p>`;
|
|
1581
|
+
return `<dl class="rd-fields">${fields2.map(([k, v]) => `<dt>${h(k)}</dt><dd>${h(v)}</dd>`).join("")}</dl>`;
|
|
1582
|
+
};
|
|
1583
|
+
function callSource(t) {
|
|
1584
|
+
if (t.service === "agent") return "Agent";
|
|
1585
|
+
if (t.response?.source === "replayed") return "Replayed";
|
|
1586
|
+
if (t.response?.source === "simulated") return "Simulated";
|
|
1587
|
+
return t.source === "world" ? "Scenario" : t.source === "delivery" ? "Delivery" : toolName(String(t.service ?? ""));
|
|
1588
|
+
}
|
|
1589
|
+
function callsSection(observation2, failing, open) {
|
|
1590
|
+
const trace = records(observation2.trace).filter((t) => t.path !== "console.manual_action").sort((a, b) => (Number(a.seq) || 0) - (Number(b.seq) || 0));
|
|
1591
|
+
if (!trace.length) return `<section class="rd-section" id="calls" aria-label="Calls"><div class="rd-section-head"><h3>Calls</h3></div>${stateCard("No calls", "The agent made no call in this attempt.")}</section>`;
|
|
1592
|
+
const times = trace.map((t) => timeOf(t.tSim)).filter(Number.isFinite), start = times.length ? Math.min(...times) : NaN, span = times.length ? Math.max(...times) - start : NaN;
|
|
1593
|
+
const shown = trace.slice(0, 300);
|
|
1594
|
+
const rows3 = shown.map((t) => {
|
|
1595
|
+
const seq = Number(t.seq), checks2 = failing.get(seq) ?? [], ms = timeOf(t.tSim), error = Boolean(t.gap || t.issue || Number(t.status) >= 400 || t.response?.ok === false);
|
|
1596
|
+
const args = t.service === "tools" ? t.request?.args : t.service === "agent" ? t.request?.output : t.request;
|
|
1597
|
+
const answer = t.service === "tools" ? t.response?.error ?? t.response?.result : t.service === "agent" ? void 0 : t.response;
|
|
1598
|
+
const status = t.status === void 0 ? "" : `<span class="rd-code${error ? " bad" : ""}">${h(t.status)}</span>`;
|
|
1599
|
+
return `<details class="rd-call${checks2.length ? " failing" : ""}" id="call-${h(seq)}"${seq === open ? " open" : ""}><summary><span class="num">${h(seq)}</span><span class="rd-call-name"><code>${h(callName(t))}</code>${checks2.length ? `<span class="rd-fails" title="${h(checks2.join(", "))}">fails ${checks2.length} ${checks2.length === 1 ? "check" : "checks"}</span>` : ""}</span><span class="rd-call-args">${h(gist(args)) || '<span class="muted">none</span>'}</span><span class="rd-call-answer">${status}${h(t.service === "agent" && t.path === "/done" ? "the agent ended its turn" : gist(answer))}</span><span class="rd-call-source">${h(callSource(t))}</span><span class="num rd-call-at"${Number.isFinite(ms) ? ` title="${h(utc(ms))}"` : ""}>${Number.isFinite(ms) && Number.isFinite(start) ? `+${h(duration(ms - start))}` : "\u2014"}</span></summary><div class="rd-call-body"><div><h4>Request \xB7 <code>${h(`${t.method ?? ""} ${t.path ?? ""}`.trim())}</code></h4>${fieldList(args)}</div><div><h4>Response${t.status === void 0 ? "" : ` \xB7 ${h(t.status)}`}${t.response?.source ? ` \xB7 ${h(String(t.response.source))}` : ""}</h4>${t.issue?.message ? `<p class="rd-text bad">${h(t.issue.message)}</p>` : ""}${answer === void 0 && t.service === "agent" ? '<p class="muted">The agent ended its turn.</p>' : fieldList(answer)}</div></div></details>`;
|
|
1600
|
+
}).join("");
|
|
1601
|
+
const head2 = `<div class="rd-calls-head" aria-hidden="true"><span>#</span><span>Call</span><span>Arguments</span><span>Response</span><span>Source</span><span>At</span></div>`;
|
|
1602
|
+
return `<section class="rd-section" id="calls" aria-label="Calls"><div class="rd-section-head"><h3>Calls</h3><span>${trace.length} ${trace.length === 1 ? "call" : "calls"}${Number.isFinite(span) && trace.length > 1 ? ` over ${h(duration(span))} of world time` : ""}${trace.length > shown.length ? ` \xB7 the first ${shown.length} shown` : ""}</span></div><div class="rd-calls-scroll"><div class="rd-calls">${head2}${rows3}</div></div></section>`;
|
|
1603
|
+
}
|
|
1604
|
+
function productionSection(batch, task, attempt) {
|
|
1605
|
+
const row2 = reproductionOf(batch, task), checks2 = records(row2?.checks);
|
|
1606
|
+
if (!row2 || !checks2.length) return "";
|
|
1607
|
+
const word = { passed: "passed", failed: "failed" };
|
|
1608
|
+
const mine = new Map(records(attempt.checks).map((c) => [String(c.id), c]));
|
|
1609
|
+
return `<section class="rd-section" aria-label="Compared with production"><div class="rd-section-head"><h3>Compared with production</h3><span>${row2.trace ? `Trace <code title="${h(row2.trace)}">${h(String(row2.trace).slice(0, 8))}</code> \xB7 ` : ""}${productionTag([row2])}</span></div><div class="rd-table"><div class="rd-table-head"><span>Check</span><span>Production</span><span>This run</span><span>This attempt</span></div>${checks2.map((c) => {
|
|
1610
|
+
const own = mine.get(String(c.check)), ownKind = own ? own.status === "skipped" && !own.error ? "skipped" : own.error ? "error" : own.passed ? "passed" : "failed" : void 0;
|
|
1611
|
+
const total = Number(c.total) || 0, failed = Number(c.failed) || 0;
|
|
1612
|
+
return `<div class="rd-table-row"><code>${h(c.check)}</code><span>${statusMark(word[c.production] ?? "ungraded")}</span><span>${total ? statusMark(failed ? "failed" : "passed", failed ? `Failed ${failed} of ${total}` : `Passed ${total} of ${total}`) : '<span class="muted">\u2014</span>'}</span><span>${ownKind ? statusMark(ownKind) : '<span class="muted">\u2014</span>'}</span></div>`;
|
|
1613
|
+
}).join("")}</div></section>`;
|
|
1614
|
+
}
|
|
1245
1615
|
function renderAttemptWorkspace(batch, attempt, evidence, options = {}) {
|
|
1246
1616
|
const entry = groupEntryForAttempt(records(batch.entries), attempt), tasks = entry ? tasksForEntry(batch, entry) : records(batch.tasks), index = tasks.findIndex((t) => t.id === attempt.taskId), task = tasks[index] ?? { id: attempt.taskId, prompt: "" };
|
|
1247
|
-
const
|
|
1617
|
+
const allAttempts = entry ? attemptsForEntry(batch, entry) : records(batch.attempts), attempts = allAttempts.filter((a) => a.taskId === attempt.taskId);
|
|
1248
1618
|
const observation2 = { ...evidence, ...evidence.observation ?? {} }, fullEvidence = { ...attempt, ...observation2, status: attempt.status };
|
|
1249
|
-
const people2 = hasConversation(observation2)
|
|
1619
|
+
const people2 = hasConversation(observation2);
|
|
1620
|
+
const view2 = ["tools", "sandbox"].includes(options.view ?? "") ? "tools" : options.view === "logs" ? "logs" : options.view === "conversation" && people2 ? "conversation" : ["activity", "evidence"].includes(options.view ?? "") || !people2 ? "evidence" : "conversation";
|
|
1250
1621
|
const world = entry?.world ?? entry?.test?.world, configuration2 = world?.configuration ?? entry?.configuration ?? entry?.test?.configuration ?? batch.configuration;
|
|
1251
1622
|
const tools = [.../* @__PURE__ */ new Set([...records(configuration2?.preset?.datasets).map((dataset) => String(dataset.tool)), ...Object.keys(observation2.state ?? {}), ...Object.keys(observation2.toolViews ?? {})])];
|
|
1252
1623
|
const tool = options.tool && tools.includes(options.tool) ? options.tool : tools[0], attemptBase = taskHref(batch, task, { attempt: attempt.id });
|
|
1253
1624
|
const response = readOnlyRun(batch) && !(typeof attempt.response === "string" && attempt.response.trim()) ? "" : managedResponse(fullEvidence);
|
|
1254
1625
|
const query = options.query ?? {};
|
|
1255
|
-
const
|
|
1256
|
-
const
|
|
1257
|
-
|
|
1626
|
+
const checks2 = records(fullEvidence.checks), failing = /* @__PURE__ */ new Map();
|
|
1627
|
+
for (const c of checks2) if (!c.passed && !c.error && c.status !== "skipped" && Array.isArray(c.evidence)) {
|
|
1628
|
+
for (const seq of c.evidence) if (Number.isSafeInteger(seq)) failing.set(seq, [...failing.get(seq) ?? [], String(c.id)]);
|
|
1629
|
+
}
|
|
1630
|
+
const callHref = (seq) => taskHref(batch, task, { attempt: attempt.id, view: "evidence", call: seq });
|
|
1258
1631
|
const focus = people2 ? checkFocus(observation2) : /* @__PURE__ */ new Map();
|
|
1259
1632
|
const jump = (checkId) => {
|
|
1260
1633
|
const id = focus.get(checkId);
|
|
1261
1634
|
return id ? taskHref(batch, task, { attempt: attempt.id, view: "conversation", focus: id }) : void 0;
|
|
1262
1635
|
};
|
|
1263
|
-
const
|
|
1264
|
-
|
|
1636
|
+
const toolsNav = `<nav class="tool-nav" aria-label="Attempt tools">${tools.map((t) => navLink(toolName(t), taskHref(batch, task, { attempt: attempt.id, view: "tools", tool: t }), t === tool ? "active" : "")).join("")}</nav>`;
|
|
1637
|
+
const logs = typeof observation2.logs === "string" ? observation2.logs : "";
|
|
1638
|
+
const content = view2 === "tools" ? toolsNav + (tool ? capturedToolView(observation2, tool, { ...query, baseHref: attemptBase }) : '<p class="quiet-empty">No captured tool data.</p>') : view2 === "conversation" ? response + conversationView(observation2, { focus: query.focus }) : view2 === "logs" ? logs.trim() ? `<pre class="rd-log">${h(logs)}</pre>` : stateCard("No log", "The agent wrote nothing to its output in this attempt.") : response + callsSection(observation2, failing, Number(query.call) || void 0) + productionSection(batch, task, fullEvidence);
|
|
1639
|
+
const tab2 = (label2, name, href2) => navLink(label2, href2, view2 === name ? "active" : "").replace("<a ", `<a ${view2 === name ? 'aria-current="page" ' : ""}`);
|
|
1640
|
+
const ms = attemptMs(attempt), calls = Number(fullEvidence.toolCalls ?? attempt.toolCalls) || 0;
|
|
1641
|
+
const attemptMeta = [ms === void 0 ? "" : duration(ms), `${calls} ${calls === 1 ? "call" : "calls"}`].filter(Boolean).join(" \xB7 ");
|
|
1642
|
+
return `<div class="rd">${runHeader(batch, task, attempts, fullEvidence, options.actionsHtml ?? "")}${runFacts(batch, records(batch.attempts))}${queueLine(batch)}${errorMessage(batch.error)}<div class="rd-body">${rail(batch, tasks, allAttempts, task, attempt, view2)}<section class="rd-main" aria-label="Attempt ${h(attempt.number)}"><header class="rd-attempt-head"><div><h2>Attempt ${h(attempt.number)}</h2>${statusMark(attemptKind(attempt))}${attempt.status === "completed" || !["starting", "running", "queued"].includes(attempt.status) ? "" : executionBadge(attempt)}<span class="rd-attempt-meta">${h(attemptMeta)}</span></div>${comparisonForm(batch, task, attempts, attempt)}</header>${invalidNote(attempt)}${checksSection(fullEvidence, callHref, jump)}<nav class="aw-tabs rd-tabs" aria-label="Attempt evidence">${people2 ? tab2("Conversation", "conversation", taskHref(batch, task, { attempt: attempt.id, view: "conversation" })) : ""}${tab2("Evidence", "evidence", people2 ? taskHref(batch, task, { attempt: attempt.id, view: "evidence" }) : attemptBase)}${tab2("World data", "tools", taskHref(batch, task, { attempt: attempt.id, view: "tools" }))}${tab2("Logs", "logs", taskHref(batch, task, { attempt: attempt.id, view: "logs" }))}</nav><div id="attempt-evidence" class="aw-evidence-body">${errorMessage(fullEvidence.error)}${content}</div></section></div></div>`;
|
|
1265
1643
|
}
|
|
1266
1644
|
function renderManagedComparison(data) {
|
|
1267
1645
|
const sides = records(data.attempts ?? [data.left, data.right]);
|
|
@@ -1391,20 +1769,20 @@ function mountWorldWorkspace(node, options) {
|
|
|
1391
1769
|
function render() {
|
|
1392
1770
|
if (disposed) return;
|
|
1393
1771
|
const currentRuns = selected ? setupRuns(runs, selected) : [], run = currentRuns[0], attempts = run?.attempts ?? [], tasks = selected?.tasks ?? [], choices = worldSetups(tests, world.id, agentId);
|
|
1394
|
-
node.innerHTML = `<div class="ww-workspace"><header class="ww-header"><h1>${h(world.name)}</h1><div class="ww-world-actions"><label class="ww-agent-select">Agent<select data-ww-select="agent"><option value="" disabled>Choose agent</option>${agents.map((a) => `<option value="${h(a.id)}" ${a.id === agentId ? "selected" : ""}>${h(agentLabel(a, agents))}</option>`).join("")}</select></label><a data-nav class="button-link" href="${base}?data=1">View data</a><button type="button" data-ww="configure">Configure</button>${selected ? options.runActions?.(selected.id) ?? button("Run tasks", "run-saved-test", selected.id, "primary") : ""}</div></header
|
|
1772
|
+
node.innerHTML = `<div class="ww-workspace"><header class="ww-header"><div class="ww-identity"><h1>${h(world.name)}</h1><div class="worlds-id"><code title="${h(world.id)}">${h(shortId(world.id))}</code>${copyButton(world.id, "Copy world id")}<span>Revision ${h(world.revision)}</span></div></div><div class="ww-world-actions"><label class="ww-agent-select">Agent<select data-ww-select="agent"><option value="" disabled>Choose agent</option>${agents.map((a) => `<option value="${h(a.id)}" ${a.id === agentId ? "selected" : ""}>${h(agentLabel(a, agents))}</option>`).join("")}</select></label><a data-nav class="button-link" href="${base}?data=1">View data</a><button type="button" data-ww="configure">Configure</button>${selected ? options.runActions?.(selected.id) ?? button("Run tasks", "run-saved-test", selected.id, "primary") : ""}</div></header><p class="ww-error" role="alert" ${error ? "" : "hidden"}>${h(error)}</p>${errors.map((e) => `<p class="ww-error" role="alert">${h(e.message)}</p>`).join("")}${error || errors.length ? '<button type="button" data-ww="retry">Retry loading tasks and runs</button>' : ""}${!loaded ? skeletonRows(4) : ""}${choices.length > 1 ? `<label class="ww-setup-select">Configuration<select data-ww-select="test">${!selected ? '<option value="" selected disabled>New configuration</option>' : ""}${choices.map((t) => `<option value="${h(t.id)}" ${t.id === selected?.id ? "selected" : ""}>${h(t.name)}</option>`).join("")}</select></label>` : ""}${loaded && configure ? configuration2() : loaded ? `${run ? `<div class="ww-latest"><a data-nav href="/playgrounds/${enc(run.id)}">${statusMark(runStatus(run))}</a><span>Latest run</span>${when(run.createdAt)}</div>` : ""}${run ? `<a data-nav class="ww-summary-link" href="/playgrounds/${enc(run.id)}" aria-label="Open the latest run">${summaryWidgets(attempts, hasChecks(run?.tasks ?? tasks), run?.summary?.counts?.requested ?? attempts.length)}</a>` : ""}<div class="ww-section-heading"><h2>Tasks${tasks.length ? ` <span class="ww-task-count">${tasks.length}</span>` : ""}</h2><div class="actions">${worldHistory(runs, world.id, agentId || void 0).length || selected ? `<button type="button" data-ww="history" aria-expanded="${showHistory}">History</button>` : ""}<button type="button" data-ww="configure">${tasks.length ? "Edit tasks" : "Add tasks"}</button></div></div>${tasks.length ? `<div class="worlds-scroll ww-tasks-scroll" role="region" aria-label="Tasks" tabindex="0"><section class="ww-task-table"><div class="ww-table-head"><span>Task</span><span>Result</span><span>Attempts</span><span>Median</span><span></span></div>${tasks.map((task, index) => {
|
|
1395
1773
|
const list4 = attempts.filter((a) => a.taskId === task.id), taskURL = run ? `/playgrounds/${enc(run.id)}?task=${enc(task.id)}${list4[0] ? "&attempt=" + enc(list4[0].id) : ""}` : "";
|
|
1396
|
-
return `<article class="ww-task-row"><div class="ww-task-identity">${taskURL ? `<a data-nav class="ww-task-name" href="${taskURL}"><span class="ww-ordinal">${index + 1}</span><strong>${h(label(task, index))}</strong></a>` : `<strong class="ww-task-name"><span class="ww-ordinal">${index + 1}</span>${h(label(task, index))}</strong>`}<p class="ww-task-prompt" title="${h(task.prompt)}">${h(task.prompt)}</p></div>${(() => {
|
|
1774
|
+
return `<article class="ww-task-row"><div class="ww-task-identity">${taskURL ? `<a data-nav class="ww-task-name" href="${taskURL}"><span class="ww-ordinal">${index + 1}</span><strong title="${h(label(task, index))}">${h(label(task, index))}</strong></a>` : `<strong class="ww-task-name"><span class="ww-ordinal">${index + 1}</span>${h(label(task, index))}</strong>`}<p class="ww-task-prompt" title="${h(task.prompt)}">${h(task.prompt)}</p></div>${(() => {
|
|
1397
1775
|
const o = taskOutcome(list4, hasChecks([task]), Number(task.attempts) || list4.length);
|
|
1398
|
-
return `<div class="ww-rate ${o.tone}"><strong>${h(o.value)}</strong><span>${h(o.note)}</span
|
|
1776
|
+
return `<div class="ww-rate ${o.tone}">${taskURL ? `<a data-nav class="ww-result-link" href="${taskURL}">${run && list4.length ? statusMark(taskKind(list4)) : ""}<strong>${h(o.value)}</strong><span>${h(o.note)}</span></a>` : `<strong>${h(o.value)}</strong><span>${h(o.note)}</span>`}</div>`;
|
|
1399
1777
|
})()}<div class="ww-attempt-marks" role="group" aria-label="Attempts for ${h(label(task, index))}">${list4.map((a) => {
|
|
1400
1778
|
const o = attemptOutcome(a);
|
|
1401
|
-
return `<a data-nav class="ww-attempt-mark ${h(a.status)} outcome-${o.key}" href="/playgrounds/${enc(run.id)}?task=${enc(task.id)}&attempt=${enc(a.id)}" title="Attempt ${a.number}: ${h(attemptLabel(a.status))} \xB7 ${o.label}" aria-label="Attempt ${a.number}: ${h(attemptLabel(a.status))} \xB7 ${o.label}">${
|
|
1779
|
+
return `<a data-nav class="ww-attempt-mark ${h(a.status)} outcome-${o.key}" href="/playgrounds/${enc(run.id)}?task=${enc(task.id)}&attempt=${enc(a.id)}" title="Attempt ${a.number}: ${h(attemptLabel(a.status))} \xB7 ${o.label}" aria-label="Attempt ${a.number}: ${h(attemptLabel(a.status))} \xB7 ${o.label}">${glyph(attemptKind(a))}</a>`;
|
|
1402
1780
|
}).join("") || `<span class="muted">Repeat ${h(task.attempts)} times</span>`}</div><span class="ww-task-time">${list4.length ? h(medianTime(list4)) : ""}</span>${taskURL ? `<a data-nav class="ww-row-inspect" href="${taskURL}" aria-label="Inspect ${h(label(task, index))}">\u2192</a>` : "<span></span>"}</article>`;
|
|
1403
|
-
}).join("")}</section>` :
|
|
1781
|
+
}).join("")}</section></div>` : stateCard("Add tasks to this world", agents.length ? "Configure tasks for your agent to run." : "Connect an agent to run tasks.", agents.length ? '<button type="button" data-ww="configure">Add tasks</button>' : '<a data-nav href="/agents">Connect an agent</a>')}${selected && !currentRuns.length && setupHistory(runs, selected).some((item) => item.earlier) ? '<p class="ww-snapshot-notice">This configuration has changed. Earlier attempts are in History.</p>' : ""}${showHistory ? history2() : ""}` : ""}${peopleSection(world)}</div>`;
|
|
1404
1782
|
}
|
|
1405
1783
|
function history2() {
|
|
1406
1784
|
const all = worldHistory(runs, world.id, agentId || void 0);
|
|
1407
|
-
return `<section class="ww-history"><div class="ww-section-heading"><h2>History</h2><button type="button" data-ww="new">New configuration</button></div>${all.length ? all.map(({ run, attemptCount, grouped }) => `<a data-nav class="
|
|
1785
|
+
return `<section class="ww-history"><div class="ww-section-heading"><h2>History</h2><button type="button" data-ww="new">New configuration</button></div>${all.length ? `<div class="worlds-scroll" role="region" aria-label="Run history" tabindex="0"><table class="worlds-table ww-history-table"><thead><tr><th scope="col">Result</th><th scope="col">Run</th><th scope="col" class="num">Attempts</th><th scope="col" class="num">Started</th></tr></thead><tbody>${all.map(({ run, attemptCount, grouped }) => `<tr><td><a data-nav href="/playgrounds/${enc(run.id)}">${statusMark(runStatus(run))}</a></td><td><a data-nav class="worlds-name" href="/playgrounds/${enc(run.id)}" title="${h(run.groupName ?? run.test?.name ?? run.id)}">${h(run.groupName ?? run.test?.name ?? shortId(run.id))}</a><div class="worlds-id"><code title="${h(run.id)}">${h(shortId(run.id))}</code>${copyButton(run.id, "Copy run id")}${grouped ? "<span>Group</span>" : ""}</div></td><td class="num"><a data-nav href="/playgrounds/${enc(run.id)}">${attemptCount}</a></td><td class="num">${when(run.createdAt)}</td></tr>`).join("")}</tbody></table></div>` : stateCard("No runs recorded", "Run tasks to see their results here.")}</section>`;
|
|
1408
1786
|
}
|
|
1409
1787
|
async function refresh(initial = false) {
|
|
1410
1788
|
try {
|
|
@@ -1476,6 +1854,12 @@ function mountWorldWorkspace(node, options) {
|
|
|
1476
1854
|
capture();
|
|
1477
1855
|
error = "";
|
|
1478
1856
|
switch (control.dataset.ww) {
|
|
1857
|
+
case "retry":
|
|
1858
|
+
clearTimeout(timer);
|
|
1859
|
+
loaded = false;
|
|
1860
|
+
render();
|
|
1861
|
+
void refresh(true);
|
|
1862
|
+
return;
|
|
1479
1863
|
case "configure":
|
|
1480
1864
|
if (launchPending()) {
|
|
1481
1865
|
error = "Resolve the pending run before editing this configuration.";
|
|
@@ -1559,7 +1943,45 @@ function worldDataPage(title2, context, back, data, base, query) {
|
|
|
1559
1943
|
};
|
|
1560
1944
|
const tabs = tools.map((name) => `<a data-nav class="${name === tool ? "active" : ""}" href="${h(link(name))}" ${name === tool ? 'aria-current="page"' : ""}><span class="world-data-logo" aria-hidden="true">${toolLogo(name)}</span>${h(toolName(name))}</a>`).join("");
|
|
1561
1945
|
const options = Object.fromEntries([...query].filter(([key]) => key === "resource" || key === "conversation"));
|
|
1562
|
-
return `<a data-nav class="back" href="${h(back.href)}">\u2190 ${h(back.label)}</a><header class="page-head"><div><h1>${h(title2)}</h1><p class="page-meta">${h(context)}</p></div></header><p class="world-data-note">Starting data, before any run. Read-only.</p>` + (tools.length ? `<nav class="tabs world-data-tabs" aria-label="Tools">${tabs}</nav>${recordsView(data, tool, { ...options, embedded: true, baseHref: link(tool) })}` :
|
|
1946
|
+
return `<div class="world-data-page"><a data-nav class="back" href="${h(back.href)}">\u2190 ${h(back.label)}</a><header class="page-head"><div><h1>${h(title2)}</h1><p class="page-meta">${h(context)}</p></div></header><p class="world-data-note">Starting data, before any run. Read-only.</p>` + (tools.length ? `<nav class="tabs world-data-tabs" aria-label="Tools">${tabs}</nav>${recordsView(data, tool, { ...options, embedded: true, baseHref: link(tool) })}` : stateCard("No tools in this world", "Choose tools in the world editor.")) + "</div>";
|
|
1947
|
+
}
|
|
1948
|
+
function worldToolsCell(world) {
|
|
1949
|
+
const tools = [...new Set(world.tools ?? (world.configuration?.preset?.datasets ?? []).map((dataset) => dataset.tool))];
|
|
1950
|
+
const names = tools.map(toolName);
|
|
1951
|
+
return `<div class="world-tool-icons" role="group" aria-label="Tools: ${h(names.join(", "))}">${tools.slice(0, 2).map((tool) => `<span class="world-tool-name" title="${h(toolName(tool))}">${toolLogo(tool)}<span>${h(toolName(tool))}</span></span>`).join("")}${tools.length > 2 ? `<span class="world-tool-more" title="${h(names.join(", "))}">+${tools.length - 2}</span>` : ""}</div>`;
|
|
1952
|
+
}
|
|
1953
|
+
function worldsTable(worlds2, taskCounts, writable = true) {
|
|
1954
|
+
if (!worlds2.length) return stateCard("No worlds yet", "Create a world with the tools your agent uses.", writable ? '<a href="/worlds/new" data-nav class="button-link primary">Create world</a>' : "");
|
|
1955
|
+
return `<div class="worlds-scroll" role="region" aria-label="Worlds" tabindex="0"><table class="worlds-table${taskCounts ? "" : " worlds-no-tasks"}"><thead><tr><th scope="col">World</th><th scope="col">Tools</th>${taskCounts ? '<th scope="col" class="num">Tasks</th>' : ""}<th scope="col" class="num">Revision</th><th scope="col" class="num">Updated</th></tr></thead><tbody>${worlds2.map((world) => {
|
|
1956
|
+
const base = "/worlds/" + encodeURIComponent(world.id);
|
|
1957
|
+
return `<tr><td><a data-nav class="worlds-name" href="${base}" title="${h(world.name)}">${h(world.name)}</a><div class="worlds-id"><code title="${h(world.id)}">${h(shortId(world.id))}</code>${copyButton(world.id, "Copy world id")}</div></td><td>${worldToolsCell(world)}</td>${taskCounts ? `<td class="num"><a data-nav href="${base}" data-world-count="${h(world.id)}">${h(taskCounts.get(world.id) ?? 0)}</a></td>` : ""}<td class="num">${h(world.revision ?? "\u2014")}</td><td class="num">${when(world.updatedAt)}</td></tr>`;
|
|
1958
|
+
}).join("")}</tbody></table></div>`;
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
// frontend/src/agent-page.ts
|
|
1962
|
+
function agentConnection(agent, operation) {
|
|
1963
|
+
const ready = agent.execution?.mode === "container" && !!agent.taskInput;
|
|
1964
|
+
const [kind, label2] = operation?.state === "connecting" ? ["running", "Connecting\u2026"] : operation?.state === "queued" ? ["queued", "Connect queued"] : operation?.stale ? ["invalid", "Needs recheck"] : operation?.state === "connected" ? ["passed", "Connected"] : operation?.state === "failed" ? ["failed", "Connection failed"] : operation?.state === "cancelled" ? ["stopped", "Connection cancelled"] : operation?.state === "configured" || ready ? ["ungraded", "Configured"] : ["ungraded", "Not connected"];
|
|
1965
|
+
return { kind, label: label2 };
|
|
1966
|
+
}
|
|
1967
|
+
function agentFacts(agent, operation) {
|
|
1968
|
+
const connection = agentConnection(agent, operation), folder = String(agent.cwd ?? "");
|
|
1969
|
+
const command = String(agent.command ?? agent.configPath ?? "");
|
|
1970
|
+
const execution = agent.execution?.mode === "container" ? String(agent.execution.image ?? "Container") : "Host process";
|
|
1971
|
+
const items = [
|
|
1972
|
+
{ label: "Folder", value: folder, mono: true, title: folder, html: `<span class="catalog-copy"><span class="catalog-cut">${h(folder)}</span>${copyButton(folder, "Copy folder")}</span>` },
|
|
1973
|
+
{ label: agent.command ? "Start command" : "Config", value: command, mono: true, title: command, html: `<span class="catalog-cut">${h(command)}</span>` },
|
|
1974
|
+
{ label: "Execution", value: execution, mono: agent.execution?.mode === "container", title: execution },
|
|
1975
|
+
{ label: "Connection", value: connection.label, html: statusMark(connection.kind, connection.label) }
|
|
1976
|
+
];
|
|
1977
|
+
if (agent.provider?.model) items.push({ label: "Model", value: String(agent.provider.model) });
|
|
1978
|
+
return facts(items, "Agent facts");
|
|
1979
|
+
}
|
|
1980
|
+
function agentRecentRuns(runs, agent, emptyAction, options = {}) {
|
|
1981
|
+
const selected = options.testId ? runs.filter((run) => run.test?.id === options.testId || run.entries?.some((entry) => entry.test?.id === options.testId)) : runs;
|
|
1982
|
+
const recent = [...selected].sort((a, b) => timeOf(b.createdAt) - timeOf(a.createdAt) || String(b.id).localeCompare(String(a.id))).slice(0, options.testId ? selected.length : 10);
|
|
1983
|
+
const all = "/playgrounds?" + new URLSearchParams({ agent: agent.id });
|
|
1984
|
+
return `<section class="agent-recent"><div class="section-title"><h2>${options.testId ? "Runs" : "Recent runs"}</h2>${recent.length ? `<a data-nav href="${h(all)}">All runs</a>` : ""}</div>${recent.length ? runsTable(recent, { now: options.now }) : stateCard("No runs yet", "Run a saved task to see its results here.", emptyAction)}</section>`;
|
|
1563
1985
|
}
|
|
1564
1986
|
|
|
1565
1987
|
// frontend/src/workspace-view.ts
|
|
@@ -1579,7 +2001,7 @@ function viewBanner(boot2, now = /* @__PURE__ */ new Date()) {
|
|
|
1579
2001
|
if (machine.state === "starting") return '<section class="view-banner" role="status"><span class="status-spinner" aria-hidden="true"></span><div><strong>Your workspace is starting\u2026</strong><p>Worlds, agents and tools open here when it is up, and runs started in the workspace are listed again. This page reloads by itself.</p></div></section>';
|
|
1580
2002
|
if (machine.state === "capped") {
|
|
1581
2003
|
const month = now.toLocaleString("en-US", { month: "long", timeZone: "UTC" }), ask = boot2.hosted?.execution === false;
|
|
1582
|
-
return `<section class="view-banner" role="status"><div><strong>Hosted hours used for ${h(month)}</strong><p>This workspace used its ${h(hoursLabel(machine.hoursCap))} for ${h(month)}. Your data is kept; the workspace wakes again on the 1st.
|
|
2004
|
+
return `<section class="view-banner" role="status"><div><strong>Hosted hours used for ${h(month)}</strong><p>This workspace used its ${h(hoursLabel(machine.hoursCap))} for ${h(month)}. Your data is kept; the workspace wakes again on the 1st. Connect with <code>ancha doctor --on cloud</code>, then <code>ancha run --on cloud</code>${ask ? ', or <a href="/account#hosted">request higher limits</a> to run your own agent on the workspace machine' : ""}.</p></div></section>`;
|
|
1583
2005
|
}
|
|
1584
2006
|
const asleep = machine.state === "absent" ? "Your workspace hasn\u2019t started yet." : "Your workspace is asleep.";
|
|
1585
2007
|
return `<section class="view-banner" role="status"><div><strong>${asleep}</strong><p>Runs you upload are here, and your worlds and agents as the workspace last listed them. Start it to work with them.</p></div>${machine.canStart ? button("Start workspace", "start-workspace", "", "primary") : '<p class="muted">This workspace is read-only right now.</p>'}</section>`;
|
|
@@ -1668,7 +2090,7 @@ function starterCount(tool, key, state) {
|
|
|
1668
2090
|
}
|
|
1669
2091
|
|
|
1670
2092
|
// frontend/src/generated/coding-agent-skill.ts
|
|
1671
|
-
var codingAgentSkill = "---\nname: ancha\ndescription: Test, debug and fix an AI agent (a Slack bot, a support or on-call agent) against stateful replicas of the tools it uses, built from its production traces, and prove a fix with graded runs in the cloud. Use when asked to test an agent with Ancha, or in a repository that has ancha.yaml.\n---\n\n# Ancha\n\nAncha gives an AI agent the other side of its job: stateful replicas of the tools it uses (Slack, GitHub, Datadog, PagerDuty and more), seeded with one fictional company or rebuilt from a production trace, and checks that grade every attempt from the agent's calls and the world's end state. The verdict comes from the world, not from mocks you wrote yourself. `ancha run --on cloud` runs each attempt on a fresh machine of its own in Ancha's cloud.\n\n## Run the CLI\n\nBefore the CLI is installed, run every command as `npx -y @ancha-labs/cli <command>`. After `npm install -g @ancha-labs/cli` (Node 24 or newer), run `ancha <command>`. Never run `npx` with the bare name `ancha`: that npm name is not this package.\n\nAdd `--json` to every command. Runs print NDJSON events that end with `run_finished`; hosted imports print one result per saved test. `env list` and `sandbox list` return arrays; trace commands use the fields described in `ancha docs traces`. `ancha schema <kind> --json` prints the JSON Schema of `ancha.yaml`, scene files and these outputs. If your command can time out, give `ancha run` an `--idempotency-key <key>`: running it again with the same key returns the same run instead of starting another.\n\n## First steps\n\n<!-- ancha:first-steps -->\n1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.\n ```sh\n ancha --version || npm install -g @ancha-labs/cli\n ancha login\n ```\n2. **Name the agent's command.** Run it in the agent's project: it writes `ancha.yaml`, and installs and runs nothing.\n ```sh\n ancha init --agent \"<the command that starts your agent>\"\n ```\n3. **Store the secrets it needs.** Run it in the agent's project: it stores the key in your workspace and names it under `agent.pass_env` in `ancha.yaml`, so the agent gets it in cloud runs. The value comes from your shell, never from an argument.\n ```sh\n ancha secrets set OPENAI_API_KEY\n ```\n4. **Connect it.** A fresh machine in the cloud installs the project's dependencies and finds the agent's command; an agent served over HTTP also starts and answers.\n ```sh\n ancha doctor --on cloud\n ```\n - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.\n5. **Make a test from one production failure.** Take the trace of one run where the agent went wrong, with its tool calls and their results, and say what went wrong. The test lands in `scenes/from-traces/` and in your workspace.\n ```sh\n ancha import trace.jsonl --expect \"<what went wrong>\" --json\n ```\n - A trace in Langfuse or LangSmith: `ancha import --from langfuse <trace id>`, or `--from langsmith`.\n - A trace your agent already sent to your workspace: `ancha traces --failed`, then `ancha pull <trace id> --expect \"<what went wrong>\"`.\n - The test lists what one trace cannot settle: answer with `ancha pull <test id> --answer <question>=<answer>`.\n6. **Point the agent at the test's tools.** In a test, the agent calls Ancha instead of production:\n - Its clients for Slack, GitHub and the other tools Ancha replicates take the URLs and credentials Ancha supplies: `ancha connect <tool>` prints the settings.\n - Its own functions: wrap them with `wrapTools` from `@ancha-labs/tools` (`ancha.wrap_tools` in Python), or serve them over MCP.\n7. **Run it in the cloud.** Three attempts of the test. The run says, check by check, whether production's failure happens again, and ends with the link to its result.\n ```sh\n ancha run --on cloud scenes/from-traces/<test>/scene.yaml --attempts 3 --concurrency 3 --json\n ```\n - Your agent and its worlds run in the cloud, each attempt on a fresh machine of its own; a run keeps going when your laptop closes, and its results land in Runs.\n - `--concurrency <n>` sets how many attempts run at once.\n - `ancha wait <run id>` follows a run again from any terminal; `ancha explain <run id>` shows why a check failed.\n - `ancha status --on cloud` shows which of these steps your workspace has done.\n8. **Fix the agent and keep the test.** Keep the failing run as the reference, fix the agent, and run again: exit 0 means every check passes and nothing regressed.\n ```sh\n ancha baseline save before --from <run id>\n ancha run --on cloud scenes/from-traces/<test>/scene.yaml --attempts 3 --concurrency 3 --compare before --json\n ```\n - Commit `scenes/from-traces/` so every run, in CI too, keeps it fixed.\n9. **Run it on this computer.** While you develop, `ancha run --on local` runs the agent and its worlds on this computer, with the same checks.\n ```sh\n ancha run --on local scenes/from-traces/<test>/scene.yaml --attempts 1 --json\n ```\n - Here the agent gets the keys in `agent.pass_env` from your shell, and model-graded checks need `OPENROUTER_API_KEY`.\n<!-- /ancha:first-steps -->\n\n## Cloud runs\n\n- `ancha run --on cloud` sends the project as one bundle: the agent's files, without hidden directories, dependencies or credential-like files, and its tests with their worlds and checks, which stay with the grader and never reach the agent. Each attempt's machine installs the dependencies, runs the agent and grades it with the same engine as a run on this computer. `--attempts <n>` sets the attempts per test, `--concurrency <n>` how many run at once.\n- The agent gets the workspace's secrets for the names in `agent.pass_env`, and its network reaches its tools and its model providers. Model-graded checks and the people in a world run on the workspace's model credit.\n- The `run_finished` event carries `url` (the result in the workspace) and `summary`, with `counts` of the attempts: requested, completed, invalid, skipped and cancelled. Interrupting the command stops the following, never the run: `ancha wait <run id>` follows it again, and `--detach` returns once the run is accepted.\n- `ancha explain <run id> --json` shows each failed check: what was expected, what happened, and the calls and world events behind it. Read it before guessing from the code; many bugs only show up with the world's data and timing.\n- `ancha status --on cloud --json` shows the workspace's checks (agent connected, traces imported, first graded cloud run) and the next command. In CI, `ANCHA_SERVER_URL` and `ANCHA_API_KEY` replace the login. More: `ancha docs cloud`.\n\n## An app, not a command\n\nIf the AI feature lives inside an app (a web app or API server with its database, workers and scheduled jobs), don't wrap it in `agent.command`. Ancha starts the app once per attempt with `agent.start`, waits for `agent.ready_url`, delivers the tools' events to `agent.url`, and a scene's `world_rules.app_calls` call the app's own routes, such as its cron jobs, at a time. Read `ancha docs apps` before writing `ancha.yaml`. The start script gives the app a clean database, cache and seed every attempt: a new world has new URLs and tokens, and stale rows or sync cursors make an app silently do nothing.\n\n## More from production traces\n\n`ancha import <trace file> --json` sends the trace to the workspace, which rebuilds the world and the checks, and writes the test to `scenes/from-traces/<name>/scene.yaml`. The test lists the questions one trace cannot settle, each with the default it uses. Ask the user for the answers; don't guess them. Pass them with `ancha pull <test id> --answer <question>=<value>`. `ancha import --offline <trace file> --json` makes the tests on this computer instead, one per conversation, and uploads nothing; there, `--answer` and `--force` go on the import.\n\nThe test should fail the same way production did. If it doesn't, run it on this computer: `ancha traces diff <trace file> latest` shows the calls production made and the attempt didn't, and the import also lists the app's own setup calls, which the start script or an `app_call` has to make.\n\nIf the user's workspace takes traces (their agents send them to it), each trace becomes a test there: `ancha pull --all --json` writes every test that is turned on (`--agent <name>` for one agent's), `ancha traces --failed --json` lists the ones where production failed a check, `ancha traces show <id> --json` previews the test, and `ancha pull <id> --json` writes one, with `--answer` for its questions. Checks you add to a pulled `scene.yaml` stay when you pull a newer version; any other edit stops the pull. More: `ancha docs traces`.\n\n## Other tests\n\nThe starter scene `ancha init` writes when `scenes/` holds no tests only proves that the agent reaches each tool. For the agent's real job beyond its traces, `ancha test new \"<the test in one sentence>\" --json` drafts a test with people for the project's world (`ancha init --intent \"<company and scenario>\"` makes the world and a first test). Review its checks before you run it. To write a seed yourself, `ancha twins seed <tool> --json` prints the tool's fields, an example that validates as written, and the checks a scene can make on it. More: `ancha docs scenes`.\n\n## The rule\n\nFix the agent, not `ancha.yaml`, the scenes or their checks. The exception is a check that is wrong for the real API, such as a method the official SDK never sends. Then don't quietly edit it: tell the user, show the evidence (the call from `ancha explain`, the vendor's documentation), and change it only with their agreement.\n\nNever give the agent under test the scenes, checks, seeds or reference companions (`oracle.mjs`, `null.mjs`), and never point it at a real SaaS API.\n\n## What the agent gets\n\nEach attempt gives the agent its tools as environment variables, with fake credentials that only work against the replicas:\n\n- Slack: `SLACK_API_URL` (ends in `/api/`), `SLACK_BOT_TOKEN`\n- GitHub: `GITHUB_API_URL`, `GITHUB_TOKEN`\n- Datadog: `DATADOG_API_URL`, `DD_API_KEY`, `DD_APP_KEY`\n- PagerDuty: `PAGERDUTY_API_URL`, `PAGERDUTY_API_TOKEN`, `PAGERDUTY_FROM_EMAIL`, `PAGERDUTY_ROUTING_KEY`\n- the same pattern for the other tools in the world; `ANCHA_TASK` carries a command-line task.\n\n`ancha connect <tool> --lang ts|py` prints the SDK settings. `ancha twins coverage <tool>` lists the endpoints each replica implements.\n\nGoogle clients (`googleapis`, `@googleapis/*`) take the replica's URL in each call's options: `drive.files.list(params, { rootUrl: process.env.GOOGLE_DRIVE_API_URL + '/' })`. A `rootUrl` set on the client keeps only the host; Ancha still routes those calls by their token, but the client sends file uploads to www.googleapis.com.\n\nThe agent's own keys are the names in `agent.pass_env` in `ancha.yaml`, such as `agent.pass_env: [OPENAI_API_KEY]`, and `agent.env` sets fixed values, such as the path of a key file. In the cloud each name comes from the workspace's secrets (`ancha secrets set NAME`). `ancha run --on local` starts the agent on this computer instead, with this computer's network and those names from this shell (or `--pass-env NAME`); `--on docker` seals it in a container (`agent.execution: { mode: container, image: node:24-slim }`, which needs Docker). An agent without its model key stops at its first model call.\n\n## When something fails\n\n- Exit 1: a check failed or the comparison regressed (a single check's drop counts, see `comparison.droppedChecks`). Run `ancha explain <run id> --json`.\n- Exit 2: usage, config, scene or authentication error, or a cancelled cloud run. `AUTH_INVALID` means `ancha login` again or a valid `ANCHA_API_KEY`; `CONFIG_INVALID` naming a workspace secret means `ancha secrets set NAME`. Read the `hint`.\n- Exit 3: infrastructure, or an attempt the harness couldn't run or grade. It counts as invalid, never as a failed check, so it's not the agent's fault; run again, and `ancha doctor --on cloud --json` if it repeats.\n- Exit 4, only with `--strict`: the agent called an endpoint a replica doesn't implement. `ancha explain` lists these endpoints even without `--strict`; check `ancha twins coverage <tool>` before changing the agent.\n\nRead the error's stable `code` and `message`, then follow its `hint` when provided. More: `ancha docs`, `ancha docs <topic>` for setup, run, traces, explain, compare, scenes, integrations, cloud and playgrounds, and https://docs.ancha.io/coding-agents.\n\nTell the user what you ran, where it ran, the pass rate, the evidence and the result link. Never claim a fix until `ancha run --compare` exits 0.\n";
|
|
2093
|
+
var codingAgentSkill = "---\nname: ancha\ndescription: Test, debug and fix an AI agent (a Slack bot, a support or on-call agent) against stateful replicas of the tools it uses, built from its production traces, and prove a fix with graded runs in the cloud. Use when asked to test an agent with Ancha, or in a repository that has ancha.yaml.\n---\n\n# Ancha\n\nAncha gives an AI agent the other side of its job: stateful replicas of the tools it uses (Slack, GitHub, Datadog, PagerDuty and more), seeded with one fictional company or rebuilt from a production trace, and checks that grade every attempt from the agent's calls and the world's end state. The verdict comes from the world, not from mocks you wrote yourself. `ancha run --on cloud` runs each attempt on a fresh machine of its own in Ancha's cloud.\n\n## Run the CLI\n\nBefore the CLI is installed, run every command as `npx -y @ancha-labs/cli <command>`. After `npm install -g @ancha-labs/cli` (Node 24 or newer), run `ancha <command>`. Never run `npx` with the bare name `ancha`: that npm name is not this package.\n\nAdd `--json` to every command. Runs print NDJSON events that end with `run_finished`; hosted imports print one result per saved test. `env list` and `sandbox list` return arrays; trace commands use the fields described in `ancha docs traces`. `ancha schema <kind> --json` prints the JSON Schema of `ancha.yaml`, scene files and these outputs. If your command can time out, give `ancha run` an `--idempotency-key <key>`: running it again with the same key returns the same run instead of starting another.\n\n## First steps\n\n<!-- ancha:first-steps -->\n1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.\n ```sh\n ancha --version || npm install -g @ancha-labs/cli\n ancha login\n ```\n2. **Name the agent's command.** Run it in the agent's project: it writes `ancha.yaml`, and installs and runs nothing.\n ```sh\n ancha init --agent \"<the command that starts your agent>\"\n ```\n3. **Store the secrets it needs.** Run it in the agent's project: it stores the key in your workspace and names it under `agent.pass_env` in `ancha.yaml`, so the agent gets it in cloud runs. The value comes from your shell, never from an argument.\n ```sh\n ancha secrets set OPENAI_API_KEY\n ```\n4. **Connect it.** A fresh machine in the cloud installs the project's dependencies and finds the agent's command; an agent served over HTTP also starts and answers.\n ```sh\n ancha doctor --on cloud\n ```\n - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.\n5. **Make a test from one production failure.** Take the trace of one run where the agent went wrong, with its tool calls and their results, and say what went wrong. The test lands in `scenes/from-traces/` and in your workspace.\n ```sh\n ancha import trace.jsonl --expect \"<what went wrong>\" --json\n ```\n - A trace in Langfuse or LangSmith: `ancha import --from langfuse <trace id>`, or `--from langsmith`.\n - A trace your agent already sent to your workspace: `ancha traces --failed`, then `ancha pull <trace id> --expect \"<what went wrong>\"`.\n - The test lists what one trace cannot settle: answer with `ancha pull <test id> --answer <question>=<answer>`.\n6. **Point the agent at the test's tools.** In a test, the agent calls Ancha instead of production:\n - Its clients for Slack, GitHub and the other tools Ancha replicates take the URLs and credentials Ancha supplies: `ancha connect <tool>` prints the settings.\n - Its own functions: wrap them with `wrapTools` from `@ancha-labs/tools` (`ancha.wrap_tools` in Python), or serve them over MCP.\n7. **Run it in the cloud.** Three attempts of the test. The run says, check by check, whether production's failure happens again, and ends with the link to its result.\n ```sh\n ancha run --on cloud scenes/from-traces/<test>/scene.yaml --attempts 3 --concurrency 3 --json\n ```\n - Your agent and its worlds run in the cloud, each attempt on a fresh machine of its own; a run keeps going when your laptop closes, and its results land in Runs.\n - `--concurrency <n>` sets how many attempts run at once.\n - `ancha wait <run id>` follows a run again from any terminal; `ancha explain <run id>` shows why a check failed.\n - `ancha status --on cloud` shows which of these steps your workspace has done.\n8. **Fix the agent and keep the test.** Keep the failing run as the reference, fix the agent, and run again: exit 0 means every check passes and nothing regressed.\n ```sh\n ancha baseline save before --from <run id>\n ancha run --on cloud scenes/from-traces/<test>/scene.yaml --attempts 3 --concurrency 3 --compare before --json\n ```\n - Commit `scenes/from-traces/` so every run, in CI too, keeps it fixed.\n9. **Run it on this computer.** While you develop, `ancha run --on local` runs the agent and its worlds on this computer, with the same checks.\n ```sh\n ancha run --on local scenes/from-traces/<test>/scene.yaml --attempts 1 --json\n ```\n - Here the agent gets the keys in `agent.pass_env` from your shell, and model-graded checks need `OPENROUTER_API_KEY`.\n<!-- /ancha:first-steps -->\n\n## Cloud runs\n\n- `ancha run --on cloud` sends the project as one bundle: the agent's files, without hidden directories, dependencies or credential-like files, and its tests with their worlds and checks, which stay with the grader and never reach the agent. Each attempt's machine installs the dependencies, runs the agent and grades it with the same engine as a run on this computer. `--attempts <n>` sets the attempts per test, `--concurrency <n>` how many run at once.\n- The agent gets the workspace's secrets for the names in `agent.pass_env`, and its network reaches its tools and its model providers. Model-graded checks and the people in a world run on the workspace's model credit.\n- The `run_finished` event carries `url` (the result in the workspace) and `summary`, with `counts` of the attempts: requested, completed, invalid, skipped and cancelled. Interrupting the command stops the following, never the run: `ancha wait <run id>` follows it again, and `--detach` returns once the run is accepted.\n- `ancha explain <run id> --json` shows each failed check: what was expected, what happened, and the calls and world events behind it. Read it before guessing from the code; many bugs only show up with the world's data and timing.\n- `ancha status --on cloud --json` shows the workspace's checks (agent connected, traces imported, first graded cloud run) and the next command. In CI, `ANCHA_SERVER_URL` and `ANCHA_API_KEY` replace the login. More: `ancha docs cloud`.\n\n## An app, not a command\n\nIf the AI feature lives inside an app (a web app or API server with its database, workers and scheduled jobs), don't wrap it in `agent.command`. Ancha starts the app once per attempt with `agent.start`, waits for `agent.ready_url`, delivers the tools' events to `agent.url`, and a scene's `world_rules.app_calls` call the app's own routes, such as its cron jobs, at a time. Read `ancha docs apps` before writing `ancha.yaml`. The start script gives the app a clean database, cache and seed every attempt: a new world has new URLs and tokens, and stale rows or sync cursors make an app silently do nothing.\n\n## More from production traces\n\n`ancha import <trace file> --json` sends the trace to the workspace, which rebuilds the world and the checks, and writes the test to `scenes/from-traces/<name>/scene.yaml`. The test lists the questions one trace cannot settle, each with the default it uses. Ask the user for the answers; don't guess them. Pass them with `ancha pull <test id> --answer <question>=<value>`. `ancha import --offline <trace file> --json` makes the tests on this computer instead, one per conversation, and uploads nothing; there, `--answer` and `--force` go on the import.\n\nThe test should fail the same way production did. If it doesn't, run it on this computer: `ancha traces diff <trace file> latest` shows the calls production made and the attempt didn't, and the import also lists the app's own setup calls, which the start script or an `app_call` has to make.\n\nIf the user's workspace takes traces (their agents send them to it), each trace becomes a test there: `ancha pull --all --json` writes every test that is turned on (`--agent <name>` for one agent's), `ancha traces --failed --json` lists the ones where production failed a check, `ancha traces show <id> --json` previews the test, and `ancha pull <id> --json` writes one, with `--answer` for its questions. Checks you add to a pulled `scene.yaml` stay when you pull a newer version; any other edit stops the pull. More: `ancha docs traces`.\n\n## Other tests\n\nThe starter scene `ancha init` writes when `scenes/` holds no tests only proves that the agent reaches each tool. For the agent's real job beyond its traces, `ancha test new \"<the test in one sentence>\" --json` drafts a test with people for the project's world (`ancha init --intent \"<company and scenario>\"` makes the world and a first test). Review its checks before you run it. To write a seed yourself, `ancha twins seed <tool> --json` prints the tool's fields, an example that validates as written, and the checks a scene can make on it. More: `ancha docs scenes`.\n\n## The rule\n\nFix the agent, not `ancha.yaml`, the scenes or their checks. The exception is a check that is wrong for the real API, such as a method the official SDK never sends. Then don't quietly edit it: tell the user, show the evidence (the call from `ancha explain`, the vendor's documentation), and change it only with their agreement.\n\nNever give the agent under test the scenes, checks, seeds or reference companions (`oracle.mjs`, `null.mjs`), and never point it at a real SaaS API.\n\n## What the agent gets\n\nEach attempt gives the agent its tools as environment variables, with fake credentials that only work against the replicas:\n\n- Slack: `SLACK_API_URL` (ends in `/api/`), `SLACK_BOT_TOKEN`\n- GitHub: `GITHUB_API_URL`, `GITHUB_TOKEN`\n- Datadog: `DATADOG_API_URL`, `DD_API_KEY`, `DD_APP_KEY`\n- PagerDuty: `PAGERDUTY_API_URL`, `PAGERDUTY_API_TOKEN`, `PAGERDUTY_FROM_EMAIL`, `PAGERDUTY_ROUTING_KEY`\n- the same pattern for the other tools in the world; `ANCHA_TASK` carries a command-line task.\n\n`ancha connect <tool> --lang ts|py` prints the SDK settings. `ancha twins coverage <tool>` lists the endpoints each replica implements.\n\nGoogle clients (`googleapis`, `@googleapis/*`) take the replica's URL in each call's options: `drive.files.list(params, { rootUrl: process.env.GOOGLE_DRIVE_API_URL + '/' })`. A `rootUrl` set on the client keeps only the host; Ancha still routes those calls by their token, but the client sends file uploads to www.googleapis.com.\n\nThe agent's own keys are the names in `agent.pass_env` in `ancha.yaml`, such as `agent.pass_env: [OPENAI_API_KEY]`, and `agent.env` sets fixed values, such as the path of a key file. In the cloud each name comes from the workspace's secrets (`ancha secrets set NAME`). `ancha run --on local` starts the agent on this computer instead, with this computer's network and those names from this shell (or `--pass-env NAME`); `--on docker` seals it in a container (`agent.execution: { mode: container, image: node:24-slim }`, which needs Docker). An agent without its model key stops at its first model call.\n\n## When something fails\n\n- Exit 1: a check failed or the comparison regressed (a single check's drop counts, see `comparison.droppedChecks`). Run `ancha explain <run id> --json`.\n- Exit 2: usage, config, scene or authentication error, or a cancelled cloud run. `AUTH_INVALID` means `ancha login` again or a valid `ANCHA_API_KEY`; `CONFIG_INVALID` naming a workspace secret means `ancha secrets set NAME`. Read the `hint`.\n- Exit 3: infrastructure, or an attempt the harness couldn't run or grade. It counts as invalid, never as a failed check, so it's not the agent's fault; run again, and `ancha doctor --on cloud --json` if it repeats.\n- Exit 4, only with `--strict`: an endpoint coverage error or a verdict using simulated tool answers. The summary names the tests, trials and evaluated checks using those answers. `ancha explain` lists endpoint errors; `ancha twins coverage <tool>` shows the endpoint inventory.\n\nRead the error's stable `code` and `message`, then follow its `hint` when provided. More: `ancha docs`, `ancha docs <topic>` for setup, run, traces, explain, compare, scenes, integrations, cloud and playgrounds, and https://docs.ancha.io/coding-agents.\n\nTell the user what you ran, where it ran, the pass rate, the evidence and the result link. Never claim a fix until `ancha run --compare` exits 0.\n";
|
|
1672
2094
|
|
|
1673
2095
|
// frontend/src/workspace-pages.ts
|
|
1674
2096
|
var startSentence = "Set up Ancha for this agent: read https://app.ancha.io/llms.txt and follow its first steps.";
|
|
@@ -1678,10 +2100,40 @@ function startCard(sampleRunId, hosted = false) {
|
|
|
1678
2100
|
return `<section class="start-card" aria-label="Start"><h2>Give this to your coding agent</h2><div class="start-sentence"><code>${h(startSentence)}</code><button class="primary" data-action="copy-start-sentence">Copy</button></div>${sample}</section>`;
|
|
1679
2101
|
}
|
|
1680
2102
|
function helpPage() {
|
|
1681
|
-
|
|
2103
|
+
const groups = [
|
|
2104
|
+
["Set up", [
|
|
2105
|
+
['ancha init --agent "<command>"', "Set up the project with its agent start command."],
|
|
2106
|
+
["ancha connect <tool>", "Print the tool\u2019s SDK connection settings."],
|
|
2107
|
+
["ancha ui", "Open the local console."]
|
|
2108
|
+
]],
|
|
2109
|
+
["Tests", [
|
|
2110
|
+
['ancha test new "<intent>"', "Draft a test from one sentence."],
|
|
2111
|
+
["ancha run --on local", "Run the project\u2019s tests on this computer."],
|
|
2112
|
+
["ancha run --on cloud --attempts 3", "Run three attempts per test in the cloud."]
|
|
2113
|
+
]],
|
|
2114
|
+
["Results", [
|
|
2115
|
+
["ancha runs list", "List runs and their results."],
|
|
2116
|
+
["ancha runs show <id>", "Show a run\u2019s attempts and grade."],
|
|
2117
|
+
["ancha explain <run>", "Read the checks and calls behind a run\u2019s result."],
|
|
2118
|
+
["ancha baseline save <name> --from <run>", "Save a completed run as a baseline."]
|
|
2119
|
+
]],
|
|
2120
|
+
["Traces", [
|
|
2121
|
+
['ancha import <trace.jsonl> --expect "<what went wrong>"', "Turn a production failure into a test with a check."],
|
|
2122
|
+
["ancha import --offline <trace.jsonl>", "Create tests from a trace on this computer."],
|
|
2123
|
+
["ancha traces --failed", "List production traces with failed checks."],
|
|
2124
|
+
["ancha traces show <id>", "Preview the test a production trace makes."],
|
|
2125
|
+
["ancha pull <id>", "Write the test a production trace made into this project."]
|
|
2126
|
+
]],
|
|
2127
|
+
["Hosted", [
|
|
2128
|
+
["ancha login", "Link this computer to your hosted workspace."],
|
|
2129
|
+
["ancha secrets set <NAME>", "Copy a variable from this shell to the workspace."],
|
|
2130
|
+
["ancha secrets list", "List the workspace\u2019s variable names."]
|
|
2131
|
+
]]
|
|
2132
|
+
];
|
|
2133
|
+
return `<section class="help-focus"><h2>Use with your coding agent.</h2><p>Give it Ancha\u2019s instructions to connect your project, create a world, and run tests.</p><div class="actions"><button class="primary" data-action="copy-ancha-skill">Copy instructions</button><button data-action="download-ancha-skill">Download SKILL.md</button><a class="button-link" href="https://app.ancha.io/llms.txt" target="_blank" rel="noopener">Open llms.txt</a></div></section><section class="help-reference"><h2>Command reference</h2><div class="catalog-scroll" tabindex="0" aria-label="Command reference"><table class="catalog-table help-table"><thead><tr><th scope="col">Command</th><th scope="col">What it does</th></tr></thead>${groups.map(([job, commands]) => `<tbody><tr class="help-job"><th scope="rowgroup" colspan="2">${h(job)}</th></tr>${commands.map(([command, description]) => `<tr><td><div class="catalog-copy"><code>${h(command)}</code>${copyButton(command, "Copy command")}</div></td><td>${h(description)}</td></tr>`).join("")}</tbody>`).join("")}</table></div><p class="muted">CLI guide: <code>ancha docs cli-quickstart</code></p></section>`;
|
|
1682
2134
|
}
|
|
1683
2135
|
function testCard(test, world, base, actions, detail = false) {
|
|
1684
|
-
return `<
|
|
2136
|
+
return `<section class="agent-saved-test"><header><div>${detail ? "" : `<a class="test-title" data-nav href="${h(base)}?tab=test&test=${encodeURIComponent(test.id)}">${h(test.name)}</a>`}<div class="test-context">${world ? `<a data-nav href="/worlds/${encodeURIComponent(world.id)}">${h(world.name)}</a>` : "Saved world"}<span>\xB7</span><span>${test.tasks.length} ${test.tasks.length === 1 ? "task" : "tasks"}</span></div></div><div class="actions">${actions}</div></header><div class="catalog-scroll" tabindex="0" aria-label="Test tasks"><table class="catalog-table agent-tasks-table agent-test-tasks"><thead><tr><th scope="col">Prompt</th><th scope="col" class="num">Repeat</th></tr></thead><tbody>${test.tasks.map((task) => `<tr><td><span class="catalog-cut" title="${h(task.prompt)}">${h(task.prompt)}</span></td><td class="num">${h(task.attempts)}</td></tr>`).join("")}</tbody></table></div></section>`;
|
|
1685
2137
|
}
|
|
1686
2138
|
function agentWorldTasks(tests, worlds2, actions) {
|
|
1687
2139
|
const groups = /* @__PURE__ */ new Map();
|
|
@@ -1690,13 +2142,16 @@ function agentWorldTasks(tests, worlds2, actions) {
|
|
|
1690
2142
|
group.push(test);
|
|
1691
2143
|
groups.set(test.worldId, group);
|
|
1692
2144
|
}
|
|
1693
|
-
return [...groups].map(([worldId, configurations]) => {
|
|
2145
|
+
return `<div class="catalog-scroll agent-tasks-scroll" tabindex="0" aria-label="Tasks by world"><table class="catalog-table agent-tasks-table"><thead><tr><th scope="col">Prompt</th><th scope="col" class="num">Repeat</th><th scope="col">Actions</th></tr></thead>${[...groups].map(([worldId, configurations]) => {
|
|
1694
2146
|
const world = worlds2.find((item) => item.id === worldId);
|
|
1695
|
-
return `<
|
|
2147
|
+
return `<tbody><tr class="agent-world-group"><th scope="rowgroup" colspan="3"><a data-nav href="/worlds/${encodeURIComponent(worldId)}">${h(world?.name ?? "Saved world")}</a></th></tr>${configurations.map((test, place) => {
|
|
1696
2148
|
const href2 = "/worlds/" + encodeURIComponent(worldId) + "?" + new URLSearchParams({ agent: test.agentId, test: test.id });
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
2149
|
+
const tasks = test.tasks ?? [];
|
|
2150
|
+
const cell2 = `<td rowspan="${Math.max(1, tasks.length)}" class="agent-task-actions${place === configurations.length - 1 ? " agent-task-last" : ""}"><div class="agent-task-config">${configurations.length > 1 ? `<span class="catalog-cut" title="${h(test.name)}">${h(test.name)}</span>` : ""}<div class="actions"><a data-nav href="${h(href2)}">Open world</a>${actions(test.id)}</div></div></td>`;
|
|
2151
|
+
if (!tasks.length) return `<tr><td class="muted">No tasks</td><td class="num">0</td>${cell2}</tr>`;
|
|
2152
|
+
return tasks.map((task, index) => `<tr><td><a data-nav class="catalog-cut" href="${h(href2)}" title="${h(task.prompt)}">${h(task.prompt)}</a></td><td class="num">${h(task.attempts)}</td>${index === 0 ? cell2 : ""}</tr>`).join("");
|
|
2153
|
+
}).join("")}</tbody>`;
|
|
2154
|
+
}).join("")}</table></div>`;
|
|
1700
2155
|
}
|
|
1701
2156
|
var SECTIONS = { worlds: "Worlds", agents: "Agents", playgrounds: "Runs", tools: "Tools", help: "Help", settings: "Settings" };
|
|
1702
2157
|
var notFoundPage = (hosted) => `<p>Nothing lives at this address.</p><p>${hosted ? '<a href="/start">Get started</a>' : '<a href="/playgrounds" data-nav>Go to Runs</a>'}</p>`;
|
|
@@ -1707,12 +2162,12 @@ var worldTools = (tools, chosen) => tools.filter((t) => taskTool(t.name) || chos
|
|
|
1707
2162
|
function mountWorlds(node, worlds2, tools, selected, api2, go2) {
|
|
1708
2163
|
const world = worlds2.find((w) => w.id === selected), editing = selected === "new" || new URLSearchParams(location.search).has("edit");
|
|
1709
2164
|
if (selected && selected !== "new" && !world) {
|
|
1710
|
-
node.innerHTML =
|
|
2165
|
+
node.innerHTML = `<div role="alert">${stateCard("This world is unavailable.", "", '<a data-nav href="/worlds">Back to Worlds</a>', "error")}</div>`;
|
|
1711
2166
|
return;
|
|
1712
2167
|
}
|
|
1713
2168
|
if (editing) {
|
|
1714
2169
|
const chosen = world?.configuration.preset.datasets.map((d) => d.tool) ?? [new URLSearchParams(location.search).get("tool")].filter((name) => !!name && taskTool(name) && tools.some((t) => t.name === name));
|
|
1715
|
-
node.innerHTML = `<form id="catalog-world-editor" class="world-editor-page"><label>World name<input name="name" maxlength="100" value="${h(world?.name ?? "")}" required autofocus></label><h2>Tools</h2><div class="world-tool-grid">${worldTools(tools, chosen).map((t) => `<label class="world-tool ${chosen.includes(t.name) ? "selected" : ""}"><input type="checkbox" name="tools" value="${h(t.name)}" ${chosen.includes(t.name) ? "checked" : ""}>${toolLogo(t.name)}<span>${h(toolName(t.name))}</span></label>`).join("")}</div><p class="error" role="alert" id="world-error"></p><div class="actions"><button type="submit" class="primary">Save world</button><a data-nav href="${world ? "/worlds/" + encodeURIComponent(world.id) : "/worlds"}">Cancel</a></div></form>`;
|
|
2170
|
+
node.innerHTML = `<form id="catalog-world-editor" class="world-editor-page"><label>World name<input name="name" maxlength="100" value="${h(world?.name ?? "")}" required autofocus></label><h2>Tools</h2><div class="world-tool-grid">${worldTools(tools, chosen).map((t) => `<label class="world-tool ${chosen.includes(t.name) ? "selected" : ""}"><input type="checkbox" name="tools" value="${h(t.name)}" ${chosen.includes(t.name) ? "checked" : ""}>${toolLogo(t.name)}<span title="${h(toolName(t.name))}">${h(toolName(t.name))}</span></label>`).join("")}</div><p class="error" role="alert" id="world-error"></p><div class="actions"><button type="submit" class="primary">Save world</button><a data-nav href="${world ? "/worlds/" + encodeURIComponent(world.id) : "/worlds"}">Cancel</a></div></form>`;
|
|
1716
2171
|
const form = node.querySelector("form");
|
|
1717
2172
|
form.addEventListener("change", (e) => {
|
|
1718
2173
|
const input = e.target;
|
|
@@ -1734,7 +2189,7 @@ function mountWorlds(node, worlds2, tools, selected, api2, go2) {
|
|
|
1734
2189
|
node.innerHTML = `<p class="world-intro">Each trial starts with a fresh copy of this world.</p><div class="world-tool-grid">${world.configuration.preset.datasets.map((d) => `<a class="world-tool world-data-link" data-nav href="/tools/${encodeURIComponent(d.tool)}">${toolLogo(d.tool)}<strong>${h(toolName(d.tool))}</strong><span>Preview starter data \u2192</span></a>`).join("")}</div>`;
|
|
1735
2190
|
return;
|
|
1736
2191
|
}
|
|
1737
|
-
node.innerHTML = worlds2
|
|
2192
|
+
node.innerHTML = worldsTable(worlds2);
|
|
1738
2193
|
}
|
|
1739
2194
|
|
|
1740
2195
|
// frontend/src/test-flow.ts
|
|
@@ -2094,10 +2549,10 @@ function mountGroupFlow(node, options) {
|
|
|
2094
2549
|
draft.pendingSubmission = request;
|
|
2095
2550
|
remember();
|
|
2096
2551
|
}
|
|
2097
|
-
const
|
|
2552
|
+
const result = await options.api("/playgrounds/groups", draft.pendingSubmission);
|
|
2098
2553
|
sessionStorage.removeItem(key);
|
|
2099
2554
|
accepted = true;
|
|
2100
|
-
options.go("/playgrounds/" + encodeURIComponent(
|
|
2555
|
+
options.go("/playgrounds/" + encodeURIComponent(result.id));
|
|
2101
2556
|
} catch (e) {
|
|
2102
2557
|
if (groupSubmissionWasRejected(e)) {
|
|
2103
2558
|
delete draft.pendingSubmission;
|
|
@@ -2228,18 +2683,65 @@ function connectionText(info, tool) {
|
|
|
2228
2683
|
return keys.filter((key) => info.env[key] !== void 0).map((key) => `${key}=${JSON.stringify(info.env[key])}`).join("\n") + "\n";
|
|
2229
2684
|
}
|
|
2230
2685
|
|
|
2686
|
+
// frontend/src/tools-page.ts
|
|
2687
|
+
function filteredTools(tools, filters = {}) {
|
|
2688
|
+
const query = (filters.q ?? "").trim().toLowerCase();
|
|
2689
|
+
return [...tools].sort((a, b) => (toolOrder.indexOf(a.name) + 99) % 99 - (toolOrder.indexOf(b.name) + 99) % 99).filter((t) => (!filters.category || (toolCategory[t.name] ?? "Tool") === filters.category) && [t.name, toolName(t.name), toolCategory[t.name] ?? "Tool", t.descriptor?.description ?? toolDescription(t.name)].join(" ").toLowerCase().includes(query));
|
|
2690
|
+
}
|
|
2691
|
+
function toolTiles(tools, filters = {}) {
|
|
2692
|
+
const matches = filteredTools(tools, filters);
|
|
2693
|
+
if (!matches.length) return stateCard("No tools match", "Try another name, category or description.", '<a class="button-link" data-tool-clear href="/tools">Clear</a>');
|
|
2694
|
+
return `<div class="tools-grid">${matches.map((t) => {
|
|
2695
|
+
const d = t.descriptor ?? {}, endpoints = (t.coverage ?? []).length;
|
|
2696
|
+
const version = String(d.version ?? "").replace(/\bsubset\b/gi, "").trim();
|
|
2697
|
+
const api2 = version && !/[A-Za-z]{3,}/.test(version) ? `API ${version}` : version;
|
|
2698
|
+
const description = d.description ?? toolDescription(t.name);
|
|
2699
|
+
return `<a class="tool-card" data-nav href="/tools/${encodeURIComponent(t.name)}"><div class="tool-card-head">${toolLogo(t.name)}<strong title="${h(toolName(t.name))}">${h(toolName(t.name))}</strong></div><div class="tool-card-foot" title="${h([toolCategory[t.name] ?? "Tool", `${endpoints} endpoints`, api2].filter(Boolean).join(" \xB7 "))}"><span>${h(toolCategory[t.name] ?? "Tool")}</span><span>${endpoints} endpoint${endpoints === 1 ? "" : "s"}</span>${api2 ? `<span>${h(api2)}</span>` : ""}</div><p title="${h(description)}">${h(description)}</p></a>`;
|
|
2700
|
+
}).join("")}</div>`;
|
|
2701
|
+
}
|
|
2702
|
+
function toolsCatalog(tools, filters = {}) {
|
|
2703
|
+
const categories = [...new Set(tools.map((t) => toolCategory[t.name] ?? "Tool"))];
|
|
2704
|
+
return `<section class="tools-catalog" aria-label="Tool catalog"><label class="tools-search"><span class="sr-only">Search tools</span><input id="tools-search" type="search" placeholder="Search name, category or description" value="${h(filters.q ?? "")}"></label><div class="tool-categories" role="group" aria-label="Tool category">${["", ...categories].map((category) => {
|
|
2705
|
+
const count = category ? tools.filter((t) => (toolCategory[t.name] ?? "Tool") === category).length : tools.length;
|
|
2706
|
+
return `<button type="button" data-tool-category="${h(category)}" aria-pressed="${(filters.category ?? "") === category}">${h(category || "All")} <span>${count}</span></button>`;
|
|
2707
|
+
}).join("")}</div><p class="tools-result-count" role="status">${filteredTools(tools, filters).length} of ${tools.length} tools</p><div id="tool-tiles">${toolTiles(tools, filters)}</div></section>`;
|
|
2708
|
+
}
|
|
2709
|
+
function toolEndpoints(coverage) {
|
|
2710
|
+
if (!coverage.length) return "";
|
|
2711
|
+
const methods = ["GET", "POST", "PUT", "PATCH", "DELETE"];
|
|
2712
|
+
const sorted = [...coverage].sort((a, b) => String(a.path).localeCompare(String(b.path)) || methods.indexOf(a.method) - methods.indexOf(b.method));
|
|
2713
|
+
return `<section class="tool-aside-section"><h2>Endpoints <span>${coverage.length}</span></h2>${coverage.length > 12 ? '<label class="endpoint-search"><span class="sr-only">Filter endpoints</span><input id="endpoint-filter" type="search" placeholder="Filter method or path"></label>' : ""}<div class="catalog-scroll endpoint-scroll" tabindex="0" aria-label="Endpoints"><table class="catalog-table endpoint-table"><thead><tr><th scope="col">Method</th><th scope="col">Path</th></tr></thead><tbody>${sorted.map((c) => `<tr title="${h(`${c.method} ${c.path}${c.notes ? ` \u2014 ${c.notes}` : ""}`)}"><td><code class="method-pill">${h(c.method)}</code></td><td><code>${h(c.path)}</code></td></tr>`).join("")}</tbody></table></div><p id="endpoint-empty" class="hint" role="status" hidden>No endpoints match.</p></section>`;
|
|
2714
|
+
}
|
|
2715
|
+
function toolConnect(name) {
|
|
2716
|
+
const env = connectionFields[name] ?? [];
|
|
2717
|
+
return env.length ? `<section class="tool-aside-section"><h2>Connect your agent</h2><p>Your agent reads these at start; point your client at the URL instead of the real service.</p><div class="catalog-scroll" tabindex="0" aria-label="Connection variables"><table class="catalog-table connect-table"><thead><tr><th scope="col">Variable</th><th scope="col">Holds</th></tr></thead><tbody>${env.map((key) => `<tr><td><div class="catalog-copy"><code>${h(key)}</code>${copyButton(key, "Copy variable name")}</div></td><td>${h(connectionLabel(key))}</td></tr>`).join("")}</tbody></table></div>${connectionNote[name] ? `<p class="hint">${h(connectionNote[name])}</p>` : ""}</section>` : "";
|
|
2718
|
+
}
|
|
2719
|
+
function agentList(agents, instead) {
|
|
2720
|
+
if (!agents.length) return stateCard("No agents", instead ? "" : "Choose your local project to get started.", instead ?? copyCommand("ancha init") + button("Connect agent", "add-agent", "", "primary"));
|
|
2721
|
+
const model = agents.some((a) => a.provider?.model);
|
|
2722
|
+
return `<div class="catalog-scroll agents-scroll" tabindex="0" aria-label="Agents"><table class="catalog-table agents-table"><thead><tr><th scope="col">Agent</th><th scope="col">Folder</th><th scope="col">Start command / config</th>${model ? '<th scope="col">Model</th>' : ""}</tr></thead><tbody>${agents.map((a) => `<tr><td><a data-nav class="catalog-agent-name" href="/agents/${encodeURIComponent(a.id)}" title="${h(a.name)}">${h(a.name)}</a><div class="catalog-copy agent-ref"><code title="${h(a.id)}">${h(shortId(a.id))}</code>${copyButton(a.id, "Copy agent id")}</div></td><td><div class="catalog-copy"><code class="catalog-cut" title="${h(a.cwd ?? "")}">${h(a.cwd ?? "")}</code>${a.cwd ? copyButton(a.cwd, "Copy folder") : ""}</div></td><td><code class="catalog-cut" title="${h(a.command ?? a.configPath ?? "")}">${h(a.command ?? a.configPath ?? "")}</code></td>${model ? `<td><span class="catalog-cut" title="${h(a.provider?.model ?? "")}">${h(a.provider?.model ?? "")}</span></td>` : ""}</tr>`).join("")}</tbody></table></div>`;
|
|
2723
|
+
}
|
|
2724
|
+
function settingsPage(boot2) {
|
|
2725
|
+
if (!boot2.hosted) {
|
|
2726
|
+
const workspace = String(boot2.workspace ?? "");
|
|
2727
|
+
return `<section class="settings-page"><h2>Local workspace</h2>${facts([{ label: "Workspace", value: workspace, mono: true, html: `${h(workspace)}${copyButton(workspace, "Copy workspace path")}` }], "Workspace settings")}<p class="muted">Agents, worlds, tests and results are saved here.</p></section>`;
|
|
2728
|
+
}
|
|
2729
|
+
const hosted = boot2.hosted, items = [];
|
|
2730
|
+
if (hosted.tier) {
|
|
2731
|
+
const free = hosted.execution === false, value = free ? "Free" : "Hosted runs";
|
|
2732
|
+
items.push({ label: "This workspace", value, html: `${value} \xB7 <a href="/account#hosted">${free ? "Request hosted runs" : "Machine time"}</a>` });
|
|
2733
|
+
}
|
|
2734
|
+
if (hosted.console) items.push({ label: "Console", value: String(hosted.console), html: `<a href="${h(hosted.console)}">${h(hosted.console)}</a>` });
|
|
2735
|
+
if (hosted.worldServer) items.push({ label: "World server", value: String(hosted.worldServer), mono: true, html: `${h(hosted.worldServer)}${copyButton(String(hosted.worldServer), "Copy world server")}` });
|
|
2736
|
+
return `<section class="settings-page"><h2>Hosted workspace</h2>${facts(items, "Workspace settings")}<p class="muted">For CI, set <code>ANCHA_SERVER_URL</code> to the world server and <code>ANCHA_API_KEY</code> to a key from <a href="/account">Account settings</a>. On your computer, <code>ancha login</code> sets both.</p></section>`;
|
|
2737
|
+
}
|
|
2738
|
+
|
|
2231
2739
|
// frontend/src/journey.ts
|
|
2232
2740
|
function connectionStatus(verification) {
|
|
2233
2741
|
if (!verification) return badge("Not checked");
|
|
2234
2742
|
const status = verification.status;
|
|
2235
2743
|
return badge(status === "connected" || status === "verified" ? "Connected" : status === "running" ? "Connecting" : status === "failed" ? "Connection failed" : status === "stale" ? "Needs recheck" : "Not checked", status === "connected" || status === "verified" ? "good" : status === "failed" ? "bad" : "warn");
|
|
2236
2744
|
}
|
|
2237
|
-
function agentList(agents, instead) {
|
|
2238
|
-
return agents.length ? `<div class="agent-card-grid">${agents.map((a) => {
|
|
2239
|
-
const initials = String(a.name).trim().split(/\s+/).slice(0, 2).map((word) => Array.from(word)[0] ?? "").join("").toUpperCase();
|
|
2240
|
-
return `<a class="agent-card" data-nav href="/agents/${encodeURIComponent(a.id)}"><span class="agent-monogram" aria-hidden="true">${h(initials)}</span><h2>${h(a.name)}</h2>${a.provider?.model ? `<p class="agent-card-model">${h(a.provider.model)}</p>` : ""}<span class="agent-card-footer">Open agent <span aria-hidden="true">\u2197</span></span></a>`;
|
|
2241
|
-
}).join("")}</div>` : `<section class="empty first-use agent-empty"><h2>No agents yet</h2>${instead ?? `<p>Choose your local project to get started.</p>${button("Connect agent", "add-agent", "", "primary")}`}</section>`;
|
|
2242
|
-
}
|
|
2243
2745
|
function scenarioList(scenes) {
|
|
2244
2746
|
return `<div class="scenario-list">${scenes.map((s) => `<a class="scenario-row" href="/scenarios/${encodeURIComponent(s.key)}" data-nav><div><h2>${h(title(s.scene))}</h2><p>${h(s.scene.twins.map(toolName).join(" \xB7 "))}</p></div>${s.origin === "draft" ? badge("Draft \xB7 unverified") : ""}<span aria-hidden="true">\u2192</span></a>`).join("")}</div>`;
|
|
2245
2747
|
}
|
|
@@ -2264,11 +2766,11 @@ function comparisonSetup(runId, runs) {
|
|
|
2264
2766
|
if (!baselines.length) return '<div class="empty compact"><h3>No baseline yet</h3><p>Complete another run with the same scenarios and test data to compare results.</p></div>';
|
|
2265
2767
|
return `<p class="hint">Choose a completed run with matching scenarios and test data.</p><form id="compare-form"><input type="hidden" name="current" value="${h(runId)}"><label>Baseline<select name="baseline" required>${baselines.map((r) => `<option value="${h(r.runId)}">${h(r.metadata?.label ?? "CLI test")} \xB7 ${h(r.runId)}</option>`).join("")}</select></label><button class="primary">Compare</button></form>`;
|
|
2266
2768
|
}
|
|
2267
|
-
function comparisonResults(
|
|
2769
|
+
function comparisonResults(result, labels) {
|
|
2268
2770
|
const percent2 = (rate) => `${(rate * 100).toLocaleString("en-US", { maximumFractionDigits: 1 })}%`;
|
|
2269
2771
|
const change = (delta) => delta === 0 ? "No change" : Math.abs(delta * 100) < 0.1 ? `${delta > 0 ? "Increase" : "Decrease"} under 0.1 percentage points` : `${delta > 0 ? "+" : "\u2212"}${Math.abs(delta * 100).toLocaleString("en-US", { maximumFractionDigits: 1 })} percentage points`;
|
|
2270
2772
|
const attempts = (count) => `${count} ${count === 1 ? "attempt" : "attempts"}`;
|
|
2271
|
-
return `<p>${
|
|
2773
|
+
return `<p>${result.regressed ? "Pass rate decreased in one or more scenarios." : "No decrease in pass rate."}</p><div class="table-wrap comparison-table"><table><thead><tr><th scope="col">Scenario</th><th scope="col">Before</th><th scope="col">After</th><th scope="col">Change</th></tr></thead><tbody>${result.scenes.map((s, index) => `<tr><th scope="row">${h(labels[s.sceneId] ?? `Scenario ${index + 1}`)}</th><td><strong>${percent2(s.before)}</strong><span class="comparison-attempts">${attempts(s.beforeTrials)}</span></td><td><strong>${percent2(s.after)}</strong><span class="comparison-attempts">${attempts(s.afterTrials)}</span></td><td>${badge(change(s.delta), s.delta > 0 ? "good" : s.delta < 0 ? "bad" : "")}</td></tr>`).join("")}</tbody></table></div><p class="hint">Observed pass rates; no claim of statistical significance.</p>${details("Comparison details", result)}`;
|
|
2272
2774
|
}
|
|
2273
2775
|
function dataSelection(item) {
|
|
2274
2776
|
if (!item) return "";
|
|
@@ -2422,13 +2924,13 @@ async function api(path2, data, signal, background = false) {
|
|
|
2422
2924
|
});
|
|
2423
2925
|
connected = true;
|
|
2424
2926
|
noteConnection(true);
|
|
2425
|
-
const
|
|
2927
|
+
const result = await res.json();
|
|
2426
2928
|
if (!res.ok) {
|
|
2427
|
-
const refusal =
|
|
2428
|
-
const message = refusal ? [refusal.message, refusal.hint].map(sentence2).filter(Boolean).join(" ") :
|
|
2429
|
-
throw Object.assign(new Error(message), { status: res.status, code: refusal?.code ??
|
|
2929
|
+
const refusal = result.error && typeof result.error === "object" ? result.error : void 0;
|
|
2930
|
+
const message = refusal ? [refusal.message, refusal.hint].map(sentence2).filter(Boolean).join(" ") : result.error ?? `Request failed (${res.status})`;
|
|
2931
|
+
throw Object.assign(new Error(message), { status: res.status, code: refusal?.code ?? result.code, run: result.run });
|
|
2430
2932
|
}
|
|
2431
|
-
return
|
|
2933
|
+
return result;
|
|
2432
2934
|
}
|
|
2433
2935
|
var sentence2 = (text2) => {
|
|
2434
2936
|
const t = String(text2 ?? "").trim();
|
|
@@ -2469,13 +2971,13 @@ function waitForWorkspace() {
|
|
|
2469
2971
|
}
|
|
2470
2972
|
async function startWorkspace() {
|
|
2471
2973
|
const res = await fetch("/workspace/start", { method: "POST" }).catch(() => void 0);
|
|
2472
|
-
const
|
|
2473
|
-
if (!res || !res.ok &&
|
|
2474
|
-
boot = { ...boot, machine: { ...boot.machine, state:
|
|
2974
|
+
const result = await res?.json().catch(() => ({})) ?? {};
|
|
2975
|
+
if (!res || !res.ok && result.state !== "capped") throw new Error(result.error ?? "We could not start your workspace. Try again in a minute.");
|
|
2976
|
+
boot = { ...boot, machine: { ...boot.machine, state: result.state === "capped" ? "capped" : "starting", ...result.state === "capped" && { canStart: false } } };
|
|
2475
2977
|
await load();
|
|
2476
|
-
if (
|
|
2978
|
+
if (result.state !== "capped") waitForWorkspace();
|
|
2477
2979
|
}
|
|
2478
|
-
var betaNote = () => '<p class="beta-note">
|
|
2980
|
+
var betaNote = () => '<p class="beta-note">Connect with <code>ancha doctor --on cloud</code>, then <code>ancha run --on cloud</code>. To run your own agent on the workspace machine, <a href="/account#hosted">request higher limits in Settings</a>.</p>';
|
|
2479
2981
|
var poll = (path2) => api(path2, void 0, void 0, true);
|
|
2480
2982
|
function path() {
|
|
2481
2983
|
return location.pathname.split("/").filter(Boolean).map(decodeURIComponent);
|
|
@@ -2537,13 +3039,13 @@ function shell(section, content) {
|
|
|
2537
3039
|
}
|
|
2538
3040
|
function folderScenes(scenes) {
|
|
2539
3041
|
if (!scenes.length) return "";
|
|
2540
|
-
return `<section class="folder-scenes" aria-labelledby="folder-scenes-title"><div class="section-title"><div><h2 id="folder-scenes-title">Scenes in this folder</h2><p class="muted">Open one to see its starting data before any run.</p></div></div><div class="
|
|
3042
|
+
return `<section class="folder-scenes" aria-labelledby="folder-scenes-title"><div class="section-title"><div><h2 id="folder-scenes-title">Scenes in this folder</h2><p class="muted">Open one to see its starting data before any run.</p></div></div><div class="worlds-scroll" role="region" aria-label="Scenes in this folder" tabindex="0"><table class="worlds-table scenes-table"><thead><tr><th scope="col">Scene</th><th scope="col">Tools</th><th scope="col">Path</th></tr></thead><tbody>${scenes.map((scene) => `<tr><td><a class="worlds-name" href="/worlds?scene=${enc2(String(scene.key))}" data-nav title="${h(String(scene.title || scene.id))}">${h(String(scene.title || scene.id))}</a></td><td>${worldToolIcons(scene)}</td><td><code class="worlds-path" title="${h(String(scene.path))}">${h(String(scene.path))}</code></td></tr>`).join("")}</tbody></table></div></section>`;
|
|
2541
3043
|
}
|
|
2542
3044
|
function worldToolIcons(world) {
|
|
2543
|
-
|
|
2544
|
-
return `<div class="world-tool-icons" role="group" aria-label="Tools: ${h(tools.map(toolName).join(", "))}">${tools.map((tool) => `<span title="${h(toolName(tool))}" role="img" aria-label="${h(toolName(tool))}">${toolLogo(tool)}</span>`).join("")}</div>`;
|
|
3045
|
+
return worldToolsCell(world);
|
|
2545
3046
|
}
|
|
2546
3047
|
var head = (heading2, actions = "", meta = "") => `<header class="page-head"><div><h1>${h(heading2)}</h1>${meta ? `<p class="page-meta">${h(meta)}</p>` : ""}</div>${actions ? `<div class="actions">${actions}</div>` : ""}</header>`;
|
|
3048
|
+
var catalogHead = (heading2, actions = "", meta = "") => head(heading2, actions, meta).replace("page-head", "page-head catalog-head");
|
|
2547
3049
|
var toolTabs = (selected, mode = "tool", enabled = ["slack", "datadog", "pagerduty", "github"]) => `<div class="tabs tools" role="group" aria-label="Tool views">${enabled.map((id) => button(toolName(id), mode, id, selected === id ? "active" : "")).join("")}</div>`;
|
|
2548
3050
|
async function refreshCatalog() {
|
|
2549
3051
|
catalog = await api("/scenarios");
|
|
@@ -2609,9 +3111,10 @@ async function load() {
|
|
|
2609
3111
|
renderAgents(p[1]);
|
|
2610
3112
|
if (p[1]) pollAgent(p[1], thisGeneration);
|
|
2611
3113
|
} else if (section === "help" || section === "settings") {
|
|
2612
|
-
shell(section,
|
|
3114
|
+
shell(section, catalogHead(section === "help" ? "Help" : "Settings") + (section === "help" ? helpPage() : settingsPage(boot)));
|
|
2613
3115
|
} else if (section === "worlds") {
|
|
2614
3116
|
const q = new URLSearchParams(location.search), sceneKey = p[1] ? null : q.get("scene"), revision = q.get("revision");
|
|
3117
|
+
if (!document.querySelector("#worlds-page, #world-workspace, .world-data-page")) shell("worlds", head("Worlds") + '<div id="worlds-page" class="worlds-loading">' + skeletonRows(5) + "</div>");
|
|
2615
3118
|
if (!viewMode2() && (sceneKey !== null || !!p[1] && p[1] !== "new" && q.has("data"))) {
|
|
2616
3119
|
const source = sceneKey !== null ? `/scenarios/data?key=${enc2(sceneKey)}` : `/worlds/${enc2(p[1])}/data${revision ? `?revision=${enc2(revision)}` : ""}`;
|
|
2617
3120
|
const data = worldData?.source === source && Date.now() - worldData.at < 6e4 ? worldData.data : await api(source);
|
|
@@ -2622,10 +3125,10 @@ async function load() {
|
|
|
2622
3125
|
else shell("worlds", worldDataPage(String(data.world?.name ?? "World"), `Revision ${data.world?.revision}`, { href: `/worlds/${enc2(p[1])}`, label: String(data.world?.name ?? "World") }, data, `/worlds/${enc2(p[1])}?data=1${revision ? `&revision=${enc2(revision)}` : ""}`, q));
|
|
2623
3126
|
return;
|
|
2624
3127
|
}
|
|
2625
|
-
const [
|
|
3128
|
+
const [result, registry, definitions, folder] = await Promise.all([api("/worlds"), api("/agents"), api("/playground-tests"), !p[1] && !viewMode2() ? api("/scenarios/folder").catch(() => ({ scenes: [] })) : Promise.resolve({ scenes: [] })]);
|
|
2626
3129
|
if (thisGeneration !== generation) return;
|
|
2627
|
-
worldsAnswer =
|
|
2628
|
-
worlds =
|
|
3130
|
+
worldsAnswer = result;
|
|
3131
|
+
worlds = result.worlds ?? [];
|
|
2629
3132
|
agentCatalog = registry.agents ?? [];
|
|
2630
3133
|
savedPlaygroundTests = definitions.tests ?? [];
|
|
2631
3134
|
for (const world of worlds) {
|
|
@@ -2637,7 +3140,7 @@ async function load() {
|
|
|
2637
3140
|
if (viewMode2()) {
|
|
2638
3141
|
current = {};
|
|
2639
3142
|
shell("worlds", head("Worlds") + '<div id="worlds-page"></div>');
|
|
2640
|
-
document.querySelector("#worlds-page").innerHTML = snapshotNote(worldsAnswer) + (worldsAnswer.snapshotAt
|
|
3143
|
+
document.querySelector("#worlds-page").innerHTML = snapshotNote(worldsAnswer) + (worldsAnswer.snapshotAt ? worldsTable(worlds, worldTaskCounts, false) : "");
|
|
2641
3144
|
} else if (selected && !editing) {
|
|
2642
3145
|
current = { world: selected };
|
|
2643
3146
|
shell("worlds", '<div id="world-workspace"></div>');
|
|
@@ -2652,7 +3155,7 @@ async function load() {
|
|
|
2652
3155
|
const ownAgents = agentCatalog.filter((a) => !/(^|\/)sample-agent\/?$/.test(String(a.cwd ?? "")));
|
|
2653
3156
|
const sampleRun = !p[1] && !ownAgents.length ? ((await api("/playgrounds")).runs ?? []).slice().sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))[0] : void 0;
|
|
2654
3157
|
if (thisGeneration !== generation) return;
|
|
2655
|
-
if (!p[1]) document.querySelector("#worlds-page").innerHTML = (ownAgents.length ? "" : startCard(sampleRun?.id, Boolean(boot.hosted))) + (worlds
|
|
3158
|
+
if (!p[1]) document.querySelector("#worlds-page").innerHTML = (ownAgents.length ? "" : startCard(sampleRun?.id, Boolean(boot.hosted))) + worldsTable(worlds, worldTaskCounts) + folderScenes(folder.scenes ?? []);
|
|
2656
3159
|
else mountWorlds(document.querySelector("#worlds-page"), worlds, toolCatalog, p[1], api, go);
|
|
2657
3160
|
}
|
|
2658
3161
|
} else if (section === "tools") {
|
|
@@ -2661,8 +3164,10 @@ async function load() {
|
|
|
2661
3164
|
if (thisGeneration !== generation) return;
|
|
2662
3165
|
renderTools(p[1]);
|
|
2663
3166
|
} else if (section === "playgrounds" && p[1]) {
|
|
2664
|
-
const
|
|
2665
|
-
const [batch, worldList,
|
|
3167
|
+
const q = new URLSearchParams(location.search), asked = q.get("attempt");
|
|
3168
|
+
const [batch, worldList, askedEvidence] = await Promise.all([api(`/playgrounds/${enc2(p[1])}`), api("/worlds"), asked ? api(`/playgrounds/${enc2(p[1])}/attempts/${enc2(asked)}`) : Promise.resolve({})]);
|
|
3169
|
+
shownAttempt = asked || q.get("compare") ? void 0 : defaultAttempt(batch, q.get("task") ?? void 0)?.id;
|
|
3170
|
+
const evidence = shownAttempt ? await api(`/playgrounds/${enc2(p[1])}/attempts/${enc2(shownAttempt)}`) : askedEvidence;
|
|
2666
3171
|
current = batch;
|
|
2667
3172
|
worlds = worldList.worlds ?? [];
|
|
2668
3173
|
batchEvidence = evidence;
|
|
@@ -2670,10 +3175,11 @@ async function load() {
|
|
|
2670
3175
|
renderPlayground();
|
|
2671
3176
|
pollPlayground(p[1], thisGeneration);
|
|
2672
3177
|
} else if (section === "playgrounds") {
|
|
2673
|
-
|
|
3178
|
+
if (!runsList) shell("playgrounds", skeletonRows(8));
|
|
3179
|
+
runsList = await api("/playgrounds?include=cli");
|
|
2674
3180
|
if (thisGeneration !== generation) return;
|
|
2675
3181
|
current = {};
|
|
2676
|
-
|
|
3182
|
+
renderRunsList();
|
|
2677
3183
|
} else shell(section, notFound());
|
|
2678
3184
|
} catch (e) {
|
|
2679
3185
|
if (thisGeneration !== generation) return;
|
|
@@ -2693,17 +3199,17 @@ async function suggestAgentCommand(form) {
|
|
|
2693
3199
|
if (!folder?.value.trim() || !command || command.value.trim()) return;
|
|
2694
3200
|
const path2 = folder.value;
|
|
2695
3201
|
try {
|
|
2696
|
-
const
|
|
2697
|
-
if (form.isConnected && folder.value === path2 && !command.value.trim() &&
|
|
2698
|
-
command.value =
|
|
3202
|
+
const result = await api("/agents/detect", { cwd: path2 });
|
|
3203
|
+
if (form.isConnected && folder.value === path2 && !command.value.trim() && result.suggestions?.command) {
|
|
3204
|
+
command.value = result.suggestions.command;
|
|
2699
3205
|
let note = form.querySelector(".command-suggestion");
|
|
2700
3206
|
if (!note) {
|
|
2701
3207
|
note = document.createElement("p");
|
|
2702
3208
|
note.className = "hint command-suggestion";
|
|
2703
3209
|
command.closest("label")?.after(note);
|
|
2704
3210
|
}
|
|
2705
|
-
note.textContent = `${
|
|
2706
|
-
for (const [name, value] of Object.entries(connectDefaults(
|
|
3211
|
+
note.textContent = `${result.language ? `Detected a ${result.language} project${result.evidence?.length ? ` from ${result.evidence.join(", ")}` : ""}. ` : "Suggested from your project. "}Confirm this is how you start the agent.`;
|
|
3212
|
+
for (const [name, value] of Object.entries(connectDefaults(result))) {
|
|
2707
3213
|
const select = form.querySelector(`select[name=${name}]`);
|
|
2708
3214
|
if (select && !select.value) {
|
|
2709
3215
|
select.value = value;
|
|
@@ -2786,7 +3292,7 @@ function providerValue(data) {
|
|
|
2786
3292
|
function renderAgents(id) {
|
|
2787
3293
|
renderedLocation = new URL(location.href);
|
|
2788
3294
|
if (!id) {
|
|
2789
|
-
const listHead = (actions2 = "") => boot.hosted ? `<a class="back" href="/agents">\u2190 Agents</a>${
|
|
3295
|
+
const listHead = (actions2 = "") => boot.hosted ? `<a class="back" href="/agents">\u2190 Agents</a>${catalogHead("Connected agents", actions2)}` : catalogHead("Agents", actions2);
|
|
2790
3296
|
if (viewMode2()) {
|
|
2791
3297
|
shell("agents", listHead() + snapshotNote(agentsAnswer) + (agentsAnswer.snapshotAt ? agentList(agentCatalog, void 0) : ""));
|
|
2792
3298
|
return;
|
|
@@ -2817,18 +3323,19 @@ function renderAgents(id) {
|
|
|
2817
3323
|
if (!a.id) throw new Error("This agent is no longer available.");
|
|
2818
3324
|
selectedAgent = "agent:" + a.id;
|
|
2819
3325
|
const q = new URLSearchParams(location.search), page = q.get("tab") ?? "overview", base = "/agents/" + enc2(a.id);
|
|
2820
|
-
const operation = connectionOperation, connecting = operation?.state === "connecting", queuedConnect = operation?.state === "queued"
|
|
2821
|
-
const status =
|
|
3326
|
+
const operation = connectionOperation, connecting = operation?.state === "connecting", queuedConnect = operation?.state === "queued";
|
|
3327
|
+
const status = agentConnection(a, operation).label;
|
|
3328
|
+
const primary = page === "setup" ? "" : agentPrimary(a, operation);
|
|
2822
3329
|
const blocked = blockedConnect?.agentId === a.id ? blockedConnect : null;
|
|
2823
3330
|
if (blocked) blockedConnect = null;
|
|
2824
|
-
const connectionNotice = blocked ? `<
|
|
3331
|
+
const connectionNotice = blocked ? `<div role="alert">${stateCard("Connection waiting", runnerBusyHtml(blocked.message, blocked.run), "", "queued")}</div>` : connecting || queuedConnect ? `<div class="connect-progress c-state c-state-${connecting ? "running" : "queued"}" role="status"><div>${statusMark(connecting ? "running" : "queued", status)}<p>${h(operation?.message ?? (queuedConnect ? "Waiting for another connection to finish." : ""))}</p></div>${button("Cancel", "cancel-connect", operation.id)}</div>` : operation?.state === "failed" ? `<div role="alert">${stateCard("Couldn\u2019t connect", h(operation.message ?? operation.error ?? "Check your settings and try again."), navLink("Edit connection", url(base, { tab: "setup" }), "button-link"), "error")}</div>` : "";
|
|
2825
3332
|
let content = "";
|
|
2826
3333
|
if (page === "new-test") {
|
|
2827
3334
|
if (q.get("test") && !savedPlaygroundTests.some((t) => t.id === q.get("test"))) {
|
|
2828
|
-
shell("agents", navLink("\u2190 " + a.name, base, "back") + head("Test unavailable") +
|
|
3335
|
+
shell("agents", `<div class="agent-page">${navLink("\u2190 " + a.name, base, "back") + head("Test unavailable") + stateCard("This test is unavailable.", "", navLink("Back to agent", base), "error")}</div>`);
|
|
2829
3336
|
return;
|
|
2830
3337
|
}
|
|
2831
|
-
shell("agents", navLink("\u2190 " + a.name, base, "back") + head(q.get("test") ? "Edit test" : "New test")
|
|
3338
|
+
shell("agents", `<div class="agent-flow-page">${navLink("\u2190 " + a.name, base, "back") + head(q.get("test") ? "Edit test" : "New test")}<div id="test-flow"></div></div>`);
|
|
2832
3339
|
mountTestFlow(document.querySelector("#test-flow"), { agent: a, tools: toolCatalog, worlds, test: savedPlaygroundTests.find((t) => t.id === q.get("test")), api, go, preview: async (tool) => {
|
|
2833
3340
|
const data = await starterPreview(tool);
|
|
2834
3341
|
return `<div class="section-title"><h3>${h(toolName(tool))}</h3></div>` + toolView(data, tool, { baseHref: "/tools/" + enc2(tool) });
|
|
@@ -2844,17 +3351,15 @@ function renderAgents(id) {
|
|
|
2844
3351
|
const selectedTest = tests.find((t) => t.id === q.get("test"));
|
|
2845
3352
|
if (page === "test") {
|
|
2846
3353
|
if (!selectedTest) {
|
|
2847
|
-
shell("agents", head("Test unavailable"));
|
|
3354
|
+
shell("agents", `<div class="agent-page">${head("Test unavailable") + stateCard("This test is unavailable.", "", navLink("Back to agent", base), "error")}</div>`);
|
|
2848
3355
|
return;
|
|
2849
3356
|
}
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
} else content = connectionNotice + `<section><div class="section-title"><h2>Tasks</h2></div>${tests.length ? agentWorldTasks(tests, worlds, (id2) => savedTestActions(id2, "Run tasks")) : '<p class="quiet-empty"><a data-nav href="/worlds">Choose a world to add tasks.</a></p>'}</section>${playgroundErrors.map((e) => `<p class="error">${h(e.message)}</p>`).join("")}<p id="page-form-error" class="error" role="alert"></p>`;
|
|
3357
|
+
content = testCard(selectedTest, worlds.find((w) => w.id === selectedTest.worldId), base, savedTestActions(selectedTest.id) + navLink("Edit", url(base, { tab: "new-test", test: selectedTest.id })) + button("Archive", "archive-test", selectedTest.id, "link"), true) + `<div id="agent-recent-runs">${agentRecentRuns(playgroundRuns, a, savedTestActions(selectedTest.id), { testId: selectedTest.id })}</div>`;
|
|
3358
|
+
} else content = connectionNotice + `<section><div class="section-title"><h2>Tasks</h2></div>${tests.length ? agentWorldTasks(tests, worlds, (id2) => savedTestActions(id2, "Run tasks")) : stateCard("No tasks", "Choose a world to add tasks.", '<a data-nav href="/worlds">Choose a world</a>')}</section><div id="agent-recent-runs">${agentRecentRuns(playgroundRuns, a, "")}</div>${playgroundErrors.map((e) => `<div role="alert">${stateCard("Run could not be read", h(e.message), `<a class="button-link" href="${h(url(base, { tab: page }))}">Retry</a>`, "error")}</div>`).join("")}<p id="page-form-error" class="error" role="alert"></p>`;
|
|
2853
3359
|
}
|
|
2854
|
-
const primary = page === "setup" || connecting || queuedConnect ? "" : ready ? button("Add tasks", "add-tasks", a.id, "primary") : ownRunsOff() ? "" : navLink("Connect agent", url(base, { tab: "setup" }), "button-link primary");
|
|
2855
3360
|
const connectionTone = operation?.state === "failed" ? "failed" : operation?.stale ? "stale" : connecting || queuedConnect ? "connecting" : operation?.state === "cancelled" ? "cancelled" : "";
|
|
2856
3361
|
const settingsControl = page === "setup" ? navLink("\u2190 Overview", base, "button-link") : `<a data-nav class="agent-settings-control" href="${h(url(base, { tab: "setup" }))}" title="${h("Connection settings \xB7 " + status)}" aria-label="${h("Connection settings \xB7 " + status)}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 3-.5 2-1.8 1-2-.6-2.2 3.8L4 10.7v2.1l-1.5 1.5 2.2 3.8 2-.6 1.8 1L9 21h4.4l.5-2.5 1.8-1 2 .6 2.2-3.8-1.5-1.5v-2.1l1.5-1.5-2.2-3.8-2 .6-1.8-1L13.4 3Z"/><circle cx="11.2" cy="12" r="3"/></svg>${connectionTone ? `<span class="agent-connection-dot ${connectionTone}" aria-hidden="true"></span>` : ""}</a>`;
|
|
2857
|
-
shell("agents", (page === "test" ? navLink("\u2190 " + a.name, base, "back") : agentsBack()) + head(page === "test" ? savedPlaygroundTests.find((t) => t.id === q.get("test"))?.name ?? a.name : a.name, page === "test" ? "" : primary + settingsControl) + content);
|
|
3362
|
+
shell("agents", `<div class="agent-page">${(page === "test" ? navLink("\u2190 " + a.name, base, "back") : agentsBack()) + head(page === "test" ? savedPlaygroundTests.find((t) => t.id === q.get("test"))?.name ?? a.name : a.name, page === "test" ? "" : primary + settingsControl) + (page === "test" ? "" : agentFacts(a, operation)) + content}</div>`);
|
|
2858
3363
|
}
|
|
2859
3364
|
function retainReadingPosition(render) {
|
|
2860
3365
|
const scrolls = [...document.querySelectorAll(".aw-attempt-list,.world-nav")].map((el) => ({ selector: el.classList.contains("aw-attempt-list") ? ".aw-attempt-list" : ".world-nav", top: el.scrollTop, left: el.scrollLeft }));
|
|
@@ -2871,6 +3376,18 @@ function retainReadingPosition(render) {
|
|
|
2871
3376
|
}
|
|
2872
3377
|
window.scrollTo({ top: y });
|
|
2873
3378
|
}
|
|
3379
|
+
function agentPrimary(a, operation) {
|
|
3380
|
+
if (operation?.state === "connecting" || operation?.state === "queued") return "";
|
|
3381
|
+
if (a.execution?.mode === "container" && a.taskInput) return button("Add tasks", "add-tasks", a.id, "primary");
|
|
3382
|
+
return ownRunsOff() ? "" : navLink("Connect agent", url("/agents/" + enc2(a.id), { tab: "setup" }), "button-link primary");
|
|
3383
|
+
}
|
|
3384
|
+
function refreshAgentRuns() {
|
|
3385
|
+
const area = document.querySelector("#agent-recent-runs");
|
|
3386
|
+
if (!area) return;
|
|
3387
|
+
const a = current.agent ?? current, q = new URLSearchParams(location.search);
|
|
3388
|
+
const testId = q.get("tab") === "test" ? q.get("test") ?? void 0 : void 0;
|
|
3389
|
+
area.innerHTML = agentRecentRuns(playgroundRuns, a, testId ? savedTestActions(testId) : "", { testId });
|
|
3390
|
+
}
|
|
2874
3391
|
function pollAgent(id, version) {
|
|
2875
3392
|
const waiting = (state) => state === "connecting" || state === "queued";
|
|
2876
3393
|
if (version !== generation || !playgroundRuns.some((r) => !terminal(r.status)) && !waiting(connectionOperation?.state)) return;
|
|
@@ -2887,12 +3404,10 @@ function pollAgent(id, version) {
|
|
|
2887
3404
|
const text2 = document.querySelector(".connect-progress p");
|
|
2888
3405
|
if (text2) text2.textContent = op.message ?? "";
|
|
2889
3406
|
}
|
|
2890
|
-
const
|
|
3407
|
+
const result = await poll(`/playgrounds?agentId=${enc2(id)}`);
|
|
2891
3408
|
if (version !== generation) return;
|
|
2892
|
-
playgroundRuns =
|
|
2893
|
-
|
|
2894
|
-
const active = playgroundRuns.filter((r) => !terminal(r.status)), area = document.querySelector("#agent-active-runs");
|
|
2895
|
-
if (area) area.innerHTML = active.length ? `<h2>Active runs</h2>${batchHistory(active)}` : "";
|
|
3409
|
+
playgroundRuns = result.runs ?? [];
|
|
3410
|
+
refreshAgentRuns();
|
|
2896
3411
|
pollAgent(id, version);
|
|
2897
3412
|
} catch {
|
|
2898
3413
|
if (version !== generation) return;
|
|
@@ -2902,23 +3417,37 @@ function pollAgent(id, version) {
|
|
|
2902
3417
|
}
|
|
2903
3418
|
}, 2e3);
|
|
2904
3419
|
}
|
|
3420
|
+
var runsList;
|
|
3421
|
+
var searchTimer;
|
|
3422
|
+
var shownAttempt;
|
|
3423
|
+
function renderRunsList() {
|
|
3424
|
+
const q = new URLSearchParams(location.search), get = (key) => q.get(key) ?? void 0;
|
|
3425
|
+
shell("playgrounds", runsPage(runsList?.runs ?? [], { q: get("q"), range: get("range"), agent: get("agent"), result: get("result"), where: get("where"), commit: get("commit"), source: get("source"), target: get("target"), limit: Number(q.get("limit")) || void 0 }, boot.hosted || viewMode2() ? { emptyHtml: "Runs from <code>ancha run --on cloud</code>, from CI and the results <code>ancha run --upload</code> sends from your computer land here. Run your first test in the cloud:" } : {}));
|
|
3426
|
+
}
|
|
3427
|
+
function runFilterUrl(form) {
|
|
3428
|
+
const params = new URLSearchParams();
|
|
3429
|
+
for (const [key, value] of new FormData(form)) if (value) params.set(key, String(value));
|
|
3430
|
+
return "/playgrounds" + (params.size ? "?" + params : "");
|
|
3431
|
+
}
|
|
2905
3432
|
function renderPlayground() {
|
|
2906
3433
|
renderedLocation = new URL(location.href);
|
|
2907
|
-
const batch = current, q = new URLSearchParams(location.search), selected = q.get("attempt"), attempt = (batch.attempts ?? []).find((a) => a.id === selected), base = "/playgrounds/" + enc2(batch.id);
|
|
3434
|
+
const batch = current, q = new URLSearchParams(location.search), selected = q.get("attempt") ?? shownAttempt, attempt = (batch.attempts ?? []).find((a) => a.id === selected), base = "/playgrounds/" + enc2(batch.id);
|
|
2908
3435
|
const actions = readOnlyRun(batch) ? batch.origin?.stored ? button("Delete run", "delete-stored-run", batch.id, "link") : "" : !terminal(batch.status) ? button("Stop", "stop-playground", batch.id) : rerunAction(batch.id);
|
|
2909
3436
|
if (selected && !attempt) throw new Error("This attempt is not available.");
|
|
2910
3437
|
if (q.get("compare")) {
|
|
2911
3438
|
const back = q.get("task") ? url(base, { task: q.get("task") }) : base;
|
|
2912
3439
|
shell("playgrounds", head("Compare attempts", navLink("Back", back, "button-link")) + '<div id="comparison-body" role="status">Loading comparison\u2026</div>');
|
|
2913
3440
|
const version = generation;
|
|
2914
|
-
void api(`/playgrounds/${enc2(batch.id)}/compare?left=${enc2(q.get("compare"))}&right=${enc2(q.get("with") ?? "")}`).then((
|
|
2915
|
-
if (version === generation) document.querySelector("#comparison-body").innerHTML = renderManagedComparison(
|
|
3441
|
+
void api(`/playgrounds/${enc2(batch.id)}/compare?left=${enc2(q.get("compare"))}&right=${enc2(q.get("with") ?? "")}`).then((result) => {
|
|
3442
|
+
if (version === generation) document.querySelector("#comparison-body").innerHTML = renderManagedComparison(result);
|
|
2916
3443
|
}).catch((e) => notify(String(e), true));
|
|
2917
3444
|
return;
|
|
2918
3445
|
}
|
|
2919
3446
|
shell("playgrounds", attempt ? renderAttemptWorkspace(batch, attempt, batchEvidence, { view: q.get("view") ?? void 0, tool: q.get("tool") ?? void 0, actionsHtml: actions, query: Object.fromEntries(q) }) : renderRunOverview(batch, actions, { task: q.get("task") ?? void 0 }));
|
|
2920
3447
|
const focus = q.get("focus");
|
|
2921
3448
|
if (attempt && focus) document.getElementById(entryAnchor(focus))?.scrollIntoView({ block: "center" });
|
|
3449
|
+
const call = q.get("call");
|
|
3450
|
+
if (attempt && call) document.getElementById(`call-${call}`)?.scrollIntoView({ block: "center" });
|
|
2922
3451
|
}
|
|
2923
3452
|
function pollPlayground(id, version) {
|
|
2924
3453
|
if (version !== generation || terminal(current.status)) return;
|
|
@@ -2926,7 +3455,9 @@ function pollPlayground(id, version) {
|
|
|
2926
3455
|
try {
|
|
2927
3456
|
const batch = await poll(`/playgrounds/${enc2(id)}`);
|
|
2928
3457
|
if (version !== generation) return;
|
|
2929
|
-
const
|
|
3458
|
+
const q = new URLSearchParams(location.search);
|
|
3459
|
+
if (!q.get("attempt") && !q.get("compare") && !shownAttempt) shownAttempt = defaultAttempt(batch, q.get("task") ?? void 0)?.id;
|
|
3460
|
+
const selected = q.get("attempt") ?? shownAttempt, evidence = selected ? await poll(`/playgrounds/${enc2(id)}/attempts/${enc2(selected)}`) : {};
|
|
2930
3461
|
if (version !== generation) return;
|
|
2931
3462
|
const changed = JSON.stringify(current) !== JSON.stringify(batch) || JSON.stringify(batchEvidence) !== JSON.stringify(evidence);
|
|
2932
3463
|
current = batch;
|
|
@@ -2948,23 +3479,50 @@ function renderTools(selected) {
|
|
|
2948
3479
|
const tool = toolCatalog.find((t) => t.name === selected);
|
|
2949
3480
|
if (selected && !tool) throw new Error("Tool not found.");
|
|
2950
3481
|
if (!tool) {
|
|
2951
|
-
const
|
|
3482
|
+
const filters = Object.fromEntries(new URLSearchParams(location.search));
|
|
2952
3483
|
const cliNote = boot.hosted ? '<p class="tools-cli-note">These replicas come with this workspace. To use all of them from your computer, update your CLI: <code>npm install -g @ancha-labs/cli@latest</code></p>' : "";
|
|
2953
|
-
shell("tools",
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
3484
|
+
shell("tools", catalogHead("Tools", '<a class="button-link" href="mailto:patrick@ancha.io?subject=Tool%20request">Request a tool</a>', "Replicas of the APIs agents call. Every attempt gets its own copy, seeded with the data shown on each tool.") + cliNote + toolsCatalog(toolCatalog, filters));
|
|
3485
|
+
const catalogNode = document.querySelector(".tools-catalog");
|
|
3486
|
+
const update = () => {
|
|
3487
|
+
const next = new URL(location.href);
|
|
3488
|
+
for (const key of ["q", "category"]) {
|
|
3489
|
+
if (filters[key]) next.searchParams.set(key, filters[key]);
|
|
3490
|
+
else next.searchParams.delete(key);
|
|
3491
|
+
}
|
|
3492
|
+
history.replaceState(history.state, "", next);
|
|
3493
|
+
renderedLocation = next;
|
|
3494
|
+
catalogNode.querySelector("#tool-tiles").innerHTML = toolTiles(toolCatalog, filters);
|
|
3495
|
+
catalogNode.querySelector(".tools-result-count").textContent = `${filteredTools(toolCatalog, filters).length} of ${toolCatalog.length} tools`;
|
|
3496
|
+
catalogNode.querySelectorAll("[data-tool-category]").forEach((chip) => chip.setAttribute("aria-pressed", String(chip.dataset.toolCategory === (filters.category ?? ""))));
|
|
3497
|
+
};
|
|
3498
|
+
catalogNode.querySelector("#tools-search").addEventListener("input", (event) => {
|
|
3499
|
+
filters.q = event.target.value;
|
|
3500
|
+
update();
|
|
3501
|
+
});
|
|
3502
|
+
catalogNode.addEventListener("click", (event) => {
|
|
3503
|
+
const target = event.target.closest("[data-tool-category], [data-tool-clear]");
|
|
3504
|
+
if (!target) return;
|
|
3505
|
+
event.preventDefault();
|
|
3506
|
+
if (target.hasAttribute("data-tool-clear")) {
|
|
3507
|
+
filters.q = "";
|
|
3508
|
+
filters.category = "";
|
|
3509
|
+
catalogNode.querySelector("#tools-search").value = "";
|
|
3510
|
+
} else filters.category = target.dataset.toolCategory ?? "";
|
|
3511
|
+
update();
|
|
3512
|
+
});
|
|
2958
3513
|
return;
|
|
2959
3514
|
}
|
|
2960
|
-
const d = tool.descriptor ?? {},
|
|
2961
|
-
const methods = ["GET", "POST", "PUT", "PATCH", "DELETE"], sorted = [...coverage].sort((a, b) => String(a.path).localeCompare(String(b.path)) || methods.indexOf(a.method) - methods.indexOf(b.method));
|
|
2962
|
-
const row2 = (c) => `<li title="${h(`${c.method} ${c.path}${c.notes ? ` \u2014 ${c.notes}` : ""}`)}"><code>${h(c.method)}</code><span>${h(c.path).replaceAll("/", "/<wbr>")}</span></li>`;
|
|
2963
|
-
const endpoints = coverage.length ? `<section class="tool-aside-section"><h2>Endpoints <span>${coverage.length}</span></h2><ul class="cov-list">${sorted.slice(0, 10).map(row2).join("")}</ul>${coverage.length > 10 ? `<details class="cov-more"><summary>All ${coverage.length} endpoints</summary><ul class="cov-list">${sorted.slice(10).map(row2).join("")}</ul></details>` : ""}</section>` : "";
|
|
2964
|
-
const connect = env.length ? `<section class="tool-aside-section"><h2>Connect your agent</h2><p>Your agent reads these at start; point your client at the URL instead of the real service.</p><dl class="env-list">${env.map((key) => `<div><dt><code>${h(key)}</code></dt><dd>${h(connectionLabel(key))}</dd></div>`).join("")}</dl>${connectionNote[tool.name] ? `<p class="hint">${h(connectionNote[tool.name])}</p>` : ""}</section>` : "";
|
|
2965
|
-
const limits = (d.limitations ?? []).length ? `<section class="tool-aside-section"><ul class="tool-limits">${(d.limitations ?? []).map((x) => `<li>${h(x)}</li>`).join("")}</ul></section>` : "";
|
|
3515
|
+
const d = tool.descriptor ?? {}, endpoints = toolEndpoints(tool.coverage ?? []), connect = toolConnect(tool.name);
|
|
2966
3516
|
const preview = viewMode2() ? waitingForToolPreview() : previewCache.has(tool.name) ? toolView(starterObservation, tool.name, { ...Object.fromEntries(new URLSearchParams(location.search)), baseHref: "/tools/" + enc2(tool.name), embedded: true }) : `<p class="loading" role="status">Loading ${h(toolName(tool.name))}\u2026</p>`;
|
|
2967
|
-
shell("tools", `<a class="back" data-nav href="/tools">\u2190 All tools</a><header class="page-head tool-hero"><div class="tool-hero-id">${toolLogo(tool.name)}<div><h1>${h(toolName(tool.name))}</h1><p class="page-meta">${h(toolCategory[tool.name] ?? "Tool")} \xB7 ${h(d.description ?? toolDescription(tool.name))}</p></div></div>${viewMode2() || !taskTool(tool.name) ? "" : `<div class="actions"><a class="button-link primary" data-nav href="/worlds/new?tool=${enc2(tool.name)}">Use in a world</a></div>`}</header><p class="tool-intro">A replica of the ${h(toolName(tool.name))} API with its own data. Every attempt starts from a fresh copy of what is below, and every call your agent makes is recorded.</p>${!viewMode2() && previewCache.has(tool.name) ? starterStats(tool.name) : ""}<div class="tool-page"><section class="tool-main"><h2 class="tool-main-title">Starter data</h2>${preview}</section><aside class="tool-aside">${connect}${endpoints}
|
|
3517
|
+
shell("tools", `<a class="back" data-nav href="/tools">\u2190 All tools</a><header class="page-head tool-hero"><div class="tool-hero-id">${toolLogo(tool.name)}<div><h1>${h(toolName(tool.name))}</h1><p class="page-meta">${h(toolCategory[tool.name] ?? "Tool")} \xB7 ${h(d.description ?? toolDescription(tool.name))}</p></div></div>${viewMode2() || !taskTool(tool.name) ? "" : `<div class="actions"><a class="button-link primary" data-nav href="/worlds/new?tool=${enc2(tool.name)}">Use in a world</a></div>`}</header><p class="tool-intro">A replica of the ${h(toolName(tool.name))} API with its own data. Every attempt starts from a fresh copy of what is below, and every call your agent makes is recorded.</p>${!viewMode2() && previewCache.has(tool.name) ? starterStats(tool.name) : ""}<div class="tool-page"><section class="tool-main"><h2 class="tool-main-title">Starter data</h2>${preview}</section><aside class="tool-aside">${connect}${endpoints}</aside></div>`);
|
|
3518
|
+
document.querySelector("#endpoint-filter")?.addEventListener("input", (event) => {
|
|
3519
|
+
const query = event.target.value.trim().toLowerCase();
|
|
3520
|
+
const rows3 = [...document.querySelectorAll(".endpoint-table tbody tr")];
|
|
3521
|
+
rows3.forEach((row2) => {
|
|
3522
|
+
row2.hidden = !`${row2.textContent} ${row2.title}`.toLowerCase().includes(query);
|
|
3523
|
+
});
|
|
3524
|
+
document.querySelector("#endpoint-empty").hidden = rows3.some((row2) => !row2.hidden);
|
|
3525
|
+
});
|
|
2968
3526
|
}
|
|
2969
3527
|
function renderScenarios() {
|
|
2970
3528
|
if (!current.scene) {
|
|
@@ -3034,14 +3592,14 @@ function runCaseTitle(caseId, scenarioId) {
|
|
|
3034
3592
|
function renderAttempt(scene, trial) {
|
|
3035
3593
|
const recorded = legacyObservation.context?.scenario ?? runCaseItem(scene)?.scene;
|
|
3036
3594
|
current.displayScene = recorded;
|
|
3037
|
-
const q = new URLSearchParams(location.search), base = url("/runs/" + enc2(current.runId), { scene, trial }),
|
|
3595
|
+
const q = new URLSearchParams(location.search), base = url("/runs/" + enc2(current.runId), { scene, trial }), view2 = q.get("view") ?? "activity", tool = q.get("tool"), tools = recorded?.twins ?? Object.keys(observation.state ?? {});
|
|
3038
3596
|
const o = { ...observation, checks: Array.isArray(observation.checks) ? observation.checks : observation.checks?.checks ?? [] }, diagnostic = current.metadata?.diagnostic;
|
|
3039
|
-
const tabs = navTabs([["activity", "Activity", url("/runs/" + enc2(current.runId), { scene, trial, view: "activity" })], ["sandbox", "Tools", url("/runs/" + enc2(current.runId), { scene, trial, view: "sandbox" })], ...!diagnostic ? [["result", "Outcomes", url("/runs/" + enc2(current.runId), { scene, trial, view: "result" })]] : []],
|
|
3597
|
+
const tabs = navTabs([["activity", "Activity", url("/runs/" + enc2(current.runId), { scene, trial, view: "activity" })], ["sandbox", "Tools", url("/runs/" + enc2(current.runId), { scene, trial, view: "sandbox" })], ...!diagnostic ? [["result", "Outcomes", url("/runs/" + enc2(current.runId), { scene, trial, view: "result" })]] : []], view2 === "tools" ? "sandbox" : view2);
|
|
3040
3598
|
const status = legacyObservation.state === "live" ? badge("Running", "accent") : observation.entry ? attemptStatus(observation.entry, diagnostic) : badge(legacyObservation.attempt?.state ?? "Unavailable");
|
|
3041
3599
|
let content = legacyObservation.reason ? `<p class="quiet-empty">${h(legacyObservation.reason)}</p>` : "";
|
|
3042
3600
|
if (legacyObservation.observation) {
|
|
3043
|
-
if (
|
|
3044
|
-
else if (["sandbox", "tools"].includes(
|
|
3601
|
+
if (view2 === "result") content += attemptResult(o, recorded, q.get("check"), base);
|
|
3602
|
+
else if (["sandbox", "tools"].includes(view2)) content += `<nav class="tool-nav" aria-label="Trial tools">${tools.map((t) => navLink(toolName(t), url("/runs/" + enc2(current.runId), { scene, trial, view: "sandbox", tool: t }), t === (tool || tools[0]) ? "active" : "")).join("")}</nav><p class="preview-context">${legacyObservation.state === "live" ? "Current captured data" : "Captured final data"}</p>${toolView(o, tool || tools[0], { ...Object.fromEntries(q), baseHref: base })}`;
|
|
3045
3603
|
else content += `${observation.taskDelivery?.response ? responseView({ response: observation.taskDelivery.response, status: legacyObservation.state === "live" ? "running" : "completed" }) : ""}${activityView(o, { baseHref: base })}`;
|
|
3046
3604
|
}
|
|
3047
3605
|
shell("runs", navLink("\u2190 Run", "/runs/" + enc2(current.runId), "back") + head(`${recorded ? title(recorded) : runCaseTitle(scene)} \xB7 trial ${trial}`, current.owned ? button("Stop run", "cancel-run", current.runId) : diagnostic ? "" : button("Run again", "rerun", current.runId, "primary")) + `<p class="task-prompt">${h(recorded?.task ?? "The exact task is not available in this saved result.")}</p><div class="batch-progress">${status}</div>${tabs}<div id="attempt-evidence">${content}</div>`);
|
|
@@ -3149,13 +3707,13 @@ async function mutate(action2, payload = {}) {
|
|
|
3149
3707
|
setBusy(true);
|
|
3150
3708
|
const version = generation, id = current.sandbox.id;
|
|
3151
3709
|
try {
|
|
3152
|
-
const
|
|
3710
|
+
const result = await api(`/sandboxes/${enc2(id)}/${action2}`, { revision: observation.revision, ...payload });
|
|
3153
3711
|
if (version !== generation) return;
|
|
3154
|
-
if (
|
|
3712
|
+
if (result.observation) observation = result.observation;
|
|
3155
3713
|
renderSandbox();
|
|
3156
|
-
if (
|
|
3714
|
+
if (result.operation && !result.operation.ok) {
|
|
3157
3715
|
stopPlay();
|
|
3158
|
-
throw new Error(`Operation rejected: ${JSON.stringify(
|
|
3716
|
+
throw new Error(`Operation rejected: ${JSON.stringify(result.operation.body)}`);
|
|
3159
3717
|
}
|
|
3160
3718
|
} catch (e) {
|
|
3161
3719
|
stopPlay();
|
|
@@ -3223,6 +3781,15 @@ async function action(kind, value, target) {
|
|
|
3223
3781
|
go("/playgrounds");
|
|
3224
3782
|
return;
|
|
3225
3783
|
}
|
|
3784
|
+
if (kind === "copy-text") {
|
|
3785
|
+
await navigator.clipboard.writeText(value);
|
|
3786
|
+
target.dataset.copied = "1";
|
|
3787
|
+
setTimeout(() => {
|
|
3788
|
+
delete target.dataset.copied;
|
|
3789
|
+
}, 1500);
|
|
3790
|
+
notify("Copied.");
|
|
3791
|
+
return;
|
|
3792
|
+
}
|
|
3226
3793
|
if (kind === "close") return dialog.close();
|
|
3227
3794
|
if (kind === "add-task" || kind === "remove-task") {
|
|
3228
3795
|
rememberDraft();
|
|
@@ -3253,8 +3820,8 @@ async function action(kind, value, target) {
|
|
|
3253
3820
|
target.setAttribute("aria-busy", "true");
|
|
3254
3821
|
target.disabled = true;
|
|
3255
3822
|
try {
|
|
3256
|
-
const
|
|
3257
|
-
go(`/playgrounds/${enc2(
|
|
3823
|
+
const result = await api(`/playgrounds/${enc2(value)}/rerun`, { idempotencyKey: submission.idempotencyKey });
|
|
3824
|
+
go(`/playgrounds/${enc2(result.id)}`);
|
|
3258
3825
|
sessionStorage.removeItem(storageKey);
|
|
3259
3826
|
return;
|
|
3260
3827
|
} catch (error) {
|
|
@@ -3287,8 +3854,8 @@ async function action(kind, value, target) {
|
|
|
3287
3854
|
target.setAttribute("aria-busy", "true");
|
|
3288
3855
|
target.disabled = true;
|
|
3289
3856
|
try {
|
|
3290
|
-
const
|
|
3291
|
-
go("/playgrounds/" + enc2(
|
|
3857
|
+
const result = await api("/playgrounds", submission);
|
|
3858
|
+
go("/playgrounds/" + enc2(result.id));
|
|
3292
3859
|
sessionStorage.removeItem(storageKey);
|
|
3293
3860
|
return;
|
|
3294
3861
|
} catch (error) {
|
|
@@ -3396,8 +3963,8 @@ async function action(kind, value, target) {
|
|
|
3396
3963
|
if (kind === "browse") return go("/scenarios");
|
|
3397
3964
|
if (kind === "recreate-sandbox") {
|
|
3398
3965
|
const s = current.sandbox;
|
|
3399
|
-
const
|
|
3400
|
-
go(`/sandboxes/${enc2(
|
|
3966
|
+
const result = await api("/sandboxes", { configuration: s.configuration, seed: s.seed });
|
|
3967
|
+
go(`/sandboxes/${enc2(result.sandbox.id)}`);
|
|
3401
3968
|
return;
|
|
3402
3969
|
}
|
|
3403
3970
|
if (kind === "create") {
|
|
@@ -3436,9 +4003,9 @@ async function action(kind, value, target) {
|
|
|
3436
4003
|
if (kind === "download-mcp") return download("ancha-mcp.json", JSON.stringify(connectionInfo.mcp.configuration, null, 2) + "\n", "application/json");
|
|
3437
4004
|
if (kind === "download-certificate") return download("ancha-google-ads.pem", connectionInfo.services["google-ads"].tlsRootCertificate);
|
|
3438
4005
|
if (kind === "sandbox-fork") {
|
|
3439
|
-
const
|
|
4006
|
+
const result = await api(`/sandboxes/${enc2(current.sandbox.id)}/fork`, {});
|
|
3440
4007
|
dialog.close();
|
|
3441
|
-
go(`/sandboxes/${enc2(
|
|
4008
|
+
go(`/sandboxes/${enc2(result.sandbox.id)}`);
|
|
3442
4009
|
return notify("Fresh sandbox created from the original data.");
|
|
3443
4010
|
}
|
|
3444
4011
|
if (kind === "test") return testForm(value);
|
|
@@ -3568,8 +4135,8 @@ async function action(kind, value, target) {
|
|
|
3568
4135
|
return renderSandbox();
|
|
3569
4136
|
}
|
|
3570
4137
|
if (kind === "renew") {
|
|
3571
|
-
const
|
|
3572
|
-
current.lease =
|
|
4138
|
+
const result = await api(`/sandboxes/${enc2(current.sandbox.id)}/renew`, {});
|
|
4139
|
+
current.lease = result.lease;
|
|
3573
4140
|
renderSandbox();
|
|
3574
4141
|
if (dialog.open) await action("sandbox-details", "", target);
|
|
3575
4142
|
return notify("Sandbox lifetime renewed.");
|
|
@@ -3647,9 +4214,7 @@ document.addEventListener("change", (event) => {
|
|
|
3647
4214
|
return;
|
|
3648
4215
|
}
|
|
3649
4216
|
if (el.matches("[data-run-filter]")) {
|
|
3650
|
-
|
|
3651
|
-
for (const [key, value] of new FormData(el.closest("form"))) if (value) params.set(key, String(value));
|
|
3652
|
-
go("/playgrounds" + (params.size ? "?" + params : ""));
|
|
4217
|
+
go(runFilterUrl(el.closest("form")));
|
|
3653
4218
|
return;
|
|
3654
4219
|
}
|
|
3655
4220
|
if (el.id === "task-input-kind") {
|
|
@@ -3714,6 +4279,11 @@ document.addEventListener("change", (event) => {
|
|
|
3714
4279
|
document.addEventListener("submit", (event) => {
|
|
3715
4280
|
const form = event.target;
|
|
3716
4281
|
event.preventDefault();
|
|
4282
|
+
if (form.classList.contains("runs-filters")) {
|
|
4283
|
+
clearTimeout(searchTimer);
|
|
4284
|
+
go(runFilterUrl(form));
|
|
4285
|
+
return;
|
|
4286
|
+
}
|
|
3717
4287
|
const submit = form.querySelector('button[type="submit"],button:not([type])');
|
|
3718
4288
|
if (submit) submit.disabled = true;
|
|
3719
4289
|
void submitForm(form).catch((e) => {
|
|
@@ -3731,7 +4301,22 @@ document.addEventListener("focusout", (event) => {
|
|
|
3731
4301
|
if (el.name === "cwd" && el.closest("form")) void suggestAgentCommand(el.closest("form"));
|
|
3732
4302
|
});
|
|
3733
4303
|
document.addEventListener("input", (event) => {
|
|
3734
|
-
|
|
4304
|
+
const el = event.target;
|
|
4305
|
+
if (el.closest("#playground-form")) updateTaskCount();
|
|
4306
|
+
if (el.matches("[data-run-search]")) {
|
|
4307
|
+
clearTimeout(searchTimer);
|
|
4308
|
+
searchTimer = setTimeout(() => {
|
|
4309
|
+
if (!el.isConnected) return;
|
|
4310
|
+
history.replaceState({}, "", runFilterUrl(el.form));
|
|
4311
|
+
const caret = el.selectionStart;
|
|
4312
|
+
renderRunsList();
|
|
4313
|
+
const next = document.querySelector("[data-run-search]");
|
|
4314
|
+
if (next) {
|
|
4315
|
+
next.focus();
|
|
4316
|
+
next.setSelectionRange(caret, caret);
|
|
4317
|
+
}
|
|
4318
|
+
}, 250);
|
|
4319
|
+
}
|
|
3735
4320
|
});
|
|
3736
4321
|
async function submitForm(form) {
|
|
3737
4322
|
const values = new FormData(form), d = Object.fromEntries(values);
|
|
@@ -3751,8 +4336,8 @@ async function submitForm(form) {
|
|
|
3751
4336
|
if (form.id === "playground-form") {
|
|
3752
4337
|
rememberDraft();
|
|
3753
4338
|
const draft = agentDraft(form.dataset.agent);
|
|
3754
|
-
const
|
|
3755
|
-
go("/playgrounds/" + enc2(
|
|
4339
|
+
const result = await api("/playgrounds", { agentId: form.dataset.agent, tasks: draft.tasks, concurrency: draft.concurrency, seed: "playground-1" });
|
|
4340
|
+
go("/playgrounds/" + enc2(result.id));
|
|
3756
4341
|
return;
|
|
3757
4342
|
}
|
|
3758
4343
|
if (form.id === "agent-settings-form") {
|
|
@@ -3816,14 +4401,14 @@ async function submitForm(form) {
|
|
|
3816
4401
|
notify("Draft saved.");
|
|
3817
4402
|
}
|
|
3818
4403
|
if (form.id === "compare-form") {
|
|
3819
|
-
const
|
|
3820
|
-
const labels = Object.fromEntries(
|
|
4404
|
+
const result = await api("/compare", d);
|
|
4405
|
+
const labels = Object.fromEntries(result.scenes.map((row2, index) => {
|
|
3821
4406
|
const saved = current.metadata?.cases?.find((c) => c.id === row2.sceneId);
|
|
3822
4407
|
const summary = current.summary?.scenes?.find((c) => c.sceneId === row2.sceneId);
|
|
3823
4408
|
const item = catalog.scenes.find((c) => c.caseId === row2.sceneId || c.scene.id === (summary?.scenarioId ?? row2.sceneId));
|
|
3824
4409
|
return [row2.sceneId, saved?.title ?? (item ? title(item.scene) : summary?.scenarioId ? title({ id: summary.scenarioId }) : `Scenario ${index + 1}`)];
|
|
3825
4410
|
}));
|
|
3826
|
-
modal("Run comparison", comparisonResults(
|
|
4411
|
+
modal("Run comparison", comparisonResults(result, labels), true);
|
|
3827
4412
|
}
|
|
3828
4413
|
if (form.id === "slack-form") {
|
|
3829
4414
|
stopPlay();
|