Files
hx/crates/hx-core/src/subagent.rs
T
johannesandClaude Sonnet 5.5 32ae759703 claude_cli: add usage_total for the whole run (#190)
Done.usage stays the last request (context size); usage_total is the sum
over all requests. Exposed in the NDJSON done line, RPC replies and hx stats.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 12:24:11 +01:00

745 lines
26 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/`.
//! Every child is also kept in [`Subs`] after it ends, so the UI can show it, queue a message
//! for it while it runs, or continue it afterwards.
use crate::agent::{Agent, Error};
use crate::hook::{Event, Hook, HookAction};
use crate::session::Session;
use crate::tool::{Registry, Tool, ToolCtx, ToolResult};
use async_trait::async_trait;
use hx_ai::{Message, Provider, StreamEvent, ToolSpec, Usage};
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Instant;
use tokio::sync::{Semaphore, mpsc};
/// 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: Arc<Semaphore>,
n: AtomicUsize,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Status {
Running,
Done,
Failed(String),
Aborted,
}
/// What the UI reads while a child runs (everything behind std mutexes: readable from draw code).
pub struct Shared {
pub id: usize,
pub kind: &'static str,
pub model: String,
/// the first prompt
pub prompt: String,
pub started: Instant,
pub ended: Mutex<Option<Instant>>,
pub status: Mutex<Status>,
pub calls: AtomicUsize,
pub usage: Mutex<Usage>,
/// messages from the user, delivered at the child's next turn end
inbox: Mutex<Vec<String>>,
/// part of `usage` already added to `State::sub_usage`
rolled: Mutex<Usage>,
}
impl Shared {
pub fn status(&self) -> Status {
self.status
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
/// Run time so far, or total when finished.
pub fn elapsed(&self) -> std::time::Duration {
let end = *self.ended.lock().unwrap_or_else(|e| e.into_inner());
end.unwrap_or_else(Instant::now) - self.started
}
/// Time since the child finished; `None` while running.
pub fn since_end(&self) -> Option<std::time::Duration> {
(*self.ended.lock().unwrap_or_else(|e| e.into_inner())).map(|t| t.elapsed())
}
}
pub struct Sub {
pub sh: Arc<Shared>,
agent: tokio::sync::Mutex<Agent>,
abort: crate::agent::AbortHandle,
state: Arc<crate::State>,
sem: Arc<Semaphore>,
}
/// Every child of this session, oldest first, plus where their events go.
#[derive(Default)]
pub struct Subs {
list: Mutex<Vec<Arc<Sub>>>,
/// (child id, event) for the UI; set by interactive frontends
pub events: OnceLock<mpsc::UnboundedSender<(usize, Event)>>,
watching: std::sync::atomic::AtomicBool,
}
const KEEP: usize = 20;
impl Subs {
pub fn list(&self) -> Vec<Arc<Sub>> {
self.list.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
pub fn get(&self, id: usize) -> Option<Arc<Sub>> {
self.list().into_iter().find(|s| s.sh.id == id)
}
/// Abort every running child (also those continued in the background after their task ended).
pub fn abort_all(&self) {
for s in self.list() {
if s.sh.status() == Status::Running {
s.abort();
}
}
}
pub fn any_running(&self) -> bool {
self.list().iter().any(|s| s.sh.status() == Status::Running)
}
/// Once per session: every parent abort reaches all running children. The parent flag resets
/// after each run, so the loop re-arms.
fn watch(&self, state: &Arc<crate::State>) {
let Some(mut rx) = state.abort.get().cloned() else {
return;
};
if self.watching.swap(true, Ordering::Relaxed) {
return;
}
let st = state.clone();
tokio::spawn(async move {
while rx.wait_for(|a| *a).await.is_ok() {
st.subs.abort_all();
if rx.wait_for(|a| !*a).await.is_err() {
break;
}
}
});
}
fn add(&self, s: Arc<Sub>) {
let mut l = self.list.lock().unwrap_or_else(|e| e.into_inner());
l.push(s);
// drop the oldest finished children beyond KEEP (their session files stay)
while l.len() > KEEP {
match l.iter().position(|s| s.sh.status() != Status::Running) {
Some(i) => {
l.remove(i);
}
None => break,
}
}
}
}
fn diff(a: &Usage, b: &Usage) -> Usage {
Usage {
input_tokens: a.input_tokens.saturating_sub(b.input_tokens),
output_tokens: a.output_tokens.saturating_sub(b.output_tokens),
cache_read_tokens: a.cache_read_tokens.saturating_sub(b.cache_read_tokens),
cache_write_tokens: a.cache_write_tokens.saturating_sub(b.cache_write_tokens),
}
}
/// On the child's bus: counts, forwards events to the UI, delivers queued user messages.
struct Live(Arc<Shared>, Option<mpsc::UnboundedSender<(usize, Event)>>);
#[async_trait]
impl Hook for Live {
async fn on(&self, ev: &Event) -> HookAction {
match ev {
Event::ToolCall { .. } => {
self.0.calls.fetch_add(1, Ordering::Relaxed);
}
Event::Stream(StreamEvent::Done { usage, .. }) => {
self.0
.usage
.lock()
.unwrap_or_else(|e| e.into_inner())
.add(usage);
}
_ => {}
}
if let Some(tx) = &self.1 {
let _ = tx.send((self.0.id, ev.clone()));
}
if matches!(ev, Event::TurnEnd | Event::AgentEnd) {
let m = std::mem::take(&mut *self.0.inbox.lock().unwrap_or_else(|e| e.into_inner()));
if !m.is_empty() {
return HookAction::Inject(m.join("\n\n"));
}
}
HookAction::Continue
}
}
impl Sub {
pub fn abort(&self) {
self.abort.abort();
}
/// A message for this child: queued for its next turn end while it runs (like steering the
/// main agent); otherwise it continues the child's conversation in the background.
pub fn prompt(self: &Arc<Self>, text: String) {
{
let mut st = self.sh.status.lock().unwrap_or_else(|e| e.into_inner());
if *st == Status::Running {
self.sh
.inbox
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(text);
return;
}
*st = Status::Running;
*self.sh.ended.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
let me = self.clone();
tokio::spawn(async move {
let _permit = me.sem.acquire().await;
let _ = me.drive(text).await;
});
}
/// Run until done, then once more per message that arrived meanwhile; sets the final status.
async fn drive(&self, mut p: String) -> Result<Message, Error> {
let mut a = self.agent.lock().await;
loop {
let r = a.run(p).await;
let cur = a.usage().clone();
let delta = {
let mut rolled = self.sh.rolled.lock().unwrap_or_else(|e| e.into_inner());
let d = diff(&cur, &rolled);
*rolled = cur;
d
};
self.state
.sub_usage
.lock()
.unwrap_or_else(|e| e.into_inner())
.add(&delta);
let mut st = self.sh.status.lock().unwrap_or_else(|e| e.into_inner());
let pending =
std::mem::take(&mut *self.sh.inbox.lock().unwrap_or_else(|e| e.into_inner()));
if r.is_ok() && !pending.is_empty() {
p = pending.join("\n\n");
continue;
}
*st = match &r {
Ok(_) => Status::Done,
Err(Error::Aborted) => Status::Aborted,
Err(e) => Status::Failed(e.to_string()),
};
*self.sh.ended.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now());
return r;
}
}
}
/// 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", "skill"];
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, and run the narrowest relevant check (build, test, lint) after editing. 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: Arc::new(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. The user is asked to approve every call: use it only when the user asked for subagents or parallel work, or when a search would clearly put >10k tokens in your context. Do ordinary discovery (read, grep, lsp, bash) yourself in this session. kind=explore (default): read-only research on a cheaper model. kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers. For 2+ independent subtasks pass `prompts` (array); they run in parallel.".into(),
input_schema: json!({"type":"object","properties":{
"prompt":{"type":"string"},
"prompts":{"type":"array","items":{"type":"string"},"description":"several independent subtasks: one subagent each, run in parallel, answers returned numbered"},
"kind":{"type":"string","enum":["explore","general"]}},
}),
}
}
#[async_trait]
impl Tool for Task {
fn spec(&self) -> ToolSpec {
spec()
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let Some(ps) = a["prompts"].as_array() else {
return self
.run(
a["prompt"].as_str().unwrap_or_default(),
a["kind"].as_str(),
cx,
)
.await;
};
// fan-out: one child per prompt, concurrent (the semaphore caps how many run at once)
let kind = a["kind"].as_str();
let rs = futures::future::join_all(
ps.iter()
.map(|p| self.run(p.as_str().unwrap_or_default(), kind, cx)),
)
.await;
let mut out = String::new();
let mut err = !rs.is_empty();
for (i, r) in rs.into_iter().enumerate() {
err &= r.is_error;
out.push_str(&format!("## {}\n{}\n\n", i + 1, r.content));
}
ToolResult {
content: out,
is_error: err,
images: vec![],
}
}
}
impl Task {
async fn run(&self, prompt: &str, kind: Option<&str>, cx: &ToolCtx) -> ToolResult {
let (kind, role) = match kind {
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 id = self.n.fetch_add(1, Ordering::Relaxed) + 1;
let path = self.dir.join(format!("{id:03}-{kind}.jsonl"));
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);
let sh = Arc::new(Shared {
id,
kind,
model: role.model.clone(),
prompt: prompt.to_string(),
started: Instant::now(),
ended: Mutex::new(None),
status: Mutex::new(Status::Running),
calls: AtomicUsize::new(0),
usage: Mutex::default(),
inbox: Mutex::default(),
rolled: Mutex::default(),
});
child
.bus
.add(Live(sh.clone(), cx.state.subs.events.get().cloned()));
if kind == "general" {
for h in &self.hooks {
child.bus.add_arc(h.clone());
}
}
let sub = Arc::new(Sub {
sh: sh.clone(),
agent: tokio::sync::Mutex::new(child),
abort: handle,
state: cx.state.clone(),
sem: self.sem.clone(),
});
cx.state.subs.add(sub.clone());
cx.state.subs.watch(&cx.state);
// waiting for a slot may have outlasted an abort
if aborted() {
sub.abort();
}
let r = sub.drive(prompt.to_string()).await;
let u = sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone();
let tok = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens;
let stats = format!(
"[task {kind} · {} tool calls · {}k tok · {}s]",
sh.calls.load(Ordering::Relaxed),
tok / 1000,
sh.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::{ContentBlock, Request, Role as R, StopReason};
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,
usage_total: None,
})])
.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 prompts_fan_out_into_numbered_answers() {
let d = tempfile::tempdir().unwrap();
let p = Arc::new(Script(
Mutex::new(vec![text("one"), text("two")]),
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!({"prompts":["a","b"]}), &cx).await;
assert!(!r.is_error, "{r:?}");
assert!(
r.content.starts_with("## 1\n") && r.content.contains("## 2\n"),
"{}",
r.content
);
assert_eq!(cx.state.subs.list().len(), 2);
}
#[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:?}");
}
#[tokio::test]
async fn registry_keeps_child_and_message_during_run_is_delivered_at_turn_end() {
let d = tempfile::tempdir().unwrap();
let p = Arc::new(Script(
Mutex::new(vec![call("read", json!({})), text("a"), text("b")]),
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 (tx, mut rx) = mpsc::unbounded_channel();
let _ = cx.state.subs.events.set(tx);
// queue a message while the child runs: the first Done event is a good "while running" point
let st = cx.state.clone();
let q = tokio::spawn(async move {
while let Some((id, ev)) = rx.recv().await {
if matches!(ev, Event::TurnStart) {
st.subs.get(id).unwrap().prompt("also check b".into());
return;
}
}
});
let r = t.call(json!({"prompt":"look"}), &cx).await;
q.await.unwrap();
assert!(!r.is_error, "{r:?}");
let subs = cx.state.subs.list();
assert_eq!(subs.len(), 1);
assert_eq!(subs[0].sh.status(), Status::Done);
assert_eq!(subs[0].sh.calls.load(Ordering::Relaxed), 1);
// the message reached the child's next request (after its tool round)
let reqs = p.1.lock().unwrap();
let last = &reqs.last().unwrap().messages;
assert!(
last.iter().any(|m| m.text().contains("also check b")),
"{last:?}"
);
}
#[tokio::test]
async fn prompting_a_finished_child_continues_it_and_rolls_up_usage() {
let d = tempfile::tempdir().unwrap();
let p = Arc::new(Script(
Mutex::new(vec![text("first"), text("second")]),
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(),
};
t.call(json!({"prompt":"one"}), &cx).await;
let sub = cx.state.subs.get(1).unwrap();
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 1000);
sub.prompt("two".into());
assert_eq!(sub.sh.status(), Status::Running);
for _ in 0..100 {
if sub.sh.status() == Status::Done {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert_eq!(sub.sh.status(), Status::Done);
// same conversation: second request carries the first exchange; only the delta was rolled up
let reqs = p.1.lock().unwrap();
assert_eq!(reqs[1].messages.len(), 3);
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 2000);
}
#[tokio::test]
async fn parent_abort_reaches_background_child() {
let d = tempfile::tempdir().unwrap();
let p = Arc::new(Script(
Mutex::new(vec![text("a"), call("read", json!({}))]),
Default::default(),
));
let t = Task::new(
role(&p, "cheap"),
role(&p, "main"),
d.path().join("s.sub"),
2,
);
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();
t.call(json!({"prompt":"one"}), &cx).await;
let sub = cx.state.subs.get(1).unwrap();
sub.prompt("two".into());
assert!(cx.state.subs.any_running());
h.abort();
for _ in 0..100 {
if sub.sh.status() == Status::Aborted {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert_eq!(sub.sh.status(), Status::Aborted);
}
}