Files
hx/crates/hx-tools/src/lib.rs
T

725 lines
26 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Built-in tools: read, write, edit, bash.
pub mod codemode;
pub mod skill;
pub mod web;
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 = 600;
const MAX_BYTES: usize = 20_000;
/// bash keeps this much of the start (command echo, first errors) and the rest from the end.
const HEAD_BYTES: usize = 4_000;
pub(crate) 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.
/// First `head` bytes + last `max - head` bytes, char-boundary safe. Returns (text, cut bytes).
fn head_tail(s: &str, max: usize, head: usize) -> (String, usize) {
if s.len() <= max {
return (s.to_string(), 0);
}
let mut h = head;
while !s.is_char_boundary(h) {
h -= 1;
}
let t = tail(s, max - head);
let cut = s.len() - h - t.len();
(format!("{}\n[... {cut} bytes cut ...]\n{t}", &s[..h]), cut)
}
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)
.add(AskUser)
.add(ExitPlan)
.add(MemoryWrite)
.add(MemoryForget)
.add(skill::Skill);
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());
if let Err(e) = hx_core::sandbox::guard_read(&p) {
return ToolResult::err(e);
}
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());
if let Err(e) = hx_core::sandbox::guard_write(&p) {
return ToolResult::err(e);
}
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()));
}
let old = tokio::fs::read_to_string(&p).await.ok();
match tokio::fs::write(&p, c).await {
Ok(()) => {
cx.state.mark_seen(&p);
cx.state.log_edit(&p, old, c);
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());
if let Err(e) = hx_core::sandbox::guard_write(&p) {
return ToolResult::err(e);
}
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);
cx.state.log_edit(&p, Some(src.clone()), &out);
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 AskUser;
#[async_trait]
impl Tool for AskUser {
fn spec(&self) -> ToolSpec {
spec(
"ask_user",
"Ask the user to pick between options (they may also type their own answer). Only when a decision blocks you and cannot be inferred; otherwise pick a default and say so.",
json!({"type":"object","properties":{
"question":{"type":"string"},
"options":{"type":"array","maxItems":6,"items":{"type":"object","properties":{
"label":{"type":"string"},"description":{"type":"string"}},"required":["label"]}},
"multi":{"type":"boolean","description":"allow several options"}},
"required":["question"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let options = a["options"]
.as_array()
.into_iter()
.flatten()
.filter_map(|o| {
Some((
o["label"].as_str()?.to_string(),
o["description"].as_str().unwrap_or_default().to_string(),
))
})
.take(6)
.collect();
let q = hx_core::Question {
text: a["question"].as_str().unwrap_or_default().into(),
options,
multi: a["multi"].as_bool().unwrap_or(false),
other: true,
plan: None,
};
match cx.state.choose(q).await {
Err(e) => ToolResult::err(e),
Ok(None) => {
ToolResult::ok("user dismissed the question; proceed with your best default")
}
Ok(Some(v)) => ToolResult::ok(v.join(", ")),
}
}
}
/// Plan mode's end: the TUI shows the plan in full, the user approves or sends feedback.
pub struct ExitPlan;
#[async_trait]
impl Tool for ExitPlan {
fn spec(&self) -> ToolSpec {
spec(
"exit_plan",
"Only in plan mode: present your finished plan (markdown, complete) for approval. Plan mode ends once the user approves.",
json!({"type":"object","properties":{"plan":{"type":"string"}},"required":["plan"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let on = || cx.state.allow.lock().unwrap_or_else(|e| e.into_inner());
if !on().plan_on() {
return ToolResult::ok("not in plan mode; just do the work");
}
let q = hx_core::Question {
text: "Implement this plan?".into(),
options: vec![
("Implement".into(), "leave plan mode and start".into()),
(
"Keep planning".into(),
"stay read-only; type feedback below".into(),
),
],
multi: false,
other: true,
plan: a["plan"].as_str().map(Into::into),
};
match cx.state.choose(q).await {
Ok(Some(v)) if v.first().is_some_and(|s| s == "Implement") => {
on().set_plan(false);
ToolResult::ok("plan approved; plan mode is off, implement it now")
}
Ok(Some(v)) if v.first().is_some_and(|s| s != "Keep planning") => {
ToolResult::ok(format!(
"plan not approved, user feedback: {}. Revise and call exit_plan again.",
v.join(", ")
))
}
// no frontend (print mode) or dismissed: stay in plan mode
_ => ToolResult::ok("plan not approved; keep planning and ask what to change"),
}
}
}
/// Bytes of running bash output kept for the live view.
const LIVE_TAIL: usize = 2048;
pub struct Bash;
#[async_trait]
impl Tool for Bash {
fn spec(&self) -> ToolSpec {
spec(
"bash",
"Run a shell command in the working directory. Read-only commands (ls cat head tail rg fd find grep wc jq sort, git status/log/diff/show, piped together) run at once; everything else, e.g. node, python, sed, cargo, asks the user first. To inspect files prefer read/rg/fd. stdout and stderr are merged. Long output keeps the start and the end; the middle is cut and the full output saved to a file.",
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 = hx_core::sandbox::command("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 mut child = match c.spawn() {
Ok(c) => c,
Err(e) => return ToolResult::err(format!("spawn: {e}")),
};
let pid = child.id();
// read output as it comes so the UI can show the last lines live (state.live)
let mut so = child.stdout.take().expect("piped");
let live = &cx.state.live;
let run = async {
use tokio::io::AsyncReadExt;
let mut out = vec![];
let mut chunk = [0u8; 8192];
loop {
match so.read(&mut chunk).await {
Ok(0) | Err(_) => break,
Ok(n) => {
out.extend_from_slice(&chunk[..n]);
let start = out.len().saturating_sub(LIVE_TAIL);
live.lock().unwrap_or_else(|e| e.into_inner()).insert(
cmd.to_string(),
String::from_utf8_lossy(&out[start..]).into(),
);
}
}
}
child.wait().await.map(|st| (out, st))
};
let res = tokio::time::timeout(Duration::from_secs(secs), run).await;
live.lock().unwrap_or_else(|e| e.into_inner()).remove(cmd);
let (out, code) = match res {
Ok(Ok((o, st))) => (o, st.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, cut) = head_tail(&s, MAX_BYTES, HEAD_BYTES);
if cut > 0 {
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}",
cut,
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())
)),
}
}
}
fn memory_dir(a: &Value, cx: &ToolCtx) -> PathBuf {
hx_core::memory::dir(
a["scope"].as_str() == Some("project"),
&hx_core::context::hx_home(),
&cx.cwd,
)
}
pub struct MemoryWrite;
#[async_trait]
impl Tool for MemoryWrite {
fn spec(&self) -> ToolSpec {
spec(
"memory_write",
"Save or replace a persistent memory topic (durable facts only, not task progress). `hook` is the one-line index entry shown in every future session; `body` is the full text, read on demand. Appears in the prompt from the next session.",
json!({"type":"object","properties":{
"scope":{"type":"string","enum":["global","project"],"description":"global: about the user/environment; project: this repo"},
"slug":{"type":"string","description":"a-z 0-9 - _"},
"hook":{"type":"string","description":"one line, max 100 chars"},
"body":{"type":"string"}},
"required":["scope","slug","hook","body"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let g = |k: &str| a[k].as_str().unwrap_or_default();
match hx_core::memory::write(&memory_dir(&a, cx), g("slug"), g("hook"), g("body")) {
Ok(()) => ToolResult::ok(format!(
"saved {} memory '{}' – {}",
a["scope"].as_str().unwrap_or("global"),
g("slug"),
g("hook")
)),
Err(e) => ToolResult::err(e),
}
}
}
pub struct MemoryForget;
#[async_trait]
impl Tool for MemoryForget {
fn spec(&self) -> ToolSpec {
spec(
"memory_forget",
"Delete a memory topic and its index line.",
json!({"type":"object","properties":{
"scope":{"type":"string","enum":["global","project"]},
"slug":{"type":"string"}},
"required":["scope","slug"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let slug = a["slug"].as_str().unwrap_or_default();
match hx_core::memory::forget(&memory_dir(&a, cx), slug) {
Ok(()) => ToolResult::ok(format!("forgot memory '{slug}'")),
Err(e) => ToolResult::err(e),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[tokio::test]
async fn bash_streams_live_tail() {
let d = tempfile::tempdir().unwrap();
let c = cx(d.path());
let cmd = "echo one; sleep 0.4; echo two";
let st = c.state.clone();
let peek = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
st.live.lock().unwrap().get(cmd).cloned()
});
let r = Bash.call(json!({"command": cmd}), &c).await;
assert_eq!(peek.await.unwrap().as_deref(), Some("one\n"));
assert_eq!(r.content, "one\ntwo\n");
assert!(c.state.live.lock().unwrap().is_empty(), "cleared when done");
}
fn cx(d: &Path) -> ToolCtx {
ToolCtx {
cwd: d.into(),
state: Default::default(),
}
}
#[tokio::test]
async fn memory_tools_write_and_forget() {
let t = tempfile::tempdir().unwrap();
let c = cx(t.path());
let a = json!({"scope":"project","slug":"x","hook":"h","body":"b"});
assert!(!MemoryWrite.call(a, &c).await.is_error);
assert!(t.path().join(".hx/memory/topics/x.md").exists());
let f = json!({"scope":"project","slug":"x"});
assert!(!MemoryForget.call(f.clone(), &c).await.is_error);
assert!(MemoryForget.call(f, &c).await.is_error);
}
#[tokio::test]
async fn ask_user_paths() {
let d = tempfile::tempdir().unwrap();
let c = cx(d.path());
let a =
json!({"question":"db?","options":[{"label":"pg","description":"x"},{"label":"lite"}]});
let r = AskUser.call(a.clone(), &c).await;
assert!(r.is_error && r.content.contains("no interactive user"));
let _ = c.state.choose.set(std::sync::Arc::new(|q| {
Box::pin(async move {
assert!(!q.multi && q.other);
if q.text == "db?" {
Some(vec!["pg".into(), "me".into()])
} else {
None
}
})
}));
assert_eq!(AskUser.call(a, &c).await, ToolResult::ok("pg, me"));
let r = AskUser.call(json!({"question":"other"}), &c).await;
assert!(!r.is_error && r.content.contains("dismissed"));
}
#[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="));
}
#[test]
fn head_tail_keeps_both_ends() {
let s = format!("HEAD{}TAIL", "é".repeat(5000));
let (o, cut) = head_tail(&s, 1000, 200);
assert!(o.starts_with("HEAD") && o.ends_with("TAIL") && cut > 0 && o.len() < 1100);
assert_eq!(head_tail("short", 1000, 200), ("short".to_string(), 0));
}
#[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 + 400);
}
}