reasonally 0.3.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.
@@ -1,4 +1,4 @@
1
- import { Container, Input, matchesKey, SelectList, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
1
+ import { Container, Input, Markdown, matchesKey, SelectList, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
2
2
  import { diffLineKind } from "./format.js";
3
3
  import { style, theme } from "./theme.js";
4
4
  /** Everything the agent says or does is indented this much; the user's "›" sits in the margin. */
@@ -307,6 +307,110 @@ export class ApprovalBox {
307
307
  return lines;
308
308
  }
309
309
  }
310
+ /** A plan, as Markdown under "⏸ Plan": streamed while it's written, then left in the scrollback. */
311
+ export class PlanBlock {
312
+ edited;
313
+ markdown;
314
+ constructor(text, edited = false) {
315
+ this.edited = edited;
316
+ this.markdown = new Markdown(text, INDENT.length, 0, markdownTheme);
317
+ }
318
+ setText(text) {
319
+ this.markdown.setText(text);
320
+ }
321
+ invalidate() {
322
+ this.markdown.invalidate();
323
+ }
324
+ render(width) {
325
+ const head = theme.accent(style.bold(this.edited ? "⏸ Plan (edited)" : "⏸ Plan"));
326
+ return ["", `${INDENT}${head}`, ...this.markdown.render(width)];
327
+ }
328
+ }
329
+ /** Keys pressed this soon after the plan box appears don't count (they were meant for the input). */
330
+ export const PLAN_ARM_MS = 350;
331
+ /**
332
+ * "Ready to build?" under a presented plan: y builds asking before edits, a auto-accepts edits,
333
+ * n says what to change (empty just stops), ctrl+g edits the plan in your editor, Esc stops.
334
+ */
335
+ export class PlanApprovalBox {
336
+ resolve;
337
+ onEdit;
338
+ now;
339
+ focused = false;
340
+ /** The user edited the plan: the answer carries their version. */
341
+ edited = false;
342
+ feedback = null;
343
+ armedAt;
344
+ constructor(resolve, onEdit, armMs = PLAN_ARM_MS, now = Date.now) {
345
+ this.resolve = resolve;
346
+ this.onEdit = onEdit;
347
+ this.now = now;
348
+ this.armedAt = now() + armMs;
349
+ }
350
+ invalidate() { }
351
+ handleInput(data) {
352
+ if (this.now() < this.armedAt)
353
+ return;
354
+ if (this.feedback) {
355
+ if (matchesKey(data, "escape")) {
356
+ this.feedback = null;
357
+ return;
358
+ }
359
+ this.feedback.handleInput(data);
360
+ return;
361
+ }
362
+ if (matchesKey(data, "escape"))
363
+ return this.resolve({ kind: "no" });
364
+ if (matchesKey(data, "ctrl+g"))
365
+ return this.onEdit();
366
+ const key = data.toLowerCase();
367
+ if (key === "y")
368
+ this.resolve({ kind: "yes" });
369
+ else if (key === "a")
370
+ this.resolve({ kind: "always" });
371
+ else if (key === "n") {
372
+ const input = new Input({
373
+ prompt: "",
374
+ placeholder: "Say what to change (Enter on empty just stops)",
375
+ });
376
+ input.focused = this.focused;
377
+ input.onSubmit = (value) => this.resolve({ kind: "no", feedback: value.trim() || undefined });
378
+ this.feedback = input;
379
+ }
380
+ }
381
+ render(width) {
382
+ const heading = `${style.bold("Ready to build?")}${this.edited ? ` ${theme.warning("edited")}` : ""}`;
383
+ const body = [
384
+ theme.muted(this.edited ? "It follows your edited version." : "Nothing has changed yet."),
385
+ ];
386
+ if (this.feedback) {
387
+ this.feedback.focused = this.focused;
388
+ const input = this.feedback.render(Math.max(10, width - 4))[0] ?? "";
389
+ return [
390
+ ...boxed(heading, body, theme.accent("What should change in the plan?"), width),
391
+ `${INDENT} ${input}`,
392
+ theme.muted(`${INDENT} Enter to send · empty to just stop · esc to go back`),
393
+ ];
394
+ }
395
+ const options = [
396
+ `${style.bold("y")} yes, ask before edits`,
397
+ `${style.bold("a")} yes, auto-accept edits`,
398
+ `${style.bold("n")} no, keep planning`,
399
+ `${style.bold("ctrl+g")} edit`,
400
+ ];
401
+ const footer = `${theme.accent("Build?")} ${options.join(theme.muted(" · "))}`;
402
+ const lines = boxed(heading, body, footer, width);
403
+ // On narrow terminals the options wrap rather than vanish.
404
+ if (visibleWidth(footer) > width - 4) {
405
+ lines.pop();
406
+ lines.push(`${INDENT}${theme.border("╰")} ${theme.accent("Build?")}`);
407
+ for (const opt of options) {
408
+ lines.push(...wrapTextWithAnsi(opt, nestedWidth(width)).map((l) => NESTED + l));
409
+ }
410
+ }
411
+ return lines;
412
+ }
413
+ }
310
414
  /** A filterable list (model picker): type to filter, ↑↓ to move, Enter to pick, Esc to cancel. */
311
415
  export class Picker {
312
416
  title;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Editing a plan in the person's own editor (`$VISUAL`, then `$EDITOR`, then nano or vi; Notepad
3
+ * on Windows), the way `git commit` does. The plan goes in a private temporary file, deleted
4
+ * afterwards whatever happens.
5
+ */
6
+ import { spawn } from "node:child_process";
7
+ import { constants } from "node:fs";
8
+ import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
10
+ import { delimiter, join } from "node:path";
11
+ const isWindows = process.platform === "win32";
12
+ /** An editor that returns sooner than this without a change probably didn't wait for you. */
13
+ const QUICK_MS = 1000;
14
+ async function onPath(name, env) {
15
+ for (const dir of (env.PATH ?? "").split(delimiter)) {
16
+ if (!dir)
17
+ continue;
18
+ try {
19
+ await access(join(dir, name), constants.X_OK);
20
+ return true;
21
+ }
22
+ catch {
23
+ // keep looking
24
+ }
25
+ }
26
+ return false;
27
+ }
28
+ /** The editor command line to run: the person's choice, else one that's sure to exist. */
29
+ export async function editorCommand(env) {
30
+ const chosen = env.VISUAL?.trim() || env.EDITOR?.trim();
31
+ if (chosen)
32
+ return chosen;
33
+ if (isWindows)
34
+ return "notepad";
35
+ return (await onPath("nano", env)) ? "nano" : "vi";
36
+ }
37
+ /** Runs `editor` on `file` with the terminal handed over, until it exits. */
38
+ function runEditor(editor, file, env) {
39
+ return new Promise((resolve, reject) => {
40
+ // Through the shell, so EDITOR="code --wait" works; the file is passed as $1, never parsed.
41
+ const child = isWindows
42
+ ? spawn(editor, [file], { stdio: "inherit", env, shell: true })
43
+ : spawn(env.SHELL || "/bin/sh", ["-c", `${editor} "$1"`, "reasonally-editor", file], {
44
+ stdio: "inherit",
45
+ env,
46
+ });
47
+ child.on("error", reject);
48
+ child.on("exit", (code) => resolve(code));
49
+ });
50
+ }
51
+ /** Opens `text` in the person's editor and reports what they did with it. */
52
+ export async function editInEditor(text, options = {}) {
53
+ const env = options.env ?? process.env;
54
+ const now = options.now ?? Date.now;
55
+ const dir = await mkdtemp(join(tmpdir(), "reasonally-plan-"));
56
+ const file = join(dir, "plan.md");
57
+ // Ctrl+C meant for the editor shouldn't stop us too while it has the terminal.
58
+ const ignore = () => { };
59
+ process.on("SIGINT", ignore);
60
+ try {
61
+ await writeFile(file, `${text}\n`, { mode: 0o600 });
62
+ const editor = await editorCommand(env);
63
+ const started = now();
64
+ let code;
65
+ try {
66
+ code = await runEditor(editor, file, env);
67
+ }
68
+ catch (error) {
69
+ return { kind: "failed", message: error.message };
70
+ }
71
+ // 126/127: the shell couldn't run it (not found, not executable).
72
+ if (code === 126 || code === 127)
73
+ return { kind: "failed", message: `${editor} didn't start.` };
74
+ if (code !== 0)
75
+ return { kind: "unchanged", quick: false };
76
+ const edited = (await readFile(file, "utf8")).trim();
77
+ if (!edited)
78
+ return { kind: "empty" };
79
+ if (edited === text.trim())
80
+ return { kind: "unchanged", quick: now() - started < QUICK_MS };
81
+ return { kind: "edited", text: edited };
82
+ }
83
+ finally {
84
+ process.off("SIGINT", ignore);
85
+ await rm(dir, { recursive: true, force: true });
86
+ }
87
+ }
88
+ /** How many lines differ between two versions (each line counted once, moved lines aside). */
89
+ export function changedLines(before, after) {
90
+ const left = new Map();
91
+ for (const line of before.split("\n"))
92
+ left.set(line, (left.get(line) ?? 0) + 1);
93
+ let added = 0;
94
+ for (const line of after.split("\n")) {
95
+ const n = left.get(line) ?? 0;
96
+ if (n > 0)
97
+ left.set(line, n - 1);
98
+ else
99
+ added++;
100
+ }
101
+ const removed = [...left.values()].reduce((a, b) => a + b, 0);
102
+ return Math.max(added, removed);
103
+ }
@@ -13,9 +13,11 @@ export function formatTokens(n) {
13
13
  return `${+(n / 1000).toFixed(1)}K`;
14
14
  return String(n);
15
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)`;
16
18
  /** "Ask before edits (shift+tab) · 12% context · ~$0.04 · $18.20 left" */
17
19
  export function statusLine(s) {
18
- const parts = [`${MODE_LABELS[s.mode]} (shift+tab)`];
20
+ const parts = [modeStatus(s.mode)];
19
21
  if (s.contextTokens !== null) {
20
22
  const pct = Math.min(100, Math.round((s.contextTokens / s.contextLength) * 100));
21
23
  parts.push(`${pct === 0 && s.contextTokens > 0 ? "<1" : pct}% context`);
@@ -114,3 +116,9 @@ export function compactionNote(before, after, contextLength) {
114
116
  : `${formatTokens(before)} → ${formatTokens(after)} tokens`;
115
117
  return `Summarized earlier conversation to free up context (${change}).`;
116
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
+ }
package/dist/tui/start.js CHANGED
@@ -7,9 +7,10 @@ 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
9
  import { gitBranch, loadInstructions, systemPrompt } from "../agent/prompt.js";
10
- import { listSessions, loadSession, sessionsDir } from "../agent/session.js";
10
+ import { listSessions, loadSession, sessionHolder, sessionsDir, } from "../agent/session.js";
11
11
  import { shellFor } from "../agent/tools/bash.js";
12
12
  import { App } from "./app.js";
13
+ import { openElsewhere } from "./format.js";
13
14
  /** The key the agent's last model is remembered under in state.json (not a harness id). */
14
15
  export const MODEL_MEMORY_KEY = "tui";
15
16
  async function currentSession() {
@@ -71,8 +72,11 @@ export async function startTui(args, log) {
71
72
  let startNotice;
72
73
  if (args.continue) {
73
74
  const [latest] = await listSessions(sessions);
74
- resume = latest ? await loadSession(latest.path) : null;
75
- if (!resume)
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)
76
80
  startNotice = "No saved conversation in this folder yet; starting a new one.";
77
81
  // Continue with the conversation's own model unless one was asked for.
78
82
  else if (!args.model)
@@ -108,7 +112,7 @@ export async function startTui(args, log) {
108
112
  resume,
109
113
  pickSession: args.resume,
110
114
  startNotice,
111
- mode: args.yes ? "full" : "ask",
115
+ mode: args.plan ? "plan" : args.yes ? "full" : "ask",
112
116
  systemPrompt: promptFor,
113
117
  fetchBalance: balanceOf,
114
118
  login: async (report) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reasonally",
3
- "version": "0.3.0",
3
+ "version": "0.4.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": {