diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 93803db..ce576dc 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -12,3 +12,4 @@ jobs: - run: cargo clippy --workspace --all-targets -- -D warnings - run: cargo test --workspace - run: cargo build && sh tests/e2e.sh + - run: python3 tests/tui_smoke.py diff --git a/Cargo.lock b/Cargo.lock index 84b9765..46a1a8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,21 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "anstream" version = "1.0.0" @@ -58,6 +73,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -69,12 +93,27 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "atomic" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" +dependencies = [ + "bytemuck", +] + [[package]] name = "atomic-waker" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "aws-lc-rs" version = "1.18.1" @@ -98,18 +137,54 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64" version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bit-set" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block-buffer" version = "0.12.1" @@ -135,12 +210,33 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cc" version = "1.5.1" @@ -172,8 +268,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cpufeatures", - "rand_core", + "cpufeatures 0.3.1", + "rand_core 0.10.1", ] [[package]] @@ -241,12 +337,35 @@ dependencies = [ "memchr", ] +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + [[package]] name = "const-oid" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[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 = "core-foundation" version = "0.10.1" @@ -263,6 +382,15 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -272,6 +400,75 @@ dependencies = [ "libc", ] +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags 2.13.2", + "crossterm_winapi", + "derive_more", + "document-features", + "futures-core", + "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 = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "crypto-common" version = "0.2.2" @@ -281,15 +478,103 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "csscolorparser" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2a7d3066da2de787b7f032c736763eb7ae5d355f81a68bab2675a96008b0bf" +dependencies = [ + "lab", + "phf", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.6", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "deltae" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4" + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[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 = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + [[package]] name = "digest" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer", + "block-buffer 0.12.1", "const-oid", - "crypto-common", + "crypto-common 0.2.2", ] [[package]] @@ -303,12 +588,27 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "dunce" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + [[package]] name = "equivalent" version = "1.0.2" @@ -325,6 +625,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + [[package]] name = "eventsource-stream" version = "0.2.3" @@ -336,24 +645,63 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fancy-regex" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b95f7c0680e4142284cf8b22c14a476e87d61b004a3a0861872b32ef7ead40a2" +dependencies = [ + "bit-set", + "regex", +] + [[package]] name = "fastrand" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "finl_unicode" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bb028c8b4148c9ee0cca68fcd9add6044e81d3619f48577ddf13a263d047a2" + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -457,6 +805,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -470,6 +828,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -479,11 +849,24 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", - "rand_core", + "r-efi 6.0.0", + "rand_core 0.10.1", "wasm-bindgen", ] +[[package]] +name = "globset" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + [[package]] name = "h2" version = "0.4.19" @@ -503,11 +886,27 @@ dependencies = [ "tracing", ] +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] [[package]] name = "heck" @@ -515,6 +914,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "http" version = "1.5.0" @@ -559,15 +964,15 @@ name = "hx-ai" version = "0.1.0" dependencies = [ "async-trait", - "base64", + "base64 0.23.1", "eventsource-stream", "futures", "getrandom 0.4.3", "reqwest", "serde", "serde_json", - "sha2", - "thiserror", + "sha2 0.11.0", + "thiserror 2.0.21", "tokio", ] @@ -581,7 +986,10 @@ dependencies = [ "hx-ai", "hx-core", "hx-tools", + "hx-tui", + "serde", "tokio", + "toml", ] [[package]] @@ -594,7 +1002,7 @@ dependencies = [ "serde", "serde_json", "tempfile", - "thiserror", + "thiserror 2.0.21", "tokio", ] @@ -611,7 +1019,7 @@ name = "hx-tools" version = "0.1.0" dependencies = [ "async-trait", - "base64", + "base64 0.23.1", "hx-ai", "hx-core", "serde_json", @@ -623,6 +1031,17 @@ dependencies = [ [[package]] name = "hx-tui" version = "0.1.0" +dependencies = [ + "async-trait", + "crossterm", + "futures", + "hx-ai", + "hx-core", + "ignore", + "ratatui", + "serde_json", + "tokio", +] [[package]] name = "hybrid-array" @@ -675,7 +1094,7 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "futures-channel", "futures-util", @@ -776,6 +1195,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -797,6 +1222,22 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "ignore" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b69833ed729dc5aa7d19541d96d6cf8e9137194207a04916d658e43168402f" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata", + "same-file", + "walkdir", + "winapi-util", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -804,7 +1245,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.17.1", +] + +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.6", ] [[package]] @@ -819,6 +1282,15 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -837,7 +1309,7 @@ dependencies = [ "jni-sys", "log", "simd_cesu8", - "thiserror", + "thiserror 2.0.21", "walkdir", "windows-link", ] @@ -895,12 +1367,50 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "kasuari" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899" +dependencies = [ + "hashbrown 0.16.1", + "portable-atomic", + "thiserror 2.0.21", +] + +[[package]] +name = "lab" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf36173d4167ed999940f804952e6b08197cae5ad5d572eb4db150ce8ad5d58f" + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + [[package]] name = "libc" version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "line-clipping" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -913,24 +1423,73 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "litrs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + +[[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.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown 0.17.1", +] + [[package]] name = "lru-slab" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "mac_address" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0aeb26bf5e836cc1c341c8106051b573f1766dfa05aa87f0b98be5e51b02303" +dependencies = [ + "nix", + "winapi", +] + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memmem" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64a92489e2744ce060c349162be1c5f33c6969234104dbd99ddb5feb08b8c15" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -944,10 +1503,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" dependencies = [ "libc", + "log", "wasi", "windows-sys 0.61.2", ] +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + [[package]] name = "nom" version = "7.1.3" @@ -958,6 +1531,41 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_threads" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" +dependencies = [ + "libc", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -976,12 +1584,171 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "ordered-float" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951" +dependencies = [ + "num-traits", +] + +[[package]] +name = "palette" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" +dependencies = [ + "approx", + "libm", + "palette_derive", + "palette_math", +] + +[[package]] +name = "palette_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be" +dependencies = [ + "by_address", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "palette_math" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" +dependencies = [ + "libm", +] + +[[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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pest" +version = "2.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45d3aca230fad2e6f6317ca0a72724338c4960cb97168a85cdee66df4a9a21a8" +dependencies = [ + "memchr", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "284b60557f2c4a2e72ad3f2d34d42685a2fa4a6a61d0d2a10c0ae2a5e916c2cf" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9d1f08a115309ee99268cf85e5228e0e56aa9caf8841ec12866b6be07c3109" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pest_meta" +version = "2.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed93ba1a9ffcca32130a5188701c81c0c49cf00d4b7c5007d5148951d743adcb" +dependencies = [ + "pest", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand 0.8.8", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -994,6 +1761,12 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + [[package]] name = "potential_utf" version = "0.1.6" @@ -1003,6 +1776,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -1026,7 +1805,7 @@ dependencies = [ "rustc-hash", "rustls", "socket2", - "thiserror", + "thiserror 2.0.21", "tokio", "tracing", "web-time", @@ -1042,14 +1821,14 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand", + "rand 0.10.3", "rand_pcg", "ring", "rustc-hash", "rustls", "rustls-pki-types", "slab", - "thiserror", + "thiserror 2.0.21", "tinyvec", "tracing", "web-time", @@ -1078,12 +1857,27 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.10.3" @@ -1092,9 +1886,15 @@ checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", "getrandom 0.4.3", - "rand_core", + "rand_core 0.10.1", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + [[package]] name = "rand_core" version = "0.10.1" @@ -1107,16 +1907,155 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" dependencies = [ - "rand_core", + "rand_core 0.10.1", ] +[[package]] +name = "ratatui" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d" +dependencies = [ + "instability", + "ratatui-core", + "ratatui-crossterm", + "ratatui-macros", + "ratatui-termina", + "ratatui-termwiz", + "ratatui-widgets", + "serde", +] + +[[package]] +name = "ratatui-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" +dependencies = [ + "bitflags 2.13.2", + "compact_str", + "critical-section", + "hashbrown 0.17.1", + "itertools", + "kasuari", + "lru", + "palette", + "serde", + "strum", + "thiserror 2.0.21", + "unicode-segmentation", + "unicode-truncate", + "unicode-width", +] + +[[package]] +name = "ratatui-crossterm" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" +dependencies = [ + "cfg-if", + "crossterm", + "instability", + "ratatui-core", +] + +[[package]] +name = "ratatui-macros" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed7dc68daa7498a43e4d68e0eb078427e10c38fbcfbb1e42d955f1fa2140d814" +dependencies = [ + "ratatui-core", + "ratatui-widgets", +] + +[[package]] +name = "ratatui-termina" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0bf912d9e66f057a759d92e386a280ea886b352ab757d6ac4d653c7ed2c43c2" +dependencies = [ + "instability", + "ratatui-core", + "termina", +] + +[[package]] +name = "ratatui-termwiz" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf03e0380b7744054d6cb74224fe3adf062a029754933f575ca1e3b4c2ce977" +dependencies = [ + "ratatui-core", + "termwiz", +] + +[[package]] +name = "ratatui-widgets" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1" +dependencies = [ + "bitflags 2.13.2", + "hashbrown 0.17.1", + "indoc", + "instability", + "itertools", + "line-clipping", + "ratatui-core", + "serde", + "strum", + "time", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "reqwest" version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "futures-core", "futures-util", @@ -1187,7 +2126,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", @@ -1299,13 +2238,19 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "security-framework" version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "core-foundation", "core-foundation-sys", "libc", @@ -1371,6 +2316,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -1383,6 +2337,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha2" version = "0.11.0" @@ -1390,8 +2355,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -1400,6 +2365,27 @@ 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" @@ -1435,6 +2421,12 @@ dependencies = [ "bstr", ] +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + [[package]] name = "slab" version = "0.4.12" @@ -1463,18 +2455,56 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "subtle" version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "2.0.119" @@ -1530,13 +2560,109 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "termina" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9048a889effe34a5cddee0af7f53285198b16dca3be510858d38dfdb3e62a04e" +dependencies = [ + "bitflags 2.13.2", + "parking_lot", + "rustix", + "signal-hook", + "windows-sys 0.61.2", +] + +[[package]] +name = "terminfo" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ea810f0692f9f51b382fff5893887bb4580f5fa246fde546e0b13e7fcee662" +dependencies = [ + "fnv", + "nom", + "phf", + "phf_codegen", +] + +[[package]] +name = "termios" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411c5bf740737c7918b8b1fe232dca4dc9f8e754b8ad5e20966814001ed0ac6b" +dependencies = [ + "libc", +] + +[[package]] +name = "termwiz" +version = "0.23.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4676b37242ccbd1aabf56edb093a4827dc49086c0ffd764a5705899e0f35f8f7" +dependencies = [ + "anyhow", + "base64 0.22.1", + "bitflags 2.13.2", + "fancy-regex", + "filedescriptor", + "finl_unicode", + "fixedbitset", + "hex", + "lazy_static", + "libc", + "log", + "memmem", + "nix", + "num-derive", + "num-traits", + "ordered-float", + "pest", + "pest_derive", + "phf", + "sha2 0.10.9", + "signal-hook", + "siphasher", + "terminfo", + "termios", + "thiserror 1.0.69", + "ucd-trie", + "unicode-segmentation", + "vtparse", + "wezterm-bidi", + "wezterm-blob-leases", + "wezterm-color-types", + "wezterm-dynamic", + "wezterm-input-types", + "winapi", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -1550,6 +2676,27 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + [[package]] name = "tinystr" version = "0.8.4" @@ -1617,6 +2764,45 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + [[package]] name = "tower" version = "0.5.3" @@ -1638,7 +2824,7 @@ version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags", + "bitflags 2.13.2", "bytes", "futures-util", "http", @@ -1693,12 +2879,41 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + [[package]] name = "unicode-ident" version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + [[package]] name = "untrusted" version = "0.9.0" @@ -1729,6 +2944,33 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "atomic", + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vtparse" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9b2acfb050df409c972a37d3b8e08cdea3bddb0c09db9d53137e504cfabed0" +dependencies = [ + "utf8parse", +] + [[package]] name = "walkdir" version = "2.5.0" @@ -1754,6 +2996,15 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -1852,6 +3103,94 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "wezterm-bidi" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0a6e355560527dd2d1cf7890652f4f09bb3433b6aadade4c9b5ed76de5f3ec" +dependencies = [ + "log", + "wezterm-dynamic", +] + +[[package]] +name = "wezterm-blob-leases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "692daff6d93d94e29e4114544ef6d5c942a7ed998b37abdc19b17136ea428eb7" +dependencies = [ + "getrandom 0.3.4", + "mac_address", + "sha2 0.10.9", + "thiserror 1.0.69", + "uuid", +] + +[[package]] +name = "wezterm-color-types" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7de81ef35c9010270d63772bebef2f2d6d1f2d20a983d27505ac850b8c4b4296" +dependencies = [ + "csscolorparser", + "deltae", + "lazy_static", + "wezterm-dynamic", +] + +[[package]] +name = "wezterm-dynamic" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f2ab60e120fd6eaa68d9567f3226e876684639d22a4219b313ff69ec0ccd5ac" +dependencies = [ + "log", + "ordered-float", + "strsim", + "thiserror 1.0.69", + "wezterm-dynamic-derive", +] + +[[package]] +name = "wezterm-dynamic-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c0cf2d539c645b448eaffec9ec494b8b19bd5077d9e58cb1ae7efece8d575b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "wezterm-input-types" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7012add459f951456ec9d6c7e6fc340b1ce15d6fc9629f8c42853412c029e57e" +dependencies = [ + "bitflags 1.3.2", + "euclid", + "lazy_static", + "serde", + "wezterm-dynamic", +] + +[[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-util" version = "0.1.11" @@ -1861,6 +3200,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[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" @@ -1949,6 +3294,18 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.4" diff --git a/README.md b/README.md index d364cde..499d172 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,25 @@ Minimal Rust coding agent. Uses your existing subscriptions, no API keys. cargo build --release hx login claude # Claude Pro/Max hx login codex # ChatGPT Plus/Pro -hx -p "hello" # Claude -hx --provider codex -p "hello" # Codex +hx # interactive TUI +hx -p "hello" # one-shot, Claude +hx --provider codex -p "hello" # one-shot, Codex +hx -c # continue last session in this directory +``` + +TUI: `enter` send, `alt-enter`/`ctrl-j` newline, `esc` abort, `ctrl-o` expand tool output, `tab` completes `@file` +(mentioned files are attached), `pgup`/`pgdn` scroll. Commands: `/model `, `/provider claude|codex`, +`/compact`, `/clear`, `/quit`. Messages typed while the agent works are queued. + +Config: `~/.hx/config.toml`, overridden per project by `.hx/config.toml`: + +```toml +provider = "claude" # or "codex" +claude_model = "claude-sonnet-4-5" +codex_model = "gpt-5-codex" +compact_at = 150000 # auto-compact threshold (estimated tokens) +max_tokens = 16384 +# system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended ``` Existing Claude Code (`~/.claude/.credentials.json`) and Codex CLI (`~/.codex/auth.json`) logins are picked up automatically. diff --git a/crates/hx-cli/Cargo.toml b/crates/hx-cli/Cargo.toml index 264b1a4..383fa10 100644 --- a/crates/hx-cli/Cargo.toml +++ b/crates/hx-cli/Cargo.toml @@ -15,7 +15,10 @@ clap = { version = "4.6.7", features = ["derive", "env"] } hx-ai = { version = "0.1.0", path = "../hx-ai" } hx-core = { version = "0.1.0", path = "../hx-core" } hx-tools = { version = "0.1.0", path = "../hx-tools" } +hx-tui = { version = "0.1.0", path = "../hx-tui" } +serde = { version = "1.0.229", features = ["derive"] } tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal"] } +toml = "1.1.6" [lints] workspace = true diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 2e24fb6..56be972 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -18,9 +18,9 @@ struct Cli { /// Print mode: send one prompt, stream the reply to stdout, exit. #[arg(short, long)] print: Option, - /// claude | codex - #[arg(long, env = "HX_PROVIDER", default_value = "claude")] - provider: Kind, + /// claude | codex (default from ~/.hx/config.toml, else claude) + #[arg(long, env = "HX_PROVIDER")] + provider: Option, #[arg(short, long, env = "HX_MODEL")] model: Option, /// Session file to resume (JSONL). Default: new file under ~/.hx/sessions. @@ -39,11 +39,70 @@ enum Cmd { Logout { provider: Kind }, } -fn default_model(k: Kind) -> &'static str { +/// `~/.hx/config.toml`, overridden by `.hx/config.toml` in the project. +#[derive(Default, serde::Deserialize)] +#[serde(default, deny_unknown_fields)] +struct Config { + provider: Option, + model: Option, + claude_model: Option, + codex_model: Option, + /// Auto-compact threshold in estimated tokens. + compact_at: Option, + max_tokens: Option, + /// Replaces the built-in system prompt (AGENTS.md etc. are still appended). + system_prompt: Option, +} + +impl Config { + fn load(cwd: &std::path::Path) -> Result { + let mut c = Config::default(); + for p in [ + context::hx_home().join("config.toml"), + cwd.join(".hx/config.toml"), + ] { + let Ok(s) = std::fs::read_to_string(&p) else { + continue; + }; + let o: Config = + toml::from_str(&s).map_err(|e| anyhow::anyhow!("{}: {e}", p.display()))?; + c = Config { + provider: o.provider.or(c.provider), + model: o.model.or(c.model), + claude_model: o.claude_model.or(c.claude_model), + codex_model: o.codex_model.or(c.codex_model), + compact_at: o.compact_at.or(c.compact_at), + max_tokens: o.max_tokens.or(c.max_tokens), + system_prompt: o.system_prompt.or(c.system_prompt), + }; + } + Ok(c) + } +} + +fn default_model(k: Kind) -> String { match k { Kind::Claude => "claude-sonnet-4-5", Kind::Codex => "gpt-5-codex", } + .into() +} + +/// USD per million tokens. ponytail: subscription usage isn't billed per token; this is an API-equivalent estimate. +fn pricing(model: &str) -> Option { + let p = |input, output, cache_read, cache_write| hx_ai::Pricing { + input, + output, + cache_read, + cache_write, + }; + Some(match model { + m if m.contains("opus") => p(15.0, 75.0, 1.5, 18.75), + m if m.contains("sonnet") => p(3.0, 15.0, 0.3, 3.75), + m if m.contains("haiku") => p(1.0, 5.0, 0.1, 1.25), + m if m.starts_with("gpt-5") => p(1.25, 10.0, 0.125, 0.0), + _ => return None, + }) } fn provider(k: Kind) -> hx_ai::Result> { @@ -117,10 +176,16 @@ async fn main() -> Result<()> { Some(Cmd::Logout { provider }) => return Ok(auth::logout(provider)?), None => {} } - let Some(prompt) = cli.print else { - anyhow::bail!("interactive mode not implemented yet; use -p \"prompt\""); - }; let cwd = std::env::current_dir()?; + let cfg = Config::load(&cwd)?; + let kind = cli.provider.or(cfg.provider).unwrap_or(Kind::Claude); + let model = cli.model.or(cfg.model).unwrap_or_else(|| { + match kind { + Kind::Claude => cfg.claude_model.clone(), + Kind::Codex => cfg.codex_model.clone(), + } + .unwrap_or_else(|| default_model(kind)) + }); let dir = session_dir(&cwd); let path = match (cli.session, cli.r#continue) { (Some(p), _) => p, @@ -140,15 +205,30 @@ async fn main() -> Result<()> { state: Default::default(), }; let (mut agent, abort) = Agent::new( - provider(cli.provider)?, + provider(kind)?, hx_tools::registry(), Session::open(&path)?, cx, ); - agent.model = cli - .model - .unwrap_or_else(|| default_model(cli.provider).into()); - agent.system = context::system_prompt(None, &context::hx_home(), &cwd); + agent.model = model; + agent.system = context::system_prompt(cfg.system_prompt.as_deref(), &context::hx_home(), &cwd); + if let Some(n) = cfg.compact_at { + agent.compact_at = n; + } + if let Some(n) = cfg.max_tokens { + agent.max_tokens = n; + } + let Some(prompt) = cli.print else { + hx_tui::run(hx_tui::Setup { + agent, + kind, + make_provider: Box::new(provider), + default_model, + pricing, + }) + .await?; + return Ok(()); + }; agent.bus.add(Printer); tokio::spawn(async move { if tokio::signal::ctrl_c().await.is_ok() { @@ -157,8 +237,11 @@ async fn main() -> Result<()> { }); let r = agent.run(prompt).await; let u = &agent.usage; + let cost = pricing(&agent.model) + .map(|p| format!(" ~${:.4}", u.cost(&p))) + .unwrap_or_default(); eprintln!( - "[{} in / {} out tokens; session {}]", + "[{} in / {} out tokens{cost}; session {}]", u.input_tokens + u.cache_read_tokens, u.output_tokens, path.display() @@ -166,3 +249,19 @@ async fn main() -> Result<()> { r?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn config_parse() { + let c: Config = + toml::from_str("provider = \"codex\"\ncodex_model = \"gpt-5\"\ncompact_at = 1000") + .unwrap(); + assert_eq!(c.provider, Some(Kind::Codex)); + assert_eq!(c.codex_model.as_deref(), Some("gpt-5")); + assert!(toml::from_str::("typo = 1").is_err()); + assert!(pricing("claude-sonnet-4-5").is_some() && pricing("mystery").is_none()); + } +} diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 6875670..8fa7e1d 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -33,7 +33,62 @@ pub struct Agent { pub max_turns: u32, pub usage: Usage, pub session: Session, + /// Auto-compact when the estimated context exceeds this many tokens. + pub compact_at: usize, abort: watch::Receiver, + abort_tx: Arc>, +} + +const SUMMARY_PROMPT: &str = "Summarize the conversation below for a coding agent that will continue the work. \ +Keep: the user's goals and constraints, decisions made, files touched and why, current state, open problems, next steps. \ +Be concise and factual. Output only the summary."; + +/// Rough token estimate (bytes / 4). +pub fn estimate_tokens(msgs: &[Message]) -> usize { + serde_json::to_string(msgs).map_or(0, |s| s.len() / 4) +} + +fn is_prompt(m: &Message) -> bool { + m.role == Role::User + && !m + .content + .iter() + .any(|b| matches!(b, ContentBlock::ToolResult { .. })) +} + +fn transcript(msgs: &[Message]) -> String { + let cut = |s: &str| -> String { + if s.len() > 800 { + format!("{}…", s.chars().take(800).collect::()) + } else { + s.to_string() + } + }; + let mut t = String::new(); + for m in msgs { + let who = if m.role == Role::User { + "USER" + } else { + "ASSISTANT" + }; + for b in &m.content { + match b { + ContentBlock::Text { text } => t.push_str(&format!("{who}: {text}\n")), + ContentBlock::ToolUse { name, input, .. } => { + t.push_str(&format!("TOOL CALL {name}: {}\n", cut(&input.to_string()))) + } + ContentBlock::ToolResult { + content, is_error, .. + } => t.push_str(&format!( + "TOOL RESULT{}: {}\n", + if *is_error { " (error)" } else { "" }, + cut(content) + )), + _ => {} + } + } + } + t } /// Cheap handle to cancel a running `Agent::run`. @@ -53,6 +108,7 @@ impl Agent { cx: ToolCtx, ) -> (Self, AbortHandle) { let (tx, rx) = watch::channel(false); + let tx = Arc::new(tx); let a = Self { provider, tools, @@ -64,9 +120,53 @@ impl Agent { max_turns: 200, usage: Usage::default(), session, + compact_at: 150_000, abort: rx, + abort_tx: tx.clone(), }; - (a, AbortHandle(Arc::new(tx))) + (a, AbortHandle(tx)) + } + + pub fn abort_handle(&self) -> AbortHandle { + AbortHandle(self.abort_tx.clone()) + } + + /// Summarize everything before the most recent user prompts, keeping at least `keep` messages verbatim. + /// The session file keeps full history; the head moves to a new root. Returns false if nothing to cut. + /// ponytail: cuts only at user prompts, so one very long tool loop from a single prompt can't be compacted. + pub async fn compact(&mut self, keep: usize) -> Result { + let msgs = self.session.messages(); + let Some(cut) = (1..=msgs.len().saturating_sub(keep)) + .rev() + .find(|&i| is_prompt(&msgs[i])) + else { + return Ok(false); + }; + let req = Request { + model: self.model.clone(), + system: SUMMARY_PROMPT.into(), + messages: vec![Message::user(transcript(&msgs[..cut]))], + tools: vec![], + max_tokens: 4096, + }; + let mut s = self.provider.stream(req).await?; + let mut summary = None; + while let Some(ev) = s.next().await { + if let StreamEvent::Done { message, usage, .. } = ev? { + self.usage.add(&usage); + summary = Some(message.text()); + } + } + let summary = summary.ok_or(Error::Truncated)?; + let mut kept = msgs[cut..].to_vec(); + kept[0].content.insert( + 0, + ContentBlock::Text { + text: format!("[Summary of earlier conversation]\n{summary}\n[End of summary]"), + }, + ); + self.session.rebase(kept)?; + Ok(true) } fn push(&mut self, m: Message) -> Result<(), Error> { @@ -83,12 +183,25 @@ impl Agent { } /// Run until the model stops calling tools (and no hook injects more work). + /// An abort ends this run only; the next `run` starts un-aborted. pub async fn run(&mut self, prompt: impl Into) -> Result { + let r = self.run_inner(prompt.into()).await; + self.abort_tx + .send_if_modified(|a| std::mem::replace(a, false)); + r + } + + async fn run_inner(&mut self, prompt: String) -> Result { self.push(Message::user(prompt))?; for _ in 0..self.max_turns { if self.aborted() { return Err(Error::Aborted); } + if estimate_tokens(&self.session.messages()) > self.compact_at + && self.compact(6).await? + { + self.emit(Event::Info("context compacted".into())).await; + } self.emit(Event::TurnStart).await; let req = Request { model: self.model.clone(), @@ -112,7 +225,7 @@ impl Agent { } None => break, }, - _ = abort.changed() => return Err(Error::Aborted), + _ = async { abort.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted), } } let (msg, stop, usage) = done.ok_or(Error::Truncated)?; @@ -378,4 +491,39 @@ mod tests { h.abort(); assert!(matches!(a.run("again").await, Err(Error::Aborted))); } + + #[tokio::test] + async fn compaction() { + let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]); + let script = Arc::new(Script( + Mutex::new(vec![text("r1"), text("r2"), text("SUMMARY"), text("r3")]), + Mutex::new(vec![]), + )); + let dir = tempfile::tempdir().unwrap(); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let path = dir.path().join("s.jsonl"); + let (mut a, _h) = Agent::new( + script.clone(), + Registry::default(), + Session::open(&path).unwrap(), + cx, + ); + a.run("p1").await.unwrap(); + a.run("p2").await.unwrap(); + assert!(!a.compact(10).await.unwrap(), "nothing old enough to cut"); + assert!(a.compact(2).await.unwrap()); + let m = a.session.messages(); + assert_eq!(m.len(), 2); + assert!(m[0].text().contains("SUMMARY") && m[0].text().ends_with("p2")); + { + let reqs = script.1.lock().unwrap(); + let t = reqs[2].messages[0].text(); + assert!(t.contains("USER: p1") && t.contains("ASSISTANT: r1") && !t.contains("p2")); + } + a.run("p3").await.unwrap(); + assert_eq!(Session::open(&path).unwrap().messages().len(), 4); + } } diff --git a/crates/hx-core/src/hook.rs b/crates/hx-core/src/hook.rs index b702d08..a94c4ff 100644 --- a/crates/hx-core/src/hook.rs +++ b/crates/hx-core/src/hook.rs @@ -29,6 +29,8 @@ pub enum Event { /// Streaming output from the model (UI). Stream(StreamEvent), Message(Message), + /// Human-readable notice for the UI (compaction etc). + Info(String), } #[derive(Debug, Clone, PartialEq)] diff --git a/crates/hx-core/src/session.rs b/crates/hx-core/src/session.rs index 06e3a1f..42b9c6a 100644 --- a/crates/hx-core/src/session.rs +++ b/crates/hx-core/src/session.rs @@ -72,6 +72,15 @@ impl Session { Ok(id) } + /// Start a new root with `msgs` (used by compaction). Old entries stay in the file. + pub fn rebase(&mut self, msgs: Vec) -> std::io::Result<()> { + self.head = None; + for m in msgs { + self.append(m)?; + } + Ok(()) + } + /// Move head to `id` so the next append branches from it. pub fn fork(&mut self, id: u64) -> bool { let ok = self.entries.iter().any(|e| e.id == id); diff --git a/crates/hx-tui/Cargo.toml b/crates/hx-tui/Cargo.toml index 1abea9f..e3dfc3e 100644 --- a/crates/hx-tui/Cargo.toml +++ b/crates/hx-tui/Cargo.toml @@ -5,6 +5,15 @@ edition.workspace = true license.workspace = true [dependencies] +async-trait = "0.1.92" +crossterm = { version = "0.29.0", features = ["event-stream"] } +futures = "0.3.34" +hx-ai = { version = "0.1.0", path = "../hx-ai" } +hx-core = { version = "0.1.0", path = "../hx-core" } +ignore = "0.4.33" +ratatui = { version = "0.30.2", features = ["unstable-rendered-line-info"] } +serde_json = "1.0.151" +tokio = { version = "1.53.1", features = ["rt", "macros", "sync", "time", "rt-multi-thread"] } [lints] workspace = true diff --git a/crates/hx-tui/src/editor.rs b/crates/hx-tui/src/editor.rs new file mode 100644 index 0000000..2daa772 --- /dev/null +++ b/crates/hx-tui/src/editor.rs @@ -0,0 +1,303 @@ +//! Multi-line input editor with history and `@file` completion. + +#[derive(Default)] +pub struct Editor { + pub buf: String, + /// byte offset, always on a char boundary + pub cur: usize, + history: Vec, + /// index into history while browsing; None = editing a fresh line + hist_pos: Option, + stash: String, +} + +pub enum Action { + None, + Submit(String), +} + +impl Editor { + pub fn insert(&mut self, s: &str) { + // normalize pasted CRLF + let s = s.replace("\r\n", "\n").replace('\r', "\n"); + self.buf.insert_str(self.cur, &s); + self.cur += s.len(); + } + + fn prev_boundary(&self) -> usize { + self.buf[..self.cur] + .char_indices() + .next_back() + .map_or(0, |(i, _)| i) + } + fn next_boundary(&self) -> usize { + self.buf[self.cur..] + .chars() + .next() + .map_or(self.cur, |c| self.cur + c.len_utf8()) + } + fn line_start(&self) -> usize { + self.buf[..self.cur].rfind('\n').map_or(0, |i| i + 1) + } + fn line_end(&self) -> usize { + self.buf[self.cur..] + .find('\n') + .map_or(self.buf.len(), |i| self.cur + i) + } + + pub fn backspace(&mut self) { + if self.cur > 0 { + let p = self.prev_boundary(); + self.buf.replace_range(p..self.cur, ""); + self.cur = p; + } + } + pub fn delete(&mut self) { + let n = self.next_boundary(); + self.buf.replace_range(self.cur..n, ""); + } + pub fn left(&mut self) { + self.cur = self.prev_boundary(); + } + pub fn right(&mut self) { + self.cur = self.next_boundary(); + } + pub fn home(&mut self) { + self.cur = self.line_start(); + } + pub fn end(&mut self) { + self.cur = self.line_end(); + } + /// Delete from line start to cursor. + pub fn kill_line(&mut self) { + let s = self.line_start(); + self.buf.replace_range(s..self.cur, ""); + self.cur = s; + } + pub fn kill_word(&mut self) { + let before = &self.buf[..self.cur]; + let trimmed = before.trim_end(); + let s = trimmed.rfind(char::is_whitespace).map_or(0, |i| i + 1); + self.buf.replace_range(s..self.cur, ""); + self.cur = s; + } + + /// Up: previous line in a multi-line buffer, else history. + pub fn up(&mut self) { + let ls = self.line_start(); + if ls > 0 { + let col = self.buf[ls..self.cur].chars().count(); + let pls = self.buf[..ls - 1].rfind('\n').map_or(0, |i| i + 1); + self.cur = advance(&self.buf, pls, ls - 1, col); + return; + } + if self.history.is_empty() { + return; + } + let i = match self.hist_pos { + None => { + self.stash = std::mem::take(&mut self.buf); + self.history.len() - 1 + } + Some(0) => 0, + Some(i) => i - 1, + }; + self.hist_pos = Some(i); + self.buf = self.history[i].clone(); + self.cur = self.buf.len(); + } + + pub fn down(&mut self) { + let le = self.line_end(); + if le < self.buf.len() { + let col = self.buf[self.line_start()..self.cur].chars().count(); + let nle = self.buf[le + 1..] + .find('\n') + .map_or(self.buf.len(), |i| le + 1 + i); + self.cur = advance(&self.buf, le + 1, nle, col); + return; + } + match self.hist_pos { + None => {} + Some(i) if i + 1 < self.history.len() => { + self.hist_pos = Some(i + 1); + self.buf = self.history[i + 1].clone(); + } + Some(_) => { + self.hist_pos = None; + self.buf = std::mem::take(&mut self.stash); + } + } + self.cur = self.buf.len(); + } + + pub fn submit(&mut self) -> Action { + let s = std::mem::take(&mut self.buf); + self.cur = 0; + self.hist_pos = None; + if s.trim().is_empty() { + return Action::None; + } + if self.history.last() != Some(&s) { + self.history.push(s.clone()); + } + Action::Submit(s) + } + + /// The `@partial` token ending at the cursor, if any: (start byte, text after '@'). + pub fn at_token(&self) -> Option<(usize, &str)> { + let before = &self.buf[..self.cur]; + let start = before + .rfind(|c: char| c.is_whitespace()) + .map_or(0, |i| i + 1); + before[start..].strip_prefix('@').map(|t| (start, t)) + } + + /// Replace the current `@token` with `@path`. + pub fn complete(&mut self, path: &str, done: bool) { + if let Some((s, _)) = self.at_token() { + let rep = if done { + format!("@{path} ") + } else { + format!("@{path}") + }; + self.buf.replace_range(s..self.cur, &rep); + self.cur = s + rep.len(); + } + } + + /// (row, col) of the cursor in chars. + pub fn cursor_rc(&self) -> (usize, usize) { + let before = &self.buf[..self.cur]; + ( + before.matches('\n').count(), + before[self.line_start()..].chars().count(), + ) + } +} + +/// Byte offset `col` chars into `buf[from..to]`, clamped to `to`. +fn advance(buf: &str, from: usize, to: usize, col: usize) -> usize { + buf[from..to] + .char_indices() + .nth(col) + .map_or(to, |(i, _)| from + i) +} + +/// Case-insensitive subsequence match; shorter paths and basename hits rank first. +pub fn fuzzy<'a>(files: &'a [String], q: &str, n: usize) -> Vec<&'a String> { + let q = q.to_lowercase(); + let mut hits: Vec<(usize, &String)> = files + .iter() + .filter_map(|f| { + let l = f.to_lowercase(); + let mut it = l.chars(); + if !q.chars().all(|c| it.any(|x| x == c)) { + return None; + } + let base = l.rsplit('/').next().unwrap_or(&l); + let bonus = if base.contains(&q) { + 0 + } else if l.contains(&q) { + 1000 + } else { + 2000 + }; + Some((bonus + f.len(), f)) + }) + .collect(); + hits.sort(); + hits.into_iter().take(n).map(|(_, f)| f).collect() +} + +pub fn common_prefix(xs: &[&String]) -> String { + let Some(first) = xs.first() else { + return String::new(); + }; + let mut end = first.len(); + for x in &xs[1..] { + end = end.min( + first + .bytes() + .zip(x.bytes()) + .take_while(|(a, b)| a == b) + .count(), + ); + } + while !first.is_char_boundary(end) { + end -= 1; + } + first[..end].to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn edit_and_multiline_nav() { + let mut e = Editor::default(); + e.insert("héllo"); + e.left(); + e.backspace(); + assert_eq!(e.buf, "hélo"); + e.insert("\r\nworld"); + assert_eq!(e.buf, "hél\r\nworldo".replace("\r\n", "\n")); + assert_eq!(e.cursor_rc(), (1, 5)); + e.up(); + assert_eq!(e.cursor_rc(), (0, 3)); + e.down(); + assert_eq!(e.cursor_rc(), (1, 3)); + e.end(); + e.kill_line(); + assert_eq!(e.buf, "hél\n"); + e.insert("a b"); + e.kill_word(); + assert_eq!(e.buf, "hél\na "); + } + + #[test] + fn history_and_submit() { + let mut e = Editor::default(); + assert!(matches!(e.submit(), Action::None)); + for s in ["a", "b"] { + e.insert(s); + assert!(matches!(e.submit(), Action::Submit(x) if x == s)); + } + e.insert("draft"); + e.up(); + assert_eq!(e.buf, "b"); + e.up(); + e.up(); + assert_eq!(e.buf, "a"); + e.down(); + e.down(); + assert_eq!(e.buf, "draft"); + } + + #[test] + fn at_completion() { + let files: Vec = [ + "src/main.rs", + "src/lib.rs", + "crates/x/src/main.rs", + "README.md", + ] + .map(String::from) + .into(); + assert_eq!(fuzzy(&files, "main", 5), [&files[0], &files[2]]); + assert_eq!(fuzzy(&files, "srlib", 5), [&files[1]]); + let mut e = Editor::default(); + e.insert("look at @mai"); + assert_eq!(e.at_token(), Some((8, "mai"))); + let hits = fuzzy(&files, "mai", 5); + assert_eq!(common_prefix(&hits), ""); + e.complete("src/main.rs", true); + assert_eq!(e.buf, "look at @src/main.rs "); + assert_eq!(e.at_token(), None); + assert_eq!( + common_prefix(&[&"src/a".to_string(), &"src/b".to_string()]), + "src/" + ); + } +} diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index b93cf3f..1686505 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -1,14 +1,500 @@ -pub fn add(left: u64, right: u64) -> u64 { - left + right +//! Interactive terminal UI. + +pub mod editor; +pub mod transcript; + +use crossterm::event::{ + Event as TEvent, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, +}; +use editor::{Action, Editor}; +use futures::StreamExt; +use hx_ai::auth::Kind; +use hx_ai::{Provider, Usage}; +use hx_core::agent::{AbortHandle, Agent}; +use hx_core::hook::{Event, Hook, HookAction}; +use ratatui::layout::{Constraint, Layout}; +use ratatui::style::{Color, Style}; +use ratatui::text::Line; +use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use std::collections::VecDeque; +use std::sync::Arc; +use tokio::sync::{Mutex, mpsc}; +use transcript::{Item, Transcript}; + +pub type MakeProvider = Box hx_ai::Result> + Send>; + +pub struct Setup { + pub agent: Agent, + pub kind: Kind, + pub make_provider: MakeProvider, + /// Default model per provider, used on `/provider`. + pub default_model: fn(Kind) -> String, + /// Pricing lookup for the footer; None = unknown. + pub pricing: fn(&str) -> Option, +} + +enum Ui { + Ev(Event), + Done(Result<(), String>), + Compacted(Result), +} + +/// Forwards agent events to the UI loop. +struct Forward(mpsc::UnboundedSender); +#[async_trait::async_trait] +impl Hook for Forward { + async fn on(&self, ev: &Event) -> HookAction { + let _ = self.0.send(Ui::Ev(ev.clone())); + HookAction::Continue + } +} + +struct App { + t: Transcript, + ed: Editor, + files: Vec, + /// lines scrolled up from the bottom + scroll: u16, + expanded: bool, + busy: bool, + queue: VecDeque, + kind: Kind, + model: String, + usage: Usage, + ctx_tokens: usize, + quit: bool, + hint: String, +} + +const HELP: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · tab @file · \ +/model · /provider claude|codex · /compact · /clear · /quit"; + +fn project_files(root: &std::path::Path) -> Vec { + ignore::WalkBuilder::new(root) + .hidden(true) + .build() + .flatten() + .filter(|e| e.file_type().is_some_and(|t| t.is_file())) + .filter_map(|e| { + e.path() + .strip_prefix(root) + .ok() + .map(|p| p.to_string_lossy().into_owned()) + }) + .take(20_000) + .collect() +} + +/// Expand `@path` mentions of existing files into attached contents. +fn expand_mentions(s: &str, root: &std::path::Path) -> String { + let mut att = String::new(); + for w in s.split_whitespace().filter_map(|w| w.strip_prefix('@')) { + let p = root.join(w); + if let Ok(c) = std::fs::read_to_string(&p) + && c.len() < 200_000 + { + att.push_str(&format!("\n\n\n{c}\n")); + } + } + format!("{s}{att}") +} + +pub async fn run(setup: Setup) -> std::io::Result<()> { + let Setup { + mut agent, + kind, + make_provider, + default_model, + pricing, + } = setup; + let (tx, mut rx) = mpsc::unbounded_channel(); + agent.bus.add(Forward(tx.clone())); + let abort: AbortHandle = agent.abort_handle(); + let cwd = agent.cx.cwd.clone(); + let mut app = App { + t: Transcript::default(), + ed: Editor::default(), + files: project_files(&cwd), + scroll: 0, + expanded: false, + busy: false, + queue: VecDeque::new(), + kind, + model: agent.model.clone(), + usage: Usage::default(), + ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()), + quit: false, + hint: String::new(), + }; + // show resumed history + for m in agent.session.messages() { + for b in &m.content { + match (m.role, b) { + (hx_ai::Role::User, hx_ai::ContentBlock::Text { text }) => { + app.t.push(Item::User(text.clone())) + } + (hx_ai::Role::Assistant, hx_ai::ContentBlock::Text { text }) => { + app.t.push(Item::Assistant(text.clone())) + } + _ => {} + } + } + } + app.t.push(Item::Info(format!( + "hx · {:?} · {} · {HELP}", + app.kind, app.model + ))); + let agent = Arc::new(Mutex::new(agent)); + + let mut term = ratatui::init(); + let mut keys = EventStream::new(); + let mut tick = tokio::time::interval(std::time::Duration::from_millis(50)); + let mut dirty = true; + while !app.quit { + if std::mem::take(&mut dirty) { + term.draw(|f| draw(f, &mut app))?; + } + tokio::select! { + k = keys.next() => { + let Some(Ok(ev)) = k else { break }; + dirty = true; + match ev { + TEvent::Key(k) if k.kind != KeyEventKind::Release => { + if let Some(line) = on_key(&mut app, k, &abort) { + submit(&mut app, line, &agent, &tx, &make_provider, default_model, &cwd).await; + } + } + TEvent::Paste(s) => app.ed.insert(&s), + _ => {} + } + } + Some(u) = rx.recv() => { + dirty = true; + match u { + Ui::Ev(e) => { + if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e { + app.usage.add(usage); + app.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize; + } + app.t.apply(&e); + } + Ui::Done(r) => { + app.busy = false; + match r { + Err(e) if e == "aborted" => app.t.push(Item::Info("aborted".into())), + Err(e) => app.t.push(Item::Error(e)), + Ok(()) => {} + } + if let Some(next) = app.queue.pop_front() { + submit(&mut app, next, &agent, &tx, &make_provider, default_model, &cwd).await; + } + } + Ui::Compacted(r) => { + app.busy = false; + app.t.push(match r { + Ok(true) => Item::Info("context compacted".into()), + Ok(false) => Item::Info("nothing to compact".into()), + Err(e) => Item::Error(e), + }); + app.ctx_tokens = hx_core::agent::estimate_tokens(&agent.lock().await.session.messages()); + } + } + } + _ = tick.tick(), if app.busy => dirty = true, + } + } + ratatui::restore(); + let a = agent.lock().await; + let cost = pricing(&a.model) + .map(|p| format!(" ${:.4}", app.usage.cost(&p))) + .unwrap_or_default(); + eprintln!( + "[{} in / {} out tokens{cost}; session {}]", + app.usage.input_tokens + app.usage.cache_read_tokens, + app.usage.output_tokens, + a.session.path().display() + ); + Ok(()) +} + +/// Returns a line to submit, if any. +fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { + let ctrl = k.modifiers.contains(KeyModifiers::CONTROL); + let alt = k.modifiers.contains(KeyModifiers::ALT); + let shift = k.modifiers.contains(KeyModifiers::SHIFT); + app.hint.clear(); + match k.code { + KeyCode::Char('c') if ctrl => { + if app.busy { + app.queue.clear(); + abort.abort(); + } else if app.ed.buf.is_empty() { + app.quit = true; + } else { + app.ed = std::mem::take(&mut app.ed); + app.ed.buf.clear(); + app.ed.cur = 0; + } + } + KeyCode::Char('d') if ctrl && app.ed.buf.is_empty() && !app.busy => app.quit = true, + KeyCode::Esc if app.busy => { + app.queue.clear(); + abort.abort(); + } + KeyCode::Char('o') if ctrl => app.expanded = !app.expanded, + KeyCode::Char('j') if ctrl => app.ed.insert("\n"), + KeyCode::Enter if alt || shift => app.ed.insert("\n"), + KeyCode::Enter => { + if let Action::Submit(s) = app.ed.submit() { + return Some(s); + } + } + KeyCode::Char('u') if ctrl => app.ed.kill_line(), + KeyCode::Char('w') if ctrl => app.ed.kill_word(), + KeyCode::Char('a') if ctrl => app.ed.home(), + KeyCode::Char('e') if ctrl => app.ed.end(), + KeyCode::Char(c) if !ctrl => app.ed.insert(c.encode_utf8(&mut [0; 4])), + KeyCode::Backspace => app.ed.backspace(), + KeyCode::Delete => app.ed.delete(), + KeyCode::Left => app.ed.left(), + KeyCode::Right => app.ed.right(), + KeyCode::Home => app.ed.home(), + KeyCode::End => app.ed.end(), + KeyCode::Up => app.ed.up(), + KeyCode::Down => app.ed.down(), + KeyCode::PageUp => app.scroll = app.scroll.saturating_add(10), + KeyCode::PageDown => app.scroll = app.scroll.saturating_sub(10), + KeyCode::Tab => { + if let Some((_, q)) = app.ed.at_token() { + let hits = editor::fuzzy(&app.files, q, 8); + match hits.len() { + 0 => app.hint = "no match".into(), + 1 => { + let h = hits[0].clone(); + app.ed.complete(&h, true); + } + _ => { + let pre = editor::common_prefix(&hits); + if pre.len() > q.len() { + app.ed.complete(&pre, false); + } + app.hint = hits + .iter() + .map(|s| s.as_str()) + .collect::>() + .join(" "); + } + } + } + } + _ => {} + } + None +} + +async fn submit( + app: &mut App, + line: String, + agent: &Arc>, + tx: &mpsc::UnboundedSender, + make_provider: &MakeProvider, + default_model: fn(Kind) -> String, + cwd: &std::path::Path, +) { + app.scroll = 0; + if let Some(cmd) = line.strip_prefix('/') { + let (c, arg) = cmd + .split_once(' ') + .map_or((cmd, ""), |(a, b)| (a, b.trim())); + if app.busy && c != "quit" { + app.t.push(Item::Error("busy; esc to abort first".into())); + return; + } + match c { + "quit" | "exit" => app.quit = true, + "help" => app.t.push(Item::Info(HELP.into())), + "model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))), + "model" => { + agent.lock().await.model = arg.into(); + app.model = arg.into(); + app.t.push(Item::Info(format!("model → {arg}"))); + } + "provider" => match arg + .parse::() + .map_err(|e| e.to_string()) + .and_then(|k| make_provider(k).map(|p| (k, p)).map_err(|e| e.to_string())) + { + Ok((k, p)) => { + let mut a = agent.lock().await; + a.provider = p; + a.model = default_model(k); + app.kind = k; + app.model = a.model.clone(); + app.t + .push(Item::Info(format!("provider → {k:?} ({})", app.model))); + } + Err(e) => app.t.push(Item::Error(e)), + }, + "compact" => { + app.busy = true; + app.t.push(Item::Info("compacting…".into())); + let (agent, tx) = (agent.clone(), tx.clone()); + tokio::spawn(async move { + let r = agent + .lock() + .await + .compact(4) + .await + .map_err(|e| e.to_string()); + let _ = tx.send(Ui::Compacted(r)); + }); + } + "clear" => { + let mut a = agent.lock().await; + let _ = a.session.rebase(vec![]); + app.t = Transcript::default(); + app.ctx_tokens = 0; + app.t.push(Item::Info("cleared".into())); + } + _ => app + .t + .push(Item::Error(format!("unknown command /{c}; /help"))), + } + return; + } + if app.busy { + app.t.push(Item::Info(format!( + "queued: {}", + line.lines().next().unwrap_or_default() + ))); + app.queue.push_back(line); + return; + } + app.t.push(Item::User(line.clone())); + app.busy = true; + let prompt = expand_mentions(&line, cwd); + let (agent, tx) = (agent.clone(), tx.clone()); + tokio::spawn(async move { + let r = agent + .lock() + .await + .run(prompt) + .await + .map(|_| ()) + .map_err(|e| e.to_string()); + let _ = tx.send(Ui::Done(r)); + }); +} + +fn draw(f: &mut ratatui::Frame, app: &mut App) { + let input_h = (app.ed.buf.lines().count().max(1) + usize::from(app.ed.buf.ends_with('\n'))) + .min(10) as u16 + + 2; + let [main, status, input] = Layout::vertical([ + Constraint::Min(3), + Constraint::Length(1), + Constraint::Length(input_h), + ]) + .areas(f.area()); + + let para = Paragraph::new(app.t.lines(app.expanded)).wrap(Wrap { trim: false }); + let total = para.line_count(main.width) as u16; + let max_up = total.saturating_sub(main.height); + app.scroll = app.scroll.min(max_up); + f.render_widget(para.scroll((max_up - app.scroll, 0)), main); + + let spin = if app.busy { + ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][(std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + / 80 + % 10) as usize] + } else { + " " + }; + let q = if app.queue.is_empty() { + String::new() + } else { + format!(" · {} queued", app.queue.len()) + }; + let up = if app.scroll > 0 { + format!(" · ↑{}", app.scroll) + } else { + String::new() + }; + let st = if app.hint.is_empty() { + format!( + "{spin} {:?} · {} · ctx {}k · {}↑ {}↓{q}{up}", + app.kind, + app.model, + app.ctx_tokens / 1000, + app.usage.input_tokens + app.usage.cache_read_tokens, + app.usage.output_tokens + ) + } else { + app.hint.clone() + }; + f.render_widget( + Line::styled(st, Style::default().fg(Color::DarkGray)), + status, + ); + + let block = Block::default() + .borders(Borders::TOP | Borders::BOTTOM) + .border_style(Style::default().fg(Color::DarkGray)); + let inner = block.inner(input); + f.render_widget(Paragraph::new(app.ed.buf.as_str()).block(block), input); + let (r, c) = app.ed.cursor_rc(); + let skip = (r as u16).saturating_sub(inner.height.saturating_sub(1)); + f.set_cursor_position((inner.x + c as u16, inner.y + r as u16 - skip)); } #[cfg(test)] mod tests { use super::*; + use ratatui::backend::TestBackend; #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); + fn mentions() { + let d = std::env::temp_dir().join(format!("hx-tui-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join("a.txt"), "AAA").unwrap(); + let s = expand_mentions("see @a.txt and @nope", &d); + assert!(s.starts_with("see @a.txt and @nope") && s.contains("\nAAA")); + assert!(!s.contains("nope\">")); + } + + #[test] + fn draw_snapshot() { + let mut app = App { + t: Transcript::default(), + ed: Editor::default(), + files: vec![], + scroll: 0, + expanded: false, + busy: false, + queue: VecDeque::new(), + kind: Kind::Claude, + model: "m1".into(), + usage: Usage::default(), + ctx_tokens: 12_000, + quit: false, + hint: String::new(), + }; + app.t.push(Item::User("hello".into())); + app.t.push(Item::Assistant("hi **there**".into())); + app.ed.insert("typing"); + let mut term = ratatui::Terminal::new(TestBackend::new(40, 10)).unwrap(); + term.draw(|f| draw(f, &mut app)).unwrap(); + let buf = term.backend().buffer().clone(); + let rows: Vec = (0..10) + .map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect()) + .collect(); + let all = rows.join("\n"); + assert!(all.contains("> hello"), "{all}"); + assert!(all.contains("hi there"), "{all}"); + assert!(all.contains("Claude · m1 · ctx 12k"), "{all}"); + assert!(rows[8].starts_with("typing"), "{all}"); } } diff --git a/crates/hx-tui/src/transcript.rs b/crates/hx-tui/src/transcript.rs new file mode 100644 index 0000000..d905e01 --- /dev/null +++ b/crates/hx-tui/src/transcript.rs @@ -0,0 +1,326 @@ +//! Transcript model and rendering (markdown-ish text, tool calls, diffs). + +use hx_ai::StreamEvent; +use hx_core::hook::Event; +use ratatui::style::{Color, Modifier, Style}; +use ratatui::text::{Line, Span}; +use serde_json::Value; + +#[derive(Debug, Clone, PartialEq)] +pub enum Item { + User(String), + Assistant(String), + Thinking(String), + Tool { + id: String, + name: String, + args: Value, + result: Option<(String, bool)>, + }, + Info(String), + Error(String), +} + +#[derive(Default)] +pub struct Transcript { + pub items: Vec, + /// true while the last Assistant/Thinking item is still streaming + streaming: bool, +} + +impl Transcript { + pub fn push(&mut self, i: Item) { + self.streaming = false; + self.items.push(i); + } + + pub fn apply(&mut self, ev: &Event) { + match ev { + Event::Stream(StreamEvent::TextDelta { text }) => match self.items.last_mut() { + Some(Item::Assistant(s)) if self.streaming => s.push_str(text), + _ => { + self.push(Item::Assistant(text.clone())); + self.streaming = true; + } + }, + Event::Stream(StreamEvent::ThinkingDelta { text }) => match self.items.last_mut() { + Some(Item::Thinking(s)) if self.streaming => s.push_str(text), + _ => { + self.push(Item::Thinking(text.clone())); + self.streaming = true; + } + }, + Event::Stream(StreamEvent::Done { .. }) => self.streaming = false, + Event::ToolCall { id, name, args } => self.push(Item::Tool { + id: id.clone(), + name: name.clone(), + args: args.clone(), + result: None, + }), + Event::ToolResult { + id, + content, + is_error, + .. + } => { + if let Some(Item::Tool { result, .. }) = self + .items + .iter_mut() + .rev() + .find(|i| matches!(i, Item::Tool { id: x, .. } if x == id)) + { + *result = Some((content.clone(), *is_error)); + } + } + Event::Info(s) => self.push(Item::Info(s.clone())), + _ => {} + } + } + + pub fn lines(&self, expanded: bool) -> Vec> { + let mut out = vec![]; + for it in &self.items { + render(it, expanded, &mut out); + out.push(Line::default()); + } + out + } +} + +fn dim() -> Style { + Style::default().fg(Color::DarkGray) +} + +fn summary(name: &str, args: &Value) -> String { + let s = ["path", "command", "pattern", "query"] + .iter() + .find_map(|k| args[*k].as_str()); + let s = s.map_or_else(|| args.to_string(), str::to_string); + let first = s.lines().next().unwrap_or_default(); + let mut t: String = first.chars().take(120).collect(); + if t.len() < s.len() { + t.push('…'); + } + format!("{name} {t}") +} + +fn render(it: &Item, expanded: bool, out: &mut Vec>) { + match it { + Item::User(s) => { + for (i, l) in s.lines().enumerate() { + let p = if i == 0 { "> " } else { " " }; + out.push(Line::from(vec![ + Span::styled( + p, + Style::default() + .fg(Color::Cyan) + .add_modifier(Modifier::BOLD), + ), + Span::styled(l.to_string(), Style::default().add_modifier(Modifier::BOLD)), + ])); + } + } + Item::Assistant(s) => markdown(s, out), + Item::Thinking(s) => { + for l in s.lines() { + out.push(Line::styled( + l.to_string(), + dim().add_modifier(Modifier::ITALIC), + )); + } + } + Item::Info(s) => out.push(Line::styled(format!("· {s}"), dim())), + Item::Error(s) => out.push(Line::styled( + format!("error: {s}"), + Style::default().fg(Color::Red), + )), + Item::Tool { + name, args, result, .. + } => { + let (mark, color) = match result { + None => ("○", Color::Yellow), + Some((_, false)) => ("●", Color::Green), + Some((_, true)) => ("●", Color::Red), + }; + out.push(Line::from(vec![ + Span::styled(format!("{mark} "), Style::default().fg(color)), + Span::styled( + summary(name, args), + Style::default().add_modifier(Modifier::BOLD), + ), + ])); + if let Some((content, err)) = result { + tool_body(name, content, *err, expanded, out); + } + } + } +} + +/// Collapsed: diffs in full (edits are what you want to review), bash tail, others 1 line. +fn tool_body(name: &str, content: &str, err: bool, expanded: bool, out: &mut Vec>) { + let lines: Vec<&str> = content.lines().collect(); + let is_diff = name == "edit" && !err; + let (show, skipped_front): (Vec<&str>, usize) = if expanded || is_diff { + (lines.clone(), 0) + } else if name == "bash" || err { + let n = lines.len().saturating_sub(5); + (lines[n..].to_vec(), n) + } else { + (lines.iter().take(1).copied().collect(), 0) + }; + let hidden = lines.len() - show.len(); + if skipped_front > 0 { + out.push(Line::styled( + format!(" ⋮ {skipped_front} earlier lines (ctrl-o)"), + dim(), + )); + } + for l in &show { + let style = if is_diff { + match l.as_bytes().first() { + Some(b'+') if !l.starts_with("+++") => Style::default().fg(Color::Green), + Some(b'-') if !l.starts_with("---") => Style::default().fg(Color::Red), + Some(b'@') => Style::default().fg(Color::Cyan), + _ => dim(), + } + } else if err { + Style::default().fg(Color::Red) + } else { + dim() + }; + out.push(Line::styled(format!(" {l}"), style)); + } + if hidden > 0 && skipped_front == 0 { + out.push(Line::styled( + format!(" … {hidden} more lines (ctrl-o)"), + dim(), + )); + } +} + +/// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**. +fn markdown(s: &str, out: &mut Vec>) { + let mut code = false; + for l in s.lines() { + if l.trim_start().starts_with("```") { + code = !code; + out.push(Line::styled(l.to_string(), dim())); + continue; + } + if code { + out.push(Line::styled( + l.to_string(), + Style::default().fg(Color::Cyan), + )); + } else if l.starts_with('#') { + out.push(Line::styled( + l.trim_start_matches('#').trim().to_string(), + Style::default().add_modifier(Modifier::BOLD | Modifier::UNDERLINED), + )); + } else { + out.push(inline(l)); + } + } +} + +fn inline(l: &str) -> Line<'static> { + let mut spans = vec![]; + let mut rest = l; + while !rest.is_empty() { + let next = [ + ("`", Style::default().fg(Color::Yellow)), + ("**", Style::default().add_modifier(Modifier::BOLD)), + ] + .into_iter() + .filter_map(|(d, st)| { + let i = rest.find(d)?; + let j = rest[i + d.len()..].find(d)?; + Some((i, j, d, st)) + }) + .min_by_key(|x| x.0); + match next { + Some((i, j, d, st)) => { + spans.push(Span::raw(rest[..i].to_string())); + spans.push(Span::styled( + rest[i + d.len()..i + d.len() + j].to_string(), + st, + )); + rest = &rest[i + d.len() * 2 + j..]; + } + None => { + spans.push(Span::raw(rest.to_string())); + break; + } + } + } + Line::from(spans) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn text(ls: &[Line]) -> Vec { + ls.iter() + .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect()) + .collect() + } + + #[test] + fn stream_and_tools() { + let mut t = Transcript::default(); + t.push(Item::User("hi".into())); + for d in ["Hel", "lo"] { + t.apply(&Event::Stream(StreamEvent::TextDelta { text: d.into() })); + } + t.apply(&Event::ToolCall { + id: "1".into(), + name: "edit".into(), + args: json!({"path": "a.rs"}), + }); + t.apply(&Event::ToolResult { + id: "1".into(), + name: "edit".into(), + args: json!({}), + content: "edited a.rs\n@@ -1 +1 @@\n-old\n+new".into(), + is_error: false, + }); + t.apply(&Event::Stream(StreamEvent::TextDelta { + text: "After".into(), + })); + assert_eq!(t.items[1], Item::Assistant("Hello".into())); + assert_eq!(t.items[3], Item::Assistant("After".into())); + let ls = t.lines(false); + let s = text(&ls); + assert!(s.contains(&"● edit a.rs".to_string())); + let minus = ls + .iter() + .find(|l| text(std::slice::from_ref(l))[0] == " -old") + .unwrap(); + assert_eq!(minus.style.fg, Some(Color::Red)); + } + + #[test] + fn collapse_bash_tail() { + let mut out = vec![]; + let body: String = (1..=20).map(|i| format!("l{i}\n")).collect(); + tool_body("bash", &body, false, false, &mut out); + let s = text(&out); + assert_eq!(s[0], " ⋮ 15 earlier lines (ctrl-o)"); + assert_eq!(s.last().unwrap(), " l20"); + out.clear(); + tool_body("bash", &body, false, true, &mut out); + assert_eq!(out.len(), 20); + out.clear(); + tool_body("read", &body, false, false, &mut out); + assert_eq!(text(&out), [" l1", " … 19 more lines (ctrl-o)"]); + } + + #[test] + fn inline_md() { + assert_eq!(text(&[inline("a `b` **c** d")]), ["a b c d"]); + assert_eq!(inline("a `b` c").spans[1].style.fg, Some(Color::Yellow)); + assert_eq!(text(&[inline("x ` unclosed")]), ["x ` unclosed"]); + } +} diff --git a/tests/tui_smoke.py b/tests/tui_smoke.py new file mode 100644 index 0000000..ae758eb --- /dev/null +++ b/tests/tui_smoke.py @@ -0,0 +1,67 @@ +"""Drive the interactive TUI in a pty against the fake API. Prints screen text at checkpoints.""" +import os, pty, sys, time, subprocess, select, re, json, tempfile, signal + +root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +port = 20000 + os.getpid() % 20000 +srv = subprocess.Popen([sys.executable, f"{root}/tests/fake_anthropic.py", str(port)]) +tmp = tempfile.mkdtemp() +os.makedirs(f"{tmp}/home/.hx"); os.makedirs(f"{tmp}/repo") +open(f"{tmp}/home/.hx/auth.json", "w").write(json.dumps({"claude": {"access": "fake-token", "refresh": "r", "expires": 99999999999999}})) +open(f"{tmp}/repo/notes.md", "w").write("NOTES\n") +time.sleep(0.5) + +pid, fd = pty.fork() +if pid == 0: + os.chdir(f"{tmp}/repo") + os.environ.update(HOME=f"{tmp}/home", HX_BASE_URL=f"http://127.0.0.1:{port}", TERM="xterm-256color", COLUMNS="100", LINES="30") + os.execv(f"{root}/target/debug/hx", ["hx"]) + +import fcntl, termios, struct +fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 30, 100, 0, 0)) +buf = b"" +def pump(t): + global buf + end = time.time() + t + while time.time() < end: + r, _, _ = select.select([fd], [], [], 0.05) + if r: + try: + buf += os.read(fd, 65536) + except OSError: + return +def plain(): + s = buf.decode(errors="replace") + s = re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", " ", s) + return re.sub(r"\x1b[()][A-Z0-9]|\x1b[=>]", "", s) +def send(b, t=0.6): + os.write(fd, b); pump(t) + +ok = True +def check(label, needle): + global ok + hit = needle in plain() + ok &= hit + print(f"{'PASS' if hit else 'FAIL'} {label}: {needle!r}") + +pump(1.5) +check("startup footer", "Claude") +send(b"@not"); send(b"\t") +check("tab completion", "es.md") +send(b"\x15") # ctrl-u +send(b"make hello.txt"); send(b"\r", 3) +check("tool call shown", "write hello.txt") +check("final answer", "Done: file says hi from hx.") +check("file written", "") if os.path.exists(f"{tmp}/repo/hello.txt") else (print("FAIL file"), None) +send(b"/model claude-opus-4-1\r") +check("model switch", "model → claude-opus-4-1") +send(b"/bogus\r") +check("unknown cmd", "unknown command /bogus") +send(b"\x03", 1) # ctrl-c on empty -> quit +try: + _, st = os.waitpid(pid, 0) + print("exit status", st) +except ChildProcessError: + pass +check("exit summary", "session") +srv.kill() +sys.exit(0 if ok else 1)