reasonally 0.1.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.
Files changed (42) hide show
  1. package/README.md +143 -5
  2. package/dist/agent/accumulate.js +146 -0
  3. package/dist/agent/client.js +174 -0
  4. package/dist/agent/compact.js +79 -0
  5. package/dist/agent/cost.js +22 -0
  6. package/dist/agent/loop-constants.js +3 -0
  7. package/dist/agent/loop.js +559 -0
  8. package/dist/agent/mcp-config.js +72 -0
  9. package/dist/agent/mcp.js +194 -0
  10. package/dist/agent/permissions.js +116 -0
  11. package/dist/agent/prompt.js +98 -0
  12. package/dist/agent/session.js +196 -0
  13. package/dist/agent/sse.js +46 -0
  14. package/dist/agent/tools/bash.js +176 -0
  15. package/dist/agent/tools/diff.js +33 -0
  16. package/dist/agent/tools/files.js +270 -0
  17. package/dist/agent/tools/index.js +21 -0
  18. package/dist/agent/tools/paths.js +43 -0
  19. package/dist/agent/tools/search.js +288 -0
  20. package/dist/agent/tools/task.js +42 -0
  21. package/dist/agent/tools/todo.js +59 -0
  22. package/dist/agent/tools/types.js +57 -0
  23. package/dist/agent/types.js +2 -0
  24. package/dist/api.js +5 -1
  25. package/dist/browser/command.js +93 -0
  26. package/dist/browser/guards.js +138 -0
  27. package/dist/browser/pairing.js +123 -0
  28. package/dist/browser/protocol.js +172 -0
  29. package/dist/browser/server.js +157 -0
  30. package/dist/browser/sessions.js +478 -0
  31. package/dist/catalog.js +12 -0
  32. package/dist/cli.js +43 -3
  33. package/dist/config.js +17 -4
  34. package/dist/tui/app.js +869 -0
  35. package/dist/tui/args.js +32 -0
  36. package/dist/tui/commands.js +38 -0
  37. package/dist/tui/components.js +375 -0
  38. package/dist/tui/format.js +116 -0
  39. package/dist/tui/node-version.js +7 -0
  40. package/dist/tui/start.js +135 -0
  41. package/dist/tui/theme.js +36 -0
  42. package/package.json +11 -3
@@ -0,0 +1,32 @@
1
+ /** Flags for bare `reasonally` (the agent). No terminal UI imports: `cli.ts` loads this eagerly. */
2
+ export function parseAgentArgs(argv) {
3
+ const args = { model: null, yes: false, continue: false, resume: false };
4
+ for (let i = 0; i < argv.length; i++) {
5
+ const arg = argv[i];
6
+ if (arg === "--model" || arg === "-m") {
7
+ const value = argv[i + 1];
8
+ if (!value || value.startsWith("-"))
9
+ return { ok: false, error: `${arg} needs a model id.` };
10
+ args.model = value;
11
+ i++;
12
+ }
13
+ else if (arg.startsWith("--model=")) {
14
+ args.model = arg.slice("--model=".length) || null;
15
+ }
16
+ else if (arg === "--yes" || arg === "-y") {
17
+ args.yes = true;
18
+ }
19
+ else if (arg === "--continue" || arg === "-c") {
20
+ args.continue = true;
21
+ }
22
+ else if (arg === "--resume" || arg === "-r") {
23
+ args.resume = true;
24
+ }
25
+ else {
26
+ return { ok: false, error: `Unknown option "${arg}". See \`reasonally --help\`.` };
27
+ }
28
+ }
29
+ return { ok: true, args };
30
+ }
31
+ /** Bare `reasonally` opens the agent only in an interactive terminal; scripts still get help. */
32
+ export const isInteractive = (stdin, stdout) => Boolean(stdin.isTTY && stdout.isTTY);
@@ -0,0 +1,38 @@
1
+ export const COMMANDS = [
2
+ { name: "model", description: "Switch model" },
3
+ { name: "mode", description: "Switch between asking, auto-accepting edits, and not asking" },
4
+ { name: "new", description: "Start a new conversation" },
5
+ { name: "resume", description: "Continue an earlier conversation in this folder" },
6
+ { name: "compact", description: "Summarize the conversation so far to free up context" },
7
+ { name: "cost", description: "Show this session's cost and your balance" },
8
+ { name: "mcp", description: "Show MCP servers and their tools" },
9
+ { name: "login", description: "Log in again (e.g. after a key was revoked)" },
10
+ { name: "help", description: "Show commands and keys" },
11
+ { name: "exit", description: "Quit" },
12
+ ];
13
+ /** "/model foo" → { name: "model", arg: "foo" }; null when it isn't a command. */
14
+ export function parseCommand(text) {
15
+ const match = /^\/([a-z-]+)(?:\s+([\s\S]*))?$/i.exec(text.trim());
16
+ if (!match)
17
+ return null;
18
+ return { name: match[1].toLowerCase(), arg: (match[2] ?? "").trim() };
19
+ }
20
+ export const KEYS = [
21
+ ["Enter", "send · Shift+Enter or Ctrl+J for a new line"],
22
+ ["Esc", "stop the current reply or command"],
23
+ ["Shift+Tab", "switch mode"],
24
+ ["Ctrl+O", "show the full output of the last step"],
25
+ ["Ctrl+C", "clear the input · twice to quit"],
26
+ ["@", "mention a file"],
27
+ ["↑ ↓", "earlier messages"],
28
+ ];
29
+ export function helpText() {
30
+ const width = Math.max(...COMMANDS.map((c) => c.name.length)) + 2;
31
+ return [
32
+ "Commands",
33
+ ...COMMANDS.map((c) => ` /${c.name.padEnd(width)}${c.description}`),
34
+ "",
35
+ "Keys",
36
+ ...KEYS.map(([key, what]) => ` ${key.padEnd(width + 1)}${what}`),
37
+ ].join("\n");
38
+ }
@@ -0,0 +1,375 @@
1
+ import { Container, Input, matchesKey, SelectList, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
2
+ import { diffLineKind } from "./format.js";
3
+ import { style, theme } from "./theme.js";
4
+ /** Everything the agent says or does is indented this much; the user's "›" sits in the margin. */
5
+ export const INDENT = " ";
6
+ /** Text nested under a step (its output, reasoning, wrapped options). */
7
+ const NESTED = " ";
8
+ const nestedWidth = (width) => Math.max(10, width - NESTED.length);
9
+ /** "Reasonally · model · folder", shortening the folder from the left to fit one line. */
10
+ export class Header {
11
+ model;
12
+ folder;
13
+ constructor(model, folder) {
14
+ this.model = model;
15
+ this.folder = folder;
16
+ }
17
+ invalidate() { }
18
+ render(width) {
19
+ const prefix = `Reasonally · ${this.model} · `;
20
+ const room = Math.max(12, width - INDENT.length - prefix.length);
21
+ const folder = this.folder.length > room
22
+ ? `…${this.folder.slice(this.folder.length - room + 1)}`
23
+ : this.folder;
24
+ return [
25
+ "",
26
+ truncateToWidth(`${INDENT}${theme.brand("Reasonally")}${theme.muted(` · ${this.model} · ${folder}`)}`, width),
27
+ ...wrapTextWithAnsi(theme.muted("Ask for anything in this project. / for commands · @ for files · esc to stop"), Math.max(10, width - INDENT.length)).map((l) => INDENT + l),
28
+ ];
29
+ }
30
+ }
31
+ /** Lines of plain or styled text, wrapped to the width, with a hanging indent. */
32
+ export class Lines {
33
+ text;
34
+ indent;
35
+ constructor(text, indent = 0) {
36
+ this.text = text;
37
+ this.indent = indent;
38
+ }
39
+ setText(text) {
40
+ this.text = text;
41
+ }
42
+ invalidate() { }
43
+ render(width) {
44
+ if (!this.text)
45
+ return [];
46
+ const pad = " ".repeat(this.indent);
47
+ const inner = Math.max(10, width - this.indent);
48
+ return this.text
49
+ .split("\n")
50
+ .flatMap((line) => wrapTextWithAnsi(line, inner).map((l) => pad + l));
51
+ }
52
+ }
53
+ /**
54
+ * A container whose lines never run past the width. Components wrap their own text; this is the
55
+ * backstop, so one layout mistake clips a line instead of crashing the screen.
56
+ */
57
+ export class Clamped extends Container {
58
+ render(width) {
59
+ return super
60
+ .render(width)
61
+ .map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width) : line));
62
+ }
63
+ }
64
+ /** One empty line. */
65
+ export const gap = () => ({ render: () => [""], invalidate() { } });
66
+ /** "› your message", wrapped under the marker. */
67
+ export class UserMessage {
68
+ text;
69
+ constructor(text) {
70
+ this.text = text;
71
+ }
72
+ invalidate() { }
73
+ render(width) {
74
+ const lines = this.text
75
+ .split("\n")
76
+ .flatMap((l) => wrapTextWithAnsi(l, Math.max(10, width - 2)));
77
+ return [
78
+ "",
79
+ ...lines.map((l, i) => `${i === 0 ? theme.accent("›") : " "} ${theme.user(l)}`),
80
+ "",
81
+ ];
82
+ }
83
+ }
84
+ /** Colors a unified diff: added green, removed red, hunk headers cyan, context dim. */
85
+ export function colorDiffLine(line) {
86
+ switch (diffLineKind(line)) {
87
+ case "added":
88
+ return theme.added(line);
89
+ case "removed":
90
+ return theme.removed(line);
91
+ case "hunk":
92
+ return theme.hunk(line);
93
+ default:
94
+ return theme.faint(line);
95
+ }
96
+ }
97
+ const looksLikeDiff = (text) => text.startsWith("@@ ");
98
+ /** Expanded text under a step: diffs colored, anything else dimmed. Capped so it can't flood. */
99
+ function detailLines(detail, width, max = 200) {
100
+ const diff = looksLikeDiff(detail);
101
+ const raw = detail.replace(/\s+$/, "").split("\n");
102
+ const shown = raw.slice(0, max);
103
+ const out = shown.flatMap((line) => wrapTextWithAnsi(diff ? colorDiffLine(line) : theme.faint(line), nestedWidth(width)).map((l) => NESTED + l));
104
+ if (raw.length > max)
105
+ out.push(theme.muted(`${NESTED}… ${raw.length - max} more lines`));
106
+ return out;
107
+ }
108
+ /** A tool step: "● Read src/app.ts (120 lines)", expandable with ctrl+o. */
109
+ export class ToolLine {
110
+ id;
111
+ title;
112
+ status = "running";
113
+ summary = null;
114
+ detail = null;
115
+ /** What it's doing right now, while running (helpers report their steps). */
116
+ progress = null;
117
+ expanded = false;
118
+ constructor(id, title) {
119
+ this.id = id;
120
+ this.title = title;
121
+ }
122
+ finish(status, summary, detail) {
123
+ this.status = status;
124
+ this.summary = summary;
125
+ this.detail = detail ?? null;
126
+ }
127
+ get expandable() {
128
+ return Boolean(this.detail?.trim());
129
+ }
130
+ invalidate() { }
131
+ render(width) {
132
+ const dot = this.status === "running"
133
+ ? theme.muted("●")
134
+ : this.status === "error"
135
+ ? theme.error("●")
136
+ : theme.success("●");
137
+ const text = this.summary ?? (this.progress ? `${this.title} · ${this.progress}` : `${this.title}…`);
138
+ const hint = this.expandable && !this.expanded ? theme.muted(" (ctrl+o)") : "";
139
+ const head = wrapTextWithAnsi(`${text}${hint}`, Math.max(10, width - 4)).map((l, i) => `${INDENT}${i === 0 ? dot : " "} ${this.status === "running" ? theme.muted(l) : l}`);
140
+ return this.expanded && this.detail ? [...head, ...detailLines(this.detail, width)] : head;
141
+ }
142
+ }
143
+ /** The model's reasoning: dimmed, showing its last lines while it thinks; collapsed after. */
144
+ export class Reasoning {
145
+ text = "";
146
+ done = false;
147
+ expanded = false;
148
+ started = Date.now();
149
+ seconds = 0;
150
+ append(text) {
151
+ this.text += text;
152
+ }
153
+ finish() {
154
+ if (this.done)
155
+ return;
156
+ this.done = true;
157
+ this.seconds = Math.max(1, Math.round((Date.now() - this.started) / 1000));
158
+ }
159
+ get expandable() {
160
+ return this.done && Boolean(this.text.trim());
161
+ }
162
+ invalidate() { }
163
+ render(width) {
164
+ const body = this.text.trim().split("\n");
165
+ if (!this.done) {
166
+ const tail = body
167
+ .filter((l) => l.trim())
168
+ .flatMap((l) => wrapTextWithAnsi(l, nestedWidth(width)))
169
+ .slice(-3)
170
+ .map((l) => NESTED + theme.faint(style.italic(l)));
171
+ return [`${INDENT}${theme.muted("✻")} ${theme.muted("Thinking…")}`, ...tail];
172
+ }
173
+ const head = `${INDENT}${theme.muted("✻")} ${theme.muted(`Thought for ${this.seconds}s`)}${this.expanded ? "" : theme.muted(" (ctrl+o)")}`;
174
+ if (!this.expanded)
175
+ return [head];
176
+ return [
177
+ head,
178
+ ...body.flatMap((l) => wrapTextWithAnsi(l, nestedWidth(width)).map((w) => NESTED + theme.faint(style.italic(w)))),
179
+ ];
180
+ }
181
+ }
182
+ /** Styled Markdown for the model's replies. */
183
+ export const markdownTheme = {
184
+ heading: (t) => style.bold(t),
185
+ link: (t) => theme.accent(t),
186
+ linkUrl: (t) => theme.muted(t),
187
+ code: (t) => theme.accent(t),
188
+ codeBlock: (t) => t,
189
+ codeBlockBorder: (t) => theme.muted(t),
190
+ quote: (t) => style.italic(t),
191
+ quoteBorder: (t) => theme.muted(t),
192
+ hr: (t) => theme.muted(t),
193
+ listBullet: (t) => theme.muted(t),
194
+ bold: (t) => style.bold(t),
195
+ italic: (t) => style.italic(t),
196
+ strikethrough: (t) => style.strike(t),
197
+ underline: (t) => style.underline(t),
198
+ };
199
+ export const selectListTheme = {
200
+ selectedPrefix: (t) => theme.accent(t),
201
+ selectedText: (t) => style.bold(t),
202
+ description: (t) => theme.muted(t),
203
+ scrollInfo: (t) => theme.muted(t),
204
+ noMatch: (t) => theme.muted(t),
205
+ };
206
+ /** A box drawn with a left rule: "╭ title", "│ line", "╰ footer". */
207
+ function boxed(title, body, footer, width) {
208
+ const inner = Math.max(10, width - 4);
209
+ const rule = (ch, text) => `${INDENT}${theme.border(ch)} ${truncateToWidth(text, inner)}`;
210
+ return [rule("╭", title), ...body.map((l) => rule("│", l)), rule("╰", footer)];
211
+ }
212
+ const PREVIEW_LINES = 24;
213
+ /**
214
+ * Asks before an edit or command: shows what will happen, then y / a / n. "n" asks what to do
215
+ * instead (empty just stops). Esc declines and stops.
216
+ */
217
+ export class ApprovalBox {
218
+ request;
219
+ resolve;
220
+ focused = false;
221
+ feedback = null;
222
+ showAll = false;
223
+ constructor(request, resolve) {
224
+ this.request = request;
225
+ this.resolve = resolve;
226
+ }
227
+ /** Commands show in full below, so the box is titled by what it is. */
228
+ get heading() {
229
+ return this.request.kind === "exec" && this.request.tool === "bash"
230
+ ? "Run a command"
231
+ : this.request.title;
232
+ }
233
+ /** ctrl+o: show the whole preview. */
234
+ toggleExpanded() {
235
+ this.showAll = !this.showAll;
236
+ }
237
+ invalidate() { }
238
+ handleInput(data) {
239
+ if (this.feedback) {
240
+ if (matchesKey(data, "escape")) {
241
+ this.feedback = null;
242
+ return;
243
+ }
244
+ this.feedback.handleInput(data);
245
+ return;
246
+ }
247
+ if (matchesKey(data, "escape"))
248
+ return this.resolve({ kind: "no" });
249
+ const key = data.toLowerCase();
250
+ if (key === "y")
251
+ this.resolve({ kind: "yes" });
252
+ else if (key === "a" && this.request.always)
253
+ this.resolve({ kind: "always" });
254
+ else if (key === "n") {
255
+ const input = new Input({
256
+ prompt: "",
257
+ placeholder: "Tell it what to do instead (Enter on empty just stops)",
258
+ });
259
+ input.focused = this.focused;
260
+ input.onSubmit = (value) => this.resolve({ kind: "no", feedback: value.trim() || undefined });
261
+ this.feedback = input;
262
+ }
263
+ }
264
+ render(width) {
265
+ const r = this.request;
266
+ const body = [];
267
+ if (r.reason)
268
+ body.push(theme.warning(r.reason));
269
+ if (r.preview) {
270
+ const lines = r.preview.replace(/\s+$/, "").split("\n");
271
+ const diff = looksLikeDiff(r.preview);
272
+ const limit = this.showAll ? lines.length : PREVIEW_LINES;
273
+ for (const line of lines.slice(0, limit))
274
+ body.push(diff ? colorDiffLine(line) : line);
275
+ if (lines.length > limit) {
276
+ body.push(theme.muted(`… ${lines.length - limit} more lines (ctrl+o to see all)`));
277
+ }
278
+ }
279
+ if (this.feedback) {
280
+ this.feedback.focused = this.focused;
281
+ const input = this.feedback.render(Math.max(10, width - 4))[0] ?? "";
282
+ return [
283
+ ...boxed(style.bold(this.heading), body, theme.accent("What should it do instead?"), width),
284
+ `${INDENT} ${input}`,
285
+ theme.muted(`${INDENT} Enter to send · empty to just stop · esc to go back`),
286
+ ];
287
+ }
288
+ const options = [
289
+ `${style.bold("y")} yes`,
290
+ ...(r.always ? [`${style.bold("a")} ${r.always}`] : []),
291
+ `${style.bold("n")} no, and tell it why`,
292
+ ].join(theme.muted(" · "));
293
+ const footer = `${theme.accent("Allow?")} ${options}`;
294
+ const lines = boxed(style.bold(this.heading), body, footer, width);
295
+ // On narrow terminals the options wrap rather than vanish.
296
+ if (visibleWidth(footer) > width - 4) {
297
+ lines.pop();
298
+ lines.push(`${INDENT}${theme.border("╰")} ${theme.accent("Allow?")}`);
299
+ for (const opt of [
300
+ `${style.bold("y")} yes`,
301
+ ...(r.always ? [`${style.bold("a")} ${r.always}`] : []),
302
+ `${style.bold("n")} no, and tell it why`,
303
+ ]) {
304
+ lines.push(...wrapTextWithAnsi(opt, nestedWidth(width)).map((l) => NESTED + l));
305
+ }
306
+ }
307
+ return lines;
308
+ }
309
+ }
310
+ /** A filterable list (model picker): type to filter, ↑↓ to move, Enter to pick, Esc to cancel. */
311
+ export class Picker {
312
+ title;
313
+ items;
314
+ maxVisible;
315
+ focused = false;
316
+ filter = new Input({ prompt: "› ", placeholder: "Type to search" });
317
+ list;
318
+ onSelect;
319
+ onCancel;
320
+ constructor(title, items, maxVisible = 10) {
321
+ this.title = title;
322
+ this.items = items;
323
+ this.maxVisible = maxVisible;
324
+ this.list = this.makeList(items);
325
+ }
326
+ makeList(items) {
327
+ const list = new SelectList(items, this.maxVisible, selectListTheme, {
328
+ minPrimaryColumnWidth: 20,
329
+ maxPrimaryColumnWidth: 48,
330
+ });
331
+ list.onSelect = (item) => this.onSelect?.(item.value);
332
+ list.onCancel = () => this.onCancel?.();
333
+ return list;
334
+ }
335
+ /** Puts the cursor on `value` (the current model). */
336
+ select(value) {
337
+ const index = this.items.findIndex((i) => i.value === value);
338
+ if (index >= 0)
339
+ this.list.setSelectedIndex(index);
340
+ }
341
+ invalidate() { }
342
+ handleInput(data) {
343
+ if (matchesKey(data, "up") ||
344
+ matchesKey(data, "down") ||
345
+ matchesKey(data, "enter") ||
346
+ matchesKey(data, "escape") ||
347
+ matchesKey(data, "pageUp") ||
348
+ matchesKey(data, "pageDown")) {
349
+ this.list.handleInput(data);
350
+ return;
351
+ }
352
+ const before = this.filter.getValue();
353
+ this.filter.handleInput(data);
354
+ const after = this.filter.getValue();
355
+ if (after !== before) {
356
+ const words = after.toLowerCase().split(/\s+/).filter(Boolean);
357
+ const items = this.items.filter((i) => {
358
+ const hay = `${i.value} ${i.label} ${i.description ?? ""}`.toLowerCase();
359
+ return words.every((w) => hay.includes(w));
360
+ });
361
+ this.list = this.makeList(items);
362
+ }
363
+ }
364
+ render(width) {
365
+ this.filter.focused = this.focused;
366
+ const inner = Math.max(10, width - INDENT.length);
367
+ return [
368
+ "",
369
+ theme.accent(style.bold(this.title)),
370
+ ...this.filter.render(inner),
371
+ ...this.list.render(inner),
372
+ theme.muted("↑↓ to move · Enter to pick · Esc to cancel"),
373
+ ].map((l) => (l ? INDENT + l : l));
374
+ }
375
+ }
@@ -0,0 +1,116 @@
1
+ /** Pure text for the TUI: what each state says. Kept apart from rendering so it's unit-tested. */
2
+ import { ApiError } from "../api.js";
3
+ import { StreamError } from "../agent/client.js";
4
+ import { formatUsd } from "../agent/cost.js";
5
+ import { MODE_LABELS } from "../agent/permissions.js";
6
+ /** 1234 → "1.2K", 200000 → "200K", 1000000 → "1M". */
7
+ export function formatTokens(n) {
8
+ if (n >= 1_000_000)
9
+ return `${+(n / 1_000_000).toFixed(n % 1_000_000 ? 1 : 0)}M`;
10
+ if (n >= 10_000)
11
+ return `${Math.round(n / 1000)}K`;
12
+ if (n >= 1000)
13
+ return `${+(n / 1000).toFixed(1)}K`;
14
+ return String(n);
15
+ }
16
+ /** "Ask before edits (shift+tab) · 12% context · ~$0.04 · $18.20 left" */
17
+ export function statusLine(s) {
18
+ const parts = [`${MODE_LABELS[s.mode]} (shift+tab)`];
19
+ if (s.contextTokens !== null) {
20
+ const pct = Math.min(100, Math.round((s.contextTokens / s.contextLength) * 100));
21
+ parts.push(`${pct === 0 && s.contextTokens > 0 ? "<1" : pct}% context`);
22
+ }
23
+ if (s.costMicros > 0n)
24
+ parts.push(`~${formatUsd(s.costMicros)}`);
25
+ if (s.balance !== null)
26
+ parts.push(`${s.balance} left`);
27
+ return parts.join(" · ");
28
+ }
29
+ /** "★ anthropic/claude-sonnet-4.5" / "200K · $3.30 / $16.50" for the model picker. */
30
+ export function modelChoice(m) {
31
+ const coding = m.categories.includes("programming");
32
+ const price = `$${m.inputPerM.toFixed(2)} / $${m.outputPerM.toFixed(2)} per 1M`;
33
+ return {
34
+ value: m.id,
35
+ label: `${coding ? "★" : " "} ${m.id}`,
36
+ description: `${formatTokens(m.contextLength)} · ${price}${coding ? " · good for code" : ""}`,
37
+ };
38
+ }
39
+ /** Coding models first, then by id. */
40
+ export function sortModels(models) {
41
+ const coding = (m) => (m.categories.includes("programming") ? 0 : 1);
42
+ return [...models].sort((a, b) => coding(a) - coding(b) || a.id.localeCompare(b.id));
43
+ }
44
+ /** What to tell the user when a request fails for good (after any retries). */
45
+ export function describeError(error, appUrl) {
46
+ const billing = `${appUrl.replace(/^https?:\/\//, "")}/dashboard/billing`;
47
+ if (error instanceof ApiError) {
48
+ if (error.status === 401) {
49
+ return {
50
+ message: "Your login was revoked or has expired.",
51
+ next: "login",
52
+ hint: "Press Enter to log in again.",
53
+ };
54
+ }
55
+ if (error.status === 402) {
56
+ return {
57
+ message: error.message,
58
+ next: "retry",
59
+ hint: `Add credits at ${billing}, then press Enter to retry.`,
60
+ };
61
+ }
62
+ if (error.status === 429) {
63
+ return {
64
+ message: "Reasonally is busy right now.",
65
+ next: "retry",
66
+ hint: "Press Enter to try again.",
67
+ };
68
+ }
69
+ if (error.status === 0) {
70
+ return {
71
+ message: "Can't reach Reasonally.",
72
+ next: "retry",
73
+ hint: "Check your connection, then press Enter to retry.",
74
+ };
75
+ }
76
+ if (error.status >= 500) {
77
+ return {
78
+ message: "Reasonally had a problem answering.",
79
+ next: "retry",
80
+ hint: "Press Enter to try again.",
81
+ };
82
+ }
83
+ return { message: error.message, next: null, hint: null };
84
+ }
85
+ if (error instanceof StreamError) {
86
+ return { message: error.message, next: "retry", hint: "Press Enter to try again." };
87
+ }
88
+ return { message: error.message, next: null, hint: null };
89
+ }
90
+ /** "Retrying in 4s… (esc to stop)", worded for the cause. */
91
+ export function retryMessage(error, delayMs) {
92
+ const seconds = Math.max(1, Math.round(delayMs / 1000));
93
+ if (error instanceof ApiError && error.status === 429)
94
+ return `Busy, retrying in ${seconds}s…`;
95
+ if (error instanceof ApiError && error.status === 0) {
96
+ return `Can't reach Reasonally. Retrying in ${seconds}s…`;
97
+ }
98
+ return `Something went wrong. Retrying in ${seconds}s…`;
99
+ }
100
+ export function diffLineKind(line) {
101
+ if (line.startsWith("@@"))
102
+ return "hunk";
103
+ if (line.startsWith("+"))
104
+ return "added";
105
+ if (line.startsWith("-"))
106
+ return "removed";
107
+ return "context";
108
+ }
109
+ /** "Summarized … (82% → 14%)", or token counts when the context is still small. */
110
+ export function compactionNote(before, after, contextLength) {
111
+ const pct = (n) => Math.round((n / contextLength) * 100);
112
+ const change = pct(before) >= 10
113
+ ? `${pct(before)}% → ${pct(after)}% of context`
114
+ : `${formatTokens(before)} → ${formatTokens(after)} tokens`;
115
+ return `Summarized earlier conversation to free up context (${change}).`;
116
+ }
@@ -0,0 +1,7 @@
1
+ /** Whether the agent's terminal UI can run on this Node: its UI library needs 22.19 or later. */
2
+ export function nodeSupported(version) {
3
+ const [major, minor] = version.replace(/^v/, "").split(".").map(Number);
4
+ return major > 22 || (major === 22 && minor >= 19);
5
+ }
6
+ export const NODE_TOO_OLD = (version) => `Reasonally's agent needs Node.js 22.19 or later (you have ${version.replace(/^v/, "")}). ` +
7
+ "Your other commands still work.";