@hexdecimal16/nexo 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +75 -0
- package/README.md +75 -2
- package/cli/src/bin.js +12 -0
- package/cli/src/common.js +78 -0
- package/cli/src/doctor.js +27 -0
- package/cli/src/eval-cases.js +65 -0
- package/cli/src/eval.js +67 -0
- package/cli/src/init.js +186 -0
- package/cli/src/interactive.js +171 -0
- package/cli/src/learn.js +178 -0
- package/cli/src/main.js +266 -0
- package/cli/src/optimize.js +289 -0
- package/cli/src/prompter.js +47 -0
- package/cli/src/review.js +120 -0
- package/cli/src/runtime.js +2 -0
- package/cli/src/sessions.js +34 -0
- package/cli/src/settings.js +169 -0
- package/cli/src/ui.js +112 -0
- package/cli/src/version.js +19 -0
- package/core/src/approval/classifier.js +152 -0
- package/core/src/config/load.js +283 -0
- package/core/src/config/schema.js +186 -0
- package/core/src/cost/admission.js +90 -0
- package/core/src/cost/budget.js +67 -0
- package/core/src/cost/pricing.js +53 -0
- package/core/src/engine/charged-completion.js +79 -0
- package/core/src/engine/errors.js +77 -0
- package/core/src/engine/mcp.js +11 -0
- package/core/src/engine/messages.js +86 -0
- package/core/src/engine/prompts.js +32 -0
- package/core/src/engine/provider-gate.js +33 -0
- package/core/src/engine/recorder.js +61 -0
- package/core/src/engine/run.js +1115 -0
- package/core/src/engine/semaphore.js +45 -0
- package/core/src/engine/spawn-tool.js +119 -0
- package/core/src/engine/task-graph.js +153 -0
- package/core/src/index.js +32 -0
- package/core/src/learn/caller.js +171 -0
- package/core/src/learn/context.js +112 -0
- package/core/src/learn/embedder.js +216 -0
- package/core/src/learn/job.js +196 -0
- package/core/src/learn/wiki.js +116 -0
- package/core/src/learn/worker.js +141 -0
- package/core/src/optimize/adapter.js +250 -0
- package/core/src/optimize/climb.js +338 -0
- package/core/src/optimize/mine.js +95 -0
- package/core/src/optimize/optimize.js +377 -0
- package/core/src/optimize/optimizer-run.js +67 -0
- package/core/src/optimize/reflect.js +100 -0
- package/core/src/optimize/scratchpad-wiki.js +69 -0
- package/core/src/providers/claude-p.js +363 -0
- package/core/src/providers/kiro-p.js +408 -0
- package/core/src/providers/models.js +10 -0
- package/core/src/scoring/calibration.js +31 -0
- package/core/src/scoring/continuation.js +24 -0
- package/core/src/scoring/runner.js +322 -0
- package/core/src/scoring/sources.js +88 -0
- package/core/src/session/lock.js +88 -0
- package/core/src/session/session.js +647 -0
- package/core/src/session/shell.js +26 -0
- package/core/src/session/transcript.js +86 -0
- package/core/src/settings/config-edit.js +472 -0
- package/core/src/settings/credentials.js +120 -0
- package/core/src/settings/doctor.js +103 -0
- package/core/src/settings/settings.js +265 -0
- package/mcp/src/hub.js +184 -0
- package/mcp/src/index.js +1 -0
- package/memory/src/curate.js +121 -0
- package/memory/src/index.js +4 -0
- package/memory/src/prompts.js +143 -0
- package/memory/src/retrieval.js +91 -0
- package/memory/src/similarity.js +47 -0
- package/optimize/src/engine.js +206 -0
- package/optimize/src/index.js +8 -0
- package/optimize/src/merge.js +73 -0
- package/optimize/src/novelty.js +37 -0
- package/optimize/src/pareto.js +83 -0
- package/optimize/src/proposer.js +148 -0
- package/optimize/src/report.js +107 -0
- package/optimize/src/rng.js +34 -0
- package/optimize/src/target.js +34 -0
- package/package.json +47 -4
- package/router/src/effort.js +5 -0
- package/router/src/escalation.js +171 -0
- package/router/src/index.js +4 -0
- package/router/src/registry.js +21 -0
- package/router/src/resolve.js +117 -0
- package/scorers/src/deterministic.js +194 -0
- package/scorers/src/family.js +48 -0
- package/scorers/src/index.js +6 -0
- package/scorers/src/judge.js +284 -0
- package/scorers/src/regex-worker.js +3 -0
- package/scorers/src/spec.js +147 -0
- package/scorers/src/trajectory.js +22 -0
- package/scorers/src/types.js +1 -0
- package/sdk/src/index.js +3 -0
- package/sdk/src/nexo.js +94 -0
- package/sdk/src/runtime.js +39 -0
- package/skills/bundled/browser/SKILL.md +57 -0
- package/skills/bundled/wiki/SKILL.md +73 -0
- package/skills/src/frontmatter.js +25 -0
- package/skills/src/index.js +3 -0
- package/skills/src/load-skill-tool.js +41 -0
- package/skills/src/loader.js +95 -0
- package/store/src/artifacts.js +124 -0
- package/store/src/budget-ledger.js +18 -0
- package/store/src/cost-report.js +46 -0
- package/store/src/cursor.js +35 -0
- package/store/src/db.js +83 -0
- package/store/src/errors.js +9 -0
- package/store/src/eval-cases.js +255 -0
- package/store/src/feedback.js +154 -0
- package/store/src/goldens.js +61 -0
- package/store/src/ids.js +6 -0
- package/store/src/index.js +25 -0
- package/store/src/judge-calibration.js +182 -0
- package/store/src/learn-jobs.js +145 -0
- package/store/src/memories.js +261 -0
- package/store/src/migrations/001_init.sql +81 -0
- package/store/src/migrations/002_feedback.sql +9 -0
- package/store/src/migrations/003_sessions.sql +19 -0
- package/store/src/migrations/004_scoring.sql +22 -0
- package/store/src/migrations/005_judge_calibration.sql +27 -0
- package/store/src/migrations/006_learning.sql +77 -0
- package/store/src/migrations/007_optimize.sql +55 -0
- package/store/src/migrations/008_mined_cases_and_climb.sql +46 -0
- package/store/src/mine.js +51 -0
- package/store/src/optim.js +291 -0
- package/store/src/paths.js +22 -0
- package/store/src/playbooks.js +199 -0
- package/store/src/reindex.js +143 -0
- package/store/src/run-dir.js +151 -0
- package/store/src/runs.js +310 -0
- package/store/src/scores.js +92 -0
- package/store/src/sessions.js +304 -0
- package/store/src/span-tree.js +98 -0
- package/store/src/spans.js +84 -0
- package/store/src/sql.js +13 -0
- package/store/src/workspace-copy.js +80 -0
- package/telemetry/src/errors.js +32 -0
- package/telemetry/src/index.js +3 -0
- package/telemetry/src/logger.js +39 -0
- package/telemetry/src/redact.js +106 -0
- package/tools/src/builtin.js +269 -0
- package/tools/src/change-tracker.js +57 -0
- package/tools/src/confine.js +101 -0
- package/tools/src/index.js +7 -0
- package/tools/src/leases.js +57 -0
- package/tools/src/policy.js +162 -0
- package/tools/src/read-only.js +338 -0
- package/tools/src/session-rules.js +140 -0
- package/tui/src/app.js +965 -0
- package/tui/src/approvals.js +96 -0
- package/tui/src/commands.js +38 -0
- package/tui/src/components.js +248 -0
- package/tui/src/index.js +5 -0
- package/tui/src/picker.js +78 -0
- package/tui/src/session-picker.js +100 -0
- package/tui/src/settings-screen.js +346 -0
- package/tui/src/text.js +70 -0
- package/tui/src/theme.js +44 -0
- package/web/public/cost.html +25 -0
- package/web/public/fonts/GeistMono-400.woff2 +0 -0
- package/web/public/fonts/GeistMono-600.woff2 +0 -0
- package/web/public/fonts/InstrumentSans-400.woff2 +0 -0
- package/web/public/fonts/InstrumentSans-600.woff2 +0 -0
- package/web/public/index.html +39 -0
- package/web/public/judge.html +21 -0
- package/web/public/learning.html +46 -0
- package/web/public/lib/api-types.ts +616 -0
- package/web/public/lib/common-view.ts +47 -0
- package/web/public/lib/cost-view.ts +35 -0
- package/web/public/lib/files-view.ts +90 -0
- package/web/public/lib/format.ts +35 -0
- package/web/public/lib/html.ts +51 -0
- package/web/public/lib/judge-view.ts +62 -0
- package/web/public/lib/learning-view.ts +102 -0
- package/web/public/lib/optim-view.ts +148 -0
- package/web/public/lib/pager.ts +56 -0
- package/web/public/lib/poller.ts +79 -0
- package/web/public/lib/run-view.ts +61 -0
- package/web/public/lib/runs-view.ts +87 -0
- package/web/public/lib/score-view.ts +94 -0
- package/web/public/lib/sessions-view.ts +28 -0
- package/web/public/lib/span-view.ts +90 -0
- package/web/public/lib/theme.ts +60 -0
- package/web/public/lib/timeline.ts +97 -0
- package/web/public/lib/wikis-view.ts +257 -0
- package/web/public/optim.html +30 -0
- package/web/public/pages/api.ts +60 -0
- package/web/public/pages/cost.ts +36 -0
- package/web/public/pages/judge.ts +15 -0
- package/web/public/pages/learning.ts +92 -0
- package/web/public/pages/optim.ts +68 -0
- package/web/public/pages/paging.ts +18 -0
- package/web/public/pages/run.ts +221 -0
- package/web/public/pages/runs.ts +91 -0
- package/web/public/pages/sessions.ts +25 -0
- package/web/public/pages/wikis.ts +103 -0
- package/web/public/run.html +36 -0
- package/web/public/sessions.html +28 -0
- package/web/public/style.css +288 -0
- package/web/public/wikis.html +25 -0
- package/web/src/api.js +682 -0
- package/web/src/http-errors.js +60 -0
- package/web/src/index.js +5 -0
- package/web/src/server.js +292 -0
- package/web/src/static.js +86 -0
- package/web/src/strip.js +22 -0
package/tui/src/app.js
ADDED
|
@@ -0,0 +1,965 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { sep } from "node:path";
|
|
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";
|
|
5
|
+
import { getSessionRow, sessionNotFound } from "../../store/src/index.js";
|
|
6
|
+
import { toErrorPayload } from "../../telemetry/src/index.js";
|
|
7
|
+
import { describeSessionRule } from "../../tools/src/index.js";
|
|
8
|
+
import { createApprovalPrompter } from "./approvals.js";
|
|
9
|
+
import { helpText, parseSlashCommand, SLASH_COMMANDS } from "./commands.js";
|
|
10
|
+
import { Block, DynamicLine, QueuedList, SafeContainer, SafeMarkdown, SubagentLine, Ticker, ToolLine, ViewMode } from "./components.js";
|
|
11
|
+
import { createSessionPickerScreen } from "./session-picker.js";
|
|
12
|
+
import { SettingsScreen } from "./settings-screen.js";
|
|
13
|
+
import { escapeControl, escapeControlKeepLines, formatError, oneLine, toolSummary, usd } from "./text.js";
|
|
14
|
+
import { editorTheme, markdownTheme, shellBorder, style } from "./theme.js";
|
|
15
|
+
/** Shortens a path under the user's home directory to `~/…`. */
|
|
16
|
+
function tildePath(path) {
|
|
17
|
+
const home = homedir();
|
|
18
|
+
return home && (path === home || path.startsWith(home + sep)) ? `~${path.slice(home.length)}` : path;
|
|
19
|
+
}
|
|
20
|
+
/** Where the session's files go: the `--workspace` folder, else each turn's run folder. Control-escaped. */
|
|
21
|
+
function filesLine(session) {
|
|
22
|
+
if (session.workspace !== null)
|
|
23
|
+
return `files: ${escapeControl(tildePath(session.workspace))}`;
|
|
24
|
+
return `files: ${escapeControl(tildePath(session.runsDir))}/<turn id>/workspace (carried over each turn)`;
|
|
25
|
+
}
|
|
26
|
+
const DOUBLE_CTRL_C_MS = 1000;
|
|
27
|
+
/** Two Esc presses within this window on an idle prompt clear the draft (and keep it in history). */
|
|
28
|
+
const DOUBLE_ESC_MS = 800;
|
|
29
|
+
/** Last lines of a `!` command's output shown in the chat (the model gets more). */
|
|
30
|
+
const SHELL_SCREEN_LINES = 200;
|
|
31
|
+
/** Time given to paint the "opening…" footer before the synchronous session open blocks the loop (one render interval and a margin). */
|
|
32
|
+
const OPENING_PAINT_MS = 30;
|
|
33
|
+
const EXIT_TIMEOUT_MS = 5000;
|
|
34
|
+
/** Started TUIs, so `restoreTerminal` can stop them from a crash handler. */
|
|
35
|
+
const activeTuis = new Set();
|
|
36
|
+
/** Starts a TUI that `restoreTerminal` puts back on exit or crash. */
|
|
37
|
+
export function startTui(tui) {
|
|
38
|
+
// Links render as "text (url)": an OSC 8 hyperlink would hide the real target behind the text.
|
|
39
|
+
setCapabilityOverrides({ hyperlinks: false });
|
|
40
|
+
activeTuis.add(tui);
|
|
41
|
+
tui.start();
|
|
42
|
+
}
|
|
43
|
+
export function stopTui(tui) {
|
|
44
|
+
if (!activeTuis.delete(tui))
|
|
45
|
+
return;
|
|
46
|
+
tui.stop();
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Restores the terminal (raw mode off, cursor shown, keyboard protocol popped) for every TUI this package started.
|
|
50
|
+
* Synchronous and safe to call more than once; meant for the CLI's `exit`, `uncaughtException` and
|
|
51
|
+
* `unhandledRejection` handlers. The package installs no process handlers itself.
|
|
52
|
+
*/
|
|
53
|
+
export function restoreTerminal() {
|
|
54
|
+
for (const tui of [...activeTuis]) {
|
|
55
|
+
activeTuis.delete(tui);
|
|
56
|
+
try {
|
|
57
|
+
tui.stop();
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
// Best effort: the terminal may already be gone.
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const TICK_MS = 80;
|
|
65
|
+
function textOf(content) {
|
|
66
|
+
if (typeof content === "string")
|
|
67
|
+
return content;
|
|
68
|
+
if (!Array.isArray(content))
|
|
69
|
+
return "";
|
|
70
|
+
return content.map((b) => (b && typeof b === "object" && b.type === "text" ? String(b.text ?? "") : "")).join("");
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* `score 0.82 ✓` for the latest scoring round of a turn (mean of the scorers that answered), followed by `· N failed`
|
|
74
|
+
* when some scorers failed; null when nothing scored it.
|
|
75
|
+
*/
|
|
76
|
+
export function scoreSummary(result) {
|
|
77
|
+
const scores = result.scores ?? [];
|
|
78
|
+
if (scores.length === 0)
|
|
79
|
+
return null;
|
|
80
|
+
const answered = scores.filter((s) => s.status === "ok" && s.value !== null);
|
|
81
|
+
if (answered.length === 0)
|
|
82
|
+
return "score failed";
|
|
83
|
+
const mean = answered.reduce((sum, s) => sum + (s.value ?? 0), 0) / answered.length;
|
|
84
|
+
const failed = scores.filter((s) => s.status === "failed").length;
|
|
85
|
+
// A scorer without a pass/fail verdict (passed null) neither passes nor fails the turn.
|
|
86
|
+
const mark = answered.some((s) => s.passed === false) ? "✗" : answered.some((s) => s.passed === true) ? "✓" : "–";
|
|
87
|
+
return `score ${mean.toFixed(2)} ${mark}${failed > 0 ? ` · ${failed} failed` : ""}`;
|
|
88
|
+
}
|
|
89
|
+
/** The verdict shown on a chat score line: `0.82 ✓`, `0.40 ✗`, `0.50 –` (no pass/fail verdict) or `failed`. */
|
|
90
|
+
export function scoreVerdict(score) {
|
|
91
|
+
if (score.status === "failed")
|
|
92
|
+
return style.red("failed");
|
|
93
|
+
const value = score.value === null ? "–" : score.value.toFixed(2);
|
|
94
|
+
return `${value} ${score.passed === null ? style.gray("–") : score.passed ? style.green("✓") : style.red("✗")}`;
|
|
95
|
+
}
|
|
96
|
+
/** Runs the chat UI: the conversation, the editor, the footer, approvals, slash commands and the settings screen. */
|
|
97
|
+
class InteractiveApp {
|
|
98
|
+
options;
|
|
99
|
+
settings;
|
|
100
|
+
terminal;
|
|
101
|
+
tui;
|
|
102
|
+
chat = new Container();
|
|
103
|
+
status = new Container();
|
|
104
|
+
slot = new Container();
|
|
105
|
+
editor;
|
|
106
|
+
ticker = new Ticker();
|
|
107
|
+
now;
|
|
108
|
+
prompter;
|
|
109
|
+
session = null;
|
|
110
|
+
screen = "chat";
|
|
111
|
+
running = false;
|
|
112
|
+
turnAbort = null;
|
|
113
|
+
turnPromise = null;
|
|
114
|
+
/** The running work is a `!` command, not a turn. */
|
|
115
|
+
runningShell = false;
|
|
116
|
+
/** Messages typed while a turn or command runs; sent one at a time once it ends, moved back to the editor on abort or failure. */
|
|
117
|
+
queued = [];
|
|
118
|
+
queueView = new QueuedList(() => this.queued.map((q) => q.text));
|
|
119
|
+
turnCost = 0;
|
|
120
|
+
lastTurnCost = 0;
|
|
121
|
+
/** The last turn's approver spend: shown by /cost, never counted against a budget. */
|
|
122
|
+
lastTurnApprovalCost = 0;
|
|
123
|
+
/** Footer text for the latest turn's scores, e.g. `score 0.82 ✓`; null when nothing scored it. */
|
|
124
|
+
lastScore = null;
|
|
125
|
+
currentText = null;
|
|
126
|
+
tools = new Map();
|
|
127
|
+
view = new ViewMode();
|
|
128
|
+
subagents = new Map();
|
|
129
|
+
tickTimer = null;
|
|
130
|
+
loader = null;
|
|
131
|
+
lastCtrlC = Number.NEGATIVE_INFINITY;
|
|
132
|
+
lastEscape = Number.NEGATIVE_INFINITY;
|
|
133
|
+
defaultModel = "";
|
|
134
|
+
/** Model and effort of the running turn's root run, from its run_start and escalation events; null between turns. */
|
|
135
|
+
liveModel = null;
|
|
136
|
+
defaultEffort = "";
|
|
137
|
+
exiting = false;
|
|
138
|
+
resolveForce = () => { };
|
|
139
|
+
forced = new Promise((resolve) => {
|
|
140
|
+
this.resolveForce = resolve;
|
|
141
|
+
});
|
|
142
|
+
resolveExit = () => { };
|
|
143
|
+
exitRequested = new Promise((resolve) => {
|
|
144
|
+
this.resolveExit = resolve;
|
|
145
|
+
});
|
|
146
|
+
constructor(options) {
|
|
147
|
+
this.options = options;
|
|
148
|
+
this.settings = options.settings;
|
|
149
|
+
this.terminal = options.terminal ?? new ProcessTerminal();
|
|
150
|
+
this.now = options.now ?? Date.now;
|
|
151
|
+
this.tui = new TuiMainScreen(this.terminal);
|
|
152
|
+
this.editor = new Editor(this.tui, editorTheme);
|
|
153
|
+
this.editor.borderColor = (border) => (this.shellMode() ? shellBorder(border) : editorTheme.borderColor(border));
|
|
154
|
+
this.editor.onSubmit = (text) => this.onSubmit(text);
|
|
155
|
+
this.prompter = createApprovalPrompter({ show: (box) => this.showApproval(box) }, { now: this.now, redact: (text) => this.settings.redact(text) });
|
|
156
|
+
const root = new SafeContainer();
|
|
157
|
+
root.addChild(this.chat);
|
|
158
|
+
root.addChild(this.status);
|
|
159
|
+
root.addChild(this.queueView);
|
|
160
|
+
root.addChild(this.slot);
|
|
161
|
+
root.addChild(new DynamicLine(() => this.footerText()));
|
|
162
|
+
this.tui.addChild(root);
|
|
163
|
+
this.tui.addInputListener((data) => this.onKey(data));
|
|
164
|
+
}
|
|
165
|
+
async run() {
|
|
166
|
+
const onSignal = () => this.requestExit();
|
|
167
|
+
this.options.signal?.addEventListener("abort", onSignal, { once: true });
|
|
168
|
+
startTui(this.tui);
|
|
169
|
+
try {
|
|
170
|
+
if (this.options.signal?.aborted)
|
|
171
|
+
return await this.shutdown(0);
|
|
172
|
+
if (this.options.setup !== false && this.settings.setupStatus().needed) {
|
|
173
|
+
const completed = await this.openSettings("setup");
|
|
174
|
+
if (!completed || this.exiting) {
|
|
175
|
+
this.say("setup cancelled; run nexo again to finish it");
|
|
176
|
+
return await this.shutdown(1);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// Paint the "opening…" footer before the (synchronous) session open.
|
|
180
|
+
this.tui.requestRender();
|
|
181
|
+
await new Promise((resolve) => setTimeout(resolve, OPENING_PAINT_MS));
|
|
182
|
+
try {
|
|
183
|
+
this.session = this.options.openSession(this.prompter);
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
await this.shutdown(1);
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
this.refreshDefaults();
|
|
190
|
+
this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider([...SLASH_COMMANDS], this.session.cwd));
|
|
191
|
+
this.renderHeader(this.session);
|
|
192
|
+
this.showEditor();
|
|
193
|
+
await this.exitRequested;
|
|
194
|
+
return await this.shutdown(0);
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
this.options.signal?.removeEventListener("abort", onSignal);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
// Lifecycle
|
|
201
|
+
requestExit() {
|
|
202
|
+
if (this.exiting)
|
|
203
|
+
return;
|
|
204
|
+
this.exiting = true;
|
|
205
|
+
this.turnAbort?.abort();
|
|
206
|
+
this.resolveExit();
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Aborts the turn and waits for it to be saved, but at most `exitTimeoutMs`; a Ctrl-C while waiting stops waiting.
|
|
210
|
+
* The terminal is always restored. The session is closed unless its turn is still running (its lock is then
|
|
211
|
+
* released at process exit).
|
|
212
|
+
*/
|
|
213
|
+
async shutdown(code) {
|
|
214
|
+
this.exiting = true;
|
|
215
|
+
this.turnAbort?.abort();
|
|
216
|
+
let timer;
|
|
217
|
+
try {
|
|
218
|
+
if (this.turnPromise) {
|
|
219
|
+
this.say("stopping the turn… (ctrl-c to quit without waiting)");
|
|
220
|
+
this.tui.requestRender();
|
|
221
|
+
const deadline = new Promise((resolve) => {
|
|
222
|
+
timer = setTimeout(resolve, this.options.exitTimeoutMs ?? EXIT_TIMEOUT_MS);
|
|
223
|
+
});
|
|
224
|
+
await Promise.race([this.turnPromise, deadline, this.forced]);
|
|
225
|
+
}
|
|
226
|
+
this.stopTicker();
|
|
227
|
+
this.tui.renderNow();
|
|
228
|
+
await this.terminal.drainInput(1000, 50);
|
|
229
|
+
}
|
|
230
|
+
finally {
|
|
231
|
+
if (timer)
|
|
232
|
+
clearTimeout(timer);
|
|
233
|
+
this.stopTicker();
|
|
234
|
+
stopTui(this.tui);
|
|
235
|
+
}
|
|
236
|
+
if (this.session && !this.session.running)
|
|
237
|
+
this.session.close();
|
|
238
|
+
return code;
|
|
239
|
+
}
|
|
240
|
+
// Layout helpers
|
|
241
|
+
showEditor() {
|
|
242
|
+
this.screen = "chat";
|
|
243
|
+
this.slot.clear();
|
|
244
|
+
this.slot.addChild(this.editor);
|
|
245
|
+
this.tui.setFocus(this.editor);
|
|
246
|
+
this.tui.requestRender();
|
|
247
|
+
}
|
|
248
|
+
/** Swaps the editor for an approval box; the editor keeps its draft and comes back when the returned function runs. */
|
|
249
|
+
showApproval(box) {
|
|
250
|
+
this.screen = "approval";
|
|
251
|
+
this.slot.clear();
|
|
252
|
+
this.slot.addChild(box);
|
|
253
|
+
this.tui.setFocus(box);
|
|
254
|
+
this.tui.requestRender();
|
|
255
|
+
return () => {
|
|
256
|
+
if (this.slot.children.includes(box))
|
|
257
|
+
this.showEditor();
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
add(component) {
|
|
261
|
+
this.chat.addChild(component);
|
|
262
|
+
this.tui.requestRender();
|
|
263
|
+
}
|
|
264
|
+
say(text) {
|
|
265
|
+
this.add(new Block(escapeControlKeepLines(text), style.gray, " "));
|
|
266
|
+
}
|
|
267
|
+
sayError(error) {
|
|
268
|
+
this.add(new Block(formatError(error), style.red, " "));
|
|
269
|
+
}
|
|
270
|
+
renderHeader(session, options = { transcript: true }) {
|
|
271
|
+
const resumed = options.transcript && session.turns > 0;
|
|
272
|
+
this.add(new Block(`${style.bold("nexo")} ${style.gray(`session ${session.id}${session.title ? ` · ${escapeControl(oneLine(session.title, 60))}` : ""}`)}`));
|
|
273
|
+
this.say(filesLine(session));
|
|
274
|
+
if (resumed)
|
|
275
|
+
this.renderTranscript(session.transcript());
|
|
276
|
+
this.say(`${resumed ? `resumed after ${session.turns} turn${session.turns === 1 ? "" : "s"} · ` : ""}/help for commands · esc or ctrl-c stops a turn · ctrl-d quits`);
|
|
277
|
+
}
|
|
278
|
+
/** Replays a resumed conversation: user messages, assistant text and tool calls. */
|
|
279
|
+
renderTranscript(lines) {
|
|
280
|
+
for (const line of lines) {
|
|
281
|
+
if (line.type === "compaction") {
|
|
282
|
+
this.say(line.summary ? "── earlier turns summarized ──" : "── conversation cleared ──");
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
const message = line.message;
|
|
286
|
+
if (message.role === "user") {
|
|
287
|
+
this.add(new Block(escapeControlKeepLines(textOf(message.content)), style.dim, "› "));
|
|
288
|
+
}
|
|
289
|
+
else if (message.role === "assistant" && Array.isArray(message.content)) {
|
|
290
|
+
for (const block of message.content) {
|
|
291
|
+
if (block.type === "text" && block.text)
|
|
292
|
+
this.add(new SafeMarkdown(escapeControlKeepLines(block.text), 0, 1, markdownTheme));
|
|
293
|
+
else if (block.type === "toolCall")
|
|
294
|
+
this.add(new Block(`● ${toolSummary(block.name ?? "tool", block.arguments)}`, style.gray));
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
refreshDefaults() {
|
|
300
|
+
try {
|
|
301
|
+
const { config } = this.settings.loadConfig();
|
|
302
|
+
this.defaultModel = `${config.models.s1.provider}/${config.models.s1.id}`;
|
|
303
|
+
this.defaultEffort = config.models.s1.effort ?? "";
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
this.defaultModel = "";
|
|
307
|
+
this.defaultEffort = "";
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/** The input is a `!` command: the editor border and the footer say so. */
|
|
311
|
+
shellMode() {
|
|
312
|
+
return this.screen === "chat" && this.session !== null && this.editor.getText().trimStart().startsWith("!");
|
|
313
|
+
}
|
|
314
|
+
footerText() {
|
|
315
|
+
const session = this.session;
|
|
316
|
+
if (!session)
|
|
317
|
+
return style.gray(this.screen === "settings" ? "nexo · setup" : "nexo · opening…");
|
|
318
|
+
if (this.shellMode())
|
|
319
|
+
return shellBorder(`! shell mode · output goes to the model with your next message · ${escapeControl(session.shellDir)}`);
|
|
320
|
+
// During a turn: the model the root run is on now (its start model, then S2 once an escalation applies).
|
|
321
|
+
const live = this.running ? this.liveModel : null;
|
|
322
|
+
const last = session.lastModel;
|
|
323
|
+
const model = live?.model ?? session.modelOverride ?? (last ? `${last.provider}/${last.id}` : this.defaultModel || "model ?");
|
|
324
|
+
const effort = live?.effort ?? session.effort ?? last?.effort ?? (this.defaultEffort || "default effort");
|
|
325
|
+
const turn = this.running ? this.turnCost : this.lastTurnCost;
|
|
326
|
+
const spent = session.costUsd + (this.running ? this.turnCost : 0);
|
|
327
|
+
const fraction = session.contextFraction;
|
|
328
|
+
const ctx = fraction === null ? "ctx –" : `ctx ${Math.round(fraction * 100)}%`;
|
|
329
|
+
const score = !this.running && this.lastScore ? [this.lastScore] : [];
|
|
330
|
+
const parts = [escapeControl(model), escapeControl(effort), ...(session.autoApprove ? ["auto"] : []), `turn ${usd(turn)}`, ...score, `session ${usd(spent)}/${usd(session.budgetUsd)}`, ctx];
|
|
331
|
+
return style.gray(parts.join(" · ")) + (this.running ? style.cyan(" · running…") : "");
|
|
332
|
+
}
|
|
333
|
+
// Input
|
|
334
|
+
onKey(data) {
|
|
335
|
+
// The kitty keyboard protocol also reports key releases; only presses count (the editor drops releases itself).
|
|
336
|
+
if (isKeyRelease(data))
|
|
337
|
+
return undefined;
|
|
338
|
+
if (this.exiting) {
|
|
339
|
+
if (matchesKey(data, "ctrl+c"))
|
|
340
|
+
this.resolveForce();
|
|
341
|
+
return { consume: true };
|
|
342
|
+
}
|
|
343
|
+
if (matchesKey(data, "ctrl+c")) {
|
|
344
|
+
if (this.running) {
|
|
345
|
+
this.restoreQueueToEditor();
|
|
346
|
+
this.turnAbort?.abort();
|
|
347
|
+
return { consume: true };
|
|
348
|
+
}
|
|
349
|
+
if (this.screen !== "chat" || !this.session)
|
|
350
|
+
return undefined;
|
|
351
|
+
const now = this.now();
|
|
352
|
+
if (now - this.lastCtrlC <= DOUBLE_CTRL_C_MS && this.editor.getText() === "") {
|
|
353
|
+
this.requestExit();
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
this.editor.setText("");
|
|
357
|
+
this.lastCtrlC = now;
|
|
358
|
+
this.tui.requestRender();
|
|
359
|
+
}
|
|
360
|
+
return { consume: true };
|
|
361
|
+
}
|
|
362
|
+
if (matchesKey(data, "escape") && this.running && this.screen === "chat" && !this.editor.isShowingAutocomplete()) {
|
|
363
|
+
this.restoreQueueToEditor();
|
|
364
|
+
this.turnAbort?.abort();
|
|
365
|
+
return { consume: true };
|
|
366
|
+
}
|
|
367
|
+
if (matchesKey(data, "escape") && !this.running && this.screen === "chat" && this.session && !this.editor.isShowingAutocomplete()) {
|
|
368
|
+
// Idle prompt, like Claude Code: a second Esc clears the draft but saves it to history, so Up brings it back.
|
|
369
|
+
const text = this.editor.getText();
|
|
370
|
+
const now = this.now();
|
|
371
|
+
if (text.trim() !== "" && now - this.lastEscape <= DOUBLE_ESC_MS) {
|
|
372
|
+
this.editor.addToHistory(text.trim());
|
|
373
|
+
this.editor.setText("");
|
|
374
|
+
this.lastEscape = Number.NEGATIVE_INFINITY;
|
|
375
|
+
this.tui.requestRender();
|
|
376
|
+
return { consume: true };
|
|
377
|
+
}
|
|
378
|
+
this.lastEscape = text.trim() !== "" ? now : Number.NEGATIVE_INFINITY;
|
|
379
|
+
return undefined;
|
|
380
|
+
}
|
|
381
|
+
if (matchesKey(data, "ctrl+o") && this.screen === "chat") {
|
|
382
|
+
if (isKeyRepeat(data))
|
|
383
|
+
return { consume: true };
|
|
384
|
+
this.view.verbose = !this.view.verbose;
|
|
385
|
+
this.tui.requestRender(true);
|
|
386
|
+
return { consume: true };
|
|
387
|
+
}
|
|
388
|
+
if (matchesKey(data, "ctrl+d") && this.screen === "chat" && this.session && !this.running && this.editor.getText() === "") {
|
|
389
|
+
this.requestExit();
|
|
390
|
+
return { consume: true };
|
|
391
|
+
}
|
|
392
|
+
if (matchesKey(data, "enter") && this.screen === "chat" && this.editor.isShowingAutocomplete() && /^\/\S+\s/.test(this.editor.getText())) {
|
|
393
|
+
// The editor only accepts an argument completion on Enter; press Enter again once it has, so `/effort high⏎` submits.
|
|
394
|
+
queueMicrotask(() => {
|
|
395
|
+
if (!this.editor.isShowingAutocomplete())
|
|
396
|
+
this.editor.handleInput(data);
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
return undefined;
|
|
400
|
+
}
|
|
401
|
+
onSubmit(raw) {
|
|
402
|
+
const text = raw.trim();
|
|
403
|
+
if (!text || !this.session)
|
|
404
|
+
return;
|
|
405
|
+
this.editor.addToHistory(text);
|
|
406
|
+
const command = parseSlashCommand(text);
|
|
407
|
+
if (command) {
|
|
408
|
+
this.runCommand(command.name, command.args);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (text.startsWith("!") && !text.slice(1).trim()) {
|
|
412
|
+
this.say("Type a command after !, e.g. !git status");
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
if (this.running) {
|
|
416
|
+
// Plain text goes into the running turn at its next step; `!` commands and anything typed during a command wait.
|
|
417
|
+
const steered = !this.runningShell && !text.startsWith("!") && this.session.steer(text);
|
|
418
|
+
this.queued.push({ text, steered });
|
|
419
|
+
this.say(`queued (${this.queued.length}) · ${steered ? "sent to the agent at its next step" : `sent when the ${this.runningShell ? "command" : "turn"} ends`}`);
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
this.dispatch(text);
|
|
423
|
+
}
|
|
424
|
+
/** Starts a `!` command or a turn for one message, whether typed just now or taken from the queue. */
|
|
425
|
+
dispatch(text) {
|
|
426
|
+
const session = this.session;
|
|
427
|
+
if (!session)
|
|
428
|
+
return;
|
|
429
|
+
let work;
|
|
430
|
+
if (text.startsWith("!")) {
|
|
431
|
+
const shell = text.slice(1).trim();
|
|
432
|
+
this.add(new Block(escapeControlKeepLines(shell), style.dim, "! "));
|
|
433
|
+
work = this.runShell(session, shell);
|
|
434
|
+
}
|
|
435
|
+
else {
|
|
436
|
+
this.add(new Block(escapeControlKeepLines(text), style.dim, "› "));
|
|
437
|
+
work = this.runTurn(session, text);
|
|
438
|
+
}
|
|
439
|
+
// A queued follow-up starts from inside the previous work, so only clear the promise if it is still ours.
|
|
440
|
+
const tracked = work.finally(() => {
|
|
441
|
+
if (this.turnPromise === tracked)
|
|
442
|
+
this.turnPromise = null;
|
|
443
|
+
});
|
|
444
|
+
this.turnPromise = tracked;
|
|
445
|
+
}
|
|
446
|
+
/** Puts the queued messages back in the editor, ahead of any draft, so an interrupt never starts another turn on its own. */
|
|
447
|
+
restoreQueueToEditor() {
|
|
448
|
+
if (this.queued.length === 0)
|
|
449
|
+
return;
|
|
450
|
+
const draft = this.editor.getText();
|
|
451
|
+
this.session?.clearSteering();
|
|
452
|
+
this.editor.setText([...this.queued.map((q) => q.text), draft].filter(Boolean).join("\n\n"));
|
|
453
|
+
this.queued = [];
|
|
454
|
+
this.tui.requestRender();
|
|
455
|
+
}
|
|
456
|
+
/** After a turn or command ends: sends the next queued message if it went fine, otherwise hands the queue back to the editor. */
|
|
457
|
+
drainQueue(ok) {
|
|
458
|
+
if (this.exiting || this.running || this.queued.length === 0)
|
|
459
|
+
return;
|
|
460
|
+
// Steered messages the turn never took (it stopped first) run as later turns instead.
|
|
461
|
+
for (const q of this.queued)
|
|
462
|
+
q.steered = false;
|
|
463
|
+
if (ok) {
|
|
464
|
+
this.dispatch(this.queued.shift().text);
|
|
465
|
+
}
|
|
466
|
+
else {
|
|
467
|
+
const count = this.queued.length;
|
|
468
|
+
this.restoreQueueToEditor();
|
|
469
|
+
this.say(`${count} queued ${count === 1 ? "message" : "messages"} moved back to the editor`);
|
|
470
|
+
}
|
|
471
|
+
this.tui.requestRender();
|
|
472
|
+
}
|
|
473
|
+
// Turns
|
|
474
|
+
async runTurn(session, text) {
|
|
475
|
+
if (session.continuesOnS2)
|
|
476
|
+
this.say("continuing on s2 — the previous turn stopped on it before finishing");
|
|
477
|
+
const abort = new AbortController();
|
|
478
|
+
this.turnAbort = abort;
|
|
479
|
+
this.running = true;
|
|
480
|
+
this.turnCost = 0;
|
|
481
|
+
this.lastScore = null;
|
|
482
|
+
this.currentText = null;
|
|
483
|
+
this.tools.clear();
|
|
484
|
+
this.subagents.clear();
|
|
485
|
+
this.startTicker();
|
|
486
|
+
let result = null;
|
|
487
|
+
try {
|
|
488
|
+
result = await session.turn(text, { signal: abort.signal, onEvent: (event) => this.onEvent(event) });
|
|
489
|
+
}
|
|
490
|
+
catch (error) {
|
|
491
|
+
this.sayError(toErrorPayload(error));
|
|
492
|
+
}
|
|
493
|
+
finally {
|
|
494
|
+
this.running = false;
|
|
495
|
+
this.liveModel = null;
|
|
496
|
+
this.turnAbort = null;
|
|
497
|
+
this.stopTicker();
|
|
498
|
+
for (const line of this.tools.values())
|
|
499
|
+
line.interrupt();
|
|
500
|
+
for (const line of this.subagents.values())
|
|
501
|
+
line.interrupt();
|
|
502
|
+
this.currentText = null;
|
|
503
|
+
}
|
|
504
|
+
if (result) {
|
|
505
|
+
this.lastTurnCost = result.costUsd;
|
|
506
|
+
this.lastTurnApprovalCost = result.approvalCostUsd ?? 0;
|
|
507
|
+
this.lastScore = scoreSummary(result);
|
|
508
|
+
if (result.status === "aborted")
|
|
509
|
+
this.say("interrupted");
|
|
510
|
+
else if (result.error)
|
|
511
|
+
this.sayError(result.error);
|
|
512
|
+
else if (result.status !== "succeeded")
|
|
513
|
+
this.say(`turn ended: ${result.status}`);
|
|
514
|
+
}
|
|
515
|
+
this.tui.requestRender();
|
|
516
|
+
this.drainQueue(result !== null && result.status === "succeeded" && !result.error);
|
|
517
|
+
}
|
|
518
|
+
/** Runs a `!` command like a turn (esc and ctrl-c stop it), then shows its output and how it ended. */
|
|
519
|
+
async runShell(session, command) {
|
|
520
|
+
const abort = new AbortController();
|
|
521
|
+
this.turnAbort = abort;
|
|
522
|
+
this.running = true;
|
|
523
|
+
this.runningShell = true;
|
|
524
|
+
this.startTicker();
|
|
525
|
+
let ok = false;
|
|
526
|
+
try {
|
|
527
|
+
const result = await session.shell(command, { signal: abort.signal });
|
|
528
|
+
const lines = result.output.replace(/\n$/, "").split("\n");
|
|
529
|
+
const hidden = lines.length - SHELL_SCREEN_LINES;
|
|
530
|
+
const shown = hidden > 0 ? [`… ${hidden} earlier lines not shown`, ...lines.slice(-SHELL_SCREEN_LINES)] : lines;
|
|
531
|
+
if (result.output)
|
|
532
|
+
this.add(new Block(escapeControlKeepLines(shown.join("\n")), (t) => t, " "));
|
|
533
|
+
const ending = { exited: `exit code ${result.exitCode}`, timeout: "timed out", aborted: "stopped", failed: "failed to start" }[result.ended];
|
|
534
|
+
this.say(`${ending}${result.truncated ? " · output truncated" : ""}`);
|
|
535
|
+
ok = result.ended === "exited";
|
|
536
|
+
}
|
|
537
|
+
catch (error) {
|
|
538
|
+
this.sayError(toErrorPayload(error));
|
|
539
|
+
}
|
|
540
|
+
finally {
|
|
541
|
+
this.running = false;
|
|
542
|
+
this.runningShell = false;
|
|
543
|
+
this.turnAbort = null;
|
|
544
|
+
this.stopTicker();
|
|
545
|
+
}
|
|
546
|
+
this.tui.requestRender();
|
|
547
|
+
this.drainQueue(ok);
|
|
548
|
+
}
|
|
549
|
+
onEvent(event) {
|
|
550
|
+
switch (event.type) {
|
|
551
|
+
case "steer_injected": {
|
|
552
|
+
if (event.depth !== 0)
|
|
553
|
+
return;
|
|
554
|
+
const i = this.queued.findIndex((q) => q.steered);
|
|
555
|
+
if (i >= 0)
|
|
556
|
+
this.queued.splice(i, 1);
|
|
557
|
+
// The reply to it streams into a new block below the message.
|
|
558
|
+
this.currentText = null;
|
|
559
|
+
this.chat.addChild(new Block(escapeControlKeepLines(event.text), style.dim, "› "));
|
|
560
|
+
break;
|
|
561
|
+
}
|
|
562
|
+
case "text_delta": {
|
|
563
|
+
if (event.depth !== 0)
|
|
564
|
+
return;
|
|
565
|
+
if (!this.currentText) {
|
|
566
|
+
const component = new SafeMarkdown("", 0, 1, markdownTheme);
|
|
567
|
+
this.currentText = { component, text: "" };
|
|
568
|
+
this.chat.addChild(component);
|
|
569
|
+
}
|
|
570
|
+
this.currentText.text += event.delta;
|
|
571
|
+
this.currentText.component.setText(escapeControlKeepLines(this.settings.redact(this.currentText.text)));
|
|
572
|
+
break;
|
|
573
|
+
}
|
|
574
|
+
case "tool_start": {
|
|
575
|
+
if (event.depth !== 0)
|
|
576
|
+
return;
|
|
577
|
+
this.currentText = null;
|
|
578
|
+
const line = new ToolLine(toolSummary(event.toolName, event.args), toolSummary(event.toolName, event.args, Number.POSITIVE_INFINITY), this.ticker, this.view);
|
|
579
|
+
this.tools.set(event.toolCallId, line);
|
|
580
|
+
this.chat.addChild(line);
|
|
581
|
+
break;
|
|
582
|
+
}
|
|
583
|
+
case "tool_end": {
|
|
584
|
+
if (event.depth !== 0)
|
|
585
|
+
return;
|
|
586
|
+
this.tools.get(event.toolCallId)?.finish(event.isError, event.durationMs, event.output);
|
|
587
|
+
this.tools.delete(event.toolCallId);
|
|
588
|
+
break;
|
|
589
|
+
}
|
|
590
|
+
case "run_start": {
|
|
591
|
+
if (event.depth === 0) {
|
|
592
|
+
this.liveModel = { model: event.model, effort: event.effort };
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
const line = new SubagentLine(escapeControl(oneLine(event.instruction, 70)), event.depth, this.ticker);
|
|
596
|
+
this.subagents.set(event.runId, line);
|
|
597
|
+
this.chat.addChild(line);
|
|
598
|
+
break;
|
|
599
|
+
}
|
|
600
|
+
case "run_end": {
|
|
601
|
+
if (event.depth === 0)
|
|
602
|
+
return;
|
|
603
|
+
this.subagents.get(event.runId)?.finish(event.status, event.costUsd);
|
|
604
|
+
this.subagents.delete(event.runId);
|
|
605
|
+
break;
|
|
606
|
+
}
|
|
607
|
+
case "llm_end":
|
|
608
|
+
this.turnCost += event.costUsd;
|
|
609
|
+
break;
|
|
610
|
+
case "escalation": {
|
|
611
|
+
if (event.depth !== 0)
|
|
612
|
+
return;
|
|
613
|
+
this.currentText = null;
|
|
614
|
+
if (event.applied)
|
|
615
|
+
this.liveModel = { model: event.model, effort: event.effort };
|
|
616
|
+
const why = `${event.trigger}: ${escapeControl(oneLine(event.reason, 120))}`;
|
|
617
|
+
this.chat.addChild(event.applied
|
|
618
|
+
? new Block(`↑ escalated to ${escapeControl(event.model)} — ${why}`, style.yellow, " ")
|
|
619
|
+
: new Block(`escalation suppressed (${escapeControl(event.blockedBy ?? "?")}) — ${why}`, style.gray, " "));
|
|
620
|
+
break;
|
|
621
|
+
}
|
|
622
|
+
case "approval": {
|
|
623
|
+
this.chat.addChild(new Block(`${event.depth > 0 ? `[subagent ${event.runId.slice(-6)}] ` : ""}auto-allowed: ${escapeControl(oneLine(event.reason, 160))}`, style.gray, " "));
|
|
624
|
+
break;
|
|
625
|
+
}
|
|
626
|
+
case "escalation_failed": {
|
|
627
|
+
if (event.depth !== 0)
|
|
628
|
+
return;
|
|
629
|
+
this.currentText = null;
|
|
630
|
+
this.liveModel = { model: event.model, effort: event.effort };
|
|
631
|
+
const error = `[${escapeControl(oneLine(event.error.code, 40))}] ${escapeControl(oneLine(event.error.message, 120))}`;
|
|
632
|
+
this.chat.addChild(new Block(`✗ s2 continuation failed ${error}; kept the previous answer`, style.red, " "));
|
|
633
|
+
break;
|
|
634
|
+
}
|
|
635
|
+
case "score": {
|
|
636
|
+
if (event.depth !== 0)
|
|
637
|
+
return;
|
|
638
|
+
this.currentText = null;
|
|
639
|
+
this.chat.addChild(new Block(`score ${escapeControl(oneLine(event.scorer, 60))}: ${scoreVerdict(event)}`, style.gray, " "));
|
|
640
|
+
break;
|
|
641
|
+
}
|
|
642
|
+
case "compaction_start":
|
|
643
|
+
this.currentText = null;
|
|
644
|
+
this.chat.addChild(new Block("compacting earlier turns…", style.gray, " "));
|
|
645
|
+
break;
|
|
646
|
+
case "compaction_end":
|
|
647
|
+
this.chat.addChild(new Block(event.ok ? `earlier turns compacted (${usd(event.costUsd)})` : "compaction failed; continuing with the full history", style.gray, " "));
|
|
648
|
+
break;
|
|
649
|
+
}
|
|
650
|
+
this.tui.requestRender();
|
|
651
|
+
}
|
|
652
|
+
startTicker() {
|
|
653
|
+
this.stopTicker();
|
|
654
|
+
this.loader = new Loader(this.tui, style.cyan, style.gray, "working… (esc to stop)");
|
|
655
|
+
this.status.addChild(this.loader);
|
|
656
|
+
this.tickTimer = setInterval(() => {
|
|
657
|
+
this.ticker.frame++;
|
|
658
|
+
this.tui.requestRender();
|
|
659
|
+
}, TICK_MS);
|
|
660
|
+
}
|
|
661
|
+
stopTicker() {
|
|
662
|
+
if (this.tickTimer)
|
|
663
|
+
clearInterval(this.tickTimer);
|
|
664
|
+
this.tickTimer = null;
|
|
665
|
+
this.loader?.stop();
|
|
666
|
+
this.loader = null;
|
|
667
|
+
this.status.clear();
|
|
668
|
+
}
|
|
669
|
+
// Slash commands
|
|
670
|
+
runCommand(name, args) {
|
|
671
|
+
const session = this.session;
|
|
672
|
+
if (!session)
|
|
673
|
+
return;
|
|
674
|
+
const idleOnly = !["help", "cost", "sessions", "exit"].includes(name);
|
|
675
|
+
if (idleOnly && this.running && SLASH_COMMANDS.some((c) => c.name === name)) {
|
|
676
|
+
this.say(`A turn is running — press esc to stop it before /${name}`);
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
try {
|
|
680
|
+
switch (name) {
|
|
681
|
+
case "help":
|
|
682
|
+
this.say(`${helpText()}\n\n${filesLine(session)}`);
|
|
683
|
+
break;
|
|
684
|
+
case "done":
|
|
685
|
+
session.review("done");
|
|
686
|
+
this.say("marked the last turn done");
|
|
687
|
+
break;
|
|
688
|
+
case "notdone":
|
|
689
|
+
session.review("not_done", args || undefined);
|
|
690
|
+
this.say(`marked the last turn not done${args ? " with your comment" : ""}`);
|
|
691
|
+
break;
|
|
692
|
+
case "cost":
|
|
693
|
+
this.say(`session ${usd(session.costUsd)} of ${usd(session.budgetUsd)} (${usd(session.remainingUsd)} left) · last turn ${usd(this.lastTurnCost)}${this.lastTurnApprovalCost > 0 ? ` (+ ${usd(this.lastTurnApprovalCost)} approvals, not budgeted)` : ""} · ${session.turns} turn${session.turns === 1 ? "" : "s"}`);
|
|
694
|
+
break;
|
|
695
|
+
case "budget": {
|
|
696
|
+
const value = args.replace(/^\$/, "");
|
|
697
|
+
session.setBudget(value === "" ? Number.NaN : Number(value));
|
|
698
|
+
this.say(`session budget set to ${usd(session.budgetUsd)}`);
|
|
699
|
+
break;
|
|
700
|
+
}
|
|
701
|
+
case "model":
|
|
702
|
+
if (!args)
|
|
703
|
+
this.say(`model: ${escapeControl(session.model ?? `${this.defaultModel} (default)`)}`);
|
|
704
|
+
else {
|
|
705
|
+
session.setModel(args === "default" ? null : args);
|
|
706
|
+
this.say(session.model ? `model set to ${escapeControl(session.model)} for this session` : "model override cleared");
|
|
707
|
+
}
|
|
708
|
+
break;
|
|
709
|
+
case "effort":
|
|
710
|
+
if (!args)
|
|
711
|
+
this.say(`effort: ${escapeControl(session.effort ?? `${this.defaultEffort || "default"} (default)`)}`);
|
|
712
|
+
else {
|
|
713
|
+
session.setEffort(args === "default" ? null : args);
|
|
714
|
+
this.say(session.effort ? `effort set to ${session.effort} for this session` : "effort override cleared");
|
|
715
|
+
}
|
|
716
|
+
break;
|
|
717
|
+
case "auto": {
|
|
718
|
+
if (!args) {
|
|
719
|
+
const source = session.autoApproveOverride === null ? "tools.autoApprove" : "/auto for this session";
|
|
720
|
+
this.say(`auto mode: ${session.autoApprove ? "on" : "off"} (${source})`);
|
|
721
|
+
}
|
|
722
|
+
else if (args === "on" || args === "off" || args === "default") {
|
|
723
|
+
session.setAutoApprove(args === "default" ? null : args === "on");
|
|
724
|
+
this.say(`auto mode ${session.autoApprove ? "on" : "off"}${args === "default" ? " (following tools.autoApprove)" : " for this session"}`);
|
|
725
|
+
}
|
|
726
|
+
else {
|
|
727
|
+
this.sayError({ code: "INVALID_REQUEST", message: `Unknown /auto argument "${escapeControl(oneLine(args, 40))}"`, hint: "Use on, off or default" });
|
|
728
|
+
}
|
|
729
|
+
break;
|
|
730
|
+
}
|
|
731
|
+
case "permissions": {
|
|
732
|
+
if (!args) {
|
|
733
|
+
const rules = session.sessionRules;
|
|
734
|
+
this.say(rules.length === 0
|
|
735
|
+
? "no session rules (pick “Always allow” in an approval box to add one)"
|
|
736
|
+
: rules.map((r, i) => `${i + 1}. ${r.kind === "prefix" ? `${escapeControl(r.tool)} ` : ""}${describeSessionRule(r)}`).join("\n"));
|
|
737
|
+
}
|
|
738
|
+
else if (args === "clear") {
|
|
739
|
+
this.say(`removed ${session.clearSessionRules()} session rule(s)`);
|
|
740
|
+
}
|
|
741
|
+
else {
|
|
742
|
+
const match = /^remove\s+(\d+)$/.exec(args);
|
|
743
|
+
if (!match)
|
|
744
|
+
this.sayError({ code: "INVALID_REQUEST", message: `Unknown /permissions argument "${escapeControl(oneLine(args, 40))}"`, hint: "Use /permissions, /permissions remove <n> or /permissions clear" });
|
|
745
|
+
else {
|
|
746
|
+
try {
|
|
747
|
+
this.say(`removed ${describeSessionRule(session.removeSessionRule(Number(match[1])))}`);
|
|
748
|
+
}
|
|
749
|
+
catch (error) {
|
|
750
|
+
this.sayError(toErrorPayload(error));
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
break;
|
|
755
|
+
}
|
|
756
|
+
case "compact":
|
|
757
|
+
session.compact();
|
|
758
|
+
this.say("older turns will be summarized at the start of the next turn");
|
|
759
|
+
break;
|
|
760
|
+
case "clear":
|
|
761
|
+
session.clear();
|
|
762
|
+
// A forced render after emptying the chat clears the screen and scrollback, then draws only what follows.
|
|
763
|
+
this.chat.clear();
|
|
764
|
+
this.renderHeader(session, { transcript: false });
|
|
765
|
+
this.say("── conversation cleared ── (same session; earlier turns stay in its history)");
|
|
766
|
+
this.tui.requestRender(true);
|
|
767
|
+
break;
|
|
768
|
+
case "sessions":
|
|
769
|
+
this.say(this.sessionsText(session));
|
|
770
|
+
break;
|
|
771
|
+
case "resume":
|
|
772
|
+
this.resume(session, args);
|
|
773
|
+
break;
|
|
774
|
+
case "settings":
|
|
775
|
+
void this.openSettings("settings").then(() => {
|
|
776
|
+
this.refreshDefaults();
|
|
777
|
+
try {
|
|
778
|
+
session.refreshConfig();
|
|
779
|
+
}
|
|
780
|
+
catch (error) {
|
|
781
|
+
this.sayError(toErrorPayload(error));
|
|
782
|
+
}
|
|
783
|
+
this.tui.requestRender();
|
|
784
|
+
this.say("settings closed; changes apply from the next turn");
|
|
785
|
+
});
|
|
786
|
+
break;
|
|
787
|
+
case "exit":
|
|
788
|
+
this.requestExit();
|
|
789
|
+
break;
|
|
790
|
+
default:
|
|
791
|
+
this.sayError({ code: "INVALID_REQUEST", message: `Unknown command /${name}`, hint: "Type /help for the list" });
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
catch (error) {
|
|
795
|
+
this.sayError(toErrorPayload(error));
|
|
796
|
+
}
|
|
797
|
+
this.tui.requestRender();
|
|
798
|
+
}
|
|
799
|
+
/** `/resume <id>` switches directly; `/resume` shows a picker of the other recent sessions. */
|
|
800
|
+
resume(current, args) {
|
|
801
|
+
if (!this.options.resumeSession) {
|
|
802
|
+
this.sayError({ code: "INVALID_REQUEST", message: "/resume is not available here", hint: "Start nexo with --resume <id>" });
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
if (args) {
|
|
806
|
+
this.switchTo(current, args);
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
const rows = listSessions(this.options.db, { limit: 50 }).filter((r) => r.id !== current.id);
|
|
810
|
+
if (rows.length === 0) {
|
|
811
|
+
this.say("no other sessions to resume");
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
this.screen = "picker";
|
|
815
|
+
const picker = createSessionPickerScreen({
|
|
816
|
+
sessions: rows,
|
|
817
|
+
now: this.now(),
|
|
818
|
+
rows: () => this.terminal.rows,
|
|
819
|
+
onPick: (id) => {
|
|
820
|
+
this.showEditor();
|
|
821
|
+
this.switchTo(current, id);
|
|
822
|
+
},
|
|
823
|
+
onCancel: () => this.showEditor(),
|
|
824
|
+
});
|
|
825
|
+
this.slot.clear();
|
|
826
|
+
this.slot.addChild(picker);
|
|
827
|
+
this.tui.setFocus(picker);
|
|
828
|
+
this.tui.requestRender();
|
|
829
|
+
}
|
|
830
|
+
/** Opens the target first and closes the current session only once that worked, so a failed resume changes nothing. */
|
|
831
|
+
switchTo(current, id) {
|
|
832
|
+
const open = this.options.resumeSession;
|
|
833
|
+
if (!open)
|
|
834
|
+
return;
|
|
835
|
+
if (id === current.id) {
|
|
836
|
+
this.say("already in that session");
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
let next;
|
|
840
|
+
try {
|
|
841
|
+
if (!getSessionRow(this.options.db, id))
|
|
842
|
+
throw sessionNotFound(id);
|
|
843
|
+
next = open(id, this.prompter);
|
|
844
|
+
}
|
|
845
|
+
catch (error) {
|
|
846
|
+
this.sayError(toErrorPayload(error));
|
|
847
|
+
this.tui.requestRender();
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
try {
|
|
851
|
+
current.close();
|
|
852
|
+
}
|
|
853
|
+
catch (error) {
|
|
854
|
+
next.close();
|
|
855
|
+
this.sayError(toErrorPayload(error));
|
|
856
|
+
this.tui.requestRender();
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
this.session = next;
|
|
860
|
+
this.turnCost = 0;
|
|
861
|
+
this.lastTurnCost = 0;
|
|
862
|
+
this.lastTurnApprovalCost = 0;
|
|
863
|
+
this.lastScore = null;
|
|
864
|
+
this.currentText = null;
|
|
865
|
+
this.liveModel = null;
|
|
866
|
+
this.tools.clear();
|
|
867
|
+
this.subagents.clear();
|
|
868
|
+
this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider([...SLASH_COMMANDS], next.cwd));
|
|
869
|
+
this.chat.clear();
|
|
870
|
+
this.renderHeader(next);
|
|
871
|
+
this.tui.requestRender(true);
|
|
872
|
+
}
|
|
873
|
+
sessionsText(current) {
|
|
874
|
+
const rows = listSessions(this.options.db, { limit: 10 });
|
|
875
|
+
if (rows.length === 0)
|
|
876
|
+
return "no sessions yet";
|
|
877
|
+
const lines = rows.map((r) => {
|
|
878
|
+
const mark = r.id === current.id ? "*" : " ";
|
|
879
|
+
const title = r.title ? escapeControl(oneLine(r.title, 40)) : "(untitled)";
|
|
880
|
+
return `${mark} ${r.id} ${title} ${r.turns} turn${r.turns === 1 ? "" : "s"} ${usd(r.costUsd)} ${r.updatedAt.slice(0, 16).replace("T", " ")}`;
|
|
881
|
+
});
|
|
882
|
+
lines.push("resume one later with: nexo --resume <id>");
|
|
883
|
+
return lines.join("\n");
|
|
884
|
+
}
|
|
885
|
+
// Settings
|
|
886
|
+
openSettings(mode) {
|
|
887
|
+
return new Promise((resolve) => {
|
|
888
|
+
this.screen = "settings";
|
|
889
|
+
const screen = new SettingsScreen({
|
|
890
|
+
settings: this.settings,
|
|
891
|
+
mode,
|
|
892
|
+
rows: () => this.terminal.rows,
|
|
893
|
+
requestRender: () => this.tui.requestRender(),
|
|
894
|
+
onClose: (completed) => {
|
|
895
|
+
if (this.session)
|
|
896
|
+
this.showEditor();
|
|
897
|
+
else {
|
|
898
|
+
this.slot.clear();
|
|
899
|
+
this.screen = "chat";
|
|
900
|
+
}
|
|
901
|
+
resolve(completed);
|
|
902
|
+
},
|
|
903
|
+
});
|
|
904
|
+
this.slot.clear();
|
|
905
|
+
this.slot.addChild(screen);
|
|
906
|
+
this.tui.setFocus(screen);
|
|
907
|
+
this.tui.requestRender();
|
|
908
|
+
void this.exitRequested.then(() => resolve(false));
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* Runs an interactive session in the terminal until the user quits. Returns the exit code: 0 after a normal exit, 1
|
|
914
|
+
* when first-run setup was cancelled. The terminal is restored and the session closed before it returns. Errors
|
|
915
|
+
* thrown by `openSession` are rethrown after the terminal is restored.
|
|
916
|
+
*/
|
|
917
|
+
export function runInteractive(options) {
|
|
918
|
+
return new InteractiveApp(options).run();
|
|
919
|
+
}
|
|
920
|
+
/** Runs the settings screen (or first-run setup) on its own, for `nexo settings` and first-run outside a session. */
|
|
921
|
+
export async function runSettingsScreen(options) {
|
|
922
|
+
const mode = options.mode ?? "settings";
|
|
923
|
+
if (mode === "setup") {
|
|
924
|
+
const status = options.settings.setupStatus();
|
|
925
|
+
if (status.error)
|
|
926
|
+
return { completed: false, error: status.error };
|
|
927
|
+
if (!status.needed)
|
|
928
|
+
return { completed: true };
|
|
929
|
+
}
|
|
930
|
+
const terminal = options.terminal ?? new ProcessTerminal();
|
|
931
|
+
const tui = new TuiMainScreen(terminal);
|
|
932
|
+
let resolveDone = () => { };
|
|
933
|
+
const done = new Promise((resolve) => {
|
|
934
|
+
resolveDone = resolve;
|
|
935
|
+
});
|
|
936
|
+
const screen = new SettingsScreen({
|
|
937
|
+
settings: options.settings,
|
|
938
|
+
mode,
|
|
939
|
+
rows: () => terminal.rows,
|
|
940
|
+
requestRender: () => tui.requestRender(),
|
|
941
|
+
onClose: (completed) => resolveDone(completed),
|
|
942
|
+
});
|
|
943
|
+
const root = new SafeContainer();
|
|
944
|
+
root.addChild(screen);
|
|
945
|
+
tui.addChild(root);
|
|
946
|
+
tui.setFocus(screen);
|
|
947
|
+
const onAbort = () => resolveDone(false);
|
|
948
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
949
|
+
startTui(tui);
|
|
950
|
+
try {
|
|
951
|
+
if (options.signal?.aborted)
|
|
952
|
+
resolveDone(false);
|
|
953
|
+
const completed = await done;
|
|
954
|
+
return { completed };
|
|
955
|
+
}
|
|
956
|
+
finally {
|
|
957
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
958
|
+
try {
|
|
959
|
+
await terminal.drainInput(1000, 50);
|
|
960
|
+
}
|
|
961
|
+
finally {
|
|
962
|
+
stopTui(tui);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
}
|