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