//! `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/`. 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, 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: 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>, 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