Subagents: task tool (explore on cheap model, general), child sessions, usage roll-up, stats
This commit is contained in:
1 parent
6b980591ed
commit
359a5058d7
14 files changed
+525
-2
No files matched your search
@@ -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<ContentBlock> = results.into_iter().flatten().collect();
|
||||
let o = self.emit(Event::TurnEnd).await;
|
||||
if !o.inject.is_empty() {
|
||||
|
||||
@@ -33,6 +33,8 @@ pub enum Event {
|
||||
Info(String),
|
||||
/// Text hooks injected at turn/agent end (lens reports etc), for display.
|
||||
Injected(Vec<String>),
|
||||
/// 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",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Ask>,
|
||||
/// Same for multiple-choice questions.
|
||||
pub choose: std::sync::OnceLock<Choose>,
|
||||
/// The owning agent's abort signal (set by `Agent::new`), so subagents stop with it.
|
||||
pub abort: std::sync::OnceLock<tokio::sync::watch::Receiver<bool>>,
|
||||
/// Tokens spent by subagents, drained into the agent's usage after each tool round.
|
||||
pub sub_usage: Mutex<hx_ai::Usage>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
|
||||
@@ -6,6 +6,42 @@ use hx_ai::{ContentBlock, Role};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
|
||||
/// One line per subagent log in `<session>.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();
|
||||
|
||||
@@ -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 `<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:?}");
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,10 @@ impl Registry {
|
||||
self.tools.insert(t.spec().name, Arc::new(t));
|
||||
self
|
||||
}
|
||||
/// Keep only tools for which `f(name)` holds.
|
||||
pub fn retain(&mut self, f: impl Fn(&str) -> bool) {
|
||||
self.tools.retain(|n, _| f(n));
|
||||
}
|
||||
pub fn specs(&self) -> Vec<ToolSpec> {
|
||||
self.tools.values().map(|t| t.spec()).collect()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user