From 359a5058d7128f8e673136659030b736348f2050 Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 2 Oct 2026 11:57:59 +0000 Subject: [PATCH] Subagents: task tool (explore on cheap model, general), child sessions, usage roll-up, stats --- README.md | 6 + crates/hx-ai/src/models.rs | 12 ++ crates/hx-cli/src/main.rs | 40 +++- crates/hx-core/src/agent.rs | 17 ++ crates/hx-core/src/hook.rs | 4 + crates/hx-core/src/lib.rs | 5 + crates/hx-core/src/stats.rs | 36 ++++ crates/hx-core/src/subagent.rs | 347 ++++++++++++++++++++++++++++++++ crates/hx-core/src/tool.rs | 4 + crates/hx-tui/src/lib.rs | 3 + crates/hx-tui/src/transcript.rs | 6 + tests/all.sh | 1 + tests/fake_anthropic.py | 4 +- tests/m8_e2e.sh | 42 ++++ 14 files changed, 525 insertions(+), 2 deletions(-) create mode 100644 crates/hx-core/src/subagent.rs create mode 100644 tests/m8_e2e.sh diff --git a/README.md b/README.md index c478895..9752e97 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ provider = "claude" # or "codex" # codex_model = "gpt-5.6-sol" # default: Codex's top-listed model # compact_at = 900000 # default: 90% of the model's context window max_tokens = 16384 +# explore_model = "claude-haiku-4-5" # model for read-only `task` subagents; default: cheapest tier of the provider # system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended [lsp] @@ -62,6 +63,10 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off # install = ["brew", "install", "zls"] # offered by the lsp tool when `zls` is missing ``` +## Subagents + +The model can call `task(prompt, kind)` to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `.sub/`; `hx stats` lists them and the footer token counts include them. A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens. + ## Skills Skills are `//SKILL.md` files with `name:` / `description:` frontmatter. Only the name and @@ -159,6 +164,7 @@ One JSON object per line on stdout. `type` is one of: | `tool_call` | `id`, `name`, `args` | | `tool_result` | `id`, `name`, `args`, `content`, `is_error` (blocked calls: `is_error: true`, content `blocked: `) | | `info` | `text` | +| `sub_usage` | `usage`: tokens spent by `task` subagents in the tools just run (already in the session total) | | `injected` | `texts`: hook reports added to the conversation at turn end (lens diagnostics, affected tests) | | `done` (last line) | `error` (null on success), `usage`, `session` | diff --git a/crates/hx-ai/src/models.rs b/crates/hx-ai/src/models.rs index a5f4df9..28fd03e 100644 --- a/crates/hx-ai/src/models.rs +++ b/crates/hx-ai/src/models.rs @@ -50,6 +50,18 @@ pub fn default_for(k: Kind, models: &[ModelInfo]) -> String { .unwrap_or_else(|| fallback(k)[0].id.clone()) } +/// Cheapest known tier of a provider (Haiku / Luna), for read-only subagents. +pub fn cheap_for(k: Kind, models: &[ModelInfo]) -> Option { + let tag = match k { + Kind::Claude => "haiku", + Kind::Codex => "luna", + }; + models + .iter() + .find(|m| m.kind == k && m.id.contains(tag)) + .map(|m| m.id.clone()) +} + /// Context window for `id`: exact match, then dated-snapshot prefix match, then a family guess. pub fn window(models: &[ModelInfo], id: &str) -> u64 { models diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index efec8c1..8907f2e 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -75,6 +75,8 @@ struct Config { /// Auto-compact threshold in estimated tokens. compact_at: Option, max_tokens: Option, + /// Model for read-only `task` subagents; default: the provider's cheapest tier (Haiku / Luna). + explore_model: Option, /// Replaces the built-in system prompt (AGENTS.md etc. are still appended). system_prompt: Option, lsp: Option, @@ -118,6 +120,7 @@ impl Config { codex_model: o.codex_model.or(c.codex_model), compact_at: o.compact_at.or(c.compact_at), max_tokens: o.max_tokens.or(c.max_tokens), + explore_model: o.explore_model.or(c.explore_model), system_prompt: o.system_prompt.or(c.system_prompt), lsp: o.lsp.or(c.lsp), extensions: [c.extensions, o.extensions].concat(), @@ -284,7 +287,8 @@ async fn main() -> Result<()> { } Some(Cmd::Logout { provider }) => return Ok(auth::logout(provider)?), Some(Cmd::Stats { session }) => { - print!("{}", hx_core::stats::report(&Session::open(session)?)); + print!("{}", hx_core::stats::report(&Session::open(&session)?)); + print!("{}", hx_core::stats::sub_report(&session)); return Ok(()); } Some(Cmd::Prefix) => { @@ -341,6 +345,7 @@ async fn main() -> Result<()> { ]; rows.extend(skill_rows); let mut specs = reg.specs(); + specs.push(hx_core::subagent::spec()); specs.sort_by_key(|t| { std::cmp::Reverse(serde_json::to_string(t).map_or(0, |s| s.len())) }); @@ -539,6 +544,39 @@ async fn main() -> Result<()> { .collect(); mgr.warm(probe).await; } + { + // children get the parent's tools as of now (no `task`, so no recursion) + let mut general = agent.tools.clone(); + general.retain(|n| n != "ask_user"); + let mut explore = agent.tools.clone(); + explore.retain(|n| hx_core::subagent::EXPLORE_TOOLS.contains(&n)); + let home = context::hx_home(); + let role = |model: String, tools, base: &str| hx_core::subagent::Role { + provider: provider(kind).expect("provider worked above"), + model, + tools, + system: context::system_prompt(Some(base), &home, &cwd), + }; + let cheap = cfg + .explore_model + .clone() + .or_else(|| hx_ai::models::cheap_for(kind, &models)) + .unwrap_or_else(|| agent.model().to_string()); + let mut task = hx_core::subagent::Task::new( + role(cheap, explore, hx_core::subagent::EXPLORE_PROMPT), + role( + agent.model().to_string(), + general, + hx_core::subagent::GENERAL_PROMPT, + ), + path.with_extension("sub"), + 3, + ); + if let Some(l) = &lens_ref { + task.hooks.push(Arc::new(ArcHook(l.clone()))); + } + agent.tools.add(task); + } let specs = command_specs(&mcp, &cwd, &models, &kinds); if cli.mode == Mode::Rpc { let r = rpc::serve( diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 30c05b1..7996b84 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -66,6 +66,7 @@ impl Agent { ) -> (Self, AbortHandle) { let (tx, rx) = watch::channel(false); let tx = Arc::new(tx); + let _ = cx.state.abort.set(rx.clone()); let a = Self { provider, tools, @@ -86,6 +87,10 @@ impl Agent { (a, AbortHandle(tx)) } + pub fn set_max_turns(&mut self, n: u32) { + self.max_turns = n; + } + pub fn abort_handle(&self) -> AbortHandle { AbortHandle(self.abort_tx.clone()) } @@ -359,6 +364,18 @@ impl Agent { is_error: r.is_error, }); } + let sub = std::mem::take( + &mut *self + .cx + .state + .sub_usage + .lock() + .unwrap_or_else(|e| e.into_inner()), + ); + if sub != Usage::default() { + self.usage.add(&sub); + self.emit(Event::SubUsage(sub)).await; + } let mut content: Vec = results.into_iter().flatten().collect(); let o = self.emit(Event::TurnEnd).await; if !o.inject.is_empty() { diff --git a/crates/hx-core/src/hook.rs b/crates/hx-core/src/hook.rs index 5a6153d..ad609f7 100644 --- a/crates/hx-core/src/hook.rs +++ b/crates/hx-core/src/hook.rs @@ -33,6 +33,8 @@ pub enum Event { Info(String), /// Text hooks injected at turn/agent end (lens reports etc), for display. Injected(Vec), + /// Tokens spent by subagents (`task` tool) in the tools just run; already added to `Agent::usage`. + SubUsage(hx_ai::Usage), } impl Event { @@ -59,6 +61,7 @@ impl Event { Event::Message(m) => json!({"type": "message", "message": m}), Event::Info(t) => json!({"type": "info", "text": t}), Event::Injected(t) => json!({"type": "injected", "texts": t}), + Event::SubUsage(u) => json!({"type": "sub_usage", "usage": u}), } } @@ -75,6 +78,7 @@ impl Event { Event::Message(_) => "message", Event::Info(_) => "info", Event::Injected(_) => "injected", + Event::SubUsage(_) => "sub_usage", } } } diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index 65354d4..7cbeac0 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -9,6 +9,7 @@ pub mod hook; pub mod mask; pub mod session; pub mod stats; +pub mod subagent; pub mod switch; pub mod tool; @@ -54,6 +55,10 @@ pub struct State { pub ask: std::sync::OnceLock, /// Same for multiple-choice questions. pub choose: std::sync::OnceLock, + /// The owning agent's abort signal (set by `Agent::new`), so subagents stop with it. + pub abort: std::sync::OnceLock>, + /// Tokens spent by subagents, drained into the agent's usage after each tool round. + pub sub_usage: Mutex, } impl State { diff --git a/crates/hx-core/src/stats.rs b/crates/hx-core/src/stats.rs index 7c73141..8caec32 100644 --- a/crates/hx-core/src/stats.rs +++ b/crates/hx-core/src/stats.rs @@ -6,6 +6,42 @@ use hx_ai::{ContentBlock, Role}; use std::collections::HashMap; use std::fmt::Write; +/// One line per subagent log in `.sub/` (empty when there are none). +pub fn sub_report(session_path: &std::path::Path) -> String { + let mut files: Vec<_> = std::fs::read_dir(session_path.with_extension("sub")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "jsonl")) + .collect(); + files.sort(); + let mut o = String::new(); + let mut tot = 0; + for p in &files { + let Ok(s) = Session::open(p) else { continue }; + let (mut n, mut inp, mut out) = (0, 0, 0); + for (_, u) in s.usages() { + n += 1; + inp += u.input_tokens + u.cache_read_tokens + u.cache_write_tokens; + out += u.output_tokens; + } + tot += inp + out; + let _ = writeln!( + o, + " {} requests {n} input {inp} output {out}", + p.file_stem().unwrap_or_default().to_string_lossy() + ); + } + if files.is_empty() { + return o; + } + format!( + "subagents ({} runs, {tot} tokens, not in the numbers above):\n{o}", + files.len() + ) +} + pub fn report(s: &Session) -> String { let msgs = s.messages(); let mut o = String::new(); diff --git a/crates/hx-core/src/subagent.rs b/crates/hx-core/src/subagent.rs new file mode 100644 index 0000000..79ca61f --- /dev/null +++ b/crates/hx-core/src/subagent.rs @@ -0,0 +1,347 @@ +//! `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