README Source History Refs Reviews Compare Notes Search Review guide core(SMH-PLAN-CORE0001): implement session, framing, tools, and bounded bash 0e7875172c50b61f410b36873162cec2d12cefbf
Oliver Jan Krylow <oliver@bugabinga.net > · 10 Sep 2026
unsigned
Browse files Compare with HEAD
Approve the plan after foundation gates and deliver the provider-free
runtime across two crates: shared IDs, messages, stream events, tool
metadata, cancellation, and errors in smith; validated config, session
model, CBOR framing, durable store, replay traces, tool registry with
file effects, and bounded cancellable bash in smith-core.
Harden per review findings: tagged content blocks keep Thinking distinct
on disk; opening a session repairs torn tails before appending; repairs
publish atomically; the writer enforces the configured frame limit and
holds an exclusive lock; loaders decode incrementally and skip oversized
frames by intact length; tool schemas validate before effects; writes
are atomic with parent creation; exact edits reject ambiguity; tool
invocation couples effects to recorded outcomes; bash drains pipes on
threads, keeps output prefixes, bounds post-exit collection, and kills
the owned process group on timeout or cancellation.
Changed files (19) Diff layout Auto Unified Split
.system/plans/SMH-PLAN-CORE0001-core-session-and-tools/index.md Modified +1 / −1 text lines
4 4 title: "Core Session and Tool Effects"title: "Core Session and Tool Effects"5 5 spec: SMH-SPEC-SPEC0001spec: SMH-SPEC-SPEC00017 7 depends_on: [SMH-PLAN-WSPC0001]depends_on: [SMH-PLAN-WSPC0001]+586 / −0 text lines
8 + source = "registry+https://github.com/rust-lang/crates.io-index" 9 + checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" 14 + source = "registry+https://github.com/rust-lang/crates.io-index" 15 + checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" 20 + source = "registry+https://github.com/rust-lang/crates.io-index" 21 + checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" 26 + source = "registry+https://github.com/rust-lang/crates.io-index" 27 + checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" 32 + source = "registry+https://github.com/rust-lang/crates.io-index" 33 + checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" 43 + source = "registry+https://github.com/rust-lang/crates.io-index" 44 + checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" 49 + source = "registry+https://github.com/rust-lang/crates.io-index" 50 + checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" 59 + source = "registry+https://github.com/rust-lang/crates.io-index" 60 + checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" 65 + source = "registry+https://github.com/rust-lang/crates.io-index" 66 + checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" 74 + source = "registry+https://github.com/rust-lang/crates.io-index" 75 + checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" 86 + source = "registry+https://github.com/rust-lang/crates.io-index" 87 + checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" 92 + source = "registry+https://github.com/rust-lang/crates.io-index" 93 + checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" 100 + name = "futures-core" 102 + source = "registry+https://github.com/rust-lang/crates.io-index" 103 + checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" 106 + name = "futures-task" 108 + source = "registry+https://github.com/rust-lang/crates.io-index" 109 + checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" 112 + name = "futures-util" 114 + source = "registry+https://github.com/rust-lang/crates.io-index" 115 + checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" 126 + source = "registry+https://github.com/rust-lang/crates.io-index" 127 + checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" 137 + source = "registry+https://github.com/rust-lang/crates.io-index" 138 + checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" 148 + source = "registry+https://github.com/rust-lang/crates.io-index" 149 + checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" 159 + source = "registry+https://github.com/rust-lang/crates.io-index" 160 + checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" 165 + source = "registry+https://github.com/rust-lang/crates.io-index" 166 + checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" 175 + source = "registry+https://github.com/rust-lang/crates.io-index" 176 + checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" 181 + source = "registry+https://github.com/rust-lang/crates.io-index" 182 + checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" 192 + source = "registry+https://github.com/rust-lang/crates.io-index" 193 + checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" 198 + source = "registry+https://github.com/rust-lang/crates.io-index" 199 + checksum = "8d8f1ea3f21fd3405dcaf6c9b5c1630af9afc422d9073ea39c5f6d6c772e08ed" 207 + source = "registry+https://github.com/rust-lang/crates.io-index" 208 + checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" 213 + source = "registry+https://github.com/rust-lang/crates.io-index" 214 + checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" 225 + source = "registry+https://github.com/rust-lang/crates.io-index" 226 + checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" 231 + source = "registry+https://github.com/rust-lang/crates.io-index" 232 + checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" 235 + name = "pin-project-lite" 237 + source = "registry+https://github.com/rust-lang/crates.io-index" 238 + checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" 243 + source = "registry+https://github.com/rust-lang/crates.io-index" 244 + checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" 252 + source = "registry+https://github.com/rust-lang/crates.io-index" 253 + checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" 261 + source = "registry+https://github.com/rust-lang/crates.io-index" 262 + checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" 267 + source = "registry+https://github.com/rust-lang/crates.io-index" 268 + checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" 278 + source = "registry+https://github.com/rust-lang/crates.io-index" 279 + checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" 284 + source = "registry+https://github.com/rust-lang/crates.io-index" 285 + checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" 294 + source = "registry+https://github.com/rust-lang/crates.io-index" 295 + checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" 301 + name = "serde_derive" 303 + source = "registry+https://github.com/rust-lang/crates.io-index" 304 + checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" 314 + source = "registry+https://github.com/rust-lang/crates.io-index" 315 + checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" 328 + source = "registry+https://github.com/rust-lang/crates.io-index" 329 + checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" 5 331 [[package ]][[package ]]6 332 name = "smith" name = "smith" 7 333 version = "0.1.0" version = "0.1.0" 9 342 [[package ]][[package ]]10 343 name = "smith-ai" name = "smith-ai" 25 358 name = "smith-core" name = "smith-core" 26 359 version = "0.1.0" version = "0.1.0" 27 360 dependencies = [dependencies = [31 372 [[package ]][[package ]]
392 + source = "registry+https://github.com/rust-lang/crates.io-index" 393 + checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" 403 + source = "registry+https://github.com/rust-lang/crates.io-index" 404 + checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" 414 + source = "registry+https://github.com/rust-lang/crates.io-index" 415 + checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" 417 + "thiserror-impl 1.0.69" ,423 + source = "registry+https://github.com/rust-lang/crates.io-index" 424 + checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" 426 + "thiserror-impl 2.0.20" ,430 + name = "thiserror-impl" 432 + source = "registry+https://github.com/rust-lang/crates.io-index" 433 + checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" 441 + name = "thiserror-impl" 443 + source = "registry+https://github.com/rust-lang/crates.io-index" 444 + checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" 452 + name = "unicode-ident" 454 + source = "registry+https://github.com/rust-lang/crates.io-index" 455 + checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" 460 + source = "registry+https://github.com/rust-lang/crates.io-index" 461 + checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" 471 + version = "0.11.1+wasi-snapshot-preview1" 472 + source = "registry+https://github.com/rust-lang/crates.io-index" 473 + checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" 476 + name = "wasm-bindgen" 478 + source = "registry+https://github.com/rust-lang/crates.io-index" 479 + checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" 484 + "wasm-bindgen-macro" ,485 + "wasm-bindgen-shared" ,489 + name = "wasm-bindgen-macro" 491 + source = "registry+https://github.com/rust-lang/crates.io-index" 492 + checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" 495 + "wasm-bindgen-macro-support" ,499 + name = "wasm-bindgen-macro-support" 501 + source = "registry+https://github.com/rust-lang/crates.io-index" 502 + checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" 508 + "wasm-bindgen-shared" ,512 + name = "wasm-bindgen-shared" 514 + source = "registry+https://github.com/rust-lang/crates.io-index" 515 + checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" 523 + source = "registry+https://github.com/rust-lang/crates.io-index" 524 + checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 526 + "winapi-i686-pc-windows-gnu" ,527 + "winapi-x86_64-pc-windows-gnu" ,531 + name = "winapi-i686-pc-windows-gnu" 533 + source = "registry+https://github.com/rust-lang/crates.io-index" 534 + checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 537 + name = "winapi-x86_64-pc-windows-gnu" 539 + source = "registry+https://github.com/rust-lang/crates.io-index" 540 + checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 545 + source = "registry+https://github.com/rust-lang/crates.io-index" 546 + checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" 552 + name = "windows-targets" 554 + source = "registry+https://github.com/rust-lang/crates.io-index" 555 + checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" 557 + "windows_aarch64_gnullvm" ,558 + "windows_aarch64_msvc" ,560 + "windows_i686_msvc" ,561 + "windows_x86_64_gnu" ,562 + "windows_x86_64_gnullvm" ,563 + "windows_x86_64_msvc" ,567 + name = "windows_aarch64_gnullvm" 569 + source = "registry+https://github.com/rust-lang/crates.io-index" 570 + checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" 573 + name = "windows_aarch64_msvc" 575 + source = "registry+https://github.com/rust-lang/crates.io-index" 576 + checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" 579 + name = "windows_i686_gnu" 581 + source = "registry+https://github.com/rust-lang/crates.io-index" 582 + checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" 585 + name = "windows_i686_msvc" 587 + source = "registry+https://github.com/rust-lang/crates.io-index" 588 + checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" 591 + name = "windows_x86_64_gnu" 593 + source = "registry+https://github.com/rust-lang/crates.io-index" 594 + checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" 597 + name = "windows_x86_64_gnullvm" 599 + source = "registry+https://github.com/rust-lang/crates.io-index" 600 + checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" 603 + name = "windows_x86_64_msvc" 605 + source = "registry+https://github.com/rust-lang/crates.io-index" 606 + checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" 48 608 [[package ]][[package ]]49 609 name = "xtask" name = "xtask" 50 610 version = "0.1.0" version = "0.1.0"
615 + source = "registry+https://github.com/rust-lang/crates.io-index" 616 + checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873" 622 + name = "zerocopy-derive" 624 + source = "registry+https://github.com/rust-lang/crates.io-index" 625 + checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc" 635 + source = "registry+https://github.com/rust-lang/crates.io-index" 636 + checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +3 / −2 text lines
19 19 mlua = { version = "0.10" , features = ["luajit" , "vendored" , "serialize" ] }mlua = { version = "0.10" , features = ["luajit" , "vendored" , "serialize" ] }20 20 mlua-pkg = "0.2" mlua-pkg = "0.2" 21 21 serde = { version = "1" , features = ["derive" ] }serde = { version = "1" , features = ["derive" ] }22 + serde_json = { version = "1" , features = ["preserve_order" ] }23 23 tokio = { version = "1" , features = ["full" ] }tokio = { version = "1" , features = ["full" ] }24 24 clap = { version = "4" , features = ["derive" ] }clap = { version = "4" , features = ["derive" ] }25 25 clap_complete = "4" clap_complete = "4" 47 47 insta = "1" insta = "1" 49 49 jsonschema = "0.28" jsonschema = "0.28" 50 - uuid = { version = "1" , features = ["v7" ] }50 + uuid = { version = "1" , features = ["v7" , " serde " ] }51 51 assert_cmd = "2" assert_cmd = "2" 52 52 assert_fs = "1" assert_fs = "1" 53 53 proptest = "1" proptest = "1" 58 58 zip = { version = "2" , default-features = false , features = ["deflate" ] }zip = { version = "2" , default-features = false , features = ["deflate" ] }59 59 tar = "0.4" tar = "0.4" 60 60 flate2 = "1" flate2 = "1" 62 63 [profile .release ][profile .release ]63 64 opt-level = 3 opt-level = 3 smith-core/Cargo.toml Modified +10 / −0 text lines
10 10 [dependencies ][dependencies ]11 11 smith = { path = "../smith" }smith = { path = "../smith" }
12 + serde = { workspace = true }13 + serde_json = { workspace = true }14 + ciborium = { workspace = true }15 + thiserror = { workspace = true }16 + uuid = { workspace = true }17 + dirs = { workspace = true }18 + fs2 = { workspace = true }20 + [target .'cfg(unix)' .dependencies ]21 + nix = { version = "0.29" , features = ["signal" ] }No final newline smith-core/src/bash.rs Added new file mode 100644+318 / −0 text lines
7 + use smith::error::{Result , SmithError};8 + use smith::tool::CancelHandle;10 + use std::process::{Child, Command, ExitStatus, Stdio};12 + use std::sync::atomic::{AtomicUsize, Ordering};13 + use std::sync::mpsc::{self, RecvTimeoutError};14 + use std::time::{Duration, Instant};16 + const READ_CHUNK : usize = 16 * 1024 ;17 + const GRACE_DRAIN : Duration = Duration::from_millis(500 );18 + const POLL_SLICE : Duration = Duration::from_millis(25 );21 + #[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]22 + pub struct BashResult {24 + pub exit_code: Option <i32 >,34 + pub duration_ms: u64 ,41 + workdir: Option <&str >,43 + max_output_bytes: usize ,44 + cancel: & CancelHandle,45 + ) -> Result <BashResult> {46 + let started = Instant::now();47 + let deadline = started + Duration::from_millis(timeout_ms.max (1 ));48 + let mut child = spawn (cmd, workdir)? ;49 + let (tx, rx) = mpsc::channel::<(Stream, Vec <u8 >)>();50 + let stdout_remaining = Arc::new(AtomicUsize::new(max_output_bytes));51 + let stderr_remaining = Arc::new(AtomicUsize::new(max_output_bytes));52 + let handles = drain_pipes (55 + stdout_remaining.clone (),56 + stderr_remaining.clone (),60 + let mut stdout: Vec <u8 > = Vec ::new();61 + let mut stderr: Vec <u8 > = Vec ::new();62 + let mut status: Option <ExitStatus> = None ;63 + let mut cancelled = false ;64 + let mut timed_out = false ;66 + while status.is_none () {67 + if cancel.is_cancelled () {69 + kill_tree (&mut child);70 + status = child.wait ().ok ();73 + let now = Instant::now();76 + kill_tree (&mut child);77 + status = child.wait ().ok ();80 + let wait = POLL_SLICE .min (deadline - now);81 + match rx.recv_timeout (wait) {82 + Ok ((stream, chunk)) => match stream {83 + Stream::Stdout => stdout.extend_from_slice (& chunk),84 + Stream::Stderr => stderr.extend_from_slice (& chunk),86 + Err (RecvTimeoutError::Timeout) => {}87 + Err (RecvTimeoutError::Disconnected) => {89 + while status.is_none () && Instant::now() < deadline {90 + if let Ok (Some (st)) = child.try_wait () {94 + if status.is_none () {95 + if let Ok (Some (st)) = child.try_wait () {101 + if status.is_none () {102 + if let Ok (Some (st)) = child.try_wait () {111 + let grace_end = Instant::now() + GRACE_DRAIN ;112 + while Instant::now() < grace_end {113 + match rx.recv_timeout (Duration::from_millis(50 )) {114 + Ok ((stream, chunk)) => match stream {115 + Stream::Stdout => stdout.extend_from_slice (& chunk),116 + Stream::Stderr => stderr.extend_from_slice (& chunk),118 + Err (RecvTimeoutError::Timeout) => continue ,119 + Err (RecvTimeoutError::Disconnected) => break ,122 + for handle in handles {123 + let _ = handle.join ();127 + exit_code: status.as_ref ().and_then (ExitStatus::code),128 + stdout: String ::from_utf8_lossy(& stdout).into_owned (),129 + stderr: String ::from_utf8_lossy(& stderr).into_owned (),132 + duration_ms: started.elapsed ().as_millis () as u64 ,136 + #[derive(Clone, Copy)]142 + fn spawn (cmd: &str , workdir: Option <&str >) -> Result <Child> {143 + let mut command = Command::new("bash" );147 + .stdout (Stdio::piped())148 + .stderr (Stdio::piped());149 + if let Some (dir) = workdir {150 + command.current_dir (dir);154 + use std::os::unix::process::CommandExt;157 + command.process_group (0 );159 + command.spawn ().map_err (|e| SmithError::Tool {160 + code: "BASH_SPAWN" .to_string (),161 + message: e.to_string (),167 + fn kill_tree (child: &mut Child) {170 + use nix::sys::signal::{Signal, killpg};171 + use nix::unistd::Pid;172 + let pgid = Pid::from_raw(child.id () as i32 );173 + let _ = killpg (pgid, Signal::SIGKILL );175 + let _ = child.kill ();183 + tx: mpsc::Sender<(Stream, Vec <u8 >)>,184 + stdout_remaining: Arc<AtomicUsize>,185 + stderr_remaining: Arc<AtomicUsize>,186 + ) -> Vec <std::thread::JoinHandle<()>> {187 + let mut handles = Vec ::new();188 + if let Some (out) = child.stdout.take () {189 + handles.push (spawn_reader (196 + if let Some (err) = child.stderr.take () {197 + handles.push (spawn_reader (207 + fn spawn_reader <R: Read + Send + 'static >(209 + tx: mpsc::Sender<(Stream, Vec <u8 >)>,211 + remaining: Arc<AtomicUsize>,212 + ) -> std::thread::JoinHandle<()> {213 + std::thread::spawn(move || {214 + let mut buf = vec! [0 u8 ; READ_CHUNK ];216 + match pipe.read (&mut buf) {219 + let keep = n.min (remaining.load (Ordering::Relaxed));221 + if tx.send ((stream, buf[.. keep].to_vec ())).is_err () {224 + remaining.fetch_sub (keep, Ordering::Relaxed);237 + #[allow(clippy::unwrap_used, clippy::expect_used)]241 + use std::time::Duration;243 + fn run (cmd: &str , timeout_ms: u64 , cap: usize ) -> BashResult {244 + execute (cmd, None , timeout_ms, cap, & CancelHandle::new()).unwrap ()248 + fn completes_and_captures_output () {249 + let res = run ("printf 'hello'" , 5_000 , 1024 );250 + assert_eq! (res.exit_code, Some (0 ));251 + assert_eq! (res.stdout, "hello" );252 + assert! (! res.timed_out && ! res.cancelled);256 + fn timeout_kills_silent_child_promptly () {257 + let res = run ("sleep 30" , 400 , 1024 );258 + assert! (res.timed_out);259 + assert_eq! (res.exit_code, None );260 + assert! (res.duration_ms < 2_000 , "took {}ms" , res.duration_ms);264 + fn stderr_heavy_child_cannot_deadlock_the_deadline () {265 + let res = run ("while true; do echo noise >&2; done" , 400 , 4096 );266 + assert! (res.timed_out);267 + assert! (res.duration_ms < 2_000 , "took {}ms" , res.duration_ms);271 + fn cancellation_stops_execution () {272 + let cancel = CancelHandle::new();274 + let cancel = cancel.clone ();275 + thread::spawn(move || {276 + thread::sleep(Duration::from_millis(120 ));280 + let res = execute ("sleep 30" , None , 10_000 , 1024 , & cancel).unwrap ();281 + handle.join ().unwrap ();282 + assert! (res.cancelled);283 + assert! (res.duration_ms < 2_000 , "took {}ms" , res.duration_ms);287 + fn output_cap_keeps_fitting_prefix () {288 + let res = run ("printf 'abcdefghij'" , 5_000 , 5 );289 + assert_eq! (res.stdout, "abcde" );293 + fn high_volume_output_is_not_throttled () {294 + let started = Instant::now();295 + let res = run ("head -c 300000 /dev/zero | tr '\\0' 'x'" , 10_000 , 1 << 20 );296 + assert_eq! (res.stdout.len (), 300_000 );298 + started.elapsed () < Duration::from_secs(3 ),299 + "throughput regression: {} bytes in {:?}" ,306 + fn descendant_processes_are_killed_with_the_tree () {307 + let dir = std::env::temp_dir().join (format! ("smith_bash_tree_{}" , std::process::id()));308 + let _ = std::fs::remove_dir_all(& dir);309 + std::fs::create_dir_all(& dir).unwrap ();310 + let marker = dir.join ("descendant_survived" );311 + let script = format! ("(sleep 30; touch {}) & sleep 30" , marker.display ());312 + let res = run (& script, 300 , 1024 );313 + assert! (res.timed_out);314 + thread::sleep(Duration::from_millis(1200 ));315 + assert! (! marker.exists (), "descendant survived the timeout kill" );316 + let _ = std::fs::remove_dir_all(& dir);smith-core/src/config.rs Added new file mode 100644+54 / −0 text lines
1 + use serde::{Deserialize, Serialize};4 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]7 + pub session_dir: String,9 + pub max_frame_bytes: usize ,11 + pub tool_timeout_ms: u64 ,13 + pub preserve_unknown_frames: bool ,19 + pub fn default_valid () -> Self {20 + let session_dir = match dirs::data_dir() {21 + Some (base) => base.join ("smith" ).join ("sessions" ),22 + None => std::path::PathBuf::from(".smith" ).join ("sessions" ),25 + session_dir: session_dir.to_string_lossy ().into_owned (),26 + max_frame_bytes: 1024 * 1024 ,27 + tool_timeout_ms: 30_000 ,28 + preserve_unknown_frames: true ,33 + pub fn validate (& self) -> Result <(), String > {34 + if self.session_dir.trim ().is_empty () {35 + return Err ("session_dir must not be empty" .to_string ());37 + if self.max_frame_bytes < 1024 {38 + return Err ("max_frame_bytes must be at least 1024" .to_string ());40 + if self.max_frame_bytes > 1024 * 1024 * 100 {41 + return Err ("max_frame_bytes exceeds safe limit of 100MB" .to_string ());43 + if self.tool_timeout_ms < 100 {44 + return Err ("tool_timeout_ms must be at least 100ms" .to_string ());50 + impl Default for Config {51 + fn default () -> Self {52 + Self ::default_valid()smith-core/src/frame.rs Added new file mode 100644+365 / −0 text lines
8 + use crate ::session::Entry;9 + use smith::error::{Result , SmithError};13 + pub const DEFAULT_MAX_FRAME_BYTES : usize = 1024 * 1024 ;16 + pub const MAX_DECLARED_LENGTH : usize = u32 ::MAX as usize ;18 + pub (crate ) const HEADER_LEN : usize = 4 ;21 + #[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]33 + declared_length: usize ,40 + pub fn encode_entry (entry: & Entry, max_frame_bytes: usize ) -> Result <Vec <u8 >> {41 + let mut limited = LimitedWriter::new(max_frame_bytes);42 + match ciborium::ser::into_writer(entry, &mut limited) {45 + if limited.overflowed () {46 + return Err (SmithError::FrameTooLarge {47 + max_bytes: max_frame_bytes,48 + actual: max_frame_bytes + 1 ,51 + return Err (SmithError::FrameEncode {52 + message: e.to_string (),56 + if limited.overflowed () {57 + return Err (SmithError::FrameTooLarge {58 + max_bytes: max_frame_bytes,59 + actual: max_frame_bytes + 1 ,62 + Ok (limited.into_inner ())66 + pub fn encode (& self, max_frame_bytes: usize ) -> Result <Vec <u8 >> {67 + let payload = match self {68 + Self ::Known { entry } => Self ::encode_entry(entry, max_frame_bytes)? ,73 + if raw_bytes.len () != * declared_length || * declared_length > max_frame_bytes {74 + return Err (SmithError::FrameEncode {76 + "unknown frame length {} inconsistent or above limit {}" ,77 + declared_length, max_frame_bytes84 + let mut out = Vec ::with_capacity(HEADER_LEN + payload.len ());85 + out.extend_from_slice (& (payload.len () as u32 ).to_le_bytes ());86 + out.extend_from_slice (& payload);92 + pub fn decode_payload (payload: Vec <u8 >) -> Self {93 + match ciborium::de::from_reader::<Entry, _ >(payload.as_slice ()) {94 + Ok (entry) => Self ::Known { entry },95 + Err (_ ) => Self ::Unknown {96 + declared_length: payload.len (),104 + #[derive(Clone, PartialEq, Eq, Debug)]105 + pub enum DecodeOutcome {107 + Frame(Frame, usize ),120 + pub fn decode_frame (buf: & [u8 ], max_frame_bytes: usize ) -> DecodeOutcome {121 + if buf.len () < HEADER_LEN {122 + return DecodeOutcome::Incomplete;124 + let declared = u32 ::from_le_bytes([buf[0 ], buf[1 ], buf[2 ], buf[3 ]]) as usize ;125 + let total = HEADER_LEN .saturating_add (declared);126 + if total > buf.len () {127 + return DecodeOutcome::Incomplete;129 + if declared > max_frame_bytes {130 + return DecodeOutcome::Skipped(total);132 + let frame = Frame::decode_payload(buf[HEADER_LEN .. total].to_vec ());133 + DecodeOutcome::Frame(frame, total)137 + pub fn write_frame (writer: &mut impl Write, frame: & Frame, max_frame_bytes: usize ) -> Result <()> {138 + let bytes = frame.encode (max_frame_bytes)? ;141 + .map_err (|e| SmithError::FrameEncode {142 + message: e.to_string (),149 + struct LimitedWriter {156 + fn new (limit: usize ) -> Self {164 + fn overflowed (& self) -> bool {168 + fn into_inner (self) -> Vec <u8 > {173 + impl Write for LimitedWriter {174 + fn write (&mut self, buf: & [u8 ]) -> std::io::Result <usize > {176 + return Err (std::io::Error::new(177 + std::io::ErrorKind::WriteZero,178 + "frame size limit exceeded" ,181 + let keep = buf.len ().min (self.remaining);182 + self.buf.extend_from_slice (& buf[.. keep]);183 + self.remaining -= keep;184 + if keep < buf.len () {185 + self.overflow = true ;186 + return Err (std::io::Error::new(187 + std::io::ErrorKind::WriteZero,188 + "frame size limit exceeded" ,194 + fn flush (&mut self) -> std::io::Result <()> {201 + pub use crate ::session::canonical_json;203 + #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]206 + use crate ::session::{Entry, EntryContent};207 + use smith::id::ToolCallId;208 + use smith::message::{ContentBlock, Message, Role};210 + fn sample_entry (thinking: bool ) -> Entry {211 + let mut msg = Message::with_text(Role::User, "hello" );213 + msg.add_block (ContentBlock::thinking("internal" ));215 + Entry::message(msg, None )219 + fn known_frame_round_trips_through_cbor () {220 + let entry = sample_entry (true );221 + let bytes = Frame::Known {222 + entry: entry.clone (),224 + .encode (DEFAULT_MAX_FRAME_BYTES )226 + match decode_frame (& bytes, DEFAULT_MAX_FRAME_BYTES ) {227 + DecodeOutcome::Frame(Frame::Known { entry: back }, consumed) => {228 + assert_eq! (consumed, bytes.len ());229 + let msg = match back.content {230 + EntryContent::Message(m) => m,231 + other => panic! ("unexpected content {other:?}" ),233 + assert_eq! (msg.blocks[0 ], ContentBlock::Text("hello" .into ()));234 + assert_eq! (msg.blocks[1 ], ContentBlock::Thinking("internal" .into ()));236 + other => panic! ("unexpected outcome {other:?}" ),241 + fn torn_tail_reports_incomplete () {242 + let bytes = Frame::Known {243 + entry: sample_entry (false ),245 + .encode (DEFAULT_MAX_FRAME_BYTES )248 + decode_frame (& bytes[.. 3 ], 1 << 20 ),249 + DecodeOutcome::Incomplete252 + decode_frame (& bytes[.. bytes.len () - 1 ], 1 << 20 ),253 + DecodeOutcome::Incomplete258 + fn oversized_complete_frame_is_skipped_by_length () {259 + let payload = vec! [0xAB_ u8 ; 100 ];260 + let mut bytes = (payload.len () as u32 ).to_le_bytes ().to_vec ();261 + bytes.extend_from_slice (& payload);263 + match decode_frame (& bytes, 50 ) {264 + DecodeOutcome::Skipped(consumed) => assert_eq! (consumed, bytes.len ()),265 + other => panic! ("unexpected outcome {other:?}" ),270 + fn oversized_truncated_frame_is_incomplete_not_scanned () {271 + let mut bytes = 200_ u32 .to_le_bytes ().to_vec ();272 + bytes.extend_from_slice (& [0 u8 ; 10 ]);273 + assert_eq! (decode_frame (& bytes, 50 ), DecodeOutcome::Incomplete);277 + fn sequential_decode_consumes_each_frame () {278 + let f1 = Frame::Known {279 + entry: sample_entry (false ),281 + let f2 = Frame::Known {282 + entry: sample_entry (false ),284 + let mut bytes = f1.encode (1 << 20 ).unwrap ();285 + bytes.extend_from_slice (& f2.encode (1 << 20 ).unwrap ());286 + let (first, used1) = match decode_frame (& bytes, 1 << 20 ) {287 + DecodeOutcome::Frame(f, n) => (f, n),288 + other => panic! ("unexpected {other:?}" ),290 + assert_eq! (first, f1);291 + let (second, used2) = match decode_frame (& bytes[used1.. ], 1 << 20 ) {292 + DecodeOutcome::Frame(f, n) => (f, n),293 + other => panic! ("unexpected {other:?}" ),295 + assert_eq! (second, f2);296 + assert_eq! (used1 + used2, bytes.len ());300 + fn encoding_rejects_frames_above_limit () {301 + let big = Entry::message(303 + let mut m = Message::with_text(Role::User, "x" );304 + m.add_block (ContentBlock::text("y" .repeat (4096 )));309 + let err = Frame::Known { entry: big }.encode (64 ).unwrap_err ();310 + assert_eq! (err.code (), "FRAME_TOO_LARGE" );314 + fn equivalent_inputs_encode_identically_despite_key_order () {315 + let a = canonical_json (& serde_json::json! ({"path" : "p" , "content" : "c" }));316 + let b = canonical_json (& serde_json::json! ({"content" : "c" , "path" : "p" }));317 + let call_id = ToolCallId::new();318 + let e1 = Entry::new(320 + EntryContent::ToolCall {321 + name: "write" .into (),326 + let mut e2 = Entry::new(328 + EntryContent::ToolCall {329 + name: "write" .into (),336 + e2.timestamp_ms = e1.timestamp_ms;337 + let b1 = Frame::Known { entry: e1.clone () }.encode (1 << 20 ).unwrap ();338 + let b2 = Frame::Known { entry: e2.clone () }.encode (1 << 20 ).unwrap ();343 + fn unknown_payload_is_preserved_verbatim () {344 + let raw = vec! [0xDE , 0xAD , 0xBE , 0xEF , 0x01 , 0x02 ];345 + let frame = Frame::Unknown {346 + declared_length: raw.len (),347 + raw_bytes: raw.clone (),349 + let bytes = frame.encode (1 << 20 ).unwrap ();350 + match decode_frame (& bytes, 1 << 20 ) {351 + DecodeOutcome::Frame(358 + assert_eq! (raw_bytes, raw);359 + assert_eq! (declared_length, raw.len ());360 + assert_eq! (used, bytes.len ());362 + other => panic! ("unexpected {other:?}" ),smith-core/src/lib.rs Modified +63 / −3 text lines
1 - #![forbid(unsafe_code)]
6 + #![forbid(unsafe_code)]7 + #![warn(missing_docs, unused_mut)]15 + clippy::redundant_clone,17 + clippy::option_if_let_else,18 + clippy::missing_const_for_fn,19 + clippy::needless_pass_by_ref_mut,20 + clippy::too_long_first_doc_paragraph,33 + pub use bash::{BashResult, execute};34 + pub use config::Config;35 + pub use frame::{DecodeOutcome, Frame, decode_frame, write_frame};36 + pub use session::{Branch, Entry, EntryContent, Session};37 + pub use store::{SessionWriter, load_session, repair_session};38 + pub use tools::{ToolOutcome, ToolRegistry, ToolSession};39 + pub use trace::{TraceKind, TraceRecord, replay};42 + #[allow(clippy::unwrap_used, clippy::expect_used)]45 + use smith::message::{Message, Role};48 + fn session_creates_and_appends () {49 + let mut session = Session::new();50 + let msg = Message::with_text(Role::User, "hello" );51 + let entry = Entry::message(msg, None );52 + session.append_to_active (entry);53 + assert_eq! (session.active_branch ().entries.len (), 1 );57 + fn config_validates_bounds () {58 + let mut cfg = Config::default_valid();59 + cfg.max_frame_bytes = 100 ;60 + assert! (cfg.validate ().is_err ());61 + cfg.max_frame_bytes = 1024 ;62 + assert! (cfg.validate ().is_ok ());smith-core/src/session.rs Added new file mode 100644+172 / −0 text lines
1 + use serde::{Deserialize, Serialize};2 + use smith::{id::* , message::Message};6 + pub fn canonical_json (value: & serde_json::Value) -> serde_json::Value {8 + serde_json::Value::Object(map) => {9 + let mut keys: Vec <& String > = map.keys ().collect ();11 + let mut out = serde_json::Map::new();13 + out.insert (key.clone (), canonical_json (& map[key]));15 + serde_json::Value::Object(out)17 + serde_json::Value::Array(items) => {18 + serde_json::Value::Array(items.iter ().map (canonical_json).collect ())20 + other => other.clone (),25 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]30 + pub parent: Option <EntryId>,32 + pub timestamp_ms: i64 ,34 + pub content: EntryContent,37 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]38 + #[serde(tag = "kind" , content = "data" )]39 + pub enum EntryContent {45 + input: serde_json::Value,46 + call_id: smith::id::ToolCallId,52 + call_id: smith::id::ToolCallId,57 + detail: serde_json::Value,62 + pub fn new (parent: Option <EntryId>, content: EntryContent) -> Self {66 + timestamp_ms: std::time::SystemTime::now()67 + .duration_since (std::time::UNIX_EPOCH )68 + .map (|d| d.as_millis () as i64 )74 + pub fn message (msg: Message, parent: Option <EntryId>) -> Self {75 + Self ::new(parent, EntryContent::Message(msg))80 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]83 + pub branch_id: BranchId,85 + pub entries: Vec <Entry>,87 + pub selected_idx: usize ,91 + pub fn new () -> Self {93 + branch_id: BranchId::new(),99 + pub fn append (&mut self, entry: Entry) -> usize {100 + self.entries.push (entry);101 + self.selected_idx = self.entries.len ().saturating_sub (1 );105 + pub fn selected_entry (& self) -> Option <& Entry> {106 + self.entries.get (self.selected_idx)111 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]116 + pub branches: Vec <Branch>,118 + pub active_branch_idx: usize ,120 + pub compaction_boundary: Option <EntryId>,124 + pub fn new () -> Self {126 + id: SessionId::new(),127 + branches: vec! [Branch::new()],128 + active_branch_idx: 0 ,129 + compaction_boundary: None ,133 + pub fn active_branch (& self) -> & Branch {134 + & self.branches[self.active_branch_idx]137 + pub fn active_branch_mut (&mut self) -> &mut Branch {138 + &mut self.branches[self.active_branch_idx]141 + pub fn append_to_active (&mut self, entry: Entry) {142 + let branch = self.active_branch_mut ();143 + branch.append (entry);146 + pub fn selected_id (& self) -> Option <EntryId> {147 + self.active_branch ().selected_entry ().map (|e| e.id)154 + pub fn from_frames (frames: & [crate::frame::Frame]) -> Self {155 + let mut session = Self ::new();156 + let mut restored: Vec <Entry> = Vec ::new();157 + for frame in frames {158 + if let crate ::frame::Frame::Known { entry } = frame {159 + if let EntryContent::Meta { kind, .. } = & entry.content {160 + if kind == "compaction" {161 + session.compaction_boundary = Some (entry.id);164 + restored.push (entry.clone ());167 + let branch = session.active_branch_mut ();168 + branch.entries = restored;169 + branch.selected_idx = branch.entries.len ().saturating_sub (1 );smith-core/src/store.rs Added new file mode 100644+463 / −0 text lines
4 + use crate ::config::Config;5 + use crate ::frame::{Frame, HEADER_LEN , write_frame};6 + use smith::error::{Result , SmithError};7 + use std::fs::{File, OpenOptions};8 + use std::io::{BufReader, Read, Seek, SeekFrom, Write};9 + use std::path::{Path, PathBuf};16 + pub struct SessionWriter {24 + pub fn open <P: AsRef <Path>>(path: P, config: Config) -> Result <Self > {25 + config.validate ().map_err (|e| SmithError::Config {26 + field: "store" .to_string (),29 + let path = path.as_ref ().to_path_buf ();30 + if let Some (parent) = path.parent () {31 + if ! parent.as_os_str ().is_empty () {32 + std::fs::create_dir_all(parent).map_err (io_err ("STORE_MKDIR" ))? ;35 + let mut file = OpenOptions::new()41 + .map_err (io_err ("STORE_OPEN" ))? ;43 + file.lock_exclusive ().map_err (io_err ("STORE_LOCK" ))? ;45 + let good_end = scan_and_fix_tail (&mut file, config.max_frame_bytes)? ;46 + file.seek (SeekFrom::Start(good_end))47 + .map_err (io_err ("STORE_SEEK" ))? ;48 + Ok (Self { file, config, path })54 + pub fn append_frame (&mut self, frame: & Frame) -> Result <()> {55 + let bytes = frame.encode (self.config.max_frame_bytes)? ;56 + self.file.write_all (& bytes).map_err (io_err ("STORE_WRITE" ))? ;57 + self.file.flush ().map_err (io_err ("STORE_WRITE" ))? ;62 + pub fn path (& self) -> & Path {67 + impl Drop for SessionWriter {70 + let _ = fs2::FileExt::unlock(& self.file);79 + pub fn load_session (path: & Path, max_frame_bytes: usize ) -> Result <Vec <Frame>> {80 + let file = File::open(path).map_err (io_err ("STORE_OPEN" ))? ;81 + let mut reader = BufReader::with_capacity(64 * 1024 , file);82 + let mut frames = Vec ::new();84 + let mut header = [0 u8 ; HEADER_LEN ];85 + match read_exact_or_eof (&mut reader, &mut header) {90 + let declared = u32 ::from_le_bytes(header) as usize ;91 + if declared > max_frame_bytes {93 + let mut remaining = declared as u64 ;98 + let chunk = remaining.min (64 * 1024 ) as usize ;99 + let mut sink = vec! [0 u8 ; chunk];100 + match reader.read_exact (&mut sink) {101 + Ok (()) => remaining -= chunk as u64 ,102 + Err (_ ) => return Ok (frames), 107 + let mut chunk = vec! [0 u8 ; declared];108 + match reader.read_exact (&mut chunk) {109 + Ok (()) => frames.push (Frame::decode_payload(chunk)),110 + Err (_ ) => return Ok (frames), 119 + pub fn repair_session (path: & Path, max_frame_bytes: usize ) -> Result <Vec <Frame>> {120 + let frames = load_session (path, max_frame_bytes)? ;121 + let tmp = path.with_extension ("smith-repair.tmp" );123 + let mut out = File::create(& tmp).map_err (io_err ("REPAIR_CREATE" ))? ;124 + for frame in & frames {125 + write_frame (&mut out, frame, max_frame_bytes)? ;127 + out.sync_all ().map_err (io_err ("REPAIR_SYNC" ))? ;129 + std::fs::rename(& tmp, path).map_err (io_err ("REPAIR_PUBLISH" ))? ;135 + fn scan_and_fix_tail (file: & File, max_frame_bytes: usize ) -> Result <u64 > {136 + let len = file.metadata ().map_err (io_err ("STORE_STAT" ))? .len ();138 + BufReader::with_capacity(64 * 1024 , file.try_clone ().map_err (io_err ("STORE_OPEN" ))? );139 + let mut good_end: u64 = 0 ;141 + let header_start = reader.stream_position ().map_err (io_err ("STORE_READ" ))? ;142 + let mut header = [0 u8 ; HEADER_LEN ];144 + if ! read_exact_or_eof (&mut reader, &mut header).unwrap_or (false ) {147 + let declared = u32 ::from_le_bytes(header) as usize ;148 + let total = declared as u64 + HEADER_LEN as u64 ;149 + let mut remaining = total;150 + let mut complete = true ;151 + while remaining > 0 {152 + let chunk = remaining.min (64 * 1024 ) as usize ;153 + let mut sink = vec! [0 u8 ; chunk];154 + match reader.read_exact (&mut sink) {155 + Ok (()) => remaining -= chunk as u64 ,166 + let _ = max_frame_bytes; 167 + good_end = header_start + total;170 + file.set_len (good_end).map_err (io_err ("STORE_TRUNCATE" ))? ;177 + fn read_exact_or_eof <R: Read>(reader: &mut R, buf: &mut [u8 ]) -> std::io::Result <bool > {179 + while filled < buf.len () {180 + match reader.read (&mut buf[filled.. ]) {185 + return Err (std::io::Error::new(186 + std::io::ErrorKind::UnexpectedEof,190 + Ok (n) => filled += n,191 + Err (e) if e.kind () == std::io::ErrorKind::Interrupted => continue ,192 + Err (e) => return Err (e),198 + fn io_err (code: &'static str ) -> impl Fn(std::io::Error) -> SmithError {199 + move | e| SmithError::Session {200 + code: code.to_string (),201 + message: e.to_string (),206 + #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]209 + use crate ::session::{Entry, EntryContent, Session};210 + use smith::message::{ContentBlock, Message, Role};212 + fn tmp_path (name: &str ) -> PathBuf {213 + let dir = std::env::temp_dir().join (format! ("smith_store_tests_{}" , std::process::id()));214 + std::fs::create_dir_all(& dir).unwrap ();218 + fn entry (text: &str ) -> Entry {219 + Entry::message(Message::with_text(Role::User, text), None )222 + fn frame (text: &str ) -> Frame {223 + Frame::Known { entry: entry (text) }227 + fn append_load_round_trip_preserves_entries () {228 + let path = tmp_path ("round_trip.smh" );229 + let _ = std::fs::remove_file(& path);230 + let cfg = Config::default_valid();232 + let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap ();233 + w.append_frame (& frame ("one" )).unwrap ();234 + w.append_frame (& frame ("two" )).unwrap ();236 + let frames = load_session (& path, cfg.max_frame_bytes).unwrap ();237 + assert_eq! (frames.len (), 2 );238 + let session = Session::from_frames(& frames);239 + assert_eq! (session.active_branch ().entries.len (), 2 );241 + session.active_branch ().entries[1 ].id,242 + session.selected_id ().unwrap ()244 + let _ = std::fs::remove_file(& path);248 + fn torn_tail_is_truncated_on_open_and_appends_stay_visible () {249 + let path = tmp_path ("torn_tail.smh" );250 + let _ = std::fs::remove_file(& path);251 + let cfg = Config::default_valid();253 + let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap ();254 + w.append_frame (& frame ("kept" )).unwrap ();257 + let good = Frame::Known {258 + entry: entry ("kept" ),260 + .encode (cfg.max_frame_bytes)262 + let mut torn = good.clone ();263 + torn.extend_from_slice (& [0x10 , 0x00 , 0x00 , 0x00 , 0xAA , 0xBB ]);264 + std::fs::write(& path, & torn).unwrap ();267 + let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap ();268 + w.append_frame (& frame ("after" )).unwrap ();270 + let frames = load_session (& path, cfg.max_frame_bytes).unwrap ();271 + let texts: Vec <String > = frames273 + .filter_map (|f| match f {274 + Frame::Known { entry } => match & entry.content {275 + EntryContent::Message(m) => match & m.blocks[0 ] {276 + ContentBlock::Text(t) => Some (t.clone ()),284 + assert_eq! (texts, vec! ["kept" .to_string (), "after" .to_string ()]);285 + let _ = std::fs::remove_file(& path);289 + fn loader_stops_at_torn_tail_without_header_fabrication () {290 + let path = tmp_path ("loader_torn.smh" );291 + let cfg = Config::default_valid();292 + let good = frame ("a" ).encode (cfg.max_frame_bytes).unwrap ();293 + let mut bytes = good.clone ();294 + bytes.extend_from_slice (& [0xFF , 0xFF ]); 295 + std::fs::write(& path, & bytes).unwrap ();296 + let frames = load_session (& path, cfg.max_frame_bytes).unwrap ();297 + assert_eq! (frames.len (), 1 );298 + let _ = std::fs::remove_file(& path);302 + fn oversized_complete_frame_is_skipped_and_following_frames_reachable () {303 + let path = tmp_path ("oversized_skip.smh" );305 + let mut bytes = 5000_ u32 .to_le_bytes ().to_vec ();306 + bytes.extend_from_slice (& vec! [0xAB_ u8 ; 5000 ]);307 + bytes.extend_from_slice (& frame ("tail" ).encode (1 << 20 ).unwrap ());308 + std::fs::write(& path, & bytes).unwrap ();309 + let frames = load_session (& path, 1024 ).unwrap ();310 + assert_eq! (frames.len (), 1 );311 + assert! (matches! (frames[0 ], Frame::Known { .. }));312 + let _ = std::fs::remove_file(& path);316 + fn repair_republishes_file_without_torn_tail () {317 + let path = tmp_path ("repair.smh" );318 + let cfg = Config::default_valid();319 + let good = frame ("a" ).encode (cfg.max_frame_bytes).unwrap ();320 + let mut bytes = good.clone ();321 + bytes.extend_from_slice (& frame ("b" ).encode (cfg.max_frame_bytes).unwrap ()[.. 6 ]);322 + std::fs::write(& path, & bytes).unwrap ();323 + let before = std::fs::metadata(& path).unwrap ().len ();324 + let frames = repair_session (& path, cfg.max_frame_bytes).unwrap ();325 + assert_eq! (frames.len (), 1 );326 + let after = std::fs::metadata(& path).unwrap ().len ();327 + assert! (after < before);328 + assert_eq! (load_session (& path, cfg.max_frame_bytes).unwrap ().len (), 1 );329 + let _ = std::fs::remove_file(& path);333 + fn writer_rejects_oversized_frame_without_touching_file () {334 + let path = tmp_path ("oversize_reject.smh" );335 + let _ = std::fs::remove_file(& path);336 + let mut cfg = Config::default_valid();337 + cfg.max_frame_bytes = 4096 ;339 + let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap ();340 + w.append_frame (& frame ("small" )).unwrap ();341 + let big = Entry::message(343 + let mut m = Message::with_text(Role::User, "x" );344 + m.add_block (ContentBlock::text("y" .repeat (8192 )));349 + let err = w.append_frame (& Frame::Known { entry: big }).unwrap_err ();350 + assert_eq! (err.code (), "FRAME_TOO_LARGE" );352 + assert_eq! (load_session (& path, cfg.max_frame_bytes).unwrap ().len (), 1 );353 + let _ = std::fs::remove_file(& path);357 + fn lock_serializes_second_writer_handle () {358 + let path = tmp_path ("locked.smh" );359 + let _ = std::fs::remove_file(& path);360 + let cfg = Config::default_valid();361 + let _w1 = SessionWriter::open(& path, cfg.clone ()).unwrap ();364 + let probe = OpenOptions::new()370 + assert! (probe.try_lock_exclusive ().is_err ());372 + let _ = std::fs::remove_file(& path);376 + fn unknown_frames_survive_write_and_load () {377 + let path = tmp_path ("unknown_frames.smh" );378 + let _ = std::fs::remove_file(& path);379 + let cfg = Config::default_valid();380 + let unknown = Frame::Unknown {382 + raw_bytes: vec! [1 , 2 , 3 , 4 , 5 , 6 ],385 + let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap ();386 + w.append_frame (& unknown).unwrap ();387 + w.append_frame (& frame ("known" )).unwrap ();389 + let frames = load_session (& path, cfg.max_frame_bytes).unwrap ();390 + assert_eq! (frames.len (), 2 );396 + assert_eq! (raw_bytes, & vec! [1 , 2 , 3 , 4 , 5 , 6 ]);397 + assert_eq! (* declared_length, 6 );399 + other => panic! ("expected unknown frame, got {other:?}" ),402 + Frame::Known { entry } => match & entry.content {403 + EntryContent::Message(m) => match & m.blocks[0 ] {404 + ContentBlock::Text(t) => assert_eq! (t, "known" ),405 + other => panic! ("unexpected block {other:?}" ),407 + other => panic! ("unexpected content {other:?}" ),409 + other => panic! ("expected known frame, got {other:?}" ),411 + let _ = std::fs::remove_file(& path);415 + fn end_to_end_tool_activity_persists_and_reconstructs () {416 + let dir = tmp_path ("e2e" );417 + std::fs::create_dir_all(& dir).unwrap ();418 + let workdir = dir.join ("work" );419 + std::fs::create_dir_all(& workdir).unwrap ();420 + let session_path = dir.join ("e2e.smh" );421 + let _ = std::fs::remove_file(& session_path);422 + let cfg = Config::default_valid();424 + let writer = SessionWriter::open(& session_path, cfg.clone ()).unwrap ();425 + let mut ts = crate ::tools::ToolSession::with_writer(workdir.clone (), writer);428 + serde_json::json! ({"path" : "out/hello.txt" , "content" : "hi" }),431 + ts.invoke ("read" , serde_json::json! ({"path" : "out/hello.txt" }))434 + let frames = load_session (& session_path, cfg.max_frame_bytes).unwrap ();435 + assert_eq! (frames.len (), 4 ); 436 + let restored = Session::from_frames(& frames);437 + assert_eq! (restored.active_branch ().entries.len (), 4 );439 + let kinds: Vec <&str > = restored443 + .map (|e| match & e.content {444 + EntryContent::ToolCall { .. } => "call" ,445 + EntryContent::ToolResult { .. } => "result" ,449 + assert_eq! (kinds, vec! ["call" , "result" , "call" , "result" ]);452 + std::fs::read_to_string(workdir.join ("out/hello.txt" )).unwrap (),455 + let _ = std::fs::remove_file(& session_path);456 + let _ = std::fs::remove_dir_all(& dir);460 + fn header_len_matches_protocol () {461 + assert_eq! (HEADER_LEN , 4 );smith-core/src/tools.rs Added new file mode 100644+754 / −0 text lines
4 + use crate ::frame::{Frame, canonical_json};5 + use crate ::session::{Entry, EntryContent, Session};6 + use crate ::store::SessionWriter;7 + use smith::error::{Result , SmithError};8 + use smith::id::ToolCallId;9 + use smith::tool::ToolMetadata;10 + use std::collections::HashMap;12 + use std::io::{BufRead, BufReader, Write};13 + use std::path::{Path, PathBuf};14 + use std::sync::atomic::{AtomicUsize, Ordering};16 + const HARD_OUTPUT_CAP : usize = 256 * 1024 ;17 + const DEFAULT_OUTPUT_CAP : usize = 64 * 1024 ;18 + const MAX_LIST_ENTRIES : usize = 1000 ;19 + const MAX_GREP_MATCHES : usize = 200 ;20 + const MAX_EDIT_FILE_BYTES : usize = 8 * 1024 * 1024 ;23 + #[derive(Clone, Debug, Default)]24 + pub struct ToolRegistry {26 + pub tools: HashMap<String , ToolMetadata>,31 + pub fn new () -> Self {36 + pub fn register (&mut self, meta: ToolMetadata) {37 + self.tools.insert (meta.name.clone (), meta);41 + pub fn with_builtins () -> Self {42 + let mut reg = Self ::new();43 + for meta in builtin_tools () {51 + pub fn builtin_tools () -> Vec <ToolMetadata> {52 + let object = |required: & [&str ], props: serde_json::Value| {55 + "required" : required,60 + ToolMetadata::new("read" , "Read a bounded line window from a file." ).with_schema (object (63 + "path" : {"type" : "string" },64 + "offset" : {"type" : "integer" },65 + "limit" : {"type" : "integer" },66 + "max_bytes" : {"type" : "integer" },69 + ToolMetadata::new("write" , "Atomically replace a file, creating parents." ).with_schema (71 + & ["path" , "content" ],73 + "path" : {"type" : "string" },74 + "content" : {"type" : "string" },78 + ToolMetadata::new("edit" , "Apply one exact, unambiguous replacement." ).with_schema (object (79 + & ["path" , "old_string" , "new_string" ],81 + "path" : {"type" : "string" },82 + "old_string" : {"type" : "string" },83 + "new_string" : {"type" : "string" },86 + ToolMetadata::new("ls" , "List a directory deterministically." )87 + .with_schema (object (& [], serde_json::json! ({"path" : {"type" : "string" }}))),88 + ToolMetadata::new("find" , "Find directory entries matching a substring." ).with_schema (92 + "path" : {"type" : "string" },93 + "pattern" : {"type" : "string" },97 + ToolMetadata::new("grep" , "Return bounded matching lines from a file." ).with_schema (101 + "path" : {"type" : "string" },102 + "query" : {"type" : "string" },106 + ToolMetadata::new("bash" , "Run a bounded cancellable shell command." ).with_schema (object (109 + "command" : {"type" : "string" },110 + "timeout_ms" : {"type" : "integer" },118 + pub struct ToolSession {119 + registry: ToolRegistry,121 + pub session: Session,122 + writer: Option <SessionWriter>,124 + pub working_dir: PathBuf,129 + pub fn new (working_dir: impl Into <PathBuf>) -> Self {131 + registry: ToolRegistry::with_builtins(),132 + session: Session::new(),134 + working_dir: working_dir.into (),139 + pub fn with_writer (working_dir: impl Into <PathBuf>, writer: SessionWriter) -> Self {141 + writer: Some (writer),142 + ..Self ::new(working_dir)147 + pub fn register (&mut self, meta: ToolMetadata) {148 + self.registry.register (meta);153 + pub fn validate (& self, name: &str , input: & serde_json::Value) -> Result <()> {154 + let meta = self.registry.tools.get (name).ok_or_else (|| {156 + "TOOL_NOT_REGISTERED" ,157 + format! ("tool '{name}' not registered" ),162 + .ok_or_else (|| tool_err ("INVALID_INPUT" , "input must be a JSON object" ))? ;163 + let schema = & meta.input_schema;166 + .and_then (|v| v.as_array ())170 + let key = req.as_str ().unwrap_or_default ();171 + if ! obj.contains_key (key) {172 + return Err (tool_err (174 + format! ("missing required field '{key}' for tool '{name}'" ),178 + if let Some (props) = schema.get ("properties" ).and_then (|v| v.as_object ()) {179 + for (key, value) in obj {180 + if let Some (expected) = props182 + .and_then (|p| p.get ("type" ))183 + .and_then (|t| t.as_str ())185 + if ! json_type_matches (expected, value) {186 + return Err (tool_err (188 + format! ("field '{key}' for tool '{name}' must be of type {expected}" ),202 + pub fn invoke (&mut self, name: &str , input: serde_json::Value) -> Result <ToolOutcome> {203 + self.validate (name, & input)? ;204 + let call_id = ToolCallId::new();205 + let canonical_input = canonical_json (& input);206 + let parent = self.session.selected_id ();208 + let effect = execute_file_effect (name, & canonical_input, & self.working_dir);209 + let ok = effect.is_ok ();210 + let output = match & effect {211 + Ok (text) => text.clone (),212 + Err (err) => err.to_string (),214 + let outcome = ToolOutcome {216 + name: name.to_string (),218 + output: output.clone (),219 + timestamp_ms: now_ms (),222 + self.record_entry (Entry::new(224 + EntryContent::ToolCall {225 + name: name.to_string (),226 + input: canonical_input,231 + self.record_entry (Entry::new(232 + self.session.selected_id (),233 + EntryContent::ToolResult {239 + effect.map (move |_| outcome)242 + fn record_entry (&mut self, entry: Entry) -> Result <()> {243 + if let Some (writer) = &mut self.writer {244 + writer.append_frame (& Frame::Known {245 + entry: entry.clone (),248 + self.session.append_to_active (entry);254 + #[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]255 + pub struct ToolOutcome {257 + pub call_id: ToolCallId,265 + pub timestamp_ms: i64 ,268 + fn tool_err (code: &str , message: impl Into <String >) -> SmithError {270 + code: code.to_string (),271 + message: message.into (),275 + fn io_tool_err (code: &'static str ) -> impl Fn(std::io::Error) -> SmithError {276 + move | e| tool_err (code, e.to_string ())279 + fn json_type_matches (expected: &str , value: & serde_json::Value) -> bool {281 + "string" => value.is_string (),282 + "number" => value.is_number (),283 + "integer" => value.is_i64 () || value.is_u64 (),284 + "boolean" => value.is_boolean (),285 + "array" => value.is_array (),286 + "object" => value.is_object (),287 + "null" => value.is_null (),292 + fn resolve_path (input_path: &str , working_dir: & Path) -> PathBuf {293 + let p = Path::new(input_path);294 + if p.is_absolute () {303 + fn execute_file_effect (305 + input: & serde_json::Value,307 + ) -> std::result::Result <String , SmithError> {308 + let path_str = input.get ("path" ).and_then (|v| v.as_str ()).unwrap_or ("" );311 + let path = resolve_path (path_str, working_dir);312 + let offset = input.get ("offset" ).and_then (|v| v.as_u64 ()).unwrap_or (0 ) as usize ;315 + .and_then (|v| v.as_u64 ())316 + .map (|v| v.min (usize ::MAX as u64 ) as usize )317 + .unwrap_or (usize ::MAX );318 + let max_bytes = input320 + .and_then (|v| v.as_u64 ())321 + .map (|v| (v as usize ).min (HARD_OUTPUT_CAP ))322 + .unwrap_or (DEFAULT_OUTPUT_CAP );323 + read_bounded (& path, offset, limit, max_bytes)328 + .and_then (|v| v.as_str ())329 + .ok_or_else (|| tool_err ("VALIDATION" , "write requires string 'content'" ))? ;330 + let path = resolve_path (path_str, working_dir);331 + write_atomic (& path, content.as_bytes ())? ;332 + Ok (format! ("written {} bytes" , content.len ()))337 + .and_then (|v| v.as_str ())338 + .unwrap_or_default ();341 + .and_then (|v| v.as_str ())342 + .unwrap_or_default ();343 + let path = resolve_path (path_str, working_dir);344 + edit_exact (& path, old, new)347 + let dir = if path_str.is_empty () {348 + working_dir.to_path_buf ()350 + resolve_path (path_str, working_dir)352 + let mut names: Vec <String > = fs::read_dir(& dir)353 + .map_err (io_tool_err ("LS_ERROR" ))? 354 + .collect::<std::io::Result <Vec <_ >>>()355 + .map_err (io_tool_err ("LS_ERROR" ))? 357 + .map (|e| e.file_name ().to_string_lossy ().into_owned ())360 + Ok (bounded_join (names, MAX_LIST_ENTRIES ))365 + .and_then (|v| v.as_str ())366 + .unwrap_or_default ();367 + let root = if path_str.is_empty () {368 + working_dir.to_path_buf ()370 + resolve_path (path_str, working_dir)372 + let mut names: Vec <String > = fs::read_dir(& root)373 + .map_err (io_tool_err ("FIND_ERROR" ))? 374 + .collect::<std::io::Result <Vec <_ >>>()375 + .map_err (io_tool_err ("FIND_ERROR" ))? 377 + .map (|e| e.file_name ().to_string_lossy ().into_owned ())378 + .filter (|n| n.contains (pattern))381 + Ok (bounded_join (names, MAX_LIST_ENTRIES ))386 + .and_then (|v| v.as_str ())387 + .unwrap_or_default ();388 + let path = resolve_path (path_str, working_dir);389 + grep_bounded (& path, query)392 + "TOOL_NOT_IMPLEMENTED" ,393 + format! ("tool '{name}' has no built-in effect" ),404 + ) -> std::result::Result <String , SmithError> {405 + let file = fs::File::open(path).map_err (io_tool_err ("READ_ERROR" ))? ;406 + let mut reader = BufReader::with_capacity(64 * 1024 , file);408 + let sniff = reader.fill_buf ().map_err (io_tool_err ("READ_ERROR" ))? ;409 + if sniff[.. sniff.len ().min (8192 )].contains (& 0 ) {410 + return Err (tool_err (412 + "file contains NUL bytes; binary content is unsupported" ,415 + let mut out = String ::new();416 + let mut buf: Vec <u8 > = Vec ::with_capacity(8 * 1024 );417 + let mut line_no = 0 usize ;418 + let mut bytes_out = 0 usize ;421 + match reader.read_until (b '\n' , &mut buf) {424 + Err (e) => return Err (io_tool_err ("READ_ERROR" )(e)),427 + if line_no <= offset {430 + if out.lines ().count () >= limit.min (usize ::MAX - 1 ) && limit != usize ::MAX {433 + let emit = if limit == usize ::MAX {436 + (line_no - offset) <= limit441 + if bytes_out + buf.len () > max_bytes {444 + bytes_out += buf.len ();445 + out.push_str (& String ::from_utf8_lossy(& buf));446 + if bytes_out >= max_bytes {455 + fn write_atomic (path: & Path, content: & [u8 ]) -> std::result::Result <(), SmithError> {456 + let parent = path.parent ().filter (|p| ! p.as_os_str ().is_empty ());457 + if let Some (parent) = parent {458 + fs::create_dir_all(parent).map_err (io_tool_err ("WRITE_MKDIR" ))? ;460 + let tmp = temp_sibling (path);461 + let write = |tmp: & Path| -> std::io::Result <()> {462 + let mut f = fs::File::create(tmp)? ;463 + f.write_all (content)? ;467 + write (& tmp).map_err (io_tool_err ("WRITE_ERROR" ))? ;468 + fs::rename(& tmp, path).map_err (|e| {469 + let _ = fs::remove_file(& tmp);470 + io_tool_err ("WRITE_PUBLISH" )(e)475 + fn temp_sibling (path: & Path) -> PathBuf {476 + static COUNTER : AtomicUsize = AtomicUsize::new(0 );477 + let n = COUNTER .fetch_add (1 , Ordering::Relaxed);480 + .map (|s| s.to_string_lossy ().into_owned ())481 + .unwrap_or_else (|| "file" .to_string ());482 + path.with_file_name (format! (".{name}.tmp-{}-{n}" , std::process::id()))486 + fn edit_exact (path: & Path, old: &str , new: &str ) -> std::result::Result <String , SmithError> {487 + let meta = fs::metadata(path).map_err (io_tool_err ("EDIT_READ_ERROR" ))? ;488 + if meta.len () as usize > MAX_EDIT_FILE_BYTES {489 + return Err (tool_err (491 + "edit input exceeds the file size limit" ,494 + let bytes = fs::read(path).map_err (io_tool_err ("EDIT_READ_ERROR" ))? ;495 + let content = String ::from_utf8(bytes)496 + .map_err (|_| tool_err ("EDIT_NOT_UTF8" , "edit supports UTF-8 files only" ))? ;497 + let count = content.matches (old).count ();499 + return Err (tool_err (501 + "old_string not found; file unchanged" ,505 + return Err (tool_err (507 + format! ("old_string matches {count} locations; file unchanged" ),510 + let updated = content.replacen (old, new, 1 );511 + write_atomic (path, updated.as_bytes ())? ;512 + Ok ("edited" .to_string ())516 + fn bounded_join (mut names: Vec <String >, cap: usize ) -> String {517 + names.truncate (cap);518 + let mut out = names.join ("\n" );519 + let max = DEFAULT_OUTPUT_CAP ;520 + if out.len () > max {522 + out.push_str ("\n<truncated>" );528 + fn grep_bounded (path: & Path, query: &str ) -> std::result::Result <String , SmithError> {529 + let file = fs::File::open(path).map_err (io_tool_err ("GREP_READ_ERROR" ))? ;530 + let reader = BufReader::with_capacity(64 * 1024 , file);531 + let mut matches: Vec <String > = Vec ::new();532 + let mut total_bytes = 0 usize ;533 + for line in reader.lines () {534 + let line = line.map_err (io_tool_err ("GREP_READ_ERROR" ))? ;535 + if line.contains (query) {536 + if matches.len () >= MAX_GREP_MATCHES || total_bytes + line.len () > DEFAULT_OUTPUT_CAP {537 + matches.push ("<truncated>" .to_string ());540 + total_bytes += line.len ();544 + Ok (matches.join ("\n" ))548 + std::time::SystemTime::now()549 + .duration_since (std::time::UNIX_EPOCH )550 + .map (|d| d.as_millis () as i64 )555 + #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]558 + use std::path::PathBuf;560 + fn workdir (tag: &str ) -> PathBuf {561 + let dir = std::env::temp_dir().join (format! ("smith_tools_{}_{}" , tag, std::process::id()));562 + let _ = std::fs::remove_dir_all(& dir);563 + std::fs::create_dir_all(& dir).unwrap ();568 + fn write_requires_string_content_and_leaves_existing_file_untouched () {569 + let dir = workdir ("write_schema" );570 + let target = dir.join ("data.txt" );571 + std::fs::write(& target, "original" ).unwrap ();572 + let mut ts = ToolSession::new(& dir);574 + .invoke ("write" , serde_json::json! ({"path" : "data.txt" }))576 + assert_eq! (err.code (), "VALIDATION" );577 + assert_eq! (std::fs::read_to_string(& target).unwrap (), "original" );581 + serde_json::json! ({"path" : "data.txt" , "content" : 42 }),584 + assert_eq! (err.code (), "VALIDATION" );585 + assert_eq! (std::fs::read_to_string(& target).unwrap (), "original" );586 + let _ = std::fs::remove_dir_all(& dir);590 + fn write_creates_missing_parents_and_leaves_no_temp_files () {591 + let dir = workdir ("write_parents" );592 + let mut ts = ToolSession::new(& dir);595 + serde_json::json! ({"path" : "a/b/c.txt" , "content" : "deep" }),599 + std::fs::read_to_string(dir.join ("a/b/c.txt" )).unwrap (),602 + let leftovers: Vec <_ > = std::fs::read_dir(& dir)604 + .filter_map (|e| e.ok ())606 + std::fs::read_dir(e.path ())608 + .filter_map (|x| x.ok ())609 + .map (|x| x.file_name ().to_string_lossy ().into_owned ())610 + .collect::<Vec <_ >>()612 + .filter (|n| n.contains (".tmp-" ))615 + leftovers.is_empty (),616 + "temp files left behind: {leftovers:?}" 618 + let _ = std::fs::remove_dir_all(& dir);622 + fn edit_rejects_ambiguous_and_missing_matches_without_changes () {623 + let dir = workdir ("edit_amb" );624 + let target = dir.join ("f.txt" );625 + std::fs::write(& target, "a a" ).unwrap ();626 + let mut ts = ToolSession::new(& dir);630 + serde_json::json! ({"path" : "f.txt" , "old_string" : "a" , "new_string" : "b" }),633 + assert_eq! (err.code (), "EDIT_AMBIGUOUS" );634 + assert_eq! (std::fs::read_to_string(& target).unwrap (), "a a" );638 + serde_json::json! ({"path" : "f.txt" , "old_string" : "NOT_PRESENT" , "new_string" : "b" }),641 + assert_eq! (err.code (), "EDIT_NOT_FOUND" );642 + assert_eq! (std::fs::read_to_string(& target).unwrap (), "a a" );646 + serde_json::json! ({"path" : "f.txt" , "old_string" : "a a" , "new_string" : "b" }),649 + assert_eq! (std::fs::read_to_string(& target).unwrap (), "b" );650 + let _ = std::fs::remove_dir_all(& dir);654 + fn read_supports_line_windows_byte_caps_and_binary_detection () {655 + let dir = workdir ("read_caps" );656 + let mut body = String ::new();658 + body.push_str (& format! ("line-{i}\n" ));660 + std::fs::write(dir.join ("lines.txt" ), & body).unwrap ();661 + let mut ts = ToolSession::new(& dir);665 + serde_json::json! ({"path" : "lines.txt" , "offset" : 2 , "limit" : 3 }),668 + assert_eq! (out.output, "line-2\nline-3\nline-4\n" );672 + serde_json::json! ({"path" : "lines.txt" , "max_bytes" : 20 }),675 + assert! (capped.output.len () <= 20 );676 + std::fs::write(dir.join ("bin.dat" ), [0x62 , 0x00 , 0x62 ]).unwrap ();678 + .invoke ("read" , serde_json::json! ({"path" : "bin.dat" }))680 + assert_eq! (err.code (), "BINARY_CONTENT" );681 + let _ = std::fs::remove_dir_all(& dir);685 + fn ls_and_find_are_sorted_and_surface_errors () {686 + let dir = workdir ("ls_find" );687 + for name in ["zeta" , "alpha" , "mid" ] {688 + std::fs::write(dir.join (name), "" ).unwrap ();690 + let mut ts = ToolSession::new(& dir);691 + let out = ts.invoke ("ls" , serde_json::json! ({})).unwrap ();692 + assert_eq! (out.output, "alpha\nmid\nzeta" );694 + .invoke ("find" , serde_json::json! ({"pattern" : "a" }))696 + assert_eq! (found.output, "alpha\nzeta" );700 + serde_json::json! ({"path" : "missing-dir" , "pattern" : "x" }),703 + assert_eq! (err.code (), "FIND_ERROR" );704 + let _ = std::fs::remove_dir_all(& dir);708 + fn grep_returns_bounded_matches () {709 + let dir = workdir ("grep" );711 + dir.join ("log.txt" ),712 + "hit one\nmiss\nhit two\nmiss\nhit three\n" ,715 + let mut ts = ToolSession::new(& dir);719 + serde_json::json! ({"path" : "log.txt" , "query" : "hit" }),722 + assert_eq! (out.output, "hit one\nhit two\nhit three" );723 + let _ = std::fs::remove_dir_all(& dir);727 + fn unregistered_tools_and_non_object_input_are_rejected () {728 + let dir = workdir ("registry" );729 + let mut ts = ToolSession::new(& dir);730 + let err = ts.invoke ("rm" , serde_json::json! ({})).unwrap_err ();731 + assert_eq! (err.code (), "TOOL_NOT_REGISTERED" );733 + .invoke ("read" , serde_json::json! ("not-an-object" ))735 + assert_eq! (err.code (), "INVALID_INPUT" );736 + let _ = std::fs::remove_dir_all(& dir);740 + fn failed_effects_are_recorded_as_failures () {741 + let dir = workdir ("record_fail" );742 + let mut ts = ToolSession::new(& dir);743 + let res = ts.invoke ("read" , serde_json::json! ({"path" : "nope.txt" }));744 + assert! (res.is_err ());746 + assert_eq! (ts.session.active_branch ().entries.len (), 2 );747 + let last = & ts.session.active_branch ().entries[1 ];748 + match & last.content {749 + EntryContent::ToolResult { ok, .. } => assert! (! ok),750 + other => panic! ("unexpected {other:?}" ),752 + let _ = std::fs::remove_dir_all(& dir);smith-core/src/trace.rs Added new file mode 100644+82 / −0 text lines
1 + #![allow(unused_imports, dead_code)]2 + use crate ::session::{Entry, Session};6 + #[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]7 + pub struct TraceRecord {9 + pub timestamp_ms: i64 ,11 + pub session_id: SessionId,15 + pub event_ref: String,19 + #[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]40 + pub fn build_trace (session: & Session) -> Vec <TraceRecord> {41 + let mut trace = Vec ::new();42 + trace.push (TraceRecord {44 + session_id: session.id,45 + kind: TraceKind::SessionCreated,46 + event_ref: format! ("branch:{}" , session.active_branch_idx),48 + for entry in & session.active_branch ().entries {49 + trace.push (TraceRecord {50 + timestamp_ms: entry.timestamp_ms,51 + session_id: session.id,52 + kind: TraceKind::EntryAdded,53 + event_ref: format! ("entry:{}" , entry.id),61 + pub fn replay (session: & Session) -> Vec <TraceRecord> {66 + #[allow(clippy::unwrap_used, clippy::expect_used)]69 + use smith::message::{Message, Role};72 + fn trace_reconstructs_order () {73 + let mut session = crate ::session::Session::new();74 + session.append_to_active (crate ::session::Entry::message(75 + Message::with_text(Role::User, "hello" ),78 + let trace = replay (& session);79 + assert! (! trace.is_empty ());80 + assert_eq! (trace[0 ].kind, TraceKind::SessionCreated);+8 / −0 text lines
8 8 path = "src/lib.rs" path = "src/lib.rs" 10 10 [dependencies ][dependencies ]
11 + uuid = { workspace = true }12 + serde = { workspace = true }13 + ciborium = { workspace = true }14 + serde_json = { workspace = true }15 + thiserror = { workspace = true }18 + default = []No final newline new file mode 100644+62 / −0 text lines
4 + #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]7 + Session { code: String , message: String },9 + Provider { code: String , message: String },11 + Tool { code: String , message: String },13 + FrameDecode { message: String },15 + FrameEncode { message: String },17 + FrameTooLarge { max_bytes: usize , actual: usize },21 + Config { field: String , message: String },24 + impl fmt::Display for SmithError {25 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {27 + Self ::Session { code, message } => write! (f, "session [{code}]: {message}" ),28 + Self ::Provider { code, message } => write! (f, "provider [{code}]: {message}" ),29 + Self ::Tool { code, message } => write! (f, "tool [{code}]: {message}" ),30 + Self ::FrameDecode { message } => write! (f, "frame decode: {message}" ),31 + Self ::FrameEncode { message } => write! (f, "frame encode: {message}" ),32 + Self ::FrameTooLarge { max_bytes, actual } => {33 + write! (f, "frame too large: {actual} > {max_bytes} bytes" )35 + Self ::Cancelled => write! (f, "operation cancelled" ),36 + Self ::Config { field, message } => {37 + write! (f, "config [{field}]: {message}" )43 + impl std::error::Error for SmithError {}46 + pub type Result < T> = std::result::Result<T, SmithError>;50 + pub fn code (& self) -> &str {52 + Self ::Session { code, .. } => code,53 + Self ::Provider { code, .. } => code,54 + Self ::Tool { code, .. } => code,55 + Self ::FrameDecode { .. } => "FRAME_DECODE" ,56 + Self ::FrameEncode { .. } => "FRAME_ENCODE" ,57 + Self ::FrameTooLarge { .. } => "FRAME_TOO_LARGE" ,58 + Self ::Cancelled => "CANCELLED" ,59 + Self ::Config { .. } => "CONFIG" ,new file mode 100644+242 / −0 text lines
6 + Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,8 + pub struct SessionId (Uuid);11 + pub fn new () -> Self {15 + pub fn as_uuid (& self) -> Uuid {20 + impl fmt::Display for SessionId {21 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {26 + impl From <Uuid> for SessionId {27 + fn from (u: Uuid) -> Self {32 + impl From <SessionId> for Uuid {33 + fn from (id: SessionId) -> Uuid {38 + impl Default for SessionId {39 + fn default () -> Self {46 + Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,48 + pub struct BranchId (Uuid);51 + pub fn new () -> Self {55 + pub fn as_uuid (& self) -> Uuid {60 + impl fmt::Display for BranchId {61 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {66 + impl From <Uuid> for BranchId {67 + fn from (u: Uuid) -> Self {72 + impl From <BranchId> for Uuid {73 + fn from (id: BranchId) -> Uuid {78 + impl Default for BranchId {79 + fn default () -> Self {86 + Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,88 + pub struct EntryId (Uuid);91 + pub fn new () -> Self {95 + pub fn as_uuid (& self) -> Uuid {100 + impl fmt::Display for EntryId {101 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {106 + impl From <Uuid> for EntryId {107 + fn from (u: Uuid) -> Self {112 + impl From <EntryId> for Uuid {113 + fn from (id: EntryId) -> Uuid {118 + impl Default for EntryId {119 + fn default () -> Self {126 + Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,128 + pub struct ToolCallId (Uuid);131 + pub fn new () -> Self {132 + Self (Uuid::now_v7())135 + pub fn as_uuid (& self) -> Uuid {140 + impl fmt::Display for ToolCallId {141 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {146 + impl From <Uuid> for ToolCallId {147 + fn from (u: Uuid) -> Self {152 + impl From <ToolCallId> for Uuid {153 + fn from (id: ToolCallId) -> Uuid {158 + impl Default for ToolCallId {159 + fn default () -> Self {166 + Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,168 + pub struct ToolResultId (Uuid);171 + pub fn new () -> Self {172 + Self (Uuid::now_v7())175 + pub fn as_uuid (& self) -> Uuid {180 + impl fmt::Display for ToolResultId {181 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {186 + impl From <Uuid> for ToolResultId {187 + fn from (u: Uuid) -> Self {192 + impl From <ToolResultId> for Uuid {193 + fn from (id: ToolResultId) -> Uuid {198 + impl Default for ToolResultId {199 + fn default () -> Self {206 + Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,208 + pub struct MessageId (Uuid);211 + pub fn new () -> Self {212 + Self (Uuid::now_v7())215 + pub fn as_uuid (& self) -> Uuid {220 + impl fmt::Display for MessageId {221 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {226 + impl From <Uuid> for MessageId {227 + fn from (u: Uuid) -> Self {232 + impl From <MessageId> for Uuid {233 + fn from (id: MessageId) -> Uuid {238 + impl Default for MessageId {239 + fn default () -> Self {+145 / −1 text lines
1 5 #![forbid(unsafe_code)]#![forbid(unsafe_code)]2 6 #![warn(missing_docs)]#![warn(missing_docs)]
11 + clippy::must_use_candidate,12 + clippy::match_same_arms,13 + clippy::doc_markdown,14 + clippy::missing_const_for_fn,15 + clippy::missing_errors_doc,16 + clippy::module_name_repetitions,17 + clippy::struct_excessive_bools,18 + clippy::too_many_arguments,33 + pub use error::{Result , SmithError};34 + pub use id::{BranchId, EntryId, MessageId, SessionId, ToolCallId, ToolResultId};35 + pub use message::{ContentBlock, Message, Role};36 + pub use stream::{StopReason, StreamEvent, Usage};37 + pub use tool::{CancelHandle, CancellationToken, ToolCall, ToolMetadata, ToolResult};40 + #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic_in_result_fn)]45 + fn ids_are_unique_and_stable () {46 + let a = SessionId::new();47 + let b = SessionId::new();49 + assert_eq! (a, SessionId::from(a.as_uuid ()));53 + fn message_round_trips_blocks () {54 + let call_id = ToolCallId::new();55 + let mut msg = Message::with_text(Role::User, "hello" );56 + msg.add_block (ContentBlock::ToolUse {57 + name: "read" .to_string (),58 + input: serde_json::json! ({"path" : "Cargo.toml" }),61 + msg.add_block (ContentBlock::ToolResult {64 + output: "ok" .to_string (),66 + assert_eq! (msg.blocks.len (), 3 );67 + assert_eq! (msg.role, Role::User);71 + fn stream_event_serializes_deterministically () {72 + let msg = MessageId::new();73 + let call = ToolCallId::new();74 + let ev1 = StreamEvent::tool_use(msg, "write" , serde_json::json! ({"path" : "a.txt" }), call);75 + let ev2 = StreamEvent::tool_use(msg, "write" , serde_json::json! ({"path" : "a.txt" }), call);76 + let bytes1 = serde_json::to_vec(& ev1).unwrap ();77 + let bytes2 = serde_json::to_vec(& ev2).unwrap ();78 + assert_eq! (bytes1, bytes2);79 + let back: StreamEvent = serde_json::from_slice(& bytes1).unwrap ();80 + assert_eq! (back, ev1);84 + fn tool_metadata_has_schema () {85 + let meta = ToolMetadata::new("read" , "Read a file" ).with_schema (serde_json::json! ({87 + "required" : ["path" ],88 + "properties" : {"path" : {"type" : "string" }}90 + assert_eq! (meta.name, "read" );92 + meta.input_schema["required" ]95 + .contains (& "path" .into ())100 + fn cancellation_is_cooperative () {101 + let mut token = CancellationToken::new();102 + assert! (! token.is_cancelled ());104 + assert! (token.is_cancelled ());108 + fn error_codes_are_stable () {109 + let err = SmithError::Tool {110 + code: "TOOL_NOT_FOUND" .to_string (),111 + message: "missing" .to_string (),113 + assert_eq! (err.code (), "TOOL_NOT_FOUND" );114 + assert_eq! (err.to_string (), "tool [TOOL_NOT_FOUND]: missing" );118 + fn thinking_survives_cbor_round_trip () {119 + let mut msg = Message::with_text(Role::Assistant, "answer" );120 + msg.add_block (ContentBlock::thinking("secret reasoning" ));121 + let mut bytes = Vec ::new();122 + ciborium::ser::into_writer(& msg, &mut bytes).unwrap ();123 + let back: Message = ciborium::de::from_reader(bytes.as_slice ()).unwrap ();124 + assert_eq! (back.blocks[0 ], ContentBlock::text("answer" ));125 + assert_eq! (back.blocks[1 ], ContentBlock::thinking("secret reasoning" ));127 + let json = serde_json::to_value(& back.blocks[1 ]).unwrap ();128 + assert_eq! (json["type" ], "Thinking" );132 + fn cancel_handle_is_shared () {133 + let handle = CancelHandle::new();134 + let clone = handle.clone ();135 + assert! (! clone.is_cancelled ());137 + assert! (clone.is_cancelled ());141 + fn usage_defaults_to_zero () {142 + let u = Usage::default();143 + assert_eq! (u.input_tokens, 0 );144 + assert_eq! (u.output_tokens, 0 );145 + assert_eq! (u.input_cache_hit_tokens, 0 );146 + assert_eq! (u.input_cache_write_tokens, 0 );smith/src/message.rs Added new file mode 100644+157 / −0 text lines
2 + use serde::{Deserialize, Serialize};6 + #[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]18 + impl fmt::Display for Role {19 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {21 + Role::User => write! (f, "user" ),22 + Role::Assistant => write! (f, "assistant" ),23 + Role::System => write! (f, "system" ),24 + Role::Tool => write! (f, "tool" ),32 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]33 + #[serde(tag = "type" , content = "data" )]34 + pub enum ContentBlock {44 + input: serde_json::Value,60 + pub fn text <S: Into <String >>(s: S) -> Self {64 + pub fn thinking <S: Into <String >>(s: S) -> Self {65 + Self ::Thinking(s.into ())68 + pub fn tool_use <N: Into <String >>(70 + input: serde_json::Value,80 + pub fn tool_result (call_id: ToolCallId, ok: bool , output: impl Into <String >) -> Self {84 + output: output.into (),90 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]97 + pub blocks: Vec <ContentBlock>,99 + pub timestamp_ms: i64 ,103 + pub fn new (role: Role) -> Self {105 + id: MessageId::new(),108 + timestamp_ms: now_ms (),112 + pub fn with_text <S: Into <String >>(role: Role, text: S) -> Self {114 + id: MessageId::new(),116 + blocks: vec! [ContentBlock::Text(text.into ())],117 + timestamp_ms: now_ms (),121 + pub fn add_block (&mut self, block: ContentBlock) {122 + self.blocks.push (block);126 + impl fmt::Display for Message {127 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {128 + write! (f, "{} [{}]" , self.role, self.id)? ;129 + if ! self.blocks.is_empty () {131 + for (i, block) in self.blocks.iter ().enumerate () {136 + ContentBlock::Text(t) => write! (f, "text: {t}" )? ,137 + ContentBlock::Thinking(t) => write! (f, "thinking: {t}" )? ,138 + ContentBlock::ToolUse { name, call_id, .. } => {139 + write! (f, "tool_use {{ name: {name}, call_id: {call_id} }}" )? 141 + ContentBlock::ToolResult { call_id, ok, .. } => {142 + write! (f, "tool_result {{ call_id: {call_id}, ok: {ok} }}" )? 152 + use std::time::{SystemTime, UNIX_EPOCH };154 + .duration_since (UNIX_EPOCH )155 + .map (|d| d.as_millis () as i64 )new file mode 100644+154 / −0 text lines
2 + use serde::{Deserialize, Serialize};5 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]10 + message_id: MessageId,17 + message_id: MessageId,24 + message_id: MessageId,28 + input: serde_json::Value,35 + message_id: MessageId,48 + usage: Option <Usage>,58 + #[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]73 + #[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]76 + pub input_tokens: u64 ,78 + pub output_tokens: u64 ,80 + pub input_cache_hit_tokens: u64 ,82 + pub input_cache_write_tokens: u64 ,86 + pub fn new () -> Self {90 + input_cache_hit_tokens: 0 ,91 + input_cache_write_tokens: 0 ,96 + impl Default for Usage {97 + fn default () -> Self {103 + pub fn text_delta (message_id: MessageId, delta: impl Into <String >) -> Self {106 + delta: delta.into (),110 + pub fn thinking_delta (message_id: MessageId, delta: impl Into <String >) -> Self {111 + Self ::ThinkingDelta {113 + delta: delta.into (),118 + message_id: MessageId,119 + name: impl Into <String >,120 + input: serde_json::Value,121 + call_id: ToolCallId,132 + message_id: MessageId,133 + call_id: ToolCallId,135 + output: impl Into <String >,141 + output: output.into (),145 + pub fn stop (reason: StopReason, usage: Option <Usage>) -> Self {146 + Self ::Stop { reason, usage }149 + pub fn error (error: impl Into <String >) -> Self {151 + error: error.into (),new file mode 100644+100 / −0 text lines
2 + use serde::{Deserialize, Serialize};5 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]6 + pub struct ToolMetadata {10 + pub description: String,12 + pub input_schema: serde_json::Value,16 + pub fn new <N: Into <String >, D: Into <String >>(name: N, description: D) -> Self {19 + description: description.into (),20 + input_schema: serde_json::json! ({28 + pub fn with_schema (mut self, schema: serde_json::Value) -> Self {29 + self.input_schema = schema;35 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]38 + pub call_id: ToolCallId,42 + pub input: serde_json::Value,46 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]47 + pub struct ToolResult {49 + pub call_id: ToolCallId,58 + #[derive(Clone, Copy, Default, PartialEq, Eq, Debug, Serialize, Deserialize)]59 + pub struct CancellationToken {64 + impl CancellationToken {65 + pub fn new () -> Self {66 + Self { cancelled: false }69 + pub fn cancel (&mut self) {70 + self.cancelled = true ;73 + pub fn is_cancelled (& self) -> bool {80 + #[derive(Clone, Debug, Default)]81 + pub struct CancelHandle {82 + flag: std::sync::Arc<std::sync::atomic::AtomicBool>,87 + pub fn new () -> Self {92 + pub fn cancel (& self) {93 + self.flag.store (true , std::sync::atomic::Ordering::Release);97 + pub fn is_cancelled (& self) -> bool {98 + self.flag.load (std::sync::atomic::Ordering::Acquire)