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.
@@ -0,0 +1,124 @@
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
+ /** The mode as the status line names it; Plan mode gets its pause sign. */
17
+ export const modeStatus = (mode) => `${mode === "plan" ? "⏸ " : ""}${MODE_LABELS[mode]} (shift+tab)`;
18
+ /** "Ask before edits (shift+tab) · 12% context · ~$0.04 · $18.20 left" */
19
+ export function statusLine(s) {
20
+ const parts = [modeStatus(s.mode)];
21
+ if (s.contextTokens !== null) {
22
+ const pct = Math.min(100, Math.round((s.contextTokens / s.contextLength) * 100));
23
+ parts.push(`${pct === 0 && s.contextTokens > 0 ? "<1" : pct}% context`);
24
+ }
25
+ if (s.costMicros > 0n)
26
+ parts.push(`~${formatUsd(s.costMicros)}`);
27
+ if (s.balance !== null)
28
+ parts.push(`${s.balance} left`);
29
+ return parts.join(" · ");
30
+ }
31
+ /** "★ anthropic/claude-sonnet-4.5" / "200K · $3.30 / $16.50" for the model picker. */
32
+ export function modelChoice(m) {
33
+ const coding = m.categories.includes("programming");
34
+ const price = `$${m.inputPerM.toFixed(2)} / $${m.outputPerM.toFixed(2)} per 1M`;
35
+ return {
36
+ value: m.id,
37
+ label: `${coding ? "★" : " "} ${m.id}`,
38
+ description: `${formatTokens(m.contextLength)} · ${price}${coding ? " · good for code" : ""}`,
39
+ };
40
+ }
41
+ /** Coding models first, then by id. */
42
+ export function sortModels(models) {
43
+ const coding = (m) => (m.categories.includes("programming") ? 0 : 1);
44
+ return [...models].sort((a, b) => coding(a) - coding(b) || a.id.localeCompare(b.id));
45
+ }
46
+ /** What to tell the user when a request fails for good (after any retries). */
47
+ export function describeError(error, appUrl) {
48
+ const billing = `${appUrl.replace(/^https?:\/\//, "")}/dashboard/billing`;
49
+ if (error instanceof ApiError) {
50
+ if (error.status === 401) {
51
+ return {
52
+ message: "Your login was revoked or has expired.",
53
+ next: "login",
54
+ hint: "Press Enter to log in again.",
55
+ };
56
+ }
57
+ if (error.status === 402) {
58
+ return {
59
+ message: error.message,
60
+ next: "retry",
61
+ hint: `Add credits at ${billing}, then press Enter to retry.`,
62
+ };
63
+ }
64
+ if (error.status === 429) {
65
+ return {
66
+ message: "Reasonally is busy right now.",
67
+ next: "retry",
68
+ hint: "Press Enter to try again.",
69
+ };
70
+ }
71
+ if (error.status === 0) {
72
+ return {
73
+ message: "Can't reach Reasonally.",
74
+ next: "retry",
75
+ hint: "Check your connection, then press Enter to retry.",
76
+ };
77
+ }
78
+ if (error.status >= 500) {
79
+ return {
80
+ message: "Reasonally had a problem answering.",
81
+ next: "retry",
82
+ hint: "Press Enter to try again.",
83
+ };
84
+ }
85
+ return { message: error.message, next: null, hint: null };
86
+ }
87
+ if (error instanceof StreamError) {
88
+ return { message: error.message, next: "retry", hint: "Press Enter to try again." };
89
+ }
90
+ return { message: error.message, next: null, hint: null };
91
+ }
92
+ /** "Retrying in 4s… (esc to stop)", worded for the cause. */
93
+ export function retryMessage(error, delayMs) {
94
+ const seconds = Math.max(1, Math.round(delayMs / 1000));
95
+ if (error instanceof ApiError && error.status === 429)
96
+ return `Busy, retrying in ${seconds}s…`;
97
+ if (error instanceof ApiError && error.status === 0) {
98
+ return `Can't reach Reasonally. Retrying in ${seconds}s…`;
99
+ }
100
+ return `Something went wrong. Retrying in ${seconds}s…`;
101
+ }
102
+ export function diffLineKind(line) {
103
+ if (line.startsWith("@@"))
104
+ return "hunk";
105
+ if (line.startsWith("+"))
106
+ return "added";
107
+ if (line.startsWith("-"))
108
+ return "removed";
109
+ return "context";
110
+ }
111
+ /** "Summarized … (82% → 14%)", or token counts when the context is still small. */
112
+ export function compactionNote(before, after, contextLength) {
113
+ const pct = (n) => Math.round((n / contextLength) * 100);
114
+ const change = pct(before) >= 10
115
+ ? `${pct(before)}% → ${pct(after)}% of context`
116
+ : `${formatTokens(before)} → ${formatTokens(after)} tokens`;
117
+ return `Summarized earlier conversation to free up context (${change}).`;
118
+ }
119
+ /** Where a saved conversation is open right now, when it can't be continued here. */
120
+ export function openElsewhere(holder) {
121
+ return holder.surface === "desktop"
122
+ ? "That conversation is open in the Reasonally app."
123
+ : "That conversation is open in another terminal.";
124
+ }
@@ -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.";
@@ -0,0 +1,139 @@
1
+ import { realpath } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { ProcessTerminal } from "@earendil-works/pi-tui";
4
+ import { fetchAccount, fetchModels } from "../api.js";
5
+ import { agentModels, findModel } from "../catalog.js";
6
+ import { loginAndSave } from "../cli.js";
7
+ import { configDir, readCredentials, readLastModel, resolveSession, writeLastModel, } from "../config.js";
8
+ import { mcpConfigPath, readMcpConfig } from "../agent/mcp-config.js";
9
+ import { gitBranch, loadInstructions, systemPrompt } from "../agent/prompt.js";
10
+ import { listSessions, loadSession, sessionHolder, sessionsDir, } from "../agent/session.js";
11
+ import { shellFor } from "../agent/tools/bash.js";
12
+ import { App } from "./app.js";
13
+ import { openElsewhere } from "./format.js";
14
+ /** The key the agent's last model is remembered under in state.json (not a harness id). */
15
+ export const MODEL_MEMORY_KEY = "tui";
16
+ async function currentSession() {
17
+ return resolveSession(process.env, await readCredentials());
18
+ }
19
+ const balanceOf = (session) => fetchAccount(session.appUrl, session.apiKey).then((account) => account.balance, () => null);
20
+ /** Logs in if needed, loads the catalog, then runs the agent's TUI until the user quits. */
21
+ export async function startTui(args, log) {
22
+ let session = await currentSession();
23
+ if (!session) {
24
+ log("Log in to start.");
25
+ await loginAndSave(log);
26
+ session = await currentSession();
27
+ if (!session)
28
+ throw new Error("The login didn't complete. Run `reasonally login`.");
29
+ log("");
30
+ }
31
+ const [catalog, balance] = await Promise.all([
32
+ fetchModels(session.apiBaseUrl, session.apiKey),
33
+ balanceOf(session),
34
+ ]);
35
+ const models = agentModels(catalog);
36
+ let model = null;
37
+ if (args.model) {
38
+ const match = findModel(catalog, args.model);
39
+ if (!match.ok) {
40
+ log(`Unknown model "${args.model}".`);
41
+ if (match.suggestions.length)
42
+ log(`Did you mean:\n ${match.suggestions.join("\n ")}`);
43
+ log("See all models with `reasonally models`, or pick one in the agent with /model.");
44
+ return 1;
45
+ }
46
+ if (!match.model.tools) {
47
+ log(`${match.model.id} can't use tools, so it can't work as an agent. Pick another one.`);
48
+ return 1;
49
+ }
50
+ model = match.model;
51
+ await writeLastModel(MODEL_MEMORY_KEY, model.id).catch(() => { });
52
+ }
53
+ else {
54
+ const last = await readLastModel(MODEL_MEMORY_KEY);
55
+ model = models.find((m) => m.id === last) ?? null;
56
+ }
57
+ const cwd = await realpath(process.cwd());
58
+ const home = await realpath(homedir()).catch(() => homedir());
59
+ const config = configDir();
60
+ const [instructions, branch] = await Promise.all([
61
+ loadInstructions(cwd, home, config),
62
+ gitBranch(cwd),
63
+ ]);
64
+ // MCP servers come only from the user's own config; the SDK loads only if there are any.
65
+ const mcpPath = mcpConfigPath(config);
66
+ const { servers, errors: mcpErrors } = await readMcpConfig(mcpPath);
67
+ const mcp = Object.keys(servers).length
68
+ ? new (await import("../agent/mcp.js")).McpManager(servers, { cwd })
69
+ : null;
70
+ const sessions = sessionsDir(config, cwd);
71
+ let resume = null;
72
+ let startNotice;
73
+ if (args.continue) {
74
+ const [latest] = await listSessions(sessions);
75
+ const holder = latest ? await sessionHolder(latest.path) : null;
76
+ resume = latest && !holder ? await loadSession(latest.path) : null;
77
+ if (holder)
78
+ startNotice = `${openElsewhere(holder)} Starting a new one here.`;
79
+ else if (!resume)
80
+ startNotice = "No saved conversation in this folder yet; starting a new one.";
81
+ // Continue with the conversation's own model unless one was asked for.
82
+ else if (!args.model)
83
+ model = models.find((m) => m.id === resume.model) ?? model;
84
+ }
85
+ const shell = shellFor(process.env).name;
86
+ const promptFor = (m) => systemPrompt({ cwd, home, platform: process.platform, shell, date: new Date(), model: m.id, branch }, instructions);
87
+ return await new Promise((resolve) => {
88
+ let app = null;
89
+ const quit = (code) => app?.exit(code);
90
+ const onSignal = () => quit(130);
91
+ const onCrash = (error) => {
92
+ quit(1);
93
+ console.error(`Reasonally's agent crashed: ${error?.stack ?? error}`);
94
+ };
95
+ process.on("SIGTERM", onSignal);
96
+ process.on("SIGHUP", onSignal);
97
+ process.on("uncaughtException", onCrash);
98
+ process.on("unhandledRejection", onCrash);
99
+ app = new App({
100
+ terminal: new ProcessTerminal(),
101
+ session: session,
102
+ models,
103
+ model,
104
+ balance,
105
+ cwd,
106
+ home,
107
+ configDir: config,
108
+ sessionsDir: sessions,
109
+ mcp,
110
+ mcpErrors,
111
+ mcpConfigPath: mcpPath,
112
+ resume,
113
+ pickSession: args.resume,
114
+ startNotice,
115
+ mode: args.plan ? "plan" : args.yes ? "full" : "ask",
116
+ systemPrompt: promptFor,
117
+ fetchBalance: balanceOf,
118
+ login: async (report) => {
119
+ await loginAndSave(report);
120
+ const next = await currentSession();
121
+ if (!next)
122
+ throw new Error("The login didn't complete.");
123
+ return next;
124
+ },
125
+ rememberModel: (id) => writeLastModel(MODEL_MEMORY_KEY, id),
126
+ onExit: (code, summary) => {
127
+ if (summary)
128
+ process.stdout.write(`${summary}\n`);
129
+ process.off("SIGTERM", onSignal);
130
+ process.off("SIGHUP", onSignal);
131
+ process.off("uncaughtException", onCrash);
132
+ process.off("unhandledRejection", onCrash);
133
+ resolve(code);
134
+ },
135
+ });
136
+ app.start();
137
+ void mcp?.start();
138
+ });
139
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Terminal styles. Only the 16 standard colors, so text follows the user's own palette on light
3
+ * and dark backgrounds; `NO_COLOR` turns colors off (bold/dim stay, as the convention allows).
4
+ */
5
+ const noColor = () => Boolean(process.env.NO_COLOR);
6
+ const sgr = (open, close, isColor) => (text) => isColor && noColor() ? text : `\x1b[${open}m${text}\x1b[${close}m`;
7
+ export const style = {
8
+ bold: sgr(1, 22, false),
9
+ dim: sgr(2, 22, false),
10
+ italic: sgr(3, 23, false),
11
+ underline: sgr(4, 24, false),
12
+ inverse: sgr(7, 27, false),
13
+ strike: sgr(9, 29, false),
14
+ red: sgr(31, 39, true),
15
+ green: sgr(32, 39, true),
16
+ yellow: sgr(33, 39, true),
17
+ blue: sgr(34, 39, true),
18
+ magenta: sgr(35, 39, true),
19
+ cyan: sgr(36, 39, true),
20
+ gray: sgr(90, 39, true),
21
+ };
22
+ /** Roles, so the look is decided in one place. */
23
+ export const theme = {
24
+ brand: (t) => style.bold(style.cyan(t)),
25
+ accent: style.cyan,
26
+ muted: style.gray,
27
+ faint: style.dim,
28
+ success: style.green,
29
+ warning: style.yellow,
30
+ error: style.red,
31
+ added: style.green,
32
+ removed: style.red,
33
+ hunk: style.cyan,
34
+ user: style.bold,
35
+ border: style.gray,
36
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "reasonally",
3
- "version": "0.2.0",
4
- "description": "Run the coding agents you already use on Reasonally models.",
3
+ "version": "0.4.0",
4
+ "description": "Reasonally's coding agent in your terminal, plus the coding agents you already use, on Reasonally models.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "reasonally": "dist/index.js"
@@ -13,6 +13,9 @@
13
13
  "node": ">=20"
14
14
  },
15
15
  "dependencies": {
16
+ "@earendil-works/pi-tui": "1.5.0",
17
+ "@modelcontextprotocol/sdk": "1.32.2",
18
+ "diff": "9.0.0",
16
19
  "playwright-core": "1.64.1"
17
20
  },
18
21
  "scripts": {
@@ -21,8 +24,10 @@
21
24
  },
22
25
  "keywords": [
23
26
  "llm",
24
- "cli",
25
27
  "coding-agent",
28
+ "tui",
29
+ "mcp",
30
+ "cli",
26
31
  "opencode",
27
32
  "crush",
28
33
  "cline",