aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorsalmonik <salmonik@tuta.io>2026-11-15 15:07:45 +0100
committersalmonik <salmonik@tuta.io>2026-11-15 15:07:45 +0100
commit37184044609997604bfa1ab08be356d8b4e5e19d (patch)
treeb6e33c9b3d8d8fa0b51ecced4d154f4d63bf4534
parentdocs: correct the context-window assumption in ADR 0002 (diff)
downloadagent686-37184044609997604bfa1ab08be356d8b4e5e19d.tar.gz
agent686-37184044609997604bfa1ab08be356d8b4e5e19d.zip
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
Diffstat (limited to '')
-rw-r--r--Cargo.lock278
-rw-r--r--Cargo.toml1
-rw-r--r--README.md11
-rw-r--r--docs/PLAN.md17
-rw-r--r--src/lib.rs1
-rw-r--r--src/line.rs415
-rw-r--r--src/main.rs34
7 files changed, 737 insertions, 20 deletions
diff --git a/Cargo.lock b/Cargo.lock
index c2f3482..9716ba1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -12,6 +12,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
12name = "agent686" 12name = "agent686"
13version = "0.1.0" 13version = "0.1.0"
14dependencies = [ 14dependencies = [
15 "crossterm",
15 "libc", 16 "libc",
16 "serde", 17 "serde",
17 "serde_json", 18 "serde_json",
@@ -25,6 +26,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
25checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" 26checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
26 27
27[[package]] 28[[package]]
29name = "bitflags"
30version = "2.13.2"
31source = "registry+https://github.com/rust-lang/crates.io-index"
32checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
33
34[[package]]
28name = "bytes" 35name = "bytes"
29version = "1.12.1" 36version = "1.12.1"
30source = "registry+https://github.com/rust-lang/crates.io-index" 37source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -47,6 +54,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
47checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" 54checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
48 55
49[[package]] 56[[package]]
57name = "convert_case"
58version = "0.10.0"
59source = "registry+https://github.com/rust-lang/crates.io-index"
60checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
61dependencies = [
62 "unicode-segmentation",
63]
64
65[[package]]
50name = "crc32fast" 66name = "crc32fast"
51version = "1.5.5" 67version = "1.5.5"
52source = "registry+https://github.com/rust-lang/crates.io-index" 68source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -56,6 +72,74 @@ dependencies = [
56] 72]
57 73
58[[package]] 74[[package]]
75name = "crossterm"
76version = "0.29.0"
77source = "registry+https://github.com/rust-lang/crates.io-index"
78checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
79dependencies = [
80 "bitflags",
81 "crossterm_winapi",
82 "derive_more",
83 "document-features",
84 "mio",
85 "parking_lot",
86 "rustix",
87 "signal-hook",
88 "signal-hook-mio",
89 "winapi",
90]
91
92[[package]]
93name = "crossterm_winapi"
94version = "0.9.1"
95source = "registry+https://github.com/rust-lang/crates.io-index"
96checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
97dependencies = [
98 "winapi",
99]
100
101[[package]]
102name = "derive_more"
103version = "2.1.1"
104source = "registry+https://github.com/rust-lang/crates.io-index"
105checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
106dependencies = [
107 "derive_more-impl",
108]
109
110[[package]]
111name = "derive_more-impl"
112version = "2.1.1"
113source = "registry+https://github.com/rust-lang/crates.io-index"
114checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
115dependencies = [
116 "convert_case",
117 "proc-macro2",
118 "quote",
119 "rustc_version",
120 "syn 2.0.119",
121]
122
123[[package]]
124name = "document-features"
125version = "0.2.12"
126source = "registry+https://github.com/rust-lang/crates.io-index"
127checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
128dependencies = [
129 "litrs",
130]
131
132[[package]]
133name = "errno"
134version = "0.3.15"
135source = "registry+https://github.com/rust-lang/crates.io-index"
136checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
137dependencies = [
138 "libc",
139 "windows-sys 0.52.0",
140]
141
142[[package]]
59name = "find-msvc-tools" 143name = "find-msvc-tools"
60version = "0.1.15" 144version = "0.1.15"
61source = "registry+https://github.com/rust-lang/crates.io-index" 145source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -112,6 +196,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
112checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" 196checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
113 197
114[[package]] 198[[package]]
199name = "linux-raw-sys"
200version = "0.12.1"
201source = "registry+https://github.com/rust-lang/crates.io-index"
202checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
203
204[[package]]
205name = "litrs"
206version = "1.0.1"
207source = "registry+https://github.com/rust-lang/crates.io-index"
208checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70"
209
210[[package]]
211name = "lock_api"
212version = "0.4.14"
213source = "registry+https://github.com/rust-lang/crates.io-index"
214checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
215dependencies = [
216 "scopeguard",
217]
218
219[[package]]
115name = "log" 220name = "log"
116version = "0.4.35" 221version = "0.4.35"
117source = "registry+https://github.com/rust-lang/crates.io-index" 222source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -134,12 +239,47 @@ dependencies = [
134] 239]
135 240
136[[package]] 241[[package]]
242name = "mio"
243version = "1.2.5"
244source = "registry+https://github.com/rust-lang/crates.io-index"
245checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
246dependencies = [
247 "libc",
248 "log",
249 "wasi",
250 "windows-sys 0.61.2",
251]
252
253[[package]]
137name = "once_cell" 254name = "once_cell"
138version = "1.21.4" 255version = "1.21.4"
139source = "registry+https://github.com/rust-lang/crates.io-index" 256source = "registry+https://github.com/rust-lang/crates.io-index"
140checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" 257checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
141 258
142[[package]] 259[[package]]
260name = "parking_lot"
261version = "0.12.5"
262source = "registry+https://github.com/rust-lang/crates.io-index"
263checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
264dependencies = [
265 "lock_api",
266 "parking_lot_core",
267]
268
269[[package]]
270name = "parking_lot_core"
271version = "0.9.12"
272source = "registry+https://github.com/rust-lang/crates.io-index"
273checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
274dependencies = [
275 "cfg-if",
276 "libc",
277 "redox_syscall",
278 "smallvec",
279 "windows-link",
280]
281
282[[package]]
143name = "percent-encoding" 283name = "percent-encoding"
144version = "2.3.2" 284version = "2.3.2"
145source = "registry+https://github.com/rust-lang/crates.io-index" 285source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -164,6 +304,15 @@ dependencies = [
164] 304]
165 305
166[[package]] 306[[package]]
307name = "redox_syscall"
308version = "0.5.18"
309source = "registry+https://github.com/rust-lang/crates.io-index"
310checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
311dependencies = [
312 "bitflags",
313]
314
315[[package]]
167name = "ring" 316name = "ring"
168version = "0.17.14" 317version = "0.17.14"
169source = "registry+https://github.com/rust-lang/crates.io-index" 318source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -174,7 +323,29 @@ dependencies = [
174 "getrandom", 323 "getrandom",
175 "libc", 324 "libc",
176 "untrusted", 325 "untrusted",
177 "windows-sys", 326 "windows-sys 0.52.0",
327]
328
329[[package]]
330name = "rustc_version"
331version = "0.4.1"
332source = "registry+https://github.com/rust-lang/crates.io-index"
333checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
334dependencies = [
335 "semver",
336]
337
338[[package]]
339name = "rustix"
340version = "1.1.6"
341source = "registry+https://github.com/rust-lang/crates.io-index"
342checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
343dependencies = [
344 "bitflags",
345 "errno",
346 "libc",
347 "linux-raw-sys",
348 "windows-sys 0.52.0",
178] 349]
179 350
180[[package]] 351[[package]]
@@ -213,6 +384,18 @@ dependencies = [
213] 384]
214 385
215[[package]] 386[[package]]
387name = "scopeguard"
388version = "1.2.0"
389source = "registry+https://github.com/rust-lang/crates.io-index"
390checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
391
392[[package]]
393name = "semver"
394version = "1.0.28"
395source = "registry+https://github.com/rust-lang/crates.io-index"
396checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
397
398[[package]]
216name = "serde" 399name = "serde"
217version = "1.0.229" 400version = "1.0.229"
218source = "registry+https://github.com/rust-lang/crates.io-index" 401source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -239,7 +422,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
239dependencies = [ 422dependencies = [
240 "proc-macro2", 423 "proc-macro2",
241 "quote", 424 "quote",
242 "syn", 425 "syn 3.0.10",
243] 426]
244 427
245[[package]] 428[[package]]
@@ -262,12 +445,49 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
262checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" 445checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
263 446
264[[package]] 447[[package]]
448name = "signal-hook"
449version = "0.3.18"
450source = "registry+https://github.com/rust-lang/crates.io-index"
451checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
452dependencies = [
453 "libc",
454 "signal-hook-registry",
455]
456
457[[package]]
458name = "signal-hook-mio"
459version = "0.2.5"
460source = "registry+https://github.com/rust-lang/crates.io-index"
461checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
462dependencies = [
463 "libc",
464 "mio",
465 "signal-hook",
466]
467
468[[package]]
469name = "signal-hook-registry"
470version = "1.4.8"
471source = "registry+https://github.com/rust-lang/crates.io-index"
472checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
473dependencies = [
474 "errno",
475 "libc",
476]
477
478[[package]]
265name = "simd-adler32" 479name = "simd-adler32"
266version = "0.3.10" 480version = "0.3.10"
267source = "registry+https://github.com/rust-lang/crates.io-index" 481source = "registry+https://github.com/rust-lang/crates.io-index"
268checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" 482checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
269 483
270[[package]] 484[[package]]
485name = "smallvec"
486version = "1.16.5"
487source = "registry+https://github.com/rust-lang/crates.io-index"
488checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
489
490[[package]]
271name = "subtle" 491name = "subtle"
272version = "2.6.1" 492version = "2.6.1"
273source = "registry+https://github.com/rust-lang/crates.io-index" 493source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -275,6 +495,17 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
275 495
276[[package]] 496[[package]]
277name = "syn" 497name = "syn"
498version = "2.0.119"
499source = "registry+https://github.com/rust-lang/crates.io-index"
500checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
501dependencies = [
502 "proc-macro2",
503 "quote",
504 "unicode-ident",
505]
506
507[[package]]
508name = "syn"
278version = "3.0.10" 509version = "3.0.10"
279source = "registry+https://github.com/rust-lang/crates.io-index" 510source = "registry+https://github.com/rust-lang/crates.io-index"
280checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" 511checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
@@ -291,6 +522,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
291checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" 522checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
292 523
293[[package]] 524[[package]]
525name = "unicode-segmentation"
526version = "1.13.3"
527source = "registry+https://github.com/rust-lang/crates.io-index"
528checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
529
530[[package]]
294name = "untrusted" 531name = "untrusted"
295version = "0.9.0" 532version = "0.9.0"
296source = "registry+https://github.com/rust-lang/crates.io-index" 533source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -347,6 +584,34 @@ dependencies = [
347] 584]
348 585
349[[package]] 586[[package]]
587name = "winapi"
588version = "0.3.9"
589source = "registry+https://github.com/rust-lang/crates.io-index"
590checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
591dependencies = [
592 "winapi-i686-pc-windows-gnu",
593 "winapi-x86_64-pc-windows-gnu",
594]
595
596[[package]]
597name = "winapi-i686-pc-windows-gnu"
598version = "0.4.0"
599source = "registry+https://github.com/rust-lang/crates.io-index"
600checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
601
602[[package]]
603name = "winapi-x86_64-pc-windows-gnu"
604version = "0.4.0"
605source = "registry+https://github.com/rust-lang/crates.io-index"
606checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
607
608[[package]]
609name = "windows-link"
610version = "0.2.1"
611source = "registry+https://github.com/rust-lang/crates.io-index"
612checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
613
614[[package]]
350name = "windows-sys" 615name = "windows-sys"
351version = "0.52.0" 616version = "0.52.0"
352source = "registry+https://github.com/rust-lang/crates.io-index" 617source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -356,6 +621,15 @@ dependencies = [
356] 621]
357 622
358[[package]] 623[[package]]
624name = "windows-sys"
625version = "0.61.2"
626source = "registry+https://github.com/rust-lang/crates.io-index"
627checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
628dependencies = [
629 "windows-link",
630]
631
632[[package]]
359name = "windows-targets" 633name = "windows-targets"
360version = "0.52.6" 634version = "0.52.6"
361source = "registry+https://github.com/rust-lang/crates.io-index" 635source = "registry+https://github.com/rust-lang/crates.io-index"
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"] }
10serde_json = "1" 10serde_json = "1"
11ureq = { version = "3", features = ["rustls"] } 11ureq = { version = "3", features = ["rustls"] }
12libc = "0.2" 12libc = "0.2"
13crossterm = "0.29.0"
13 14
14[profile.release] 15[profile.release]
15strip = true 16strip = 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.
25```sh 25```sh
26export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key 26export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key
27./agent686 "make a calculator in C" # one turn, then exit 27./agent686 "make a calculator in C" # one turn, then exit
28./agent686 # interactive, one prompt per line 28./agent686 # interactive
29./agent686 -c # continue the most recent session 29./agent686 -c # continue the most recent session
30./agent686 --session <id> # resume it, or create it if the id is new 30./agent686 --session <id> # resume it, or create it if the id is new
31./agent686 --list # id, model, message count, age 31./agent686 --list # id, model, message count, age
@@ -36,6 +36,9 @@ Provider is OpenCode Go, `chat/completions`, model `deepseek-v4.1-flash` by
36default. Every request carries a stable `x-opencode-session` header, which the 36default. Every request carries a stable `x-opencode-session` header, which the
37service uses for routing and prompt caching. 37service uses for routing and prompt caching.
38 38
39In a terminal: up/down walks history, bracketed paste arrives as one block
40(multi-line is fine), ctrl-c abandons the line, ctrl-d exits.
41
39Rate limits and transient failures retry with backoff (four attempts, `Retry-After` 42Rate limits and transient failures retry with backoff (four attempts, `Retry-After`
40honoured); a 429 that survives them explains itself instead of dumping JSON. 43honoured); a 429 that survives them explains itself instead of dumping JSON.
41 44
@@ -52,7 +55,7 @@ that is where `rm -rf` lives.
52## Tests 55## Tests
53 56
54```sh 57```sh
55cargo test # 24 tests, no network 58cargo test # 29 tests, no network
56python3 scripts/mock-provider.py & # canned SSE provider 59python3 scripts/mock-provider.py & # canned SSE provider
57docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gate 60docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gate
58``` 61```
@@ -71,5 +74,5 @@ executed, recorded, and that a denial is returned to the model as data.
71 rewritten: cached prompt reads are ~50× cheaper, and they require a 74 rewritten: cached prompt reads are ~50× cheaper, and they require a
72 byte-identical prefix. 75 byte-identical prefix.
73 76
74No async runtime, no TUI, no MCP, no subagents, no compaction. Those are 77No async runtime, no full-screen TUI, no MCP, no subagents, no compaction. Those
75choices, not gaps: see the non-goals. 78are 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
127transcript; and `deepseek-v4.1-flash` accepted a 500k-token prompt, so the 127transcript; and `deepseek-v4.1-flash` accepted a 500k-token prompt, so the
128context ceiling is far higher than the 128k the plan assumed. 128context ceiling is far higher than the 128k the plan assumed.
129 129
130**M7 — Input editor.** ✅ Done.
131
132Replaces plain `read_line` behind the same seam. `crossterm` raw mode is enabled
133only while a prompt is being read, so Ctrl-C during a turn is still a signal and
134the double-Ctrl-C exit keeps working.
135
136- Up/down history, persisted to `~/.local/share/agent686/history`, capped at 200
137 entries, with prompt-mode commands excluded and newlines escaped per record.
138- Bracketed paste arrives as one block, including newlines: pasting a stack trace
139 is one prompt, not thirty.
140- Editing: left/right/home/end, backspace/delete, ctrl-a/e/u/k/w. Ctrl-C abandons
141 the line, Ctrl-D exits. Ctrl-J submits too, so pipes and test harnesses work.
142- Redraw moves up by the number of rows the previous buffer occupied, which
143 needed a correct terminal width: a pty that reports 0 columns is treated as 80,
144 not as 1 (treating it as 1 made every character wrap onto its own line).
145- Non-TTY stdin still falls back to plain line reading.
146
130## Acceptance test (v1) 147## Acceptance test (v1)
131 148
132> "Make a simple calculator in C" — run on the i386 box, from an empty directory. 149> "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 @@
1pub mod agent; 1pub mod agent;
2pub mod config; 2pub mod config;
3pub mod line;
3pub mod provider; 4pub mod provider;
4pub mod session; 5pub mod session;
5pub mod signal; 6pub 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 @@
1use std::io::{self, IsTerminal, Write};
2use std::path::PathBuf;
3
4use crossterm::cursor::{MoveToColumn, MoveUp};
5use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
6use crossterm::event::{DisableBracketedPaste, EnableBracketedPaste};
7use crossterm::terminal::{self, Clear, ClearType};
8use crossterm::execute;
9
10const HISTORY_LIMIT: usize = 200;
11
12pub struct Editor {
13 interactive: bool,
14 history: Vec<String>,
15 history_index: usize,
16 draft: Vec<char>,
17}
18
19impl Editor {
20 pub fn new() -> Self {
21 Self {
22 interactive: std::io::stdin().is_terminal() && std::io::stdout().is_terminal(),
23 history: load_history(),
24 history_index: 0,
25 draft: Vec::new(),
26 }
27 }
28
29 pub fn is_interactive(&self) -> bool {
30 self.interactive
31 }
32
33 /// Reads one prompt. `None` means end of input (Ctrl-D or EOF).
34 ///
35 /// Raw mode is enabled only for the duration of this call, so Ctrl-C during
36 /// a turn is still a signal handled by `signal`, not a keystroke.
37 pub fn read(&mut self, prompt: &str) -> io::Result<Option<String>> {
38 if !self.interactive {
39 return read_plain();
40 }
41
42 let guard = RawGuard::enable()?;
43 let mut buffer: Vec<char> = Vec::new();
44 let mut cursor = 0usize;
45 let mut rows = 1usize;
46
47 self.history_index = self.history.len();
48 self.draft.clear();
49
50 let width = terminal_width();
51 draw(prompt, &buffer, cursor, width, &mut rows)?;
52
53 loop {
54 let event = event::read()?;
55 match event {
56 Event::Paste(text) => {
57 insert(&mut buffer, &mut cursor, &text);
58 draw(prompt, &buffer, cursor, width, &mut rows)?;
59 }
60 Event::Key(key) if key.kind == KeyEventKind::Press => {
61 match handle_key(key, &mut buffer, &mut cursor, self) {
62 Action::Continue => {}
63 Action::Submit => {
64 // Redraw with the caret at the end so the submitted
65 // line looks complete before we move on.
66 draw(prompt, &buffer, buffer.len(), width, &mut rows)?;
67 drop(guard);
68 let line: String = buffer.iter().collect();
69 self.remember(&line);
70 println!();
71 return Ok(Some(line));
72 }
73 Action::Eof => {
74 drop(guard);
75 println!();
76 return Ok(None);
77 }
78 Action::Cancel => {
79 drop(guard);
80 println!("^C");
81 return Ok(Some(String::new()));
82 }
83 }
84 draw(prompt, &buffer, cursor, width, &mut rows)?;
85 }
86 _ => {}
87 }
88 }
89 }
90
91 fn remember(&mut self, line: &str) {
92 if line.trim().is_empty() {
93 return;
94 }
95 // Prompt-mode commands are not worth recalling.
96 if matches!(line.trim(), "/exit" | "/quit" | "/help" | "/paste") {
97 return;
98 }
99 if self.history.last().map(|last| last.as_str()) == Some(line) {
100 return;
101 }
102 self.history.push(line.to_string());
103 if self.history.len() > HISTORY_LIMIT {
104 self.history.remove(0);
105 }
106 append_history(line);
107 }
108}
109
110/// Plain line reading for pipes, scripts and tests. Identical contract.
111fn read_plain() -> io::Result<Option<String>> {
112 let mut line = String::new();
113 if io::stdin().read_line(&mut line)? == 0 {
114 return Ok(None);
115 }
116 Ok(Some(line.trim_end_matches(['\n', '\r']).to_string()))
117}
118
119enum Action {
120 Continue,
121 Submit,
122 Eof,
123 Cancel,
124}
125
126fn handle_key(
127 key: KeyEvent,
128 buffer: &mut Vec<char>,
129 cursor: &mut usize,
130 editor: &mut Editor,
131) -> Action {
132 let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
133
134 match key.code {
135 KeyCode::Enter => return Action::Submit,
136 // Ctrl-J is what a pipe or a test harness sends for a newline; terminals
137 // send CR for Enter, so both have to submit.
138 KeyCode::Char('j') if ctrl => return Action::Submit,
139 KeyCode::Char('d') if ctrl => {
140 if buffer.is_empty() {
141 return Action::Eof;
142 }
143 if *cursor < buffer.len() {
144 buffer.remove(*cursor);
145 }
146 }
147 KeyCode::Char('c') if ctrl => return Action::Cancel,
148 KeyCode::Char('a') if ctrl => *cursor = 0,
149 KeyCode::Char('e') if ctrl => *cursor = buffer.len(),
150 KeyCode::Char('u') if ctrl => {
151 buffer.clear();
152 *cursor = 0;
153 }
154 KeyCode::Char('k') if ctrl => buffer.truncate(*cursor),
155 KeyCode::Char('w') if ctrl => {
156 let mut end = *cursor;
157 while end > 0 && buffer[end - 1].is_whitespace() {
158 end -= 1;
159 }
160 while end > 0 && !buffer[end - 1].is_whitespace() {
161 end -= 1;
162 }
163 buffer.drain(end..*cursor);
164 *cursor = end;
165 }
166 KeyCode::Char(ch) if !ctrl => {
167 buffer.insert(*cursor, ch);
168 *cursor += 1;
169 }
170 KeyCode::Tab => {
171 for _ in 0..4 {
172 buffer.insert(*cursor, ' ');
173 *cursor += 1;
174 }
175 }
176 KeyCode::Backspace => {
177 if *cursor > 0 {
178 buffer.remove(*cursor - 1);
179 *cursor -= 1;
180 }
181 }
182 KeyCode::Delete => {
183 if *cursor < buffer.len() {
184 buffer.remove(*cursor);
185 }
186 }
187 KeyCode::Left => *cursor = cursor.saturating_sub(1),
188 KeyCode::Right => *cursor = (*cursor + 1).min(buffer.len()),
189 KeyCode::Home => *cursor = 0,
190 KeyCode::End => *cursor = buffer.len(),
191 KeyCode::Up => editor.history_up(buffer, cursor),
192 KeyCode::Down => editor.history_down(buffer, cursor),
193 _ => {}
194 }
195 Action::Continue
196}
197
198impl Editor {
199 fn history_up(&mut self, buffer: &mut Vec<char>, cursor: &mut usize) {
200 if self.history.is_empty() || self.history_index == 0 {
201 return;
202 }
203 if self.history_index == self.history.len() {
204 self.draft = buffer.clone();
205 }
206 self.history_index -= 1;
207 *buffer = self.history[self.history_index].chars().collect();
208 *cursor = buffer.len();
209 }
210
211 fn history_down(&mut self, buffer: &mut Vec<char>, cursor: &mut usize) {
212 if self.history_index >= self.history.len() {
213 return;
214 }
215 self.history_index += 1;
216 if self.history_index == self.history.len() {
217 *buffer = self.draft.clone();
218 } else {
219 *buffer = self.history[self.history_index].chars().collect();
220 }
221 *cursor = buffer.len();
222 }
223}
224
225fn insert(buffer: &mut Vec<char>, cursor: &mut usize, text: &str) {
226 let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
227 for (offset, ch) in normalized.chars().enumerate() {
228 buffer.insert(*cursor + offset, ch);
229 }
230 *cursor += normalized.chars().count();
231}
232
233fn terminal_width() -> usize {
234 match terminal::size() {
235 // A pty with no size reported reports 0 columns; treating that as 1
236 // would make every character wrap onto its own line.
237 Ok((cols, _)) if cols > 0 => cols as usize,
238 _ => 80,
239 }
240}
241
242/// Position of the cursor after consuming `prompt` plus `buffer[..upto]`.
243/// Approximates every character as one column; good enough for a prompt line.
244fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, usize) {
245 let mut row = 0usize;
246 let mut col = 0usize;
247 for ch in prompt.chars().chain(buffer[..upto.min(buffer.len())].iter().copied()) {
248 advance(ch, &mut row, &mut col, width);
249 }
250 (row, col)
251}
252
253fn advance(ch: char, row: &mut usize, col: &mut usize, width: usize) {
254 if ch == '\n' {
255 *row += 1;
256 *col = 0;
257 return;
258 }
259 *col += 1;
260 if *col >= width {
261 *col = 0;
262 *row += 1;
263 }
264}
265
266fn draw(
267 prompt: &str,
268 buffer: &[char],
269 cursor: usize,
270 width: usize,
271 rows: &mut usize,
272) -> io::Result<()> {
273 let mut out = io::stdout();
274
275 let total = layout(prompt, buffer, buffer.len(), width).0 + 1;
276 let (cursor_row, cursor_col) = layout(prompt, buffer, cursor, width);
277
278 if *rows > 1 {
279 execute!(out, MoveUp((*rows - 1) as u16))?;
280 }
281 execute!(out, MoveToColumn(0), Clear(ClearType::FromCursorDown))?;
282
283 let mut text = String::with_capacity(prompt.len() + buffer.len());
284 text.push_str(prompt);
285 for ch in buffer {
286 if *ch == '\n' {
287 text.push_str("\r\n");
288 } else {
289 text.push(*ch);
290 }
291 }
292 out.write_all(text.as_bytes())?;
293
294 let end_row = total - 1;
295 if end_row > cursor_row {
296 execute!(out, MoveUp((end_row - cursor_row) as u16))?;
297 }
298 execute!(out, MoveToColumn(cursor_col as u16))?;
299 out.flush()?;
300
301 *rows = total;
302 Ok(())
303}
304
305struct RawGuard;
306
307impl RawGuard {
308 fn enable() -> io::Result<Self> {
309 terminal::enable_raw_mode()?;
310 execute!(io::stdout(), EnableBracketedPaste)?;
311 Ok(RawGuard)
312 }
313}
314
315impl Drop for RawGuard {
316 fn drop(&mut self) {
317 let _ = execute!(io::stdout(), DisableBracketedPaste);
318 let _ = terminal::disable_raw_mode();
319 }
320}
321
322fn history_path() -> PathBuf {
323 crate::session::data_root().join("history")
324}
325
326fn load_history() -> Vec<String> {
327 let text = std::fs::read_to_string(history_path()).unwrap_or_default();
328 let mut lines: Vec<String> = text
329 .split('\n')
330 .filter(|line| !line.trim().is_empty() && !line.starts_with('\u{0}'))
331 .map(|line| line.replace('\u{0}', "\n"))
332 .collect();
333 if lines.len() > HISTORY_LIMIT {
334 lines.drain(..lines.len() - HISTORY_LIMIT);
335 }
336 lines
337}
338
339fn append_history(line: &str) {
340 let path = history_path();
341 if let Some(parent) = path.parent() {
342 let _ = std::fs::create_dir_all(parent);
343 }
344 if let Ok(mut file) = std::fs::OpenOptions::new()
345 .create(true)
346 .append(true)
347 .open(&path)
348 {
349 // One record per line, so newlines inside a prompt are escaped.
350 let _ = writeln!(file, "{}", line.replace('\n', "\u{0}"));
351 }
352}
353
354#[cfg(test)]
355mod tests {
356 use super::*;
357
358 #[test]
359 fn layout_accounts_for_newlines() {
360 let buffer: Vec<char> = "ab\ncd".chars().collect();
361 assert_eq!(layout("> ", &buffer, 0, 80), (0, 2));
362 assert_eq!(layout("> ", &buffer, 2, 80), (0, 4));
363 assert_eq!(layout("> ", &buffer, 3, 80), (1, 0));
364 assert_eq!(layout("> ", &buffer, 5, 80), (1, 2));
365 }
366
367 #[test]
368 fn layout_wraps_at_the_terminal_width() {
369 let buffer: Vec<char> = "abcdef".chars().collect();
370 // Prompt takes 2 columns, so the 6 chars fill exactly 8.
371 assert_eq!(layout("> ", &buffer, 6, 8), (1, 0));
372 assert_eq!(layout("> ", &buffer, 3, 8), (0, 5));
373 }
374
375 #[test]
376 fn width_falls_back_when_the_terminal_reports_none() {
377 // Cannot control the real terminal here, but the fallback path must not
378 // produce a one-column layout.
379 assert!(terminal_width() >= 1);
380 }
381
382 #[test]
383 fn insert_normalises_line_endings() {
384 let mut buffer = vec!['a'];
385 let mut cursor = 1;
386 insert(&mut buffer, &mut cursor, "b\r\nc");
387 assert_eq!(buffer, vec!['a', 'b', '\n', 'c']);
388 assert_eq!(cursor, 4);
389 }
390
391 #[test]
392 fn history_walks_both_ways() {
393 let mut editor = Editor {
394 interactive: false,
395 history: vec!["one".into(), "two".into()],
396 history_index: 0,
397 draft: Vec::new(),
398 };
399 editor.history_index = editor.history.len();
400
401 let mut buffer = vec!['x'];
402 let mut cursor = 1;
403 editor.history_up(&mut buffer, &mut cursor);
404 assert_eq!(buffer.iter().collect::<String>(), "two");
405 editor.history_up(&mut buffer, &mut cursor);
406 assert_eq!(buffer.iter().collect::<String>(), "one");
407 editor.history_up(&mut buffer, &mut cursor);
408 assert_eq!(buffer.iter().collect::<String>(), "one");
409
410 editor.history_down(&mut buffer, &mut cursor);
411 assert_eq!(buffer.iter().collect::<String>(), "two");
412 editor.history_down(&mut buffer, &mut cursor);
413 assert_eq!(buffer.iter().collect::<String>(), "x");
414 }
415}
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 @@
1use std::io::{BufRead, IsTerminal, Write}; 1use std::io::{BufRead, Write};
2use std::path::PathBuf; 2use std::path::PathBuf;
3use std::time::SystemTime; 3use std::time::SystemTime;
4 4
5use serde_json::Value; 5use serde_json::Value;
6 6
7use agent686::config::Config; 7use agent686::config::Config;
8use agent686::line::Editor;
8use agent686::session::{self, Session}; 9use agent686::session::{self, Session};
9use agent686::ui::Approver; 10use agent686::ui::Approver;
10use agent686::{agent, signal}; 11use agent686::{agent, signal};
@@ -16,7 +17,12 @@ USAGE:
16 agent686 [OPTIONS] [PROMPT...] 17 agent686 [OPTIONS] [PROMPT...]
17 18
18With a prompt it runs one turn and exits. Without one it reads prompts from 19With a prompt it runs one turn and exits. Without one it reads prompts from
19stdin, one per line. Commands: /paste, /exit, /help. 20stdin. In a terminal: up/down for history, ctrl-a/e/u/w/k to edit, ctrl-d to
21exit, ctrl-c to abandon the line. Commands: /paste, /exit, /help.
22
23/cmd
24 /paste read a block of lines until a lone `.`
25 /exit quit
20 26
21OPTIONS: 27OPTIONS:
22 -m, --model <ID> model id (default: deepseek-v4.1-flash) 28 -m, --model <ID> model id (default: deepseek-v4.1-flash)
@@ -109,7 +115,8 @@ fn main() {
109 return; 115 return;
110 } 116 }
111 117
112 let interactive = std::io::stdin().is_terminal(); 118 let mut editor = Editor::new();
119 let interactive = editor.is_interactive();
113 if interactive { 120 if interactive {
114 eprintln!( 121 eprintln!(
115 "agent686 · {} · session {}{}", 122 "agent686 · {} · session {}{}",
@@ -117,22 +124,21 @@ fn main() {
117 cfg.session, 124 cfg.session,
118 if cfg.yolo { " · yolo" } else { "" } 125 if cfg.yolo { " · yolo" } else { "" }
119 ); 126 );
120 eprintln!("one prompt per line · /paste · /exit"); 127 eprintln!("type a prompt · up/down history · ctrl-d exit · /help");
121 } 128 }
122 129
123 let stdin = std::io::stdin(); 130 let stdin = std::io::stdin();
124 let mut line = String::new(); 131 let mut line = String::new();
125 loop { 132 loop {
126 if interactive { 133 let mut text = match editor.read("> ") {
127 print!("> "); 134 Ok(Some(text)) => text,
128 let _ = std::io::stdout().flush(); 135 Ok(None) => break,
129 } 136 Err(error) => {
130 line.clear(); 137 eprintln!("agent686: input: {error}");
131 if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { 138 break;
132 break; 139 }
133 } 140 };
134 let mut text = line.trim_end().to_string(); 141 if text.trim().is_empty() {
135 if text.is_empty() {
136 continue; 142 continue;
137 } 143 }
138 144