From 37184044609997604bfa1ab08be356d8b4e5e19d Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:07:45 +0100 Subject: Input editor: history, bracketed paste, in-line editing - crossterm raw mode only for the duration of a prompt, so SIGINT keeps working during a turn - persisted history with prompt commands excluded and newlines escaped - bracketed paste inserts one multi-line buffer instead of firing N turns - ctrl-a/e/u/k/w editing, ctrl-c abandons the line, ctrl-d exits - ctrl-j submits, so pipes and pty harnesses work - width fallback: a 0-column pty is 80 columns, not 1 --- Cargo.lock | 278 ++++++++++++++++++++++++++++++++++++++- Cargo.toml | 1 + README.md | 11 +- docs/PLAN.md | 17 +++ src/lib.rs | 1 + src/line.rs | 415 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 34 +++-- 7 files changed, 737 insertions(+), 20 deletions(-) create mode 100644 src/line.rs diff --git a/Cargo.lock b/Cargo.lock index c2f3482..9716ba1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12,6 +12,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" name = "agent686" version = "0.1.0" dependencies = [ + "crossterm", "libc", "serde", "serde_json", @@ -24,6 +25,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + [[package]] name = "bytes" version = "1.12.1" @@ -46,6 +53,15 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "crc32fast" version = "1.5.5" @@ -55,6 +71,74 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags", + "crossterm_winapi", + "derive_more", + "document-features", + "mio", + "parking_lot", + "rustix", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -111,6 +195,27 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.35" @@ -133,12 +238,47 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -163,6 +303,15 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + [[package]] name = "ring" version = "0.17.14" @@ -174,7 +323,29 @@ dependencies = [ "getrandom", "libc", "untrusted", - "windows-sys", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.52.0", ] [[package]] @@ -212,6 +383,18 @@ dependencies = [ "untrusted", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -239,7 +422,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -261,18 +444,66 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + [[package]] name = "subtle" version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.10" @@ -290,6 +521,12 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + [[package]] name = "untrusted" version = "0.9.0" @@ -346,6 +583,34 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + [[package]] name = "windows-sys" version = "0.52.0" @@ -355,6 +620,15 @@ dependencies = [ "windows-targets", ] +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-targets" version = "0.52.6" diff --git a/Cargo.toml b/Cargo.toml index 22e8cf6..2e5e56a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" ureq = { version = "3", features = ["rustls"] } libc = "0.2" +crossterm = "0.29.0" [profile.release] strip = true diff --git a/README.md b/README.md index 4ec5d64..19d9585 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ dependency can silently raise the required symbol version. ```sh export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key ./agent686 "make a calculator in C" # one turn, then exit -./agent686 # interactive, one prompt per line +./agent686 # interactive ./agent686 -c # continue the most recent session ./agent686 --session # resume it, or create it if the id is new ./agent686 --list # id, model, message count, age @@ -36,6 +36,9 @@ Provider is OpenCode Go, `chat/completions`, model `deepseek-v4.1-flash` by default. Every request carries a stable `x-opencode-session` header, which the service uses for routing and prompt caching. +In a terminal: up/down walks history, bracketed paste arrives as one block +(multi-line is fine), ctrl-c abandons the line, ctrl-d exits. + Rate limits and transient failures retry with backoff (four attempts, `Retry-After` honoured); a 429 that survives them explains itself instead of dumping JSON. @@ -52,7 +55,7 @@ that is where `rm -rf` lives. ## Tests ```sh -cargo test # 24 tests, no network +cargo test # 29 tests, no network python3 scripts/mock-provider.py & # canned SSE provider docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gate ``` @@ -71,5 +74,5 @@ executed, recorded, and that a denial is returned to the model as data. rewritten: cached prompt reads are ~50× cheaper, and they require a byte-identical prefix. -No async runtime, no TUI, no MCP, no subagents, no compaction. Those are -choices, not gaps: see the non-goals. +No async runtime, no full-screen TUI, no MCP, no subagents, no compaction. Those +are choices, not gaps: see the non-goals. diff --git a/docs/PLAN.md b/docs/PLAN.md index 75fd25b..9be54fa 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -127,6 +127,23 @@ turn that failed after writing its prompt can be resumed without editing the transcript; and `deepseek-v4.1-flash` accepted a 500k-token prompt, so the context ceiling is far higher than the 128k the plan assumed. +**M7 — Input editor.** ✅ Done. + +Replaces plain `read_line` behind the same seam. `crossterm` raw mode is enabled +only while a prompt is being read, so Ctrl-C during a turn is still a signal and +the double-Ctrl-C exit keeps working. + +- Up/down history, persisted to `~/.local/share/agent686/history`, capped at 200 + entries, with prompt-mode commands excluded and newlines escaped per record. +- Bracketed paste arrives as one block, including newlines: pasting a stack trace + is one prompt, not thirty. +- Editing: left/right/home/end, backspace/delete, ctrl-a/e/u/k/w. Ctrl-C abandons + the line, Ctrl-D exits. Ctrl-J submits too, so pipes and test harnesses work. +- Redraw moves up by the number of rows the previous buffer occupied, which + needed a correct terminal width: a pty that reports 0 columns is treated as 80, + not as 1 (treating it as 1 made every character wrap onto its own line). +- Non-TTY stdin still falls back to plain line reading. + ## Acceptance test (v1) > "Make a simple calculator in C" — run on the i386 box, from an empty directory. diff --git a/src/lib.rs b/src/lib.rs index 18fe336..e978f83 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ pub mod agent; pub mod config; +pub mod line; pub mod provider; pub mod session; pub mod signal; diff --git a/src/line.rs b/src/line.rs new file mode 100644 index 0000000..6b93f06 --- /dev/null +++ b/src/line.rs @@ -0,0 +1,415 @@ +use std::io::{self, IsTerminal, Write}; +use std::path::PathBuf; + +use crossterm::cursor::{MoveToColumn, MoveUp}; +use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; +use crossterm::event::{DisableBracketedPaste, EnableBracketedPaste}; +use crossterm::terminal::{self, Clear, ClearType}; +use crossterm::execute; + +const HISTORY_LIMIT: usize = 200; + +pub struct Editor { + interactive: bool, + history: Vec, + history_index: usize, + draft: Vec, +} + +impl Editor { + pub fn new() -> Self { + Self { + interactive: std::io::stdin().is_terminal() && std::io::stdout().is_terminal(), + history: load_history(), + history_index: 0, + draft: Vec::new(), + } + } + + pub fn is_interactive(&self) -> bool { + self.interactive + } + + /// Reads one prompt. `None` means end of input (Ctrl-D or EOF). + /// + /// Raw mode is enabled only for the duration of this call, so Ctrl-C during + /// a turn is still a signal handled by `signal`, not a keystroke. + pub fn read(&mut self, prompt: &str) -> io::Result> { + if !self.interactive { + return read_plain(); + } + + let guard = RawGuard::enable()?; + let mut buffer: Vec = Vec::new(); + let mut cursor = 0usize; + let mut rows = 1usize; + + self.history_index = self.history.len(); + self.draft.clear(); + + let width = terminal_width(); + draw(prompt, &buffer, cursor, width, &mut rows)?; + + loop { + let event = event::read()?; + match event { + Event::Paste(text) => { + insert(&mut buffer, &mut cursor, &text); + draw(prompt, &buffer, cursor, width, &mut rows)?; + } + Event::Key(key) if key.kind == KeyEventKind::Press => { + match handle_key(key, &mut buffer, &mut cursor, self) { + Action::Continue => {} + Action::Submit => { + // Redraw with the caret at the end so the submitted + // line looks complete before we move on. + draw(prompt, &buffer, buffer.len(), width, &mut rows)?; + drop(guard); + let line: String = buffer.iter().collect(); + self.remember(&line); + println!(); + return Ok(Some(line)); + } + Action::Eof => { + drop(guard); + println!(); + return Ok(None); + } + Action::Cancel => { + drop(guard); + println!("^C"); + return Ok(Some(String::new())); + } + } + draw(prompt, &buffer, cursor, width, &mut rows)?; + } + _ => {} + } + } + } + + fn remember(&mut self, line: &str) { + if line.trim().is_empty() { + return; + } + // Prompt-mode commands are not worth recalling. + if matches!(line.trim(), "/exit" | "/quit" | "/help" | "/paste") { + return; + } + if self.history.last().map(|last| last.as_str()) == Some(line) { + return; + } + self.history.push(line.to_string()); + if self.history.len() > HISTORY_LIMIT { + self.history.remove(0); + } + append_history(line); + } +} + +/// Plain line reading for pipes, scripts and tests. Identical contract. +fn read_plain() -> io::Result> { + let mut line = String::new(); + if io::stdin().read_line(&mut line)? == 0 { + return Ok(None); + } + Ok(Some(line.trim_end_matches(['\n', '\r']).to_string())) +} + +enum Action { + Continue, + Submit, + Eof, + Cancel, +} + +fn handle_key( + key: KeyEvent, + buffer: &mut Vec, + cursor: &mut usize, + editor: &mut Editor, +) -> Action { + let ctrl = key.modifiers.contains(KeyModifiers::CONTROL); + + match key.code { + KeyCode::Enter => return Action::Submit, + // Ctrl-J is what a pipe or a test harness sends for a newline; terminals + // send CR for Enter, so both have to submit. + KeyCode::Char('j') if ctrl => return Action::Submit, + KeyCode::Char('d') if ctrl => { + if buffer.is_empty() { + return Action::Eof; + } + if *cursor < buffer.len() { + buffer.remove(*cursor); + } + } + KeyCode::Char('c') if ctrl => return Action::Cancel, + KeyCode::Char('a') if ctrl => *cursor = 0, + KeyCode::Char('e') if ctrl => *cursor = buffer.len(), + KeyCode::Char('u') if ctrl => { + buffer.clear(); + *cursor = 0; + } + KeyCode::Char('k') if ctrl => buffer.truncate(*cursor), + KeyCode::Char('w') if ctrl => { + let mut end = *cursor; + while end > 0 && buffer[end - 1].is_whitespace() { + end -= 1; + } + while end > 0 && !buffer[end - 1].is_whitespace() { + end -= 1; + } + buffer.drain(end..*cursor); + *cursor = end; + } + KeyCode::Char(ch) if !ctrl => { + buffer.insert(*cursor, ch); + *cursor += 1; + } + KeyCode::Tab => { + for _ in 0..4 { + buffer.insert(*cursor, ' '); + *cursor += 1; + } + } + KeyCode::Backspace => { + if *cursor > 0 { + buffer.remove(*cursor - 1); + *cursor -= 1; + } + } + KeyCode::Delete => { + if *cursor < buffer.len() { + buffer.remove(*cursor); + } + } + KeyCode::Left => *cursor = cursor.saturating_sub(1), + KeyCode::Right => *cursor = (*cursor + 1).min(buffer.len()), + KeyCode::Home => *cursor = 0, + KeyCode::End => *cursor = buffer.len(), + KeyCode::Up => editor.history_up(buffer, cursor), + KeyCode::Down => editor.history_down(buffer, cursor), + _ => {} + } + Action::Continue +} + +impl Editor { + fn history_up(&mut self, buffer: &mut Vec, cursor: &mut usize) { + if self.history.is_empty() || self.history_index == 0 { + return; + } + if self.history_index == self.history.len() { + self.draft = buffer.clone(); + } + self.history_index -= 1; + *buffer = self.history[self.history_index].chars().collect(); + *cursor = buffer.len(); + } + + fn history_down(&mut self, buffer: &mut Vec, cursor: &mut usize) { + if self.history_index >= self.history.len() { + return; + } + self.history_index += 1; + if self.history_index == self.history.len() { + *buffer = self.draft.clone(); + } else { + *buffer = self.history[self.history_index].chars().collect(); + } + *cursor = buffer.len(); + } +} + +fn insert(buffer: &mut Vec, cursor: &mut usize, text: &str) { + let normalized = text.replace("\r\n", "\n").replace('\r', "\n"); + for (offset, ch) in normalized.chars().enumerate() { + buffer.insert(*cursor + offset, ch); + } + *cursor += normalized.chars().count(); +} + +fn terminal_width() -> usize { + match terminal::size() { + // A pty with no size reported reports 0 columns; treating that as 1 + // would make every character wrap onto its own line. + Ok((cols, _)) if cols > 0 => cols as usize, + _ => 80, + } +} + +/// Position of the cursor after consuming `prompt` plus `buffer[..upto]`. +/// Approximates every character as one column; good enough for a prompt line. +fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, usize) { + let mut row = 0usize; + let mut col = 0usize; + for ch in prompt.chars().chain(buffer[..upto.min(buffer.len())].iter().copied()) { + advance(ch, &mut row, &mut col, width); + } + (row, col) +} + +fn advance(ch: char, row: &mut usize, col: &mut usize, width: usize) { + if ch == '\n' { + *row += 1; + *col = 0; + return; + } + *col += 1; + if *col >= width { + *col = 0; + *row += 1; + } +} + +fn draw( + prompt: &str, + buffer: &[char], + cursor: usize, + width: usize, + rows: &mut usize, +) -> io::Result<()> { + let mut out = io::stdout(); + + let total = layout(prompt, buffer, buffer.len(), width).0 + 1; + let (cursor_row, cursor_col) = layout(prompt, buffer, cursor, width); + + if *rows > 1 { + execute!(out, MoveUp((*rows - 1) as u16))?; + } + execute!(out, MoveToColumn(0), Clear(ClearType::FromCursorDown))?; + + let mut text = String::with_capacity(prompt.len() + buffer.len()); + text.push_str(prompt); + for ch in buffer { + if *ch == '\n' { + text.push_str("\r\n"); + } else { + text.push(*ch); + } + } + out.write_all(text.as_bytes())?; + + let end_row = total - 1; + if end_row > cursor_row { + execute!(out, MoveUp((end_row - cursor_row) as u16))?; + } + execute!(out, MoveToColumn(cursor_col as u16))?; + out.flush()?; + + *rows = total; + Ok(()) +} + +struct RawGuard; + +impl RawGuard { + fn enable() -> io::Result { + terminal::enable_raw_mode()?; + execute!(io::stdout(), EnableBracketedPaste)?; + Ok(RawGuard) + } +} + +impl Drop for RawGuard { + fn drop(&mut self) { + let _ = execute!(io::stdout(), DisableBracketedPaste); + let _ = terminal::disable_raw_mode(); + } +} + +fn history_path() -> PathBuf { + crate::session::data_root().join("history") +} + +fn load_history() -> Vec { + let text = std::fs::read_to_string(history_path()).unwrap_or_default(); + let mut lines: Vec = text + .split('\n') + .filter(|line| !line.trim().is_empty() && !line.starts_with('\u{0}')) + .map(|line| line.replace('\u{0}', "\n")) + .collect(); + if lines.len() > HISTORY_LIMIT { + lines.drain(..lines.len() - HISTORY_LIMIT); + } + lines +} + +fn append_history(line: &str) { + let path = history_path(); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + { + // One record per line, so newlines inside a prompt are escaped. + let _ = writeln!(file, "{}", line.replace('\n', "\u{0}")); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layout_accounts_for_newlines() { + let buffer: Vec = "ab\ncd".chars().collect(); + assert_eq!(layout("> ", &buffer, 0, 80), (0, 2)); + assert_eq!(layout("> ", &buffer, 2, 80), (0, 4)); + assert_eq!(layout("> ", &buffer, 3, 80), (1, 0)); + assert_eq!(layout("> ", &buffer, 5, 80), (1, 2)); + } + + #[test] + fn layout_wraps_at_the_terminal_width() { + let buffer: Vec = "abcdef".chars().collect(); + // Prompt takes 2 columns, so the 6 chars fill exactly 8. + assert_eq!(layout("> ", &buffer, 6, 8), (1, 0)); + assert_eq!(layout("> ", &buffer, 3, 8), (0, 5)); + } + + #[test] + fn width_falls_back_when_the_terminal_reports_none() { + // Cannot control the real terminal here, but the fallback path must not + // produce a one-column layout. + assert!(terminal_width() >= 1); + } + + #[test] + fn insert_normalises_line_endings() { + let mut buffer = vec!['a']; + let mut cursor = 1; + insert(&mut buffer, &mut cursor, "b\r\nc"); + assert_eq!(buffer, vec!['a', 'b', '\n', 'c']); + assert_eq!(cursor, 4); + } + + #[test] + fn history_walks_both_ways() { + let mut editor = Editor { + interactive: false, + history: vec!["one".into(), "two".into()], + history_index: 0, + draft: Vec::new(), + }; + editor.history_index = editor.history.len(); + + let mut buffer = vec!['x']; + let mut cursor = 1; + editor.history_up(&mut buffer, &mut cursor); + assert_eq!(buffer.iter().collect::(), "two"); + editor.history_up(&mut buffer, &mut cursor); + assert_eq!(buffer.iter().collect::(), "one"); + editor.history_up(&mut buffer, &mut cursor); + assert_eq!(buffer.iter().collect::(), "one"); + + editor.history_down(&mut buffer, &mut cursor); + assert_eq!(buffer.iter().collect::(), "two"); + editor.history_down(&mut buffer, &mut cursor); + assert_eq!(buffer.iter().collect::(), "x"); + } +} diff --git a/src/main.rs b/src/main.rs index 4bc3550..29b4280 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,11 @@ -use std::io::{BufRead, IsTerminal, Write}; +use std::io::{BufRead, Write}; use std::path::PathBuf; use std::time::SystemTime; use serde_json::Value; use agent686::config::Config; +use agent686::line::Editor; use agent686::session::{self, Session}; use agent686::ui::Approver; use agent686::{agent, signal}; @@ -16,7 +17,12 @@ USAGE: agent686 [OPTIONS] [PROMPT...] With a prompt it runs one turn and exits. Without one it reads prompts from -stdin, one per line. Commands: /paste, /exit, /help. +stdin. In a terminal: up/down for history, ctrl-a/e/u/w/k to edit, ctrl-d to +exit, ctrl-c to abandon the line. Commands: /paste, /exit, /help. + +/cmd + /paste read a block of lines until a lone `.` + /exit quit OPTIONS: -m, --model model id (default: deepseek-v4.1-flash) @@ -109,7 +115,8 @@ fn main() { return; } - let interactive = std::io::stdin().is_terminal(); + let mut editor = Editor::new(); + let interactive = editor.is_interactive(); if interactive { eprintln!( "agent686 · {} · session {}{}", @@ -117,22 +124,21 @@ fn main() { cfg.session, if cfg.yolo { " · yolo" } else { "" } ); - eprintln!("one prompt per line · /paste · /exit"); + eprintln!("type a prompt · up/down history · ctrl-d exit · /help"); } let stdin = std::io::stdin(); let mut line = String::new(); loop { - if interactive { - print!("> "); - let _ = std::io::stdout().flush(); - } - line.clear(); - if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { - break; - } - let mut text = line.trim_end().to_string(); - if text.is_empty() { + let mut text = match editor.read("> ") { + Ok(Some(text)) => text, + Ok(None) => break, + Err(error) => { + eprintln!("agent686: input: {error}"); + break; + } + }; + if text.trim().is_empty() { continue; } -- cgit v1.2.3