task: prompts[] fan-out, steer away from lone tasks, hx stats task report

This commit is contained in:
hermes committed 2026-10-14 09:14:43 +00:00
1 parent 57eddb98ca
commit 99a0deff1a
4 files changed
+128 -5

No files matched your search

+1
View File
@@ -413,6 +413,7 @@ 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::task_report(&Session::open(&session)?));
print!("{}", hx_core::stats::sub_report(&session));
return Ok(());
}
+64
View File
@@ -6,6 +6,46 @@ use hx_ai::{ContentBlock, Role};
use std::collections::HashMap;
use std::fmt::Write;
/// How `task` was used in the parent session: calls per assistant turn (1 = parent waits on a
/// lone child), kinds, and bytes of answers carried back. Empty when `task` was never called.
pub fn task_report(s: &Session) -> String {
let (mut single, mut batch, mut calls, mut explore, mut bytes) = (0, 0, 0, 0, 0);
let mut ids = std::collections::HashSet::new();
for m in s.messages() {
let mut n = 0;
for b in &m.content {
match b {
ContentBlock::ToolUse { id, name, input } if name == "task" => {
n += 1;
ids.insert(id.clone());
if input["kind"].as_str().unwrap_or("explore") == "explore" {
explore += 1;
}
}
ContentBlock::ToolResult {
tool_use_id,
content,
..
} if ids.contains(tool_use_id) => bytes += content.len(),
_ => {}
}
}
calls += n;
match n {
0 => {}
1 => single += 1,
_ => batch += 1,
}
}
if calls == 0 {
return String::new();
}
format!(
"task calls: {calls} ({explore} explore, {} general); turns with one task {single}, with several {batch}; answers {bytes} bytes\n",
calls - explore
)
}
/// 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"))
@@ -276,6 +316,30 @@ mod tests {
use super::*;
use hx_ai::{Message, Usage};
#[test]
fn task_report_counts_lone_and_batched_turns() {
let d = tempfile::tempdir().unwrap();
let mut s = Session::open(d.path().join("s.jsonl")).unwrap();
let tu = |id: &str, k: &str| ContentBlock::ToolUse {
id: id.into(),
name: "task".into(),
input: serde_json::json!({"kind": k}),
};
for c in [
vec![tu("a", "explore")],
vec![tu("b", "explore"), tu("c", "general")],
] {
s.append(Message {
role: Role::Assistant,
content: c,
})
.unwrap();
}
let r = task_report(&s);
assert!(r.contains("task calls: 3 (2 explore, 1 general)"), "{r}");
assert!(r.contains("one task 1, with several 1"), "{r}");
}
#[test]
fn report_counts() {
let d = tempfile::tempdir().unwrap();
+62 -4
View File
@@ -252,11 +252,12 @@ impl Task {
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(),
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"]}},
"required":["prompt"]}),
}),
}
}
@@ -266,8 +267,38 @@ impl Tool for Task {
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() {
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)")),
@@ -488,6 +519,33 @@ mod tests {
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();