reasonally 0.2.0 → 0.4.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.
- package/README.md +137 -5
- package/dist/agent/accumulate.js +150 -0
- package/dist/agent/client.js +176 -0
- package/dist/agent/compact.js +79 -0
- package/dist/agent/cost.js +22 -0
- package/dist/agent/loop-constants.js +11 -0
- package/dist/agent/loop.js +734 -0
- package/dist/agent/mcp-config.js +72 -0
- package/dist/agent/mcp.js +195 -0
- package/dist/agent/permissions.js +153 -0
- package/dist/agent/prompt.js +112 -0
- package/dist/agent/readonly-command.js +315 -0
- package/dist/agent/session.js +417 -0
- package/dist/agent/sse.js +46 -0
- package/dist/agent/tools/bash.js +196 -0
- package/dist/agent/tools/diff.js +33 -0
- package/dist/agent/tools/files.js +270 -0
- package/dist/agent/tools/index.js +23 -0
- package/dist/agent/tools/paths.js +43 -0
- package/dist/agent/tools/plan.js +101 -0
- package/dist/agent/tools/search.js +288 -0
- package/dist/agent/tools/task.js +42 -0
- package/dist/agent/tools/todo.js +59 -0
- package/dist/agent/tools/types.js +57 -0
- package/dist/agent/types.js +2 -0
- package/dist/api.js +8 -2
- package/dist/catalog.js +12 -0
- package/dist/cli.js +37 -3
- package/dist/config.js +17 -4
- package/dist/login.js +41 -13
- package/dist/tui/app.js +1010 -0
- package/dist/tui/args.js +43 -0
- package/dist/tui/commands.js +42 -0
- package/dist/tui/components.js +479 -0
- package/dist/tui/external-editor.js +103 -0
- package/dist/tui/format.js +124 -0
- package/dist/tui/node-version.js +7 -0
- package/dist/tui/start.js +139 -0
- package/dist/tui/theme.js +36 -0
- package/package.json +8 -3
package/dist/tui/app.js
ADDED
|
@@ -0,0 +1,1010 @@
|
|
|
1
|
+
import { CombinedAutocompleteProvider, Editor, Loader, Markdown, matchesKey, TuiMainScreen, } from "@earendil-works/pi-tui";
|
|
2
|
+
import { formatUsd } from "../agent/cost.js";
|
|
3
|
+
import { Agent, } from "../agent/loop.js";
|
|
4
|
+
import { emptyAllows, MODE_LABELS, MODES, } from "../agent/permissions.js";
|
|
5
|
+
import { MCP_EXAMPLE } from "../agent/mcp-config.js";
|
|
6
|
+
import { count } from "../agent/tools/files.js";
|
|
7
|
+
import { BUILTIN_TOOLS } from "../agent/tools/index.js";
|
|
8
|
+
import { tildePath } from "../agent/tools/paths.js";
|
|
9
|
+
import { formatTodos } from "../agent/tools/todo.js";
|
|
10
|
+
import { FileTracker } from "../agent/tools/types.js";
|
|
11
|
+
import { commandEnv } from "../agent/tools/bash.js";
|
|
12
|
+
import { listSessions, loadSession, sessionHolder, SessionWriter, stepRecord, timeAgo, } from "../agent/session.js";
|
|
13
|
+
import { PLAN_OUTCOME_LABELS, PLAN_TOOL } from "../agent/tools/plan.js";
|
|
14
|
+
import { changedLines, editInEditor } from "./external-editor.js";
|
|
15
|
+
import { COMMANDS, helpText, parseCommand } from "./commands.js";
|
|
16
|
+
import { ApprovalBox, Clamped, PlanApprovalBox, PlanBlock, gap, Header, INDENT, Lines, markdownTheme, Picker, Reasoning, selectListTheme, ToolLine, UserMessage, } from "./components.js";
|
|
17
|
+
import { compactionNote, describeError, formatTokens, modelChoice, openElsewhere, retryMessage, sortModels, modeStatus, statusLine, } from "./format.js";
|
|
18
|
+
import { style, theme } from "./theme.js";
|
|
19
|
+
export class App {
|
|
20
|
+
options;
|
|
21
|
+
tui;
|
|
22
|
+
transcript = new Clamped();
|
|
23
|
+
activity = new Clamped();
|
|
24
|
+
editor;
|
|
25
|
+
status = new Lines("", 1);
|
|
26
|
+
loader = null;
|
|
27
|
+
loaderText = "";
|
|
28
|
+
session;
|
|
29
|
+
model;
|
|
30
|
+
agent = null;
|
|
31
|
+
permissions;
|
|
32
|
+
files = new FileTracker();
|
|
33
|
+
todos = [];
|
|
34
|
+
balance;
|
|
35
|
+
/** Cost of earlier conversations in this session (`/new`). */
|
|
36
|
+
spentBefore = 0n;
|
|
37
|
+
busy = null;
|
|
38
|
+
queued = [];
|
|
39
|
+
queuedNote = null;
|
|
40
|
+
/** What Enter on an empty input does after an error. */
|
|
41
|
+
pendingNext = null;
|
|
42
|
+
/** A message waiting for a model to be picked. */
|
|
43
|
+
afterPick = null;
|
|
44
|
+
picker = null;
|
|
45
|
+
approval = null;
|
|
46
|
+
lastExpandable = null;
|
|
47
|
+
lastCtrlC = 0;
|
|
48
|
+
hint = null;
|
|
49
|
+
hintTimer;
|
|
50
|
+
exited = false;
|
|
51
|
+
writer = null;
|
|
52
|
+
approvals = Promise.resolve();
|
|
53
|
+
header = null;
|
|
54
|
+
/** The kind of the last transcript entry, for spacing. */
|
|
55
|
+
lastKind = null;
|
|
56
|
+
// The reply being streamed.
|
|
57
|
+
replyText = "";
|
|
58
|
+
reply = null;
|
|
59
|
+
reasoning = null;
|
|
60
|
+
toolLines = new Map();
|
|
61
|
+
/** The plan being written or waiting for an answer, in the transcript. */
|
|
62
|
+
planBlock = null;
|
|
63
|
+
/** How the last presented plan ended, for the words at the end of the turn. */
|
|
64
|
+
lastPlanOutcome = null;
|
|
65
|
+
/** The plan is open in the person's editor. */
|
|
66
|
+
editingPlan = false;
|
|
67
|
+
constructor(options) {
|
|
68
|
+
this.options = options;
|
|
69
|
+
this.session = options.session;
|
|
70
|
+
this.model = options.model;
|
|
71
|
+
this.balance = options.balance;
|
|
72
|
+
this.permissions = {
|
|
73
|
+
mode: options.mode,
|
|
74
|
+
allows: emptyAllows(),
|
|
75
|
+
context: { cwd: options.cwd, home: options.home, configDir: options.configDir },
|
|
76
|
+
};
|
|
77
|
+
this.tui = new TuiMainScreen(options.terminal);
|
|
78
|
+
this.editor = new Editor(this.tui, { borderColor: theme.border, selectList: selectListTheme }, { paddingX: 1 });
|
|
79
|
+
this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider(COMMANDS.map((c) => ({ name: c.name, description: c.description })), options.cwd, null));
|
|
80
|
+
this.editor.onSubmit = (text) => this.submit(text);
|
|
81
|
+
this.tui.addChild(this.transcript);
|
|
82
|
+
this.tui.addChild(this.activity);
|
|
83
|
+
this.tui.addChild(this.editor);
|
|
84
|
+
this.tui.addChild(this.status);
|
|
85
|
+
this.tui.addInputListener((data) => (this.onKey(data) ? { consume: true } : undefined));
|
|
86
|
+
if (this.model)
|
|
87
|
+
this.agent = this.newAgent(this.model);
|
|
88
|
+
}
|
|
89
|
+
start() {
|
|
90
|
+
const folder = tildePath(this.options.cwd, this.options.home);
|
|
91
|
+
this.options.terminal.setTitle(`Reasonally · ${folder}`);
|
|
92
|
+
this.header = new Header(this.model?.id ?? "no model yet", folder);
|
|
93
|
+
this.add(this.header);
|
|
94
|
+
if (this.options.cwd === this.options.home || this.options.cwd === "/") {
|
|
95
|
+
this.notice(theme.warning(`You're in ${this.options.cwd === "/" ? "the root folder" : "your home folder"}; the agent can read and edit files here.`));
|
|
96
|
+
}
|
|
97
|
+
if (this.balance && /^\$0\.00$/.test(this.balance)) {
|
|
98
|
+
this.notice(theme.warning(`Your balance is $0.00. Add credits at ${this.billingUrl()} to start.`));
|
|
99
|
+
}
|
|
100
|
+
this.watchMcp();
|
|
101
|
+
if (this.options.startNotice)
|
|
102
|
+
this.notice(theme.muted(this.options.startNotice));
|
|
103
|
+
if (this.options.resume)
|
|
104
|
+
this.resumeSession(this.options.resume);
|
|
105
|
+
this.tui.setFocus(this.editor);
|
|
106
|
+
this.updateStatus();
|
|
107
|
+
this.tui.start();
|
|
108
|
+
if (this.options.pickSession)
|
|
109
|
+
void this.openSessionPicker();
|
|
110
|
+
else if (!this.model)
|
|
111
|
+
this.openModelPicker();
|
|
112
|
+
}
|
|
113
|
+
// --- input ------------------------------------------------------------------------------------
|
|
114
|
+
/** Global keys. Returns true when the key was handled here. */
|
|
115
|
+
onKey(data) {
|
|
116
|
+
if (matchesKey(data, "ctrl+c")) {
|
|
117
|
+
if (this.approval) {
|
|
118
|
+
this.busy?.abort();
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
if (this.picker) {
|
|
122
|
+
this.closePicker();
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
if (this.editor.getText()) {
|
|
126
|
+
this.editor.setText("");
|
|
127
|
+
this.tui.requestRender();
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
if (this.busy) {
|
|
131
|
+
this.busy.abort();
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
if (Date.now() - this.lastCtrlC < 2000) {
|
|
135
|
+
this.exit(0);
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
this.lastCtrlC = Date.now();
|
|
139
|
+
this.flash("Press Ctrl+C again to quit.");
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
if (matchesKey(data, "ctrl+d")) {
|
|
143
|
+
if (!this.editor.getText() && !this.busy && !this.approval && !this.picker) {
|
|
144
|
+
this.exit(0);
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
if (this.picker || this.approval) {
|
|
150
|
+
if (matchesKey(data, "ctrl+o") && this.approval instanceof ApprovalBox) {
|
|
151
|
+
this.approval.toggleExpanded();
|
|
152
|
+
this.tui.requestRender();
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
return false; // they handle their own keys, Esc included
|
|
156
|
+
}
|
|
157
|
+
if (matchesKey(data, "escape")) {
|
|
158
|
+
if (this.editor.capturesViewportInput)
|
|
159
|
+
return false; // closes the autocomplete menu
|
|
160
|
+
if (this.busy) {
|
|
161
|
+
this.busy.abort();
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
if (matchesKey(data, "shift+tab")) {
|
|
167
|
+
this.cycleMode();
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
if (matchesKey(data, "ctrl+o")) {
|
|
171
|
+
const target = this.lastExpandable;
|
|
172
|
+
if (target && !(target instanceof ApprovalBox) && target.expandable) {
|
|
173
|
+
target.expanded = !target.expanded;
|
|
174
|
+
this.tui.requestRender();
|
|
175
|
+
}
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
submit(raw) {
|
|
181
|
+
const text = raw.trim();
|
|
182
|
+
if (!text) {
|
|
183
|
+
if (this.busy)
|
|
184
|
+
return;
|
|
185
|
+
if (this.pendingNext === "retry")
|
|
186
|
+
this.retry();
|
|
187
|
+
else if (this.pendingNext === "login")
|
|
188
|
+
void this.relogin();
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const command = text.startsWith("/") ? parseCommand(text) : null;
|
|
192
|
+
if (text.startsWith("/")) {
|
|
193
|
+
this.editor.addToHistory(text);
|
|
194
|
+
if (command)
|
|
195
|
+
this.runCommand(command.name, command.arg);
|
|
196
|
+
else
|
|
197
|
+
this.notice(theme.warning(`"${text}" isn't a command. Type /help for the list.`));
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
this.editor.addToHistory(text);
|
|
201
|
+
if (!this.agent) {
|
|
202
|
+
this.afterPick = text;
|
|
203
|
+
this.openModelPicker();
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (this.busy) {
|
|
207
|
+
this.queued.push(text);
|
|
208
|
+
this.showQueued();
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
this.addUser(text);
|
|
212
|
+
const agent = this.agent;
|
|
213
|
+
void this.runTurn((signal) => agent.send(text, signal));
|
|
214
|
+
}
|
|
215
|
+
// --- turns ------------------------------------------------------------------------------------
|
|
216
|
+
async runTurn(start) {
|
|
217
|
+
const controller = new AbortController();
|
|
218
|
+
this.busy = controller;
|
|
219
|
+
this.pendingNext = null;
|
|
220
|
+
this.showLoader("Thinking…");
|
|
221
|
+
try {
|
|
222
|
+
for await (const event of start(controller.signal))
|
|
223
|
+
this.onEvent(event);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
this.showError(error);
|
|
227
|
+
}
|
|
228
|
+
finally {
|
|
229
|
+
this.busy = null;
|
|
230
|
+
this.reasoning?.finish();
|
|
231
|
+
this.hideLoader();
|
|
232
|
+
this.updateStatus();
|
|
233
|
+
this.refreshBalanceSoon();
|
|
234
|
+
this.flushQueue();
|
|
235
|
+
this.tui.requestRender();
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
retry() {
|
|
239
|
+
const agent = this.agent;
|
|
240
|
+
if (!agent?.canRetry)
|
|
241
|
+
return;
|
|
242
|
+
void this.runTurn((signal) => agent.retry(signal));
|
|
243
|
+
}
|
|
244
|
+
flushQueue() {
|
|
245
|
+
if (this.queuedNote) {
|
|
246
|
+
this.activity.removeChild(this.queuedNote);
|
|
247
|
+
this.queuedNote = null;
|
|
248
|
+
}
|
|
249
|
+
if (!this.queued.length || !this.agent || this.exited)
|
|
250
|
+
return;
|
|
251
|
+
const text = this.queued.splice(0).join("\n\n");
|
|
252
|
+
this.addUser(text);
|
|
253
|
+
const agent = this.agent;
|
|
254
|
+
void this.runTurn((signal) => agent.send(text, signal));
|
|
255
|
+
}
|
|
256
|
+
showQueued() {
|
|
257
|
+
const text = theme.muted(`Queued (${this.queued.length}). Sends when this step finishes, or now with esc.`);
|
|
258
|
+
if (!this.queuedNote) {
|
|
259
|
+
this.queuedNote = new Lines(text, 2);
|
|
260
|
+
this.activity.addChild(this.queuedNote);
|
|
261
|
+
}
|
|
262
|
+
else
|
|
263
|
+
this.queuedNote.setText(text);
|
|
264
|
+
this.tui.requestRender();
|
|
265
|
+
}
|
|
266
|
+
onEvent(event) {
|
|
267
|
+
switch (event.type) {
|
|
268
|
+
case "model_start":
|
|
269
|
+
this.reply = null;
|
|
270
|
+
this.replyText = "";
|
|
271
|
+
this.reasoning = null;
|
|
272
|
+
this.setLoader("Thinking…");
|
|
273
|
+
break;
|
|
274
|
+
case "reasoning":
|
|
275
|
+
if (!this.reasoning) {
|
|
276
|
+
this.reasoning = new Reasoning();
|
|
277
|
+
this.add(this.reasoning, "steps");
|
|
278
|
+
this.lastExpandable = this.reasoning;
|
|
279
|
+
}
|
|
280
|
+
this.reasoning.append(event.text);
|
|
281
|
+
break;
|
|
282
|
+
case "text":
|
|
283
|
+
this.reasoning?.finish();
|
|
284
|
+
if (!this.reply) {
|
|
285
|
+
this.reply = new Markdown("", INDENT.length, 0, markdownTheme);
|
|
286
|
+
this.add(this.reply, "text");
|
|
287
|
+
}
|
|
288
|
+
this.replyText += event.text;
|
|
289
|
+
this.reply.setText(this.replyText);
|
|
290
|
+
this.setLoader("Writing…");
|
|
291
|
+
break;
|
|
292
|
+
case "tool_call_streaming":
|
|
293
|
+
this.reasoning?.finish();
|
|
294
|
+
this.setLoader(event.name === PLAN_TOOL ? "Writing the plan…" : `Preparing ${event.name}…`);
|
|
295
|
+
break;
|
|
296
|
+
case "plan_draft":
|
|
297
|
+
this.reasoning?.finish();
|
|
298
|
+
if (this.planBlock)
|
|
299
|
+
this.planBlock.setText(event.text);
|
|
300
|
+
else {
|
|
301
|
+
this.planBlock = new PlanBlock(event.text);
|
|
302
|
+
this.add(this.planBlock, "text");
|
|
303
|
+
}
|
|
304
|
+
this.setLoader("Writing the plan…");
|
|
305
|
+
break;
|
|
306
|
+
case "plan_draft_dropped":
|
|
307
|
+
if (this.planBlock)
|
|
308
|
+
this.transcript.removeChild(this.planBlock);
|
|
309
|
+
this.planBlock = null;
|
|
310
|
+
break;
|
|
311
|
+
case "mode_changed":
|
|
312
|
+
// The agent switched it (the plan was approved); the status line shows it below.
|
|
313
|
+
break;
|
|
314
|
+
case "model_done":
|
|
315
|
+
this.reasoning?.finish();
|
|
316
|
+
this.reply = null;
|
|
317
|
+
break;
|
|
318
|
+
case "tool_start": {
|
|
319
|
+
// A plan shows as itself (above), and its outcome as a line once answered.
|
|
320
|
+
if (event.name === PLAN_TOOL)
|
|
321
|
+
break;
|
|
322
|
+
const line = new ToolLine(event.id, event.title);
|
|
323
|
+
this.toolLines.set(event.id, line);
|
|
324
|
+
this.add(line, "steps");
|
|
325
|
+
const helpers = [...this.toolLines.values()].filter((l) => l.status === "running" && l.title.startsWith("Helper: ")).length;
|
|
326
|
+
this.setLoader(event.name === "task"
|
|
327
|
+
? helpers > 1
|
|
328
|
+
? `${helpers} helpers working…`
|
|
329
|
+
: "Helper working…"
|
|
330
|
+
: `${event.title}…`);
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
case "tool_done": {
|
|
334
|
+
let line = this.toolLines.get(event.id);
|
|
335
|
+
if (!line) {
|
|
336
|
+
line = new ToolLine(event.id, event.title);
|
|
337
|
+
this.add(line, "steps");
|
|
338
|
+
}
|
|
339
|
+
const { result } = event;
|
|
340
|
+
const feedback = result.plan?.feedback;
|
|
341
|
+
line.finish(result.isError ? "error" : "done", feedback ? `${result.summary} · ${feedback}` : result.summary, result.detail);
|
|
342
|
+
if (event.name === PLAN_TOOL) {
|
|
343
|
+
this.planBlock = null;
|
|
344
|
+
this.lastPlanOutcome = result.plan?.outcome ?? null;
|
|
345
|
+
}
|
|
346
|
+
if (event.name === "todo" && this.todos.length) {
|
|
347
|
+
line.detail = formatTodos(this.todos);
|
|
348
|
+
line.expanded = true;
|
|
349
|
+
}
|
|
350
|
+
this.writer?.append(stepRecord(event.id, event.title, result));
|
|
351
|
+
if (line.expandable)
|
|
352
|
+
this.lastExpandable = line;
|
|
353
|
+
this.setLoader("Thinking…");
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
356
|
+
case "retry":
|
|
357
|
+
this.setLoader(retryMessage(event.error, event.delayMs));
|
|
358
|
+
break;
|
|
359
|
+
case "notice":
|
|
360
|
+
this.notice(theme.muted(event.text));
|
|
361
|
+
break;
|
|
362
|
+
case "compacting":
|
|
363
|
+
this.setLoader("Summarizing earlier conversation…");
|
|
364
|
+
break;
|
|
365
|
+
case "compacted":
|
|
366
|
+
this.notice(theme.muted(compactionNote(event.beforeTokens, event.afterTokens, this.model?.contextLength ?? 1)));
|
|
367
|
+
break;
|
|
368
|
+
case "error":
|
|
369
|
+
this.showError(event.error);
|
|
370
|
+
break;
|
|
371
|
+
case "done":
|
|
372
|
+
if (event.reason === "aborted")
|
|
373
|
+
this.notice(theme.muted("Stopped. What should it do instead?"));
|
|
374
|
+
if (event.reason === "declined") {
|
|
375
|
+
this.notice(theme.muted(this.lastPlanOutcome === "not-approved"
|
|
376
|
+
? "Plan not approved. Say what should change, or press Shift+Tab to leave Plan mode."
|
|
377
|
+
: "Okay, I won't. What should it do instead?"));
|
|
378
|
+
}
|
|
379
|
+
this.lastPlanOutcome = null;
|
|
380
|
+
break;
|
|
381
|
+
}
|
|
382
|
+
this.updateStatus();
|
|
383
|
+
this.tui.requestRender();
|
|
384
|
+
}
|
|
385
|
+
showError(error) {
|
|
386
|
+
const copy = describeError(error, this.session.appUrl);
|
|
387
|
+
this.pendingNext = copy.next;
|
|
388
|
+
this.notice([theme.error(`✗ ${copy.message}`), ...(copy.hint ? [theme.muted(copy.hint)] : [])].join("\n"));
|
|
389
|
+
}
|
|
390
|
+
/** Shows an approval box and waits for y / a / n (or Esc, or the turn being stopped). */
|
|
391
|
+
/** Approvals wait their turn: helpers working at once ask one at a time. */
|
|
392
|
+
approve(request, signal) {
|
|
393
|
+
const show = () => signal.aborted
|
|
394
|
+
? Promise.resolve({ kind: "no" })
|
|
395
|
+
: this.showApproval(request, signal);
|
|
396
|
+
const next = this.approvals.then(show, show);
|
|
397
|
+
this.approvals = next.catch(() => { });
|
|
398
|
+
return next;
|
|
399
|
+
}
|
|
400
|
+
showApproval(request, signal) {
|
|
401
|
+
if (request.tool === PLAN_TOOL)
|
|
402
|
+
return this.showPlanApproval(request, signal);
|
|
403
|
+
return new Promise((resolve) => {
|
|
404
|
+
let done = false;
|
|
405
|
+
const finish = (decision) => {
|
|
406
|
+
if (done)
|
|
407
|
+
return;
|
|
408
|
+
done = true;
|
|
409
|
+
signal.removeEventListener("abort", onAbort);
|
|
410
|
+
if (this.approval === box) {
|
|
411
|
+
this.activity.removeChild(box);
|
|
412
|
+
this.approval = null;
|
|
413
|
+
}
|
|
414
|
+
if (this.lastExpandable === box)
|
|
415
|
+
this.lastExpandable = null;
|
|
416
|
+
this.tui.setFocus(this.editor);
|
|
417
|
+
if (!signal.aborted)
|
|
418
|
+
this.showLoader(`${request.title}…`);
|
|
419
|
+
this.tui.requestRender();
|
|
420
|
+
resolve(decision);
|
|
421
|
+
};
|
|
422
|
+
const onAbort = () => finish({ kind: "no" });
|
|
423
|
+
const box = new ApprovalBox(request, finish);
|
|
424
|
+
this.hideLoader();
|
|
425
|
+
this.approval = box;
|
|
426
|
+
this.lastExpandable = box;
|
|
427
|
+
this.activity.addChild(box);
|
|
428
|
+
this.tui.setFocus(box);
|
|
429
|
+
this.tui.requestRender();
|
|
430
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* "Ready to build?" under the plan. Ctrl+G hands the terminal to the person's editor and comes
|
|
435
|
+
* back with their version, which the answer then carries.
|
|
436
|
+
*/
|
|
437
|
+
showPlanApproval(request, signal) {
|
|
438
|
+
const original = request.preview ?? "";
|
|
439
|
+
// The draft becomes the plan as presented (or it appears now, if it wasn't streamed).
|
|
440
|
+
if (this.planBlock)
|
|
441
|
+
this.planBlock.setText(original);
|
|
442
|
+
else {
|
|
443
|
+
this.planBlock = new PlanBlock(original);
|
|
444
|
+
this.add(this.planBlock, "text");
|
|
445
|
+
}
|
|
446
|
+
return new Promise((resolve) => {
|
|
447
|
+
let done = false;
|
|
448
|
+
let edited = null;
|
|
449
|
+
const finish = (decision) => {
|
|
450
|
+
if (done)
|
|
451
|
+
return;
|
|
452
|
+
done = true;
|
|
453
|
+
signal.removeEventListener("abort", onAbort);
|
|
454
|
+
if (this.approval === box) {
|
|
455
|
+
this.activity.removeChild(box);
|
|
456
|
+
this.approval = null;
|
|
457
|
+
}
|
|
458
|
+
this.tui.setFocus(this.editor);
|
|
459
|
+
if (!signal.aborted) {
|
|
460
|
+
if (decision.kind !== "no")
|
|
461
|
+
this.showLoader("Starting on the plan…");
|
|
462
|
+
else if (decision.feedback)
|
|
463
|
+
this.showLoader("Revising the plan…");
|
|
464
|
+
}
|
|
465
|
+
this.tui.requestRender();
|
|
466
|
+
resolve(edited !== null ? { ...decision, plan: edited } : decision);
|
|
467
|
+
};
|
|
468
|
+
const onAbort = () => finish({ kind: "no" });
|
|
469
|
+
const edit = async () => {
|
|
470
|
+
if (this.editingPlan || done)
|
|
471
|
+
return;
|
|
472
|
+
this.editingPlan = true;
|
|
473
|
+
const before = edited ?? original;
|
|
474
|
+
let outcome;
|
|
475
|
+
this.tui.stop();
|
|
476
|
+
try {
|
|
477
|
+
outcome = await (this.options.editPlan ?? editInEditor)(before);
|
|
478
|
+
}
|
|
479
|
+
catch (error) {
|
|
480
|
+
outcome = { kind: "failed", message: error.message };
|
|
481
|
+
}
|
|
482
|
+
finally {
|
|
483
|
+
this.tui.start();
|
|
484
|
+
// A forced redraw: renders asked for while the editor had the screen were skipped.
|
|
485
|
+
this.tui.requestRender(true);
|
|
486
|
+
this.editingPlan = false;
|
|
487
|
+
}
|
|
488
|
+
if (done)
|
|
489
|
+
return;
|
|
490
|
+
if (outcome.kind === "failed")
|
|
491
|
+
this.flash("Couldn't open your editor. Set $EDITOR.");
|
|
492
|
+
else if (outcome.kind === "empty") {
|
|
493
|
+
this.notice(theme.muted("The edited plan was empty, so the plan stays as it was."));
|
|
494
|
+
}
|
|
495
|
+
else if (outcome.kind === "unchanged") {
|
|
496
|
+
if (outcome.quick)
|
|
497
|
+
this.flash("If your editor returns at once, set EDITOR='code --wait'.");
|
|
498
|
+
}
|
|
499
|
+
else {
|
|
500
|
+
const n = changedLines(before, outcome.text);
|
|
501
|
+
edited = outcome.text;
|
|
502
|
+
box.edited = true;
|
|
503
|
+
this.add(new PlanBlock(outcome.text, true), "text");
|
|
504
|
+
this.notice(`${theme.warning("✎")} Plan edited ${theme.muted(`· ${n} ${n === 1 ? "line" : "lines"} changed`)}`);
|
|
505
|
+
}
|
|
506
|
+
this.tui.requestRender();
|
|
507
|
+
};
|
|
508
|
+
const box = new PlanApprovalBox(finish, () => void edit(), this.options.planArmMs);
|
|
509
|
+
this.hideLoader();
|
|
510
|
+
this.approval = box;
|
|
511
|
+
this.activity.addChild(box);
|
|
512
|
+
this.tui.setFocus(box);
|
|
513
|
+
this.tui.requestRender();
|
|
514
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
// --- commands ---------------------------------------------------------------------------------
|
|
518
|
+
runCommand(name, arg) {
|
|
519
|
+
switch (name) {
|
|
520
|
+
case "model":
|
|
521
|
+
if (this.busy)
|
|
522
|
+
return this.notice(theme.muted("Switch models after this step (esc to stop it)."));
|
|
523
|
+
return this.openModelPicker(arg);
|
|
524
|
+
case "mode": {
|
|
525
|
+
const wanted = MODES.find((m) => m.startsWith(arg.toLowerCase()) && arg);
|
|
526
|
+
if (wanted)
|
|
527
|
+
this.setMode(wanted);
|
|
528
|
+
else
|
|
529
|
+
this.cycleMode();
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
case "new":
|
|
533
|
+
case "clear":
|
|
534
|
+
if (this.busy)
|
|
535
|
+
return this.notice(theme.muted("Stop the current task first (esc)."));
|
|
536
|
+
void this.writer?.release();
|
|
537
|
+
this.writer = null;
|
|
538
|
+
if (this.agent)
|
|
539
|
+
this.spentBefore += this.agent.totalCostMicros;
|
|
540
|
+
this.agent = this.model ? this.newAgent(this.model) : null;
|
|
541
|
+
this.permissions.allows = emptyAllows();
|
|
542
|
+
this.todos.length = 0;
|
|
543
|
+
this.notice(theme.muted("── New conversation ──"));
|
|
544
|
+
this.updateStatus();
|
|
545
|
+
return;
|
|
546
|
+
case "cost": {
|
|
547
|
+
const context = this.agent?.contextTokens;
|
|
548
|
+
this.notice([
|
|
549
|
+
`This session: ~${formatUsd(this.sessionCost())} (an estimate; your usage page has exact charges)`,
|
|
550
|
+
`Balance: ${this.balance ?? "unknown"}`,
|
|
551
|
+
...(context != null && this.model
|
|
552
|
+
? [
|
|
553
|
+
`Context: ${formatTokens(context)} of ${formatTokens(this.model.contextLength)} tokens`,
|
|
554
|
+
]
|
|
555
|
+
: []),
|
|
556
|
+
].join("\n"));
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
case "compact": {
|
|
560
|
+
if (this.busy)
|
|
561
|
+
return this.notice(theme.muted("Compact after this step (esc to stop it)."));
|
|
562
|
+
const agent = this.agent;
|
|
563
|
+
if (!agent)
|
|
564
|
+
return;
|
|
565
|
+
void this.runTurn((signal) => agent.compactNow(signal));
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
case "resume":
|
|
569
|
+
if (this.busy)
|
|
570
|
+
return this.notice(theme.muted("Resume after this step (esc to stop it)."));
|
|
571
|
+
void this.openSessionPicker();
|
|
572
|
+
return;
|
|
573
|
+
case "login":
|
|
574
|
+
if (this.busy)
|
|
575
|
+
return this.notice(theme.muted("Log in after this step (esc to stop it)."));
|
|
576
|
+
void this.relogin();
|
|
577
|
+
return;
|
|
578
|
+
case "mcp":
|
|
579
|
+
this.notice(this.mcpReport());
|
|
580
|
+
return;
|
|
581
|
+
case "help":
|
|
582
|
+
this.notice(helpText());
|
|
583
|
+
return;
|
|
584
|
+
case "exit":
|
|
585
|
+
case "quit":
|
|
586
|
+
this.exit(0);
|
|
587
|
+
return;
|
|
588
|
+
default:
|
|
589
|
+
this.notice(theme.warning(`/${name} isn't a command. Type /help for the list.`));
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
cycleMode() {
|
|
593
|
+
const next = MODES[(MODES.indexOf(this.permissions.mode) + 1) % MODES.length];
|
|
594
|
+
this.setMode(next);
|
|
595
|
+
}
|
|
596
|
+
setMode(mode) {
|
|
597
|
+
this.permissions.mode = mode;
|
|
598
|
+
if (mode === "full") {
|
|
599
|
+
this.flash("Don't ask: edits and commands run without asking. Shift+Tab to switch back.");
|
|
600
|
+
}
|
|
601
|
+
else if (mode === "plan") {
|
|
602
|
+
this.flash("Plan mode: it looks around and plans. Nothing changes until you approve.");
|
|
603
|
+
}
|
|
604
|
+
this.updateStatus();
|
|
605
|
+
this.tui.requestRender();
|
|
606
|
+
}
|
|
607
|
+
openModelPicker(filter = "") {
|
|
608
|
+
if (this.picker)
|
|
609
|
+
return;
|
|
610
|
+
const items = sortModels(this.options.models).map(modelChoice);
|
|
611
|
+
if (!items.length) {
|
|
612
|
+
this.notice(theme.error("No models that can use tools are available to your workspace."));
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
const picker = new Picker(this.model ? "Switch model" : "Pick a model (you can change it any time with /model)", items);
|
|
616
|
+
if (this.model)
|
|
617
|
+
picker.select(this.model.id);
|
|
618
|
+
if (filter)
|
|
619
|
+
for (const ch of filter)
|
|
620
|
+
picker.handleInput(ch);
|
|
621
|
+
picker.onSelect = (id) => void this.pickModel(id);
|
|
622
|
+
picker.onCancel = () => {
|
|
623
|
+
this.closePicker();
|
|
624
|
+
if (!this.model)
|
|
625
|
+
this.notice(theme.muted("Pick a model to start: type /model."));
|
|
626
|
+
};
|
|
627
|
+
this.picker = picker;
|
|
628
|
+
this.activity.addChild(picker);
|
|
629
|
+
this.tui.setFocus(picker);
|
|
630
|
+
this.tui.requestRender();
|
|
631
|
+
}
|
|
632
|
+
closePicker() {
|
|
633
|
+
if (!this.picker)
|
|
634
|
+
return;
|
|
635
|
+
this.activity.removeChild(this.picker);
|
|
636
|
+
this.picker = null;
|
|
637
|
+
this.tui.setFocus(this.editor);
|
|
638
|
+
this.tui.requestRender();
|
|
639
|
+
}
|
|
640
|
+
async pickModel(id) {
|
|
641
|
+
const model = this.options.models.find((m) => m.id === id);
|
|
642
|
+
this.closePicker();
|
|
643
|
+
if (!model)
|
|
644
|
+
return;
|
|
645
|
+
this.model = model;
|
|
646
|
+
if (this.header)
|
|
647
|
+
this.header.model = model.id;
|
|
648
|
+
this.writer?.append({ type: "model", id: model.id });
|
|
649
|
+
if (this.agent) {
|
|
650
|
+
this.agent.options.model = model;
|
|
651
|
+
this.agent.messages[0] = { role: "system", content: this.options.systemPrompt(model) };
|
|
652
|
+
}
|
|
653
|
+
else {
|
|
654
|
+
this.agent = this.newAgent(model);
|
|
655
|
+
}
|
|
656
|
+
this.notice(theme.muted(`Using ${model.id}.`));
|
|
657
|
+
this.updateStatus();
|
|
658
|
+
await this.options.rememberModel(model.id).catch(() => { });
|
|
659
|
+
const waiting = this.afterPick;
|
|
660
|
+
this.afterPick = null;
|
|
661
|
+
if (waiting)
|
|
662
|
+
this.submit(waiting);
|
|
663
|
+
}
|
|
664
|
+
async relogin() {
|
|
665
|
+
this.pendingNext = null;
|
|
666
|
+
const lines = new Lines("", 2);
|
|
667
|
+
this.add(lines);
|
|
668
|
+
const log = [];
|
|
669
|
+
this.showLoader("Waiting for you to approve this computer in your browser…");
|
|
670
|
+
try {
|
|
671
|
+
this.session = await this.options.login((line) => {
|
|
672
|
+
log.push(line);
|
|
673
|
+
lines.setText(theme.muted(log.join("\n")));
|
|
674
|
+
this.tui.requestRender();
|
|
675
|
+
});
|
|
676
|
+
if (this.agent) {
|
|
677
|
+
this.agent.options.apiKey = this.session.apiKey;
|
|
678
|
+
this.agent.options.apiBaseUrl = this.session.apiBaseUrl;
|
|
679
|
+
}
|
|
680
|
+
this.hideLoader();
|
|
681
|
+
this.notice(theme.success("Logged in."));
|
|
682
|
+
this.refreshBalanceSoon(0);
|
|
683
|
+
if (this.agent?.canRetry)
|
|
684
|
+
this.retry();
|
|
685
|
+
}
|
|
686
|
+
catch (error) {
|
|
687
|
+
this.hideLoader();
|
|
688
|
+
this.notice(theme.error(`✗ ${error.message}`));
|
|
689
|
+
this.pendingNext = "login";
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
// --- helpers ----------------------------------------------------------------------------------
|
|
693
|
+
// --- MCP ------------------------------------------------------------------------------------
|
|
694
|
+
tools() {
|
|
695
|
+
return [...BUILTIN_TOOLS, ...(this.options.mcp?.tools ?? [])];
|
|
696
|
+
}
|
|
697
|
+
/** Picks up MCP tools as servers connect, and says once how the start-up went. */
|
|
698
|
+
watchMcp() {
|
|
699
|
+
const mcp = this.options.mcp;
|
|
700
|
+
for (const error of this.options.mcpErrors ?? [])
|
|
701
|
+
this.notice(theme.warning(error));
|
|
702
|
+
if (!mcp)
|
|
703
|
+
return;
|
|
704
|
+
let reported = false;
|
|
705
|
+
mcp.onChange = () => {
|
|
706
|
+
if (this.agent)
|
|
707
|
+
this.agent.options.tools = this.tools();
|
|
708
|
+
const statuses = [...mcp.statuses.values()];
|
|
709
|
+
if (reported || statuses.some((s) => s.state === "connecting"))
|
|
710
|
+
return;
|
|
711
|
+
reported = true;
|
|
712
|
+
const ok = statuses.filter((s) => s.state === "connected");
|
|
713
|
+
if (ok.length) {
|
|
714
|
+
this.notice(theme.muted(`MCP: ${ok.map((s) => `${s.name} (${count(s.tools, "tool")})`).join(", ")}.`));
|
|
715
|
+
}
|
|
716
|
+
for (const s of statuses.filter((s) => s.state === "failed")) {
|
|
717
|
+
this.notice(theme.warning(`MCP server ${s.name} couldn't start: ${s.error}. /mcp for details.`));
|
|
718
|
+
}
|
|
719
|
+
this.tui.requestRender();
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
mcpReport() {
|
|
723
|
+
const mcp = this.options.mcp;
|
|
724
|
+
const where = tildePath(this.options.mcpConfigPath, this.options.home);
|
|
725
|
+
if (!mcp || mcp.statuses.size === 0) {
|
|
726
|
+
return [
|
|
727
|
+
`No MCP servers set up. Add them to ${where}, for example:`,
|
|
728
|
+
"",
|
|
729
|
+
theme.muted(MCP_EXAMPLE),
|
|
730
|
+
"",
|
|
731
|
+
theme.muted("Then restart reasonally."),
|
|
732
|
+
].join("\n");
|
|
733
|
+
}
|
|
734
|
+
const lines = [...mcp.statuses.values()].map((s) => {
|
|
735
|
+
const state = s.state === "connected"
|
|
736
|
+
? theme.success(`connected · ${count(s.tools, "tool")}`)
|
|
737
|
+
: s.state === "connecting"
|
|
738
|
+
? theme.muted("connecting…")
|
|
739
|
+
: theme.error(`failed: ${s.error}`);
|
|
740
|
+
return `${s.name} (${s.transport}) · ${state}`;
|
|
741
|
+
});
|
|
742
|
+
return [`MCP servers (${where})`, ...lines.map((l) => ` ${l}`)].join("\n");
|
|
743
|
+
}
|
|
744
|
+
// --- sessions -------------------------------------------------------------------------------
|
|
745
|
+
/** Saves each change to the conversation as it happens (the file starts with the first one). */
|
|
746
|
+
save(change) {
|
|
747
|
+
if (!this.model)
|
|
748
|
+
return;
|
|
749
|
+
this.writer ??= SessionWriter.create(this.options.sessionsDir, this.options.cwd, this.model.id, new Date(), "terminal");
|
|
750
|
+
if (change.type === "usage") {
|
|
751
|
+
this.writer.append({
|
|
752
|
+
type: "usage",
|
|
753
|
+
promptTokens: change.usage.promptTokens,
|
|
754
|
+
completionTokens: change.usage.completionTokens,
|
|
755
|
+
costMicros: change.costMicros.toString(),
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
else if (change.type === "append") {
|
|
759
|
+
this.writer.append({ type: "append", message: change.message });
|
|
760
|
+
}
|
|
761
|
+
else {
|
|
762
|
+
this.writer.append({ type: "replace", reason: change.reason, messages: change.messages });
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
/** Continues a saved conversation: reprints it as it looked, then carries on in the same file. */
|
|
766
|
+
resumeSession(loaded) {
|
|
767
|
+
const model = this.options.models.find((m) => m.id === loaded.model) ?? this.model;
|
|
768
|
+
if (!model) {
|
|
769
|
+
this.notice(theme.warning("Pick a model to continue this conversation: type /model."));
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
if (model.id !== loaded.model) {
|
|
773
|
+
this.notice(theme.muted(`${loaded.model} isn't available any more; using ${model.id}.`));
|
|
774
|
+
}
|
|
775
|
+
this.model = model;
|
|
776
|
+
if (this.header)
|
|
777
|
+
this.header.model = model.id;
|
|
778
|
+
this.agent = this.newAgent(model);
|
|
779
|
+
this.agent.restore(loaded.messages);
|
|
780
|
+
void this.writer?.release();
|
|
781
|
+
this.writer = SessionWriter.resume(loaded.path);
|
|
782
|
+
// The callers checked that nothing else has it open.
|
|
783
|
+
void this.writer.claim("terminal");
|
|
784
|
+
for (const entry of loaded.display) {
|
|
785
|
+
if (entry.kind === "user")
|
|
786
|
+
this.addUser(entry.text);
|
|
787
|
+
else if (entry.kind === "text") {
|
|
788
|
+
this.add(new Markdown(entry.text, INDENT.length, 0, markdownTheme), "text");
|
|
789
|
+
}
|
|
790
|
+
else if (entry.kind === "step") {
|
|
791
|
+
const line = new ToolLine("", entry.title);
|
|
792
|
+
line.finish(entry.isError ? "error" : "done", entry.summary);
|
|
793
|
+
this.add(line, "steps");
|
|
794
|
+
}
|
|
795
|
+
else if (entry.kind === "plan") {
|
|
796
|
+
this.add(new PlanBlock(entry.text, entry.edited), "text");
|
|
797
|
+
const line = new ToolLine("", "Plan");
|
|
798
|
+
const failed = entry.outcome === "not-approved" || entry.outcome === "stopped";
|
|
799
|
+
const label = PLAN_OUTCOME_LABELS[entry.outcome];
|
|
800
|
+
line.finish(failed ? "error" : "done", entry.feedback ? `${label} · ${entry.feedback}` : label);
|
|
801
|
+
this.add(line, "steps");
|
|
802
|
+
}
|
|
803
|
+
else
|
|
804
|
+
this.notice(theme.muted("Summarized earlier conversation."));
|
|
805
|
+
}
|
|
806
|
+
this.notice(theme.muted(`Resumed the conversation from ${timeAgo(loaded.updatedAt)}.`));
|
|
807
|
+
this.updateStatus();
|
|
808
|
+
}
|
|
809
|
+
async openSessionPicker() {
|
|
810
|
+
if (this.picker)
|
|
811
|
+
return;
|
|
812
|
+
const sessions = await listSessions(this.options.sessionsDir);
|
|
813
|
+
const current = this.writer?.path;
|
|
814
|
+
const choices = sessions.filter((s) => s.path !== current);
|
|
815
|
+
if (!choices.length) {
|
|
816
|
+
this.notice(theme.muted("No other saved conversations in this folder yet."));
|
|
817
|
+
if (!this.model)
|
|
818
|
+
this.openModelPicker();
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
const picker = new Picker("Resume a conversation", choices.map((s) => ({
|
|
822
|
+
value: s.path,
|
|
823
|
+
label: s.firstMessage.replace(/\s+/g, " ").slice(0, 60),
|
|
824
|
+
description: `${timeAgo(s.updatedAt)} · ${s.model}${s.costMicros > 0n ? ` · ~${formatUsd(s.costMicros)}` : ""}`,
|
|
825
|
+
})));
|
|
826
|
+
picker.onSelect = (path) => void this.pickSession(path);
|
|
827
|
+
picker.onCancel = () => {
|
|
828
|
+
this.closePicker();
|
|
829
|
+
if (!this.model)
|
|
830
|
+
this.openModelPicker();
|
|
831
|
+
};
|
|
832
|
+
this.picker = picker;
|
|
833
|
+
this.activity.addChild(picker);
|
|
834
|
+
this.tui.setFocus(picker);
|
|
835
|
+
this.tui.requestRender();
|
|
836
|
+
}
|
|
837
|
+
async pickSession(path) {
|
|
838
|
+
this.closePicker();
|
|
839
|
+
const holder = await sessionHolder(path);
|
|
840
|
+
if (holder) {
|
|
841
|
+
this.notice(theme.muted(`${openElsewhere(holder)} Close it there to continue it here.`));
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
const loaded = await loadSession(path);
|
|
845
|
+
if (!loaded) {
|
|
846
|
+
this.notice(theme.error("✗ That conversation couldn't be read."));
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
if (this.agent)
|
|
850
|
+
this.spentBefore += this.agent.totalCostMicros;
|
|
851
|
+
this.permissions.allows = emptyAllows();
|
|
852
|
+
this.notice(theme.muted("── Resumed conversation ──"));
|
|
853
|
+
this.resumeSession(loaded);
|
|
854
|
+
}
|
|
855
|
+
newAgent(model) {
|
|
856
|
+
this.todos = [];
|
|
857
|
+
return new Agent({
|
|
858
|
+
apiBaseUrl: this.session.apiBaseUrl,
|
|
859
|
+
apiKey: this.session.apiKey,
|
|
860
|
+
model,
|
|
861
|
+
tools: this.tools(),
|
|
862
|
+
systemPrompt: this.options.systemPrompt(model),
|
|
863
|
+
toolContext: {
|
|
864
|
+
cwd: this.options.cwd,
|
|
865
|
+
home: this.options.home,
|
|
866
|
+
files: this.files,
|
|
867
|
+
todos: this.todos,
|
|
868
|
+
env: commandEnv(process.env),
|
|
869
|
+
},
|
|
870
|
+
permissions: this.permissions,
|
|
871
|
+
approve: (request, signal) => this.approve(request, signal),
|
|
872
|
+
onProgress: (id, text) => {
|
|
873
|
+
const line = this.toolLines.get(id);
|
|
874
|
+
if (!line || line.status !== "running")
|
|
875
|
+
return;
|
|
876
|
+
line.progress = text;
|
|
877
|
+
this.tui.requestRender();
|
|
878
|
+
},
|
|
879
|
+
fetch: this.options.fetch,
|
|
880
|
+
onChange: (change) => this.save(change),
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
sessionCost() {
|
|
884
|
+
return this.spentBefore + (this.agent?.totalCostMicros ?? 0n);
|
|
885
|
+
}
|
|
886
|
+
billingUrl() {
|
|
887
|
+
return `${this.session.appUrl.replace(/^https?:\/\//, "")}/dashboard/billing`;
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Adds to the transcript. A blank line separates the model's text from runs of tool steps,
|
|
891
|
+
* so each reads as its own block.
|
|
892
|
+
*/
|
|
893
|
+
add(component, kind = "other") {
|
|
894
|
+
if (kind !== "other" && this.lastKind !== null && this.lastKind !== kind) {
|
|
895
|
+
this.transcript.addChild(gap());
|
|
896
|
+
}
|
|
897
|
+
this.lastKind = kind;
|
|
898
|
+
this.transcript.addChild(component);
|
|
899
|
+
this.tui.requestRender();
|
|
900
|
+
}
|
|
901
|
+
addUser(text) {
|
|
902
|
+
this.add(new UserMessage(text));
|
|
903
|
+
this.lastKind = null; // the message ends with its own blank line
|
|
904
|
+
}
|
|
905
|
+
notice(text) {
|
|
906
|
+
this.add(new Lines(`\n${text}`, 2));
|
|
907
|
+
}
|
|
908
|
+
/** A short-lived message in the status line. */
|
|
909
|
+
flash(text) {
|
|
910
|
+
this.hint = text;
|
|
911
|
+
clearTimeout(this.hintTimer);
|
|
912
|
+
this.hintTimer = setTimeout(() => {
|
|
913
|
+
this.hint = null;
|
|
914
|
+
this.updateStatus();
|
|
915
|
+
this.tui.requestRender();
|
|
916
|
+
}, 2500);
|
|
917
|
+
this.hintTimer.unref();
|
|
918
|
+
this.updateStatus();
|
|
919
|
+
this.tui.requestRender();
|
|
920
|
+
}
|
|
921
|
+
updateStatus() {
|
|
922
|
+
const mode = this.permissions.mode;
|
|
923
|
+
const line = statusLine({
|
|
924
|
+
mode,
|
|
925
|
+
contextTokens: this.agent?.contextTokens ?? null,
|
|
926
|
+
contextLength: this.model?.contextLength ?? 1,
|
|
927
|
+
costMicros: this.sessionCost(),
|
|
928
|
+
balance: this.balance,
|
|
929
|
+
});
|
|
930
|
+
// Plan mode stands out, so it's clear at a glance that nothing will change.
|
|
931
|
+
const shown = mode === "plan"
|
|
932
|
+
? theme.accent(modeStatus(mode)) + theme.muted(line.slice(modeStatus(mode).length))
|
|
933
|
+
: theme.muted(line);
|
|
934
|
+
this.status.setText(this.hint ? theme.warning(this.hint) : shown);
|
|
935
|
+
}
|
|
936
|
+
showLoader(text) {
|
|
937
|
+
this.loaderText = text;
|
|
938
|
+
if (this.loader) {
|
|
939
|
+
this.loader.setMessage(`${text} ${theme.muted("(esc to stop)")}`);
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
this.loader = new Loader(this.tui, theme.accent, (t) => t, `${text} ${theme.muted("(esc to stop)")}`);
|
|
943
|
+
this.loader.setPaddingX(INDENT.length);
|
|
944
|
+
this.activity.addChild(this.loader);
|
|
945
|
+
this.loader.start();
|
|
946
|
+
}
|
|
947
|
+
setLoader(text) {
|
|
948
|
+
if (text !== this.loaderText && this.loader)
|
|
949
|
+
this.showLoader(text);
|
|
950
|
+
}
|
|
951
|
+
hideLoader() {
|
|
952
|
+
if (!this.loader)
|
|
953
|
+
return;
|
|
954
|
+
this.loader.stop();
|
|
955
|
+
this.activity.removeChild(this.loader);
|
|
956
|
+
this.loader = null;
|
|
957
|
+
}
|
|
958
|
+
refreshBalanceSoon(delay = this.options.balanceDelayMs ?? 1500) {
|
|
959
|
+
setTimeout(() => {
|
|
960
|
+
this.options
|
|
961
|
+
.fetchBalance(this.session)
|
|
962
|
+
.then((balance) => {
|
|
963
|
+
if (balance === null || this.exited)
|
|
964
|
+
return;
|
|
965
|
+
this.balance = balance;
|
|
966
|
+
this.updateStatus();
|
|
967
|
+
this.tui.requestRender();
|
|
968
|
+
})
|
|
969
|
+
.catch(() => { });
|
|
970
|
+
}, delay).unref();
|
|
971
|
+
}
|
|
972
|
+
/** Restores the terminal, prints a one-line summary and reports the exit code. */
|
|
973
|
+
exit(code) {
|
|
974
|
+
if (this.exited)
|
|
975
|
+
return;
|
|
976
|
+
this.exited = true;
|
|
977
|
+
this.busy?.abort();
|
|
978
|
+
this.hideLoader();
|
|
979
|
+
clearTimeout(this.hintTimer);
|
|
980
|
+
// Leave the conversation on screen, without the input box and status line.
|
|
981
|
+
this.tui.removeChild(this.activity);
|
|
982
|
+
this.tui.removeChild(this.editor);
|
|
983
|
+
this.tui.removeChild(this.status);
|
|
984
|
+
this.tui.renderNow(true);
|
|
985
|
+
this.tui.stop();
|
|
986
|
+
const cost = this.sessionCost();
|
|
987
|
+
const costText = cost > 0n ? style.dim(`~${formatUsd(cost)} this session`) : null;
|
|
988
|
+
const writer = this.writer;
|
|
989
|
+
const mcp = this.options.mcp;
|
|
990
|
+
if (!writer && !mcp) {
|
|
991
|
+
this.options.onExit(code, costText);
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
// Let the last writes land (and MCP servers stop) before reporting where it was saved.
|
|
995
|
+
const stopping = mcp
|
|
996
|
+
? Promise.race([mcp.close(), new Promise((r) => setTimeout(r, 2000).unref())])
|
|
997
|
+
: Promise.resolve();
|
|
998
|
+
void Promise.all([writer?.release(), stopping]).then(() => {
|
|
999
|
+
const saved = writer?.started && !writer.failed
|
|
1000
|
+
? `${style.dim("Saved. Continue with:")} reasonally --continue`
|
|
1001
|
+
: null;
|
|
1002
|
+
const summary = [saved, costText].filter(Boolean).join(" ");
|
|
1003
|
+
this.options.onExit(code, summary || null);
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
/** For tests: the label of the current mode. */
|
|
1007
|
+
get modeLabel() {
|
|
1008
|
+
return MODE_LABELS[this.permissions.mode];
|
|
1009
|
+
}
|
|
1010
|
+
}
|