@hexdecimal16/nexo 0.0.0-stage → 0.2.1

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.
Files changed (209) hide show
  1. package/LICENSE +75 -0
  2. package/README.md +75 -2
  3. package/cli/src/bin.js +12 -0
  4. package/cli/src/common.js +78 -0
  5. package/cli/src/doctor.js +27 -0
  6. package/cli/src/eval-cases.js +65 -0
  7. package/cli/src/eval.js +67 -0
  8. package/cli/src/init.js +186 -0
  9. package/cli/src/interactive.js +171 -0
  10. package/cli/src/learn.js +178 -0
  11. package/cli/src/main.js +266 -0
  12. package/cli/src/optimize.js +289 -0
  13. package/cli/src/prompter.js +47 -0
  14. package/cli/src/review.js +120 -0
  15. package/cli/src/runtime.js +2 -0
  16. package/cli/src/sessions.js +34 -0
  17. package/cli/src/settings.js +169 -0
  18. package/cli/src/ui.js +112 -0
  19. package/cli/src/version.js +19 -0
  20. package/core/src/approval/classifier.js +152 -0
  21. package/core/src/config/load.js +283 -0
  22. package/core/src/config/schema.js +186 -0
  23. package/core/src/cost/admission.js +90 -0
  24. package/core/src/cost/budget.js +67 -0
  25. package/core/src/cost/pricing.js +53 -0
  26. package/core/src/engine/charged-completion.js +79 -0
  27. package/core/src/engine/errors.js +77 -0
  28. package/core/src/engine/mcp.js +11 -0
  29. package/core/src/engine/messages.js +86 -0
  30. package/core/src/engine/prompts.js +32 -0
  31. package/core/src/engine/provider-gate.js +33 -0
  32. package/core/src/engine/recorder.js +61 -0
  33. package/core/src/engine/run.js +1115 -0
  34. package/core/src/engine/semaphore.js +45 -0
  35. package/core/src/engine/spawn-tool.js +119 -0
  36. package/core/src/engine/task-graph.js +153 -0
  37. package/core/src/index.js +32 -0
  38. package/core/src/learn/caller.js +171 -0
  39. package/core/src/learn/context.js +112 -0
  40. package/core/src/learn/embedder.js +216 -0
  41. package/core/src/learn/job.js +196 -0
  42. package/core/src/learn/wiki.js +116 -0
  43. package/core/src/learn/worker.js +141 -0
  44. package/core/src/optimize/adapter.js +250 -0
  45. package/core/src/optimize/climb.js +338 -0
  46. package/core/src/optimize/mine.js +95 -0
  47. package/core/src/optimize/optimize.js +377 -0
  48. package/core/src/optimize/optimizer-run.js +67 -0
  49. package/core/src/optimize/reflect.js +100 -0
  50. package/core/src/optimize/scratchpad-wiki.js +69 -0
  51. package/core/src/providers/claude-p.js +363 -0
  52. package/core/src/providers/kiro-p.js +408 -0
  53. package/core/src/providers/models.js +10 -0
  54. package/core/src/scoring/calibration.js +31 -0
  55. package/core/src/scoring/continuation.js +24 -0
  56. package/core/src/scoring/runner.js +322 -0
  57. package/core/src/scoring/sources.js +88 -0
  58. package/core/src/session/lock.js +88 -0
  59. package/core/src/session/session.js +647 -0
  60. package/core/src/session/shell.js +26 -0
  61. package/core/src/session/transcript.js +86 -0
  62. package/core/src/settings/config-edit.js +472 -0
  63. package/core/src/settings/credentials.js +120 -0
  64. package/core/src/settings/doctor.js +103 -0
  65. package/core/src/settings/settings.js +265 -0
  66. package/mcp/src/hub.js +184 -0
  67. package/mcp/src/index.js +1 -0
  68. package/memory/src/curate.js +121 -0
  69. package/memory/src/index.js +4 -0
  70. package/memory/src/prompts.js +143 -0
  71. package/memory/src/retrieval.js +91 -0
  72. package/memory/src/similarity.js +47 -0
  73. package/optimize/src/engine.js +206 -0
  74. package/optimize/src/index.js +8 -0
  75. package/optimize/src/merge.js +73 -0
  76. package/optimize/src/novelty.js +37 -0
  77. package/optimize/src/pareto.js +83 -0
  78. package/optimize/src/proposer.js +148 -0
  79. package/optimize/src/report.js +107 -0
  80. package/optimize/src/rng.js +34 -0
  81. package/optimize/src/target.js +34 -0
  82. package/package.json +47 -4
  83. package/router/src/effort.js +5 -0
  84. package/router/src/escalation.js +171 -0
  85. package/router/src/index.js +4 -0
  86. package/router/src/registry.js +21 -0
  87. package/router/src/resolve.js +117 -0
  88. package/scorers/src/deterministic.js +194 -0
  89. package/scorers/src/family.js +48 -0
  90. package/scorers/src/index.js +6 -0
  91. package/scorers/src/judge.js +284 -0
  92. package/scorers/src/regex-worker.js +3 -0
  93. package/scorers/src/spec.js +147 -0
  94. package/scorers/src/trajectory.js +22 -0
  95. package/scorers/src/types.js +1 -0
  96. package/sdk/src/index.js +3 -0
  97. package/sdk/src/nexo.js +94 -0
  98. package/sdk/src/runtime.js +39 -0
  99. package/skills/bundled/browser/SKILL.md +57 -0
  100. package/skills/bundled/wiki/SKILL.md +73 -0
  101. package/skills/src/frontmatter.js +25 -0
  102. package/skills/src/index.js +3 -0
  103. package/skills/src/load-skill-tool.js +41 -0
  104. package/skills/src/loader.js +95 -0
  105. package/store/src/artifacts.js +124 -0
  106. package/store/src/budget-ledger.js +18 -0
  107. package/store/src/cost-report.js +46 -0
  108. package/store/src/cursor.js +35 -0
  109. package/store/src/db.js +83 -0
  110. package/store/src/errors.js +9 -0
  111. package/store/src/eval-cases.js +255 -0
  112. package/store/src/feedback.js +154 -0
  113. package/store/src/goldens.js +61 -0
  114. package/store/src/ids.js +6 -0
  115. package/store/src/index.js +25 -0
  116. package/store/src/judge-calibration.js +182 -0
  117. package/store/src/learn-jobs.js +145 -0
  118. package/store/src/memories.js +261 -0
  119. package/store/src/migrations/001_init.sql +81 -0
  120. package/store/src/migrations/002_feedback.sql +9 -0
  121. package/store/src/migrations/003_sessions.sql +19 -0
  122. package/store/src/migrations/004_scoring.sql +22 -0
  123. package/store/src/migrations/005_judge_calibration.sql +27 -0
  124. package/store/src/migrations/006_learning.sql +77 -0
  125. package/store/src/migrations/007_optimize.sql +55 -0
  126. package/store/src/migrations/008_mined_cases_and_climb.sql +46 -0
  127. package/store/src/mine.js +51 -0
  128. package/store/src/optim.js +291 -0
  129. package/store/src/paths.js +22 -0
  130. package/store/src/playbooks.js +199 -0
  131. package/store/src/reindex.js +143 -0
  132. package/store/src/run-dir.js +151 -0
  133. package/store/src/runs.js +310 -0
  134. package/store/src/scores.js +92 -0
  135. package/store/src/sessions.js +304 -0
  136. package/store/src/span-tree.js +98 -0
  137. package/store/src/spans.js +84 -0
  138. package/store/src/sql.js +13 -0
  139. package/store/src/workspace-copy.js +80 -0
  140. package/telemetry/src/errors.js +32 -0
  141. package/telemetry/src/index.js +3 -0
  142. package/telemetry/src/logger.js +39 -0
  143. package/telemetry/src/redact.js +106 -0
  144. package/tools/src/builtin.js +269 -0
  145. package/tools/src/change-tracker.js +57 -0
  146. package/tools/src/confine.js +101 -0
  147. package/tools/src/index.js +7 -0
  148. package/tools/src/leases.js +57 -0
  149. package/tools/src/policy.js +162 -0
  150. package/tools/src/read-only.js +338 -0
  151. package/tools/src/session-rules.js +140 -0
  152. package/tui/src/app.js +965 -0
  153. package/tui/src/approvals.js +96 -0
  154. package/tui/src/commands.js +38 -0
  155. package/tui/src/components.js +248 -0
  156. package/tui/src/index.js +5 -0
  157. package/tui/src/picker.js +78 -0
  158. package/tui/src/session-picker.js +100 -0
  159. package/tui/src/settings-screen.js +346 -0
  160. package/tui/src/text.js +70 -0
  161. package/tui/src/theme.js +44 -0
  162. package/web/public/cost.html +25 -0
  163. package/web/public/fonts/GeistMono-400.woff2 +0 -0
  164. package/web/public/fonts/GeistMono-600.woff2 +0 -0
  165. package/web/public/fonts/InstrumentSans-400.woff2 +0 -0
  166. package/web/public/fonts/InstrumentSans-600.woff2 +0 -0
  167. package/web/public/index.html +39 -0
  168. package/web/public/judge.html +21 -0
  169. package/web/public/learning.html +46 -0
  170. package/web/public/lib/api-types.ts +616 -0
  171. package/web/public/lib/common-view.ts +47 -0
  172. package/web/public/lib/cost-view.ts +35 -0
  173. package/web/public/lib/files-view.ts +90 -0
  174. package/web/public/lib/format.ts +35 -0
  175. package/web/public/lib/html.ts +51 -0
  176. package/web/public/lib/judge-view.ts +62 -0
  177. package/web/public/lib/learning-view.ts +102 -0
  178. package/web/public/lib/optim-view.ts +148 -0
  179. package/web/public/lib/pager.ts +56 -0
  180. package/web/public/lib/poller.ts +79 -0
  181. package/web/public/lib/run-view.ts +61 -0
  182. package/web/public/lib/runs-view.ts +87 -0
  183. package/web/public/lib/score-view.ts +94 -0
  184. package/web/public/lib/sessions-view.ts +28 -0
  185. package/web/public/lib/span-view.ts +90 -0
  186. package/web/public/lib/theme.ts +60 -0
  187. package/web/public/lib/timeline.ts +97 -0
  188. package/web/public/lib/wikis-view.ts +257 -0
  189. package/web/public/optim.html +30 -0
  190. package/web/public/pages/api.ts +60 -0
  191. package/web/public/pages/cost.ts +36 -0
  192. package/web/public/pages/judge.ts +15 -0
  193. package/web/public/pages/learning.ts +92 -0
  194. package/web/public/pages/optim.ts +68 -0
  195. package/web/public/pages/paging.ts +18 -0
  196. package/web/public/pages/run.ts +221 -0
  197. package/web/public/pages/runs.ts +91 -0
  198. package/web/public/pages/sessions.ts +25 -0
  199. package/web/public/pages/wikis.ts +103 -0
  200. package/web/public/run.html +36 -0
  201. package/web/public/sessions.html +28 -0
  202. package/web/public/style.css +288 -0
  203. package/web/public/wikis.html +25 -0
  204. package/web/src/api.js +682 -0
  205. package/web/src/http-errors.js +60 -0
  206. package/web/src/index.js +5 -0
  207. package/web/src/server.js +292 -0
  208. package/web/src/static.js +86 -0
  209. package/web/src/strip.js +22 -0
@@ -0,0 +1,90 @@
1
+ import type { DirListing } from "./api-types.ts";
2
+ import { html, type SafeHtml } from "./html.ts";
3
+
4
+ export type DiffLineKind = "add" | "del" | "ctx" | "hunk" | "meta";
5
+
6
+ export interface DiffLine {
7
+ kind: DiffLineKind;
8
+ text: string;
9
+ }
10
+
11
+ export function isDiffPath(path: string): boolean {
12
+ return /\.(diff|patch)$/.test(path);
13
+ }
14
+
15
+ /** API path of a file or directory inside a run directory, each segment percent-encoded. */
16
+ export function filePath(runId: string, path: string, full = false): string {
17
+ const encoded = path.split("/").filter(Boolean).map(encodeURIComponent).join("/");
18
+ return `/api/runs/${encodeURIComponent(runId)}/files/${encoded}${full ? "?full=1" : ""}`;
19
+ }
20
+
21
+ export function parseUnifiedDiff(text: string): DiffLine[] {
22
+ const lines = text.split("\n");
23
+ if (lines.at(-1) === "") lines.pop();
24
+ return lines.map((line): DiffLine => {
25
+ if (line.startsWith("+++") || line.startsWith("---") || line.startsWith("Index:") || line.startsWith("====")) return { kind: "meta", text: line };
26
+ if (line.startsWith("@@")) return { kind: "hunk", text: line };
27
+ if (line.startsWith("+")) return { kind: "add", text: line };
28
+ if (line.startsWith("-")) return { kind: "del", text: line };
29
+ return { kind: "ctx", text: line };
30
+ });
31
+ }
32
+
33
+ export function renderDiff(lines: DiffLine[]): SafeHtml {
34
+ return html`<pre class="diff">${lines.map((l) => html`<span class="diff-${l.kind}">${l.text}</span>`)}</pre>`;
35
+ }
36
+
37
+ function formatSize(bytes: number): string {
38
+ if (bytes < 1024) return `${bytes} B`;
39
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
40
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
41
+ }
42
+
43
+ export function renderListing(listing: DirListing): SafeHtml {
44
+ const segments = listing.path ? listing.path.split("/") : [];
45
+ const crumbs = [html`<button type="button" class="link" data-dir="">run</button>`];
46
+ segments.forEach((name, i) => crumbs.push(html` / <button type="button" class="link" data-dir="${segments.slice(0, i + 1).join("/")}">${name}</button>`));
47
+ return html`<nav class="crumbs">${crumbs}</nav>
48
+ <ul class="files">${listing.entries.length === 0 ? html`<li class="muted">empty</li>` : ""}${listing.entries.map((e) => {
49
+ if (e.kind === "dir") return html`<li><button type="button" class="link dir" data-dir="${e.path}">${e.name}/</button></li>`;
50
+ if (e.kind === "symlink") return html`<li><button type="button" class="link file" data-file="${e.path}">${e.name}</button> <span class="muted">symlink</span></li>`;
51
+ if (e.kind === "other") return html`<li><span class="muted">${e.name} (not a regular file)</span></li>`;
52
+ return html`<li><button type="button" class="link file" data-file="${e.path}">${e.name}</button> <span class="muted">${formatSize(e.size)}</span></li>`;
53
+ })}</ul>`;
54
+ }
55
+
56
+ export type MediaKind = "video" | "audio" | "image";
57
+
58
+ /** Extensions the files API serves under a media type (kept in step with `MEDIA_TYPES` in the server's api.ts). */
59
+ const MEDIA_KINDS: Record<string, MediaKind> = {
60
+ mp4: "video", m4v: "video", webm: "video", mov: "video",
61
+ mp3: "audio", m4a: "audio", wav: "audio", ogg: "audio",
62
+ png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image",
63
+ };
64
+
65
+ export function mediaKind(path: string): MediaKind | null {
66
+ const dot = path.lastIndexOf(".");
67
+ if (dot < 0 || dot < path.lastIndexOf("/")) return null;
68
+ return MEDIA_KINDS[path.slice(dot + 1).toLowerCase()] ?? null;
69
+ }
70
+
71
+ /** A player or image for a media file, loaded straight from the files API, with a link to open it on its own. */
72
+ export function renderMedia(path: string, kind: MediaKind, src: string): SafeHtml {
73
+ const player =
74
+ kind === "video" ? html`<video class="media" controls preload="metadata" src="${src}"></video>`
75
+ : kind === "audio" ? html`<audio class="media" controls preload="metadata" src="${src}"></audio>`
76
+ : html`<img class="media" alt="${path}" src="${src}">`;
77
+ return html`<div class="file-view">
78
+ <div class="file-head mono">${path} · <a href="${src}" target="_blank" rel="noopener noreferrer">open</a></div>
79
+ ${player}
80
+ </div>`;
81
+ }
82
+
83
+ /** File contents: unified diffs get line colouring, anything else is plain preformatted text. */
84
+ export function renderFile(path: string, text: string, truncatedSize: number | null): SafeHtml {
85
+ return html`<div class="file-view">
86
+ <div class="file-head mono">${path}</div>
87
+ ${truncatedSize !== null ? html`<p class="note">Showing the first 1 MB of ${formatSize(truncatedSize)}. <button type="button" class="link" data-file-full="${path}">Load everything</button></p>` : ""}
88
+ ${isDiffPath(path) ? renderDiff(parseUnifiedDiff(text)) : html`<pre>${text}</pre>`}
89
+ </div>`;
90
+ }
@@ -0,0 +1,35 @@
1
+ // Display formatting with no locale or time-zone dependence, so output is identical in tests and browsers.
2
+
3
+ export function formatUsd(usd: number, unknown = false): string {
4
+ const value = `$${(Number.isFinite(usd) ? usd : 0).toFixed(4)}`;
5
+ return unknown ? `${value} + unpriced` : value;
6
+ }
7
+
8
+ export function formatDuration(ms: number | null): string {
9
+ if (ms === null || !Number.isFinite(ms) || ms < 0) return "–";
10
+ if (ms < 1000) return `${Math.round(ms)} ms`;
11
+ if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;
12
+ const minutes = Math.floor(ms / 60_000);
13
+ const seconds = Math.floor((ms % 60_000) / 1000);
14
+ return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
15
+ }
16
+
17
+ /** Milliseconds from start to end, or to `nowMs` while the span or run is still open. */
18
+ export function durationMs(startIso: string, endIso: string | null, nowMs: number): number {
19
+ const start = Date.parse(startIso);
20
+ const end = endIso === null ? nowMs : Date.parse(endIso);
21
+ return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : 0;
22
+ }
23
+
24
+ /** `2026-10-10T10:00:00.000Z` → `2026-10-10 10:00:00` (UTC). */
25
+ export function formatTime(iso: string | null): string {
26
+ return iso ? iso.replace("T", " ").slice(0, 19) : "–";
27
+ }
28
+
29
+ export function shortId(id: string): string {
30
+ return id.slice(-6);
31
+ }
32
+
33
+ export function truncate(text: string, max: number): string {
34
+ return text.length > max ? `${text.slice(0, max)}…` : text;
35
+ }
@@ -0,0 +1,51 @@
1
+ // Escaping HTML builder. Every interpolated value is escaped unless it is itself a SafeHtml produced by `html`,
2
+ // so agent-produced text (instructions, outputs, tool results, file names) can never become markup.
3
+
4
+ export class SafeHtml {
5
+ readonly value: string;
6
+
7
+ constructor(value: string) {
8
+ this.value = value;
9
+ }
10
+
11
+ toString(): string {
12
+ return this.value;
13
+ }
14
+ }
15
+
16
+ const ESCAPES: Record<string, string> = {
17
+ "&": "&amp;",
18
+ "<": "&lt;",
19
+ ">": "&gt;",
20
+ '"': "&quot;",
21
+ "'": "&#39;",
22
+ "`": "&#96;",
23
+ };
24
+
25
+ /** Escapes text for use in element content and in quoted attribute values. */
26
+ export function esc(value: unknown): string {
27
+ return String(value ?? "").replace(/[&<>"'`]/g, (c) => ESCAPES[c] ?? c);
28
+ }
29
+
30
+ function part(value: unknown): string {
31
+ if (value instanceof SafeHtml) return value.value;
32
+ if (Array.isArray(value)) return value.map(part).join("");
33
+ if (value === null || value === undefined || value === false) return "";
34
+ return esc(value);
35
+ }
36
+
37
+ /** Tagged template: `html\`<td>${text}</td>\``. Arrays are concatenated; null, undefined and false render nothing. */
38
+ export function html(strings: TemplateStringsArray, ...values: unknown[]): SafeHtml {
39
+ let out = strings[0] ?? "";
40
+ for (let i = 0; i < values.length; i++) out += part(values[i]) + (strings[i + 1] ?? "");
41
+ return new SafeHtml(out);
42
+ }
43
+
44
+ /** Pretty JSON for display inside <pre>; the caller still interpolates it through `html`. */
45
+ export function prettyJson(value: unknown): string {
46
+ try {
47
+ return JSON.stringify(value, null, 2) ?? String(value);
48
+ } catch {
49
+ return String(value);
50
+ }
51
+ }
@@ -0,0 +1,62 @@
1
+ import type { Calibration, ConfusionMatrix, JudgeCalibrationResponse } from "./api-types.ts";
2
+ import { runLink } from "./common-view.ts";
3
+ import { formatTime, truncate } from "./format.ts";
4
+ import { html, type SafeHtml } from "./html.ts";
5
+
6
+ function pct(value: number | null): string {
7
+ return value === null ? "–" : `${(value * 100).toFixed(1)}%`;
8
+ }
9
+
10
+ function kappa(value: number | null): string {
11
+ return value === null ? "–" : value.toFixed(3);
12
+ }
13
+
14
+ function renderMatrix(m: ConfusionMatrix): SafeHtml {
15
+ return html`<table class="matrix">
16
+ <thead><tr><th></th><th class="num">human done</th><th class="num">human not done</th></tr></thead>
17
+ <tbody>
18
+ <tr><th>judge pass</th><td class="num">${m.bothPass}</td><td class="num">${m.judgePassHumanFail}</td></tr>
19
+ <tr><th>judge fail</th><td class="num">${m.judgeFailHumanPass}</td><td class="num">${m.bothFail}</td></tr>
20
+ </tbody>
21
+ </table>`;
22
+ }
23
+
24
+ function renderHistory(history: readonly Calibration[]): SafeHtml {
25
+ if (history.length === 0) return html`<p class="muted">No stored calibration yet. Run <code>nexo eval judge</code> to store one.</p>`;
26
+ return html`<table class="runs">
27
+ <thead><tr><th>When (UTC)</th><th>Judge</th><th class="num">Cases</th><th class="num">Accuracy</th><th class="num">Cohen's κ</th></tr></thead>
28
+ <tbody>${history.map(
29
+ (c) => html`<tr><td class="mono">${formatTime(c.createdAt)}</td><td class="mono">${c.judgeKey}</td><td class="num">${c.cases}</td><td class="num">${pct(c.accuracy)}</td><td class="num">${kappa(c.kappa)}</td></tr>`,
30
+ )}</tbody>
31
+ </table>`;
32
+ }
33
+
34
+ /** The judge calibration view: current agreement with human verdicts, stored `nexo eval judge` results, disagreements. */
35
+ export function renderCalibration(data: JudgeCalibrationResponse): SafeHtml {
36
+ const current = data.current;
37
+ return html`<section>
38
+ <h2>Judge</h2>
39
+ ${data.judgeKey ? html`<p class="mono">${data.judgeKey}</p>` : html`<p class="warn">No judge is configured (models.judge). Stored results of every judge are listed below.</p>`}
40
+ ${data.warnings.map((w) => html`<p class="badge-line"><span class="badge badge-warn">same-family judge</span> ${w}</p>`)}
41
+ </section>
42
+ <section>
43
+ <h2>Agreement with human verdicts now</h2>
44
+ ${current === null
45
+ ? html`<p class="muted">Configure a judge to see its agreement.</p>`
46
+ : current.cases === 0
47
+ ? html`<p class="muted">No run has both a score from this judge and a human verdict yet. Review judged runs in the review queue.</p>`
48
+ : html`<div class="facts"><span>${current.cases} cases</span> · <span>accuracy ${pct(current.accuracy)}</span> · <span>Cohen's κ ${kappa(current.kappa)}</span></div>${renderMatrix(current.matrix)}`}
49
+ </section>
50
+ <section>
51
+ <h2>Stored calibrations</h2>
52
+ ${renderHistory(data.history)}
53
+ </section>
54
+ <section>
55
+ <h2>Disagreements</h2>
56
+ ${data.disagreements.length === 0
57
+ ? html`<p class="muted">The judge agrees with every human verdict.</p>`
58
+ : html`<ul class="disagreements">${data.disagreements.map(
59
+ (d) => html`<li><a href="${runLink(d.runId)}">${truncate(d.instruction.split("\n")[0] ?? "", 100) || d.runId}</a> — judge ${d.judgePassed ? "pass" : "fail"}, human ${d.verdict === "done" ? "done" : "not done"}${d.comment ? html` <span class="muted">“${truncate(d.comment, 160)}”</span>` : ""}</li>`,
60
+ )}</ul>`}
61
+ </section>`;
62
+ }
@@ -0,0 +1,102 @@
1
+ import type { LearnJobsResponse, Memory, PlaybookItem, PlaybookListResponse, PlaybookResponse } from "./api-types.ts";
2
+ import { runLink, statusBadge } from "./common-view.ts";
3
+ import { formatTime, truncate } from "./format.ts";
4
+ import { html, type SafeHtml } from "./html.ts";
5
+ import { type Page, pageParams } from "./pager.ts";
6
+
7
+ export const MEMORY_SCOPES_HINT = "user, global or skill:<name>";
8
+
9
+ /** One page of `/api/memories` with the filter form's values (empty values left out). */
10
+ export function memoriesQuery(scope: string, type: string, all: boolean, page: Page): string {
11
+ const params = new URLSearchParams();
12
+ if (scope.trim()) params.set("scope", scope.trim());
13
+ if (type) params.set("type", type);
14
+ if (all) params.set("all", "1");
15
+ return `/api/memories?${pageParams(page, params).toString()}`;
16
+ }
17
+
18
+ /** One page of `/api/learn/jobs`, newest first. */
19
+ export function jobsQuery(page: Page): string {
20
+ return `/api/learn/jobs?${pageParams(page).toString()}`;
21
+ }
22
+
23
+ function sourceBadge(source: string): SafeHtml {
24
+ const cls = /^[a-z]{1,16}$/.test(source) ? source : "other";
25
+ return html`<span class="badge source-${cls}">${source}</span>`;
26
+ }
27
+
28
+ function memoryState(m: Memory): SafeHtml | string {
29
+ if (m.retiredAt) return html`<span class="muted">retired ${formatTime(m.retiredAt)}</span>`;
30
+ if (m.supersededBy) return html`<span class="muted">replaced</span>`;
31
+ return "";
32
+ }
33
+
34
+ /** The memory table; live memories get a Retire button (`data-retire-memory`) and every row a History button. */
35
+ export function renderMemories(memories: readonly Memory[], readOnly: boolean): SafeHtml {
36
+ if (memories.length === 0) return html`<p class="muted">No memories match. Runs add them as they are reviewed and learned from; <code>nexo memory add</code> adds one by hand.</p>`;
37
+ return html`<table class="runs memories">
38
+ <thead><tr><th>Scope</th><th>Type</th><th>Source</th><th class="num">Importance</th><th>Memory</th><th>Created (UTC)</th><th>Last used</th><th></th></tr></thead>
39
+ <tbody>${memories.map(
40
+ (m) => html`<tr>
41
+ <td class="mono">${m.scope}</td><td>${m.type}</td><td>${sourceBadge(m.source)}</td><td class="num">${m.importance.toFixed(2)}</td>
42
+ <td>${m.content}${m.sourceRunId ? html` <a class="muted" href="${runLink(m.sourceRunId)}">run</a>` : ""} ${memoryState(m)}</td>
43
+ <td class="mono">${formatTime(m.createdAt)}</td><td class="mono">${formatTime(m.lastUsedAt)}</td>
44
+ <td class="actions"><button type="button" data-memory-history="${m.id}">History</button>${!readOnly && !m.retiredAt && !m.supersededBy ? html` <button type="button" class="danger" data-retire-memory="${m.id}">Retire</button>` : ""}</td>
45
+ </tr>`,
46
+ )}</tbody>
47
+ </table>`;
48
+ }
49
+
50
+ /** The replaced versions of a memory, newest first, under a heading that says which memory they belong to. */
51
+ export function renderMemoryHistory(memory: Memory, history: readonly Memory[]): SafeHtml {
52
+ const heading = html`<h3>History of “${truncate(memory.content, 80)}”</h3>`;
53
+ if (history.length === 0) return html`${heading}<p class="muted">This memory has not replaced an earlier one.</p>`;
54
+ return html`${heading}<ol class="history">${history.map((m) => html`<li><span class="mono">${formatTime(m.createdAt)}</span> ${sourceBadge(m.source)} ${m.content}</li>`)}</ol>`;
55
+ }
56
+
57
+ /** Links to each skill's playbook (`data-playbook`). */
58
+ export function renderPlaybookList(data: PlaybookListResponse): SafeHtml {
59
+ if (data.playbooks.length === 0) return html`<p class="muted">No playbook yet. The curator adds items after runs that used a skill; <code>nexo playbook add</code> adds a human one.</p>`;
60
+ return html`<ul class="playbook-list">${data.playbooks.map(
61
+ (p) => html`<li><button type="button" class="link" data-playbook="${p.skill}">${p.skill}</button> <span class="muted">${p.activeItems} item${p.activeItems === 1 ? "" : "s"}${p.version === null ? "" : ` · v${p.version} (${p.origin ?? "?"})`}</span></li>`,
62
+ )}</ul>`;
63
+ }
64
+
65
+ function itemHistory(item: PlaybookItem): SafeHtml {
66
+ return html`<details><summary>history (${item.history.length})</summary><ol class="history">${item.history.map(
67
+ (h) => html`<li><span class="mono">${formatTime(h.createdAt)}</span> ${h.action} by ${h.actor}${h.content ? html`: ${truncate(h.content, 200)}` : ""}${h.runId ? html` <a class="muted" href="${runLink(h.runId)}">run</a>` : ""}</li>`,
68
+ )}</ol></details>`;
69
+ }
70
+
71
+ /** One skill's playbook: items with source, helpful/harmful counters, history and a Retire button (`data-retire-item`), then the versions. */
72
+ export function renderPlaybook(data: PlaybookResponse, readOnly: boolean): SafeHtml {
73
+ return html`<h3>${data.skill}</h3>
74
+ ${data.items.length === 0
75
+ ? html`<p class="muted">No active items.</p>`
76
+ : html`<table class="runs playbook">
77
+ <thead><tr><th>Key</th><th>Source</th><th class="num">Helpful</th><th class="num">Harmful</th><th>Item</th><th></th></tr></thead>
78
+ <tbody>${data.items.map(
79
+ (i) => html`<tr${i.status === "retired" ? html` class="retired"` : ""}>
80
+ <td class="mono">${i.key}</td><td>${sourceBadge(i.source)}</td><td class="num">${i.helpful}</td><td class="num">${i.harmful}</td>
81
+ <td>${i.content}${i.status === "retired" ? html` <span class="muted">retired</span>` : ""}${itemHistory(i)}</td>
82
+ <td class="actions">${!readOnly && i.status === "active" ? html`<button type="button" class="danger" data-retire-item="${i.key}" data-skill="${data.skill}">Retire</button>` : ""}</td>
83
+ </tr>`,
84
+ )}</tbody>
85
+ </table>`}
86
+ <p class="muted">Versions: ${data.versions.length === 0 ? "none yet" : data.versions.map((v, n) => html`${n > 0 ? ", " : ""}v${v.version} (${v.origin}${v.status === "active" ? ", active" : ""})`)}</p>`;
87
+ }
88
+
89
+ /** Job counts and the newest jobs with their errors. */
90
+ export function renderJobs(data: LearnJobsResponse): SafeHtml {
91
+ const c = data.counts;
92
+ return html`<div class="facts"><span>${c.pending} pending</span> · <span>${c.running} running</span> · <span>${c.succeeded} succeeded</span> · <span>${c.failed} failed</span></div>
93
+ ${c.failed > 0 ? html`<p class="muted">Failed jobs with attempts left run again with <code>nexo learn --retry</code>.</p>` : ""}
94
+ ${data.jobs.length === 0
95
+ ? html`<p class="muted">No learn jobs yet.</p>`
96
+ : html`<table class="runs">
97
+ <thead><tr><th>Updated (UTC)</th><th>Run</th><th>Trigger</th><th>Status</th><th class="num">Attempts</th><th>Error</th></tr></thead>
98
+ <tbody>${data.jobs.map(
99
+ (j) => html`<tr><td class="mono">${formatTime(j.updatedAt)}</td><td><a class="mono" href="${runLink(j.runId)}">${j.runId}</a></td><td>${j.trigger.replace("_", " ")}</td><td>${statusBadge(j.status)}</td><td class="num">${j.attempts}</td><td>${j.lastError ? html`<strong>${j.lastError.code}</strong> ${truncate(j.lastError.message, 200)}` : ""}</td></tr>`,
100
+ )}</tbody>
101
+ </table>`}`;
102
+ }
@@ -0,0 +1,148 @@
1
+ import type { CaseScore, DiffLine, EvalCaseItem, OptimCandidate, OptimDetailResponse, OptimReport, OptimRunItem, PromotionState } from "./api-types.ts";
2
+ import { runLink, statusBadge } from "./common-view.ts";
3
+ import { formatTime, formatUsd, shortId, truncate } from "./format.ts";
4
+ import { html, type SafeHtml } from "./html.ts";
5
+ import { type Page, pageParams } from "./pager.ts";
6
+
7
+ function quality(value: number | null | undefined): string {
8
+ return value === null || value === undefined ? "–" : value.toFixed(3);
9
+ }
10
+
11
+ function version(v: number | null): string {
12
+ return v === null ? "–" : `v${v}`;
13
+ }
14
+
15
+ /** One page of `/api/optim`, newest first. */
16
+ export function optimQuery(page: Page): string {
17
+ return `/api/optim?${pageParams(page).toString()}`;
18
+ }
19
+
20
+ /** The optimizations table; each row opens its detail (`data-optim`). */
21
+ export function renderOptimList(runs: readonly OptimRunItem[]): SafeHtml {
22
+ if (runs.length === 0) return html`<p class="muted">No optimizations yet. Start one with <code>nexo optimize --target skill:&lt;name&gt;</code>.</p>`;
23
+ return html`<table class="runs optim">
24
+ <thead><tr><th>Started (UTC)</th><th>Target</th><th>Status</th><th>Stopped by</th><th class="num">Spent</th><th class="num">Rollouts</th><th>Holdout quality</th><th>Versions</th><th>Promotion</th></tr></thead>
25
+ <tbody>${runs.map(
26
+ (r) => html`<tr>
27
+ <td class="mono"><button type="button" class="link" data-optim="${r.id}">${formatTime(r.createdAt)}</button></td>
28
+ <td class="mono">${r.mode === "climb" ? "climb " : ""}${r.target}</td><td>${statusBadge(r.status)}${r.climbOutcome ? html` <span class="muted">${r.climbOutcome.replace("_", " ")}</span>` : ""}</td><td>${r.stopReason ?? "–"}</td>
29
+ <td class="num">${formatUsd(r.spentUsd)} of $${r.budgetUsd.toFixed(2)}</td><td class="num">${r.rollouts}</td>
30
+ <td>${r.holdoutBefore === null ? "–" : `${quality(r.holdoutBefore)} → ${quality(r.holdoutAfter)}`}</td>
31
+ <td>${version(r.baseVersion)} → ${version(r.bestVersion)}</td><td>${r.promotion ? r.promotion.replace("_", " ") : "–"}</td>
32
+ </tr>`,
33
+ )}</tbody>
34
+ </table>`;
35
+ }
36
+
37
+ function scoreCell(s: CaseScore): SafeHtml {
38
+ return html`${quality(s.quality)} <span class="muted">${formatUsd(s.costUsd)}</span>`;
39
+ }
40
+
41
+ function renderHoldout(report: OptimReport): SafeHtml {
42
+ const h = report.holdout;
43
+ return html`<h3>Holdout report</h3>
44
+ <p>Quality ${quality(h.before.quality)} → <strong>${quality(h.after.quality)}</strong>, cost per case ${formatUsd(h.before.costUsd)} → ${formatUsd(h.after.costUsd)}.
45
+ ${h.wins} win${h.wins === 1 ? "" : "s"}, ${h.losses} loss${h.losses === 1 ? "" : "es"}, ${h.ties} tie${h.ties === 1 ? "" : "s"}.
46
+ ${report.improved ? "" : html`<span class="muted">No candidate beat the starting version.</span>`}</p>
47
+ <table class="runs holdout"><thead><tr><th>Case</th><th>Before</th><th>After</th><th>Outcome</th></tr></thead>
48
+ <tbody>${h.cases.map((c) => html`<tr><td>${truncate(c.input, 120)}</td><td>${scoreCell(c.before)}</td><td>${scoreCell(c.after)}</td><td><span class="badge outcome-${c.outcome}">${c.outcome}</span></td></tr>`)}</tbody></table>
49
+ <p class="muted">Stopped by ${report.stopReason} after ${report.iterations} iteration${report.iterations === 1 ? "" : "s"} and ${report.rollouts} rollouts (${formatUsd(report.spentUsd)}); ${report.merges} merge${report.merges === 1 ? "" : "s"}${report.mergeNote ? ` (${report.mergeNote})` : ""}.</p>`;
50
+ }
51
+
52
+ /** The base → best text diff, one line per row. */
53
+ export function renderDiff(diff: readonly DiffLine[]): SafeHtml {
54
+ if (diff.every((d) => d.op === "same")) return html`<p class="muted">The best candidate is the starting text.</p>`;
55
+ return html`<pre class="diff">${diff.map((d) => html`<span class="${d.op === "add" ? "diff-add" : d.op === "del" ? "diff-del" : ""}">${d.op === "add" ? "+ " : d.op === "del" ? "- " : " "}${d.text}</span>`)}</pre>`;
56
+ }
57
+
58
+ function mean(scores: readonly CaseScore[]): string {
59
+ return scores.length === 0 ? "–" : quality(scores.reduce((s, x) => s + x.quality, 0) / scores.length);
60
+ }
61
+
62
+ const RATIONALE_CHARS = 160;
63
+
64
+ /** How an edit's prediction held up on the minibatch, and its rationale (clipped); empty without either. */
65
+ function predictionNote(minibatch: NonNullable<OptimCandidate["minibatch"]>): SafeHtml | "" {
66
+ const p = minibatch.prediction;
67
+ const why = minibatch.rationale ? (minibatch.rationale.length > RATIONALE_CHARS ? `${minibatch.rationale.slice(0, RATIONALE_CHARS - 1)}…` : minibatch.rationale) : "";
68
+ if (!p && !why) return "";
69
+ const check = p ? `fixes ${p.fixesHit}/${p.fixesPredicted} · risks ${p.atRiskHit}/${p.atRiskPredicted}${p.unpredictedRegressions > 0 ? ` · ${p.unpredictedRegressions} unpredicted` : ""}` : "";
70
+ return html`${check ? html`<div class="muted">${check}</div>` : ""}${why ? html`<div class="muted">${why}</div>` : ""}`;
71
+ }
72
+
73
+ /** Every candidate with its parents, minibatch comparison and pareto mean (the lineage). */
74
+ export function renderLineage(candidates: readonly OptimCandidate[]): SafeHtml {
75
+ return html`<table class="runs lineage">
76
+ <thead><tr><th>Candidate</th><th>Origin</th><th>Parents</th><th class="num">Iteration</th><th>Minibatch</th><th>Pareto mean</th><th>Version</th><th>Accepted</th></tr></thead>
77
+ <tbody>${candidates.map(
78
+ (c) => html`<tr>
79
+ <td class="mono">${shortId(c.id)}</td><td>${c.origin}${c.component ? ` · ${c.component}` : ""}</td>
80
+ <td class="mono">${c.parentIds.map(shortId).join(", ") || "–"}</td><td class="num">${c.iteration}</td>
81
+ <td>${c.minibatch ? html`${mean(c.minibatch.parent)} → ${mean(c.minibatch.child)}${predictionNote(c.minibatch)}` : "–"}</td>
82
+ <td>${c.meanScore === null ? "–" : html`${quality(c.meanScore)} <span class="muted">${formatUsd(c.meanCostUsd ?? 0)}</span>`}</td>
83
+ <td>${version(c.version)} ${c.artifactStatus ? html`<span class="muted">${c.artifactStatus}</span>` : ""}</td><td>${c.accepted ? "yes" : "no"}</td>
84
+ </tr>`,
85
+ )}</tbody>
86
+ </table>`;
87
+ }
88
+
89
+ function runsToReview(promotion: PromotionState): string[] {
90
+ const list = promotion.error?.context?.runsToReview;
91
+ return Array.isArray(list) ? list.filter((id): id is string => typeof id === "string") : [];
92
+ }
93
+
94
+ /** The evidence line and the Approve button (`data-approve`), or why approval is refused with the runs to review. */
95
+ export function renderApproval(data: OptimDetailResponse, readOnly: boolean): SafeHtml {
96
+ const e = data.report?.evidence;
97
+ const evidence = !e
98
+ ? ""
99
+ : e.humanScored
100
+ ? html`<p>Evidence: human verdicts only (judge-rubric candidates are scored against your done / not done verdicts).</p>`
101
+ : html`<p>Evidence: ${e.judgeOnly ? html`<strong>judge only</strong>` : "includes deterministic scorers"} · judge <span class="mono">${e.judgeKey ?? "none"}</span> · Cohen's κ ${data.promotion.kappa === null ? (e.kappa === null ? "–" : e.kappa.toFixed(2)) : data.promotion.kappa.toFixed(2)} (minimum ${e.minJudgeKappa}).</p>`;
102
+ if (data.run.promotion === "approved") return html`${evidence}<p>Approved ${formatTime(data.run.promotedAt)}. Roll back with <code>nexo optimize rollback ${data.run.id}</code>.</p>`;
103
+ if (data.promotion.allowed) {
104
+ return readOnly
105
+ ? html`${evidence}<p class="muted">The UI is read-only; approve with <code>nexo optimize approve ${data.run.id}</code>.</p>`
106
+ : html`${evidence}<p><button type="button" class="primary" data-approve="${data.run.id}">Approve ${version(data.run.bestVersion)}</button> makes it the active version and retires ${version(data.run.baseVersion)}.</p>`;
107
+ }
108
+ const review = runsToReview(data.promotion);
109
+ return html`${evidence}<div class="error" role="note"><strong>Cannot approve</strong> ${data.promotion.error?.message ?? ""}${data.promotion.error?.hint ? html`<div class="hint">${data.promotion.error.hint}</div>` : ""}</div>
110
+ ${review.length > 0 ? html`<p>Review these runs to calibrate the judge:</p><ul>${review.map((id) => html`<li><a href="${runLink(id)}">${id}</a></li>`)}</ul>` : ""}`;
111
+ }
112
+
113
+ /** The winner of a climb comparison in words (mirrors comparisonWinnerLabel of @nexo/optimize, which public/ cannot import). */
114
+ function comparisonWinner(c: { label: string; winner: "A" | "B" | "tie" }): string {
115
+ if (c.winner === "tie") return "tie";
116
+ if (c.label === "golden") return c.winner === "A" ? "baseline preferred" : "golden preferred";
117
+ return c.winner === "A" ? "child preferred" : "base preferred";
118
+ }
119
+
120
+ function renderClimb(climb: NonNullable<OptimReport["climb"]>): SafeHtml {
121
+ return html`<h3>Climb</h3>
122
+ <p>Case <span class="mono">${climb.caseId}</span> · ${climb.guardIds.length} guard${climb.guardIds.length === 1 ? "" : "s"} · outcome <strong>${climb.outcome.replace("_", " ")}</strong>.</p>
123
+ ${climb.critique ? html`<p class="muted">${climb.critique}</p>` : ""}
124
+ ${climb.comparisons.length === 0 ? "" : html`<table class="runs"><thead><tr><th>Comparison</th><th>Winner</th></tr></thead><tbody>${climb.comparisons.map((c) => html`<tr><td>${c.label}</td><td>${comparisonWinner(c)}</td></tr>`)}</tbody></table>`}`;
125
+ }
126
+
127
+ /** The proposed (mined) eval cases with Accept / Dismiss buttons. */
128
+ export function renderProposedCases(cases: readonly EvalCaseItem[], readOnly: boolean): SafeHtml {
129
+ if (cases.length === 0) return html`<p class="muted">No proposed eval cases. Mine some with <code>nexo eval mine --target &lt;target&gt;</code>.</p>`;
130
+ return html`<table><thead><tr><th>Target</th><th>Instruction</th><th>Runs</th><th>Proposed</th><th></th></tr></thead><tbody>${cases.map(
131
+ (c) => html`<tr><td>${c.target}</td><td>${truncate(c.input.split("\n")[0] ?? "", 100)}</td><td>${String(c.clusterSize)}</td><td>${formatTime(c.createdAt)}</td><td>${
132
+ readOnly ? "" : html`<button type="button" data-accept="${c.id}">Accept</button> <button type="button" data-dismiss="${c.id}">Dismiss</button>`
133
+ }</td></tr>`,
134
+ )}</tbody></table>`;
135
+ }
136
+
137
+ /** One optimization: header, holdout report, approval, diff and lineage. */
138
+ export function renderOptimDetail(data: OptimDetailResponse, readOnly: boolean): SafeHtml {
139
+ const r = data.run;
140
+ return html`<h2>${r.target} ${statusBadge(r.status)}</h2>
141
+ <p class="muted mono">${r.id} · ${version(r.baseVersion)} → ${version(r.bestVersion)} · ${formatUsd(r.spentUsd)} of $${r.budgetUsd.toFixed(2)} · ${r.rollouts} rollouts · seed ${r.seed}</p>
142
+ ${r.error ? html`<div class="error" role="alert"><strong>${r.error.code}</strong> ${r.error.message}</div>` : ""}
143
+ ${data.report?.climb ? renderClimb(data.report.climb) : ""}
144
+ ${data.report ? renderHoldout(data.report) : html`<p class="muted">No report: ${r.status === "running" ? "the optimization is still running" : "the optimization did not finish"}.</p>`}
145
+ ${renderApproval(data, readOnly)}
146
+ ${data.report ? html`<h3>Text diff</h3>${renderDiff(data.report.diff)}` : ""}
147
+ <h3>Lineage</h3>${renderLineage(data.candidates)}`;
148
+ }
@@ -0,0 +1,56 @@
1
+ import { html, type SafeHtml } from "./html.ts";
2
+
3
+ export const PAGE_SIZES = [25, 50, 100] as const;
4
+ export const DEFAULT_PAGE_SIZE = 25;
5
+
6
+ /** The page a list shows: rows skipped and rows per page. */
7
+ export interface Page {
8
+ offset: number;
9
+ limit: number;
10
+ }
11
+
12
+ export interface PageState extends Page {
13
+ /** Rows across every page, from the API. */
14
+ total: number;
15
+ }
16
+
17
+ export function pageCount(total: number, limit: number): number {
18
+ return Math.max(1, Math.ceil(total / limit));
19
+ }
20
+
21
+ /** Up to seven slots: every page of a short table; otherwise the first and last pages, the current one with its neighbours, and null for each gap. */
22
+ export function pageNumbers(current: number, count: number): (number | null)[] {
23
+ if (count <= 7) return Array.from({ length: count }, (_, i) => i + 1);
24
+ if (current <= 4) return [1, 2, 3, 4, 5, null, count];
25
+ if (current >= count - 3) return [1, null, count - 4, count - 3, count - 2, count - 1, count];
26
+ return [1, null, current - 1, current, current + 1, null, count];
27
+ }
28
+
29
+ /** Adds the page to query parameters: `limit` always, `offset` past the first page. */
30
+ export function pageParams(page: Page, params: URLSearchParams = new URLSearchParams()): URLSearchParams {
31
+ params.set("limit", String(page.limit));
32
+ if (page.offset > 0) params.set("offset", String(page.offset));
33
+ return params;
34
+ }
35
+
36
+ /**
37
+ * Page controls under a table: the row range, Previous, the page numbers, Next and the rows-per-page choice. Buttons carry
38
+ * `data-page-offset`; the select carries `data-page-size` (see pages/paging.ts). Empty for a table without rows.
39
+ */
40
+ export function renderPager(page: PageState): SafeHtml {
41
+ if (page.total === 0) return html``;
42
+ const count = pageCount(page.total, page.limit);
43
+ const current = Math.min(count, Math.floor(page.offset / page.limit) + 1);
44
+ const first = (current - 1) * page.limit;
45
+ const button = (offset: number, label: string, extra: SafeHtml | string, disabled: boolean): SafeHtml =>
46
+ html`<button type="button" data-page-offset="${offset}"${extra}${disabled ? html` disabled` : ""}>${label}</button>`;
47
+ return html`<nav class="pager" aria-label="Pages">
48
+ <span class="pager-range">${first + 1}–${Math.min(page.total, first + page.limit)} of ${page.total}</span>
49
+ ${button(Math.max(0, first - page.limit), "‹ Prev", html` aria-label="Previous page"`, current === 1)}
50
+ ${pageNumbers(current, count).map((n) =>
51
+ n === null ? html`<span class="pager-gap">…</span>` : button((n - 1) * page.limit, String(n), n === current ? html` aria-current="page"` : "", false),
52
+ )}
53
+ ${button(first + page.limit, "Next ›", html` aria-label="Next page"`, current === count)}
54
+ <label>Rows per page <select data-page-size>${PAGE_SIZES.map((s) => html`<option value="${s}"${s === page.limit ? html` selected` : ""}>${s}</option>`)}</select></label>
55
+ </nav>`;
56
+ }
@@ -0,0 +1,79 @@
1
+ // One polling loop for the run page. `refresh()` can be called at any time (a poll tick, a saved verdict): it cancels
2
+ // the pending tick, joins a refresh already in flight instead of starting a second one, and schedules at most one
3
+ // next tick. A failed refresh while polling retries with exponential backoff. Timers are injected, so this module
4
+ // stays free of DOM APIs and is tested under vitest.
5
+
6
+ /** Milliseconds between refreshes of a run that is still running. */
7
+ export const POLL_MS = 3000;
8
+
9
+ /** Longest wait between retries after failed refreshes. */
10
+ export const MAX_POLL_BACKOFF_MS = 30_000;
11
+
12
+ /** Delay before the next refresh: POLL_MS while healthy, doubling per consecutive failure up to MAX_POLL_BACKOFF_MS. */
13
+ export function pollDelay(failures: number, intervalMs: number = POLL_MS, maxMs: number = MAX_POLL_BACKOFF_MS): number {
14
+ return Math.min(maxMs, intervalMs * 2 ** Math.max(0, failures));
15
+ }
16
+
17
+ export interface PollerOptions {
18
+ /** Loads and renders once; resolves true while the run is still running (keep polling). */
19
+ task: () => Promise<boolean>;
20
+ onError: (error: unknown) => void;
21
+ setTimer: (callback: () => void, ms: number) => unknown;
22
+ clearTimer: (handle: unknown) => void;
23
+ intervalMs?: number;
24
+ maxBackoffMs?: number;
25
+ }
26
+
27
+ export interface Poller {
28
+ refresh(): Promise<void>;
29
+ }
30
+
31
+ export function createPoller(options: PollerOptions): Poller {
32
+ let timer: unknown = null;
33
+ let inFlight: Promise<void> | null = null;
34
+ let again = false;
35
+ let polling = false;
36
+ let failures = 0;
37
+
38
+ const schedule = (ms: number): void => {
39
+ timer = options.setTimer(() => {
40
+ timer = null;
41
+ void refresh();
42
+ }, ms);
43
+ };
44
+
45
+ const runOnce = async (): Promise<void> => {
46
+ do {
47
+ again = false;
48
+ try {
49
+ polling = await options.task();
50
+ failures = 0;
51
+ } catch (error) {
52
+ failures++;
53
+ try {
54
+ options.onError(error);
55
+ } catch {
56
+ // A failing error handler must not end the loop.
57
+ }
58
+ }
59
+ } while (again);
60
+ // Cleared in the same synchronous step as the schedule, so a refresh() can never see a finished loop as in flight.
61
+ inFlight = null;
62
+ if (polling) schedule(pollDelay(failures, options.intervalMs, options.maxBackoffMs));
63
+ };
64
+
65
+ const refresh = (): Promise<void> => {
66
+ if (timer !== null) {
67
+ options.clearTimer(timer);
68
+ timer = null;
69
+ }
70
+ if (inFlight) {
71
+ again = true;
72
+ return inFlight;
73
+ }
74
+ inFlight = runOnce();
75
+ return inFlight;
76
+ };
77
+
78
+ return { refresh };
79
+ }