Files
hx/crates/hx-core/src/subagent.rs
T
hermes 359a5058d7
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
Subagents: task tool (explore on cheap model, general), child sessions, usage roll-up, stats
2026-10-02 11:57:59 +00:00

348 lines
12 KiB
Rust

//! `task` tool: run a subagent with a fresh context; only its final answer comes back.
//!
//! `explore` is read-only research on a cheap model, `general` has the parent's tools. Children
//! share the parent's `State` (read-guard, usage counter, abort) and log to `<session>.sub/`.
use crate::agent::Agent;
use crate::hook::Hook;
use crate::session::Session;
use crate::tool::{Registry, Tool, ToolCtx, ToolResult};
use async_trait::async_trait;
use hx_ai::{ContentBlock, Provider, ToolSpec};
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
use tokio::sync::Semaphore;
/// Everything needed to start one kind of child.
pub struct Role {
pub provider: Arc<dyn Provider>,
pub model: String,
pub tools: Registry,
pub system: String,
}
pub struct Task {
pub explore: Role,
pub general: Role,
/// where child sessions are written
pub dir: PathBuf,
/// hooks (lens) the `general` child runs with
pub hooks: Vec<Arc<dyn Hook>>,
pub max_turns: u32,
sem: Semaphore,
n: AtomicUsize,
}
/// Tools of a read-only child. ponytail: `bash` can still write; the prompt forbids it. Drop
/// `bash` for a search/grep tool if models ignore that.
pub const EXPLORE_TOOLS: &[&str] = &["read", "lsp", "bash"];
pub const EXPLORE_PROMPT: &str = "You are a research subagent of hx. Answer the task by reading code; do not modify anything (no writes, no redirects, no installs). Your final message is the only thing the caller sees: give the answer with file:line references, short, no preamble.";
pub const GENERAL_PROMPT: &str = "You are a subagent of hx working in the user's repository. Do the task fully with the tools; read files before editing them. Your final message is the only thing the caller sees: say what you changed or found, short, with file paths.";
const MAX_RESULT: usize = 8_000;
impl Task {
pub fn new(explore: Role, general: Role, dir: PathBuf, parallel: usize) -> Self {
Self {
explore,
general,
dir: dir.clone(),
hooks: vec![],
max_turns: 40,
sem: Semaphore::new(parallel.max(1)),
// continue numbering when the session is resumed
n: AtomicUsize::new(std::fs::read_dir(&dir).map_or(0, |d| d.count())),
}
}
}
/// Schema of the `task` tool (also used by `hx prefix`).
pub fn spec() -> ToolSpec {
ToolSpec {
name: "task".into(),
description: "Run a subagent in a fresh context; you get back only its final answer. kind=explore (default): read-only research on a cheaper model; use it for searching/reading that would fill your context (many files or >10k tokens). kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make the prompt self-contained. Several task calls in one turn run in parallel. Not for small lookups.".into(),
input_schema: json!({"type":"object","properties":{
"prompt":{"type":"string"},
"kind":{"type":"string","enum":["explore","general"]}},
"required":["prompt"]}),
}
}
#[async_trait]
impl Tool for Task {
fn spec(&self) -> ToolSpec {
spec()
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let prompt = a["prompt"].as_str().unwrap_or_default();
let (kind, role) = match a["kind"].as_str() {
None | Some("explore") => ("explore", &self.explore),
Some("general") => ("general", &self.general),
Some(k) => return ToolResult::err(format!("unknown kind `{k}` (explore | general)")),
};
let aborted = || cx.state.abort.get().is_some_and(|r| *r.borrow());
if aborted() {
return ToolResult::err("aborted");
}
let Ok(_permit) = self.sem.acquire().await else {
return ToolResult::err("subagents unavailable");
};
let path = self.dir.join(format!(
"{:03}-{kind}.jsonl",
self.n.fetch_add(1, Ordering::Relaxed) + 1
));
let session = match Session::open(&path) {
Ok(s) => s,
Err(e) => return ToolResult::err(format!("subagent session: {e}")),
};
let (mut child, handle) = Agent::new(
role.provider.clone(),
role.tools.clone(),
session,
ToolCtx {
cwd: cx.cwd.clone(),
state: cx.state.clone(),
},
);
child.set_model(role.model.clone());
child.set_system(role.system.clone());
child.set_max_turns(self.max_turns);
if kind == "general" {
for h in &self.hooks {
child.bus.add_arc(h.clone());
}
}
// parent abort stops the child
let bridge = cx.state.abort.get().cloned().map(|mut rx| {
tokio::spawn(async move {
if rx.wait_for(|a| *a).await.is_ok() {
handle.abort();
}
})
});
let t0 = Instant::now();
// waiting for a slot may have outlasted an abort
let r = if aborted() {
Err(crate::agent::Error::Aborted)
} else {
child.run(prompt).await
};
if let Some(b) = bridge {
b.abort();
}
let u = child.usage().clone();
cx.state
.sub_usage
.lock()
.unwrap_or_else(|e| e.into_inner())
.add(&u);
let calls: usize = child
.session()
.messages()
.iter()
.flat_map(|m| &m.content)
.filter(|b| matches!(b, ContentBlock::ToolUse { .. }))
.count();
let tok = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens;
let stats = format!(
"[task {kind} · {calls} tool calls · {}k tok · {}s]",
tok / 1000,
t0.elapsed().as_secs()
);
match r {
Ok(m) => {
let mut t = m.text();
if t.len() > MAX_RESULT {
let mut i = MAX_RESULT;
while !t.is_char_boundary(i) {
i -= 1;
}
t.truncate(i);
t.push_str("\n[... answer cut ...]");
}
ToolResult::ok(format!("{t}\n{stats}"))
}
Err(e) => ToolResult::err(format!("subagent failed: {e}\n{stats}")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::{StreamExt, stream::BoxStream};
use hx_ai::{Message, Request, Role as R, StopReason, StreamEvent, Usage};
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 usage = Usage {
input_tokens: 1000,
output_tokens: 10,
..Default::default()
};
Ok(futures::stream::iter(vec![Ok(StreamEvent::Done {
message: m,
stop,
usage,
})])
.boxed())
}
}
fn text(t: &str) -> Message {
Message {
role: R::Assistant,
content: vec![ContentBlock::Text { text: t.into() }],
}
}
fn call(name: &str, input: Value) -> Message {
Message {
role: R::Assistant,
content: vec![ContentBlock::ToolUse {
id: "t1".into(),
name: name.into(),
input,
}],
}
}
struct Echo;
#[async_trait]
impl Tool for Echo {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: "read".into(),
description: "".into(),
input_schema: json!({"type":"object"}),
}
}
async fn call(&self, _: Value, _: &ToolCtx) -> ToolResult {
ToolResult::ok("file body")
}
}
fn role(p: &Arc<Script>, model: &str) -> Role {
let mut tools = Registry::default();
tools.add(Echo);
Role {
provider: p.clone(),
model: model.into(),
tools,
system: "child".into(),
}
}
#[tokio::test]
async fn child_runs_returns_answer_and_usage() {
let d = tempfile::tempdir().unwrap();
let p = Arc::new(Script(
Mutex::new(vec![call("read", json!({})), text("found it")]),
Default::default(),
));
let t = Task::new(
role(&p, "cheap"),
role(&p, "main"),
d.path().join("s.sub"),
3,
);
let cx = ToolCtx {
cwd: d.path().into(),
state: Default::default(),
};
let r = t.call(json!({"prompt":"look"}), &cx).await;
assert!(!r.is_error, "{r:?}");
assert!(
r.content
.starts_with("found it\n[task explore · 1 tool calls · 2k tok"),
"{}",
r.content
);
let reqs = p.1.lock().unwrap();
assert_eq!(
(reqs[0].model.as_str(), reqs[0].system.as_str()),
("cheap", "child")
);
assert_eq!(reqs[0].messages[0].text(), "look");
// usage reaches the parent through State; child log is on disk
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 2000);
assert!(d.path().join("s.sub/001-explore.jsonl").exists());
}
#[tokio::test]
async fn kind_picks_role_unknown_errors_long_answer_cut() {
let d = tempfile::tempdir().unwrap();
let p = Arc::new(Script(
Mutex::new(vec![text(&"x".repeat(20_000))]),
Default::default(),
));
let t = Task::new(
role(&p, "cheap"),
role(&p, "main"),
d.path().join("s.sub"),
1,
);
let cx = ToolCtx {
cwd: d.path().into(),
state: Default::default(),
};
assert!(
t.call(json!({"prompt":"a","kind":"nope"}), &cx)
.await
.is_error
);
let r = t.call(json!({"prompt":"a","kind":"general"}), &cx).await;
assert!(r.content.contains("[... answer cut ...]") && r.content.len() < 8_200);
assert_eq!(p.1.lock().unwrap()[0].model, "main");
assert!(d.path().join("s.sub/001-general.jsonl").exists());
}
#[tokio::test]
async fn parent_abort_stops_child() {
let d = tempfile::tempdir().unwrap();
// empty script: a second request would panic; abort must end the run first
let p = Arc::new(Script(
Mutex::new(vec![call("read", json!({}))]),
Default::default(),
));
let t = Task::new(
role(&p, "cheap"),
role(&p, "main"),
d.path().join("s.sub"),
1,
);
let (_parent, h) = Agent::new(
p.clone(),
Registry::default(),
Session::open(d.path().join("p.jsonl")).unwrap(),
ToolCtx {
cwd: d.path().into(),
state: Default::default(),
},
);
let cx = _parent.cx.clone();
h.abort();
let r = t.call(json!({"prompt":"a"}), &cx).await;
assert!(r.is_error && r.content.contains("aborted"), "{r:?}");
}
}