@hexdecimal16/nexo 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/src/common.js +2 -1
- package/cli/src/companion.js +23 -0
- package/cli/src/interactive.js +7 -5
- package/cli/src/ui.js +2 -0
- package/core/src/config/schema.js +3 -0
- package/core/src/engine/prompts.js +2 -0
- package/core/src/engine/run.js +6 -2
- package/core/src/engine/spawn-tool.js +29 -3
- package/core/src/index.js +2 -0
- package/core/src/learn/job.js +6 -1
- package/core/src/session/project-instructions.js +96 -0
- package/core/src/session/project-root.js +83 -0
- package/core/src/session/session.js +2 -1
- package/memory/src/curate.js +9 -5
- package/memory/src/prompts.js +4 -3
- package/package.json +1 -1
- package/sdk/src/index.js +1 -0
- package/sdk/src/run-tree.js +81 -0
- package/store/src/memories.js +1 -1
- package/store/src/sessions.js +17 -2
- package/tools/src/builtin.js +32 -5
- package/tools/src/html-text.js +68 -0
- package/tui/src/app.js +13 -8
- package/tui/src/commands.js +1 -1
- package/tui/src/components.js +31 -5
- package/web/public/cost.html +1 -0
- package/web/public/index.html +1 -0
- package/web/public/judge.html +1 -0
- package/web/public/learning.html +1 -0
- package/web/public/lib/companion-mood.ts +82 -0
- package/web/public/lib/companion-pages.ts +31 -0
- package/web/public/optim.html +1 -0
- package/web/public/pages/companion.ts +264 -0
- package/web/public/run.html +1 -0
- package/web/public/sessions.html +1 -0
- package/web/public/style.css +61 -0
- package/web/public/wikis.html +1 -0
- package/web/src/companion.js +149 -0
- package/web/src/server.js +9 -0
package/store/src/sessions.js
CHANGED
|
@@ -56,10 +56,25 @@ export function getSessionRow(db, id) {
|
|
|
56
56
|
}
|
|
57
57
|
/** Sessions, most recently updated first; `withTurns` leaves out sessions that never ran a turn (no recorded turn and no linked run). */
|
|
58
58
|
export function listSessionRows(db, options = {}) {
|
|
59
|
-
const
|
|
59
|
+
const clauses = [];
|
|
60
|
+
const params = [];
|
|
61
|
+
if (options.withTurns)
|
|
62
|
+
clauses.push("(turns > 0 OR EXISTS (SELECT 1 FROM runs WHERE runs.session_id = sessions.id))");
|
|
63
|
+
// Sessions started in any of the `underDir` directories or below them (a project's roots, e.g. all its git worktrees).
|
|
64
|
+
if (options.underDir !== undefined) {
|
|
65
|
+
const dirs = typeof options.underDir === "string" ? [options.underDir] : options.underDir;
|
|
66
|
+
const parts = dirs.map((raw) => {
|
|
67
|
+
const dir = raw.replace(/\/+$/, "") || "/";
|
|
68
|
+
const prefix = dir === "/" ? "/" : `${dir}/`;
|
|
69
|
+
params.push(dir, prefix.length, prefix);
|
|
70
|
+
return "(cwd = ? OR substr(cwd, 1, ?) = ?)";
|
|
71
|
+
});
|
|
72
|
+
clauses.push(parts.length > 0 ? `(${parts.join(" OR ")})` : "0");
|
|
73
|
+
}
|
|
74
|
+
const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")} ` : "";
|
|
60
75
|
return db
|
|
61
76
|
.prepare(`SELECT * FROM sessions ${where}ORDER BY updated_at DESC, id DESC LIMIT ?`)
|
|
62
|
-
.all(options.limit ?? 20)
|
|
77
|
+
.all(...params, options.limit ?? 20)
|
|
63
78
|
.map(decode);
|
|
64
79
|
}
|
|
65
80
|
/**
|
package/tools/src/builtin.js
CHANGED
|
@@ -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:
|
|
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
|
|
262
|
-
const
|
|
263
|
-
|
|
264
|
-
|
|
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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { homedir } from "node:os";
|
|
2
2
|
import { sep } from "node:path";
|
|
3
3
|
import { CombinedAutocompleteProvider, Container, Editor, isKeyRelease, isKeyRepeat, Loader, matchesKey, ProcessTerminal, setCapabilityOverrides, TuiMainScreen, } from "@earendil-works/pi-tui";
|
|
4
|
-
import { listSessions } from "../../core/src/index.js";
|
|
4
|
+
import { listSessions, projectRoots } from "../../core/src/index.js";
|
|
5
5
|
import { getSessionRow, sessionNotFound } from "../../store/src/index.js";
|
|
6
6
|
import { toErrorPayload } from "../../telemetry/src/index.js";
|
|
7
7
|
import { describeSessionRule } from "../../tools/src/index.js";
|
|
@@ -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,
|
|
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
|
}
|
|
@@ -802,13 +806,14 @@ class InteractiveApp {
|
|
|
802
806
|
this.sayError({ code: "INVALID_REQUEST", message: "/resume is not available here", hint: "Start nexo with --resume <id>" });
|
|
803
807
|
return;
|
|
804
808
|
}
|
|
805
|
-
|
|
809
|
+
const all = args.trim() === "--all";
|
|
810
|
+
if (args && !all) {
|
|
806
811
|
this.switchTo(current, args);
|
|
807
812
|
return;
|
|
808
813
|
}
|
|
809
|
-
const rows = listSessions(this.options.db, { limit: 50 }).filter((r) => r.id !== current.id);
|
|
814
|
+
const rows = listSessions(this.options.db, { limit: 50, ...(all ? {} : { underDir: projectRoots(current.cwd) }) }).filter((r) => r.id !== current.id);
|
|
810
815
|
if (rows.length === 0) {
|
|
811
|
-
this.say("no other sessions to resume");
|
|
816
|
+
this.say(all ? "no other sessions to resume" : "no other sessions in this project (try /resume --all)");
|
|
812
817
|
return;
|
|
813
818
|
}
|
|
814
819
|
this.screen = "picker";
|
package/tui/src/commands.js
CHANGED
|
@@ -25,7 +25,7 @@ export const SLASH_COMMANDS = [
|
|
|
25
25
|
{ name: "compact", description: "Summarize older turns at the start of the next turn" },
|
|
26
26
|
{ name: "clear", description: "Start a new conversation in this session" },
|
|
27
27
|
{ name: "sessions", description: "List recent sessions" },
|
|
28
|
-
{ name: "resume", description: "Switch to another session (a picker when no id is given)", argumentHint: "[id]" },
|
|
28
|
+
{ name: "resume", description: "Switch to another session (a picker when no id is given)", argumentHint: "[id|--all]" },
|
|
29
29
|
{ name: "settings", description: "Open settings (models, keys, budgets, tool policy)" },
|
|
30
30
|
{ name: "exit", description: "Leave nexo (the session can be resumed)" },
|
|
31
31
|
];
|
package/tui/src/components.js
CHANGED
|
@@ -140,35 +140,61 @@ export class ToolLine {
|
|
|
140
140
|
}
|
|
141
141
|
invalidate() { }
|
|
142
142
|
}
|
|
143
|
-
/** One
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
171
|
-
|
|
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
|
}
|
package/web/public/cost.html
CHANGED
package/web/public/index.html
CHANGED
package/web/public/judge.html
CHANGED
package/web/public/learning.html
CHANGED
|
@@ -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
|
+
}
|
package/web/public/optim.html
CHANGED
|
@@ -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>
|