//! `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 `.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, 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>, pub max_turns: u32, sem: Arc, 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>, pub status: Mutex, pub calls: AtomicUsize, pub usage: Mutex, /// messages from the user, delivered at the child's next turn end inbox: Mutex>, /// part of `usage` already added to `State::sub_usage` rolled: Mutex, } 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 { (*self.ended.lock().unwrap_or_else(|e| e.into_inner())).map(|t| t.elapsed()) } } pub struct Sub { pub sh: Arc, agent: tokio::sync::Mutex, abort: crate::agent::AbortHandle, state: Arc, sem: Arc, } /// Every child of this session, oldest first, plus where their events go. #[derive(Default)] pub struct Subs { list: Mutex>>, /// (child id, event) for the UI; set by interactive frontends pub events: OnceLock>, watching: std::sync::atomic::AtomicBool, } const KEEP: usize = 20; impl Subs { pub fn list(&self) -> Vec> { self.list.lock().unwrap_or_else(|e| e.into_inner()).clone() } pub fn get(&self, id: usize) -> Option> { 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) { 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) { 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, Option>); #[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, 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 { 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. 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 every prompt self-contained. You are blocked until it answers, so a single task you then wait on only pays off when the search would put >10k tokens in your context; otherwise do it yourself. Prefer splitting work into 2+ independent subtasks: pass `prompts` (array) or several task calls in one turn, they run in parallel. Not for small lookups.".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, } } } 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>, Mutex>); #[async_trait] impl Provider for Script { async fn stream( &self, req: Request, ) -> hx_ai::Result>> { 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