diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index ce9eb19..93803db 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -11,3 +11,4 @@ jobs: - run: cargo fmt --all --check - run: cargo clippy --workspace --all-targets -- -D warnings - run: cargo test --workspace + - run: cargo build && sh tests/e2e.sh diff --git a/Cargo.lock b/Cargo.lock index 387af53..84b9765 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -119,6 +119,16 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "serde_core", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -305,6 +315,16 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "eventsource-stream" version = "0.2.3" @@ -316,6 +336,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -550,15 +576,27 @@ name = "hx-cli" version = "0.1.0" dependencies = [ "anyhow", + "async-trait", "clap", - "futures", "hx-ai", + "hx-core", + "hx-tools", "tokio", ] [[package]] name = "hx-core" version = "0.1.0" +dependencies = [ + "async-trait", + "futures", + "hx-ai", + "serde", + "serde_json", + "tempfile", + "thiserror", + "tokio", +] [[package]] name = "hx-lens" @@ -571,6 +609,16 @@ version = "0.1.0" [[package]] name = "hx-tools" version = "0.1.0" +dependencies = [ + "async-trait", + "base64", + "hx-ai", + "hx-core", + "serde_json", + "similar", + "tempfile", + "tokio", +] [[package]] name = "hx-tui" @@ -853,6 +901,12 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.3" @@ -1127,6 +1181,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.45" @@ -1333,6 +1400,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[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_cesu8" version = "1.2.0" @@ -1349,6 +1426,15 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "similar" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f66ca1f7aca2474dc10c942eb22feffc897735f54cd1db90138c2fddb490987" +dependencies = [ + "bstr", +] + [[package]] name = "slab" version = "0.4.12" @@ -1431,6 +1517,19 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -1477,6 +1576,7 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.61.2", diff --git a/crates/hx-cli/Cargo.toml b/crates/hx-cli/Cargo.toml index cba1a03..264b1a4 100644 --- a/crates/hx-cli/Cargo.toml +++ b/crates/hx-cli/Cargo.toml @@ -10,10 +10,12 @@ path = "src/main.rs" [dependencies] anyhow = "1.0.104" +async-trait = "0.1.92" clap = { version = "4.6.7", features = ["derive", "env"] } -futures = "0.3.34" hx-ai = { version = "0.1.0", path = "../hx-ai" } -tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros"] } +hx-core = { version = "0.1.0", path = "../hx-core" } +hx-tools = { version = "0.1.0", path = "../hx-tools" } +tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal"] } [lints] workspace = true diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 67dac4e..2e24fb6 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -1,9 +1,14 @@ use anyhow::Result; use clap::{Parser, Subcommand}; -use futures::StreamExt; use hx_ai::auth::{self, Kind}; -use hx_ai::{Message, Provider, Request, StreamEvent, anthropic::Anthropic, codex::Codex}; +use hx_ai::{Provider, StreamEvent, anthropic::Anthropic, codex::Codex}; +use hx_core::agent::Agent; +use hx_core::context; +use hx_core::hook::{Event, Hook, HookAction}; +use hx_core::session::Session; +use hx_core::tool::ToolCtx; use std::io::Write; +use std::sync::Arc; #[derive(Parser)] #[command(name = "hx", version, about = "Minimal coding agent")] @@ -18,6 +23,12 @@ struct Cli { provider: Kind, #[arg(short, long, env = "HX_MODEL")] model: Option, + /// Session file to resume (JSONL). Default: new file under ~/.hx/sessions. + #[arg(short, long)] + session: Option, + /// Continue the most recent session in this directory. + #[arg(short, long)] + r#continue: bool, } #[derive(Subcommand)] @@ -35,13 +46,65 @@ fn default_model(k: Kind) -> &'static str { } } -fn provider(k: Kind) -> hx_ai::Result> { +fn provider(k: Kind) -> hx_ai::Result> { Ok(match k { - Kind::Claude => Box::new(Anthropic::login_default()?), - Kind::Codex => Box::new(Codex::login_default()?), + Kind::Claude => { + let a = Anthropic::login_default()?; + Arc::new(match std::env::var("HX_BASE_URL") { + Ok(u) => a.with_base_url(u), + Err(_) => a, + }) + } + Kind::Codex => { + let c = Codex::login_default()?; + Arc::new(match std::env::var("HX_BASE_URL") { + Ok(u) => c.with_base_url(u), + Err(_) => c, + }) + } }) } +/// Streams text to stdout and tool activity to stderr. +struct Printer; +#[async_trait::async_trait] +impl Hook for Printer { + async fn on(&self, ev: &Event) -> HookAction { + match ev { + Event::Stream(StreamEvent::TextDelta { text }) => { + let mut o = std::io::stdout().lock(); + let _ = o.write_all(text.as_bytes()); + let _ = o.flush(); + } + Event::Stream(StreamEvent::Done { .. }) => println!(), + Event::ToolCall { name, args, .. } => { + let a = args.to_string(); + eprintln!("> {name} {}", a.chars().take(160).collect::()); + } + Event::ToolResult { + is_error: true, + content, + .. + } => { + eprintln!(" ! {}", content.lines().next().unwrap_or_default()); + } + _ => {} + } + HookAction::Continue + } +} + +fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf { + let slug: String = cwd + .to_string_lossy() + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect(); + context::hx_home() + .join("sessions") + .join(slug.trim_matches('-')) +} + #[tokio::main] async fn main() -> Result<()> { let cli = Cli::parse(); @@ -57,34 +120,49 @@ async fn main() -> Result<()> { let Some(prompt) = cli.print else { anyhow::bail!("interactive mode not implemented yet; use -p \"prompt\""); }; - let p = provider(cli.provider)?; - let req = Request { - model: cli - .model - .unwrap_or_else(|| default_model(cli.provider).into()), - system: String::new(), - messages: vec![Message::user(prompt)], - tools: vec![], - max_tokens: 8192, - }; - let mut s = p.stream(req).await?; - let mut out = std::io::stdout().lock(); - while let Some(ev) = s.next().await { - match ev? { - StreamEvent::TextDelta { text } => { - out.write_all(text.as_bytes())?; - out.flush()?; - } - StreamEvent::Done { usage, .. } => { - writeln!(out)?; - eprintln!( - "[{} in / {} out tokens]", - usage.input_tokens + usage.cache_read_tokens, - usage.output_tokens - ); - } - _ => {} + let cwd = std::env::current_dir()?; + let dir = session_dir(&cwd); + let path = match (cli.session, cli.r#continue) { + (Some(p), _) => p, + (None, true) => std::fs::read_dir(&dir) + .ok() + .and_then(|rd| rd.flatten().map(|e| e.path()).max()) + .ok_or_else(|| anyhow::anyhow!("no previous session in {}", dir.display()))?, + (None, false) => { + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH)? + .as_millis(); + dir.join(format!("{ts}.jsonl")) } - } + }; + let cx = ToolCtx { + cwd: cwd.clone(), + state: Default::default(), + }; + let (mut agent, abort) = Agent::new( + provider(cli.provider)?, + hx_tools::registry(), + Session::open(&path)?, + cx, + ); + agent.model = cli + .model + .unwrap_or_else(|| default_model(cli.provider).into()); + agent.system = context::system_prompt(None, &context::hx_home(), &cwd); + agent.bus.add(Printer); + tokio::spawn(async move { + if tokio::signal::ctrl_c().await.is_ok() { + abort.abort(); + } + }); + let r = agent.run(prompt).await; + let u = &agent.usage; + eprintln!( + "[{} in / {} out tokens; session {}]", + u.input_tokens + u.cache_read_tokens, + u.output_tokens, + path.display() + ); + r?; Ok(()) } diff --git a/crates/hx-core/Cargo.toml b/crates/hx-core/Cargo.toml index 2fd1cfb..e8bc561 100644 --- a/crates/hx-core/Cargo.toml +++ b/crates/hx-core/Cargo.toml @@ -5,6 +5,17 @@ edition.workspace = true license.workspace = true [dependencies] +async-trait = "0.1.92" +futures = "0.3.34" +hx-ai = { version = "0.1.0", path = "../hx-ai" } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.151" +thiserror = "2.0.21" +tokio = { version = "1.53.1", features = ["rt", "sync", "time", "macros", "fs"] } [lints] workspace = true + +[dev-dependencies] +tempfile = "3.27.0" +tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread"] } diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs new file mode 100644 index 0000000..6875670 --- /dev/null +++ b/crates/hx-core/src/agent.rs @@ -0,0 +1,381 @@ +//! Agent loop: stream -> tool calls -> hooks -> results -> repeat. + +use crate::hook::{Bus, Event}; +use crate::session::Session; +use crate::tool::{Registry, ToolCtx}; +use futures::StreamExt; +use hx_ai::{ContentBlock, Message, Provider, Request, Role, StopReason, StreamEvent, Usage}; +use std::sync::Arc; +use tokio::sync::watch; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error(transparent)] + Ai(#[from] hx_ai::Error), + #[error("session: {0}")] + Io(#[from] std::io::Error), + #[error("aborted")] + Aborted, + #[error("stream ended without Done")] + Truncated, + #[error("max turns ({0}) reached")] + MaxTurns(u32), +} + +pub struct Agent { + pub provider: Arc, + pub tools: Registry, + pub bus: Bus, + pub cx: ToolCtx, + pub model: String, + pub system: String, + pub max_tokens: u32, + pub max_turns: u32, + pub usage: Usage, + pub session: Session, + abort: watch::Receiver, +} + +/// Cheap handle to cancel a running `Agent::run`. +#[derive(Clone)] +pub struct AbortHandle(Arc>); +impl AbortHandle { + pub fn abort(&self) { + let _ = self.0.send(true); + } +} + +impl Agent { + pub fn new( + provider: Arc, + tools: Registry, + session: Session, + cx: ToolCtx, + ) -> (Self, AbortHandle) { + let (tx, rx) = watch::channel(false); + let a = Self { + provider, + tools, + bus: Bus::default(), + cx, + model: String::new(), + system: String::new(), + max_tokens: 16_384, + max_turns: 200, + usage: Usage::default(), + session, + abort: rx, + }; + (a, AbortHandle(Arc::new(tx))) + } + + fn push(&mut self, m: Message) -> Result<(), Error> { + self.session.append(m.clone())?; + Ok(()) + } + + async fn emit(&self, ev: Event) -> crate::hook::Outcome { + self.bus.emit(ev).await + } + + fn aborted(&self) -> bool { + *self.abort.borrow() + } + + /// Run until the model stops calling tools (and no hook injects more work). + pub async fn run(&mut self, prompt: impl Into) -> Result { + self.push(Message::user(prompt))?; + for _ in 0..self.max_turns { + if self.aborted() { + return Err(Error::Aborted); + } + self.emit(Event::TurnStart).await; + let req = Request { + model: self.model.clone(), + system: self.system.clone(), + messages: self.session.messages(), + tools: self.tools.specs(), + max_tokens: self.max_tokens, + }; + let mut s = self.provider.stream(req).await?; + let mut done = None; + let mut abort = self.abort.clone(); + loop { + tokio::select! { + ev = s.next() => match ev { + Some(ev) => { + let ev = ev?; + if let StreamEvent::Done { message, stop, usage } = &ev { + done = Some((message.clone(), *stop, usage.clone())); + } + self.emit(Event::Stream(ev)).await; + } + None => break, + }, + _ = abort.changed() => return Err(Error::Aborted), + } + } + let (msg, stop, usage) = done.ok_or(Error::Truncated)?; + self.usage.add(&usage); + self.push(msg.clone())?; + self.emit(Event::Message(msg.clone())).await; + + let calls: Vec<(String, String, serde_json::Value)> = msg + .content + .iter() + .filter_map(|b| match b { + ContentBlock::ToolUse { id, name, input } => { + Some((id.clone(), name.clone(), input.clone())) + } + _ => None, + }) + .collect(); + + if calls.is_empty() { + let o = self.emit(Event::AgentEnd).await; + if o.inject.is_empty() || stop == StopReason::MaxTokens { + return Ok(msg); + } + self.push(Message::user(o.inject.join("\n\n")))?; + continue; + } + + // pre-hooks decide block / mutate per call + let mut results: Vec> = vec![None; calls.len()]; + let mut runnable = vec![]; + for (i, (id, name, args)) in calls.iter().enumerate() { + let o = self + .emit(Event::ToolCall { + id: id.clone(), + name: name.clone(), + args: args.clone(), + }) + .await; + match o.blocked { + Some(r) => { + results[i] = Some(ContentBlock::ToolResult { + tool_use_id: id.clone(), + content: format!("blocked: {r}"), + is_error: true, + }) + } + None => { + runnable.push((i, name.clone(), o.args.unwrap_or_else(|| args.clone()))) + } + } + } + let outs = self + .tools + .call_all( + runnable + .iter() + .map(|(_, n, a)| (n.clone(), a.clone())) + .collect(), + &self.cx, + ) + .await; + for ((i, name, args), r) in runnable.into_iter().zip(outs) { + let id = calls[i].0.clone(); + self.emit(Event::ToolResult { + id: id.clone(), + name, + args, + content: r.content.clone(), + is_error: r.is_error, + }) + .await; + results[i] = Some(ContentBlock::ToolResult { + tool_use_id: id, + content: r.content, + is_error: r.is_error, + }); + } + let mut content: Vec = results.into_iter().flatten().collect(); + let o = self.emit(Event::TurnEnd).await; + content.extend(o.inject.into_iter().map(|text| ContentBlock::Text { text })); + self.push(Message { + role: Role::User, + content, + })?; + } + Err(Error::MaxTurns(self.max_turns)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::hook::{Hook, HookAction}; + use crate::tool::{Tool, ToolResult}; + use async_trait::async_trait; + use futures::stream::BoxStream; + use hx_ai::ToolSpec; + use serde_json::{Value, json}; + use std::sync::Mutex; + + /// Replays scripted assistant messages; records requests. + struct Script(Mutex>, Mutex>); + #[async_trait] + impl Provider for Script { + async fn stream( + &self, + req: Request, + ) -> hx_ai::Result>> { + self.1.lock().unwrap().push(req); + let m = self.0.lock().unwrap().remove(0); + let stop = if m + .content + .iter() + .any(|b| matches!(b, ContentBlock::ToolUse { .. })) + { + StopReason::ToolUse + } else { + StopReason::EndTurn + }; + let evs = vec![ + Ok(StreamEvent::TextDelta { text: m.text() }), + Ok(StreamEvent::Done { + message: m, + stop, + usage: Usage { + input_tokens: 1, + output_tokens: 2, + ..Default::default() + }, + }), + ]; + Ok(futures::stream::iter(evs).boxed()) + } + } + + struct Echo; + #[async_trait] + impl Tool for Echo { + fn spec(&self) -> ToolSpec { + ToolSpec { + name: "echo".into(), + description: "".into(), + input_schema: json!({"type":"object"}), + } + } + async fn call(&self, a: Value, _: &ToolCtx) -> ToolResult { + ToolResult::ok(a["s"].as_str().unwrap_or_default()) + } + } + + struct Guard; + #[async_trait] + impl Hook for Guard { + async fn on(&self, ev: &Event) -> HookAction { + match ev { + Event::ToolCall { args, .. } if args["s"] == "bad" => { + HookAction::Block("nope".into()) + } + Event::TurnEnd => HookAction::Inject("lens: ok".into()), + _ => HookAction::Continue, + } + } + } + + fn asst(blocks: Vec) -> Message { + Message { + role: Role::Assistant, + content: blocks, + } + } + fn tu(id: &str, s: &str) -> ContentBlock { + ContentBlock::ToolUse { + id: id.into(), + name: "echo".into(), + input: json!({"s": s}), + } + } + + #[tokio::test] + async fn multi_turn_with_hooks() { + let script = Arc::new(Script( + Mutex::new(vec![ + asst(vec![tu("1", "hi"), tu("2", "bad")]), + asst(vec![ContentBlock::Text { + text: "done".into(), + }]), + ]), + Mutex::new(vec![]), + )); + let dir = tempfile::tempdir().unwrap(); + let mut tools = Registry::default(); + tools.add(Echo); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let (mut a, _h) = Agent::new( + script.clone(), + tools, + Session::open(dir.path().join("s.jsonl")).unwrap(), + cx, + ); + a.bus.add(Guard); + let out = a.run("go").await.unwrap(); + assert_eq!(out.text(), "done"); + assert_eq!(a.usage.output_tokens, 4); + + let reqs = script.1.lock().unwrap(); + assert_eq!(reqs.len(), 2); + let turn = &reqs[1].messages[2]; + assert_eq!( + turn.content[0], + ContentBlock::ToolResult { + tool_use_id: "1".into(), + content: "hi".into(), + is_error: false + } + ); + assert!( + matches!(&turn.content[1], ContentBlock::ToolResult { is_error: true, content, .. } if content.contains("nope")) + ); + assert_eq!( + turn.content[2], + ContentBlock::Text { + text: "lens: ok".into() + } + ); + // resumable from disk + assert_eq!( + Session::open(dir.path().join("s.jsonl")) + .unwrap() + .messages() + .len(), + 4 + ); + } + + #[tokio::test] + async fn abort_and_max_turns() { + let loop_forever = Arc::new(Script( + Mutex::new( + (0..5) + .map(|i| asst(vec![tu(&i.to_string(), "x")])) + .collect(), + ), + Mutex::new(vec![]), + )); + let dir = tempfile::tempdir().unwrap(); + let mut tools = Registry::default(); + tools.add(Echo); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let (mut a, h) = Agent::new( + loop_forever, + tools, + Session::open(dir.path().join("s.jsonl")).unwrap(), + cx, + ); + a.max_turns = 2; + assert!(matches!(a.run("go").await, Err(Error::MaxTurns(2)))); + h.abort(); + assert!(matches!(a.run("again").await, Err(Error::Aborted))); + } +} diff --git a/crates/hx-core/src/context.rs b/crates/hx-core/src/context.rs new file mode 100644 index 0000000..b5faa89 --- /dev/null +++ b/crates/hx-core/src/context.rs @@ -0,0 +1,151 @@ +//! System prompt, AGENTS.md discovery, skills. + +use std::path::{Path, PathBuf}; + +pub const DEFAULT_PROMPT: &str = "You are hx, a coding agent working in the user's repository. \ +Use the tools to read, edit and run code. Read files before editing them. Keep answers short."; + +const CONTEXT_FILES: &[&str] = &["AGENTS.md", "CLAUDE.md"]; + +pub fn hx_home() -> PathBuf { + std::env::var_os("HX_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| { + std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_default() + .join(".hx") + }) +} + +/// Context files from global (`~/.hx`) then root-most to `cwd`. First match per dir. +pub fn context_files(home: &Path, cwd: &Path) -> Vec<(PathBuf, String)> { + let mut dirs: Vec<&Path> = cwd.ancestors().collect(); + dirs.reverse(); + let mut out = vec![]; + for d in std::iter::once(home).chain(dirs) { + for n in CONTEXT_FILES { + let p = d.join(n); + if let Ok(s) = std::fs::read_to_string(&p) { + out.push((p, s)); + break; + } + } + } + out +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Skill { + pub name: String, + pub description: String, + pub path: PathBuf, +} + +/// `//SKILL.md` with `name:` / `description:` frontmatter. Project skills override global. +pub fn skills(home: &Path, cwd: &Path) -> Vec { + let mut out: Vec = vec![]; + for dir in [home.join("skills"), cwd.join(".hx/skills")] { + let Ok(rd) = std::fs::read_dir(&dir) else { + continue; + }; + let mut paths: Vec<_> = rd + .flatten() + .map(|e| e.path().join("SKILL.md")) + .filter(|p| p.is_file()) + .collect(); + paths.sort(); + for p in paths { + let Ok(s) = std::fs::read_to_string(&p) else { + continue; + }; + let fm = s + .strip_prefix("---") + .and_then(|r| r.split_once("\n---")) + .map_or("", |(f, _)| f); + let get = |k: &str| { + fm.lines().find_map(|l| { + l.strip_prefix(k)? + .strip_prefix(':') + .map(|v| v.trim().trim_matches('"').to_string()) + }) + }; + let name = get("name").unwrap_or_else(|| { + p.parent() + .and_then(|d| d.file_name()) + .unwrap_or_default() + .to_string_lossy() + .into() + }); + let sk = Skill { + description: get("description").unwrap_or_default(), + name, + path: p, + }; + out.retain(|x| x.name != sk.name); + out.push(sk); + } + } + out +} + +pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> String { + let mut s = base.unwrap_or(DEFAULT_PROMPT).to_string(); + s.push_str(&format!("\n\nWorking directory: {}", cwd.display())); + let sk = skills(home, cwd); + if !sk.is_empty() { + s.push_str("\n\n# Skills\nRead a skill's file with `read` when the task matches it.\n"); + for k in sk { + s.push_str(&format!( + "- {}: {} ({})\n", + k.name, + k.description, + k.path.display() + )); + } + } + for (p, c) in context_files(home, cwd) { + s.push_str(&format!("\n\n# {}\n{}", p.display(), c.trim())); + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prompt_assembly() { + let t = tempfile::tempdir().unwrap(); + let home = t.path().join("home"); + let proj = t.path().join("proj/sub"); + std::fs::create_dir_all(home.join("skills/g")).unwrap(); + std::fs::create_dir_all(proj.join(".hx/skills/g")).unwrap(); + std::fs::write(home.join("AGENTS.md"), "GLOBAL").unwrap(); + std::fs::write(t.path().join("proj/AGENTS.md"), "PROJ").unwrap(); + std::fs::write(t.path().join("proj/CLAUDE.md"), "IGNORED").unwrap(); + std::fs::write(proj.join("CLAUDE.md"), "SUB").unwrap(); + std::fs::write( + home.join("skills/g/SKILL.md"), + "---\nname: g\ndescription: global\n---\nbody", + ) + .unwrap(); + std::fs::write( + proj.join(".hx/skills/g/SKILL.md"), + "---\nname: g\ndescription: \"local\"\n---\nBODY", + ) + .unwrap(); + + let s = system_prompt(None, &home, &proj); + let (g, p, sub) = ( + s.find("GLOBAL").unwrap(), + s.find("PROJ").unwrap(), + s.find("SUB").unwrap(), + ); + assert!(g < p && p < sub); + assert!(!s.contains("IGNORED")); + assert!(s.contains("- g: local") && !s.contains("global (")); + assert!(!s.contains("BODY"), "skill body must load on demand only"); + assert!(system_prompt(Some("CUSTOM"), &home, &proj).starts_with("CUSTOM")); + } +} diff --git a/crates/hx-core/src/hook.rs b/crates/hx-core/src/hook.rs new file mode 100644 index 0000000..b702d08 --- /dev/null +++ b/crates/hx-core/src/hook.rs @@ -0,0 +1,134 @@ +//! Event bus and hooks. Lens, MCP and extensions all plug in here. + +use async_trait::async_trait; +use hx_ai::{Message, StreamEvent}; +use serde_json::Value; +use std::sync::Arc; + +#[derive(Debug, Clone)] +pub enum Event { + SessionStart, + TurnStart, + /// Before a tool runs. `Block` or `Mutate` apply. + ToolCall { + id: String, + name: String, + args: Value, + }, + ToolResult { + id: String, + name: String, + args: Value, + content: String, + is_error: bool, + }, + /// After all tools of a turn ran. `Inject` adds a user message before the next request. + TurnEnd, + /// Model finished without tool calls. `Inject` makes the agent continue. + AgentEnd, + /// Streaming output from the model (UI). + Stream(StreamEvent), + Message(Message), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum HookAction { + Continue, + Block(String), + Mutate(Value), + Inject(String), +} + +#[async_trait] +pub trait Hook: Send + Sync { + async fn on(&self, ev: &Event) -> HookAction; +} + +#[derive(Default, Clone)] +pub struct Bus { + hooks: Vec>, +} + +/// Aggregate outcome of dispatching one event to all hooks. +#[derive(Debug, Default, PartialEq)] +pub struct Outcome { + pub blocked: Option, + pub args: Option, + pub inject: Vec, +} + +impl Bus { + pub fn add(&mut self, h: impl Hook + 'static) -> &mut Self { + self.hooks.push(Arc::new(h)); + self + } + + /// Hooks run in registration order. First `Block` wins; `Mutate` is visible to later hooks. + pub async fn emit(&self, ev: Event) -> Outcome { + let mut ev = ev; + let mut o = Outcome::default(); + for h in &self.hooks { + match h.on(&ev).await { + HookAction::Continue => {} + HookAction::Block(r) => { + o.blocked = Some(r); + break; + } + HookAction::Mutate(v) => { + if let Event::ToolCall { args, .. } = &mut ev { + *args = v.clone(); + o.args = Some(v); + } + } + HookAction::Inject(m) => o.inject.push(m), + } + } + o + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + struct NoRm; + #[async_trait] + impl Hook for NoRm { + async fn on(&self, ev: &Event) -> HookAction { + match ev { + Event::ToolCall { args, .. } + if args["cmd"].as_str().is_some_and(|c| c.contains("rm -rf")) => + { + HookAction::Block("no".into()) + } + Event::ToolCall { args, .. } if args["cmd"] == "ls" => { + HookAction::Mutate(json!({"cmd": "ls -la"})) + } + Event::TurnEnd => HookAction::Inject("diag".into()), + _ => HookAction::Continue, + } + } + } + + #[tokio::test] + async fn block_mutate_inject() { + let mut b = Bus::default(); + b.add(NoRm); + let call = |c: &str| Event::ToolCall { + id: "1".into(), + name: "bash".into(), + args: json!({"cmd": c}), + }; + assert_eq!( + b.emit(call("rm -rf /")).await.blocked.as_deref(), + Some("no") + ); + assert_eq!( + b.emit(call("ls")).await.args, + Some(json!({"cmd": "ls -la"})) + ); + assert_eq!(b.emit(Event::TurnEnd).await.inject, ["diag"]); + assert_eq!(b.emit(Event::SessionStart).await, Outcome::default()); + } +} diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index b93cf3f..6fee57a 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -1,14 +1,38 @@ -pub fn add(left: u64, right: u64) -> u64 { - left + right +//! hx core: tools, hooks, agent loop, sessions, context. + +pub mod agent; +pub mod context; +pub mod hook; +pub mod session; +pub mod tool; + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Mutex; +use std::time::SystemTime; + +/// Cross-tool shared state. +#[derive(Default)] +pub struct State { + /// File -> mtime when the agent last read or wrote it. Used by the read-guard. + pub seen: Mutex>>, } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); +impl State { + pub fn mark_seen(&self, p: &std::path::Path) { + let m = std::fs::metadata(p).and_then(|m| m.modified()).ok(); + self.seen + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(p.to_path_buf(), m); + } + /// True when the file was read/written by the agent and not changed on disk since. + pub fn is_fresh(&self, p: &std::path::Path) -> bool { + let now = std::fs::metadata(p).and_then(|m| m.modified()).ok(); + self.seen + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(p) + .is_some_and(|m| *m == now) } } diff --git a/crates/hx-core/src/session.rs b/crates/hx-core/src/session.rs new file mode 100644 index 0000000..06e3a1f --- /dev/null +++ b/crates/hx-core/src/session.rs @@ -0,0 +1,125 @@ +//! Append-only JSONL session tree. Each entry has `id` + `parent`; the head is the last appended id. +//! Forking = appending with an older parent. Resume = walk parents from the head. + +use hx_ai::Message; +use serde::{Deserialize, Serialize}; +use std::io::{BufRead, Write}; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Entry { + pub id: u64, + pub parent: Option, + pub message: Message, +} + +pub struct Session { + path: PathBuf, + entries: Vec, + head: Option, +} + +impl Session { + /// Open (or create) a session file; head = last entry. + pub fn open(path: impl AsRef) -> std::io::Result { + let path = path.as_ref().to_path_buf(); + if let Some(d) = path.parent() { + std::fs::create_dir_all(d)?; + } + let mut entries = vec![]; + if let Ok(f) = std::fs::File::open(&path) { + for l in std::io::BufReader::new(f).lines() { + let l = l?; + // skip a torn last line from a crash rather than losing the session + if let Ok(e) = serde_json::from_str::(&l) { + entries.push(e); + } + } + } + let head = entries.last().map(|e| e.id); + Ok(Self { + path, + entries, + head, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + pub fn head(&self) -> Option { + self.head + } + + pub fn append(&mut self, message: Message) -> std::io::Result { + let id = self.entries.last().map_or(0, |e| e.id + 1); + let e = Entry { + id, + parent: self.head, + message, + }; + let mut f = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&self.path)?; + writeln!( + f, + "{}", + serde_json::to_string(&e).map_err(std::io::Error::other)? + )?; + self.entries.push(e); + self.head = Some(id); + Ok(id) + } + + /// Move head to `id` so the next append branches from it. + pub fn fork(&mut self, id: u64) -> bool { + let ok = self.entries.iter().any(|e| e.id == id); + if ok { + self.head = Some(id); + } + ok + } + + /// Messages on the path root..=head. + pub fn messages(&self) -> Vec { + let mut out = vec![]; + let mut cur = self.head; + while let Some(id) = cur { + let Some(e) = self.entries.iter().find(|e| e.id == id) else { + break; + }; + out.push(e.message.clone()); + cur = e.parent; + } + out.reverse(); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn branch_and_resume() { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("s/a.jsonl"); + let mut s = Session::open(&p).unwrap(); + let a = s.append(Message::user("a")).unwrap(); + s.append(Message::user("b")).unwrap(); + assert!(s.fork(a)); + s.append(Message::user("c")).unwrap(); + let txt = |s: &Session| s.messages().iter().map(|m| m.text()).collect::>(); + assert_eq!(txt(&s), ["a", "c"]); + std::fs::OpenOptions::new() + .append(true) + .open(&p) + .unwrap() + .write_all(b"{torn") + .unwrap(); + let s2 = Session::open(&p).unwrap(); + assert_eq!(txt(&s2), ["a", "c"]); + assert!(!Session::open(&p).unwrap().fork(99)); + } +} diff --git a/crates/hx-core/src/tool.rs b/crates/hx-core/src/tool.rs new file mode 100644 index 0000000..a9b7d80 --- /dev/null +++ b/crates/hx-core/src/tool.rs @@ -0,0 +1,174 @@ +//! Tools: trait, context, registry, argument validation, parallel dispatch. + +use async_trait::async_trait; +use hx_ai::ToolSpec; +use serde_json::Value; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; + +#[derive(Debug, Clone, PartialEq)] +pub struct ToolResult { + pub content: String, + pub is_error: bool, +} + +impl ToolResult { + pub fn ok(s: impl Into) -> Self { + Self { + content: s.into(), + is_error: false, + } + } + pub fn err(s: impl Into) -> Self { + Self { + content: s.into(), + is_error: true, + } + } +} + +/// Per-call context. Shared state (read-tracking, seq log) hangs off `state`. +#[derive(Clone)] +pub struct ToolCtx { + pub cwd: PathBuf, + pub state: Arc, +} + +#[async_trait] +pub trait Tool: Send + Sync { + fn spec(&self) -> ToolSpec; + async fn call(&self, args: Value, cx: &ToolCtx) -> ToolResult; +} + +/// Minimal JSON-schema check: object type, required keys, primitive property types. +/// ponytail: no nested/enum/format checks; swap for `jsonschema` crate if models send bad nested args. +pub fn validate(schema: &Value, args: &Value) -> Result<(), String> { + let Some(obj) = args.as_object() else { + return Err("arguments must be a JSON object".into()); + }; + for r in schema["required"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if !obj.contains_key(r) { + return Err(format!("missing required argument `{r}`")); + } + } + for (k, v) in obj { + let Some(want) = schema["properties"][k]["type"].as_str() else { + continue; + }; + let ok = match want { + "string" => v.is_string(), + "integer" => v.is_i64() || v.is_u64(), + "number" => v.is_number(), + "boolean" => v.is_boolean(), + "array" => v.is_array(), + "object" => v.is_object(), + _ => true, + }; + if !ok && !v.is_null() { + return Err(format!("argument `{k}` must be {want}")); + } + } + Ok(()) +} + +#[derive(Default, Clone)] +pub struct Registry { + tools: BTreeMap>, +} + +impl Registry { + pub fn add(&mut self, t: impl Tool + 'static) -> &mut Self { + self.tools.insert(t.spec().name, Arc::new(t)); + self + } + pub fn specs(&self) -> Vec { + self.tools.values().map(|t| t.spec()).collect() + } + pub fn get(&self, name: &str) -> Option> { + self.tools.get(name).cloned() + } + + pub async fn call(&self, name: &str, args: Value, cx: &ToolCtx) -> ToolResult { + let Some(t) = self.get(name) else { + return ToolResult::err(format!("unknown tool `{name}`")); + }; + if let Err(e) = validate(&t.spec().input_schema, &args) { + return ToolResult::err(e); + } + t.call(args, cx).await + } + + /// Run calls concurrently; results keep input order. + pub async fn call_all(&self, calls: Vec<(String, Value)>, cx: &ToolCtx) -> Vec { + futures::future::join_all( + calls + .into_iter() + .map(|(n, a)| async move { self.call(&n, a, cx).await }), + ) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::time::{Duration, Instant}; + + struct Sleep; + #[async_trait] + impl Tool for Sleep { + fn spec(&self) -> ToolSpec { + ToolSpec { + name: "sleep".into(), + description: "sleep ms".into(), + input_schema: json!({"type":"object","properties":{"ms":{"type":"integer"}},"required":["ms"]}), + } + } + async fn call(&self, a: Value, _: &ToolCtx) -> ToolResult { + let ms = a["ms"].as_u64().unwrap(); + tokio::time::sleep(Duration::from_millis(ms)).await; + ToolResult::ok(ms.to_string()) + } + } + + pub(crate) fn cx() -> ToolCtx { + ToolCtx { + cwd: std::env::temp_dir(), + state: Default::default(), + } + } + + #[tokio::test] + async fn registry_validation_parallel() { + let mut r = Registry::default(); + r.add(Sleep); + assert_eq!(r.specs().len(), 1); + assert!(r.call("nope", json!({}), &cx()).await.is_error); + let e = r.call("sleep", json!({}), &cx()).await; + assert!(e.is_error && e.content.contains("`ms`")); + let e = r.call("sleep", json!({"ms": "x"}), &cx()).await; + assert!(e.is_error && e.content.contains("integer")); + let t = Instant::now(); + let out = r + .call_all( + vec![ + ("sleep".into(), json!({"ms": 150})), + ("sleep".into(), json!({"ms": 10})), + ], + &cx(), + ) + .await; + assert!(t.elapsed() < Duration::from_millis(280), "not parallel"); + assert_eq!( + out.iter().map(|r| r.content.as_str()).collect::>(), + ["150", "10"] + ); + } +} diff --git a/crates/hx-tools/Cargo.toml b/crates/hx-tools/Cargo.toml index ece2e77..0e583a2 100644 --- a/crates/hx-tools/Cargo.toml +++ b/crates/hx-tools/Cargo.toml @@ -5,6 +5,17 @@ edition.workspace = true license.workspace = true [dependencies] +async-trait = "0.1.92" +base64 = "0.23.1" +hx-ai = { version = "0.1.0", path = "../hx-ai" } +hx-core = { version = "0.1.0", path = "../hx-core" } +serde_json = "1.0.151" +similar = "3.2.0" +tokio = { version = "1.53.1", features = ["process", "time", "io-util", "rt", "macros"] } [lints] workspace = true + +[dev-dependencies] +tempfile = "3.27.0" +tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread"] } diff --git a/crates/hx-tools/src/lib.rs b/crates/hx-tools/src/lib.rs index b93cf3f..0ecef46 100644 --- a/crates/hx-tools/src/lib.rs +++ b/crates/hx-tools/src/lib.rs @@ -1,14 +1,449 @@ -pub fn add(left: u64, right: u64) -> u64 { - left + right +//! Built-in tools: read, write, edit, bash. + +use async_trait::async_trait; +use hx_ai::ToolSpec; +use hx_core::tool::{Registry, Tool, ToolCtx, ToolResult}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +const MAX_LINES: usize = 2000; +const MAX_BYTES: usize = 50_000; + +fn spec(name: &str, desc: &str, schema: Value) -> ToolSpec { + ToolSpec { + name: name.into(), + description: desc.into(), + input_schema: schema, + } +} + +fn resolve(cx: &ToolCtx, p: &str) -> PathBuf { + let p = Path::new(p); + if p.is_absolute() { + p.into() + } else { + cx.cwd.join(p) + } +} + +/// Keep the tail of `s` within `max` bytes on a char boundary. +fn tail(s: &str, max: usize) -> &str { + if s.len() <= max { + return s; + } + let mut i = s.len() - max; + while !s.is_char_boundary(i) { + i += 1; + } + &s[i..] +} + +pub fn registry() -> Registry { + let mut r = Registry::default(); + r.add(Read).add(Write).add(Edit).add(Bash); + r +} + +pub struct Read; +#[async_trait] +impl Tool for Read { + fn spec(&self) -> ToolSpec { + spec( + "read", + "Read a file. Returns numbered lines. Use offset/limit for large files. Images are returned as attachments.", + json!({"type":"object","properties":{ + "path":{"type":"string"}, + "offset":{"type":"integer","description":"1-based first line"}, + "limit":{"type":"integer","description":"max lines"}}, + "required":["path"]}), + ) + } + async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { + let p = resolve(cx, a["path"].as_str().unwrap_or_default()); + let bytes = match tokio::fs::read(&p).await { + Ok(b) => b, + Err(e) => return ToolResult::err(format!("{}: {e}", p.display())), + }; + cx.state.mark_seen(&p); + let ext = p + .extension() + .and_then(|e| e.to_str()) + .unwrap_or_default() + .to_ascii_lowercase(); + if let Some(mt) = match ext.as_str() { + "png" => Some("image/png"), + "jpg" | "jpeg" => Some("image/jpeg"), + "gif" => Some("image/gif"), + "webp" => Some("image/webp"), + _ => None, + } { + // ponytail: image returned as data URL text; switch ToolResult to blocks when the TUI renders images. + use base64::Engine; + return ToolResult::ok(format!( + "data:{mt};base64,{}", + base64::engine::general_purpose::STANDARD.encode(&bytes) + )); + } + if bytes.iter().take(8000).any(|&b| b == 0) { + return ToolResult::err(format!( + "{}: binary file ({} bytes)", + p.display(), + bytes.len() + )); + } + let text = String::from_utf8_lossy(&bytes); + let total = text.lines().count(); + let start = a["offset"].as_u64().unwrap_or(1).max(1) as usize; + let limit = a["limit"] + .as_u64() + .map_or(MAX_LINES, |l| l as usize) + .min(MAX_LINES); + let mut out = String::new(); + let mut shown = 0; + for (i, l) in text.lines().enumerate().skip(start - 1).take(limit) { + let line = format!("{:>6}\t{l}\n", i + 1); + if out.len() + line.len() > MAX_BYTES { + break; + } + out.push_str(&line); + shown += 1; + } + let end = start - 1 + shown; + if end < total { + out.push_str(&format!( + "\n[showing lines {start}-{end} of {total}; use offset={} to continue]", + end + 1 + )); + } + if total == 0 { + out = "[empty file]".into(); + } + ToolResult::ok(out) + } +} + +pub struct Write; +#[async_trait] +impl Tool for Write { + fn spec(&self) -> ToolSpec { + spec( + "write", + "Create or overwrite a file with the given content. Creates parent directories.", + json!({"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path","content"]}), + ) + } + async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { + let p = resolve(cx, a["path"].as_str().unwrap_or_default()); + let c = a["content"].as_str().unwrap_or_default(); + if p.exists() && !cx.state.is_fresh(&p) { + return ToolResult::err(format!( + "{} exists and was not read (or changed on disk) since; read it first", + p.display() + )); + } + if let Some(d) = p.parent() + && let Err(e) = tokio::fs::create_dir_all(d).await + { + return ToolResult::err(format!("{}: {e}", d.display())); + } + match tokio::fs::write(&p, c).await { + Ok(()) => { + cx.state.mark_seen(&p); + ToolResult::ok(format!( + "wrote {} ({} lines)", + p.display(), + c.lines().count() + )) + } + Err(e) => ToolResult::err(format!("{}: {e}", p.display())), + } + } +} + +pub struct Edit; +#[async_trait] +impl Tool for Edit { + fn spec(&self) -> ToolSpec { + spec( + "edit", + "Replace an exact string in a file. old_string must match exactly once unless replace_all is true. Read the file first.", + json!({"type":"object","properties":{ + "path":{"type":"string"}, + "old_string":{"type":"string"}, + "new_string":{"type":"string"}, + "replace_all":{"type":"boolean"}}, + "required":["path","old_string","new_string"]}), + ) + } + async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { + let p = resolve(cx, a["path"].as_str().unwrap_or_default()); + let (old, new) = ( + a["old_string"].as_str().unwrap_or_default(), + a["new_string"].as_str().unwrap_or_default(), + ); + if old.is_empty() { + return ToolResult::err("old_string is empty; use write to create files"); + } + if !cx.state.is_fresh(&p) { + return ToolResult::err(format!( + "{} was not read (or changed on disk) since; read it first", + p.display() + )); + } + let src = match tokio::fs::read_to_string(&p).await { + Ok(s) => s, + Err(e) => return ToolResult::err(format!("{}: {e}", p.display())), + }; + // Models send LF; preserve CRLF files. + let crlf = src.contains("\r\n"); + let fix = |s: &str| { + if crlf { + s.replace("\r\n", "\n").replace('\n', "\r\n") + } else { + s.to_string() + } + }; + let (old, new) = (fix(old), fix(new)); + let n = src.matches(&old).count(); + let all = a["replace_all"].as_bool().unwrap_or(false); + match (n, all) { + (0, _) => { + return ToolResult::err( + "old_string not found; re-read the file and copy the exact text", + ); + } + (n, false) if n > 1 => { + return ToolResult::err(format!( + "old_string matches {n} times; add surrounding context or set replace_all" + )); + } + _ => {} + } + let out = if all { + src.replace(&old, &new) + } else { + src.replacen(&old, &new, 1) + }; + if let Err(e) = tokio::fs::write(&p, &out).await { + return ToolResult::err(format!("{}: {e}", p.display())); + } + cx.state.mark_seen(&p); + let diff = similar::TextDiff::from_lines(&src, &out) + .unified_diff() + .context_radius(2) + .to_string(); + ToolResult::ok(format!( + "edited {} ({n} replacement{})\n{diff}", + p.display(), + if n == 1 { "" } else { "s" } + )) + } +} + +pub struct Bash; +#[async_trait] +impl Tool for Bash { + fn spec(&self) -> ToolSpec { + spec( + "bash", + "Run a shell command in the working directory. stdout and stderr are merged. Long output is truncated to the tail.", + json!({"type":"object","properties":{ + "command":{"type":"string"}, + "timeout":{"type":"integer","description":"seconds, default 120"}}, + "required":["command"]}), + ) + } + async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { + let cmd = a["command"].as_str().unwrap_or_default(); + let secs = a["timeout"].as_u64().unwrap_or(120).clamp(1, 3600); + let mut c = tokio::process::Command::new("bash"); + c.arg("-c") + .arg(format!("exec 2>&1; {cmd}")) + .current_dir(&cx.cwd) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::piped()) + .kill_on_drop(true); + // own process group so timeouts kill children too + #[cfg(unix)] + c.process_group(0); + let child = match c.spawn() { + Ok(c) => c, + Err(e) => return ToolResult::err(format!("spawn: {e}")), + }; + let pid = child.id(); + let res = tokio::time::timeout(Duration::from_secs(secs), child.wait_with_output()).await; + let (out, code) = match res { + Ok(Ok(o)) => (o.stdout, o.status.code()), + Ok(Err(e)) => return ToolResult::err(format!("wait: {e}")), + Err(_) => { + #[cfg(unix)] + if let Some(pid) = pid { + let _ = std::process::Command::new("kill") + .args(["-KILL", &format!("-{pid}")]) + .status(); + } + return ToolResult::err(format!("timed out after {secs}s")); + } + }; + let s = String::from_utf8_lossy(&out); + let mut body = tail(&s, MAX_BYTES).to_string(); + if body.len() < s.len() { + let f = std::env::temp_dir().join(format!( + "hx-bash-{}.log", + std::process::id() as u128 * 1000 + pid.unwrap_or(0) as u128 + )); + let _ = std::fs::write(&f, s.as_bytes()); + body = format!( + "[truncated {} bytes; full output: {}]\n{body}", + s.len() - body.len(), + f.display() + ); + } + match code { + Some(0) => ToolResult::ok(if body.is_empty() { + "(no output)".into() + } else { + body + }), + c => ToolResult::err(format!( + "{body}\n[exit {}]", + c.map_or("signal".into(), |c| c.to_string()) + )), + } + } } #[cfg(test)] mod tests { use super::*; + use std::time::Instant; - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); + fn cx(d: &Path) -> ToolCtx { + ToolCtx { + cwd: d.into(), + state: Default::default(), + } + } + + #[tokio::test] + async fn read_ranges_binary_missing() { + let d = tempfile::tempdir().unwrap(); + let c = cx(d.path()); + let body: String = (1..=10).map(|i| format!("l{i}\n")).collect(); + std::fs::write(d.path().join("a.txt"), body).unwrap(); + let r = Read + .call(json!({"path":"a.txt","offset":3,"limit":2}), &c) + .await; + assert!(!r.is_error); + assert!(r.content.contains(" 3\tl3\n 4\tl4\n") && !r.content.contains("l5\n")); + assert!(r.content.contains("offset=5")); + std::fs::write(d.path().join("b.bin"), [0u8, 1, 2]).unwrap(); + assert!( + Read.call(json!({"path":"b.bin"}), &c) + .await + .content + .contains("binary") + ); + assert!(Read.call(json!({"path":"nope"}), &c).await.is_error); + std::fs::write(d.path().join("big.txt"), "x".repeat(200) + "\n").unwrap(); + let big: String = (0..1000).map(|_| "y".repeat(200) + "\n").collect(); + std::fs::write(d.path().join("big.txt"), big).unwrap(); + let r = Read.call(json!({"path":"big.txt"}), &c).await; + assert!(r.content.len() < MAX_BYTES + 200 && r.content.contains("use offset=")); + } + + #[tokio::test] + async fn write_edit_guard_crlf() { + let d = tempfile::tempdir().unwrap(); + let c = cx(d.path()); + assert!( + !Write + .call(json!({"path":"x/new.rs","content":"a\nb\n"}), &c) + .await + .is_error + ); + // blind overwrite of an existing unread file is refused + std::fs::write(d.path().join("other.rs"), "keep").unwrap(); + assert!( + Write + .call(json!({"path":"other.rs","content":"z"}), &c) + .await + .is_error + ); + assert!( + Edit.call( + json!({"path":"other.rs","old_string":"keep","new_string":"z"}), + &c + ) + .await + .is_error + ); + + let p = d.path().join("f.rs"); + std::fs::write(&p, "fn a() {}\r\nfn a() {}\r\nfn b() {}\r\n").unwrap(); + Read.call(json!({"path":"f.rs"}), &c).await; + let amb = Edit + .call( + json!({"path":"f.rs","old_string":"fn a() {}","new_string":"x"}), + &c, + ) + .await; + assert!(amb.is_error && amb.content.contains("2 times")); + assert!( + Edit.call( + json!({"path":"f.rs","old_string":"zzz","new_string":"x"}), + &c + ) + .await + .is_error + ); + let ok = Edit.call(json!({"path":"f.rs","old_string":"fn a() {}\nfn b","new_string":"fn c() {}\nfn b"}), &c).await; + assert!(!ok.is_error, "{}", ok.content); + assert!(ok.content.contains("-fn a") && ok.content.contains("+fn c")); + assert_eq!( + std::fs::read_to_string(&p).unwrap(), + "fn a() {}\r\nfn c() {}\r\nfn b() {}\r\n" + ); + // external change invalidates + std::thread::sleep(Duration::from_millis(20)); + std::fs::write(&p, "changed\n").unwrap(); + assert!( + Edit.call( + json!({"path":"f.rs","old_string":"changed","new_string":"x"}), + &c + ) + .await + .is_error + ); + Read.call(json!({"path":"f.rs"}), &c).await; + assert!(!Edit.call(json!({"path":"f.rs","old_string":"changed","new_string":"x","replace_all":true}), &c).await.is_error); + } + + #[tokio::test] + async fn bash_output_exit_timeout() { + let d = tempfile::tempdir().unwrap(); + let c = cx(d.path()); + let r = Bash + .call(json!({"command":"echo out; echo err >&2; pwd"}), &c) + .await; + assert!(!r.is_error && r.content.contains("out") && r.content.contains("err")); + assert!( + r.content + .contains(d.path().file_name().unwrap().to_str().unwrap()) + ); + let r = Bash.call(json!({"command":"exit 3"}), &c).await; + assert!(r.is_error && r.content.contains("[exit 3]")); + let t = Instant::now(); + let r = Bash + .call(json!({"command":"sleep 30 & sleep 30","timeout":1}), &c) + .await; + assert!( + r.is_error && r.content.contains("timed out") && t.elapsed() < Duration::from_secs(5) + ); + let r = Bash + .call(json!({"command":"yes | head -c 200000"}), &c) + .await; + assert!(r.content.contains("[truncated") && r.content.len() < MAX_BYTES + 300); } } diff --git a/tests/e2e.sh b/tests/e2e.sh new file mode 100755 index 0000000..e050ec9 --- /dev/null +++ b/tests/e2e.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# End-to-end: hx -p against a scripted fake Anthropic API. No network, no real credentials. +set -eu +root=$(cd "$(dirname "$0")/.." && pwd) +tmp=$(mktemp -d) +trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT +port=$((20000 + $$ % 20000)) +python3 "$root/tests/fake_anthropic.py" $port & srv=$! +mkdir -p "$tmp/home/.hx" "$tmp/repo" +echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json" +sleep 0.5 +cd "$tmp/repo" +HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port" "$root/target/debug/hx" -p "make hello.txt" > "$tmp/out" 2> "$tmp/err" +grep -q "Done: file says hi from hx." "$tmp/out" +[ "$(cat hello.txt)" = "hi from hx" ] +log=$(curl -s "http://127.0.0.1:$port/") +echo "$log" | grep -q '"auth": "Bearer fake-token"' +echo "$log" | grep -q 'oauth-2025-04-20' +echo "$log" | grep -q 'hi from hx' # bash tool result sent back to the model +ls "$tmp/home/.hx/sessions/"*/*.jsonl > /dev/null +echo "e2e ok" diff --git a/tests/fake_anthropic.py b/tests/fake_anthropic.py new file mode 100644 index 0000000..6a1bd57 --- /dev/null +++ b/tests/fake_anthropic.py @@ -0,0 +1,52 @@ +"""Scripted fake of the Anthropic SSE API for end-to-end tests of `hx -p`. + +Turn 1: tool_use write hello.txt. Turn 2: tool_use bash cat. Turn 3: final text. +Usage: python3 tests/fake_anthropic.py PORT +""" +import http.server, json, sys + +TURNS = [ + [("tool_use", {"id": "t1", "name": "Write", "input": {"path": "hello.txt", "content": "hi from hx\n"}})], + [("tool_use", {"id": "t2", "name": "Bash", "input": {"command": "cat hello.txt"}})], + [("text", "Done: file says hi from hx.")], +] +LOG = [] + + +def sse(ev, d): + return f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() + + +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers["content-length"]))) + LOG.append({"auth": self.headers.get("authorization"), "beta": self.headers.get("anthropic-beta"), "body": body}) + turn = TURNS[min(len(LOG) - 1, len(TURNS) - 1)] + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.end_headers() + w = self.wfile.write + w(sse("message_start", {"message": {"usage": {"input_tokens": 5, "output_tokens": 1}}})) + stop = "end_turn" + for i, (kind, v) in enumerate(turn): + if kind == "text": + w(sse("content_block_start", {"index": i, "content_block": {"type": "text", "text": ""}})) + w(sse("content_block_delta", {"index": i, "delta": {"type": "text_delta", "text": v}})) + else: + stop = "tool_use" + w(sse("content_block_start", {"index": i, "content_block": {"type": "tool_use", "id": v["id"], "name": v["name"], "input": {}}})) + w(sse("content_block_delta", {"index": i, "delta": {"type": "input_json_delta", "partial_json": json.dumps(v["input"])}})) + w(sse("content_block_stop", {"index": i})) + w(sse("message_delta", {"delta": {"stop_reason": stop}, "usage": {"output_tokens": 3}})) + w(sse("message_stop", {})) + + def do_GET(self): + self.send_response(200) + self.end_headers() + self.wfile.write(json.dumps(LOG).encode()) + + +http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()