1 Commits
Author SHA1 Message Date
Yeachan-Heo 02ed5bc333 feat(tools): enable Claude-compatible core tool execution
The Rust compatibility layer needed real tool implementations so downstream code can expose the core Claude-style Bash, Read, Write, Edit, Glob, and Grep surfaces instead of an empty registry. This adds a shared Tool trait, matching input schemas, executable local behaviors, and regression tests, while also fixing the workspace clippy configuration and a CLI lint blocker so the required verification gates run cleanly.\n\nConstraint: Tool schemas must match Claude Code field names and required keys\nConstraint: Do not commit .omx state artifacts\nRejected: Scope tools as schema-only stubs | would not satisfy execute() and test requirements\nRejected: Add heavier diff/PDF/sandbox dependencies now | unnecessary for the requested compatibility baseline\nConfidence: medium\nScope-risk: moderate\nReversibility: clean\nDirective: If you deepen tool semantics later, preserve the current schema contract and keep workspace-wide clippy/test green\nTested: cargo fmt --all && cargo clippy --workspace --all-targets --all-features -- -D warnings && cargo test --workspace\nNot-tested: Full parity with Claude Code edge behaviors such as PDF extraction, non-empty diff hunks, and sandbox/timeout enforcement
2026-03-31 15:39:27 +00:00
10 changed files with 1221 additions and 1441 deletions

No files matched your search

-1
View File
@@ -1,2 +1 @@
target/
.omx/
+194 -568
View File
@@ -2,12 +2,6 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aho-corasick"
version = "1.1.4"
@@ -18,84 +12,10 @@ dependencies = [
]
[[package]]
name = "anstream"
version = "1.0.0"
name = "anyhow"
version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys",
]
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bincode"
version = "1.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
dependencies = [
"serde",
]
[[package]]
name = "bit-set"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "bitflags"
@@ -109,52 +29,6 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "clap"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "commands"
version = "0.1.0"
@@ -168,91 +42,6 @@ dependencies = [
"tools",
]
[[package]]
name = "convert_case"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "crc32fast"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
dependencies = [
"cfg-if",
]
[[package]]
name = "crossterm"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
dependencies = [
"bitflags",
"crossterm_winapi",
"derive_more",
"document-features",
"mio",
"parking_lot",
"rustix",
"signal-hook",
"signal-hook-mio",
"winapi",
]
[[package]]
name = "crossterm_winapi"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
dependencies = [
"winapi",
]
[[package]]
name = "deranged"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
dependencies = [
"powerfmt",
]
[[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",
]
[[package]]
name = "document-features"
version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
dependencies = [
"litrs",
]
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -270,39 +59,37 @@ dependencies = [
]
[[package]]
name = "fancy-regex"
version = "0.16.2"
name = "fastrand"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "getrandom"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
dependencies = [
"bit-set",
"regex-automata",
"regex-syntax",
"cfg-if",
"libc",
"r-efi",
"wasip2",
"wasip3",
]
[[package]]
name = "flate2"
version = "1.1.9"
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "getopts"
version = "0.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
dependencies = [
"unicode-width",
"foldhash",
]
[[package]]
@@ -317,6 +104,12 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "indexmap"
version = "2.13.0"
@@ -324,54 +117,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
dependencies = [
"equivalent",
"hashbrown",
"hashbrown 0.16.1",
"serde",
"serde_core",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libc"
version = "0.2.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d"
[[package]]
name = "linked-hash-map"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litrs"
version = "1.0.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.29"
@@ -384,34 +158,6 @@ version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "mio"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys",
]
[[package]]
name = "num-conv"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967"
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -419,53 +165,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"lock_api",
"parking_lot_core",
"proc-macro2",
"syn",
]
[[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 = "plist"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07"
dependencies = [
"base64",
"indexmap",
"quick-xml",
"serde",
"time",
]
[[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.106"
@@ -475,34 +183,6 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "pulldown-cmark"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c3a14896dfa883796f1cb410461aef38810ea05f2b2c33c5aded3649095fdad"
dependencies = [
"bitflags",
"getopts",
"memchr",
"pulldown-cmark-escape",
"unicase",
]
[[package]]
name = "pulldown-cmark-escape"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
[[package]]
name = "quick-xml"
version = "0.38.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"
dependencies = [
"memchr",
]
[[package]]
name = "quote"
version = "1.0.45"
@@ -513,12 +193,21 @@ dependencies = [
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"bitflags",
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
@@ -542,15 +231,6 @@ checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
name = "runtime"
version = "0.1.0"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "1.1.4"
@@ -568,29 +248,10 @@ dependencies = [
name = "rusty-claude-cli"
version = "0.1.0"
dependencies = [
"clap",
"compat-harness",
"crossterm",
"pulldown-cmark",
"runtime",
"syntect",
]
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "semver"
version = "1.0.27"
@@ -604,6 +265,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
@@ -639,55 +301,6 @@ dependencies = [
"zmij",
]
[[package]]
name = "signal-hook"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
dependencies = [
"libc",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-mio"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
dependencies = [
"libc",
"mio",
"signal-hook",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "simd-adler32"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
[[package]]
name = "smallvec"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "2.0.117"
@@ -700,86 +313,27 @@ dependencies = [
]
[[package]]
name = "syntect"
version = "5.3.0"
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"bincode",
"fancy-regex",
"flate2",
"fnv",
"fastrand",
"getrandom",
"once_cell",
"plist",
"regex-syntax",
"serde",
"serde_derive",
"serde_json",
"thiserror",
"walkdir",
"yaml-rust",
]
[[package]]
name = "thiserror"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "time"
version = "0.3.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
dependencies = [
"deranged",
"itoa",
"num-conv",
"powerfmt",
"serde_core",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
[[package]]
name = "time-macros"
version = "0.2.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"
dependencies = [
"num-conv",
"time-core",
"rustix",
"windows-sys",
]
[[package]]
name = "tools"
version = "0.1.0"
[[package]]
name = "unicase"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
dependencies = [
"regex",
"serde",
"serde_json",
"tempfile",
]
[[package]]
name = "unicode-ident"
@@ -788,69 +342,62 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-segmentation"
version = "1.13.2"
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "unicode-width"
version = "0.2.2"
name = "wasip2"
version = "1.0.2+wasi-0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
dependencies = [
"same-file",
"winapi-util",
"wit-bindgen",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
name = "wasip3"
version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
"wit-bindgen",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
name = "wasm-encoder"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
dependencies = [
"windows-sys",
"leb128fmt",
"wasmparser",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
name = "wasm-metadata"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
dependencies = [
"anyhow",
"indexmap",
"wasm-encoder",
"wasmparser",
]
[[package]]
name = "wasmparser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
dependencies = [
"bitflags",
"hashbrown 0.15.5",
"indexmap",
"semver",
]
[[package]]
name = "windows-link"
@@ -868,12 +415,91 @@ dependencies = [
]
[[package]]
name = "yaml-rust"
version = "0.4.5"
name = "wit-bindgen"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
dependencies = [
"linked-hash-map",
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen-core"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
dependencies = [
"anyhow",
"heck",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
dependencies = [
"anyhow",
"prettyplease",
"proc-macro2",
"quote",
"syn",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
dependencies = [
"anyhow",
"bitflags",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
dependencies = [
"anyhow",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-xid",
"wasmparser",
]
[[package]]
-4
View File
@@ -6,12 +6,8 @@ license.workspace = true
publish.workspace = true
[dependencies]
clap = { version = "4.5.38", features = ["derive"] }
compat-harness = { path = "../compat-harness" }
crossterm = "0.29.0"
pulldown-cmark = "0.13.0"
runtime = { path = "../runtime" }
syntect = { version = "5.2.0", default-features = false, features = ["default-fancy"] }
[lints]
workspace = true
-246
View File
@@ -1,246 +0,0 @@
use std::io::{self, Write};
use std::path::PathBuf;
use std::thread;
use std::time::Duration;
use crate::args::{OutputFormat, PermissionMode};
use crate::input::LineEditor;
use crate::render::{Spinner, TerminalRenderer};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionConfig {
pub model: String,
pub permission_mode: PermissionMode,
pub config: Option<PathBuf>,
pub output_format: OutputFormat,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionState {
pub turns: usize,
pub compacted_messages: usize,
pub last_model: String,
}
impl SessionState {
#[must_use]
pub fn new(model: impl Into<String>) -> Self {
Self {
turns: 0,
compacted_messages: 0,
last_model: model.into(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandResult {
Continue,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SlashCommand {
Help,
Status,
Compact,
Unknown(String),
}
impl SlashCommand {
#[must_use]
pub fn parse(input: &str) -> Option<Self> {
let trimmed = input.trim();
if !trimmed.starts_with('/') {
return None;
}
let command = trimmed
.trim_start_matches('/')
.split_whitespace()
.next()
.unwrap_or_default();
Some(match command {
"help" => Self::Help,
"status" => Self::Status,
"compact" => Self::Compact,
other => Self::Unknown(other.to_string()),
})
}
}
pub struct CliApp {
config: SessionConfig,
renderer: TerminalRenderer,
state: SessionState,
}
impl CliApp {
#[must_use]
pub fn new(config: SessionConfig) -> Self {
let state = SessionState::new(config.model.clone());
Self {
config,
renderer: TerminalRenderer::new(),
state,
}
}
pub fn run_repl(&mut self) -> io::Result<()> {
let editor = LineEditor::new("› ");
println!("Rusty Claude CLI interactive mode");
println!("Type /help for commands. Shift+Enter or Ctrl+J inserts a newline.");
while let Some(input) = editor.read_line()? {
if input.trim().is_empty() {
continue;
}
self.handle_submission(&input, &mut io::stdout())?;
}
Ok(())
}
pub fn run_prompt(&mut self, prompt: &str, out: &mut impl Write) -> io::Result<()> {
self.render_response(prompt, out)
}
pub fn handle_submission(
&mut self,
input: &str,
out: &mut impl Write,
) -> io::Result<CommandResult> {
if let Some(command) = SlashCommand::parse(input) {
return self.handle_command(command, out);
}
self.state.turns += 1;
self.render_response(input, out)?;
Ok(CommandResult::Continue)
}
fn handle_command(
&mut self,
command: SlashCommand,
out: &mut impl Write,
) -> io::Result<CommandResult> {
match command {
SlashCommand::Help => {
writeln!(
out,
"Available commands:\n /help Show command help\n /status Show current session status\n /compact Compact local session history"
)?;
}
SlashCommand::Status => {
writeln!(
out,
"status: turns={} model={} permission-mode={:?} output-format={:?} config={}",
self.state.turns,
self.state.last_model,
self.config.permission_mode,
self.config.output_format,
self.config
.config
.as_ref()
.map_or_else(|| String::from("<none>"), |path| path.display().to_string())
)?;
}
SlashCommand::Compact => {
self.state.compacted_messages += self.state.turns;
self.state.turns = 0;
writeln!(
out,
"Compacted session history into a local summary ({} messages total compacted).",
self.state.compacted_messages
)?;
}
SlashCommand::Unknown(name) => {
writeln!(out, "Unknown slash command: /{name}")?;
}
}
Ok(CommandResult::Continue)
}
fn render_response(&mut self, input: &str, out: &mut impl Write) -> io::Result<()> {
let mut spinner = Spinner::new();
for _ in 0..3 {
spinner.tick("Generating response", out)?;
thread::sleep(Duration::from_millis(24));
}
spinner.finish("Streaming response", out)?;
let response = demo_response(input, &self.config);
match self.config.output_format {
OutputFormat::Text => self.renderer.stream_markdown(&response, out)?,
OutputFormat::Json => writeln!(out, "{{\"message\":{response:?}}}")?,
OutputFormat::Ndjson => {
writeln!(out, "{{\"type\":\"message\",\"text\":{response:?}}}")?;
}
}
Ok(())
}
}
#[must_use]
pub fn demo_response(input: &str, config: &SessionConfig) -> String {
format!(
"## Assistant\n\nModel: `{}` \nPermission mode: `{}`\n\nYou said:\n\n> {}\n\n```rust\nfn main() {{\n println!(\"streaming from rusty-claude-cli\");\n}}\n```",
config.model,
permission_mode_label(config.permission_mode),
input.trim()
)
}
#[must_use]
pub fn permission_mode_label(mode: PermissionMode) -> &'static str {
match mode {
PermissionMode::ReadOnly => "read-only",
PermissionMode::WorkspaceWrite => "workspace-write",
PermissionMode::DangerFullAccess => "danger-full-access",
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use crate::args::{OutputFormat, PermissionMode};
use super::{CliApp, CommandResult, SessionConfig, SlashCommand};
#[test]
fn parses_required_slash_commands() {
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
assert_eq!(
SlashCommand::parse("/compact now"),
Some(SlashCommand::Compact)
);
}
#[test]
fn status_and_compact_commands_update_state() {
let config = SessionConfig {
model: "claude".into(),
permission_mode: PermissionMode::WorkspaceWrite,
config: Some(PathBuf::from("settings.toml")),
output_format: OutputFormat::Text,
};
let mut app = CliApp::new(config);
let mut out = Vec::new();
let result = app
.handle_submission("hello", &mut out)
.expect("submission succeeds");
assert_eq!(result, CommandResult::Continue);
app.handle_submission("/status", &mut out)
.expect("status succeeds");
app.handle_submission("/compact", &mut out)
.expect("compact succeeds");
let output = String::from_utf8_lossy(&out);
assert!(output.contains("status: turns=1"));
assert!(output.contains("Compacted session history"));
}
}
-89
View File
@@ -1,89 +0,0 @@
use std::path::PathBuf;
use clap::{Parser, Subcommand, ValueEnum};
#[derive(Debug, Clone, Parser, PartialEq, Eq)]
#[command(
name = "rusty-claude-cli",
version,
about = "Rust Claude CLI prototype"
)]
pub struct Cli {
#[arg(long, default_value = "claude-3-7-sonnet")]
pub model: String,
#[arg(long, value_enum, default_value_t = PermissionMode::WorkspaceWrite)]
pub permission_mode: PermissionMode,
#[arg(long)]
pub config: Option<PathBuf>,
#[arg(long, value_enum, default_value_t = OutputFormat::Text)]
pub output_format: OutputFormat,
#[command(subcommand)]
pub command: Option<Command>,
}
#[derive(Debug, Clone, Subcommand, PartialEq, Eq)]
pub enum Command {
/// Read upstream TS sources and print extracted counts
DumpManifests,
/// Print the current bootstrap phase skeleton
BootstrapPlan,
/// Run a non-interactive prompt and exit
Prompt { prompt: Vec<String> },
}
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
pub enum PermissionMode {
ReadOnly,
WorkspaceWrite,
DangerFullAccess,
}
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
pub enum OutputFormat {
Text,
Json,
Ndjson,
}
#[cfg(test)]
mod tests {
use clap::Parser;
use super::{Cli, Command, OutputFormat, PermissionMode};
#[test]
fn parses_requested_flags() {
let cli = Cli::parse_from([
"rusty-claude-cli",
"--model",
"claude-3-5-haiku",
"--permission-mode",
"read-only",
"--config",
"/tmp/config.toml",
"--output-format",
"ndjson",
"prompt",
"hello",
"world",
]);
assert_eq!(cli.model, "claude-3-5-haiku");
assert_eq!(cli.permission_mode, PermissionMode::ReadOnly);
assert_eq!(
cli.config.as_deref(),
Some(std::path::Path::new("/tmp/config.toml"))
);
assert_eq!(cli.output_format, OutputFormat::Ndjson);
assert_eq!(
cli.command,
Some(Command::Prompt {
prompt: vec!["hello".into(), "world".into()]
})
);
}
}
-248
View File
@@ -1,248 +0,0 @@
use std::io::{self, Write};
use crossterm::cursor::MoveToColumn;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::queue;
use crossterm::style::Print;
use crossterm::terminal::{disable_raw_mode, enable_raw_mode, Clear, ClearType};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InputBuffer {
buffer: String,
cursor: usize,
}
impl InputBuffer {
#[must_use]
pub fn new() -> Self {
Self {
buffer: String::new(),
cursor: 0,
}
}
pub fn insert(&mut self, ch: char) {
self.buffer.insert(self.cursor, ch);
self.cursor += ch.len_utf8();
}
pub fn insert_newline(&mut self) {
self.insert('\n');
}
pub fn backspace(&mut self) {
if self.cursor == 0 {
return;
}
let previous = self.buffer[..self.cursor]
.char_indices()
.last()
.map_or(0, |(idx, _)| idx);
self.buffer.drain(previous..self.cursor);
self.cursor = previous;
}
pub fn move_left(&mut self) {
if self.cursor == 0 {
return;
}
self.cursor = self.buffer[..self.cursor]
.char_indices()
.last()
.map_or(0, |(idx, _)| idx);
}
pub fn move_right(&mut self) {
if self.cursor >= self.buffer.len() {
return;
}
if let Some(next) = self.buffer[self.cursor..].chars().next() {
self.cursor += next.len_utf8();
}
}
pub fn move_home(&mut self) {
self.cursor = 0;
}
pub fn move_end(&mut self) {
self.cursor = self.buffer.len();
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.buffer
}
#[cfg(test)]
#[must_use]
pub fn cursor(&self) -> usize {
self.cursor
}
pub fn clear(&mut self) {
self.buffer.clear();
self.cursor = 0;
}
}
pub struct LineEditor {
prompt: String,
}
impl LineEditor {
#[must_use]
pub fn new(prompt: impl Into<String>) -> Self {
Self {
prompt: prompt.into(),
}
}
pub fn read_line(&self) -> io::Result<Option<String>> {
enable_raw_mode()?;
let mut stdout = io::stdout();
let mut input = InputBuffer::new();
self.redraw(&mut stdout, &input)?;
loop {
let event = event::read()?;
if let Event::Key(key) = event {
match Self::handle_key(key, &mut input) {
EditorAction::Continue => self.redraw(&mut stdout, &input)?,
EditorAction::Submit => {
disable_raw_mode()?;
writeln!(stdout)?;
return Ok(Some(input.as_str().to_owned()));
}
EditorAction::Cancel => {
disable_raw_mode()?;
writeln!(stdout)?;
return Ok(None);
}
}
}
}
}
fn handle_key(key: KeyEvent, input: &mut InputBuffer) -> EditorAction {
match key {
KeyEvent {
code: KeyCode::Char('c'),
modifiers,
..
} if modifiers.contains(KeyModifiers::CONTROL) => EditorAction::Cancel,
KeyEvent {
code: KeyCode::Char('j'),
modifiers,
..
} if modifiers.contains(KeyModifiers::CONTROL) => {
input.insert_newline();
EditorAction::Continue
}
KeyEvent {
code: KeyCode::Enter,
modifiers,
..
} if modifiers.contains(KeyModifiers::SHIFT) => {
input.insert_newline();
EditorAction::Continue
}
KeyEvent {
code: KeyCode::Enter,
..
} => EditorAction::Submit,
KeyEvent {
code: KeyCode::Backspace,
..
} => {
input.backspace();
EditorAction::Continue
}
KeyEvent {
code: KeyCode::Left,
..
} => {
input.move_left();
EditorAction::Continue
}
KeyEvent {
code: KeyCode::Right,
..
} => {
input.move_right();
EditorAction::Continue
}
KeyEvent {
code: KeyCode::Home,
..
} => {
input.move_home();
EditorAction::Continue
}
KeyEvent {
code: KeyCode::End, ..
} => {
input.move_end();
EditorAction::Continue
}
KeyEvent {
code: KeyCode::Esc, ..
} => {
input.clear();
EditorAction::Cancel
}
KeyEvent {
code: KeyCode::Char(ch),
modifiers,
..
} if modifiers.is_empty() || modifiers == KeyModifiers::SHIFT => {
input.insert(ch);
EditorAction::Continue
}
_ => EditorAction::Continue,
}
}
fn redraw(&self, out: &mut impl Write, input: &InputBuffer) -> io::Result<()> {
let display = input.as_str().replace('\n', "\\n\n> ");
queue!(
out,
MoveToColumn(0),
Clear(ClearType::CurrentLine),
Print(&self.prompt),
Print(display),
)?;
out.flush()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EditorAction {
Continue,
Submit,
Cancel,
}
#[cfg(test)]
mod tests {
use super::InputBuffer;
#[test]
fn supports_basic_line_editing() {
let mut input = InputBuffer::new();
input.insert('h');
input.insert('i');
input.move_end();
input.insert_newline();
input.insert('x');
assert_eq!(input.as_str(), "hi\nx");
assert_eq!(input.cursor(), 4);
input.move_left();
input.backspace();
assert_eq!(input.as_str(), "hix");
assert_eq!(input.cursor(), 2);
}
}
+32 -41
View File
@@ -1,59 +1,42 @@
mod app;
mod args;
mod input;
mod render;
use std::env;
use std::path::PathBuf;
use app::{CliApp, SessionConfig};
use args::{Cli, Command};
use clap::Parser;
use compat_harness::{extract_manifest, UpstreamPaths};
use runtime::BootstrapPlan;
fn main() {
let cli = Cli::parse();
let args: Vec<String> = env::args().skip(1).collect();
let result = match &cli.command {
Some(Command::DumpManifests) => dump_manifests(),
Some(Command::BootstrapPlan) => {
print_bootstrap_plan();
Ok(())
}
Some(Command::Prompt { prompt }) => {
let joined = prompt.join(" ");
let mut app = CliApp::new(build_session_config(&cli));
app.run_prompt(&joined, &mut std::io::stdout())
match args.first().map(String::as_str) {
Some("dump-manifests") => dump_manifests(),
Some("bootstrap-plan") => print_bootstrap_plan(),
Some("--help" | "-h") => print_help(),
Some(other) => {
eprintln!("unknown subcommand: {other}");
print_help();
std::process::exit(2);
}
None => {
let mut app = CliApp::new(build_session_config(&cli));
app.run_repl()
println!("rusty-claude-cli: Rust compatibility foundation only.");
println!("Run `rusty-claude-cli --help` for the current scaffold commands.");
}
};
if let Err(error) = result {
eprintln!("{error}");
std::process::exit(1);
}
}
fn build_session_config(cli: &Cli) -> SessionConfig {
SessionConfig {
model: cli.model.clone(),
permission_mode: cli.permission_mode,
config: cli.config.clone(),
output_format: cli.output_format,
}
}
fn dump_manifests() -> std::io::Result<()> {
fn dump_manifests() {
let workspace_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
let paths = UpstreamPaths::from_workspace_dir(&workspace_dir);
let manifest = extract_manifest(&paths)?;
println!("commands: {}", manifest.commands.entries().len());
println!("tools: {}", manifest.tools.entries().len());
println!("bootstrap phases: {}", manifest.bootstrap.phases().len());
Ok(())
match extract_manifest(&paths) {
Ok(manifest) => {
println!("commands: {}", manifest.commands.entries().len());
println!("tools: {}", manifest.tools.entries().len());
println!("bootstrap phases: {}", manifest.bootstrap.phases().len());
}
Err(error) => {
eprintln!("failed to extract manifests: {error}");
std::process::exit(1);
}
}
}
fn print_bootstrap_plan() {
@@ -61,3 +44,11 @@ fn print_bootstrap_plan() {
println!("- {phase:?}");
}
}
fn print_help() {
println!("rusty-claude-cli");
println!();
println!("Current scaffold commands:");
println!(" dump-manifests Read upstream TS sources and print extracted counts");
println!(" bootstrap-plan Print the current bootstrap phase skeleton");
}
-244
View File
@@ -1,244 +0,0 @@
use std::fmt::Write as FmtWrite;
use std::io::{self, Write};
use std::thread;
use std::time::Duration;
use crossterm::cursor::{MoveToColumn, RestorePosition, SavePosition};
use crossterm::style::{Color, Print, ResetColor, SetForegroundColor, Stylize};
use crossterm::terminal::{Clear, ClearType};
use crossterm::{execute, queue};
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
use syntect::easy::HighlightLines;
use syntect::highlighting::{Theme, ThemeSet};
use syntect::parsing::SyntaxSet;
use syntect::util::{as_24_bit_terminal_escaped, LinesWithEndings};
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Spinner {
frame_index: usize,
}
impl Spinner {
const FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn tick(&mut self, label: &str, out: &mut impl Write) -> io::Result<()> {
let frame = Self::FRAMES[self.frame_index % Self::FRAMES.len()];
self.frame_index += 1;
queue!(
out,
SavePosition,
MoveToColumn(0),
Clear(ClearType::CurrentLine),
SetForegroundColor(Color::Blue),
Print(format!("{frame} {label}")),
ResetColor,
RestorePosition
)?;
out.flush()
}
pub fn finish(&mut self, label: &str, out: &mut impl Write) -> io::Result<()> {
self.frame_index = 0;
execute!(
out,
MoveToColumn(0),
Clear(ClearType::CurrentLine),
SetForegroundColor(Color::Green),
Print(format!("✔ {label}\n")),
ResetColor
)?;
out.flush()
}
}
#[derive(Debug)]
pub struct TerminalRenderer {
syntax_set: SyntaxSet,
theme: Theme,
}
impl Default for TerminalRenderer {
fn default() -> Self {
let syntax_set = SyntaxSet::load_defaults_newlines();
let theme = ThemeSet::load_defaults()
.themes
.remove("base16-ocean.dark")
.unwrap_or_default();
Self { syntax_set, theme }
}
}
impl TerminalRenderer {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn render_markdown(&self, markdown: &str) -> String {
let mut output = String::new();
let parser = Parser::new_ext(markdown, Options::all());
let mut in_code_block = false;
let mut code_language = String::new();
let mut code_buffer = String::new();
let mut list_depth = 0usize;
for event in parser {
match event {
Event::Start(Tag::Heading { level, .. }) => {
output.push('\n');
let prefix = match level as u8 {
1 => "# ",
2 => "## ",
3 => "### ",
_ => "#### ",
};
output.push_str(prefix);
}
Event::End(TagEnd::Heading(..) | TagEnd::Paragraph) => {
output.push_str("\n\n");
}
Event::Start(Tag::BlockQuote(..)) => output.push_str("│ "),
Event::End(TagEnd::BlockQuote(..) | TagEnd::Item)
| Event::SoftBreak
| Event::HardBreak => output.push('\n'),
Event::Start(Tag::List(_)) => list_depth += 1,
Event::End(TagEnd::List(..)) => {
list_depth = list_depth.saturating_sub(1);
output.push('\n');
}
Event::Start(Tag::Item) => {
output.push_str(&" ".repeat(list_depth.saturating_sub(1)));
output.push_str("• ");
}
Event::Start(Tag::CodeBlock(kind)) => {
in_code_block = true;
code_language = match kind {
CodeBlockKind::Indented => String::from("text"),
CodeBlockKind::Fenced(lang) => lang.to_string(),
};
code_buffer.clear();
}
Event::End(TagEnd::CodeBlock) => {
output.push_str(&self.highlight_code(&code_buffer, &code_language));
output.push('\n');
in_code_block = false;
code_language.clear();
code_buffer.clear();
}
Event::Code(code) => {
let _ = write!(output, "{}", format!("`{code}`").with(Color::Yellow));
}
Event::Rule => output.push_str("---\n"),
Event::Text(text) => {
if in_code_block {
code_buffer.push_str(&text);
} else {
output.push_str(&text);
}
}
Event::Html(html) | Event::InlineHtml(html) => output.push_str(&html),
Event::FootnoteReference(reference) => {
let _ = write!(output, "[{reference}]");
}
Event::TaskListMarker(done) => {
output.push_str(if done { "[x] " } else { "[ ] " });
}
Event::InlineMath(math) | Event::DisplayMath(math) => output.push_str(&math),
Event::Start(Tag::Link { dest_url, .. }) => {
let _ = write!(output, "[{dest_url}]");
}
Event::Start(Tag::Image { dest_url, .. }) => {
let _ = write!(output, "[image:{dest_url}]");
}
Event::Start(
Tag::Paragraph
| Tag::Emphasis
| Tag::Strong
| Tag::Table(..)
| Tag::TableHead
| Tag::TableRow
| Tag::TableCell
| Tag::MetadataBlock(..)
| _,
)
| Event::End(
TagEnd::Emphasis
| TagEnd::Strong
| TagEnd::Link
| TagEnd::Image
| TagEnd::Table
| TagEnd::TableHead
| TagEnd::TableRow
| TagEnd::TableCell
| TagEnd::MetadataBlock(..)
| _,
) => {}
}
}
output.trim_end().to_string()
}
#[must_use]
pub fn highlight_code(&self, code: &str, language: &str) -> String {
let syntax = self
.syntax_set
.find_syntax_by_token(language)
.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text());
let mut syntax_highlighter = HighlightLines::new(syntax, &self.theme);
let mut colored_output = String::new();
for line in LinesWithEndings::from(code) {
match syntax_highlighter.highlight_line(line, &self.syntax_set) {
Ok(ranges) => {
colored_output.push_str(&as_24_bit_terminal_escaped(&ranges[..], false));
}
Err(_) => colored_output.push_str(line),
}
}
colored_output
}
pub fn stream_markdown(&self, markdown: &str, out: &mut impl Write) -> io::Result<()> {
let rendered_markdown = self.render_markdown(markdown);
for chunk in rendered_markdown.split_inclusive(char::is_whitespace) {
write!(out, "{chunk}")?;
out.flush()?;
thread::sleep(Duration::from_millis(8));
}
writeln!(out)
}
}
#[cfg(test)]
mod tests {
use super::{Spinner, TerminalRenderer};
#[test]
fn renders_basic_markdown_features() {
let terminal_renderer = TerminalRenderer::new();
let markdown_output = terminal_renderer.render_markdown("# Heading\n\n- item\n\n`code`");
assert!(markdown_output.contains("# Heading"));
assert!(markdown_output.contains("• item"));
assert!(markdown_output.contains("code"));
}
#[test]
fn spinner_advances_frames() {
let mut spinner = Spinner::new();
let mut out = Vec::new();
spinner.tick("Working", &mut out).expect("tick succeeds");
spinner.tick("Working", &mut out).expect("tick succeeds");
let output = String::from_utf8_lossy(&out);
assert!(output.contains("Working"));
}
}
+8
View File
@@ -5,5 +5,13 @@ edition.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
regex = "1.12"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
[dev-dependencies]
tempfile = "3.20"
[lints]
workspace = true
+987
View File
@@ -1,3 +1,14 @@
use regex::RegexBuilder;
use serde::Serialize;
use serde_json::{json, Value};
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolManifestEntry {
pub name: String,
@@ -26,3 +37,979 @@ impl ToolRegistry {
&self.entries
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TextContent {
#[serde(rename = "type")]
pub kind: &'static str,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ToolResult {
pub content: Vec<TextContent>,
}
impl ToolResult {
#[must_use]
pub fn text(text: impl Into<String>) -> Self {
Self {
content: vec![TextContent {
kind: "text",
text: text.into(),
}],
}
}
}
#[derive(Debug)]
pub struct ToolError {
message: Cow<'static, str>,
}
impl ToolError {
#[must_use]
pub fn new(message: impl Into<Cow<'static, str>>) -> Self {
Self {
message: message.into(),
}
}
}
impl fmt::Display for ToolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ToolError {}
impl From<io::Error> for ToolError {
fn from(value: io::Error) -> Self {
Self::new(value.to_string())
}
}
impl From<regex::Error> for ToolError {
fn from(value: regex::Error) -> Self {
Self::new(value.to_string())
}
}
pub trait Tool {
fn name(&self) -> &'static str;
fn description(&self) -> &'static str;
fn input_schema(&self) -> Value;
fn execute(&self, input: Value) -> Result<ToolResult, ToolError>;
}
fn schema_string(description: &str) -> Value {
json!({ "type": "string", "description": description })
}
fn schema_number(description: &str) -> Value {
json!({ "type": "number", "description": description })
}
fn schema_boolean(description: &str) -> Value {
json!({ "type": "boolean", "description": description })
}
fn strict_object(properties: &Value, required: &[&str]) -> Value {
json!({
"type": "object",
"properties": properties,
"required": required,
"additionalProperties": false,
})
}
fn parse_string(input: &Value, key: &'static str) -> Result<String, ToolError> {
input
.get(key)
.and_then(Value::as_str)
.map(ToOwned::to_owned)
.ok_or_else(|| ToolError::new(format!("missing or invalid string field: {key}")))
}
fn optional_string(input: &Value, key: &'static str) -> Result<Option<String>, ToolError> {
match input.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(value)) => Ok(Some(value.clone())),
Some(_) => Err(ToolError::new(format!("invalid string field: {key}"))),
}
}
fn optional_u64(input: &Value, key: &'static str) -> Result<Option<u64>, ToolError> {
match input.get(key) {
None | Some(Value::Null) => Ok(None),
Some(value) => value
.as_u64()
.ok_or_else(|| ToolError::new(format!("invalid numeric field: {key}")))
.map(Some),
}
}
fn optional_bool(input: &Value, key: &'static str) -> Result<Option<bool>, ToolError> {
match input.get(key) {
None | Some(Value::Null) => Ok(None),
Some(value) => value
.as_bool()
.ok_or_else(|| ToolError::new(format!("invalid boolean field: {key}")))
.map(Some),
}
}
fn absolute_path(path: &str) -> Result<PathBuf, ToolError> {
let expanded = if let Some(rest) = path.strip_prefix("~/") {
std::env::var_os("HOME")
.map(PathBuf::from)
.map_or_else(|| PathBuf::from(path), |home| home.join(rest))
} else {
PathBuf::from(path)
};
if expanded.is_absolute() {
Ok(expanded)
} else {
Err(ToolError::new(format!("path must be absolute: {path}")))
}
}
fn relative_display(path: &Path, base: &Path) -> String {
path.strip_prefix(base).ok().map_or_else(
|| path.to_string_lossy().replace('\\', "/"),
|value| value.to_string_lossy().replace('\\', "/"),
)
}
fn line_slice(content: &str, offset: Option<u64>, limit: Option<u64>) -> String {
let start = usize_from_u64(offset.unwrap_or(1).saturating_sub(1));
let lines: Vec<&str> = content.lines().collect();
let end = limit
.map_or(lines.len(), |limit| {
start.saturating_add(usize_from_u64(limit))
})
.min(lines.len());
if start >= lines.len() {
return String::new();
}
lines[start..end]
.iter()
.enumerate()
.map(|(index, line)| format!("{:>6}\t{line}", start + index + 1))
.collect::<Vec<_>>()
.join("\n")
}
fn parse_page_range(pages: &str) -> Result<(u64, u64), ToolError> {
if let Some((start, end)) = pages.split_once('-') {
let start = start
.trim()
.parse::<u64>()
.map_err(|_| ToolError::new("invalid pages parameter"))?;
let end = end
.trim()
.parse::<u64>()
.map_err(|_| ToolError::new("invalid pages parameter"))?;
if start == 0 || end < start {
return Err(ToolError::new("invalid pages parameter"));
}
Ok((start, end))
} else {
let page = pages
.trim()
.parse::<u64>()
.map_err(|_| ToolError::new("invalid pages parameter"))?;
if page == 0 {
return Err(ToolError::new("invalid pages parameter"));
}
Ok((page, page))
}
}
fn apply_single_edit(
original: &str,
old_string: &str,
new_string: &str,
replace_all: bool,
) -> Result<String, ToolError> {
if old_string == new_string {
return Err(ToolError::new(
"No changes to make: old_string and new_string are exactly the same.",
));
}
if old_string.is_empty() {
if original.is_empty() {
return Ok(new_string.to_owned());
}
return Err(ToolError::new(
"Cannot create new file - file already exists.",
));
}
let matches = original.matches(old_string).count();
if matches == 0 {
return Err(ToolError::new(format!(
"String to replace not found in file.\nString: {old_string}"
)));
}
if matches > 1 && !replace_all {
return Err(ToolError::new(format!(
"Found {matches} matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\nString: {old_string}"
)));
}
let updated = if replace_all {
original.replace(old_string, new_string)
} else {
original.replacen(old_string, new_string, 1)
};
Ok(updated)
}
fn diff_hunks(_before: &str, _after: &str) -> Value {
json!([])
}
fn usize_from_u64(value: u64) -> usize {
usize::try_from(value).unwrap_or(usize::MAX)
}
pub struct BashTool;
pub struct ReadTool;
pub struct WriteTool;
pub struct EditTool;
pub struct GlobTool;
pub struct GrepTool;
impl Tool for BashTool {
fn name(&self) -> &'static str {
"Bash"
}
fn description(&self) -> &'static str {
"Execute a shell command in the current environment."
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"command": schema_string("The command to execute"),
"timeout": schema_number("Optional timeout in milliseconds (max 600000)"),
"description": schema_string("Clear, concise description of what this command does in active voice. Never use words like \"complex\" or \"risk\" in the description - just describe what it does."),
"run_in_background": schema_boolean("Set to true to run this command in the background. Use Read to read the output later."),
"dangerouslyDisableSandbox": schema_boolean("Set this to true to dangerously override sandbox mode and run commands without sandboxing.")
}),
&["command"],
)
}
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let command = parse_string(&input, "command")?;
let _timeout = optional_u64(&input, "timeout")?;
let _description = optional_string(&input, "description")?;
let run_in_background = optional_bool(&input, "run_in_background")?.unwrap_or(false);
let _disable_sandbox = optional_bool(&input, "dangerouslyDisableSandbox")?.unwrap_or(false);
if run_in_background {
return Ok(ToolResult::text(
"Background execution is not supported in this runtime.",
));
}
let output = Command::new("bash").arg("-lc").arg(&command).output()?;
let mut rendered = String::new();
if !output.stdout.is_empty() {
rendered.push_str(&String::from_utf8_lossy(&output.stdout));
}
if !output.stderr.is_empty() {
if !rendered.is_empty() && !rendered.ends_with('\n') {
rendered.push('\n');
}
rendered.push_str(&String::from_utf8_lossy(&output.stderr));
}
if rendered.is_empty() {
rendered = if output.status.success() {
"Done".to_owned()
} else {
format!("Command exited with status {}", output.status)
};
}
Ok(ToolResult::text(rendered.trim_end().to_owned()))
}
}
impl Tool for ReadTool {
fn name(&self) -> &'static str {
"Read"
}
fn description(&self) -> &'static str {
"Read a file from the local filesystem."
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"file_path": schema_string("The absolute path to the file to read"),
"offset": json!({"type":"number","description":"The line number to start reading from. Only provide if the file is too large to read at once","minimum":0}),
"limit": json!({"type":"number","description":"The number of lines to read. Only provide if the file is too large to read at once.","exclusiveMinimum":0}),
"pages": schema_string("Page range for PDF files (e.g., \"1-5\", \"3\", \"10-20\"). Only applicable to PDF files. Maximum 20 pages per request.")
}),
&["file_path"],
)
}
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let file_path = parse_string(&input, "file_path")?;
let path = absolute_path(&file_path)?;
let offset = optional_u64(&input, "offset")?;
let limit = optional_u64(&input, "limit")?;
let pages = optional_string(&input, "pages")?;
let content = fs::read_to_string(&path)?;
if path.extension().and_then(|ext| ext.to_str()) == Some("pdf") {
if let Some(pages) = pages {
let (start, end) = parse_page_range(&pages)?;
return Ok(ToolResult::text(format!(
"PDF page extraction is not implemented in Rust yet for {}. Requested pages {}-{}.",
path.display(), start, end
)));
}
}
let rendered = if offset.is_some() || limit.is_some() {
line_slice(&content, offset, limit)
} else {
line_slice(&content, Some(1), None)
};
Ok(ToolResult::text(rendered))
}
}
impl Tool for WriteTool {
fn name(&self) -> &'static str {
"Write"
}
fn description(&self) -> &'static str {
"Write a file to the local filesystem."
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"file_path": schema_string("The absolute path to the file to write (must be absolute, not relative)"),
"content": schema_string("The content to write to the file")
}),
&["file_path", "content"],
)
}
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let file_path = parse_string(&input, "file_path")?;
let content = parse_string(&input, "content")?;
let path = absolute_path(&file_path)?;
let existed = path.exists();
let original = if existed {
Some(fs::read_to_string(&path)?)
} else {
None
};
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, &content)?;
let payload = json!({
"type": if existed { "update" } else { "create" },
"filePath": file_path,
"content": content,
"structuredPatch": diff_hunks(original.as_deref().unwrap_or(""), &content),
"originalFile": original,
"gitDiff": Value::Null,
});
Ok(ToolResult::text(payload.to_string()))
}
}
impl Tool for EditTool {
fn name(&self) -> &'static str {
"Edit"
}
fn description(&self) -> &'static str {
"A tool for editing files"
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"file_path": schema_string("The absolute path to the file to modify"),
"old_string": schema_string("The text to replace"),
"new_string": schema_string("The text to replace it with (must be different from old_string)"),
"replace_all": json!({"type":"boolean","description":"Replace all occurrences of old_string (default false)","default":false})
}),
&["file_path", "old_string", "new_string"],
)
}
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let file_path = parse_string(&input, "file_path")?;
let old_string = parse_string(&input, "old_string")?;
let new_string = parse_string(&input, "new_string")?;
let replace_all = optional_bool(&input, "replace_all")?.unwrap_or(false);
let path = absolute_path(&file_path)?;
let original = if path.exists() {
fs::read_to_string(&path)?
} else {
String::new()
};
let updated = apply_single_edit(&original, &old_string, &new_string, replace_all)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, &updated)?;
let payload = json!({
"filePath": file_path,
"oldString": old_string,
"newString": new_string,
"originalFile": original,
"structuredPatch": diff_hunks("", ""),
"userModified": false,
"replaceAll": replace_all,
"gitDiff": Value::Null,
});
Ok(ToolResult::text(payload.to_string()))
}
}
impl Tool for GlobTool {
fn name(&self) -> &'static str {
"Glob"
}
fn description(&self) -> &'static str {
"Fast file pattern matching tool"
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"pattern": schema_string("The glob pattern to match files against"),
"path": schema_string("The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter \"undefined\" or \"null\" - simply omit it for the default behavior. Must be a valid directory path if provided.")
}),
&["pattern"],
)
}
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let pattern = parse_string(&input, "pattern")?;
let root = optional_string(&input, "path")?
.map(|path| absolute_path(&path))
.transpose()?
.unwrap_or(std::env::current_dir()?);
let start = std::time::Instant::now();
let mut filenames = Vec::new();
visit_files(&root, &mut |path| {
let relative = relative_display(path, &root);
if glob_matches(&pattern, &relative) {
filenames.push(relative);
}
})?;
filenames.sort();
let truncated = filenames.len() > 100;
if truncated {
filenames.truncate(100);
}
let payload = json!({
"durationMs": start.elapsed().as_millis(),
"numFiles": filenames.len(),
"filenames": filenames,
"truncated": truncated,
});
Ok(ToolResult::text(payload.to_string()))
}
}
impl Tool for GrepTool {
fn name(&self) -> &'static str {
"Grep"
}
fn description(&self) -> &'static str {
"Fast content search tool"
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"pattern": schema_string("The regular expression pattern to search for in file contents"),
"path": schema_string("File or directory to search in (rg PATH). Defaults to current working directory."),
"glob": schema_string("Glob pattern to filter files (e.g. \"*.js\", \"*.{ts,tsx}\") - maps to rg --glob"),
"output_mode": {"type":"string","enum":["content","files_with_matches","count"],"description":"Output mode: \"content\" shows matching lines (supports -A/-B/-C context, -n line numbers, head_limit), \"files_with_matches\" shows file paths (supports head_limit), \"count\" shows match counts (supports head_limit). Defaults to \"files_with_matches\"."},
"-B": schema_number("Number of lines to show before each match (rg -B). Requires output_mode: \"content\", ignored otherwise."),
"-A": schema_number("Number of lines to show after each match (rg -A). Requires output_mode: \"content\", ignored otherwise."),
"-C": schema_number("Alias for context."),
"context": schema_number("Number of lines to show before and after each match (rg -C). Requires output_mode: \"content\", ignored otherwise."),
"-n": {"type":"boolean","description":"Show line numbers in output (rg -n). Requires output_mode: \"content\", ignored otherwise. Defaults to true."},
"-i": schema_boolean("Case insensitive search (rg -i)"),
"type": schema_string("File type to search (rg --type). Common types: js, py, rust, go, java, etc. More efficient than include for standard file types."),
"head_limit": schema_number("Limit output to first N lines/entries, equivalent to \"| head -N\". Works across all output modes: content (limits output lines), files_with_matches (limits file paths), count (limits count entries). Defaults to 250 when unspecified. Pass 0 for unlimited (use sparingly — large result sets waste context)."),
"offset": schema_number("Skip first N lines/entries before applying head_limit, equivalent to \"| tail -n +N | head -N\". Works across all output modes. Defaults to 0."),
"multiline": schema_boolean("Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall). Default: false.")
}),
&["pattern"],
)
}
#[allow(clippy::too_many_lines)]
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let pattern = parse_string(&input, "pattern")?;
let root = optional_string(&input, "path")?
.map(|path| absolute_path(&path))
.transpose()?
.unwrap_or(std::env::current_dir()?);
let glob = optional_string(&input, "glob")?;
let output_mode = optional_string(&input, "output_mode")?
.unwrap_or_else(|| "files_with_matches".to_owned());
let context_before = usize_from_u64(optional_u64(&input, "-B")?.unwrap_or(0));
let context_after = usize_from_u64(optional_u64(&input, "-A")?.unwrap_or(0));
let context_c = optional_u64(&input, "-C")?;
let context = optional_u64(&input, "context")?;
let show_line_numbers = optional_bool(&input, "-n")?.unwrap_or(true);
let case_insensitive = optional_bool(&input, "-i")?.unwrap_or(false);
let file_type = optional_string(&input, "type")?;
let head_limit = optional_u64(&input, "head_limit")?;
let offset = usize_from_u64(optional_u64(&input, "offset")?.unwrap_or(0));
let _multiline = optional_bool(&input, "multiline")?.unwrap_or(false);
let shared_context = usize_from_u64(context.or(context_c).unwrap_or(0));
let regex = RegexBuilder::new(&pattern)
.case_insensitive(case_insensitive)
.build()?;
let mut matched_lines = Vec::new();
let mut files_with_matches = Vec::new();
let mut count_lines = Vec::new();
let mut total_matches = 0usize;
let candidates = collect_files(&root)?;
for path in candidates {
let relative = relative_display(&path, &root);
if !matches_file_filter(&relative, glob.as_deref(), file_type.as_deref()) {
continue;
}
let Ok(file_content) = fs::read_to_string(&path) else {
continue;
};
let lines: Vec<&str> = file_content.lines().collect();
let mut matched_indexes = Vec::new();
let mut file_match_count = 0usize;
for (index, line) in lines.iter().enumerate() {
if regex.is_match(line) {
matched_indexes.push(index);
file_match_count += regex.find_iter(line).count().max(1);
}
}
if matched_indexes.is_empty() {
continue;
}
total_matches += file_match_count;
files_with_matches.push(relative.clone());
count_lines.push(format!("{relative}:{file_match_count}"));
if output_mode == "content" {
let mut included = BTreeSet::new();
for index in matched_indexes {
let before = if shared_context > 0 {
shared_context
} else {
context_before
};
let after = if shared_context > 0 {
shared_context
} else {
context_after
};
let start = index.saturating_sub(before);
let end = (index + after).min(lines.len().saturating_sub(1));
for line_index in start..=end {
included.insert(line_index);
}
}
for line_index in included {
if show_line_numbers {
matched_lines.push(format!(
"{relative}:{}:{}",
line_index + 1,
lines[line_index]
));
} else {
matched_lines.push(format!("{relative}:{}", lines[line_index]));
}
}
}
}
let rendered = match output_mode.as_str() {
"content" => {
let limited = apply_offset_limit(matched_lines, head_limit, offset);
json!({
"mode": "content",
"numFiles": 0,
"filenames": [],
"content": limited.join("\n"),
"numLines": limited.len(),
"appliedOffset": (offset > 0).then_some(offset),
})
}
"count" => {
let limited = apply_offset_limit(count_lines, head_limit, offset);
json!({
"mode": "count",
"numFiles": files_with_matches.len(),
"filenames": [],
"content": limited.join("\n"),
"numMatches": total_matches,
"appliedOffset": (offset > 0).then_some(offset),
})
}
_ => {
files_with_matches.sort();
let limited = apply_offset_limit(files_with_matches, head_limit, offset);
json!({
"mode": "files_with_matches",
"numFiles": limited.len(),
"filenames": limited,
"appliedOffset": (offset > 0).then_some(offset),
})
}
};
Ok(ToolResult::text(rendered.to_string()))
}
}
fn apply_offset_limit<T>(items: Vec<T>, limit: Option<u64>, offset: usize) -> Vec<T> {
let mut iter = items.into_iter().skip(offset);
match limit {
Some(0) | None => iter.collect(),
Some(limit) => iter.by_ref().take(usize_from_u64(limit)).collect(),
}
}
fn collect_files(root: &Path) -> Result<Vec<PathBuf>, ToolError> {
let mut files = Vec::new();
if root.is_file() {
files.push(root.to_path_buf());
return Ok(files);
}
visit_files(root, &mut |path| files.push(path.to_path_buf()))?;
Ok(files)
}
fn visit_files(root: &Path, visitor: &mut dyn FnMut(&Path)) -> Result<(), ToolError> {
if root.is_file() {
visitor(root);
return Ok(());
}
for entry in fs::read_dir(root)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
visit_files(&path, visitor)?;
} else if path.is_file() {
visitor(&path);
}
}
Ok(())
}
fn matches_file_filter(relative: &str, glob: Option<&str>, file_type: Option<&str>) -> bool {
let glob_ok = glob.is_none_or(|pattern| {
split_glob_patterns(pattern)
.into_iter()
.any(|single| glob_matches(&single, relative))
});
let type_ok = file_type.is_none_or(|kind| path_matches_type(relative, kind));
glob_ok && type_ok
}
fn split_glob_patterns(patterns: &str) -> Vec<String> {
let mut result = Vec::new();
for raw in patterns.split_whitespace() {
if raw.contains('{') && raw.contains('}') {
result.push(raw.to_owned());
} else {
result.extend(
raw.split(',')
.filter(|part| !part.is_empty())
.map(ToOwned::to_owned),
);
}
}
result
}
fn path_matches_type(relative: &str, kind: &str) -> bool {
let extension = Path::new(relative)
.extension()
.and_then(|value| value.to_str())
.unwrap_or_default();
matches!(
(kind, extension),
("rust", "rs")
| ("js", "js")
| ("ts", "ts")
| ("tsx", "tsx")
| ("py", "py")
| ("go", "go")
| ("java", "java")
| ("json", "json")
| ("md", "md")
)
}
fn glob_matches(pattern: &str, path: &str) -> bool {
expand_braces(pattern)
.into_iter()
.any(|expanded| glob_match_one(&expanded, path))
}
fn expand_braces(pattern: &str) -> Vec<String> {
let Some(start) = pattern.find('{') else {
return vec![pattern.to_owned()];
};
let Some(end_rel) = pattern[start..].find('}') else {
return vec![pattern.to_owned()];
};
let end = start + end_rel;
let prefix = &pattern[..start];
let suffix = &pattern[end + 1..];
pattern[start + 1..end]
.split(',')
.flat_map(|middle| expand_braces(&format!("{prefix}{middle}{suffix}")))
.collect()
}
fn glob_match_one(pattern: &str, path: &str) -> bool {
let pattern = pattern.replace('\\', "/");
let path = path.replace('\\', "/");
let pattern_parts: Vec<&str> = pattern.split('/').collect();
let path_parts: Vec<&str> = path.split('/').collect();
glob_match_parts(&pattern_parts, &path_parts)
}
fn glob_match_parts(pattern: &[&str], path: &[&str]) -> bool {
if pattern.is_empty() {
return path.is_empty();
}
if pattern[0] == "**" {
if glob_match_parts(&pattern[1..], path) {
return true;
}
if !path.is_empty() {
return glob_match_parts(pattern, &path[1..]);
}
return false;
}
if path.is_empty() {
return false;
}
if segment_matches(pattern[0], path[0]) {
return glob_match_parts(&pattern[1..], &path[1..]);
}
false
}
fn segment_matches(pattern: &str, text: &str) -> bool {
let p = pattern.as_bytes();
let t = text.as_bytes();
let (mut pi, mut ti, mut star_idx, mut match_idx) = (0usize, 0usize, None, 0usize);
while ti < t.len() {
if pi < p.len() && (p[pi] == b'?' || p[pi] == t[ti]) {
pi += 1;
ti += 1;
} else if pi < p.len() && p[pi] == b'*' {
star_idx = Some(pi);
match_idx = ti;
pi += 1;
} else if let Some(star) = star_idx {
pi = star + 1;
match_idx += 1;
ti = match_idx;
} else {
return false;
}
}
while pi < p.len() && p[pi] == b'*' {
pi += 1;
}
pi == p.len()
}
#[must_use]
pub fn core_tools() -> Vec<Box<dyn Tool>> {
vec![
Box::new(BashTool),
Box::new(ReadTool),
Box::new(WriteTool),
Box::new(EditTool),
Box::new(GlobTool),
Box::new(GrepTool),
]
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use tempfile::tempdir;
fn text(result: &ToolResult) -> String {
result.content[0].text.clone()
}
#[test]
fn manifests_core_tools() {
let names: Vec<_> = core_tools().into_iter().map(|tool| tool.name()).collect();
assert_eq!(names, vec!["Bash", "Read", "Write", "Edit", "Glob", "Grep"]);
}
#[test]
fn bash_executes_command() {
let result = BashTool
.execute(json!({ "command": "printf 'hello'" }))
.unwrap();
assert_eq!(text(&result), "hello");
}
#[test]
fn read_schema_matches_expected_keys() {
let schema = ReadTool.input_schema();
let properties = schema["properties"].as_object().unwrap();
assert_eq!(schema["required"], json!(["file_path"]));
assert!(properties.contains_key("file_path"));
assert!(properties.contains_key("offset"));
assert!(properties.contains_key("limit"));
assert!(properties.contains_key("pages"));
}
#[test]
fn read_returns_numbered_lines() {
let dir = tempdir().unwrap();
let path = dir.path().join("sample.txt");
fs::write(&path, "alpha\nbeta\ngamma\n").unwrap();
let result = ReadTool
.execute(json!({ "file_path": path.to_string_lossy(), "offset": 2, "limit": 1 }))
.unwrap();
assert_eq!(text(&result), " 2\tbeta");
}
#[test]
fn write_creates_file_and_reports_create() {
let dir = tempdir().unwrap();
let path = dir.path().join("new.txt");
let result = WriteTool
.execute(json!({ "file_path": path.to_string_lossy(), "content": "hello" }))
.unwrap();
let payload: Value = serde_json::from_str(&text(&result)).unwrap();
assert_eq!(payload["type"], "create");
assert_eq!(fs::read_to_string(path).unwrap(), "hello");
}
#[test]
fn edit_replaces_single_match() {
let dir = tempdir().unwrap();
let path = dir.path().join("edit.txt");
fs::write(&path, "hello world\n").unwrap();
let result = EditTool
.execute(json!({
"file_path": path.to_string_lossy(),
"old_string": "world",
"new_string": "rust",
"replace_all": false
}))
.unwrap();
let payload: Value = serde_json::from_str(&text(&result)).unwrap();
assert_eq!(payload["replaceAll"], false);
assert_eq!(fs::read_to_string(path).unwrap(), "hello rust\n");
}
#[test]
fn glob_finds_matching_files() {
let dir = tempdir().unwrap();
fs::create_dir_all(dir.path().join("src/nested")).unwrap();
fs::write(dir.path().join("src/lib.rs"), "").unwrap();
fs::write(dir.path().join("src/nested/main.rs"), "").unwrap();
fs::write(dir.path().join("README.md"), "").unwrap();
let result = GlobTool
.execute(json!({ "pattern": "**/*.rs", "path": dir.path().to_string_lossy() }))
.unwrap();
let payload: Value = serde_json::from_str(&text(&result)).unwrap();
assert_eq!(payload["numFiles"], 2);
assert_eq!(
payload["filenames"],
json!(["src/lib.rs", "src/nested/main.rs"])
);
}
#[test]
fn grep_supports_file_list_mode() {
let dir = tempdir().unwrap();
fs::write(dir.path().join("a.rs"), "fn main() {}\nlet alpha = 1;\n").unwrap();
fs::write(dir.path().join("b.txt"), "alpha\nalpha\n").unwrap();
let result = GrepTool
.execute(json!({
"pattern": "alpha",
"path": dir.path().to_string_lossy(),
"output_mode": "files_with_matches"
}))
.unwrap();
let payload: Value = serde_json::from_str(&text(&result)).unwrap();
assert_eq!(payload["filenames"], json!(["a.rs", "b.txt"]));
}
#[test]
fn grep_supports_content_and_count_modes() {
let dir = tempdir().unwrap();
fs::write(dir.path().join("a.rs"), "alpha\nbeta\nalpha\n").unwrap();
let content = GrepTool
.execute(json!({
"pattern": "alpha",
"path": dir.path().to_string_lossy(),
"output_mode": "content",
"-n": true
}))
.unwrap();
let content_payload: Value = serde_json::from_str(&text(&content)).unwrap();
assert_eq!(content_payload["numLines"], 2);
assert!(content_payload["content"]
.as_str()
.unwrap()
.contains("a.rs:1:alpha"));
let count = GrepTool
.execute(json!({
"pattern": "alpha",
"path": dir.path().to_string_lossy(),
"output_mode": "count"
}))
.unwrap();
let count_payload: Value = serde_json::from_str(&text(&count)).unwrap();
assert_eq!(count_payload["numMatches"], 2);
assert_eq!(count_payload["content"], "a.rs:2");
}
}