- hx-core: Tool trait + registry (schema validation, parallel calls), event bus with Block/Mutate/Inject hooks, agent loop (abort, max turns, AgentEnd inject), JSONL session tree (fork, resume, torn-line tolerant), AGENTS.md/CLAUDE.md hierarchy, skills index (bodies on demand) - hx-tools: read (ranges, binary, images, caps), write/edit (exact match, ambiguity, CRLF, diff, read-guard), bash (merged output, timeout kills process group, tail truncation to temp file) - hx-cli: -p runs full agent loop, --session / --continue, Ctrl-C abort, HX_BASE_URL override - tests/e2e.sh: scripted fake Anthropic server drives write -> bash -> answer Closes #6, closes #7, closes #8, closes #9, closes #10, closes #11, closes #12, closes #13, closes #14
This commit is contained in:
1 parent
da9d5d1ae0
commit
21d4d2bb3d
15 files changed
+1752
-52
No files matched your search
+441
-6
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user