@hexdecimal16/nexo 0.2.2 → 0.3.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.
@@ -0,0 +1,91 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createInterface } from "node:readline";
3
+ /** How long a process group gets between SIGTERM and SIGKILL after an abort. */
4
+ const KILL_GRACE_MS = 2_000;
5
+ const isWindows = process.platform === "win32";
6
+ const liveGroups = new Set();
7
+ let exitHandlerRegistered = false;
8
+ function killLiveGroups() {
9
+ for (const pgid of liveGroups) {
10
+ try {
11
+ process.kill(-pgid, "SIGKILL");
12
+ }
13
+ catch {
14
+ // the process group already exited
15
+ }
16
+ }
17
+ liveGroups.clear();
18
+ }
19
+ function signalGroup(child, sig) {
20
+ try {
21
+ if (!isWindows && child.pid !== undefined)
22
+ process.kill(-child.pid, sig);
23
+ else
24
+ child.kill(sig);
25
+ }
26
+ catch {
27
+ // the process group already exited
28
+ }
29
+ }
30
+ /**
31
+ * Spawns `command` in its own process group. On abort the whole group gets SIGTERM (SIGKILL after a grace period), and
32
+ * `lines` and `exit` settle at once instead of waiting for the pipes to close: the CLIs we run start helpers of their
33
+ * own, and one that outlives the signal would otherwise hold the pipes open and keep the caller waiting. The groups
34
+ * are also killed when the host exits.
35
+ */
36
+ export function spawnGroup(command, request) {
37
+ const { args, stdin, cwd, signal, onStderr } = request;
38
+ const child = spawn(command, args, { cwd, stdio: ["pipe", "pipe", "pipe"], detached: !isWindows });
39
+ const pgid = child.pid;
40
+ if (pgid !== undefined && !isWindows) {
41
+ if (!exitHandlerRegistered) {
42
+ exitHandlerRegistered = true;
43
+ process.on("exit", killLiveGroups);
44
+ }
45
+ liveGroups.add(pgid);
46
+ }
47
+ let stderr = "";
48
+ child.stderr.setEncoding("utf8");
49
+ child.stderr.on("data", (chunk) => {
50
+ if (stderr.length < 16_384)
51
+ stderr += chunk;
52
+ onStderr?.(chunk);
53
+ });
54
+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
55
+ let finish;
56
+ const exit = new Promise((resolve) => {
57
+ finish = resolve;
58
+ });
59
+ let killTimer;
60
+ const cleanup = () => {
61
+ if (pgid !== undefined)
62
+ liveGroups.delete(pgid);
63
+ if (killTimer)
64
+ clearTimeout(killTimer);
65
+ signal?.removeEventListener("abort", onAbort);
66
+ };
67
+ const onAbort = () => {
68
+ signalGroup(child, "SIGTERM");
69
+ killTimer = setTimeout(() => signalGroup(child, "SIGKILL"), KILL_GRACE_MS);
70
+ killTimer.unref();
71
+ child.stdout.destroy();
72
+ child.stderr.destroy();
73
+ lines.close();
74
+ finish({ code: null, stderr });
75
+ };
76
+ child.on("error", (error) => {
77
+ cleanup();
78
+ finish({ code: null, stderr: stderr || error.message });
79
+ });
80
+ child.on("close", (code) => {
81
+ cleanup();
82
+ finish({ code, stderr });
83
+ });
84
+ child.stdin.on("error", () => { });
85
+ child.stdin.end(stdin);
86
+ if (signal?.aborted)
87
+ onAbort();
88
+ else
89
+ signal?.addEventListener("abort", onAbort, { once: true });
90
+ return { lines, exit };
91
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hexdecimal16/nexo",
3
- "version": "0.2.2",
3
+ "version": "0.3.1",
4
4
  "description": "nexo agent engine",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "repository": {
package/sdk/src/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { checkSetup, createNexo } from "./nexo.js";
2
2
  export { createRuntime, openLogger } from "./runtime.js";
3
3
  export { NexoError } from "../../telemetry/src/index.js";
4
+ export { trackRunTree } from "./run-tree.js";
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Folds engine events into a tree of runs with status, cost, tool count and error per node, so callers do not have to
3
+ * rebuild the subagent hierarchy from the flat event stream. `onChange` fires after every update of a node.
4
+ */
5
+ export function trackRunTree(onChange) {
6
+ const nodes = new Map();
7
+ const roots = [];
8
+ const update = (runId, apply) => {
9
+ const node = nodes.get(runId);
10
+ if (!node)
11
+ return;
12
+ apply(node);
13
+ onChange?.(node);
14
+ };
15
+ return {
16
+ onEvent(event) {
17
+ switch (event.type) {
18
+ case "run_start": {
19
+ const node = {
20
+ runId: event.runId,
21
+ parentRunId: event.parentRunId,
22
+ taskId: event.taskId ?? null,
23
+ depth: event.depth,
24
+ instruction: event.instruction,
25
+ model: event.model,
26
+ effort: event.effort,
27
+ status: "running",
28
+ costUsd: 0,
29
+ toolCalls: 0,
30
+ currentTool: null,
31
+ error: null,
32
+ startedAt: Date.now(),
33
+ endedAt: null,
34
+ children: [],
35
+ };
36
+ nodes.set(node.runId, node);
37
+ const parent = event.parentRunId ? nodes.get(event.parentRunId) : undefined;
38
+ if (parent)
39
+ parent.children.push(node);
40
+ else
41
+ roots.push(node);
42
+ onChange?.(node);
43
+ break;
44
+ }
45
+ case "tool_start":
46
+ update(event.runId, (n) => {
47
+ n.toolCalls++;
48
+ n.currentTool = event.toolName;
49
+ });
50
+ break;
51
+ case "tool_end":
52
+ update(event.runId, (n) => {
53
+ n.currentTool = null;
54
+ });
55
+ break;
56
+ case "llm_end":
57
+ update(event.runId, (n) => {
58
+ n.costUsd += event.costUsd;
59
+ });
60
+ break;
61
+ case "run_end":
62
+ update(event.runId, (n) => {
63
+ n.status = event.status;
64
+ n.costUsd = event.costUsd;
65
+ n.currentTool = null;
66
+ n.error = event.error ?? null;
67
+ n.endedAt = Date.now();
68
+ });
69
+ break;
70
+ default:
71
+ break;
72
+ }
73
+ },
74
+ roots: () => roots,
75
+ get: (runId) => nodes.get(runId),
76
+ reset() {
77
+ nodes.clear();
78
+ roots.length = 0;
79
+ },
80
+ };
81
+ }
@@ -5,10 +5,19 @@ import { StringDecoder } from "node:string_decoder";
5
5
  import { NexoError } from "../../telemetry/src/index.js";
6
6
  import { Type } from "typebox";
7
7
  import { canonicalPath, nexoHomeGuard, resolveConfined, SECRET_PATH } from "./confine.js";
8
+ import { htmlToText, looksLikeHtml } from "./html-text.js";
8
9
  export const MAX_BASH_OUTPUT_BYTES = 1_000_000;
9
10
  const MAX_READ_LINES = 2000;
10
11
  const MAX_FETCH_CHARS = 100_000;
11
12
  const FETCH_TIMEOUT_MS = 30_000;
13
+ /** Most of a response body read before conversion; the converted text is then capped at MAX_FETCH_CHARS. */
14
+ const MAX_FETCH_RAW_CHARS = 2_000_000;
15
+ const FETCH_USER_AGENT = "Mozilla/5.0 (compatible; nexo)";
16
+ const FETCH_ACCEPT = "text/markdown;q=1.0, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1";
17
+ /** True for content types whose body is text an agent can read. */
18
+ function isTextualMime(mime) {
19
+ return mime.startsWith("text/") || /json|xml|javascript|yaml|markdown/.test(mime);
20
+ }
12
21
  const MAX_READ_BATCH = 20;
13
22
  /** Paths with this prefix open the run's saved large tool outputs (`tool_outputs/` in the run directory) with `read`. */
14
23
  export const TOOL_OUTPUT_PREFIX = "@tool_outputs/";
@@ -251,17 +260,35 @@ export function createBuiltinTools(ctx) {
251
260
  const webFetch = {
252
261
  name: "web_fetch",
253
262
  label: "Fetch URL",
254
- description: "Fetch an http(s) URL and return the response body as text.",
263
+ description: `Fetch an http(s) URL and return readable text. HTML pages are converted to plain text with links kept as [text](url); scripts, styles, navigation and footers are dropped. Markdown is requested first, so sites that serve it return it unchanged. Output is capped at ${MAX_FETCH_CHARS} characters. Binary files are refused. If a site blocks the fetch (for example a Cloudflare challenge), load the browser skill and read the page there.`,
255
264
  parameters: FetchParams,
256
265
  execute: async (_id, params, signal) => {
257
266
  const url = new URL(params.url);
258
267
  if (url.protocol !== "http:" && url.protocol !== "https:")
259
268
  throw new Error(`Only http and https URLs are allowed: ${params.url}`);
260
269
  const signals = [AbortSignal.timeout(FETCH_TIMEOUT_MS), ...(signal ? [signal] : [])];
261
- const response = await (ctx.fetch ?? fetch)(url.toString(), { signal: AbortSignal.any(signals) });
262
- const body = (await response.text()).slice(0, MAX_FETCH_CHARS);
263
- if (!response.ok)
264
- return textResult(`HTTP ${response.status} for ${params.url}\n${body}`, true);
270
+ const combined = AbortSignal.any(signals);
271
+ const get = (userAgent) => (ctx.fetch ?? fetch)(url.toString(), {
272
+ signal: combined,
273
+ headers: { "User-Agent": userAgent, Accept: FETCH_ACCEPT, "Accept-Language": "en-US,en;q=0.9" },
274
+ });
275
+ const challenged = (r) => r.status === 403 && r.headers.get("cf-mitigated") === "challenge";
276
+ let response = await get(FETCH_USER_AGENT);
277
+ // Some challenges let a plain client through when it does not pose as a browser.
278
+ if (challenged(response))
279
+ response = await get("nexo");
280
+ const mime = (response.headers.get("content-type") ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
281
+ if (mime && !isTextualMime(mime))
282
+ return textResult(`Unsupported content type ${mime} for ${params.url}; fetch only reads text.`, true);
283
+ const raw = (await response.text()).slice(0, MAX_FETCH_RAW_CHARS);
284
+ const isHtml = mime === "text/html" || mime === "application/xhtml+xml" || (mime === "" && looksLikeHtml(raw));
285
+ let body = isHtml ? htmlToText(raw) : raw;
286
+ if (body.length > MAX_FETCH_CHARS)
287
+ body = `${body.slice(0, MAX_FETCH_CHARS)}\n[truncated at ${MAX_FETCH_CHARS} characters]`;
288
+ if (!response.ok) {
289
+ const hint = challenged(response) ? "\nThe site served a bot challenge. Load the browser skill and open the page there." : "";
290
+ return textResult(`HTTP ${response.status} for ${params.url}\n${body}${hint}`, true);
291
+ }
265
292
  return textResult(body);
266
293
  },
267
294
  };
@@ -0,0 +1,68 @@
1
+ /** Blocks dropped with their content: they never hold readable page text. */
2
+ const DROP_BLOCKS = ["script", "style", "noscript", "svg", "iframe", "template", "head", "nav", "footer"];
3
+ const DROP_RE = new RegExp(`<(${DROP_BLOCKS.join("|")})\\b[^>]*>[\\s\\S]*?<\\/\\1\\s*>`, "gi");
4
+ const NAMED_ENTITIES = {
5
+ amp: "&",
6
+ lt: "<",
7
+ gt: ">",
8
+ quot: '"',
9
+ apos: "'",
10
+ nbsp: " ",
11
+ mdash: "\u2014",
12
+ ndash: "\u2013",
13
+ hellip: "\u2026",
14
+ lsquo: "\u2018",
15
+ rsquo: "\u2019",
16
+ ldquo: "\u201c",
17
+ rdquo: "\u201d",
18
+ };
19
+ function decodeEntities(text) {
20
+ return text.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi, (whole, dec, hex, name) => {
21
+ if (name !== undefined)
22
+ return NAMED_ENTITIES[name.toLowerCase()] ?? whole;
23
+ const code = dec !== undefined ? Number.parseInt(dec, 10) : Number.parseInt(hex ?? "", 16);
24
+ if (!Number.isInteger(code) || code < 0 || code > 0x10ffff)
25
+ return whole;
26
+ try {
27
+ return String.fromCodePoint(code);
28
+ }
29
+ catch {
30
+ return whole;
31
+ }
32
+ });
33
+ }
34
+ /** True when the text looks like an HTML document, for responses that carry no content type. */
35
+ export function looksLikeHtml(text) {
36
+ return /^\s*(<!doctype html|<html[\s>])/i.test(text);
37
+ }
38
+ /**
39
+ * Readable plain text from an HTML page: scripts, styles, navigation and footers are dropped, headings and list items
40
+ * keep a light markdown shape, and links stay as `[text](url)` so an agent can follow them.
41
+ */
42
+ export function htmlToText(html) {
43
+ let out = html.replace(/<!--[\s\S]*?-->/g, "").replace(DROP_RE, "");
44
+ out = out.replace(/<a\s[^>]*?href\s*=\s*(?:"([^"]*)"|'([^']*)')[^>]*>([\s\S]*?)<\/a\s*>/gi, (_m, dq, sq, inner) => {
45
+ const href = (dq ?? sq ?? "").trim();
46
+ const label = inner.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
47
+ if (!label)
48
+ return "";
49
+ if (!href || href.startsWith("#") || /^javascript:/i.test(href))
50
+ return label;
51
+ return `[${label}](${href})`;
52
+ });
53
+ out = out
54
+ .replace(/<h([1-6])\b[^>]*>/gi, (_m, level) => `\n\n${"#".repeat(Number(level))} `)
55
+ .replace(/<\/h[1-6]\s*>/gi, "\n\n")
56
+ .replace(/<li\b[^>]*>/gi, "\n- ")
57
+ .replace(/<br\s*\/?>/gi, "\n")
58
+ .replace(/<\/?(?:p|div|section|article|main|header|aside|ul|ol|table|tr|blockquote|pre|figure|figcaption|dl|dt|dd)\b[^>]*>/gi, "\n")
59
+ .replace(/<\/?(?:td|th)\b[^>]*>/gi, " ")
60
+ .replace(/<[^>]*>/g, "");
61
+ out = decodeEntities(out)
62
+ .replace(/[ \t\f\v\u00a0]+/g, " ")
63
+ .split("\n")
64
+ .map((line) => line.trim())
65
+ .join("\n")
66
+ .replace(/\n{3,}/g, "\n\n");
67
+ return out.trim();
68
+ }
package/tui/src/app.js CHANGED
@@ -572,8 +572,10 @@ class InteractiveApp {
572
572
  break;
573
573
  }
574
574
  case "tool_start": {
575
- if (event.depth !== 0)
575
+ if (event.depth !== 0) {
576
+ this.subagents.get(event.runId)?.toolStarted(toolSummary(event.toolName, event.args, 50));
576
577
  return;
578
+ }
577
579
  this.currentText = null;
578
580
  const line = new ToolLine(toolSummary(event.toolName, event.args), toolSummary(event.toolName, event.args, Number.POSITIVE_INFINITY), this.ticker, this.view);
579
581
  this.tools.set(event.toolCallId, line);
@@ -581,8 +583,10 @@ class InteractiveApp {
581
583
  break;
582
584
  }
583
585
  case "tool_end": {
584
- if (event.depth !== 0)
586
+ if (event.depth !== 0) {
587
+ this.subagents.get(event.runId)?.toolEnded();
585
588
  return;
589
+ }
586
590
  this.tools.get(event.toolCallId)?.finish(event.isError, event.durationMs, event.output);
587
591
  this.tools.delete(event.toolCallId);
588
592
  break;
@@ -592,7 +596,7 @@ class InteractiveApp {
592
596
  this.liveModel = { model: event.model, effort: event.effort };
593
597
  return;
594
598
  }
595
- const line = new SubagentLine(escapeControl(oneLine(event.instruction, 70)), event.depth, this.ticker);
599
+ const line = new SubagentLine(escapeControl(oneLine(event.instruction, 60)), event.depth, this.ticker, escapeControl(`${event.taskId ?? event.runId.slice(-6)} · ${event.model}`));
596
600
  this.subagents.set(event.runId, line);
597
601
  this.chat.addChild(line);
598
602
  break;
@@ -600,7 +604,7 @@ class InteractiveApp {
600
604
  case "run_end": {
601
605
  if (event.depth === 0)
602
606
  return;
603
- this.subagents.get(event.runId)?.finish(event.status, event.costUsd);
607
+ this.subagents.get(event.runId)?.finish(event.status, event.costUsd, event.error ? escapeControl(`${event.error.code}: ${oneLine(event.error.message, 120)}`) : "");
604
608
  this.subagents.delete(event.runId);
605
609
  break;
606
610
  }
@@ -140,35 +140,61 @@ export class ToolLine {
140
140
  }
141
141
  invalidate() { }
142
142
  }
143
- /** One line per spawned subagent: status and cost. */
143
+ /** One entry per spawned subagent: task id, model, elapsed time, current tool and, on failure, the error. */
144
144
  export class SubagentLine {
145
145
  state = "running";
146
146
  costUsd = 0;
147
147
  status = "";
148
+ error = "";
149
+ tool = "";
150
+ toolCalls = 0;
151
+ endedAt = null;
152
+ startedAt = Date.now();
148
153
  summary;
149
154
  ticker;
150
155
  depth;
151
- constructor(summary, depth, ticker) {
156
+ label;
157
+ constructor(summary, depth, ticker, label) {
152
158
  this.summary = summary;
153
159
  this.depth = depth;
154
160
  this.ticker = ticker;
161
+ this.label = label;
155
162
  }
156
- finish(status, costUsd) {
163
+ toolStarted(summary) {
164
+ this.tool = summary;
165
+ this.toolCalls++;
166
+ }
167
+ toolEnded() {
168
+ this.tool = "";
169
+ }
170
+ finish(status, costUsd, error = "") {
157
171
  this.state = status === "succeeded" ? "ok" : "error";
158
172
  this.status = status;
159
173
  this.costUsd = costUsd;
174
+ this.error = error;
175
+ this.tool = "";
176
+ this.endedAt = Date.now();
160
177
  }
161
178
  interrupt() {
162
179
  if (this.state === "running") {
163
180
  this.state = "error";
164
181
  this.status = "interrupted";
182
+ this.tool = "";
183
+ this.endedAt = Date.now();
165
184
  }
166
185
  }
167
186
  render(width) {
168
187
  const indent = " ".repeat(Math.max(0, this.depth - 1));
169
188
  const mark = this.state === "running" ? style.cyan(this.ticker.spinner) : this.state === "ok" ? style.green("✓") : style.red("✗");
170
- const tail = this.state === "running" ? style.gray(" running") : style.gray(` ${this.status} · ${usd(this.costUsd)}`);
171
- return [truncateToWidth(`${indent} ↳ ${mark} subagent ${this.summary}${tail}`, width)];
189
+ const elapsed = duration((this.endedAt ?? Date.now()) - this.startedAt);
190
+ const calls = this.toolCalls > 0 ? ` · ${this.toolCalls} tool${this.toolCalls === 1 ? "" : "s"}` : "";
191
+ const tail = this.state === "running" ? style.gray(` ${elapsed}${calls}`) : style.gray(` ${this.status} · ${elapsed}${calls} · ${usd(this.costUsd)}`);
192
+ const lines = [truncateToWidth(`${indent} ↳ ${mark} ${style.bold(this.label)} ${this.summary}${tail}`, width)];
193
+ if (this.state === "running" && this.tool)
194
+ lines.push(truncateToWidth(style.gray(`${indent} ${this.tool}`), width));
195
+ if (this.state === "error" && this.error)
196
+ lines.push(truncateToWidth(style.red(`${indent} ${this.error}`), width));
197
+ return lines;
172
198
  }
173
199
  invalidate() { }
174
200
  }
@@ -7,6 +7,7 @@
7
7
  <title>nexo · cost</title>
8
8
  <link rel="stylesheet" href="/style.css">
9
9
  <script type="module" src="/lib/theme.ts"></script>
10
+ <script type="module" src="/pages/companion.ts"></script>
10
11
  <script type="module" src="/pages/cost.ts"></script>
11
12
  </head>
12
13
  <body>
@@ -7,6 +7,7 @@
7
7
  <title>nexo · runs</title>
8
8
  <link rel="stylesheet" href="/style.css">
9
9
  <script type="module" src="/lib/theme.ts"></script>
10
+ <script type="module" src="/pages/companion.ts"></script>
10
11
  <script type="module" src="/pages/runs.ts"></script>
11
12
  </head>
12
13
  <body>
@@ -7,6 +7,7 @@
7
7
  <title>nexo · judge</title>
8
8
  <link rel="stylesheet" href="/style.css">
9
9
  <script type="module" src="/lib/theme.ts"></script>
10
+ <script type="module" src="/pages/companion.ts"></script>
10
11
  <script type="module" src="/pages/judge.ts"></script>
11
12
  </head>
12
13
  <body>
@@ -7,6 +7,7 @@
7
7
  <title>nexo · learning</title>
8
8
  <link rel="stylesheet" href="/style.css">
9
9
  <script type="module" src="/lib/theme.ts"></script>
10
+ <script type="module" src="/pages/companion.ts"></script>
10
11
  <script type="module" src="/pages/learning.ts"></script>
11
12
  </head>
12
13
  <body>
@@ -0,0 +1,82 @@
1
+ // nex, the nexo companion: turns the most recent runs into a mood and a one-line remark. Pure, so it is tested under
2
+ // vitest; pages/companion.ts draws the character and wires the quick actions.
3
+ import type { RunSummary } from "./api-types.ts";
4
+
5
+ export type Mood = "working" | "happy" | "worried" | "idle" | "sleepy";
6
+
7
+ export interface CompanionState {
8
+ mood: Mood;
9
+ line: string;
10
+ running: RunSummary[];
11
+ latest: RunSummary | null;
12
+ lastFailed: RunSummary | null;
13
+ }
14
+
15
+ const FAILED = new Set(["failed", "error", "aborted", "budget_exceeded"]);
16
+ const MIN = 60_000;
17
+ /** A failure this recent keeps nex worried. */
18
+ export const WORRY_MS = 60 * MIN;
19
+ /** A success this recent keeps nex happy. */
20
+ export const HAPPY_MS = 15 * MIN;
21
+ /** No activity for this long and nex dozes off. */
22
+ export const SLEEP_MS = 3 * 60 * MIN;
23
+
24
+ /** Mouth path for each mood, in the character's 64x64 viewBox. */
25
+ export const MOUTHS: Record<Mood, string> = {
26
+ happy: "M24 40 Q32 48 40 40",
27
+ idle: "M26 41 Q32 44.5 38 41",
28
+ worried: "M25 44 Q32 38 39 44",
29
+ working: "M28 42 L36 42",
30
+ sleepy: "M29 42 Q32 43.5 35 42",
31
+ };
32
+
33
+ export function isFailed(status: string): boolean {
34
+ return FAILED.has(status);
35
+ }
36
+
37
+ export function ago(ms: number): string {
38
+ if (ms < MIN) return "just now";
39
+ if (ms < 60 * MIN) return `${Math.floor(ms / MIN)}m ago`;
40
+ if (ms < 48 * 60 * MIN) return `${Math.floor(ms / (60 * MIN))}h ago`;
41
+ return `${Math.floor(ms / (24 * 60 * MIN))}d ago`;
42
+ }
43
+
44
+ function clip(text: string, max = 48): string {
45
+ const flat = text.replace(/\s+/g, " ").trim();
46
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
47
+ }
48
+
49
+ function endMs(run: RunSummary): number {
50
+ return Date.parse(run.endedAt ?? run.startedAt) || 0;
51
+ }
52
+
53
+ export function deriveMood(runs: RunSummary[], nowMs: number): CompanionState {
54
+ const running = runs.filter((r) => r.status === "running");
55
+ const finished = runs.filter((r) => r.status !== "running").sort((a, b) => endMs(b) - endMs(a));
56
+ const latest = finished[0] ?? null;
57
+ const lastFailed = finished.find((r) => isFailed(r.status)) ?? null;
58
+ const base = { running, latest, lastFailed };
59
+
60
+ if (running.length === 1 && running[0]) return { ...base, mood: "working", line: `On it: “${clip(running[0].instruction)}”` };
61
+ if (running.length > 1) return { ...base, mood: "working", line: `Juggling ${running.length} runs at once.` };
62
+ if (!latest) return { ...base, mood: "sleepy", line: "No runs yet. Start one with nexo and I'll keep watch." };
63
+
64
+ const since = Math.max(0, nowMs - endMs(latest));
65
+ const word = latest.status.replace("_", " ");
66
+ if (isFailed(latest.status) && since < WORRY_MS) return { ...base, mood: "worried", line: `“${clip(latest.instruction)}” ${word} ${ago(since)}. Want a look?` };
67
+ if (latest.status === "succeeded" && since < HAPPY_MS) return { ...base, mood: "happy", line: `Done: “${clip(latest.instruction)}” (${ago(since)}).` };
68
+ if (since >= SLEEP_MS) return { ...base, mood: "sleepy", line: `Quiet since ${ago(since)}. Napping until the next run.` };
69
+ return { ...base, mood: "idle", line: `All calm. Last run ${word} ${ago(since)}.` };
70
+ }
71
+
72
+ /** Runs that were running last poll and have now finished, split by outcome; drives nex's cheer and flinch. */
73
+ export function transitions(previousRunning: ReadonlySet<string>, runs: RunSummary[]): { succeeded: number; failed: number } {
74
+ let succeeded = 0;
75
+ let failed = 0;
76
+ for (const run of runs) {
77
+ if (!previousRunning.has(run.id) || run.status === "running") continue;
78
+ if (run.status === "succeeded") succeeded++;
79
+ else if (isFailed(run.status)) failed++;
80
+ }
81
+ return { succeeded, failed };
82
+ }
@@ -0,0 +1,31 @@
1
+ // What nex offers on each page: a label and suggested questions. Pure, so it is tested under vitest.
2
+
3
+ export type PageKey = "runs" | "run" | "cost" | "sessions" | "learning" | "judge" | "optim" | "wikis";
4
+
5
+ export interface PageContext {
6
+ page: PageKey;
7
+ label: string;
8
+ runId: string | null;
9
+ prompts: string[];
10
+ }
11
+
12
+ const BASE: Record<PageKey, { label: string; prompts: string[] }> = {
13
+ runs: { label: "runs", prompts: ["Which runs failed recently, and why?", "What should I review first?"] },
14
+ run: { label: "this run", prompts: ["Explain what happened in this run", "Why did it cost this much?", "What should I check before a verdict?"] },
15
+ cost: { label: "cost", prompts: ["Where is the spend going?", "Which runs were unusually expensive?"] },
16
+ sessions: { label: "sessions", prompts: ["Summarise my recent sessions"] },
17
+ learning: { label: "learning", prompts: ["What has nexo learned lately?", "Is anything worth retiring?"] },
18
+ judge: { label: "judge", prompts: ["How reliable is the judge?"] },
19
+ optim: { label: "optimization", prompts: ["What is the status of my optimizations?", "Does anything need approval?"] },
20
+ wikis: { label: "wikis", prompts: ["What is in my wikis?"] },
21
+ };
22
+
23
+ export function pageContext(pathname: string, search: string): PageContext {
24
+ const file = pathname === "/" || pathname === "/index.html" ? "runs" : pathname.replace(/^\/+/, "").replace(/\.html$/, "");
25
+ let page: PageKey = Object.hasOwn(BASE, file) ? (file as PageKey) : "runs";
26
+ const id = new URLSearchParams(search).get("id") ?? "";
27
+ const runId = page === "run" && /^[0-9A-Za-z]{1,64}$/.test(id) ? id : null;
28
+ if (page === "run" && runId === null) page = "runs";
29
+ const { label, prompts } = BASE[page];
30
+ return { page, label, runId, prompts };
31
+ }
@@ -7,6 +7,7 @@
7
7
  <title>nexo · optimization</title>
8
8
  <link rel="stylesheet" href="/style.css">
9
9
  <script type="module" src="/lib/theme.ts"></script>
10
+ <script type="module" src="/pages/companion.ts"></script>
10
11
  <script type="module" src="/pages/optim.ts"></script>
11
12
  </head>
12
13
  <body>