nou-cli 0.5.1 → 0.5.3

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 +48 -9
  2. package/dist/index.js +9 -99
  3. package/dist/src/agent/index.js +199 -33
  4. package/dist/src/cli.js +117 -0
  5. package/dist/src/commands/index.js +233 -25
  6. package/dist/src/config/index.js +14 -0
  7. package/dist/src/context/index.js +33 -10
  8. package/dist/src/conversations/external.js +165 -0
  9. package/dist/src/conversations/index.js +71 -0
  10. package/dist/src/engines/claude.js +10 -0
  11. package/dist/src/engines/codex.js +60 -5
  12. package/dist/src/games/index.js +217 -0
  13. package/dist/src/mcp/import.js +106 -0
  14. package/dist/src/mcp/index.js +184 -0
  15. package/dist/src/providers/anthropic.js +23 -3
  16. package/dist/src/providers/index.js +13 -0
  17. package/dist/src/providers/openai.js +6 -2
  18. package/dist/src/syntax/index.js +10 -20
  19. package/dist/src/syntax/themes.js +57 -0
  20. package/dist/src/terminal/index.js +127 -0
  21. package/dist/src/tools/index.js +86 -2
  22. package/dist/src/ui/App.js +900 -118
  23. package/dist/src/ui/Chat.js +143 -22
  24. package/dist/src/ui/ChatInput.js +9 -2
  25. package/dist/src/ui/CodeView.js +111 -20
  26. package/dist/src/ui/Editor.js +13 -6
  27. package/dist/src/ui/FileTree.js +6 -5
  28. package/dist/src/ui/GamePanel.js +99 -0
  29. package/dist/src/ui/Header.js +1 -1
  30. package/dist/src/ui/QuickOpen.js +51 -12
  31. package/dist/src/ui/Settings.js +58 -13
  32. package/dist/src/ui/Tabs.js +56 -0
  33. package/dist/src/ui/Terminal.js +84 -0
  34. package/dist/src/ui/clipboard.js +9 -7
  35. package/dist/src/ui/commands.js +36 -0
  36. package/dist/src/ui/definition.js +135 -0
  37. package/dist/src/ui/fast-width.js +62 -0
  38. package/dist/src/ui/mouse.js +4 -1
  39. package/dist/src/ui/render-options.js +4 -0
  40. package/dist/src/ui/text.js +132 -12
  41. package/dist/src/ui/width-shim.js +7 -0
  42. package/package.json +2 -1
package/README.md CHANGED
@@ -47,14 +47,17 @@ Needs **Node 22.12+** and an interactive terminal (Windows Terminal, PowerShell,
47
47
  | | |
48
48
  | --- | --- |
49
49
  | 🗂️ **File explorer** | Browse your project with file icons and git status (`M` modified, `?` new). Press <kbd>c</kbd> to see only changed files. |
50
- | 🔀 **Live diffs** | Every edit Nou proposes shows up side by side. <kbd>y</kbd> accepts, <kbd>n</kbd> rejects. Nothing touches disk without you. |
50
+ | 🔀 **Live diffs** | Every edit Nou proposes shows up side by side, and the files it is editing shimmer in the file tree while it works. <kbd>y</kbd> accepts, <kbd>n</kbd> rejects. Nothing touches disk without you. |
51
51
  | ✍️ **Built-in editor** | Press <kbd>e</kbd> to edit the open file yourself, with undo/redo and **auto-save**. |
52
+ | 📍 **Shows you where things are** | Ask "where is the LiveKit integration?" and Nou finds it and opens it in the middle panel, jumped to the exact lines and highlighted. Any file a reply mentions (`src/a.ts:12`) is a link: click it. `/open name[:line]` opens a file yourself. |
53
+ | 🎮 **Games for a break** | Add Pong, Snake and Breakout in settings → Games, then `/games` opens a panel docked under the chat: it splits that column instead of covering anything. Drag its title onto the files, code or chat to dock it there, and × at its top right closes it. A game runs only while the panel has the keyboard: Esc goes back to your code and it waits. |
54
+ | 🧠 **A capable engine** | Reads and searches in parallel, numbered reads for exact line references, edits that survive small whitespace mismatches, several edits to a file as one change, a plan for longer tasks, full command output (stderr too) with exit codes and timeouts, retries when a provider is overloaded or a connection drops (Codex too: it picks the turn back up instead of stopping at "Reconnecting..."), and conversation caching with Claude. It follows your repo's `AGENTS.md`, `CLAUDE.md` and `NOU.md` (and `~/.nou/NOU.md`). |
52
55
  | 🔎 **Finds its way around** | The agent searches your code (`grep`, `glob`) without asking, reads only what it needs, runs your tests to check its work, and summarizes long conversations to stay within the model's context (`/compact` does it on demand). |
53
56
  | ↶ **Undo anything** | Every change, Nou's or yours, is recorded. <kbd>u</kbd> undoes Nou's last edit, `/rewind` undoes its whole last turn, and your own later edits are kept. |
54
57
  | 🧾 **Session diffs** | `/diff` shows everything that changed this session, file by file (<kbd>[</kbd> <kbd>]</kbd> to step through). `/sessions` lists earlier sessions and `/diff 2` shows one. |
55
58
  | 🩺 **Problems, live** | Syntax errors instantly, plus ESLint, TypeScript, Ruff and language servers when your project has them. Shown in the gutter, inline, and in a <kbd>p</kbd> Problems panel. |
56
59
  | 🤖 **Self-correcting** | Nou checks its own edits: you see "⚠ +1 problem" *before* approving, and any problems it introduced are fed back so it fixes them. |
57
- | 🎨 **Real syntax highlighting** | tree-sitter parsing for 14 languages (TS, JS, Python, Go, Rust, Java, C, JSON, YAML…). |
60
+ | 🎨 **Real syntax highlighting** | tree-sitter parsing for 14 languages (TS, JS, Python, Go, Rust, Java, C, JSON, YAML…), in your choice of theme: One Dark (default), Tokyo Night, GitHub Dark, Dracula, High Contrast or GitHub Light (settings → Preferences → Code colors, with a preview). |
58
61
  | 🧭 **Code intelligence** | <kbd>Ctrl</kbd>+<kbd>K</kbd> hover info and <kbd>Ctrl</kbd>+<kbd>G</kbd> go-to-definition via language servers (typescript-language-server, pyright, rust-analyzer, gopls, clangd). |
59
62
  | 👀 **Knows what you're looking at** | The open file, visible lines, your cursor and unsaved edits ride along with each message. "Fix this function" just works. |
60
63
  | 🌿 **Git aware** | Sees your branch, uncommitted changes and recent commits, and can diff on its own. Press <kbd>v</kbd> to diff any file against `HEAD`. |
@@ -78,21 +81,29 @@ Every change is reviewed like a code review:
78
81
  | --- | --- |
79
82
  | 🖱️ Mouse | wheel scrolls the pane under the pointer (<kbd>Shift</kbd>+wheel or a tilt wheel: sideways) · click or drag a scrollbar to jump · click a file to open it · **double-click in the code to edit right there** (in the editor: select a word), drag to select · drag a border between panes to resize them (press <kbd>m</kbd> to turn the mouse off and select text in your terminal) |
80
83
  | <kbd>PgUp</kbd>/<kbd>PgDn</kbd>, <kbd>Shift</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd> | scroll the chat; scrolled up, new replies wait below instead of yanking the view (<kbd>Ctrl</kbd>+<kbd>End</kbd> jumps back) |
81
- | <kbd>/</kbd> | start a command from any pane |
84
+ | <kbd>?</kbd> | **every action, searchable**, each with its shortcut (also <kbd>Ctrl</kbd>+<kbd>P</kbd> then `>`) |
85
+ | <kbd>/</kbd> | start a command from any pane: a menu lists every command with what it does (<kbd>↑</kbd>/<kbd>↓</kbd> choose, <kbd>Tab</kbd> complete, <kbd>Enter</kbd> run) |
86
+ | 🖱️ Status bar | click the mode to switch it, `follow` to toggle it, the ✖/▲ counts for the Problems panel, or any shortcut hint to do it · click the model in the header to change it |
82
87
  | <kbd>Tab</kbd> | switch between files, code and chat |
83
88
  | <kbd>Shift</kbd>+<kbd>Tab</kbd> | ask → auto-edit (edits apply without asking) → auto (commands too); everything stays undoable |
84
- | <kbd>Ctrl</kbd>+<kbd>P</kbd> | fuzzy-find a file |
89
+ | <kbd>Ctrl</kbd>+<kbd>P</kbd> | fuzzy-find a file; the files you've opened are listed first |
90
+ | <kbd>b</kbd> | back to the previous file (press again to flip back) |
91
+ | <kbd>Ctrl</kbd>+<kbd>F</kbd> | find in the open file: matches are highlighted and counted; <kbd>Enter</kbd>/<kbd>↓</kbd> next, <kbd>↑</kbd> previous, <kbd>Esc</kbd> close |
92
+ | 🗂️ Tabs | every file you open gets a tab over the code: click one to switch, any tab's × to close it, ‹ › for ones that don't fit · <kbd>[</kbd>/<kbd>]</kbd> previous/next · <kbd>x</kbd> or <kbd>Ctrl</kbd>+<kbd>W</kbd> close |
93
+ | <kbd>Ctrl</kbd>+click | on a name in the code (or <kbd>Option</kbd>+click, or right-click): go to its definition; an imported name goes to its import, and the import's path opens that file |
85
94
  | <kbd>e</kbd> or a double-click | edit the open file (see the editor keys below) |
86
95
  | <kbd>p</kbd> | Problems panel: every error and warning, <kbd>Enter</kbd> jumps to it |
87
96
  | <kbd>u</kbd> | undo Nou's last edit |
88
97
  | <kbd>v</kbd> | diff the open file vs git `HEAD`, Nou's last edit, or this session · <kbd>n</kbd>/<kbd>N</kbd> jump between changes · <kbd>[</kbd>/<kbd>]</kbd> previous/next file in a session diff |
89
98
  | <kbd>c</kbd> | in the file tree: show only changed files |
90
- | <kbd>f</kbd> | follow mode (off by default): jump to files as Nou reads and edits them |
99
+ | <kbd>f</kbd> | follow mode (off by default): watch along as Nou works. Each file it reads (the exact lines, highlighted) is shown a step at a time, a little behind it, and its edits as they happen. The status bar shows how many steps behind it is; set the speed in settings → Preferences (slow · normal · fast · instant) |
91
100
  | <kbd>&lt;</kbd> / <kbd>&gt;</kbd> / <kbd>=</kbd> | make the focused pane narrower / wider / reset the layout |
92
- | <kbd>m</kbd> | mouse on/off, so you can select and copy text in the terminal |
101
+ | <kbd>`</kbd> | a terminal under the code, like VS Code's (also `/terminal`): Enter runs a command, Ctrl+C stops it, ↑↓ history, Esc back to the code, × closes it. Commands run through your shell one at a time, so full-screen programs like vim don't draw there |
102
+ | <kbd>m</kbd> | mouse on/off, so you can select and copy text in the terminal (in the chat, just drag over the text: it's copied when you let go) |
93
103
  | <kbd>s</kbd> | settings: model, preferences, plugins |
94
104
  | <kbd>y</kbd> / <kbd>n</kbd> | accept / reject a proposed edit or command, from any pane; the rest of Nou keeps working while it waits (<kbd>o</kbd> shows the edit) |
95
- | <kbd>Esc</kbd> | stop Nou · close a diff · back to chat |
105
+ | <kbd>Enter</kbd> while Nou works | queue the message: it goes when Nou finishes, together with anything else you queued, as one message (<kbd>Alt</kbd>+<kbd>Enter</kbd>: stop Nou and send it now) |
106
+ | <kbd>Esc</kbd> | stop Nou (anything queued goes back in the input) · close a diff · back to chat |
96
107
  | <kbd>Ctrl</kbd>+<kbd>C</kbd> | stop Nou while it works · press twice to quit |
97
108
 
98
109
  In the editor:
@@ -109,7 +120,11 @@ In the editor:
109
120
  | <kbd>Ctrl</kbd>+<kbd>K</kbd> · <kbd>Ctrl</kbd>+<kbd>G</kbd> | hover info · go to definition (with a language server) |
110
121
  | <kbd>Esc</kbd> | clear the selection, or leave the editor |
111
122
 
112
- Chat commands: `/settings` · `/model [provider:model]` · `/models [provider]` · `/pull <model>` · `/engine [name]` · `/auto [ask|auto-edit|auto]` · `/copy [code|file]` · `/undo` · `/rewind` · `/history` · `/diff [file or n]` · `/sessions` · `/problems` · `/compact` · `/clear` · `/help`
123
+ Chat commands: `/settings` · `/model [provider:model]` · `/models [provider]` · `/pull <model>` · `/engine [name]` · `/auto [ask|auto-edit|auto]` · `/copy [code|file]` · `/undo` · `/rewind` · `/history` · `/diff [file or n]` · `/sessions` · `/problems` · `/compact` · `/clear` · `/resume [n|last]` · `/terminal` · `/help`
124
+
125
+ New lines in a message: <kbd>Shift</kbd>/<kbd>Ctrl</kbd>/<kbd>Cmd</kbd>+<kbd>Enter</kbd> in terminals that report them (kitty, Ghostty, WezTerm, iTerm2 and others with the kitty keyboard protocol), or type `\` and press <kbd>Enter</kbd> in any terminal.
126
+
127
+ Conversations are saved per folder after each reply. `/resume` lists them and `/resume 2` (or `nou --continue` for the last one, `nou --resume` for the list) picks one back up with the engine it was on: Nou's own engine restores its messages, Claude Code its session and Codex its thread; pi is handed the conversation so far. Sessions you started in Claude Code's or Codex's own CLI in this folder are listed too (marked "CLI"), and resuming one carries it on in that engine inside Nou.
113
128
 
114
129
  ## 🧠 Models
115
130
 
@@ -165,6 +180,20 @@ nou --version
165
180
 
166
181
  Set `NOU_NO_UPDATE_CHECK=1` to turn the check off.
167
182
 
183
+ ## 🔌 MCP servers and browser control
184
+
185
+ Nou's engine can use tools from [MCP](https://modelcontextprotocol.io) servers: a browser, GitHub, your database...
186
+
187
+ - **Already use some?** Nou finds the MCP servers you've set up in Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Gemini CLI and Codex, and offers them on start: `/mcp import` brings them over, with their settings. (Your Claude Code and Codex API keys are picked up too; see *Use Claude Code / Codex keys* in settings.)
188
+ - **Browser control:** `/mcp add browser` adds [Playwright's MCP server](https://github.com/microsoft/playwright-mcp), so you can ask Nou to open a page, click through it, fill a form or check what your app shows.
189
+ - **Your own:** `/mcp add <name> <command and arguments>` or `/mcp add <name> <url>`; `/mcp` lists them and their status, `/mcp remove <name>` removes one. They live in `~/.nou/mcp.json` (same format as Claude Code and Cursor); a project's `.mcp.json` is used too, in folders you trust.
190
+
191
+ Tools that say they only read run on their own; any other MCP tool asks you first, like Nou's edits and commands. A server's own output never reaches Nou's screen.
192
+
193
+ ## 🔒 Trusting a folder
194
+
195
+ The first time you open a folder, Nou asks whether you trust its files: it reads them, and can run the folder's MCP servers and plugins. Say no and Nou doesn't open it. Trusted folders are listed in `~/.nou/config.json`.
196
+
168
197
  ## 🧩 Plugins *(early)*
169
198
 
170
199
  **Starter plugins** ship with Nou and are optional: open <kbd>s</kbd> settings → **Plugins** and press Enter on one, or type `/plugins add <name>`. Adding one copies it into `~/.nou/plugins/`, where it's yours to edit.
@@ -207,7 +236,17 @@ npm run screenshot # regenerate docs/screenshot.svg
207
236
  npm run eval # how well the agent does real tasks with a real model (see evals/)
208
237
  ```
209
238
 
210
- Releasing: bump `version` in `package.json`, merge to `master`, then run **Actions → Publish to npm**. It tests, publishes with provenance, and creates the git tag and GitHub Release. (Or publish a GitHub release tagged `vX.Y.Z`.) The token lives in the `production` environment as `NPM_TOKEN`.
239
+ ### Releasing
240
+
241
+ **Always bump the version first.** npm never accepts the same version twice, so publishing without a bump fails with *"nou-cli@X.Y.Z is already published. Bump "version" in package.json first."* Every release goes:
242
+
243
+ 1. **Bump the version** in a PR: `npm version patch --no-git-tag-version` (or `minor` / `major`), which updates `package.json` and `package-lock.json` together. Patch (0.5.1 → 0.5.2) for fixes and small features, minor (0.5 → 0.6) for bigger ones.
244
+ 2. **Merge it** to `master` once CI is green.
245
+ 3. **Run Actions → Publish to npm** (Run workflow on `master`), then **approve** the `production` environment when GitHub asks. It tests, publishes with provenance, and creates the `vX.Y.Z` git tag and GitHub Release. (Publishing a GitHub release tagged `vX.Y.Z` does the same, taking the version from the tag.)
246
+
247
+ The npm token lives in the `production` environment as `NPM_TOKEN`. Check what's live with `npm view nou-cli version`.
248
+
249
+ The workflows run on the actions' Node 24 versions (`actions/checkout@v5`, `actions/setup-node@v5`, `codeql-action@v4`), so GitHub's Node 20 deprecation warning no longer applies; Dependabot keeps them current. Jobs run on `ubuntu-latest`, which GitHub moves to Ubuntu 26 from October 19, 2026: nothing to change for that.
211
250
 
212
251
  Upkeep runs on its own:
213
252
  - **CI** on every PR: type-check, lint, build, unit and end-to-end tests on Linux, macOS and Windows (Node 22.12 and 24 too), plus installing the packed tarball to check the package works.
package/dist/index.js CHANGED
@@ -1,103 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  // Must stay the first import: loads .env before any provider reads its keys and URLs.
3
3
  import "./src/env.js";
4
- import { createElement } from "react";
5
- import { render } from "ink";
6
- import * as p from "@clack/prompts";
7
- import chalk from "chalk";
8
- import { artWork } from "./src/util/index.js";
9
- import { ensureProjectContext, loadPermanentContext } from "./src/context/index.js";
10
- import { describe, initialModel, resolveModel, saveModel } from "./src/providers/index.js";
11
- import { loadSettings } from "./src/config/index.js";
12
- import { loadCredentials } from "./src/config/credentials.js";
13
- import { borrowToolConfig, ensureLocalModel, pickStartingModel } from "./src/setup/index.js";
14
- import { checkForUpdate, currentVersion, installUpdate, relaunch } from "./src/update/index.js";
15
- import { lsp } from "./src/lsp/index.js";
16
- import { App } from "./src/ui/App.js";
17
- import { installFastOutput } from "./src/ui/fast-output.js";
18
- import { RENDER_OPTIONS } from "./src/ui/render-options.js";
19
- const HELP = `nou ${currentVersion()}: an AI coding assistant for your terminal
20
-
21
- Usage:
22
- nou open Nou in the current folder
23
- nou update update to the latest version
24
- nou --version print the version
25
- nou --help show this help
26
-
27
- Settings live in ~/.nou/config.json (or press s inside Nou); keys you enter there, or with /connect, in ~/.nou/credentials.json. Set NOU_NO_UPDATE_CHECK=1 to skip update checks.`;
28
- async function main() {
29
- const args = process.argv.slice(2);
30
- if (args.includes("--version") || args.includes("-v")) {
31
- console.log(currentVersion());
32
- return;
33
- }
34
- if (args.includes("--help") || args.includes("-h")) {
35
- console.log(HELP);
36
- return;
37
- }
38
- if (args[0] === "update") {
39
- const latest = await checkForUpdate({ force: true, timeout: 10_000 });
40
- if (!latest) {
41
- console.log(`nou ${currentVersion()} is up to date.`);
42
- return;
43
- }
44
- console.log(`Updating nou ${currentVersion()} → ${latest}...`);
45
- if (await installUpdate(latest))
46
- process.exit(0);
47
- if (process.platform !== "win32")
48
- console.log("If that was a permissions error, run: sudo npm install -g nou-cli@latest");
49
- process.exit(1);
50
- }
51
- if (!process.stdin.isTTY) {
52
- console.error("Nou needs an interactive terminal (try Windows Terminal, PowerShell, or Terminal/iTerm on macOS).");
53
- process.exit(1);
54
- }
55
- p.intro(chalk.cyan(`${artWork} \n Hello I am Nou! 🌞 ${chalk.dim(`v${currentVersion()}`)}`));
56
- const latest = await checkForUpdate();
57
- if (latest) {
58
- const update = await p.confirm({ message: `Nou ${chalk.green(latest)} is available (you have ${currentVersion()}). Update now?` });
59
- if (update === true) {
60
- const ok = await installUpdate(latest);
61
- if (ok) {
62
- p.log.success(`Updated to ${latest}. Restarting...`);
63
- relaunch();
64
- return;
65
- }
66
- p.log.warn(process.platform === "win32"
67
- ? "The update failed. You can retry later with: npm install -g nou-cli@latest"
68
- : "The update failed. If it was a permissions error, run: sudo npm install -g nou-cli@latest");
69
- }
70
- }
71
- const settings = loadSettings();
72
- loadCredentials(); // keys entered inside Nou, for whatever the environment and .env leave unset
73
- const borrowed = settings.reuseToolConfig ? borrowToolConfig() : [];
74
- for (const b of borrowed)
75
- p.log.info(`Using the ${b.provider === "anthropic" ? "Anthropic" : "OpenAI"} API key from your ${b.tool} settings.`);
76
- let choice = initialModel();
77
- // First run: start with a model that's already here, if there is one.
78
- if (!process.env.NOU_MODEL && !settings.model) {
79
- const picked = await pickStartingModel(borrowed);
80
- if (picked) {
81
- choice = picked;
82
- saveModel(picked);
83
- }
84
- }
85
- const problem = choice.provider.unavailable();
86
- if (problem) {
87
- p.log.warn(`${choice.provider.label} isn't set up (${problem}), falling back to local Ollama.`);
88
- choice = resolveModel("ollama");
89
- }
90
- const ready = await ensureLocalModel(choice);
91
- if (ready !== choice)
92
- saveModel(ready); // picked a model that's already installed instead
93
- choice = ready;
94
- p.log.info(`Model: ${chalk.yellow(describe(choice))} (change it any time with /model)`);
95
- await ensureProjectContext(choice);
96
- const permContext = await loadPermanentContext();
97
- await installFastOutput();
98
- const app = render(createElement(App, { initialModel: choice, permContext }), RENDER_OPTIONS);
99
- await app.waitUntilExit();
100
- lsp.stopAll();
101
- p.outro(chalk.cyan("Bye bye!"));
4
+ import { installFastWidth } from "./src/ui/fast-width.js";
5
+ // Answered before loading the rest, which takes most of a second.
6
+ if (process.argv[2] === "--version" || process.argv[2] === "-v") {
7
+ const { currentVersion } = await import("./src/update/index.js");
8
+ console.log(currentVersion());
9
+ process.exit(0);
102
10
  }
103
- main().catch(console.error);
11
+ // Ink's text measuring has to be swapped before Ink loads, so everything else is imported after it.
12
+ installFastWidth();
13
+ await import("./src/cli.js");
@@ -1,11 +1,29 @@
1
1
  import { randomUUID } from "crypto";
2
+ import { existsSync, statSync } from "fs";
2
3
  import { toolDefs } from "../tools/index.js";
3
- import { applyChange, capOutput, fileTree, isInProject, proposeEdit, proposeWrite, readForModel, runCommand, toRelative, } from "../commands/index.js";
4
+ import { applyChange, capOutput, fileTree, isInProject, proposeEdit, proposeEdits, proposeWrite, readForModel, runCommand, toRelative, } from "../commands/index.js";
4
5
  import { describe, keyHint } from "../providers/index.js";
5
6
  import { newCallId } from "../providers/ids.js";
6
7
  import { globFiles, grep } from "../search/index.js";
7
8
  /** Model requests per user message before stopping; real tasks (explore, edit, test, fix) take a few dozen. */
8
9
  const MAX_STEPS = 60;
10
+ /** Tries per model request when it fails for a passing reason (see withRetries). */
11
+ const RETRIES = 6;
12
+ /** Errors worth retrying: overloaded, rate limited, a server error, a dropped or timed-out connection. */
13
+ function transient(error) {
14
+ const status = Number(error?.status ?? error?.statusCode);
15
+ if (status === 408 || status === 409 || status === 429 || status >= 500)
16
+ return true;
17
+ if (status >= 400)
18
+ return false;
19
+ return transientMessage(String(error?.message ?? error));
20
+ }
21
+ /** Whether an error's text reads as a passing problem (a dropped stream, a busy or failing server). */
22
+ export function transientMessage(text) {
23
+ if (/ECONNREFUSED|ENOTFOUND|EAI_AGAIN|Invalid URL|api key|unauthori[sz]ed|\b40[13]\b/i.test(text))
24
+ return false;
25
+ return /overloaded|rate.?limit|too many requests|ECONNRESET|socket hang up|ETIMEDOUT|timed? ?out|EPIPE|network|premature close|terminated|disconnected|server had an error|internal server error|service unavailable|bad gateway|try again|\b(429|5\d\d)\b/i.test(text);
26
+ }
9
27
  /** Messages kept word for word when older ones are summarized. */
10
28
  const KEEP_RECENT = 8;
11
29
  const TRIMMED_OUTPUT = "\n[... trimmed to save context; run the tool again if you need it]";
@@ -24,6 +42,13 @@ How to work:
24
42
  4. Keep going until the task is done. The user approves each edit and command as it happens, so don't stop to ask permission between steps; ask only when the request is unclear or you need a decision.
25
43
  5. End with a short summary of what you changed and why. When the user only asks a question, answer it without editing anything.
26
44
 
45
+ - Make independent calls together: several reads or searches in one response run at the same time.
46
+ - Use grep, glob and read_file to look around, not run_command with grep, find or cat. Several edits to one file go in one multi_edit.
47
+ - If an edit fails twice, read the file again before the next try.
48
+ - For work with three or more steps, keep a plan with update_plan and update it as you go.
49
+ - Don't commit, push, install packages or delete files unless the user asked. Don't add comments the code didn't need.
50
+ - Before saying something works, check it (run the tests or the code). If you couldn't, say so.
51
+ - When the user asks where something is, or to show, open or find something, search for it (grep, glob), read enough to be sure, then call open_file on the exact place (with line and end_line) so it opens in their code view, and answer in a sentence or two with path:line.
27
52
  - If the user rejects an edit or command, don't retry it: ask what they would like instead.
28
53
  - Keep replies short. Refer to code as path:line.
29
54
 
@@ -66,6 +91,11 @@ export class Agent {
66
91
  this.hooks = hooks;
67
92
  }
68
93
  configure(options) {
94
+ // A different system prompt or tool list (an MCP server connected, a plugin switched) changes what the
95
+ // earlier thinking was written against: newer Claude models reject replaying it, so it's dropped.
96
+ const toolsChanged = options.extraTools && options.extraTools.map((t) => t.definition.name).join() !== this.extraTools.map((t) => t.definition.name).join();
97
+ if (this.messages.length && ((options.system !== undefined && options.system !== this.system) || toolsChanged))
98
+ this.forgetThinking();
69
99
  if (options.system !== undefined)
70
100
  this.system = options.system;
71
101
  if (options.extraTools)
@@ -84,6 +114,24 @@ export class Agent {
84
114
  this.messages = [];
85
115
  this.notes = [];
86
116
  }
117
+ /** Forgets the last message you sent and everything after it, as if it was never sent. */
118
+ snapshot() {
119
+ return { messages: this.messages };
120
+ }
121
+ restore(state) {
122
+ if (!Array.isArray(state?.messages))
123
+ return false;
124
+ this.messages = state.messages;
125
+ this.forgetThinking(); // written in another run, maybe with another model
126
+ return true;
127
+ }
128
+ retractLast() {
129
+ const at = this.messages.findLastIndex((m) => m.role === "user");
130
+ if (at < 0)
131
+ return false;
132
+ this.messages = this.messages.slice(0, at);
133
+ return true;
134
+ }
87
135
  /** Something the model should know before the next message (e.g. the user undid its edit). */
88
136
  note(text) {
89
137
  this.notes.push(text);
@@ -123,6 +171,8 @@ export class Agent {
123
171
  trimmed++;
124
172
  }
125
173
  }
174
+ if (trimmed)
175
+ this.forgetThinking();
126
176
  if (!force && this.requestSize() <= budget * 0.8) {
127
177
  this.hooks.onEntry({ kind: "info", text: `Trimmed ${trimmed} old tool outputs to fit the model's context.` });
128
178
  return true;
@@ -140,6 +190,7 @@ export class Agent {
140
190
  throw error;
141
191
  summary = `(The earlier conversation was dropped to fit the context; summarizing it failed: ${error.message})`;
142
192
  }
193
+ this.forgetThinking();
143
194
  const intro = `[Summary of the conversation so far]\n${summary}`;
144
195
  const rest = this.messages.slice(split);
145
196
  const first = rest[0];
@@ -152,6 +203,26 @@ export class Agent {
152
203
  });
153
204
  return true;
154
205
  }
206
+ /**
207
+ * Drops Claude's thinking blocks from the history. Newer Claude models reject a conversation whose
208
+ * earlier turns were edited while it still carries their thinking blocks (they're tied to the exact
209
+ * history they were written in), and trimming or summarizing is such an edit. Without them the model
210
+ * carries on from the visible text and tool calls, which is what the trimmed history holds anyway.
211
+ */
212
+ forgetThinking() {
213
+ this.messages = this.messages.map((m) => {
214
+ if (m.role !== "assistant" || m.raw?.provider !== "anthropic" || !Array.isArray(m.raw.data))
215
+ return m;
216
+ const kept = m.raw.data.filter((b) => b.type !== "thinking" && b.type !== "redacted_thinking");
217
+ if (kept.length === m.raw.data.length)
218
+ return m;
219
+ if (kept.length)
220
+ return { ...m, raw: { ...m.raw, data: kept } };
221
+ const plain = { ...m };
222
+ delete plain.raw;
223
+ return plain;
224
+ });
225
+ }
155
226
  /**
156
227
  * Where to cut the history for a summary: as late as possible while keeping the last few messages, and
157
228
  * only before a user or assistant message, so no tool call is separated from its result.
@@ -198,22 +269,35 @@ export class Agent {
198
269
  this.controller = new AbortController();
199
270
  const { signal } = this.controller;
200
271
  try {
272
+ let cutOff = 0;
201
273
  for (let step = 0; step < MAX_STEPS; step++) {
202
274
  if (this.requestSize() > this.contextBudget())
203
275
  await this.compact(false, signal);
204
276
  this.hooks.onBusy(`Pondering with ${describe(this.choice)}...`);
205
277
  let streamed = "";
206
- const result = await this.choice.provider.chat({
207
- model: this.choice.model,
208
- system: this.system,
209
- messages: this.messages,
210
- tools: this.tools,
211
- signal,
212
- ...(this.effort ? { effort: this.effort } : {}),
213
- onText: (delta) => {
214
- streamed += delta;
215
- this.hooks.onStream(streamed);
216
- },
278
+ let thought = "";
279
+ const result = await this.withRetries(signal, () => {
280
+ streamed = "";
281
+ thought = "";
282
+ return this.choice.provider.chat({
283
+ model: this.choice.model,
284
+ system: this.system,
285
+ messages: this.messages,
286
+ tools: this.tools,
287
+ signal,
288
+ ...(this.effort ? { effort: this.effort } : {}),
289
+ onText: (delta) => {
290
+ streamed += delta;
291
+ this.hooks.onStream(streamed);
292
+ },
293
+ // Its thinking shows on the one-line progress (the latest of it), so the chat doesn't jump.
294
+ onThinking: (delta) => {
295
+ thought = (thought + delta).slice(-400);
296
+ const latest = thought.split("\n").map((l) => l.trim()).filter(Boolean).at(-1) ?? "";
297
+ if (latest)
298
+ this.hooks.onBusy(`Thinking: ${latest.length > 90 ? `…${latest.slice(-89)}` : latest}`);
299
+ },
300
+ });
217
301
  });
218
302
  this.hooks.onStream("");
219
303
  // Tool-call ids must be unique across the conversation (results are matched by id, and some APIs
@@ -241,30 +325,51 @@ export class Agent {
241
325
  return;
242
326
  }
243
327
  if (result.stop === "max_tokens") {
244
- this.hooks.onEntry({ kind: "error", text: "The response was cut off before its tool call finished. Try asking for a smaller change." });
245
- this.dropUnansweredCalls();
246
- return;
328
+ // The reply ran out of room mid tool call (usually a whole file in one write): tell the model and
329
+ // let it try in smaller pieces, a couple of times, before giving up.
330
+ if (++cutOff > 2) {
331
+ this.hooks.onEntry({ kind: "error", text: "The response was cut off before its tool call finished, again. Try asking for a smaller change." });
332
+ this.dropUnansweredCalls();
333
+ return;
334
+ }
335
+ for (const call of result.toolCalls) {
336
+ this.messages.push({ role: "tool", callId: call.id, name: call.name, isError: true,
337
+ content: "Not run: your response hit the output limit before this call was complete. Make the change in smaller steps (edit_file or multi_edit with only the lines that change, not the whole file)." });
338
+ }
339
+ continue;
247
340
  }
248
341
  if (result.toolCalls.length === 0)
249
342
  return;
250
- for (const call of result.toolCalls) {
251
- if (signal.aborted)
252
- break;
253
- this.hooks.onBusy(`Running ${call.name}...`);
254
- const problem = invalidArgs(call, this.tools);
255
- const output = problem ?? capOutput(await this.runTool(call));
256
- this.messages.push({
257
- role: "tool",
258
- callId: call.id,
259
- name: call.name,
260
- content: problem ? `Error: ${problem}` : output,
261
- ...(problem ? { isError: true } : {}),
343
+ // Calls that only look (reads, searches) run together; the rest run one at a time, in order,
344
+ // since they may ask you first or change what a later call sees. Results keep the calls' order.
345
+ const calls = result.toolCalls;
346
+ for (let i = 0; i < calls.length && !signal.aborted;) {
347
+ let j = i + 1;
348
+ if (this.onlyLooks(calls[i]))
349
+ while (j < calls.length && this.onlyLooks(calls[j]))
350
+ j++;
351
+ const batch = calls.slice(i, j);
352
+ this.hooks.onBusy(batch.length > 1 ? `Running ${batch.length} tools...` : `Running ${batch[0].name}...`);
353
+ const outputs = await Promise.all(batch.map(async (call) => {
354
+ const problem = invalidArgs(call, this.tools);
355
+ return problem ? { error: `Error: ${problem}` } : { output: capOutput(await this.runTool(call)) };
356
+ }));
357
+ batch.forEach((call, k) => {
358
+ const out = outputs[k];
359
+ this.messages.push({
360
+ role: "tool",
361
+ callId: call.id,
362
+ name: call.name,
363
+ content: "error" in out ? out.error : out.output,
364
+ ...("error" in out ? { isError: true } : {}),
365
+ });
262
366
  });
367
+ i = j;
263
368
  }
264
369
  if (signal.aborted)
265
370
  throw new Error("aborted");
266
371
  }
267
- this.hooks.onEntry({ kind: "error", text: `Stopped after ${MAX_STEPS} steps.` });
372
+ this.hooks.onEntry({ kind: "error", text: `Paused after ${MAX_STEPS} steps so it doesn't run away. Say "continue" to let it carry on.` });
268
373
  }
269
374
  catch (error) {
270
375
  this.hooks.onStream("");
@@ -296,6 +401,40 @@ export class Agent {
296
401
  }
297
402
  }
298
403
  }
404
+ /**
405
+ * Runs a model request again when it failed for a passing reason (overloaded, rate limited, a server
406
+ * error, a dropped connection), waiting longer each time. Setup problems (a bad key, a URL that doesn't
407
+ * answer) fail straight away: waiting won't fix them, and the app shows where to.
408
+ */
409
+ async withRetries(signal, request) {
410
+ for (let attempt = 1;; attempt++) {
411
+ try {
412
+ return await request();
413
+ }
414
+ catch (error) {
415
+ if (signal.aborted || attempt >= RETRIES || !transient(error))
416
+ throw error;
417
+ const after = Number(error?.headers?.get?.("retry-after") ?? error?.headers?.["retry-after"]);
418
+ const wait = Math.min(30_000, after > 0 ? after * 1000 : 1000 * 2 ** (attempt - 1) + Math.random() * 500);
419
+ this.hooks.onStream("");
420
+ this.hooks.onBusy(`${describe(this.choice)}: ${String(error?.message ?? error).slice(0, 60)}. Retrying in ${Math.ceil(wait / 1000)}s (${attempt}/${RETRIES - 1})...`);
421
+ await new Promise((resolve) => {
422
+ const timer = setTimeout(resolve, wait);
423
+ signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
424
+ });
425
+ if (signal.aborted)
426
+ throw error;
427
+ }
428
+ }
429
+ }
430
+ /** Tools that only read, which can run alongside each other. */
431
+ onlyLooks(call) {
432
+ if (["grep", "glob", "list_files", "get_file_tree"].includes(call.name))
433
+ return true;
434
+ if (call.name === "read_file")
435
+ return typeof call.args.path === "string" && isInProject(call.args.path);
436
+ return this.extraTools.some((t) => t.definition.name === call.name && t.readOnly);
437
+ }
299
438
  async runTool(call) {
300
439
  const { name, args } = call;
301
440
  try {
@@ -309,11 +448,25 @@ export class Agent {
309
448
  }
310
449
  }
311
450
  else {
312
- this.hooks.onRead(toRelative(args.path));
451
+ const from = Number(args.offset) > 1 ? Math.floor(Number(args.offset)) : undefined;
452
+ const count = Number(args.limit) > 0 ? Math.floor(Number(args.limit)) : undefined;
453
+ this.hooks.onRead(toRelative(args.path), from ?? (count ? 1 : undefined), count ? (from ?? 1) + count - 1 : undefined);
313
454
  }
314
455
  this.hooks.onEntry({ kind: "tool", text: `Read ${args.path}` });
315
456
  return await readForModel(args.path, args.offset, args.limit);
316
457
  }
458
+ case "open_file": {
459
+ const file = toRelative(String(args.path));
460
+ if (!isInProject(file))
461
+ return "Error: only files in the project can be shown.";
462
+ if (!existsSync(file) || !statSync(file).isFile())
463
+ return `Error: ${file} is not a file. Find it with glob first.`;
464
+ const line = Number(args.line) > 0 ? Math.floor(Number(args.line)) : undefined;
465
+ const to = line && Number(args.end_line) >= line ? Math.floor(Number(args.end_line)) : line;
466
+ this.hooks.onOpen?.(file, line, to);
467
+ this.hooks.onEntry({ kind: "tool", text: `Opened ${file}${line ? `:${line}${to && to !== line ? `-${to}` : ""}` : ""}` });
468
+ return this.hooks.onOpen ? "It is now open in the user's code view." : "This interface can't show files; give the user the path instead.";
469
+ }
317
470
  case "list_files":
318
471
  case "get_file_tree": {
319
472
  this.hooks.onEntry({ kind: "tool", text: `Listed ${args.path ?? "."}` });
@@ -335,12 +488,21 @@ export class Agent {
335
488
  return globFiles(String(args.pattern), typeof args.path === "string" ? args.path : ".");
336
489
  }
337
490
  case "edit_file":
491
+ case "multi_edit":
338
492
  case "write_file": {
493
+ if (name === "multi_edit" && (!Array.isArray(args.edits) || !args.edits.length))
494
+ return "Error: edits must be a list of {old_string, new_string}.";
339
495
  const change = name === "edit_file"
340
496
  ? await proposeEdit(args.path, args.old_string, args.new_string, args.replace_all === true)
341
- : await proposeWrite(args.path, args.content ?? "");
497
+ : name === "multi_edit" ? await proposeEdits(args.path, args.edits) : await proposeWrite(args.path, args.content ?? "");
342
498
  return await this.reviewChange(change);
343
499
  }
500
+ case "update_plan": {
501
+ const steps = Array.isArray(args.steps) ? args.steps : [];
502
+ const mark = { done: "✓", in_progress: "▸", pending: "○" };
503
+ this.hooks.onEntry({ kind: "tool", text: `Plan:\n${steps.map((st) => `${mark[st.status] ?? "○"} ${st.step}`).join("\n")}` });
504
+ return "Plan updated.";
505
+ }
344
506
  case "run_command": {
345
507
  const ok = await this.hooks.approve({ kind: "command", command: args.command });
346
508
  if (!ok) {
@@ -348,7 +510,9 @@ export class Agent {
348
510
  return "User denied permission to run this command.";
349
511
  }
350
512
  this.hooks.onEntry({ kind: "tool", text: `Ran: ${args.command}` });
351
- const output = await runCommand(args.command);
513
+ // Timeouts are in seconds; a model that sends milliseconds still gets a sensible limit.
514
+ const seconds = Number(args.timeout) > 0 ? Number(args.timeout) : 0;
515
+ const output = await runCommand(args.command, seconds ? (seconds > 3600 ? seconds : seconds * 1000) : undefined, this.controller?.signal);
352
516
  return output.trim() || "(no output)";
353
517
  }
354
518
  default: {
@@ -378,10 +542,12 @@ export class Agent {
378
542
  return "User rejected this change. Ask them what they would like instead.";
379
543
  }
380
544
  const result = await applyChange(change);
381
- this.hooks.onChange(change, "applied", this.turnId);
382
545
  this.hooks.onEntry({ kind: "tool", text: result });
383
- if (result.startsWith("Failed"))
546
+ if (result.startsWith("Failed")) {
547
+ this.hooks.onChange(change, "rejected", this.turnId);
384
548
  return result;
549
+ }
550
+ this.hooks.onChange(change, "applied", this.turnId);
385
551
  this.hooks.onBusy(`Checking ${change.path} for problems...`);
386
552
  const problems = await this.hooks.checkChange?.(change).catch(() => null);
387
553
  if (problems)