@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,60 @@
1
+ import { toErrorPayload } from "../../telemetry/src/index.js";
2
+ const STATUS = {
3
+ INVALID_REQUEST: 400,
4
+ CONFIG_INVALID: 400,
5
+ FORBIDDEN: 403,
6
+ TOOL_DENIED: 403,
7
+ NOT_FOUND: 404,
8
+ SKILL_NOT_FOUND: 404,
9
+ METHOD_NOT_ALLOWED: 405,
10
+ CONFLICT: 409,
11
+ WRITE_CONFLICT: 409,
12
+ BUDGET_EXCEEDED: 402,
13
+ PROVIDER_RATE_LIMIT: 429,
14
+ PROVIDER_UNAVAILABLE: 503,
15
+ PROVIDER_TIMEOUT: 504,
16
+ };
17
+ /** HTTP status for an error code; anything unlisted (STORE_IO, INTERNAL, …) is a 500. */
18
+ export function httpStatusFor(code) {
19
+ return STATUS[code] ?? 500;
20
+ }
21
+ /** The API error envelope; `hint` and `context` are always present so clients need no existence checks. */
22
+ export function errorBody(error) {
23
+ const payload = toErrorPayload(error);
24
+ return {
25
+ status: httpStatusFor(payload.code),
26
+ body: {
27
+ error: {
28
+ code: payload.code,
29
+ message: payload.message,
30
+ retryable: payload.retryable,
31
+ hint: payload.hint ?? null,
32
+ context: payload.context ?? {},
33
+ },
34
+ },
35
+ };
36
+ }
37
+ export const SECURITY_HEADERS = {
38
+ "x-content-type-options": "nosniff",
39
+ "referrer-policy": "no-referrer",
40
+ "x-frame-options": "DENY",
41
+ "cross-origin-resource-policy": "same-origin",
42
+ };
43
+ export function sendJson(res, status, body) {
44
+ const text = JSON.stringify(body);
45
+ res.writeHead(status, {
46
+ ...SECURITY_HEADERS,
47
+ "content-type": "application/json; charset=utf-8",
48
+ "cache-control": "no-store",
49
+ "content-length": Buffer.byteLength(text),
50
+ });
51
+ res.end(text);
52
+ }
53
+ export function sendError(res, error) {
54
+ const { status, body } = errorBody(error);
55
+ if (res.headersSent) {
56
+ res.destroy();
57
+ return;
58
+ }
59
+ sendJson(res, status, body);
60
+ }
@@ -0,0 +1,5 @@
1
+ export * from "./api.js";
2
+ export * from "./http-errors.js";
3
+ export * from "./server.js";
4
+ export * from "./static.js";
5
+ export * from "./strip.js";
@@ -0,0 +1,292 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { fileURLToPath } from "node:url";
4
+ import { NexoError } from "../../telemetry/src/index.js";
5
+ import { costResponse, evalCasesResponse, reviewEvalCaseResponse, feedbackResponse, judgeCalibrationResponse, learnJobsResponse, listRunsResponse, memoriesResponse, memoryDetailResponse, metaResponse, approveOptimResponse, optimDetailResponse, optimListResponse, playbookResponse, playbooksResponse, retireMemoryResponse, retirePlaybookItemResponse, listSessionsResponse, runDetailResponse, serveRunFile, spanResponse, spanTreeResponse, listWikisResponse, listWikiPagesResponse, wikiPageResponse, } from "./api.js";
6
+ import { sendError, sendJson } from "./http-errors.js";
7
+ import { createStaticServer } from "./static.js";
8
+ export const DEFAULT_PUBLIC_DIR = fileURLToPath(new URL("../public/", import.meta.url));
9
+ /** Largest accepted request body (feedback JSON). */
10
+ export const MAX_BODY_BYTES = 64 * 1024;
11
+ export const TOKEN_HEADER = "x-nexo-token";
12
+ const RUN_ID = "([0-9A-Za-z]{1,64})";
13
+ const ROUTES = {
14
+ runs: /^\/api\/runs$/,
15
+ run: new RegExp(`^/api/runs/${RUN_ID}$`),
16
+ spans: new RegExp(`^/api/runs/${RUN_ID}/spans$`),
17
+ span: new RegExp(`^/api/runs/${RUN_ID}/spans/${RUN_ID}$`),
18
+ files: new RegExp(`^/api/runs/${RUN_ID}/files(?:/(.*))?$`),
19
+ feedback: new RegExp(`^/api/runs/${RUN_ID}/feedback$`),
20
+ sessions: /^\/api\/sessions$/,
21
+ costs: /^\/api\/costs$/,
22
+ calibration: /^\/api\/judge\/calibration$/,
23
+ memories: /^\/api\/memories$/,
24
+ memory: new RegExp(`^/api/memories/${RUN_ID}$`),
25
+ memoryRetire: new RegExp(`^/api/memories/${RUN_ID}/retire$`),
26
+ playbooks: /^\/api\/playbooks$/,
27
+ playbook: /^\/api\/playbooks\/([^/]{1,64})$/,
28
+ playbookRetire: /^\/api\/playbooks\/([^/]{1,64})\/items\/([^/]{1,64})\/retire$/,
29
+ learnJobs: /^\/api\/learn\/jobs$/,
30
+ optimList: /^\/api\/optim$/,
31
+ optim: new RegExp(`^/api/optim/${RUN_ID}$`),
32
+ optimApprove: new RegExp(`^/api/optim/${RUN_ID}/approve$`),
33
+ evalCases: /^\/api\/eval-cases$/,
34
+ evalCaseReview: new RegExp(`^/api/eval-cases/${RUN_ID}/(accept|dismiss)$`),
35
+ meta: /^\/api\/meta$/,
36
+ wikis: /^\/api\/wikis$/,
37
+ wikiPages: /^\/api\/wikis\/([^/]{1,64})\/pages$/,
38
+ wikiPage: /^\/api\/wikis\/([^/]{1,64})\/page$/,
39
+ };
40
+ function methodNotAllowed(method, path, allowed) {
41
+ return new NexoError({ code: "METHOD_NOT_ALLOWED", message: `${method} is not supported on ${path}`, context: { method, path, allowed } });
42
+ }
43
+ function forbidden(message, hint) {
44
+ return new NexoError({ code: "FORBIDDEN", message, ...(hint ? { hint } : {}) });
45
+ }
46
+ function tokensMatch(given, expected) {
47
+ if (!given)
48
+ return false;
49
+ const a = Buffer.from(given);
50
+ const b = Buffer.from(expected);
51
+ return a.length === b.length && timingSafeEqual(a, b);
52
+ }
53
+ async function readJsonBody(req) {
54
+ const type = req.headers["content-type"] ?? "";
55
+ if (!type.startsWith("application/json")) {
56
+ throw new NexoError({ code: "INVALID_REQUEST", message: "Content-Type must be application/json", context: { contentType: type } });
57
+ }
58
+ const chunks = [];
59
+ let size = 0;
60
+ for await (const chunk of req) {
61
+ size += chunk.length;
62
+ if (size > MAX_BODY_BYTES) {
63
+ throw new NexoError({ code: "INVALID_REQUEST", message: `Request body is larger than ${MAX_BODY_BYTES} bytes` });
64
+ }
65
+ chunks.push(chunk);
66
+ }
67
+ try {
68
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
69
+ }
70
+ catch {
71
+ throw new NexoError({ code: "INVALID_REQUEST", message: "Request body is not valid JSON" });
72
+ }
73
+ }
74
+ function decodePath(path) {
75
+ try {
76
+ return decodeURIComponent(path);
77
+ }
78
+ catch {
79
+ throw new NexoError({ code: "INVALID_REQUEST", message: "Path is not valid percent-encoding", context: { path } });
80
+ }
81
+ }
82
+ /**
83
+ * Starts the UI server on 127.0.0.1. GET requests need no token; every other method needs the per-launch token in
84
+ * the `x-nexo-token` header. Requests whose Host is not this loopback address are refused, which blocks DNS
85
+ * rebinding from reading the token out of a served page.
86
+ */
87
+ export async function startWebServer(options) {
88
+ const host = options.host ?? "127.0.0.1";
89
+ if (host !== "127.0.0.1")
90
+ throw new NexoError({ code: "CONFIG_INVALID", message: "The web UI binds to 127.0.0.1 only", context: { host } });
91
+ const token = options.token ?? randomBytes(24).toString("base64url");
92
+ const ctx = {
93
+ db: options.db,
94
+ redact: options.redact,
95
+ now: options.now ?? (() => new Date()),
96
+ readOnly: options.readOnly ?? null,
97
+ judge: options.judge ?? { key: null, warnings: [] },
98
+ learning: options.learning ?? { enabled: false },
99
+ optimize: options.optimize ?? { minJudgeKappa: 0.6 },
100
+ wikisDir: options.wikisDir,
101
+ };
102
+ const assertWritable = () => {
103
+ if (!ctx.readOnly)
104
+ return;
105
+ throw new NexoError({
106
+ code: "CONFIG_INVALID",
107
+ message: `The UI is read-only: ${ctx.readOnly.message}`,
108
+ ...(ctx.readOnly.hint ? { hint: ctx.readOnly.hint } : {}),
109
+ });
110
+ };
111
+ const statics = createStaticServer(options.publicDir ?? DEFAULT_PUBLIC_DIR, token);
112
+ let allowedHosts = new Set();
113
+ const handle = async (req, res) => {
114
+ const method = req.method ?? "GET";
115
+ if (!allowedHosts.has(req.headers.host ?? "")) {
116
+ throw forbidden(`Host "${req.headers.host ?? ""}" is not allowed`, "Open the URL printed by `nexo ui`");
117
+ }
118
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
119
+ const path = url.pathname;
120
+ const mutating = method !== "GET";
121
+ if (mutating && !tokensMatch(req.headers[TOKEN_HEADER], token)) {
122
+ throw forbidden("Missing or wrong UI token", `The token is per \`nexo ui\` launch. If this page was opened before a restart, reload it from the URL the newest \`nexo ui\` printed; scripts send that URL's token in the ${TOKEN_HEADER} header`);
123
+ }
124
+ if (!path.startsWith("/api/")) {
125
+ if (method !== "GET")
126
+ throw methodNotAllowed(method, path, "GET");
127
+ statics.serve(res, path);
128
+ return;
129
+ }
130
+ let m;
131
+ if (ROUTES.runs.test(path)) {
132
+ if (method !== "GET")
133
+ throw methodNotAllowed(method, path, "GET");
134
+ return sendJson(res, 200, listRunsResponse(ctx, url.searchParams));
135
+ }
136
+ if (ROUTES.sessions.test(path)) {
137
+ if (method !== "GET")
138
+ throw methodNotAllowed(method, path, "GET");
139
+ return sendJson(res, 200, listSessionsResponse(ctx, url.searchParams));
140
+ }
141
+ if ((m = ROUTES.run.exec(path))) {
142
+ if (method !== "GET")
143
+ throw methodNotAllowed(method, path, "GET");
144
+ return sendJson(res, 200, runDetailResponse(ctx, m[1]));
145
+ }
146
+ if ((m = ROUTES.spans.exec(path))) {
147
+ if (method !== "GET")
148
+ throw methodNotAllowed(method, path, "GET");
149
+ return sendJson(res, 200, spanTreeResponse(ctx, m[1]));
150
+ }
151
+ if ((m = ROUTES.span.exec(path))) {
152
+ if (method !== "GET")
153
+ throw methodNotAllowed(method, path, "GET");
154
+ return sendJson(res, 200, spanResponse(ctx, m[1], m[2]));
155
+ }
156
+ if ((m = ROUTES.files.exec(path))) {
157
+ if (method !== "GET")
158
+ throw methodNotAllowed(method, path, "GET");
159
+ return serveRunFile(ctx, res, m[1], decodePath(m[2] ?? ""), url.searchParams.get("full") === "1", req.headers.range);
160
+ }
161
+ if ((m = ROUTES.feedback.exec(path))) {
162
+ if (method !== "POST")
163
+ throw methodNotAllowed(method, path, "POST");
164
+ assertWritable();
165
+ const body = await readJsonBody(req);
166
+ return sendJson(res, 201, feedbackResponse(ctx, m[1], body));
167
+ }
168
+ if (ROUTES.meta.test(path)) {
169
+ if (method !== "GET")
170
+ throw methodNotAllowed(method, path, "GET");
171
+ return sendJson(res, 200, metaResponse(ctx));
172
+ }
173
+ if (ROUTES.costs.test(path)) {
174
+ if (method !== "GET")
175
+ throw methodNotAllowed(method, path, "GET");
176
+ return sendJson(res, 200, costResponse(ctx, url.searchParams));
177
+ }
178
+ if (ROUTES.calibration.test(path)) {
179
+ if (method !== "GET")
180
+ throw methodNotAllowed(method, path, "GET");
181
+ return sendJson(res, 200, judgeCalibrationResponse(ctx));
182
+ }
183
+ if (ROUTES.memories.test(path)) {
184
+ if (method !== "GET")
185
+ throw methodNotAllowed(method, path, "GET");
186
+ return sendJson(res, 200, memoriesResponse(ctx, url.searchParams));
187
+ }
188
+ if ((m = ROUTES.memory.exec(path))) {
189
+ if (method !== "GET")
190
+ throw methodNotAllowed(method, path, "GET");
191
+ return sendJson(res, 200, memoryDetailResponse(ctx, m[1]));
192
+ }
193
+ if ((m = ROUTES.memoryRetire.exec(path))) {
194
+ if (method !== "POST")
195
+ throw methodNotAllowed(method, path, "POST");
196
+ assertWritable();
197
+ return sendJson(res, 200, retireMemoryResponse(ctx, m[1]));
198
+ }
199
+ if (ROUTES.playbooks.test(path)) {
200
+ if (method !== "GET")
201
+ throw methodNotAllowed(method, path, "GET");
202
+ return sendJson(res, 200, playbooksResponse(ctx));
203
+ }
204
+ if ((m = ROUTES.playbook.exec(path))) {
205
+ if (method !== "GET")
206
+ throw methodNotAllowed(method, path, "GET");
207
+ return sendJson(res, 200, playbookResponse(ctx, decodePath(m[1]), url.searchParams));
208
+ }
209
+ if ((m = ROUTES.playbookRetire.exec(path))) {
210
+ if (method !== "POST")
211
+ throw methodNotAllowed(method, path, "POST");
212
+ assertWritable();
213
+ return sendJson(res, 200, retirePlaybookItemResponse(ctx, decodePath(m[1]), decodePath(m[2])));
214
+ }
215
+ if (ROUTES.learnJobs.test(path)) {
216
+ if (method !== "GET")
217
+ throw methodNotAllowed(method, path, "GET");
218
+ return sendJson(res, 200, learnJobsResponse(ctx, url.searchParams));
219
+ }
220
+ if (ROUTES.optimList.test(path)) {
221
+ if (method !== "GET")
222
+ throw methodNotAllowed(method, path, "GET");
223
+ return sendJson(res, 200, optimListResponse(ctx, url.searchParams));
224
+ }
225
+ if ((m = ROUTES.optim.exec(path))) {
226
+ if (method !== "GET")
227
+ throw methodNotAllowed(method, path, "GET");
228
+ return sendJson(res, 200, optimDetailResponse(ctx, m[1]));
229
+ }
230
+ if ((m = ROUTES.optimApprove.exec(path))) {
231
+ if (method !== "POST")
232
+ throw methodNotAllowed(method, path, "POST");
233
+ assertWritable();
234
+ return sendJson(res, 200, approveOptimResponse(ctx, m[1]));
235
+ }
236
+ if (ROUTES.evalCases.test(path)) {
237
+ if (method !== "GET")
238
+ throw methodNotAllowed(method, path, "GET");
239
+ return sendJson(res, 200, evalCasesResponse(ctx, url.searchParams));
240
+ }
241
+ if ((m = ROUTES.evalCaseReview.exec(path))) {
242
+ if (method !== "POST")
243
+ throw methodNotAllowed(method, path, "POST");
244
+ assertWritable();
245
+ return sendJson(res, 200, reviewEvalCaseResponse(ctx, m[1], m[2]));
246
+ }
247
+ if (ROUTES.wikis.test(path)) {
248
+ if (method !== "GET")
249
+ throw methodNotAllowed(method, path, "GET");
250
+ return sendJson(res, 200, listWikisResponse(ctx));
251
+ }
252
+ if ((m = ROUTES.wikiPages.exec(path))) {
253
+ if (method !== "GET")
254
+ throw methodNotAllowed(method, path, "GET");
255
+ return sendJson(res, 200, listWikiPagesResponse(ctx, decodePath(m[1])));
256
+ }
257
+ if ((m = ROUTES.wikiPage.exec(path))) {
258
+ if (method !== "GET")
259
+ throw methodNotAllowed(method, path, "GET");
260
+ return sendJson(res, 200, wikiPageResponse(ctx, decodePath(m[1]), decodePath(url.searchParams.get("path") ?? "index.md")));
261
+ }
262
+ throw new NexoError({ code: "NOT_FOUND", message: `No API route ${path}`, context: { path } });
263
+ };
264
+ const server = createServer((req, res) => {
265
+ handle(req, res).catch((error) => {
266
+ // Drains an unread request body so the error response is not cut off by a reset connection.
267
+ req.resume();
268
+ sendError(res, error);
269
+ });
270
+ });
271
+ await new Promise((resolve, reject) => {
272
+ server.once("error", (cause) => reject(new NexoError({
273
+ code: "CONFIG_INVALID",
274
+ message: `Cannot listen on ${host}:${options.port ?? 0}: ${cause.message}`,
275
+ hint: "Pick another port with --port or set ui.port in your nexo config",
276
+ context: { host, port: options.port ?? 0 },
277
+ cause,
278
+ })));
279
+ server.listen(options.port ?? 0, host, () => resolve());
280
+ });
281
+ const port = server.address().port;
282
+ allowedHosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
283
+ return {
284
+ url: `http://127.0.0.1:${port}/`,
285
+ port,
286
+ token,
287
+ close: () => new Promise((resolve, reject) => {
288
+ server.close((error) => (error ? reject(error) : resolve()));
289
+ server.closeAllConnections();
290
+ }),
291
+ };
292
+ }
@@ -0,0 +1,86 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { extname } from "node:path";
3
+ import { NexoError } from "../../telemetry/src/index.js";
4
+ import { resolveConfined } from "../../tools/src/index.js";
5
+ import { SECURITY_HEADERS } from "./http-errors.js";
6
+ import { stripBrowserTypeScript } from "./strip.js";
7
+ /** Placeholder in public HTML files that is replaced with the per-launch token. */
8
+ export const TOKEN_PLACEHOLDER = "{{NEXO_TOKEN}}";
9
+ /** Pages may load only their own scripts, styles and API; no inline script, no framing. */
10
+ export const PAGE_CSP = "default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; media-src 'self'; connect-src 'self'; " +
11
+ "base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
12
+ const TYPES = {
13
+ ".html": "text/html; charset=utf-8",
14
+ ".css": "text/css; charset=utf-8",
15
+ ".ts": "text/javascript; charset=utf-8",
16
+ ".woff2": "font/woff2",
17
+ };
18
+ function notFound(urlPath) {
19
+ return new NexoError({ code: "NOT_FOUND", message: `No page at ${urlPath}`, context: { path: urlPath } });
20
+ }
21
+ /**
22
+ * Serves `.html` (with the token filled in), `.css` and browser `.ts` (type-stripped, cached by mtime) from
23
+ * `publicDir`. Paths are confined with `resolveConfined`; any other extension is a 404.
24
+ */
25
+ export function createStaticServer(publicDir, token) {
26
+ const stripped = new Map();
27
+ const load = (file, ext, urlPath) => {
28
+ if (ext === ".woff2")
29
+ return readFileSync(file);
30
+ const source = readFileSync(file, "utf8");
31
+ if (ext === ".html")
32
+ return source.replaceAll(TOKEN_PLACEHOLDER, token);
33
+ if (ext !== ".ts")
34
+ return source;
35
+ const mtimeMs = statSync(file).mtimeMs;
36
+ const cached = stripped.get(file);
37
+ if (cached && cached.mtimeMs === mtimeMs)
38
+ return cached.code;
39
+ const code = stripBrowserTypeScript(source, urlPath);
40
+ stripped.set(file, { mtimeMs, code });
41
+ return code;
42
+ };
43
+ return {
44
+ serve(res, urlPath) {
45
+ let rel;
46
+ try {
47
+ rel = urlPath === "/" ? "index.html" : decodeURIComponent(urlPath).replace(/^\/+/, "");
48
+ }
49
+ catch {
50
+ throw notFound(urlPath);
51
+ }
52
+ const ext = extname(rel);
53
+ const type = TYPES[ext];
54
+ if (!type || rel.includes("\0"))
55
+ throw notFound(urlPath);
56
+ let file;
57
+ try {
58
+ file = resolveConfined(publicDir, rel);
59
+ }
60
+ catch {
61
+ throw notFound(urlPath);
62
+ }
63
+ let body;
64
+ try {
65
+ if (!statSync(file).isFile())
66
+ throw notFound(urlPath);
67
+ body = load(file, ext, urlPath);
68
+ }
69
+ catch (error) {
70
+ if (error instanceof NexoError)
71
+ throw error;
72
+ if (error.code === "ENOENT")
73
+ throw notFound(urlPath);
74
+ throw error;
75
+ }
76
+ res.writeHead(200, {
77
+ ...SECURITY_HEADERS,
78
+ "content-type": type,
79
+ "cache-control": "no-cache",
80
+ ...(ext === ".html" ? { "content-security-policy": PAGE_CSP } : {}),
81
+ "content-length": Buffer.byteLength(body),
82
+ });
83
+ res.end(body);
84
+ },
85
+ };
86
+ }
@@ -0,0 +1,22 @@
1
+ import { stripTypeScriptTypes } from "node:module";
2
+ const STRIP_WARNING = "stripTypeScriptTypes is an experimental feature";
3
+ /**
4
+ * Removes TypeScript types from a browser module (erasable syntax only; anything else throws
5
+ * ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX). Node emits a one-time ExperimentalWarning on the first call; this function
6
+ * drops exactly that warning and passes every other warning through.
7
+ */
8
+ export function stripBrowserTypeScript(source, sourceUrl) {
9
+ const emitWarning = process.emitWarning;
10
+ process.emitWarning = ((warning, ...rest) => {
11
+ const message = typeof warning === "string" ? warning : warning.message;
12
+ if (message.startsWith(STRIP_WARNING))
13
+ return;
14
+ emitWarning.call(process, warning, ...rest);
15
+ });
16
+ try {
17
+ return stripTypeScriptTypes(source, { mode: "strip", sourceUrl });
18
+ }
19
+ finally {
20
+ process.emitWarning = emitWarning;
21
+ }
22
+ }