@hexdecimal16/nexo 0.0.0-stage → 0.2.0

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 (208) 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 +77 -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 +261 -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/core/src/approval/classifier.js +152 -0
  20. package/core/src/config/load.js +283 -0
  21. package/core/src/config/schema.js +186 -0
  22. package/core/src/cost/admission.js +90 -0
  23. package/core/src/cost/budget.js +67 -0
  24. package/core/src/cost/pricing.js +53 -0
  25. package/core/src/engine/charged-completion.js +79 -0
  26. package/core/src/engine/errors.js +77 -0
  27. package/core/src/engine/mcp.js +11 -0
  28. package/core/src/engine/messages.js +86 -0
  29. package/core/src/engine/prompts.js +32 -0
  30. package/core/src/engine/provider-gate.js +33 -0
  31. package/core/src/engine/recorder.js +61 -0
  32. package/core/src/engine/run.js +1115 -0
  33. package/core/src/engine/semaphore.js +45 -0
  34. package/core/src/engine/spawn-tool.js +119 -0
  35. package/core/src/engine/task-graph.js +153 -0
  36. package/core/src/index.js +32 -0
  37. package/core/src/learn/caller.js +171 -0
  38. package/core/src/learn/context.js +112 -0
  39. package/core/src/learn/embedder.js +216 -0
  40. package/core/src/learn/job.js +196 -0
  41. package/core/src/learn/wiki.js +116 -0
  42. package/core/src/learn/worker.js +141 -0
  43. package/core/src/optimize/adapter.js +250 -0
  44. package/core/src/optimize/climb.js +338 -0
  45. package/core/src/optimize/mine.js +95 -0
  46. package/core/src/optimize/optimize.js +377 -0
  47. package/core/src/optimize/optimizer-run.js +67 -0
  48. package/core/src/optimize/reflect.js +100 -0
  49. package/core/src/optimize/scratchpad-wiki.js +69 -0
  50. package/core/src/providers/claude-p.js +363 -0
  51. package/core/src/providers/kiro-p.js +408 -0
  52. package/core/src/providers/models.js +10 -0
  53. package/core/src/scoring/calibration.js +31 -0
  54. package/core/src/scoring/continuation.js +24 -0
  55. package/core/src/scoring/runner.js +322 -0
  56. package/core/src/scoring/sources.js +88 -0
  57. package/core/src/session/lock.js +88 -0
  58. package/core/src/session/session.js +647 -0
  59. package/core/src/session/shell.js +26 -0
  60. package/core/src/session/transcript.js +86 -0
  61. package/core/src/settings/config-edit.js +472 -0
  62. package/core/src/settings/credentials.js +120 -0
  63. package/core/src/settings/doctor.js +103 -0
  64. package/core/src/settings/settings.js +265 -0
  65. package/mcp/src/hub.js +184 -0
  66. package/mcp/src/index.js +1 -0
  67. package/memory/src/curate.js +121 -0
  68. package/memory/src/index.js +4 -0
  69. package/memory/src/prompts.js +143 -0
  70. package/memory/src/retrieval.js +91 -0
  71. package/memory/src/similarity.js +47 -0
  72. package/optimize/src/engine.js +206 -0
  73. package/optimize/src/index.js +8 -0
  74. package/optimize/src/merge.js +73 -0
  75. package/optimize/src/novelty.js +37 -0
  76. package/optimize/src/pareto.js +83 -0
  77. package/optimize/src/proposer.js +148 -0
  78. package/optimize/src/report.js +107 -0
  79. package/optimize/src/rng.js +34 -0
  80. package/optimize/src/target.js +34 -0
  81. package/package.json +47 -4
  82. package/router/src/effort.js +5 -0
  83. package/router/src/escalation.js +171 -0
  84. package/router/src/index.js +4 -0
  85. package/router/src/registry.js +21 -0
  86. package/router/src/resolve.js +117 -0
  87. package/scorers/src/deterministic.js +194 -0
  88. package/scorers/src/family.js +48 -0
  89. package/scorers/src/index.js +6 -0
  90. package/scorers/src/judge.js +284 -0
  91. package/scorers/src/regex-worker.js +3 -0
  92. package/scorers/src/spec.js +147 -0
  93. package/scorers/src/trajectory.js +22 -0
  94. package/scorers/src/types.js +1 -0
  95. package/sdk/src/index.js +3 -0
  96. package/sdk/src/nexo.js +94 -0
  97. package/sdk/src/runtime.js +39 -0
  98. package/skills/bundled/browser/SKILL.md +57 -0
  99. package/skills/bundled/wiki/SKILL.md +73 -0
  100. package/skills/src/frontmatter.js +25 -0
  101. package/skills/src/index.js +3 -0
  102. package/skills/src/load-skill-tool.js +41 -0
  103. package/skills/src/loader.js +95 -0
  104. package/store/src/artifacts.js +124 -0
  105. package/store/src/budget-ledger.js +18 -0
  106. package/store/src/cost-report.js +46 -0
  107. package/store/src/cursor.js +35 -0
  108. package/store/src/db.js +83 -0
  109. package/store/src/errors.js +9 -0
  110. package/store/src/eval-cases.js +255 -0
  111. package/store/src/feedback.js +154 -0
  112. package/store/src/goldens.js +61 -0
  113. package/store/src/ids.js +6 -0
  114. package/store/src/index.js +25 -0
  115. package/store/src/judge-calibration.js +182 -0
  116. package/store/src/learn-jobs.js +145 -0
  117. package/store/src/memories.js +261 -0
  118. package/store/src/migrations/001_init.sql +81 -0
  119. package/store/src/migrations/002_feedback.sql +9 -0
  120. package/store/src/migrations/003_sessions.sql +19 -0
  121. package/store/src/migrations/004_scoring.sql +22 -0
  122. package/store/src/migrations/005_judge_calibration.sql +27 -0
  123. package/store/src/migrations/006_learning.sql +77 -0
  124. package/store/src/migrations/007_optimize.sql +55 -0
  125. package/store/src/migrations/008_mined_cases_and_climb.sql +46 -0
  126. package/store/src/mine.js +51 -0
  127. package/store/src/optim.js +291 -0
  128. package/store/src/paths.js +22 -0
  129. package/store/src/playbooks.js +199 -0
  130. package/store/src/reindex.js +143 -0
  131. package/store/src/run-dir.js +151 -0
  132. package/store/src/runs.js +310 -0
  133. package/store/src/scores.js +92 -0
  134. package/store/src/sessions.js +304 -0
  135. package/store/src/span-tree.js +98 -0
  136. package/store/src/spans.js +84 -0
  137. package/store/src/sql.js +13 -0
  138. package/store/src/workspace-copy.js +80 -0
  139. package/telemetry/src/errors.js +32 -0
  140. package/telemetry/src/index.js +3 -0
  141. package/telemetry/src/logger.js +39 -0
  142. package/telemetry/src/redact.js +106 -0
  143. package/tools/src/builtin.js +269 -0
  144. package/tools/src/change-tracker.js +57 -0
  145. package/tools/src/confine.js +101 -0
  146. package/tools/src/index.js +7 -0
  147. package/tools/src/leases.js +57 -0
  148. package/tools/src/policy.js +162 -0
  149. package/tools/src/read-only.js +338 -0
  150. package/tools/src/session-rules.js +140 -0
  151. package/tui/src/app.js +948 -0
  152. package/tui/src/approvals.js +96 -0
  153. package/tui/src/commands.js +38 -0
  154. package/tui/src/components.js +248 -0
  155. package/tui/src/index.js +5 -0
  156. package/tui/src/picker.js +78 -0
  157. package/tui/src/session-picker.js +100 -0
  158. package/tui/src/settings-screen.js +346 -0
  159. package/tui/src/text.js +70 -0
  160. package/tui/src/theme.js +44 -0
  161. package/web/public/cost.html +25 -0
  162. package/web/public/fonts/GeistMono-400.woff2 +0 -0
  163. package/web/public/fonts/GeistMono-600.woff2 +0 -0
  164. package/web/public/fonts/InstrumentSans-400.woff2 +0 -0
  165. package/web/public/fonts/InstrumentSans-600.woff2 +0 -0
  166. package/web/public/index.html +39 -0
  167. package/web/public/judge.html +21 -0
  168. package/web/public/learning.html +46 -0
  169. package/web/public/lib/api-types.ts +616 -0
  170. package/web/public/lib/common-view.ts +47 -0
  171. package/web/public/lib/cost-view.ts +35 -0
  172. package/web/public/lib/files-view.ts +90 -0
  173. package/web/public/lib/format.ts +35 -0
  174. package/web/public/lib/html.ts +51 -0
  175. package/web/public/lib/judge-view.ts +62 -0
  176. package/web/public/lib/learning-view.ts +102 -0
  177. package/web/public/lib/optim-view.ts +148 -0
  178. package/web/public/lib/pager.ts +56 -0
  179. package/web/public/lib/poller.ts +79 -0
  180. package/web/public/lib/run-view.ts +61 -0
  181. package/web/public/lib/runs-view.ts +87 -0
  182. package/web/public/lib/score-view.ts +94 -0
  183. package/web/public/lib/sessions-view.ts +28 -0
  184. package/web/public/lib/span-view.ts +90 -0
  185. package/web/public/lib/theme.ts +60 -0
  186. package/web/public/lib/timeline.ts +97 -0
  187. package/web/public/lib/wikis-view.ts +257 -0
  188. package/web/public/optim.html +30 -0
  189. package/web/public/pages/api.ts +60 -0
  190. package/web/public/pages/cost.ts +36 -0
  191. package/web/public/pages/judge.ts +15 -0
  192. package/web/public/pages/learning.ts +92 -0
  193. package/web/public/pages/optim.ts +68 -0
  194. package/web/public/pages/paging.ts +18 -0
  195. package/web/public/pages/run.ts +221 -0
  196. package/web/public/pages/runs.ts +91 -0
  197. package/web/public/pages/sessions.ts +25 -0
  198. package/web/public/pages/wikis.ts +103 -0
  199. package/web/public/run.html +36 -0
  200. package/web/public/sessions.html +28 -0
  201. package/web/public/style.css +288 -0
  202. package/web/public/wikis.html +25 -0
  203. package/web/src/api.js +682 -0
  204. package/web/src/http-errors.js +60 -0
  205. package/web/src/index.js +5 -0
  206. package/web/src/server.js +292 -0
  207. package/web/src/static.js +86 -0
  208. package/web/src/strip.js +22 -0
@@ -0,0 +1,61 @@
1
+ import type { Feedback, ReadOnlyInfo, RunDetailResponse, RunStatus, RunSummary } from "./api-types.ts";
2
+ import { renderError, runLink, sessionLink, stateClass, statusBadge, verdictBadge } from "./common-view.ts";
3
+ import { durationMs, formatDuration, formatTime, formatUsd, shortId, truncate } from "./format.ts";
4
+ import { html, type SafeHtml } from "./html.ts";
5
+
6
+ export function shouldPoll(status: RunStatus): boolean {
7
+ return status === "running";
8
+ }
9
+
10
+ export function renderRunHeader(detail: RunDetailResponse, nowMs: number): SafeHtml {
11
+ const { run, runJson } = detail;
12
+ const model = runJson?.model;
13
+ return html`<header class="run-header ${stateClass(run.status)}">
14
+ <div class="crumbs">${run.parentRunId ? html`<a href="${runLink(run.parentRunId)}">← parent run ${shortId(run.parentRunId)}</a>` : html`<a href="/">← runs</a>`}</div>
15
+ <h1>${truncate(run.instruction.split("\n")[0] ?? "", 200)}</h1>
16
+ <div class="facts">
17
+ ${statusBadge(run.status)} ${verdictBadge(run.verdict)}
18
+ <span class="mono">${run.id}</span>
19
+ <span>${formatTime(run.startedAt)} · ${formatDuration(durationMs(run.startedAt, run.endedAt, nowMs))}${run.status === "running" ? " so far" : ""}</span>
20
+ <span class="${run.costUnknown ? "warn" : ""}">${formatUsd(run.costUsd, run.costUnknown)}</span>
21
+ ${model ? html`<span class="mono">${model.provider}/${model.id} · effort ${model.effort} · source ${model.source}${model.role ? ` · ${model.role}` : ""}</span>` : ""}
22
+ ${run.skill ? html`<span>skill ${run.skill}</span>` : ""}
23
+ ${run.sessionId ? html`<span><a href="${sessionLink(run.sessionId)}">session ${truncate(run.sessionTitle || run.sessionId, 60)}</a>${run.turnIndex !== null ? ` · turn ${run.turnIndex}` : ""}</span>` : ""}
24
+ </div>
25
+ ${detail.dirMissing ? html`<div class="error" role="alert"><strong>Run directory missing</strong> The index still has this run, but its directory was deleted. Files and run.json are unavailable.<div class="hint">Run nexo reindex to drop runs whose directory is gone.</div></div>` : ""}
26
+ ${run.costUnknown ? html`<p class="warn">Some LLM calls in this run have no price; the cost shown leaves them out.</p>` : ""}
27
+ ${run.error ? renderError(run.error) : ""}
28
+ <details class="instruction"><summary>Instruction</summary><pre>${run.instruction}</pre></details>
29
+ ${runJson?.output ? html`<details class="output" open><summary>Output</summary><pre>${runJson.output}</pre></details>` : ""}
30
+ </header>`;
31
+ }
32
+
33
+ /** Done / not-done form for one run. A running run, or a read-only UI, gets a note instead of a form. */
34
+ export function renderFeedbackForm(run: RunSummary, latest: Feedback | undefined, readOnly: ReadOnlyInfo | null = null): SafeHtml {
35
+ if (run.status === "running") return html`<p class="muted">Review becomes available when this run finishes.</p>`;
36
+ if (readOnly) {
37
+ return html`<p class="warn">Verdicts are disabled: ${readOnly.message}.${readOnly.hint ? html` <span class="hint">${readOnly.hint}</span>` : ""}</p>`;
38
+ }
39
+ return html`<form class="feedback" data-feedback-run="${run.id}">
40
+ ${latest ? html`<p class="muted">Latest verdict: ${verdictBadge(latest.verdict)} ${formatTime(latest.createdAt)}${latest.comment ? html` · “${truncate(latest.comment, 200)}”` : ""}</p>` : ""}
41
+ <fieldset>
42
+ <legend>Was this run done?</legend>
43
+ <label><input type="radio" name="verdict" value="done" required> Done</label>
44
+ <label><input type="radio" name="verdict" value="not_done"> Not done</label>
45
+ </fieldset>
46
+ <label class="comment">Comment <textarea name="comment" rows="2" maxlength="10000" placeholder="What was missing or wrong?"></textarea></label>
47
+ <button type="submit">Save verdict</button>
48
+ <span class="form-status" aria-live="polite"></span>
49
+ </form>`;
50
+ }
51
+
52
+ export function renderChildren(children: RunSummary[], nowMs: number, readOnly: ReadOnlyInfo | null = null, latestByRun: Record<string, Feedback> = {}): SafeHtml {
53
+ if (children.length === 0) return html`<p class="muted">This run started no subagents.</p>`;
54
+ return html`<div class="children">${children.map(
55
+ (child) => html`<section class="child ${stateClass(child.status)}">
56
+ <h3><a href="${runLink(child.id)}">${truncate(child.instruction.split("\n")[0] ?? "", 120)}</a></h3>
57
+ <div class="facts">${statusBadge(child.status)} ${verdictBadge(child.verdict)} <span class="mono">${shortId(child.id)}</span> <span>${formatDuration(durationMs(child.startedAt, child.endedAt, nowMs))}</span> <span class="${child.costUnknown ? "warn" : ""}">${formatUsd(child.costUsd, child.costUnknown)}</span>${child.modelFinal ? html` <span class="mono">${child.modelFinal}</span>` : ""}</div>
58
+ ${renderFeedbackForm(child, latestByRun[child.id], readOnly)}
59
+ </section>`,
60
+ )}</div>`;
61
+ }
@@ -0,0 +1,87 @@
1
+ import type { RunStatus, RunSummary } from "./api-types.ts";
2
+ import { runLink, sessionLink, stateClass, statusBadge, verdictBadge } from "./common-view.ts";
3
+ import { durationMs, formatDuration, formatTime, formatUsd, truncate } from "./format.ts";
4
+ import { html, type SafeHtml } from "./html.ts";
5
+ import { type Page, pageParams } from "./pager.ts";
6
+ import { renderScoreCell } from "./score-view.ts";
7
+
8
+ export type RunsTab = "all" | "review";
9
+
10
+ export interface RunFilters {
11
+ tab: RunsTab;
12
+ status: string;
13
+ skill: string;
14
+ since: string;
15
+ /** Session id from the page's `?session=` parameter; empty for all runs. */
16
+ session: string;
17
+ /** "true" (scored runs), "false" (finished runs without scores) or "" (all). */
18
+ scored: string;
19
+ }
20
+
21
+ /** Filters from the page address: `?session=` picks a session's turns and `?tab=review` the review queue. */
22
+ export function readRunFilters(search: string): RunFilters {
23
+ const params = new URLSearchParams(search);
24
+ return { tab: params.get("tab") === "review" ? "review" : "all", status: "", skill: "", since: "", session: params.get("session") ?? "", scored: "" };
25
+ }
26
+
27
+ /** The search string that reopens the same tab and session, so a reload or the back button keeps them; empty for the default view. */
28
+ export function runsPageSearch(filters: RunFilters): string {
29
+ const params = new URLSearchParams();
30
+ if (filters.session) params.set("session", filters.session);
31
+ if (filters.tab === "review") params.set("tab", "review");
32
+ const query = params.toString();
33
+ return query ? `?${query}` : "";
34
+ }
35
+
36
+ /**
37
+ * API path for one page of the runs list. Without a session filter the list holds one-shot runs only; chat turns are
38
+ * listed per session. The review tab asks for finished runs without feedback, chat turns included.
39
+ */
40
+ export function runsQuery(filters: RunFilters, page: Page): string {
41
+ const params = new URLSearchParams();
42
+ if (filters.session) params.set("session", filters.session);
43
+ else if (filters.tab !== "review") params.set("oneShot", "true");
44
+ if (filters.tab === "review") params.set("reviewed", "false");
45
+ if (filters.status) params.set("status", filters.status);
46
+ if (filters.skill.trim()) params.set("skill", filters.skill.trim());
47
+ if (filters.since) params.set("since", filters.since);
48
+ if (filters.scored === "true" || filters.scored === "false") params.set("scored", filters.scored);
49
+ return `/api/runs?${pageParams(page, params).toString()}`;
50
+ }
51
+
52
+ export function renderRunRows(runs: RunSummary[], nowMs: number): SafeHtml {
53
+ return html`${runs.map(
54
+ (run) => html`<tr class="${stateClass(run.status)}">
55
+ <td class="mono">${formatTime(run.startedAt)}</td>
56
+ <td><a href="${runLink(run.id)}">${truncate(run.instruction.split("\n")[0] ?? "", 120)}</a>${run.childCount ? html` <span class="muted">· ${run.childCount} subagent${run.childCount === 1 ? "" : "s"}</span>` : ""}</td>
57
+ <td>${run.skill ?? html`<span class="muted">–</span>`}</td>
58
+ <td>${statusBadge(run.status)}</td>
59
+ <td class="mono">${run.modelFinal ?? "–"}</td>
60
+ <td class="num">${formatDuration(durationMs(run.startedAt, run.endedAt, nowMs))}</td>
61
+ <td class="num${run.costUnknown ? " warn" : ""}">${formatUsd(run.costUsd, run.costUnknown)}</td>
62
+ <td>${renderScoreCell(run.score)}</td>
63
+ <td>${verdictBadge(run.verdict)}</td>
64
+ </tr>`,
65
+ )}`;
66
+ }
67
+
68
+ /** The active session filter, with a link back to all runs; empty without one. */
69
+ export function renderSessionFilter(sessionId: string, title: string | null): SafeHtml {
70
+ if (!sessionId) return html``;
71
+ return html`<p class="session-filter">Turns of session <a class="mono" href="${sessionLink(sessionId)}">${title || sessionId}</a> <span class="muted mono">${sessionId}</span> · <a href="/">show all runs</a></p>`;
72
+ }
73
+
74
+ /** On the default view (all tabs, no session filter) chat turns are not listed; a muted line points to the Sessions page. */
75
+ export function renderRunsNote(filters: RunFilters): SafeHtml {
76
+ if (filters.session || filters.tab === "review") return html``;
77
+ return html`<p class="muted">Chat turns are listed per session on the <a href="/sessions.html">Sessions page</a>.</p>`;
78
+ }
79
+
80
+ /** `<option>`s for the status filter, from the statuses in `/api/meta`; the first option means any status. */
81
+ export function renderStatusOptions(statuses: readonly RunStatus[], selected: string): SafeHtml {
82
+ return html`<option value="">any</option>${statuses.map((s) => html`<option value="${s}"${s === selected ? html` selected` : ""}>${s.replace("_", " ")}</option>`)}`;
83
+ }
84
+
85
+ export function renderEmptyRuns(tab: RunsTab): SafeHtml {
86
+ return html`<tr><td colspan="9" class="empty">${tab === "review" ? "Nothing to review. Finished runs without a verdict appear here." : "No runs match these filters."}</td></tr>`;
87
+ }
@@ -0,0 +1,94 @@
1
+ import type { Escalation, RunScore, Score, Verdict } from "./api-types.ts";
2
+ import { formatTime, formatUsd } from "./format.ts";
3
+ import { html, type SafeHtml } from "./html.ts";
4
+
5
+ /** Badge class and mark for a pass/fail verdict; null (a score without a threshold) is neutral. */
6
+ function verdictMark(passed: boolean | null): { cls: string; mark: string; word: string } {
7
+ if (passed === null) return { cls: "score-neutral", mark: "–", word: "–" };
8
+ return passed ? { cls: "score-pass", mark: "✓", word: "pass" } : { cls: "score-fail", mark: "✗", word: "fail" };
9
+ }
10
+
11
+ /** `0.82 ✓` / `0.40 ✗` / `0.50 –` for a run's latest scoring round; `–` when never scored, `failed` when no scorer answered. */
12
+ export function renderScoreCell(score: RunScore | null): SafeHtml {
13
+ if (!score) return html`<span class="muted">–</span>`;
14
+ if (score.scorers === 0) {
15
+ const n = Math.max(1, score.failedScorers);
16
+ return html`<span class="badge warn" title="no scorer answered; the run itself may be fine">${n === 1 ? "scorer failed" : `${n} scorers failed`}</span>`;
17
+ }
18
+ const value = score.value === null ? "–" : score.value.toFixed(2);
19
+ const v = verdictMark(score.passed);
20
+ return html`<span class="badge ${v.cls}">${value} ${v.mark}</span>${score.failedScorers ? html` <span class="warn" title="scorers that failed">+${score.failedScorers} failed</span>` : ""}`;
21
+ }
22
+
23
+ /** The same-family pairs a judge score recorded in `details.sameFamily`. */
24
+ function sameFamily(score: Score): { judge: string; generator: string; family: string }[] {
25
+ const raw = score.details.sameFamily;
26
+ return Array.isArray(raw) ? (raw as { judge: string; generator: string; family: string }[]) : [];
27
+ }
28
+
29
+ interface Vote {
30
+ model: string;
31
+ score: number | null;
32
+ passed: boolean | null;
33
+ rationale?: string;
34
+ repaired?: boolean;
35
+ error?: string;
36
+ }
37
+
38
+ function renderVotes(score: Score): SafeHtml {
39
+ const votes = Array.isArray(score.details.votes) ? (score.details.votes as Vote[]) : [];
40
+ if (votes.length < 2 && !votes.some((v) => v.repaired)) return html``;
41
+ return html`<ul class="votes">${votes.map(
42
+ (v) => html`<li><span class="mono">${v.model}</span> ${v.score === null ? html`<span class="warn">failed: ${v.error ?? ""}</span>` : html`${v.score.toFixed(2)} ${v.passed ? "pass" : "fail"}`}${v.repaired ? html` <span class="muted">(after one repair)</span>` : ""}</li>`,
43
+ )}</ul>`;
44
+ }
45
+
46
+ function renderScore(score: Score): SafeHtml {
47
+ const family = sameFamily(score);
48
+ return html`<div class="score">
49
+ <div class="facts">
50
+ <strong>${score.scorerName}</strong>
51
+ <span class="kind">${score.scorerType}</span>
52
+ ${score.status === "failed"
53
+ ? html`<span class="badge score-failed">failed</span>`
54
+ : html`<span class="badge ${verdictMark(score.passed).cls}">${score.value === null ? "–" : score.value.toFixed(2)} ${verdictMark(score.passed).word}</span>`}
55
+ ${score.model ? html`<span class="mono">${score.model}</span>` : ""}
56
+ ${score.costUsd > 0 || score.costUnknown ? html`<span>${formatUsd(score.costUsd, score.costUnknown)}</span>` : ""}
57
+ ${family.length ? html`<span class="badge badge-warn" title="${family.map((f) => `${f.judge} and ${f.generator} are both ${f.family} models`).join("; ")}">same-family judge</span>` : ""}
58
+ </div>
59
+ ${score.error ? html`<div class="error"><strong>${score.error.code}</strong> ${score.error.message}${score.error.hint ? html`<div class="hint">${score.error.hint}</div>` : ""}</div>` : ""}
60
+ ${score.rationale ? html`<pre class="rationale">${score.rationale}</pre>` : ""}
61
+ ${score.criteria?.length ? html`<ul class="criteria">${score.criteria.map((c) => html`<li class="${c.passed ? "crit-pass" : "crit-fail"}">${c.passed ? "✓" : "✗"} <strong>${c.name}</strong> ${c.note}</li>`)}</ul>` : ""}
62
+ ${renderVotes(score)}
63
+ </div>`;
64
+ }
65
+
66
+ /**
67
+ * Scores of a run (the judge reasoning panel): the latest round in full, earlier rounds collapsed. A human verdict takes
68
+ * priority over every automatic score and is shown first; a judge that disagrees with it is flagged.
69
+ */
70
+ export function renderScores(scores: readonly Score[], verdict: Verdict | null, disagrees: boolean): SafeHtml {
71
+ if (scores.length === 0) return html`<p class="muted">No scorer ran for this run.</p>`;
72
+ const latest = Math.max(...scores.map((s) => s.round));
73
+ const earlier = [...new Set(scores.filter((s) => s.round < latest).map((s) => s.round))];
74
+ return html`${verdict ? html`<p class="human-priority">Human verdict: <strong>${verdict === "done" ? "done" : "not done"}</strong> — it takes priority over the automatic scores below.${disagrees ? html` <span class="badge badge-warn">judge disagrees</span>` : ""}</p>` : ""}
75
+ <div class="scores">${scores.filter((s) => s.round === latest).map(renderScore)}</div>
76
+ ${earlier.map(
77
+ (round) => html`<details class="score-round"><summary>Round ${round} (before escalation ${round + 1})</summary>${scores.filter((s) => s.round === round).map(renderScore)}</details>`,
78
+ )}`;
79
+ }
80
+
81
+ /** Escalation reasons: each trigger, whether it switched to S2, and why not when it was suppressed. */
82
+ export function renderEscalations(escalations: readonly Escalation[]): SafeHtml {
83
+ if (escalations.length === 0) return html`<p class="muted">The run stayed on its model.</p>`;
84
+ return html`<ul class="escalations">${escalations.map(
85
+ (e) => html`<li class="${e.applied ? "esc-applied" : "esc-blocked"}">
86
+ <span class="mono">${formatTime(e.at)}</span>
87
+ <strong>${e.trigger}</strong> <span class="kind">${e.phase.replaceAll("_", "-")}</span>
88
+ ${e.applied ? html`${e.from ?? "?"} → <span class="mono">${e.to ?? "?"}</span>` : html`<span class="warn">suppressed: ${e.blockedBy ?? "unknown"}</span>`}
89
+ <div class="muted">${e.reason}</div>
90
+ ${e.blockedReason ? html`<div class="muted">blocked: ${e.blockedReason}</div>` : ""}
91
+ ${e.continuationError ? html`<div class="error">continuation failed: <strong>${e.continuationError.code}</strong> ${e.continuationError.message}</div>` : ""}
92
+ </li>`,
93
+ )}</ul>`;
94
+ }
@@ -0,0 +1,28 @@
1
+ import type { SessionListItem } from "./api-types.ts";
2
+ import { runLink, sessionLink, statusBadge } from "./common-view.ts";
3
+ import { formatTime, formatUsd, truncate } from "./format.ts";
4
+ import { html, type SafeHtml } from "./html.ts";
5
+ import { type Page, pageParams } from "./pager.ts";
6
+
7
+ /** One table row per session; the title opens the session's turns, and unreviewed turns are highlighted. */
8
+ export function renderSessionRows(sessions: readonly SessionListItem[]): SafeHtml {
9
+ if (sessions.length === 0) {
10
+ return html`<tr><td colspan="7" class="empty">No sessions yet. Start one with <code>nexo</code>.</td></tr>`;
11
+ }
12
+ return html`${sessions.map(
13
+ (s) => html`<tr>
14
+ <td><a href="${sessionLink(s.id)}">${truncate(s.title, 80) || html`<span class="muted">(untitled)</span>`}</a></td>
15
+ <td>${statusBadge(s.status)}</td>
16
+ <td class="num">${s.turns}</td>
17
+ <td class="num">${formatUsd(s.costUsd)} of $${s.budgetUsd.toFixed(2)}</td>
18
+ <td class="num${s.unreviewedTurns > 0 ? " warn" : ""}">${s.unreviewedTurns}</td>
19
+ <td>${s.lastTurn ? html`<a href="${runLink(s.lastTurn.runId)}">${statusBadge(s.lastTurn.status)}</a> <span class="muted mono">${formatTime(s.lastTurn.startedAt)}</span>` : html`<span class="muted">–</span>`}</td>
20
+ <td class="mono">${formatTime(s.updatedAt)}</td>
21
+ </tr>`,
22
+ )}`;
23
+ }
24
+
25
+ /** API path for one page of sessions. */
26
+ export function sessionsQuery(page: Page): string {
27
+ return `/api/sessions?${pageParams(page).toString()}`;
28
+ }
@@ -0,0 +1,90 @@
1
+ import type { Span, SpanNode } from "./api-types.ts";
2
+ import { statusBadge } from "./common-view.ts";
3
+ import { durationMs, formatDuration, formatUsd, shortId } from "./format.ts";
4
+ import { html, prettyJson, type SafeHtml } from "./html.ts";
5
+
6
+ export function findSpan(roots: SpanNode[], id: string): SpanNode | undefined {
7
+ const stack = [...roots];
8
+ while (stack.length) {
9
+ const node = stack.pop() as SpanNode;
10
+ if (node.span.id === id) return node;
11
+ stack.push(...node.children);
12
+ }
13
+ return undefined;
14
+ }
15
+
16
+ function modelLabel(span: Span): string {
17
+ if (!span.model) return "";
18
+ const parts = [`${span.provider ?? "?"}/${span.model}`];
19
+ if (span.effort) parts.push(`effort ${span.effort}`);
20
+ if (span.modelSource) parts.push(`via ${span.modelSource}`);
21
+ return parts.join(" · ");
22
+ }
23
+
24
+ export function spanLine(span: Span, nowMs: number): SafeHtml {
25
+ const subagentRun = span.kind === "subagent" && typeof span.attrs.trajectoryId === "string" ? shortId(span.attrs.trajectoryId) : null;
26
+ return html`<span class="kind kind-${span.kind}">${span.kind}</span> <span class="span-name">${span.name}</span>${subagentRun ? html` <span class="muted mono">${subagentRun}</span>` : ""} ${statusBadge(span.status)} <span class="muted mono">${formatDuration(durationMs(span.startedAt, span.endedAt, nowMs))}${span.costUsd > 0 || span.costUnknown ? ` · ${formatUsd(span.costUsd, span.costUnknown)}` : ""}${span.model ? ` · ${modelLabel(span)}` : ""}</span>`;
27
+ }
28
+
29
+ /** Nested <details> list; nodes deeper than `openDepth` start collapsed. Each summary carries data-span-id; the selected span gets aria-current. */
30
+ export function renderSpanTree(roots: SpanNode[], nowMs: number, openDepth: number = 2, selectedId: string | null = null): SafeHtml {
31
+ const current = (id: string): SafeHtml | string => (id === selectedId ? html` aria-current="true"` : "");
32
+ const renderNode = (node: SpanNode, depth: number): SafeHtml => {
33
+ const line = spanLine(node.span, nowMs);
34
+ if (node.children.length === 0) {
35
+ return html`<li><button type="button" class="span-leaf" data-span-id="${node.span.id}"${current(node.span.id)}>${line}</button></li>`;
36
+ }
37
+ return html`<li><details${depth < openDepth || node.span.kind === "subagent" ? html` open` : ""}><summary data-span-id="${node.span.id}"${current(node.span.id)}>${line}</summary><ul>${node.children.map((c) => renderNode(c, depth + 1))}</ul></details></li>`;
38
+ };
39
+ if (roots.length === 0) return html`<p class="muted">No spans recorded.</p>`;
40
+ return html`<ul class="tree">${roots.map((r) => renderNode(r, 0))}</ul>`;
41
+ }
42
+
43
+ function fileButton(runId: string, path: string, label: string): SafeHtml {
44
+ return html`<button type="button" class="link" data-file-run="${runId}" data-file-path="${path}">${label}</button>`;
45
+ }
46
+
47
+ function renderContentBlocks(content: unknown): SafeHtml {
48
+ if (!Array.isArray(content)) return html`<pre>${prettyJson(content)}</pre>`;
49
+ return html`${content.map((block: unknown) => {
50
+ const b = (block ?? {}) as Record<string, unknown>;
51
+ if (b.type === "text") return html`<div class="msg msg-text"><div class="msg-label">assistant</div><pre>${String(b.text ?? "")}</pre></div>`;
52
+ if (b.type === "thinking") return html`<div class="msg msg-thinking"><div class="msg-label">thinking${b.redacted ? " (redacted)" : ""}</div><pre>${String(b.thinking ?? "")}</pre></div>`;
53
+ if (b.type === "toolCall") return html`<div class="msg msg-tool"><div class="msg-label">tool call · ${String(b.name ?? "")}</div><pre>${prettyJson(b.arguments)}</pre></div>`;
54
+ return html`<pre>${prettyJson(b)}</pre>`;
55
+ })}`;
56
+ }
57
+
58
+ const SHOWN_ATTRS = new Set(["content", "args", "result", "reason", "trigger", "instruction", "errorMessage"]);
59
+
60
+ /** Fields, messages, tool input and output, and remaining attributes of one span. */
61
+ export function renderSpanDetail(span: Span, attrsTruncated: boolean, nowMs: number): SafeHtml {
62
+ const a = span.attrs;
63
+ const rest = Object.fromEntries(Object.entries(a).filter(([k, v]) => !SHOWN_ATTRS.has(k) && v !== undefined && v !== null));
64
+ const rows: [string, unknown][] = [
65
+ ["kind", span.kind],
66
+ ["status", span.status],
67
+ ["started", span.startedAt],
68
+ ["duration", formatDuration(durationMs(span.startedAt, span.endedAt, nowMs)) + (span.endedAt === null ? " (running)" : "")],
69
+ ["queued", span.queuedMs === null ? null : formatDuration(span.queuedMs)],
70
+ ["model", span.model ? `${span.provider ?? "?"}/${span.model}` : null],
71
+ ["tier", span.tier],
72
+ ["effort", span.effort],
73
+ ["model source", span.modelSource],
74
+ ["tokens", span.tokensIn || span.tokensOut ? `${span.tokensIn} in · ${span.tokensOut} out · ${span.cacheRead} cache read · ${span.cacheWrite} cache write` : null],
75
+ ["cost", span.costUsd > 0 || span.costUnknown ? formatUsd(span.costUsd, span.costUnknown) : null],
76
+ ];
77
+ return html`<div class="span-detail">
78
+ <h3>${span.name}</h3>
79
+ <dl>${rows.filter(([, v]) => v !== null && v !== undefined && v !== "").map(([k, v]) => html`<dt>${k}</dt><dd>${String(v)}</dd>`)}</dl>
80
+ ${attrsTruncated ? html`<p class="note">Long values are shortened here. <button type="button" class="link" data-full-span="${span.id}">Load the full span</button></p>` : ""}
81
+ ${typeof a.reason === "string" || typeof a.trigger === "string" ? html`<div class="msg msg-escalation"><div class="msg-label">reason${typeof a.trigger === "string" ? ` · trigger ${a.trigger}` : ""}</div><pre>${String(a.reason ?? "")}</pre></div>` : ""}
82
+ ${typeof a.errorMessage === "string" ? html`<div class="msg msg-error"><div class="msg-label">error</div><pre>${a.errorMessage}</pre></div>` : ""}
83
+ ${typeof a.instruction === "string" ? html`<div class="msg"><div class="msg-label">instruction</div><pre>${a.instruction}</pre></div>` : ""}
84
+ ${a.content !== undefined ? renderContentBlocks(a.content) : ""}
85
+ ${a.args !== undefined ? html`<div class="msg msg-tool"><div class="msg-label">input</div><pre>${prettyJson(a.args)}</pre></div>` : ""}
86
+ ${typeof a.result === "string" ? html`<div class="msg msg-result"><div class="msg-label">output</div><pre>${a.result}</pre></div>` : ""}
87
+ ${span.payloadRef ? html`<p class="note">Full payload stored in ${fileButton(span.runId, span.payloadRef, span.payloadRef)}</p>` : ""}
88
+ ${Object.keys(rest).length ? html`<details><summary>attributes</summary><pre>${prettyJson(rest)}</pre></details>` : ""}
89
+ </div>`;
90
+ }
@@ -0,0 +1,60 @@
1
+ // Marks the current page in the nav and cycles the theme: system, light, dark. The choice is kept in localStorage.
2
+
3
+ const KEY = 'nexo-theme';
4
+ type Choice = 'system' | 'light' | 'dark';
5
+ const ORDER: readonly Choice[] = ['system', 'light', 'dark'];
6
+
7
+ function read(): Choice {
8
+ try {
9
+ const value = localStorage.getItem(KEY);
10
+ return value === 'light' || value === 'dark' ? value : 'system';
11
+ } catch {
12
+ return 'system';
13
+ }
14
+ }
15
+
16
+ function apply(choice: Choice): void {
17
+ if (choice === 'system') delete document.documentElement.dataset.theme;
18
+ else document.documentElement.dataset.theme = choice;
19
+ }
20
+
21
+ function markActive(nav: Element): void {
22
+ const path = location.pathname;
23
+ const target = path === '/' || path === '/index.html' || path === '/run.html' ? '/' : path;
24
+ for (const a of nav.querySelectorAll('a:not(.brand)')) {
25
+ if (a.getAttribute('href') === target) a.setAttribute('aria-current', 'page');
26
+ }
27
+ }
28
+
29
+ function addToggle(nav: Element): void {
30
+ let choice = read();
31
+ const button = document.createElement('button');
32
+ button.type = 'button';
33
+ button.className = 'theme-toggle';
34
+ const label = (): void => {
35
+ button.textContent = `theme: ${choice}`;
36
+ button.setAttribute('aria-label', `Theme: ${choice}. Activate to change.`);
37
+ };
38
+ button.addEventListener('click', () => {
39
+ choice = ORDER[(ORDER.indexOf(choice) + 1) % ORDER.length] ?? 'system';
40
+ apply(choice);
41
+ try {
42
+ if (choice === 'system') localStorage.removeItem(KEY);
43
+ else localStorage.setItem(KEY, choice);
44
+ } catch {
45
+ // Storage can be unavailable; the choice then lasts for this page only.
46
+ }
47
+ label();
48
+ });
49
+ label();
50
+ nav.append(button);
51
+ }
52
+
53
+ apply(read());
54
+ const nav = document.querySelector('nav.top');
55
+ if (nav) {
56
+ markActive(nav);
57
+ addToggle(nav);
58
+ }
59
+
60
+ export {};
@@ -0,0 +1,97 @@
1
+ import type { SpanNode } from "./api-types.ts";
2
+ import { durationMs, formatDuration, formatUsd, shortId } from "./format.ts";
3
+ import { html, type SafeHtml } from "./html.ts";
4
+
5
+ export interface TimelineRow {
6
+ spanId: string;
7
+ label: string;
8
+ runId: string | null;
9
+ depth: number;
10
+ startMs: number;
11
+ queuedMs: number;
12
+ durationMs: number;
13
+ costUsd: number;
14
+ status: string;
15
+ running: boolean;
16
+ }
17
+
18
+ export interface Timeline {
19
+ rows: TimelineRow[];
20
+ originMs: number;
21
+ totalMs: number;
22
+ }
23
+
24
+ /** Gantt rows: the top-level run span, then every subagent span at any depth in start order. */
25
+ export function timelineRows(roots: SpanNode[], nowMs: number): Timeline {
26
+ const rows: TimelineRow[] = [];
27
+ const visit = (node: SpanNode, depth: number): void => {
28
+ const span = node.span;
29
+ const isRun = span.kind === "run" && depth === 0;
30
+ if (isRun || span.kind === "subagent") {
31
+ const child = span.attrs.trajectoryId;
32
+ const childCost = span.attrs.childCostUsd;
33
+ rows.push({
34
+ spanId: span.id,
35
+ label: isRun ? "run" : `${span.name}${typeof child === "string" ? ` · ${shortId(child)}` : ""}`,
36
+ runId: isRun ? span.runId : typeof child === "string" ? child : null,
37
+ depth: isRun ? 0 : depth + 1,
38
+ startMs: Date.parse(span.startedAt),
39
+ queuedMs: span.queuedMs ?? 0,
40
+ durationMs: durationMs(span.startedAt, span.endedAt, nowMs),
41
+ costUsd: typeof childCost === "number" ? childCost : span.costUsd,
42
+ status: span.status,
43
+ running: span.endedAt === null,
44
+ });
45
+ }
46
+ for (const c of node.children) visit(c, span.kind === "subagent" ? depth + 1 : depth);
47
+ };
48
+ for (const root of roots) visit(root, 0);
49
+ if (rows.length === 0) return { rows, originMs: 0, totalMs: 0 };
50
+ const originMs = Math.min(...rows.map((r) => r.startMs - r.queuedMs));
51
+ const endMs = Math.max(...rows.map((r) => r.startMs + r.durationMs));
52
+ return { rows, originMs, totalMs: Math.max(1, endMs - originMs) };
53
+ }
54
+
55
+ const WIDTH = 1000;
56
+
57
+ function scaled(ms: number, total: number): string {
58
+ return ((ms / total) * WIDTH).toFixed(1);
59
+ }
60
+
61
+ const TICK_STEPS_MS = [1e3, 2e3, 5e3, 1e4, 3e4, 6e4, 12e4, 3e5, 6e5, 18e5, 36e5];
62
+ const MAX_TICKS = 60;
63
+
64
+ /** Gridline spacing for a timeline of `totalMs`: the first round step that gives at most 10 intervals. */
65
+ export function tickStepMs(totalMs: number): number {
66
+ return TICK_STEPS_MS.find((step) => totalMs / step <= 10) ?? 36e5;
67
+ }
68
+
69
+ function renderTicks(totalMs: number): SafeHtml {
70
+ const step = tickStepMs(totalMs);
71
+ const xs: string[] = [];
72
+ for (let t = step; t < totalMs && xs.length < MAX_TICKS; t += step) xs.push(scaled(t, totalMs));
73
+ return html`${xs.map((x) => html`<line class="tl-tick" x1="${x}" x2="${x}" y1="0" y2="10"></line>`)}`;
74
+ }
75
+
76
+ /** One SVG bar per row over a shared time grid, with a ruler above and a cap on running rows (geometry in attributes, so the page CSP needs no inline styles). The selected span's label gets aria-current. */
77
+ export function renderTimeline(timeline: Timeline, selectedId: string | null = null): SafeHtml {
78
+ if (timeline.rows.length === 0) return html`<p class="muted">No run spans recorded yet.</p>`;
79
+ const ticks = renderTicks(timeline.totalMs);
80
+ return html`<div class="timeline"><div class="tl-scale"><span></span><span><span>0s</span><span>${formatDuration(timeline.totalMs)}</span></span><span></span></div>${timeline.rows.map((row) => {
81
+ const queueStart = row.startMs - row.queuedMs - timeline.originMs;
82
+ const runStart = row.startMs - timeline.originMs;
83
+ const runX = scaled(runStart, timeline.totalMs);
84
+ const runW = scaled(Math.max(row.durationMs, timeline.totalMs / WIDTH), timeline.totalMs);
85
+ const headX = Math.max(0, Number(runX) + Number(runW) - 3).toFixed(1);
86
+ return html`<div class="tl-row">
87
+ <button type="button" class="tl-label depth-${Math.min(row.depth, 6)}" data-span-id="${row.spanId}"${row.spanId === selectedId ? html` aria-current="true"` : ""}>${row.label}</button>
88
+ <svg class="tl-bar" viewBox="0 0 ${WIDTH} 10" preserveAspectRatio="none" role="img" aria-label="${row.label}">
89
+ ${ticks}
90
+ ${row.queuedMs > 0 ? html`<rect class="tl-queue" x="${scaled(queueStart, timeline.totalMs)}" y="2" width="${scaled(row.queuedMs, timeline.totalMs)}" height="6"></rect>` : ""}
91
+ <rect class="tl-run tl-${row.running ? "running" : row.status}" x="${runX}" y="0" width="${runW}" height="10"></rect>
92
+ ${row.running ? html`<rect class="tl-head" x="${headX}" y="0" width="3" height="10"></rect>` : ""}
93
+ </svg>
94
+ <span class="tl-meta mono">${row.queuedMs > 0 ? `queued ${formatDuration(row.queuedMs)} · ` : ""}${formatDuration(row.durationMs)}${row.running ? " (running)" : ""} · ${formatUsd(row.costUsd)}</span>
95
+ </div>`;
96
+ })}</div>`;
97
+ }