M1: agent loop, tools, sessions, context, skills
ci / check (push) Canceled after 0s

- 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:
hermes committed 2026-09-30 09:36:16 +00:00
1 parent da9d5d1ae0
commit 21d4d2bb3d
15 files changed
+1752 -52

No files matched your search

+11
View File
@@ -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"] }
+381
View File
@@ -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<dyn Provider>,
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<bool>,
}
/// Cheap handle to cancel a running `Agent::run`.
#[derive(Clone)]
pub struct AbortHandle(Arc<watch::Sender<bool>>);
impl AbortHandle {
pub fn abort(&self) {
let _ = self.0.send(true);
}
}
impl Agent {
pub fn new(
provider: Arc<dyn Provider>,
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<String>) -> Result<Message, Error> {
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<Option<ContentBlock>> = 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<ContentBlock> = 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<Vec<Message>>, Mutex<Vec<Request>>);
#[async_trait]
impl Provider for Script {
async fn stream(
&self,
req: Request,
) -> hx_ai::Result<BoxStream<'static, hx_ai::Result<StreamEvent>>> {
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<ContentBlock>) -> 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)));
}
}
+151
View File
@@ -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,
}
/// `<dir>/<name>/SKILL.md` with `name:` / `description:` frontmatter. Project skills override global.
pub fn skills(home: &Path, cwd: &Path) -> Vec<Skill> {
let mut out: Vec<Skill> = 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"));
}
}
+134
View File
@@ -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<Arc<dyn Hook>>,
}
/// Aggregate outcome of dispatching one event to all hooks.
#[derive(Debug, Default, PartialEq)]
pub struct Outcome {
pub blocked: Option<String>,
pub args: Option<Value>,
pub inject: Vec<String>,
}
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());
}
}
+34 -10
View File
@@ -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<HashMap<PathBuf, Option<SystemTime>>>,
}
#[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)
}
}
+125
View File
@@ -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<u64>,
pub message: Message,
}
pub struct Session {
path: PathBuf,
entries: Vec<Entry>,
head: Option<u64>,
}
impl Session {
/// Open (or create) a session file; head = last entry.
pub fn open(path: impl AsRef<Path>) -> std::io::Result<Self> {
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::<Entry>(&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<u64> {
self.head
}
pub fn append(&mut self, message: Message) -> std::io::Result<u64> {
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<Message> {
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::<Vec<_>>();
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));
}
}
+174
View File
@@ -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<String>) -> Self {
Self {
content: s.into(),
is_error: false,
}
}
pub fn err(s: impl Into<String>) -> 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<crate::State>,
}
#[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<String, Arc<dyn Tool>>,
}
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<ToolSpec> {
self.tools.values().map(|t| t.spec()).collect()
}
pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
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<ToolResult> {
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::<Vec<_>>(),
["150", "10"]
);
}
}