- 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
@@ -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)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user