@nanobpm/nano-coder 0.68.0 → 1.0.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 (3) hide show
  1. package/README.md +125 -337
  2. package/lib/platform.js +1 -1
  3. package/package.json +8 -7
package/README.md CHANGED
@@ -1,17 +1,26 @@
1
1
  # nano-coder
2
2
 
3
- **A 6MB coding agent. Run a fleet on your laptop.**
3
+ **A 4MB coding agent. Run a fleet on your laptop.**
4
4
 
5
- nano-coder is a coding agent for the terminal, written in Rust. It uses about 6MB of resident memory, where Node-based agent CLIs take 150–660MB, so you can run dense fleets of agent workers on one machine. It runs interactively, or headless over ACP as a worker for [nano-workforce](https://github.com/nanobpm/nano-workforce) via c8ctl-nano.
5
+ nano-coder is a coding agent for the terminal, written in D. Up to 0.69 it was written in Rust; 1.0 is the D rewrite, with the same commands, config (`~/.config/nano-coder/config.toml`, `NANO_CODER_*`), session logs and ACP protocol. It uses about 4MB of memory (peak footprint on macOS), where Node-based agent CLIs take 150–660MB, so you can run dense fleets of agent workers on one machine. It runs interactively, or headless over ACP as a worker for [nano-workforce](https://github.com/nanobpm/nano-workforce) via c8ctl-nano.
6
6
 
7
7
  ## Install
8
8
 
9
9
  ```sh
10
10
  npm install -g @nanobpm/nano-coder # prebuilt binaries for macOS and Linux (x64, arm64)
11
11
  brew install nanobpm/tap/nano-coder # the same binaries through Homebrew
12
- cargo install nano-coder # or build from source
13
12
  ```
14
13
 
14
+ The Linux binaries need glibc 2.35+ and the system libcurl (`libcurl4` on Debian/Ubuntu,
15
+ `libcurl` on Fedora); macOS ships libcurl. To build from source, see
16
+ [Building and Running](#building-and-running).
17
+
18
+ ```sh
19
+ nano-coder --help
20
+ ```
21
+
22
+ `cargo install nano-coder` still installs the last Rust release (0.69), which is no longer updated.
23
+
15
24
  ## Features
16
25
 
17
26
  - **Interactive CLI**: REPL-based interface for conversing with the agent
@@ -19,7 +28,7 @@ cargo install nano-coder # or build from source
19
28
  - **Providers**: OpenAI-compatible and Anthropic endpoints (remote or local), selected per model as `provider/model`, with retry/backoff
20
29
  - **Tool Calling**: Agent can invoke registered tools during conversation, including a real `bash` tool with timeouts and bounded output
21
30
  - **Sessions**: Append-only JSONL session logs with resume and input-ID deduplication
22
- - **Lifecycle Hooks**: 6 internal hook events for observing agent behavior, plus
31
+ - **Lifecycle Hooks**: an `AgentEvents` interface for observing agent behavior, plus
23
32
  Claude Code–compatible external user hooks loaded from `.claude/settings.json`
24
33
  - **Configuration**: TOML-based config file at `~/.config/nano-coder/config.toml`
25
34
  - **Commands**: `/help`, `/version`, `/compact`, `/context`, `/verbosity`, `/settings`, `/tools`, `/skills`, `/queue`, `/restart`, `/update`, `/relaunch`, `/exit`
@@ -60,7 +69,7 @@ show in the same list (marked `steer`, with the id from the `↪ steer #N` note)
60
69
  be withdrawn or rewritten before the agent's next step. A queued message is never injected while the agent is
61
70
  asking for input (the `question` tool's picker owns the terminal until you answer).
62
71
  Slash commands work mid-turn too, where it is safe:
63
- - **Right away:** read-only ones (`/help`, `/version`, `/tools`, `/skills`, `/providers`, `/session`, `/plan`,
72
+ - **Right away:** read-only ones (`/help`, `/tools`, `/skills`, `/providers`, `/session`, `/plan`,
64
73
  `/context`, `/trajectory` (`--json`/`--markdown`), and `/mode` or `/verbosity` without an
65
74
  argument) show the current state. `/plan` shows the plan as the agent updates it.
66
75
  - **From the agent's next step:** `/mode NAME` applies when the agent takes its next step.
@@ -77,13 +86,6 @@ Slash commands work mid-turn too, where it is safe:
77
86
  the running turn, killing any running bash command; a second Ctrl-C at the prompt exits.
78
87
  At the idle prompt, **Esc Esc** instead clears the input, so a half-typed or pasted prompt
79
88
  can be discarded without deleting it character by character.
80
-
81
- Tool calls, their results and thinking blocks are shown collapsed (`● bash ls -la`,
82
- `⎿ first line (+N lines)`, `∴ Thought for 3.1s · 812 chars`). **Ctrl-O** expands the
83
- latest one in place — the call's full arguments with every line of its result, or the
84
- full reasoning text — and pressing it again collapses it. It works at the idle prompt
85
- and mid-turn (where it expands the thinking block that is still streaming), and the
86
- expanded view reflows on resize. Piped output is unchanged.
87
89
  With piped (non-terminal) stdin, lines read during a turn are queued as later prompts
88
90
  (never steer).
89
91
 
@@ -118,9 +120,7 @@ A steer that arrives too late to join the turn runs as an ordinary prompt, or is
118
120
  answered with `stopReason: "cancelled"` if the turn was cancelled. Slash-command prompts
119
121
  and other requests that arrive mid-turn are handled after the turn ends. Everything
120
122
  handled after the turn, late steers included, runs in the order the client sent it.
121
- `stopReason` is `end_turn`, `cancelled`, or `max_turn_requests`. When the provider reported
122
- token counts, the result also carries ACP's `usage`: `{"inputTokens", "outputTokens", "totalTokens"}`,
123
- summed over the turn's model calls.
123
+ `stopReason` is `end_turn`, `cancelled`, or `max_turn_requests`.
124
124
 
125
125
  **Streaming updates.** During a turn the harness sends `session/update` notifications:
126
126
  `agent_message_chunk` (with a `messageId`), `tool_call` (`toolCallId`, `title` = tool name,
@@ -166,71 +166,75 @@ explicitly (`input doesn't look like ACP JSON-RPC …`).
166
166
  ## Architecture
167
167
 
168
168
  ```
169
- src/
170
- ├── main.rs # Single binary entry point (interactive + ACP modes)
171
- ├── agent.rs # Agent core: conversation management, tool execution loop
172
- ├── acp.rs # ACP JSON-RPC protocol handler
173
- ├── hooks.rs # Internal (observe-only) lifecycle hook registry and events
174
- ├── claude_hooks.rs # External Claude Code–compatible user hooks engine
175
- ├── tools.rs # Tool registration and dispatch system
176
- ├── llm.rs # Provider-neutral messages and the async LLMClient trait
177
- ├── providers/ # Provider registry + presets, HTTP transport with retries
178
- │ ├── openai.rs # OpenAI Chat Completions (and compatible servers)
179
- │ ├── anthropic.rs # Anthropic Messages API
180
- │ ├── github_copilot.rs # UNOFFICIAL Copilot-subscription provider
181
- │ ├── muse.rs # UNOFFICIAL Meta Muse Code provider
182
- │ ├── retry.rs # Retry classification and backoff
183
- │ └── mock.rs # Offline scripted client
184
- ├── bash.rs # bash tool: timeout, file capture, bounded output
185
- ├── files.rs # read_file / write_file / edit_file tools
186
- ├── shell.rs # Bash parser used by the permission checks
187
- ├── permissions.rs # Allow/deny rules and built-in guards against destructive commands
188
- ├── sandbox.rs # Seatbelt (macOS) / Landlock (Linux) sandbox for shell commands
189
- ├── output.rs # Head/tail output bounding, spilling long output to disk
190
- ├── session.rs # Versioned append-only JSONL session log
191
- ├── session_index.rs # Session summaries (.index.jsonl) for the --resume picker
192
- ├── resume.rs # --resume picker, --resume last, --list-sessions
193
- ├── context.rs # Token accounting, context-window heuristics, overflow detection
194
- ├── status.rs # Status bar contents (the frame's last row)
195
- ├── ui.rs # Verbosity levels and the streaming output renderer
196
- ├── frame.rs # App-owned frame renderer: full redraw on resize
197
- ├── lineedit.rs # Key-by-key prompt input (editing, history, mid-turn steer/queue)
198
- ├── input_history.rs # Up/Down recall of submitted lines (session-scoped)
199
- ├── instructions.rs # AGENTS.md / CLAUDE.md discovery for the system prompt
200
- ├── plan.rs # Task plan and the plan_add / plan_update / plan_show tools
201
- ├── queue.rs # The interactive message queue and the /queue editor
202
- ├── goal.rs # report_outcome tool (completed / blocked / needs_input)
203
- ├── memory.rs # Cross-session memory: memory_save / memory_search / memory_forget
204
- ├── mode.rs # Agent mode (normal / plan / auto) and the plan-mode tool gate
205
- ├── question.rs # question tool and the mid-turn question / turn-cap rendezvous
206
- ├── commands.rs # Slash-command table for /help and the as-you-type menu
207
- ├── skills.rs # SKILL.md discovery, ai.lock sources and the load_skill tool
208
- ├── reminders.rs # <system-reminder> notes appended to tool results
209
- ├── settings.rs # /settings menu and config-file writer
210
- └── config.rs # Configuration file loading and management
169
+ source/
170
+ ├── app.d # Single binary entry point (interactive + ACP modes), REPL, key reader
171
+ └── nano/
172
+ ├── agent.d # Agent core: conversation management, tool execution loop
173
+ ├── acp.d # ACP JSON-RPC protocol handler
174
+ ├── claude_hooks.d # External Claude Code–compatible user hooks engine
175
+ ├── llm.d # Provider-neutral messages and the LLMClient interface
176
+ ├── http.d # libcurl transport (streaming, timeouts)
177
+ ├── retry.d # Retry classification and backoff
178
+ ├── providers/ # Provider registry + presets
179
+ │ ├── openai.d # OpenAI Chat Completions (and compatible servers)
180
+ │ ├── responses.d # OpenAI Responses API
181
+ │ ├── anthropic.d # Anthropic Messages API
182
+ │ ├── muse.d # UNOFFICIAL Meta Muse Code provider
183
+ │ ├── mock.d # Offline scripted client
184
+ │ └── demo.d # Offline demo model (`--model demo/demo`)
185
+ ├── copilot.d # UNOFFICIAL Copilot-subscription provider (login, tokens)
186
+ ├── tools/ # Tool registry and the built-in tools
187
+ │ ├── bash.d # bash tool: timeout, file capture, bounded output
188
+ │ ├── files.d # read_file / write_file / edit_file
189
+ │ └── search.d # glob / grep
190
+ ├── shell.d # Bash parser used by the permission checks
191
+ ├── permissions.d, guard.d # Allow/deny rules and built-in guards against destructive commands
192
+ ├── sandbox.d, landlock.d # Seatbelt (macOS) / Landlock (Linux) sandbox for shell commands
193
+ ├── session.d # Versioned append-only JSONL session log
194
+ ├── session_index.d # Session summaries (.index.jsonl) for the --resume picker
195
+ ├── resume.d # --resume picker, --resume last, --list-sessions
196
+ ├── context.d # Token accounting, context-window heuristics, overflow detection
197
+ ├── status.d # Status bar contents (the frame's last row)
198
+ ├── ui.d # Verbosity levels and the streaming output renderer
199
+ ├── frame.d, frameui.d # App-owned frame renderer and its owner thread
200
+ ├── markdown.d, md*.d # Markdown rendering of answers
201
+ ├── lineedit.d # Key-by-key prompt input (editing, history, mid-turn steer/queue)
202
+ ├── control.d # Turn control shared with the key reader: cancel, steers
203
+ ├── instructions.d # AGENTS.md / CLAUDE.md discovery for the system prompt
204
+ ├── plan.d # Task plan and the plan_add / plan_update / plan_show tools
205
+ ├── queue.d # The interactive message queue and the /queue editor
206
+ ├── goal.d # report_outcome tool (completed / blocked / needs_input)
207
+ ├── memory.d # Cross-session memory: memory_save / memory_search / memory_forget
208
+ ├── mode.d # Agent mode (normal / plan / auto) and the plan-mode tool gate
209
+ ├── question.d # question tool and the mid-turn question / turn-cap rendezvous
210
+ ├── commands.d # Slash-command table for /help and the as-you-type menu
211
+ ├── skills.d # SKILL.md discovery, ai.lock sources and the load_skill tool
212
+ ├── reminders.d # <system-reminder> notes appended to tool results
213
+ ├── herdr.d # Herdr state / resume / release reports
214
+ ├── settings.d, settings_dialog.d # /settings menu and config-file writer
215
+ ├── config.d, toml.d, toml_edit.d # Configuration file loading and editing
216
+ └── safeio.d # The audited @trusted wrappers and thread-safe primitives
211
217
  ```
212
218
 
219
+ nano-coder was written in Rust up to 0.69; 1.0 is a rewrite in D. The Rust code is on the
220
+ `rust` branch. `PORTING.md` maps every Rust module to its D counterpart and lists the known
221
+ differences, `REVIEW.md` compares the safety and architecture of the two implementations, and
222
+ `parity/manifest.tsv` records how each Rust test was ported.
223
+
213
224
  Mode selection: `--acp` flag enables ACP headless mode; default is interactive CLI.
214
225
 
215
226
  ## Lifecycle Hooks
216
227
 
217
228
  nano-coder has two hook systems.
218
229
 
219
- ### Internal hooks (observe-only)
220
-
221
- The harness exposes 6 internal lifecycle hook events for in-process Rust
222
- callbacks. These are **observe-only**: a callback can inspect the event payload
223
- (for logging, metrics, debugging) but cannot block, modify, or redirect the
224
- agent. They are registered programmatically against `agent.hooks()`.
230
+ ### Internal events (observe-only)
225
231
 
226
- | Hook | When it fires |
227
- |------|---------------|
228
- | `before_context_load` | Before processing user input |
229
- | `after_context_load` | After adding user message to conversation |
230
- | `before_llm_send` | Before sending messages to LLM |
231
- | `after_llm_response` | After receiving LLM response |
232
- | `before_tool_call` | Before executing a tool |
233
- | `after_tool_call` | After tool execution completes |
232
+ The agent loop reports what it does through the `AgentEvents` interface
233
+ (`nano/agent.d`): streamed text and reasoning, each tool call's start and end, token
234
+ usage, steering messages and complete replies. The CLI and ACP front ends implement it
235
+ to render output; an implementation can also log or collect metrics. These are
236
+ **observe-only**: they cannot block, modify or redirect the agent. (The Rust version's
237
+ six named internal hook events are replaced by this interface.)
234
238
 
235
239
  ### External user hooks (Claude Code–compatible)
236
240
 
@@ -321,9 +325,9 @@ the [permission rules and sandbox](#permissions-and-sandbox) instead.
321
325
 
322
326
  ## Permissions and Sandbox
323
327
 
324
- nano-coder never stops to ask for approval. Every tool call is checked before it runs
325
- instead, and a blocked call returns an error telling the model to stop and ask the user
326
- rather than work around the block.
328
+ nano-coder never stops to ask for approval (it runs headless in agent fleets). Every tool call
329
+ is checked before it runs instead, and a blocked call returns an error telling the model to
330
+ stop and ask the user rather than work around the block.
327
331
 
328
332
  **Order of checks:** `deny` rules, then `allow` rules, then the built-in guards. Deny always
329
333
  wins. An allow rule approves a shell command only when *every* command in it matches, so
@@ -347,23 +351,6 @@ wins. An allow rule approves a shell command only when *every* command in it mat
347
351
  that cannot be parsed, or a script computed at run time (`bash -c "$CMD"`,
348
352
  `eval "$(curl ...)"`), is blocked.
349
353
 
350
- **Shell loops** (`for`/`select`/`while`/`until`) are checked by effect. A loop whose every
351
- condition and body command is provably read-only (`echo`, `grep`, `cat`, `wc`, ...) runs
352
- freely. A `for` loop over a *literal* word list (plain words, quoted strings, brace
353
- expansions — no globs, substitutions or unknown variables) is unrolled: each value is
354
- substituted for the loop variable and every resulting body command is checked exactly as if
355
- written out by hand, so `for q in "a b" "c d"; do gh search repos "$q"; done` is allowed
356
- wherever the two `gh` commands are, and an unrolled command that is denied or catastrophic
357
- is denied. The unroll is capped (64 iterations) and refuses a body that rebinds the loop
358
- variable or still expands something at run time after substitution; those fall through to
359
- the next rule. A loop that still cannot be verified — a non-literal list, or a static body
360
- command that is not a known read-only utility — **runs when the OS sandbox is on** (the
361
- sandbox confines what it can write) and is **blocked** with the usual guidance when it is
362
- off; nano-coder never prompts for it. The hard blocks always stand: a command name computed
363
- at run time, `eval`/interpreters (`sh -c`, `python -c`, ...), path-qualified programs outside
364
- `/bin`/`/usr/bin`, assignments to `PATH`/`IFS` and other dangerous names, arithmetic-assignment
365
- tricks, and writes/redirections to computed targets.
366
-
367
354
  **Built-in guards** (`builtin_rules = true`) block:
368
355
 
369
356
  - recursive `rm` (and `mv`, `find -delete`, `chmod -R`/`chown -R`) on `/`, your home directory
@@ -413,12 +400,11 @@ can fix it. To send a message that starts with `/`, such as a path, type `//`:
413
400
 
414
401
  Typing `/` at the prompt lists the commands under it, and each further character narrows the
415
402
  list. Tab completes the command, or the part all matches share. Esc hides the list. The
416
- list is built from the same table as `/help` (`src/commands.rs`). Commands with a known
403
+ list is built from the same table as `/help` (`nano/commands.d`). Commands with a known
417
404
  argument set (`/model`, `/mode`, `/verbosity`, `/thinking`) get the same treatment for their first
418
405
  argument: a type-ahead list narrows as you type and Tab completes it.
419
406
 
420
407
  - `/help` - Show available commands
421
- - `/version` - Show the nano-coder version (the same string `nano-coder --version` prints)
422
408
  - `/compact [--smart|--standard] [focus]` - Summarize older messages with the current model,
423
409
  keeping the latest message. `--smart` / `--standard` override `compaction_mode` for this
424
410
  compaction (see [Smart compaction](#smart-compaction-experimental)). Optional text tells the
@@ -441,7 +427,6 @@ argument: a type-ahead list narrows as you type and Tab completes it.
441
427
  - `/tools` - List registered tools
442
428
  - `/skills` - List the skills the agent can load, where each lives, and any loading warnings
443
429
  - `/plan` - Show the agent's task plan with all notes
444
- - `/timers` - List the session's timers (the agent schedules them with `timer_set` to come back to you later); shows each timer's id, due time and note (see [Timers](#timers))
445
430
  - `/memory [forget ID]` - List cross-session memories with their ids, or delete one by id (see [Memory](#memory))
446
431
  - `/hooks` - List the loaded external user hooks (from `.claude/settings.json` and friends), the files they came from, and any skipped entries (see [Lifecycle Hooks](#lifecycle-hooks))
447
432
  - `/queue [list|add text|remove N...|edit N text|clear]` - Show or edit the queued messages and unread steers. Works while a turn runs, so a queued message or steer can be removed or rewritten before it is sent.
@@ -456,88 +441,26 @@ argument: a type-ahead list narrows as you type and Tab completes it.
456
441
  - `/trajectory` - Show this session's trajectory turn by turn: user input, thinking, answers, tool calls and results, tokens and timings. Each message row is labelled with its `#N` session-log ID, the same ID `history_read` and smart-compaction summaries use (compaction and crash-recovered input rows have no `#N`, as they aren't cited that way). It opens in your pager (`$PAGER`, default `less`), even when it would fit on the screen, so you dismiss it with `q` and it doesn't stay in the transcript or your scrollback — but only at an idle prompt on a terminal: invoked mid-turn (while a turn runs) or with piped output it prints inline instead. `/trajectory --json` or `/trajectory --markdown` prints an export instead; `nano-coder --trajectory SESSION_ID [--json|--markdown]` does the same for any saved session
457
442
  - `/resume [ID|last]` - Switch to a saved session without restarting: the same picker as `--resume` (leaving out the session in use), or the session with that ID, or `last` (the most recent other session in this directory). Run it at the prompt, not during a turn
458
443
  - `/restart` - Start a fresh session (clean context) without exiting
459
- - `/update` - Install the latest release through the channel nano-coder was installed from (`npm install -g @nanobpm/nano-coder@latest`, `brew upgrade nanobpm/tap/nano-coder` or `cargo install nano-coder`), with the installer's progress on the terminal; verifies the installed version afterwards and leaves the running session untouched on failure. On an install that is not managed by npm, Homebrew or cargo it prints the releases page and changes nothing. Run it at the prompt, not during a turn (see [Updates](#updates))
460
- - `/relaunch` - Restart the binary (re-resolved, so a just-installed update is picked up), resuming the current session — the transcript and scrollback carry over. Works whether or not an update was just installed. An unsent draft or queued messages are confirmed before being discarded. Run it at the prompt, not during a turn (see [Updates](#updates))
461
444
  - `/exit` - Exit the agent (prints the session's `--resume` command first, when session persistence is enabled)
462
445
 
463
- ## Updates
464
-
465
- In an interactive terminal session, nano-coder checks in the background whether a newer
466
- release exists: once at startup (in a background task — the first prompt is never delayed)
467
- and then every hour. The last-check time and the latest-known version are persisted in
468
- `<platform data dir>/nano-coder/update-check.json`, so rapid restarts do not re-check
469
- inside the hour. When a newer version is found, a single non-modal hint per new version is
470
- shown at an idle prompt:
471
-
472
- > nano-coder 0.43.0 is available (you have 0.42.1) — /update to install it
473
-
474
- The check runs only in interactive TTY sessions — never in `-p`/headless, ACP or CI runs
475
- (automated runners use deliberately pinned versions) — and only when the binary is managed
476
- by a known install channel, detected once at startup from the executable's path:
477
-
478
- - **npm** (under a `node_modules/@nanobpm/` tree — both launcher states: the
479
- platform-package binary and the self-replaced copy in `bin/`): the latest version comes
480
- from `https://registry.npmjs.org/@nanobpm/nano-coder/latest`, and `/update` runs
481
- `npm install -g @nanobpm/nano-coder@latest`.
482
- - **Homebrew** (the binary resolves into `<brew prefix>/Cellar/nano-coder/`): the latest
483
- version is the one the [nanobpm/homebrew-tap](https://github.com/nanobpm/homebrew-tap)
484
- formula points at (bumped by the release workflow a few minutes after each release), and
485
- `/update` runs `brew upgrade nanobpm/tap/nano-coder`. `/relaunch` restarts through the
486
- formula's `opt` link, so it finds the new version after brew removes the old one.
487
- - **cargo** (in `$CARGO_HOME/bin`, default `~/.cargo/bin`): the latest version comes from
488
- `https://crates.io/api/v1/crates/nano-coder`, and `/update` runs `cargo install
489
- nano-coder` — which compiles from source and takes minutes, so the installer runs
490
- attached to the terminal with its progress visible and Ctrl-C cancelling it, like a
491
- long bash command.
492
- - **anything else** (standalone tarball, a dev build in `target/`, a distro package): no
493
- background check and no self-modification. `/update` explains that the install is not
494
- managed and points at the
495
- [releases page](https://github.com/nanobpm/nano-coder/releases); a locally built binary
496
- is never overwritten.
497
-
498
- `/update` runs only at an idle prompt. It suspends the frame UI while the installer owns
499
- the terminal, then verifies the result with `nano-coder --version`: on success it suggests
500
- `/relaunch`; on failure it shows the installer's exit status and leaves the running
501
- session untouched. If the channel's tool (`npm`/`cargo`) is not on `PATH`, `/update`
502
- prints the exact manual command instead. If you are already on the latest release (a fresh
503
- check, not the hourly cache), it says so.
504
-
505
- `/relaunch` restarts the harness without losing the session: it re-resolves the binary
506
- (so a just-installed update is picked up), restores the terminal modes, and replaces the
507
- process with the original arguments plus `--resume <current session>`. The session log,
508
- persisted timers and trust decisions live outside the process and carry over; ephemeral
509
- state — session-scoped permission grants and MCP connections — is re-established by the
510
- resume, as with any `--resume`. An unsent draft or queued messages are confirmed before
511
- being discarded. It also works with no update pending, as a "restart the harness, keep
512
- the session" verb (unlike `/restart`, which starts a fresh session with clean context).
513
-
514
- The check fails silently and quickly when the network is unavailable (a short timeout, no
515
- retries, no effect on turn latency). To opt out, either:
516
-
517
- ```toml
518
- # ~/.config/nano-coder/config.toml
519
- check_updates = false
520
- ```
521
-
522
- or set an environment variable — `NANO_CODER_NO_UPDATE_CHECK=1`, or the de-facto standard
523
- `NO_UPDATE_NOTIFIER=1`.
524
-
525
446
  ## Building and Running
526
447
 
448
+ You need [LDC](https://github.com/ldc-developers/ldc) 1.43+ and dub, plus the libcurl
449
+ development headers on Linux.
450
+
527
451
  ```bash
528
- cargo build --release
529
- ./target/release/nano-coder
452
+ dub build -b release # ./nano-coder
453
+ ./nano-coder
530
454
  ```
531
455
 
532
- Or run directly:
456
+ Then, for example:
533
457
 
534
458
  ```bash
535
- cargo run
536
- cargo run -- --model anthropic/claude-sonnet-4-5
537
- cargo run -- --model ollama/qwen2.5:1.5b
538
- cargo run -- --resume sess-20260923T012518-7e7923f8
539
- cargo run -- --resume # pick a session
540
- cargo run -- --resume last # the most recent session in this directory
459
+ nano-coder --model anthropic/claude-sonnet-4-5
460
+ nano-coder --model ollama/qwen2.5:1.5b
461
+ nano-coder --resume sess-20260923T012518-7e7923f8
462
+ nano-coder --resume # pick a session
463
+ nano-coder --resume last # the most recent session in this directory
541
464
  ```
542
465
 
543
466
  **Resuming.** `--resume` without an ID opens a picker of this directory's saved sessions, most
@@ -563,16 +486,15 @@ asks again on the session's next turn.
563
486
 
564
487
  Flags: `--login github-copilot|muse`, `--list-models PROVIDER`, `--trajectory SESSION_ID [--json|--markdown]`, `--acp`, `--model provider/model` (or `AGENTIC_HARNESS_MODEL`), `--resume [SESSION_ID|last]`, `--list-sessions [--all] [--json]`,
565
488
  `--config PATH`, `--verbosity LEVEL` (`-v`), `--sandbox off|workspace|read-only` (or `NANO_CODER_SANDBOX`),
566
- `--allow RULE` and `--deny RULE` (repeatable; added to the config's rules), `--wait-timers`, `--version` (`-V`).
489
+ `--allow RULE` and `--deny RULE` (repeatable; added to the config's rules), `--version` (`-V`).
567
490
 
568
- `--wait-timers` keeps the session alive for scheduled timers (see [Timers](#timers)) after input ends.
569
- In an interactive session the agent already waits at the prompt, but a piped or redirected run exits
570
- once stdin closes — so a run that reads its prompt from a pipe needs `--wait-timers` to keep waiting
571
- for timers set during the turn to come due, fire, and be delivered. Ctrl-C exits the wait.
572
-
573
- Before opening a PR, run `cargo fmt` (style in `rustfmt.toml`), `cargo clippy --all-targets -- -D warnings`
574
- and `cargo test`; CI checks all three. To keep `git blame` past the one-time reformat, run
575
- `git config blame.ignoreRevsFile .git-blame-ignore-revs` once.
491
+ Before opening a PR, run `dub build` and `dub test` (both run `scripts/check-safe.sh`
492
+ first) and D-Scanner (`dub run dscanner -- --styleCheck --config dscanner.ini source`); CI
493
+ checks all three. All code is `@safe`: every module starts with `@safe:`, and calls the
494
+ compiler can't check are wrapped in small, commented `@trusted` functions (shared ones in
495
+ `source/nano/safeio.d`). `check-safe.sh` fails the build on a module without `@safe:`, an
496
+ uncommented `@trusted`, raw threads or `__gshared` outside `safeio.d`, or more `@trusted` than
497
+ the budgets in `scripts/` allow. The build uses `-preview=dip1000` and `-preview=nosharedaccess`.
576
498
 
577
499
  ## Configuration
578
500
 
@@ -592,10 +514,7 @@ session_titles = false # ask the model for a few-word title per
592
514
  # title_model = "openai/gpt-4o-mini" # model for titles (default: the session's model)
593
515
  auto_compact = true # summarize automatically when the context fills up
594
516
  auto_compact_threshold = 0.8 # fraction of the context window
595
- idle_compact = true # already past the threshold? compact at the idle prompt, not on your next message (Esc Esc cancels)
596
- # idle_compact_hold_secs = 180 # how long the prompt (and any draft) must sit untouched first
597
517
  compaction_mode = "standard" # standard | smart (experimental, see Smart compaction)
598
- # compaction_pin_requests = true # re-attach the user's requests verbatim after each summary (issue #66)
599
518
  # context_window = 128000 # override the window (providers can set it too)
600
519
  verbosity = "normal" # quiet | normal | verbose | debug (or --verbosity)
601
520
  timestamps = true # prefix CLI messages with the local time (HH:MM:SS)
@@ -606,12 +525,10 @@ user_rules_dirs = ["~/.claude/rules"]
606
525
  instruction_imports_outside_project = false # let project @imports / rule links leave the repo
607
526
  plan_tools = true # offer the plan_* tools (see Task Plans)
608
527
  outcome_tool = true # offer report_outcome (see Outcomes)
609
- verify_before_complete = true # ask once for the check's evidence when completing after an unchecked edit (see Outcomes)
610
528
  reminders = true # append <system-reminder> notes to tool results
611
529
  memory = "on" # on | read_only | off — cross-session memory (see Memory)
612
530
  # memory_dir = "/path/to/memory" # default: <platform data dir>/nano-coder/memory
613
531
  memory_expiry_days = 90 # expire memories unused this long (0 = never)
614
- check_updates = true # hourly background release check, interactive sessions only (see Updates)
615
532
 
616
533
  [skills] # see Skills
617
534
  enabled = true
@@ -691,7 +608,7 @@ kind = "anthropic"
691
608
  base_url = "https://llm-gateway.example.com/anthropic/v1"
692
609
  api_key_env = "WORK_GATEWAY_KEY" # or api_key = "..." (prefer the env var)
693
610
  # api_key_command = "op read op://vault/gateway/key" # used when the env var is unset
694
- timeout_secs = 300 # idle timeout: max silence between streamed bytes (default 120, or $NANO_CODER_PROVIDER_TIMEOUT_SECS)
611
+ timeout_secs = 300 # idle timeout: max silence between streamed bytes (default 600)
695
612
  max_retries = 3
696
613
  ```
697
614
 
@@ -736,45 +653,6 @@ api_key_env = "BAILIAN_TOKEN_PLAN_API_KEY"
736
653
  as thinking models like K3 require. Set `extra_body = { reasoning_effort = "low" }` to
737
654
  make K3 think less.
738
655
 
739
- #### Regional OpenRouter workspaces and curated model lists
740
-
741
- Some OpenRouter workspaces (e.g. Camunda's) reject the global `openrouter.ai` host, so
742
- the `openrouter` preset fails with them. They accept only the regional hosts
743
- `us.openrouter.ai` and `eu.openrouter.ai`, and each model is served on just one of them.
744
- Three provider settings cover this:
745
-
746
- - `[providers.<name>.models."<model>"]` takes a `base_url`, which overrides the
747
- provider's for that model, and a display `name`.
748
- - `list_models = "configured"` makes `/model`, `--list-models` and `/model` Tab completion
749
- offer only the models configured under `models`, with their names, instead of the
750
- endpoint's whole `/models` catalogue. The default is `"endpoint"`.
751
- - `disabled = true` hides a provider (a preset too) from `/providers`, the pickers and
752
- suggestions. A model spec that names it is an error.
753
-
754
- ```toml
755
- model = "openrouter-camunda/moonshotai/kimi-k3"
756
-
757
- [providers.openrouter]
758
- disabled = true # the global host is rejected
759
-
760
- [providers.openrouter-camunda]
761
- kind = "openai"
762
- base_url = "https://us.openrouter.ai/api/v1"
763
- api_key_env = "OPENROUTER_API_KEY"
764
- list_models = "configured"
765
-
766
- [providers.openrouter-camunda.models."moonshotai/kimi-k3"]
767
- name = "Kimi K3"
768
-
769
- [providers.openrouter-camunda.models."amazon/nova-lite-v1"]
770
- name = "Nova Lite 1.0"
771
- base_url = "https://eu.openrouter.ai/api/v1" # served in the EU only
772
- ```
773
-
774
- [`examples/openrouter-camunda.toml`](examples/openrouter-camunda.toml) is the full
775
- equivalent of the `opencode.json` in Camunda's handbook. A model's `"provider": {"api": …}`
776
- there becomes its `base_url` here.
777
-
778
656
  ### Temperature
779
657
 
780
658
  `temperature` is a number, or `"default"` to send none so the model uses its own default.
@@ -894,34 +772,8 @@ content hash), so session logs stay small and `--resume` still works; a missing
894
772
  resume is sent as a text placeholder.
895
773
 
896
774
  Other per-provider fields: `replay_reasoning`, `max_tokens_param` (`max_tokens`, or `max_completion_tokens`
897
- which is the `openai` default), `retry_initial_backoff_ms`, `retry_max_backoff_ms`,
898
- `retryable_statuses` and `offline_budget_ms`.
899
-
900
- `timeout_secs` is an *idle* timeout: it resets on every received byte, so a slow but steady
901
- stream is never cut off — only a genuinely stalled connection trips it. The default is 120 s
902
- (`NANO_CODER_PROVIDER_TIMEOUT_SECS` overrides the default; an explicit `timeout_secs` wins
903
- over both). When nano-coder runs under a supervisor that idle-kills a silent run — e.g. the
904
- c8ctl-nano worker, which kills a run after 300 s of no output — `timeout_secs` must stay
905
- **below** that budget: at or above it the worker kills the whole run before a stalled stream
906
- is ever detected and retried. A supervising worker can pass its own derived budget (e.g. its
907
- idle-kill budget / 2) as `NANO_CODER_PROVIDER_TIMEOUT_SECS` so the two timeouts cannot drift.
908
-
909
- A transport failure with no HTTP response (DNS, connection refused or reset, connect or
910
- idle timeout) is treated as the network being down rather than a failed attempt: nano-coder
911
- backs off (`retry_initial_backoff_ms` doubling to `retry_max_backoff_ms`) and keeps waiting,
912
- reporting the outage on a single live line (`network unavailable (…); retrying in Ns
913
- (Ctrl-C to stop)`) when stderr is a terminal, or announcing it once when output is piped, so
914
- a long outage never floods the log. When a response finally arrives it announces the
915
- recovery, so a turn survives a laptop sleep, a Wi-Fi change or a VPN reconnect instead of
916
- failing after about a minute. A redirect-policy error (a redirect loop or a disallowed
917
- redirect) is *not* an outage — HTTP is flowing — so it surfaces its actionable error at once
918
- instead of being retried. These waits do not consume `max_retries` (which still bounds
919
- HTTP-status retries like 429 or 5xx), and the Copilot session-token refresh waits the same
920
- way. If a stream drops after it started replying, the partial reply is discarded (nothing
921
- reaches history) and the request is re-sent, up to ten times per model call. The wait is
922
- unbounded by default; set `offline_budget_ms` to give up after that many milliseconds
923
- offline — the budget bounds the whole wait, backoff sleeps included, and no further request
924
- is issued once it is spent.
775
+ which is the `openai` default), `retry_initial_backoff_ms`, `retry_max_backoff_ms` and
776
+ `retryable_statuses`.
925
777
 
926
778
  The old top-level `api_key` / `base_url` still work. They apply to `default_provider`,
927
779
  which becomes `openai` if it was `mock`.
@@ -1116,20 +968,6 @@ another 10% of the window, so a context that can't shrink isn't summarized on ev
1116
968
  If summarizing fails, the older messages are dropped with a note. The session log records
1117
969
  the new conversation, so `--resume` continues from it.
1118
970
 
1119
- After the summary, compaction re-attaches the **user's requests verbatim** (a pinned block,
1120
- `compaction_pin_requests`, on by default). A summary of a summary would otherwise paraphrase
1121
- the user's original words away over repeated compactions; the pinned block is rebuilt from the
1122
- original messages each time, so an exact flag, number or phrase the user stated once survives
1123
- intact. The block is bounded by an allowance derived from the context window (about an eighth
1124
- of it): when a long session's requests outgrow it, the oldest follow-ups are dropped with an
1125
- explicit omission note — the goal and the newest requests are kept — so the pin can never push
1126
- the context past the window. The note names the dropped requests by one covering session-log span
1127
- (`#2-#40`), so however many requests are dropped the note stays a fixed, small size. Hook output appended to a prompt is not pinned as the user's
1128
- words — the user-typed text is recorded separately, so a prompt that itself mentions a
1129
- `<system-reminder>` tag (even at its very start) keeps its whole task in the pin. In smart mode each pinned request is
1130
- labelled with its `#N` log ID, so the full text is
1131
- one `history_read` away.
1132
-
1133
971
  ### Smart compaction (experimental)
1134
972
 
1135
973
  A summary is lossy: whatever it leaves out is gone for the agent, even though the session
@@ -1322,30 +1160,6 @@ the result:
1322
1160
 
1323
1161
  Plan and outcome calls don't count. Set `reminders = false` to turn them off.
1324
1162
 
1325
- ## Timers
1326
-
1327
- The `timer_*` tools let the agent schedule a note to itself to come back to you later — for
1328
- example to check on a long build, or to follow up after a delay. A timer lives only for the
1329
- session (it is written to the session log, so `--resume` restores pending ones).
1330
-
1331
- - `timer_set` - schedule a timer. Give exactly one of `after` (a delay like `30m`, `1h30m`,
1332
- `90s`, `2 hours`, `1.5h`) or `at` (a time like `HH:MM` for the next occurrence, or an ISO
1333
- date-time such as `2026-10-25T14:30`, local unless you append an offset like `+02:00` or `Z`),
1334
- plus a `note` describing what to do when it fires. Up to 10 timers can be active at once.
1335
- - `timer_list` - the session's timers with their ids, due times and notes.
1336
- - `timer_cancel` - drop a timer by `id`.
1337
- - `timer_done` - acknowledge a fired timer by `id` once it is handled.
1338
-
1339
- When a timer comes due it is delivered to the model as an automatic turn. If one fires while a
1340
- turn is already running it is delivered mid-turn; otherwise it starts a fresh automatic turn
1341
- when the session is idle. `/timers` shows the current timers in the terminal.
1342
-
1343
- In an interactive session the agent waits at the prompt, so due timers fire naturally. A piped
1344
- or redirected (non-interactive) run, however, exits as soon as stdin closes — pass
1345
- `--wait-timers` to keep such a run alive after input ends so timers set during the turn can come
1346
- due, fire and be delivered; Ctrl-C exits the wait. The timer tools are available in interactive
1347
- CLI sessions; ACP headless mode has no idle loop to fire them, so they are not offered there.
1348
-
1349
1163
  ## Outcomes
1350
1164
 
1351
1165
  `report_outcome` is the model's explicit end-of-task signal: `status` is `completed` (the
@@ -1360,15 +1174,6 @@ recorded outcome without calling the model again. In the terminal the call shows
1360
1174
  `✔ completed`, `■ blocked`, or `? needs input` followed by the summary. Set `outcome_tool = false` to leave the
1361
1175
  tool out.
1362
1176
 
1363
- A `completed` report is expected to name its check: the `summary` description asks for what was done
1364
- *and how it was checked* (the command run and its result). To back that up, `verify_before_complete`
1365
- (on by default in the terminal) watches the turn: if the model edited a file (`write_file` / `edit_file`)
1366
- after its last `bash` call and then reports `completed`, that one report is bounced with a reminder —
1367
- "You changed files after your last check. Run the relevant tests/build, or report again if no check
1368
- applies." The reminder fires at most once per turn, so a second `report_outcome` always goes through
1369
- and the model is never trapped; `blocked` and `needs_input` are never intercepted. The ACP harness
1370
- turns the flag off because the orchestrator runs its own verification there.
1371
-
1372
1177
  `needs_input` is the structural "waiting on the user" signal: an orchestrator (or auto mode)
1373
1178
  can tell it apart from a clean `completed` without guessing from the text. For a richer,
1374
1179
  multi-choice question that does not end the turn, the model uses the `question` tool instead.
@@ -1397,23 +1202,9 @@ evidence (a file path or command). Search is a case-insensitive regex
1397
1202
  over the text and the optional evidence, as in `history_search` - no embeddings or vector
1398
1203
  store.
1399
1204
 
1400
- **Tools** (offered when `memory` is on): `memory_save(scope, text, evidence?, kind?, anchors?)`,
1205
+ **Tools** (offered when `memory` is on): `memory_save(scope, text, evidence?)`,
1401
1206
  `memory_search(pattern, scope?)`, `memory_forget(id)`.
1402
1207
 
1403
- **Recall from tool calls.** Before relying on the model to search, each tool call's arguments
1404
- are matched (lexically, no model call) against memory *anchors*: backticked spans, path-like
1405
- tokens and host names in the text and evidence (common commands such as `git` are ignored), or
1406
- the entry's explicit `anchors` list, which replaces the extracted ones. A match attaches a
1407
- note to the tool result - `📌 note from an earlier session (verify ...)` with its `check:`
1408
- command and how long ago it was last used. A `hint` (the default `kind`) is recalled once per
1409
- context; a `rule` on every match. At most 2 notes are attached per turn. What has been seen is
1410
- session state (persisted like timers, reset by compaction and new sessions), never stored in
1411
- the memory file, and a `memory_search` result counts as seen. Recall works in read-only
1412
- (headless/ACP) sessions too. Each recall, and each recall later followed by a `memory_search`
1413
- of that memory, is appended to `<memory_dir>/recall.jsonl`; `/memory` shows the counts
1414
- (`recalled N×, used M×`) so over-broad anchors can be spotted. Entries without `kind`/`anchors`
1415
- load unchanged.
1416
-
1417
1208
  **Prompt.** A capped, dated index (most-recently-used first, ~4 KB with the guidance) is
1418
1209
  appended to the system prompt at session start, framed as "notes from earlier sessions; may be
1419
1210
  out of date; verify before relying on them". The rest is reachable with `memory_search`.
@@ -1488,27 +1279,25 @@ properties and findings.
1488
1279
 
1489
1280
  ### Adding Tools
1490
1281
 
1491
- ```rust
1492
- let tool_def = ToolDefinition::new(
1493
- "my_tool",
1494
- "Description of what the tool does",
1495
- json!({ "type": "object", "properties": { ... } })
1496
- );
1497
- agent.tools().register(tool_def, Box::new(|args| {
1498
- // Tool implementation
1499
- Ok(json!({ "result": "..." }))
1500
- }));
1282
+ ```d
1283
+ agent.tools.register(ToolDefinition("my_tool", "Description of what the tool does",
1284
+ parseJSON(`{"type": "object", "properties": { ... }}`)),
1285
+ (JSONValue args) {
1286
+ // Tool implementation; the string is what the model sees.
1287
+ return "result";
1288
+ });
1501
1289
  ```
1502
1290
 
1503
- The model sees a JSON string result as plain text and any other value as serialized JSON.
1291
+ ### Observing the agent
1504
1292
 
1505
- ### Adding internal (observe-only) hooks
1293
+ Pass your own `AgentEvents` to `agent.run`:
1506
1294
 
1507
- ```rust
1508
- agent.hooks().register(HookEvent::BeforeToolCall, Box::new(|ctx| {
1509
- let tool_name = ctx.data.get("tool_name").and_then(|v| v.as_str());
1510
- println!("About to call tool: {}", tool_name);
1511
- }));
1295
+ ```d
1296
+ class Logger : AgentEvents
1297
+ {
1298
+ void toolStart(const ref ToolCall call) { writeln("About to call tool: ", call.name); }
1299
+ // text, toolEnd, usage, userMessage, assistantMessage ...
1300
+ }
1512
1301
  ```
1513
1302
 
1514
1303
  These callbacks observe only; to block, modify, or add context to a tool call
@@ -1517,16 +1306,15 @@ or prompt, use the external Claude-compatible user hooks described under
1517
1306
 
1518
1307
  ### Custom LLM Client
1519
1308
 
1520
- Implement the async `LLMClient` trait (or add a `ProviderKind` in `src/providers/`):
1309
+ Implement the `LLMClient` interface (`nano/llm.d`), or add a provider in `nano/providers/`:
1521
1310
 
1522
- ```rust
1523
- #[async_trait::async_trait]
1524
- impl LLMClient for MyClient {
1525
- async fn chat(&self, request: &ChatRequest<'_>) -> Result<LLMResponse> {
1526
- // request.messages, request.tools, request.temperature, request.max_tokens
1527
- }
1528
- fn model_name(&self) -> &str { "my-model" }
1529
- fn provider_name(&self) -> &str { "mine" }
1311
+ ```d
1312
+ class MyClient : LLMClient
1313
+ {
1314
+ LLMResponse chat(const ref ChatRequest req, StreamSink sink) { /* req.messages, req.tools, ... */ }
1315
+ string[] listModels() { return ["my-model"]; }
1316
+ string modelName() const { return "my-model"; }
1317
+ string providerName() const { return "mine"; }
1530
1318
  }
1531
1319
  ```
1532
1320
 
package/lib/platform.js CHANGED
@@ -11,7 +11,7 @@ const PLATFORMS = {
11
11
  function platformPackage() {
12
12
  const key = `${process.platform}-${process.arch}`;
13
13
  const pkg = PLATFORMS[key];
14
- if (!pkg) throw new Error(`no prebuilt binary for ${key} (supported: ${Object.keys(PLATFORMS).join(', ')}); try \`cargo install nano-coder\``);
14
+ if (!pkg) throw new Error(`no prebuilt binary for ${key} (supported: ${Object.keys(PLATFORMS).join(', ')}); build it from source with \`dub build -b release\` in a checkout of https://github.com/nanobpm/nano-coder`);
15
15
  return pkg;
16
16
  }
17
17
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nanobpm/nano-coder",
3
- "version": "0.68.0",
4
- "description": "A 6MB coding agent. Run a fleet on your laptop.",
3
+ "version": "1.0.0",
4
+ "description": "A 4MB coding agent. Run a fleet on your laptop.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -13,7 +13,8 @@
13
13
  "agent",
14
14
  "coding-agent",
15
15
  "acp",
16
- "cli"
16
+ "cli",
17
+ "dlang"
17
18
  ],
18
19
  "bin": {
19
20
  "nano-coder": "bin/nano-coder"
@@ -27,9 +28,9 @@
27
28
  "node": ">=18"
28
29
  },
29
30
  "optionalDependencies": {
30
- "@nanobpm/nano-coder-darwin-arm64": "0.68.0",
31
- "@nanobpm/nano-coder-darwin-x64": "0.68.0",
32
- "@nanobpm/nano-coder-linux-arm64": "0.68.0",
33
- "@nanobpm/nano-coder-linux-x64": "0.68.0"
31
+ "@nanobpm/nano-coder-darwin-arm64": "1.0.0",
32
+ "@nanobpm/nano-coder-darwin-x64": "1.0.0",
33
+ "@nanobpm/nano-coder-linux-arm64": "1.0.0",
34
+ "@nanobpm/nano-coder-linux-x64": "1.0.0"
34
35
  }
35
36
  }