@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,171 @@
1
+ import { parseArgs } from "node:util";
2
+ import { createConfiguredMcpHub, createSession, createSettings, listSessions, nexoModels, resumeSession } from "../../core/src/index.js";
3
+ import { EFFORTS } from "../../router/src/index.js";
4
+ import { BUNDLED_SKILLS_DIR, loadSkills } from "../../skills/src/index.js";
5
+ import { ensureNexoDirs, getSessionRow, openDb, resolveNexoPaths, sessionNotFound } from "../../store/src/index.js";
6
+ import { NexoError, toErrorPayload } from "../../telemetry/src/index.js";
7
+ import { restoreTerminal, runInteractive, runSessionPicker, runSettingsScreen } from "../../tui/src/index.js";
8
+ import { EXIT_SIGINT, exitCodeFor, printError, requireTerminal, usageError } from "./common.js";
9
+ import { openLogger } from "./runtime.js";
10
+ /**
11
+ * While the TUI owns the terminal, any way the process can end must leave it usable: a normal exit, an uncaught
12
+ * exception and an unhandled rejection all restore it first (the last two then print the error and exit 1).
13
+ */
14
+ export function installCrashHandlers(options) {
15
+ const { proc, restore, stderr, exit } = options;
16
+ const redact = options.redact ?? ((text) => text);
17
+ const crash = (reason) => {
18
+ restore();
19
+ const detail = reason instanceof Error ? (reason.stack ?? reason.message) : String(reason);
20
+ stderr.write(`nexo crashed: ${redact(detail)}\n`);
21
+ exit(1);
22
+ };
23
+ const handlers = [
24
+ ["exit", restore],
25
+ ["uncaughtException", crash],
26
+ ["unhandledRejection", crash],
27
+ ];
28
+ for (const [event, handler] of handlers)
29
+ proc.on(event, handler);
30
+ return () => {
31
+ for (const [event, handler] of handlers)
32
+ proc.off(event, handler);
33
+ };
34
+ }
35
+ /** `--resume` takes an optional id, which `parseArgs` cannot express, so it is pulled out first. */
36
+ export function parseInteractiveArgs(args) {
37
+ const rest = [];
38
+ let resume = null;
39
+ for (let i = 0; i < args.length; i++) {
40
+ const arg = args[i];
41
+ if (arg === "--resume") {
42
+ const next = args[i + 1];
43
+ if (next !== undefined && !next.startsWith("-")) {
44
+ resume = { id: next };
45
+ i++;
46
+ }
47
+ else
48
+ resume = { id: null };
49
+ }
50
+ else if (arg.startsWith("--resume=")) {
51
+ resume = { id: arg.slice("--resume=".length) || null };
52
+ }
53
+ else
54
+ rest.push(arg);
55
+ }
56
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { workspace: { type: "string" }, model: { type: "string" }, effort: { type: "string" } } });
57
+ if (positionals.length > 0)
58
+ throw usageError(`Unexpected argument "${positionals[0]}"`);
59
+ if (values.effort !== undefined && !EFFORTS.includes(values.effort))
60
+ throw usageError(`--effort must be one of ${EFFORTS.join(", ")}`);
61
+ if (resume && (values.workspace !== undefined || values.model !== undefined || values.effort !== undefined)) {
62
+ throw usageError("--resume reopens a session as it was; --workspace, --model and --effort apply to new sessions only");
63
+ }
64
+ return { resume, workspace: values.workspace, model: values.model, effort: values.effort };
65
+ }
66
+ const PICKER_LIMIT = 50;
67
+ /**
68
+ * `nexo` and `nexo --resume [id]`: the chat. First run (no valid config) opens setup inside runInteractive.
69
+ */
70
+ export async function interactiveCommand(args, io, options, stdio) {
71
+ const parsed = parseInteractiveArgs(args);
72
+ requireTerminal(stdio, "nexo");
73
+ const env = options.env ?? process.env;
74
+ const cwd = options.cwd ?? process.cwd();
75
+ const paths = resolveNexoPaths(env);
76
+ ensureNexoDirs(paths);
77
+ const models = options.models ?? nexoModels();
78
+ const settings = createSettings({ paths, cwd, env, models });
79
+ const db = openDb(paths.db);
80
+ let resumeId = null;
81
+ if (parsed.resume) {
82
+ resumeId = parsed.resume.id;
83
+ if (resumeId === null) {
84
+ const rows = listSessions(db, { limit: PICKER_LIMIT });
85
+ if (rows.length === 0) {
86
+ throw new NexoError({ code: "NOT_FOUND", message: "No sessions to resume", hint: "Run `nexo` to start one" });
87
+ }
88
+ resumeId = await runSessionPicker({ sessions: rows, terminal: options.terminal, signal: options.signal });
89
+ if (resumeId === null)
90
+ return options.signal?.aborted ? EXIT_SIGINT : 0;
91
+ }
92
+ if (!getSessionRow(db, resumeId))
93
+ throw sessionNotFound(resumeId);
94
+ }
95
+ const exit = options.exit ?? (() => { });
96
+ const finish = (code) => {
97
+ exit(code);
98
+ return code;
99
+ };
100
+ const dispose = installCrashHandlers({ proc: options.proc ?? process, restore: restoreTerminal, redact: settings.redact, stderr: io.stderr, exit: options.exit ?? ((code) => process.exit(code)) });
101
+ // Started with the first session and kept for the next ones, so a browser connection survives across turns and sessions.
102
+ let mcp;
103
+ const buildDeps = (prompter) => {
104
+ const { config, hash } = settings.loadConfig();
105
+ const logger = openLogger(settings, paths, "tui");
106
+ const skills = loadSkills([BUNDLED_SKILLS_DIR, ...config.skills.dirs]);
107
+ for (const d of skills.diagnostics)
108
+ logger.warn("invalid skill skipped", { path: d.path, error: d.error });
109
+ if (mcp === undefined)
110
+ mcp = createConfiguredMcpHub(config, { cwd, logger });
111
+ return {
112
+ config,
113
+ configHash: hash,
114
+ paths,
115
+ db,
116
+ models,
117
+ logger,
118
+ redact: settings.redact,
119
+ prompter,
120
+ skills,
121
+ resolveApiKey: settings.resolveApiKey,
122
+ reloadConfig: () => settings.reloadConfig(),
123
+ ...(mcp ? { mcp } : {}),
124
+ };
125
+ };
126
+ try {
127
+ const code = await runInteractive({
128
+ settings,
129
+ db,
130
+ terminal: options.terminal,
131
+ signal: options.signal,
132
+ openSession: (prompter) => {
133
+ const deps = buildDeps(prompter);
134
+ return resumeId ? resumeSession(deps, resumeId) : createSession(deps, { cwd, workspace: parsed.workspace, model: parsed.model, effort: parsed.effort });
135
+ },
136
+ resumeSession: (id, prompter) => resumeSession(buildDeps(prompter), id),
137
+ });
138
+ await mcp?.close();
139
+ return finish(options.signal?.aborted && code === 0 ? EXIT_SIGINT : code);
140
+ }
141
+ catch (error) {
142
+ const payload = toErrorPayload(error);
143
+ printError(io, payload, settings.redact);
144
+ await mcp?.close();
145
+ return finish(exitCodeFor(payload.code));
146
+ }
147
+ finally {
148
+ dispose();
149
+ }
150
+ }
151
+ /** `nexo settings` with no subcommand: the same screen as `/settings`. */
152
+ export async function settingsScreenCommand(io, options, stdio) {
153
+ requireTerminal(stdio, "nexo settings");
154
+ const env = options.env ?? process.env;
155
+ const paths = resolveNexoPaths(env);
156
+ ensureNexoDirs(paths);
157
+ const settings = createSettings({ paths, cwd: options.cwd ?? process.cwd(), env, models: options.models ?? nexoModels() });
158
+ openLogger(settings, paths, "settings");
159
+ const dispose = installCrashHandlers({ proc: options.proc ?? process, restore: restoreTerminal, redact: settings.redact, stderr: io.stderr, exit: options.exit ?? ((code) => process.exit(code)) });
160
+ try {
161
+ const result = await runSettingsScreen({ settings, terminal: options.terminal, signal: options.signal });
162
+ if (result.error) {
163
+ printError(io, result.error, settings.redact);
164
+ return exitCodeFor(result.error.code);
165
+ }
166
+ return result.completed ? 0 : 1;
167
+ }
168
+ finally {
169
+ dispose();
170
+ }
171
+ }
@@ -0,0 +1,178 @@
1
+ import { parseArgs } from "node:util";
2
+ import { createSettings, nexoModels } from "../../core/src/index.js";
3
+ import { addMemory, addPlaybookItem, countLearnJobs, ensureNexoDirs, getActiveArtifact, isMemoryType, isSkillName, listMemories, listPlaybookItems, openDb, publishPlaybook, resolveNexoPaths, retireMemory, retirePlaybookItem, retryFailedLearnJobs, transaction, } from "../../store/src/index.js";
4
+ import { nonInteractivePrompter } from "../../tools/src/index.js";
5
+ import { escapeControl } from "../../tui/src/index.js";
6
+ import { usageError } from "./common.js";
7
+ import { createRuntime } from "./runtime.js";
8
+ const PREVIEW_CHARS = 100;
9
+ function oneLine(text, max = PREVIEW_CHARS) {
10
+ const flat = escapeControl(text.replace(/\s+/g, " ").trim());
11
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
12
+ }
13
+ /** One line per learn job as it finishes. */
14
+ export function learnEventLine(event) {
15
+ if (event.type !== "job_end")
16
+ return null;
17
+ const run = event.job.runId;
18
+ if (!event.ok)
19
+ return ` ✗ run ${run}: [${escapeControl(event.error.code)}] ${oneLine(event.error.message, 200)}`;
20
+ const c = event.outcome.curation;
21
+ const parts = [`${event.outcome.lessons} lesson${event.outcome.lessons === 1 ? "" : "s"}`];
22
+ if (c) {
23
+ if (c.memoriesAdded.length)
24
+ parts.push(`+${c.memoriesAdded.length} memor${c.memoriesAdded.length === 1 ? "y" : "ies"}`);
25
+ if (c.memoriesSuperseded.length)
26
+ parts.push(`${c.memoriesSuperseded.length} replaced`);
27
+ for (const v of c.playbookVersions)
28
+ parts.push(`playbook ${v.skill} v${v.version}`);
29
+ if (c.rejected.length)
30
+ parts.push(`${c.rejected.length} op${c.rejected.length === 1 ? "" : "s"} refused`);
31
+ }
32
+ const cost = event.outcome.costUnknown ? "cost unknown" : `$${event.outcome.costUsd.toFixed(4)}`;
33
+ return ` ✓ run ${run}: ${parts.join(", ")} · ${cost}`;
34
+ }
35
+ /** `nexo learn [--retry]`: runs pending learn jobs now; `--retry` first puts failed jobs with attempts left back to pending. Exits 1 when a job failed. */
36
+ export async function learnCommand(args, io, options) {
37
+ const { values } = parseArgs({ args, options: { retry: { type: "boolean" } } });
38
+ const runtime = createRuntime({
39
+ env: options.env ?? process.env,
40
+ cwd: options.cwd ?? process.cwd(),
41
+ prompter: nonInteractivePrompter,
42
+ models: options.models,
43
+ onLearnEvent: (event) => {
44
+ const line = learnEventLine(event);
45
+ if (line)
46
+ io.stdout.write(`${line}\n`);
47
+ },
48
+ });
49
+ try {
50
+ if (!runtime.config.learning.enabled) {
51
+ io.stdout.write("Learning is off (learning.enabled is false); no job was run.\n");
52
+ return 0;
53
+ }
54
+ if (values.retry) {
55
+ const n = retryFailedLearnJobs(runtime.db, new Date().toISOString());
56
+ io.stdout.write(`Retrying ${n} failed job${n === 1 ? "" : "s"}\n`);
57
+ }
58
+ const drained = await runtime.learner.drain({ signal: options.signal });
59
+ const counts = countLearnJobs(runtime.db);
60
+ io.stdout.write(`${drained.succeeded} succeeded, ${drained.failed} failed · ${counts.pending} pending, ${counts.failed} failed in total\n`);
61
+ if (counts.failed > 0)
62
+ io.stdout.write("Failed jobs with attempts left run again with `nexo learn --retry`.\n");
63
+ return drained.failed > 0 ? 1 : 0;
64
+ }
65
+ finally {
66
+ await runtime.mcp?.close();
67
+ runtime.db.close();
68
+ }
69
+ }
70
+ /** The database, the full redactor (config patterns and stored keys) and the config, for the memory, playbook, optimize and eval commands. */
71
+ export function openStore(options) {
72
+ const env = options.env ?? process.env;
73
+ const paths = resolveNexoPaths(env);
74
+ ensureNexoDirs(paths);
75
+ const settings = createSettings({ paths, cwd: options.cwd ?? process.cwd(), env, models: options.models ?? nexoModels() });
76
+ const { config } = settings.loadConfig();
77
+ const db = openDb(paths.db);
78
+ return { db, redact: settings.redact, config, close: () => db.close() };
79
+ }
80
+ function memoryLine(m) {
81
+ const state = m.retiredAt ? " [retired]" : m.supersededBy ? ` [replaced by ${m.supersededBy}]` : "";
82
+ return `${m.id} ${m.scope.padEnd(16)} ${m.type.padEnd(10)} ${m.source.padEnd(5)} ${m.importance.toFixed(2)} ${oneLine(m.content)}${state}`;
83
+ }
84
+ /** `nexo memory list [--scope s] [--type t] [--all]`, `nexo memory add <text…> [--scope] [--type] [--importance]`, `nexo memory retire <id>`. */
85
+ export function memoryCommand(args, io, options) {
86
+ const [sub, ...rest] = args;
87
+ const { values, positionals } = parseArgs({
88
+ args: rest,
89
+ allowPositionals: true,
90
+ options: { scope: { type: "string" }, type: { type: "string" }, importance: { type: "string" }, all: { type: "boolean" }, limit: { type: "string" } },
91
+ });
92
+ if (sub !== "list" && sub !== "add" && sub !== "retire")
93
+ throw usageError(sub === undefined ? "nexo memory needs list, add or retire" : `Unknown memory subcommand "${sub}"`);
94
+ const store = openStore(options);
95
+ try {
96
+ const now = new Date().toISOString();
97
+ if (sub === "list") {
98
+ const rows = listMemories(store.db, {
99
+ scope: values.scope,
100
+ type: values.type,
101
+ includeInactive: values.all === true,
102
+ limit: values.limit === undefined ? 200 : Number(values.limit),
103
+ });
104
+ for (const m of rows)
105
+ io.stdout.write(`${memoryLine(m)}\n`);
106
+ io.stdout.write(`${rows.length} memor${rows.length === 1 ? "y" : "ies"}\n`);
107
+ return 0;
108
+ }
109
+ if (sub === "add") {
110
+ const text = positionals.join(" ").trim();
111
+ if (!text)
112
+ throw usageError("nexo memory add needs the memory text");
113
+ const type = values.type ?? "fact";
114
+ if (!isMemoryType(type))
115
+ throw usageError("--type must be fact, preference, lesson or workflow");
116
+ const importance = values.importance === undefined ? 0.8 : Number(values.importance);
117
+ const m = addMemory(store.db, { scope: values.scope ?? "user", type, content: text, importance, source: "user" }, store.redact, now);
118
+ io.stdout.write(`Added memory ${m.id} (${m.scope}, ${m.type})\n`);
119
+ return 0;
120
+ }
121
+ const [id] = positionals;
122
+ if (!id)
123
+ throw usageError("nexo memory retire needs a memory id");
124
+ retireMemory(store.db, id, "user", now);
125
+ io.stdout.write(`Retired memory ${id}\n`);
126
+ return 0;
127
+ }
128
+ finally {
129
+ store.close();
130
+ }
131
+ }
132
+ /** `nexo playbook show <skill> [--all]`, `nexo playbook add <skill> <text…>` (a human item), `nexo playbook retire <skill> <key>`. */
133
+ export function playbookCommand(args, io, options) {
134
+ const [sub, skill, ...rest] = args;
135
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { all: { type: "boolean" } } });
136
+ if (sub !== "show" && sub !== "add" && sub !== "retire")
137
+ throw usageError(sub === undefined ? "nexo playbook needs show, add or retire" : `Unknown playbook subcommand "${sub}"`);
138
+ if (!isSkillName(skill))
139
+ throw usageError(`nexo playbook ${sub} needs a skill name`);
140
+ const store = openStore(options);
141
+ try {
142
+ const now = new Date().toISOString();
143
+ if (sub === "show") {
144
+ const artifact = getActiveArtifact(store.db, "playbook", skill);
145
+ const items = listPlaybookItems(store.db, skill, { includeRetired: values.all === true });
146
+ io.stdout.write(`Playbook ${skill}${artifact ? ` · version ${artifact.version} (${artifact.origin})` : " · no version yet"}\n`);
147
+ for (const i of items) {
148
+ io.stdout.write(` [${i.key}] ${i.source.padEnd(5)} +${i.helpful}/-${i.harmful} ${oneLine(i.content, 200)}${i.status === "retired" ? " [retired]" : ""}\n`);
149
+ }
150
+ if (items.length === 0)
151
+ io.stdout.write(" (no items)\n");
152
+ return 0;
153
+ }
154
+ if (sub === "add") {
155
+ const text = positionals.join(" ").trim();
156
+ if (!text)
157
+ throw usageError("nexo playbook add needs the item text");
158
+ const { item, version } = transaction(store.db, () => {
159
+ const added = addPlaybookItem(store.db, { skill, content: text, source: "human" }, store.redact, now);
160
+ return { item: added, version: publishPlaybook(store.db, skill, "manual", now) };
161
+ });
162
+ io.stdout.write(`Added ${skill}/${item.key}${version ? ` · playbook version ${version.version}` : ""}\n`);
163
+ return 0;
164
+ }
165
+ const [key] = positionals;
166
+ if (!key)
167
+ throw usageError("nexo playbook retire needs an item key");
168
+ const version = transaction(store.db, () => {
169
+ retirePlaybookItem(store.db, skill, key, "user", now);
170
+ return publishPlaybook(store.db, skill, "manual", now);
171
+ });
172
+ io.stdout.write(`Retired ${skill}/${key}${version ? ` · playbook version ${version.version}` : ""}\n`);
173
+ return 0;
174
+ }
175
+ finally {
176
+ store.close();
177
+ }
178
+ }
@@ -0,0 +1,261 @@
1
+ import { parseArgs } from "node:util";
2
+ import { judgeFamilyWarnings } from "../../core/src/index.js";
3
+ import { EFFORTS } from "../../router/src/index.js";
4
+ import { costReport, ensureNexoDirs, openDb, reindex, resolveNexoPaths } from "../../store/src/index.js";
5
+ import { NexoError, toErrorPayload } from "../../telemetry/src/index.js";
6
+ import { nonInteractivePrompter } from "../../tools/src/index.js";
7
+ import { EXIT_SIGINT, EXIT_SIGTERM, exitCodeFor, printError, USAGE, usageError } from "./common.js";
8
+ import { evalCommand } from "./eval.js";
9
+ import { learnCommand, learnEventLine, memoryCommand, playbookCommand } from "./learn.js";
10
+ import { optimizeCommand } from "./optimize.js";
11
+ import { createTtyPrompter } from "./prompter.js";
12
+ import { createTtyLineAsker, isInteractiveTerminal, promptReview } from "./review.js";
13
+ import { createRuntime } from "./runtime.js";
14
+ import { interactiveCommand, settingsScreenCommand } from "./interactive.js";
15
+ import { sessionsCommand } from "./sessions.js";
16
+ import { doctorCommand } from "./doctor.js";
17
+ import { initCommand } from "./init.js";
18
+ import { settingsCommand } from "./settings.js";
19
+ import { escapeControl } from "../../tui/src/index.js";
20
+ import { runUi } from "./ui.js";
21
+ export { EXIT_SIGINT, EXIT_SIGTERM, exitCodeFor };
22
+ /**
23
+ * Aborts `controller` on the first SIGINT or SIGTERM and exits the process on any later one. The exit goes through
24
+ * `exit` (process.exit by default) so exit handlers still run; `received()` names the first signal.
25
+ */
26
+ export function abortOnSignals(source, controller, exit = (code) => process.exit(code)) {
27
+ let first;
28
+ const handlers = ["SIGINT", "SIGTERM"].map((name) => {
29
+ const handler = () => {
30
+ if (first)
31
+ return exit(name === "SIGINT" ? EXIT_SIGINT : EXIT_SIGTERM);
32
+ first = name;
33
+ controller.abort();
34
+ };
35
+ source.on(name, handler);
36
+ return [name, handler];
37
+ });
38
+ return { received: () => first, dispose: () => handlers.forEach(([name, handler]) => source.off(name, handler)) };
39
+ }
40
+ /**
41
+ * Ctrl-C at a prompt is consumed by readline, so it is re-raised as SIGINT and aborts the run through the same handler
42
+ * as a Ctrl-C anywhere else.
43
+ */
44
+ function defaultPrompter() {
45
+ if (!process.stdin.isTTY)
46
+ return nonInteractivePrompter;
47
+ return createTtyPrompter(process.stdin, process.stdout, { onInterrupt: () => process.kill(process.pid, "SIGINT") });
48
+ }
49
+ /** The review prompt runs only when a person is at the terminal; piped, redirected or scripted runs never block on it. */
50
+ function defaultReviewAsker() {
51
+ if (!isInteractiveTerminal(process))
52
+ return null;
53
+ return createTtyLineAsker(process.stdin, process.stderr);
54
+ }
55
+ /** The line printed when a run escalates to S2; the reason is model-influenced text, so it is control-escaped. */
56
+ export function escalationLine(depth, model, trigger, reason) {
57
+ return `\n${" ".repeat(depth)} ↑ escalating to ${escapeControl(model)} (${trigger}: ${escapeControl(reason)})\n`;
58
+ }
59
+ /**
60
+ * One line per scorer of the latest scoring round, then the escalation count and how a failed S2 continuation ended.
61
+ * Scorer and error text is model-influenced, so it is control-escaped.
62
+ */
63
+ export function scoreLines(result) {
64
+ const lines = (result.scores ?? []).map((s) => {
65
+ const name = escapeControl(s.scorerName);
66
+ if (s.status === "failed")
67
+ return ` score ${name}: failed [${s.error?.code ?? "SCORER_FAILED"}] ${escapeControl(s.error?.message ?? "")}`.trimEnd();
68
+ const value = s.value === null ? "–" : s.value.toFixed(2);
69
+ const family = Array.isArray(s.details.sameFamily) && s.details.sameFamily.length > 0 ? " (same-family judge)" : "";
70
+ const verdict = s.passed === null ? "–" : s.passed ? "✓ pass" : "✗ fail";
71
+ return ` score ${name}: ${value} ${verdict}${family}`;
72
+ });
73
+ if (result.escalations)
74
+ lines.push(` escalated to s2 ${result.escalations === 1 ? "once" : `${result.escalations} times`}`);
75
+ const failed = result.continuationError;
76
+ if (failed)
77
+ lines.push(` ✗ s2 continuation failed [${escapeControl(failed.code)}] ${escapeControl(failed.message)}; kept the previous answer`);
78
+ return lines;
79
+ }
80
+ async function runCommand(args, io, options) {
81
+ const { values, positionals } = parseArgs({
82
+ args,
83
+ allowPositionals: true,
84
+ options: {
85
+ skill: { type: "string" },
86
+ model: { type: "string" },
87
+ effort: { type: "string" },
88
+ workspace: { type: "string" },
89
+ budget: { type: "string" },
90
+ "no-review": { type: "boolean" },
91
+ },
92
+ });
93
+ const instruction = positionals.join(" ").trim();
94
+ if (!instruction)
95
+ throw usageError("nexo run needs an instruction");
96
+ if (values.effort !== undefined && !EFFORTS.includes(values.effort)) {
97
+ throw usageError(`--effort must be one of ${EFFORTS.join(", ")}`);
98
+ }
99
+ const budgetUsd = values.budget === undefined ? undefined : Number(values.budget);
100
+ if (budgetUsd !== undefined && !(Number.isFinite(budgetUsd) && budgetUsd > 0))
101
+ throw usageError("--budget must be a positive number of USD");
102
+ const runtime = createRuntime({
103
+ env: options.env ?? process.env,
104
+ cwd: options.cwd ?? process.cwd(),
105
+ prompter: options.prompter ?? defaultPrompter(),
106
+ models: options.models,
107
+ onEvent: (event) => {
108
+ if (event.type === "text_delta" && event.depth === 0)
109
+ io.stdout.write(event.delta);
110
+ if (event.type === "run_start" && event.depth > 0)
111
+ io.stderr.write(` ↳ subagent ${event.runId.slice(-6)}: ${event.instruction.split("\n")[0]?.slice(0, 80)}\n`);
112
+ if (event.type === "tool_start")
113
+ io.stderr.write(`${" ".repeat(event.depth)} · ${event.toolName}\n`);
114
+ if (event.type === "approval")
115
+ io.stderr.write(`\x1b[2m${" ".repeat(event.depth)} auto-allowed: ${escapeControl(event.reason)}\x1b[22m\n`);
116
+ if (event.type === "escalation" && event.applied)
117
+ io.stderr.write(escalationLine(event.depth, event.model, event.trigger, event.reason));
118
+ },
119
+ onLearnEvent: (event) => {
120
+ const line = learnEventLine(event);
121
+ if (line)
122
+ io.stderr.write(`learn${line.slice(1)}\n`);
123
+ },
124
+ });
125
+ for (const warning of judgeFamilyWarnings(runtime.config))
126
+ io.stderr.write(`warning: ${escapeControl(warning)}\n`);
127
+ let result;
128
+ try {
129
+ result = await runtime.engine.run({
130
+ instruction,
131
+ skill: values.skill,
132
+ model: values.model,
133
+ effort: values.effort,
134
+ workspace: values.workspace,
135
+ budgetUsd,
136
+ }, options.signal);
137
+ }
138
+ finally {
139
+ await runtime.mcp?.close();
140
+ }
141
+ io.stdout.write("\n");
142
+ const mark = result.status === "succeeded" ? "✓" : "✗";
143
+ const unknown = result.costUnknown ? " (some calls unpriced)" : "";
144
+ io.stderr.write(`${mark} ${result.status} · $${result.costUsd.toFixed(4)}${unknown} · trajectory ${result.trajectoryId ?? "-"}${result.runDir ? ` · ${result.runDir}` : ""}\n`);
145
+ for (const line of scoreLines(result))
146
+ io.stderr.write(`${line}\n`);
147
+ if (result.error)
148
+ printError(io, result.error);
149
+ if (result.status === "aborted")
150
+ return EXIT_SIGINT;
151
+ const asker = values["no-review"] ? null : options.reviewAsker === undefined ? defaultReviewAsker() : options.reviewAsker;
152
+ if (asker && result.trajectoryId) {
153
+ if (options.signal?.aborted)
154
+ return EXIT_SIGINT;
155
+ try {
156
+ await promptReview({ asker, db: runtime.db, runId: result.trajectoryId, redact: runtime.redact, io, signal: options.signal, learn: runtime.config.learning.enabled });
157
+ }
158
+ catch (error) {
159
+ if (!(error instanceof NexoError))
160
+ throw error;
161
+ printError(io, error.toPayload());
162
+ }
163
+ if (options.signal?.aborted)
164
+ return EXIT_SIGINT;
165
+ }
166
+ // Learn from this run now, bounded by learning.drainAfterRunMs; a learning failure never changes the exit code.
167
+ const drainMs = runtime.config.learning.enabled ? runtime.config.learning.drainAfterRunMs : 0;
168
+ if (drainMs > 0) {
169
+ try {
170
+ await runtime.learner.drain({ deadlineMs: drainMs, signal: options.signal });
171
+ }
172
+ catch (error) {
173
+ runtime.logger.warn("learning after the run failed", { error });
174
+ }
175
+ }
176
+ if (result.status === "succeeded")
177
+ return 0;
178
+ return result.error ? exitCodeFor(result.error.code) : 1;
179
+ }
180
+ function costCommand(args, io, options) {
181
+ const { values } = parseArgs({ args, options: { by: { type: "string" }, since: { type: "string" } } });
182
+ const paths = resolveNexoPaths(options.env ?? process.env);
183
+ ensureNexoDirs(paths);
184
+ let report;
185
+ try {
186
+ report = costReport(openDb(paths.db), { by: values.by ?? "model", since: values.since });
187
+ }
188
+ catch (error) {
189
+ if (error instanceof NexoError && error.code === "INVALID_REQUEST")
190
+ throw usageError(error.message);
191
+ throw error;
192
+ }
193
+ io.stdout.write(`Cost by ${report.by} since ${report.since}\n`);
194
+ for (const r of report.rows) {
195
+ io.stdout.write(` ${r.key.padEnd(40)} $${r.costUsd.toFixed(4).padStart(10)} ${r.calls} calls${r.unknownCalls ? ` (${r.unknownCalls} unpriced)` : ""}\n`);
196
+ }
197
+ io.stdout.write(` ${"total".padEnd(40)} $${report.totalUsd.toFixed(4).padStart(10)}\n`);
198
+ return 0;
199
+ }
200
+ function reindexCommand(io, options) {
201
+ const paths = resolveNexoPaths(options.env ?? process.env);
202
+ ensureNexoDirs(paths);
203
+ const result = reindex(openDb(paths.db), paths.runs, paths.sessions, paths.optim);
204
+ io.stdout.write(`Reindexed ${result.runs} runs, ${result.spans} spans, ${result.sessions} sessions\n`);
205
+ for (const dir of result.skipped)
206
+ io.stderr.write(`skipped unreadable directory: ${dir}\n`);
207
+ return 0;
208
+ }
209
+ export async function runCli(argv, io, options = {}) {
210
+ const [command, ...rest] = argv;
211
+ const stdio = options.stdio ?? process;
212
+ try {
213
+ if (command === undefined || (command.startsWith("-") && command !== "--help" && command !== "-h")) {
214
+ return await interactiveCommand(argv, io, options, stdio);
215
+ }
216
+ switch (command) {
217
+ case "run":
218
+ return await runCommand(rest, io, options);
219
+ case "cost":
220
+ return costCommand(rest, io, options);
221
+ case "reindex":
222
+ return reindexCommand(io, options);
223
+ case "eval":
224
+ return await evalCommand(rest, io, options);
225
+ case "optimize":
226
+ return await optimizeCommand(rest, io, options);
227
+ case "learn":
228
+ return await learnCommand(rest, io, options);
229
+ case "memory":
230
+ return memoryCommand(rest, io, options);
231
+ case "playbook":
232
+ return playbookCommand(rest, io, options);
233
+ case "doctor":
234
+ return doctorCommand(rest, io, options);
235
+ case "init":
236
+ return await initCommand(rest, io, options, stdio);
237
+ case "sessions":
238
+ return sessionsCommand(rest, io, options);
239
+ case "settings":
240
+ return rest.length === 0 ? await settingsScreenCommand(io, options, stdio) : await settingsCommand(rest, io, options, stdio);
241
+ case "ui": {
242
+ const { values } = parseArgs({ args: rest, options: { port: { type: "string" } } });
243
+ return await runUi({ env: options.env ?? process.env, cwd: options.cwd ?? process.cwd(), port: values.port, io, signal: options.signal, models: options.models });
244
+ }
245
+ case "help":
246
+ case "--help":
247
+ case "-h":
248
+ io.stdout.write(USAGE);
249
+ return 0;
250
+ default:
251
+ throw usageError(`Unknown command "${command}"`);
252
+ }
253
+ }
254
+ catch (error) {
255
+ const payload = error instanceof TypeError && "code" in error && String(error.code).startsWith("ERR_PARSE_ARGS")
256
+ ? usageError(error.message).toPayload()
257
+ : toErrorPayload(error);
258
+ printError(io, payload);
259
+ return exitCodeFor(payload.code);
260
+ }
261
+ }