reasonally 0.4.0 → 0.6.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/dist/tui/app.js CHANGED
@@ -1,18 +1,19 @@
1
1
  import { CombinedAutocompleteProvider, Editor, Loader, Markdown, matchesKey, TuiMainScreen, } from "@earendil-works/pi-tui";
2
2
  import { formatUsd } from "../agent/cost.js";
3
3
  import { Agent, } from "../agent/loop.js";
4
- import { emptyAllows, MODE_LABELS, MODES, } from "../agent/permissions.js";
4
+ import { DEFAULT_WEB_POLICY, emptyAllows, MODE_LABELS, MODES, } from "../agent/permissions.js";
5
+ import { commandLabel, expandCommand, listCommands, parseSlash, } from "../agent/command-files.js";
5
6
  import { MCP_EXAMPLE } from "../agent/mcp-config.js";
6
7
  import { count } from "../agent/tools/files.js";
7
- import { BUILTIN_TOOLS } from "../agent/tools/index.js";
8
+ import { BUILTIN_TOOLS, webTools } from "../agent/tools/index.js";
8
9
  import { tildePath } from "../agent/tools/paths.js";
9
10
  import { formatTodos } from "../agent/tools/todo.js";
10
11
  import { FileTracker } from "../agent/tools/types.js";
11
12
  import { commandEnv } from "../agent/tools/bash.js";
12
- import { listSessions, loadSession, sessionHolder, SessionWriter, stepRecord, timeAgo, } from "../agent/session.js";
13
+ import { changeRecord, listSessions, loadSession, sessionHolder, SessionWriter, stepRecord, timeAgo, } from "../agent/session.js";
13
14
  import { PLAN_OUTCOME_LABELS, PLAN_TOOL } from "../agent/tools/plan.js";
14
15
  import { changedLines, editInEditor } from "./external-editor.js";
15
- import { COMMANDS, helpText, parseCommand } from "./commands.js";
16
+ import { appCommand, closeMatches, COMMANDS, helpText, SOURCE_LABELS } from "./commands.js";
16
17
  import { ApprovalBox, Clamped, PlanApprovalBox, PlanBlock, gap, Header, INDENT, Lines, markdownTheme, Picker, Reasoning, selectListTheme, ToolLine, UserMessage, } from "./components.js";
17
18
  import { compactionNote, describeError, formatTokens, modelChoice, openElsewhere, retryMessage, sortModels, modeStatus, statusLine, } from "./format.js";
18
19
  import { style, theme } from "./theme.js";
@@ -35,6 +36,7 @@ export class App {
35
36
  /** Cost of earlier conversations in this session (`/new`). */
36
37
  spentBefore = 0n;
37
38
  busy = null;
39
+ /** Sent once the current step ends: messages, and commands as typed (`/review auth`). */
38
40
  queued = [];
39
41
  queuedNote = null;
40
42
  /** What Enter on an empty input does after an error. */
@@ -53,6 +55,12 @@ export class App {
53
55
  header = null;
54
56
  /** The kind of the last transcript entry, for spacing. */
55
57
  lastKind = null;
58
+ /** The `/` menu: the app's commands, then saved ones. Updated in place (the menu reads it). */
59
+ slashItems = [];
60
+ saved = [];
61
+ commandProblems = [];
62
+ commandsAt = 0;
63
+ commandsLoading = null;
56
64
  // The reply being streamed.
57
65
  replyText = "";
58
66
  reply = null;
@@ -73,11 +81,19 @@ export class App {
73
81
  mode: options.mode,
74
82
  allows: emptyAllows(),
75
83
  context: { cwd: options.cwd, home: options.home, configDir: options.configDir },
84
+ web: options.web ?? DEFAULT_WEB_POLICY,
76
85
  };
77
86
  this.tui = new TuiMainScreen(options.terminal);
78
87
  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));
88
+ this.slashItems.push(...this.menuItems());
89
+ this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider(this.slashItems, options.cwd, null));
80
90
  this.editor.onSubmit = (text) => this.submit(text);
91
+ // A command file added since: it's in the menu the next time "/" is typed.
92
+ this.editor.onChange = (text) => {
93
+ if (text === "/")
94
+ void this.refreshCommands(3000);
95
+ };
96
+ void this.refreshCommands();
81
97
  this.tui.addChild(this.transcript);
82
98
  this.tui.addChild(this.activity);
83
99
  this.tui.addChild(this.editor);
@@ -188,23 +204,22 @@ export class App {
188
204
  void this.relogin();
189
205
  return;
190
206
  }
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
207
  this.editor.addToHistory(text);
208
+ // A path ("/Users/me/app is slow") isn't a command: it goes as a message.
209
+ const slash = parseSlash(text);
210
+ if (slash)
211
+ void this.runSlash(slash);
212
+ else
213
+ this.sendMessage(text);
214
+ }
215
+ sendMessage(text) {
201
216
  if (!this.agent) {
202
217
  this.afterPick = text;
203
218
  this.openModelPicker();
204
219
  return;
205
220
  }
206
221
  if (this.busy) {
207
- this.queued.push(text);
222
+ this.queued.push({ text });
208
223
  this.showQueued();
209
224
  return;
210
225
  }
@@ -212,6 +227,113 @@ export class App {
212
227
  const agent = this.agent;
213
228
  void this.runTurn((signal) => agent.send(text, signal));
214
229
  }
230
+ // --- slash commands ---------------------------------------------------------------------------
231
+ commandRoots() {
232
+ const { cwd, home, configDir } = this.options;
233
+ return { cwd, home, configDir, env: process.env };
234
+ }
235
+ /** The menu's entries: the app's commands (with their arguments), then saved commands. */
236
+ menuItems() {
237
+ const own = COMMANDS.map((c) => ({
238
+ name: c.name,
239
+ description: c.description,
240
+ argumentHint: c.argumentHint,
241
+ ...(c.name === "model" && {
242
+ getArgumentCompletions: (prefix) => sortModels(this.options.models)
243
+ .filter((m) => m.id.toLowerCase().includes(prefix.toLowerCase()))
244
+ .slice(0, 20)
245
+ .map((m) => ({ value: m.id, label: m.id, description: modelChoice(m).description })),
246
+ }),
247
+ ...(c.name === "mode" && {
248
+ getArgumentCompletions: (prefix) => MODES.filter((m) => m.startsWith(prefix.toLowerCase())).map((m) => ({
249
+ value: m,
250
+ label: m,
251
+ description: MODE_LABELS[m],
252
+ })),
253
+ }),
254
+ }));
255
+ const saved = this.saved.map((c) => ({
256
+ name: c.name,
257
+ description: c.source === "bundled"
258
+ ? c.description
259
+ : [c.description, SOURCE_LABELS[c.source]].filter(Boolean).join(" · "),
260
+ ...(c.argumentHint && { argumentHint: c.argumentHint }),
261
+ }));
262
+ return [...own, ...saved];
263
+ }
264
+ /** Reads saved commands again, unless they were read within `maxAgeMs`. */
265
+ refreshCommands(maxAgeMs = 0) {
266
+ if (this.commandsLoading)
267
+ return this.commandsLoading;
268
+ if (maxAgeMs && Date.now() - this.commandsAt < maxAgeMs)
269
+ return Promise.resolve();
270
+ this.commandsLoading = listCommands(this.commandRoots())
271
+ .then(({ commands, problems }) => {
272
+ this.saved = commands;
273
+ this.commandProblems = problems;
274
+ this.commandsAt = Date.now();
275
+ this.slashItems.splice(0, this.slashItems.length, ...this.menuItems());
276
+ })
277
+ .catch(() => { })
278
+ .finally(() => {
279
+ this.commandsLoading = null;
280
+ });
281
+ return this.commandsLoading;
282
+ }
283
+ async runSlash(ref) {
284
+ const own = appCommand(ref.name);
285
+ if (own)
286
+ return this.runCommand(own.name, ref.args);
287
+ if (!ref.name) {
288
+ return this.notice(theme.muted("Type a command's name after the /. /help lists them."));
289
+ }
290
+ const find = () => this.saved.find((c) => c.name === ref.name);
291
+ // Not known yet: the list may still be loading, or the file was just added.
292
+ if (!find())
293
+ await this.refreshCommands();
294
+ if (!find()) {
295
+ const near = closeMatches(ref.name, [
296
+ ...COMMANDS.map((c) => c.name),
297
+ ...this.saved.map((c) => c.name),
298
+ ]);
299
+ const hint = near.length ? ` Did you mean ${near.map((n) => `/${n}`).join(", ")}?` : "";
300
+ return this.notice(theme.warning(`/${ref.name} isn't a command.${hint} Type /help for the list.`));
301
+ }
302
+ this.sendCommand(ref);
303
+ }
304
+ /** A saved command (or /review, /init) as a message: queued while a step runs, like any. */
305
+ sendCommand(ref) {
306
+ if (!this.agent) {
307
+ this.afterPick = commandLabel(ref);
308
+ this.openModelPicker();
309
+ return;
310
+ }
311
+ if (this.busy) {
312
+ this.queued.push({ text: commandLabel(ref), command: ref });
313
+ this.showQueued();
314
+ return;
315
+ }
316
+ this.runPrompt(ref);
317
+ }
318
+ /** Runs a saved command: its file is read now, and what was typed is shown (`/review auth`). */
319
+ runPrompt(ref) {
320
+ const agent = this.agent;
321
+ const roots = this.commandRoots();
322
+ const show = () => this.addUser(commandLabel(ref));
323
+ const fail = (message) => {
324
+ this.notice(theme.warning(message));
325
+ // What was typed comes back, to fix or run again.
326
+ if (!this.editor.getText())
327
+ this.editor.setText(commandLabel(ref));
328
+ };
329
+ void this.runTurn(async function* (signal) {
330
+ const result = await expandCommand(ref, roots);
331
+ if (!result.ok)
332
+ return fail(result.message);
333
+ show();
334
+ yield* agent.send(result.prompt, signal, undefined, ref);
335
+ });
336
+ }
215
337
  // --- turns ------------------------------------------------------------------------------------
216
338
  async runTurn(start) {
217
339
  const controller = new AbortController();
@@ -248,10 +370,23 @@ export class App {
248
370
  }
249
371
  if (!this.queued.length || !this.agent || this.exited)
250
372
  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));
373
+ // A command goes on its own; messages before the next one go together.
374
+ const first = this.queued[0];
375
+ if (first.command) {
376
+ this.queued.shift();
377
+ this.runPrompt(first.command);
378
+ }
379
+ else {
380
+ const batch = [];
381
+ while (this.queued.length && !this.queued[0].command)
382
+ batch.push(this.queued.shift().text);
383
+ const text = batch.join("\n\n");
384
+ this.addUser(text);
385
+ const agent = this.agent;
386
+ void this.runTurn((signal) => agent.send(text, signal));
387
+ }
388
+ if (this.queued.length)
389
+ this.showQueued();
255
390
  }
256
391
  showQueued() {
257
392
  const text = theme.muted(`Queued (${this.queued.length}). Sends when this step finishes, or now with esc.`);
@@ -529,8 +664,12 @@ export class App {
529
664
  this.cycleMode();
530
665
  return;
531
666
  }
667
+ case "plan":
668
+ this.setMode("plan");
669
+ if (arg)
670
+ this.sendMessage(arg);
671
+ return;
532
672
  case "new":
533
- case "clear":
534
673
  if (this.busy)
535
674
  return this.notice(theme.muted("Stop the current task first (esc)."));
536
675
  void this.writer?.release();
@@ -543,7 +682,7 @@ export class App {
543
682
  this.notice(theme.muted("── New conversation ──"));
544
683
  this.updateStatus();
545
684
  return;
546
- case "cost": {
685
+ case "usage": {
547
686
  const context = this.agent?.contextTokens;
548
687
  this.notice([
549
688
  `This session: ~${formatUsd(this.sessionCost())} (an estimate; your usage page has exact charges)`,
@@ -562,7 +701,7 @@ export class App {
562
701
  const agent = this.agent;
563
702
  if (!agent)
564
703
  return;
565
- void this.runTurn((signal) => agent.compactNow(signal));
704
+ void this.runTurn((signal) => agent.compactNow(signal, arg || undefined));
566
705
  return;
567
706
  }
568
707
  case "resume":
@@ -579,10 +718,10 @@ export class App {
579
718
  this.notice(this.mcpReport());
580
719
  return;
581
720
  case "help":
582
- this.notice(helpText());
721
+ this.notice(helpText(this.saved, this.commandProblems, this.options.home));
722
+ void this.refreshCommands(3000);
583
723
  return;
584
724
  case "exit":
585
- case "quit":
586
725
  this.exit(0);
587
726
  return;
588
727
  default:
@@ -692,7 +831,11 @@ export class App {
692
831
  // --- helpers ----------------------------------------------------------------------------------
693
832
  // --- MCP ------------------------------------------------------------------------------------
694
833
  tools() {
695
- return [...BUILTIN_TOOLS, ...(this.options.mcp?.tools ?? [])];
834
+ return [
835
+ ...BUILTIN_TOOLS,
836
+ ...webTools(this.options.web ?? DEFAULT_WEB_POLICY),
837
+ ...(this.options.mcp?.tools ?? []),
838
+ ];
696
839
  }
697
840
  /** Picks up MCP tools as servers connect, and says once how the start-up went. */
698
841
  watchMcp() {
@@ -747,20 +890,7 @@ export class App {
747
890
  if (!this.model)
748
891
  return;
749
892
  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
- }
893
+ this.writer.append(changeRecord(change));
764
894
  }
765
895
  /** Continues a saved conversation: reprints it as it looked, then carries on in the same file. */
766
896
  resumeSession(loaded) {
@@ -782,8 +912,9 @@ export class App {
782
912
  // The callers checked that nothing else has it open.
783
913
  void this.writer.claim("terminal");
784
914
  for (const entry of loaded.display) {
785
- if (entry.kind === "user")
786
- this.addUser(entry.text);
915
+ if (entry.kind === "user") {
916
+ this.addUser(entry.command ? commandLabel(entry.command) : entry.text);
917
+ }
787
918
  else if (entry.kind === "text") {
788
919
  this.add(new Markdown(entry.text, INDENT.length, 0, markdownTheme), "text");
789
920
  }
package/dist/tui/args.js CHANGED
@@ -6,6 +6,7 @@ export function parseAgentArgs(argv) {
6
6
  plan: false,
7
7
  continue: false,
8
8
  resume: false,
9
+ noWeb: false,
9
10
  };
10
11
  for (let i = 0; i < argv.length; i++) {
11
12
  const arg = argv[i];
@@ -31,6 +32,9 @@ export function parseAgentArgs(argv) {
31
32
  else if (arg === "--resume" || arg === "-r") {
32
33
  args.resume = true;
33
34
  }
35
+ else if (arg === "--no-web") {
36
+ args.noWeb = true;
37
+ }
34
38
  else {
35
39
  return { ok: false, error: `Unknown option "${arg}". See \`reasonally --help\`.` };
36
40
  }
@@ -1,24 +1,65 @@
1
1
  export const COMMANDS = [
2
- { name: "model", description: "Switch model" },
2
+ { name: "model", description: "Switch model", argumentHint: "[name]" },
3
3
  {
4
4
  name: "mode",
5
5
  description: "Switch between asking, auto-accepting edits, planning first, and not asking",
6
+ argumentHint: "[ask|auto|plan|full]",
6
7
  },
7
- { name: "new", description: "Start a new conversation" },
8
+ {
9
+ name: "plan",
10
+ description: "Plan first; nothing changes until you approve",
11
+ argumentHint: "[task]",
12
+ },
13
+ { name: "new", description: "Start a new conversation", aliases: ["clear"] },
8
14
  { name: "resume", description: "Continue an earlier conversation in this folder" },
9
- { name: "compact", description: "Summarize the conversation so far to free up context" },
10
- { name: "cost", description: "Show this session's cost and your balance" },
15
+ {
16
+ name: "compact",
17
+ description: "Summarize the conversation so far to free up context",
18
+ argumentHint: "[focus]",
19
+ },
20
+ {
21
+ name: "usage",
22
+ description: "Show this session's cost, the context used and your balance",
23
+ aliases: ["cost", "context"],
24
+ },
11
25
  { name: "mcp", description: "Show MCP servers and their tools" },
12
26
  { name: "login", description: "Log in again (e.g. after a key was revoked)" },
13
27
  { name: "help", description: "Show commands and keys" },
14
- { name: "exit", description: "Quit" },
28
+ { name: "exit", description: "Quit", aliases: ["quit"] },
15
29
  ];
16
- /** "/model foo" → { name: "model", arg: "foo" }; null when it isn't a command. */
17
- export function parseCommand(text) {
18
- const match = /^\/([a-z-]+)(?:\s+([\s\S]*))?$/i.exec(text.trim());
19
- if (!match)
20
- return null;
21
- return { name: match[1].toLowerCase(), arg: (match[2] ?? "").trim() };
30
+ /** The command a name or alias runs, or null when it isn't one of the app's own. */
31
+ export function appCommand(name) {
32
+ return COMMANDS.find((c) => c.name === name || c.aliases?.includes(name)) ?? null;
33
+ }
34
+ /** Where a saved command came from, as the help and the menu label it. */
35
+ export const SOURCE_LABELS = {
36
+ bundled: "Reasonally",
37
+ project: "Project",
38
+ personal: "Personal",
39
+ claude: "Claude Code",
40
+ codex: "Codex",
41
+ };
42
+ /** Saved commands named like what was typed, for "did you mean". */
43
+ export function closeMatches(name, names) {
44
+ return names
45
+ .map((n) => ({ n, d: distance(name, n) }))
46
+ .filter(({ n, d }) => d <= 2 || (name.length > 1 && n.startsWith(name)))
47
+ .sort((a, b) => a.d - b.d)
48
+ .slice(0, 3)
49
+ .map(({ n }) => n);
50
+ }
51
+ function distance(a, b) {
52
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
53
+ for (let i = 1; i <= a.length; i++) {
54
+ let prev = row[0];
55
+ row[0] = i;
56
+ for (let j = 1; j <= b.length; j++) {
57
+ const next = row[j];
58
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
59
+ prev = next;
60
+ }
61
+ }
62
+ return row[b.length];
22
63
  }
23
64
  export const KEYS = [
24
65
  ["Enter", "send · Shift+Enter or Ctrl+J for a new line"],
@@ -28,15 +69,30 @@ export const KEYS = [
28
69
  ["Ctrl+G", "edit a waiting plan in your editor"],
29
70
  ["Ctrl+C", "clear the input · twice to quit"],
30
71
  ["@", "mention a file"],
72
+ ["/", "a command, at the start of a message"],
31
73
  ["↑ ↓", "earlier messages"],
32
74
  ];
33
- export function helpText() {
34
- const width = Math.max(...COMMANDS.map((c) => c.name.length)) + 2;
75
+ const usage = (c) => `/${c.name}${c.argumentHint ? ` ${c.argumentHint}` : ""}`;
76
+ export function helpText(saved = [], problems = [], home = "") {
77
+ const prompts = saved.filter((c) => c.source === "bundled");
78
+ const yours = saved.filter((c) => c.source !== "bundled");
79
+ const rows = [...COMMANDS.map((c) => usage(c)), ...saved.map(usage)];
80
+ const width = Math.max(...rows.map((r) => r.length)) + 2;
81
+ const short = (path) => home && path.startsWith(home) ? `~${path.slice(home.length)}` : path;
35
82
  return [
36
83
  "Commands",
37
- ...COMMANDS.map((c) => ` /${c.name.padEnd(width)}${c.description}`),
84
+ ...COMMANDS.map((c) => ` ${usage(c).padEnd(width)}${c.description}`),
85
+ ...prompts.map((c) => ` ${usage(c).padEnd(width)}${c.description}`),
86
+ ...(yours.length
87
+ ? [
88
+ "",
89
+ "Your commands",
90
+ ...yours.map((c) => ` ${usage(c).padEnd(width)}${c.description ? `${c.description} · ` : ""}${SOURCE_LABELS[c.source]}`),
91
+ ]
92
+ : ["", "Save a prompt as .reasonally/commands/<name>.md to run it as /<name>."]),
93
+ ...problems.map((p) => ` Skipped ${short(p.path)}: ${p.reason}.`),
38
94
  "",
39
95
  "Keys",
40
- ...KEYS.map(([key, what]) => ` ${key.padEnd(width + 1)}${what}`),
96
+ ...KEYS.map(([key, what]) => ` ${key.padEnd(width)}${what}`),
41
97
  ].join("\n");
42
98
  }
package/dist/tui/start.js CHANGED
@@ -6,6 +6,7 @@ import { agentModels, findModel } from "../catalog.js";
6
6
  import { loginAndSave } from "../cli.js";
7
7
  import { configDir, readCredentials, readLastModel, resolveSession, writeLastModel, } from "../config.js";
8
8
  import { mcpConfigPath, readMcpConfig } from "../agent/mcp-config.js";
9
+ import { DEFAULT_WEB_POLICY, WEB_OFF } from "../agent/permissions.js";
9
10
  import { gitBranch, loadInstructions, systemPrompt } from "../agent/prompt.js";
10
11
  import { listSessions, loadSession, sessionHolder, sessionsDir, } from "../agent/session.js";
11
12
  import { shellFor } from "../agent/tools/bash.js";
@@ -113,6 +114,7 @@ export async function startTui(args, log) {
113
114
  pickSession: args.resume,
114
115
  startNotice,
115
116
  mode: args.plan ? "plan" : args.yes ? "full" : "ask",
117
+ web: args.noWeb ? WEB_OFF : DEFAULT_WEB_POLICY,
116
118
  systemPrompt: promptFor,
117
119
  fetchBalance: balanceOf,
118
120
  login: async (report) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reasonally",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
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": {
@@ -15,8 +15,11 @@
15
15
  "dependencies": {
16
16
  "@earendil-works/pi-tui": "1.5.0",
17
17
  "@modelcontextprotocol/sdk": "1.32.2",
18
+ "@mozilla/readability": "0.6.0",
18
19
  "diff": "9.0.0",
19
- "playwright-core": "1.64.1"
20
+ "linkedom": "0.18.15",
21
+ "playwright-core": "1.64.1",
22
+ "turndown": "7.2.5"
20
23
  },
21
24
  "scripts": {
22
25
  "build": "tsc -p tsconfig.build.json",