task: prompts[] fan-out, discourage lone tasks, stats #150
No files matched your search
@@ -85,7 +85,7 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off
|
||||
|
||||
Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt; `read` and read-only `bash` (`ls cat head tail wc grep rg fd pwd echo stat file du df which tree diff`, `git status|log|diff|show|branch|blame|ls-files|rev-parse`) run freely, unless chained/redirected or a path looks secret (`.env*`, `.ssh/`, `.aws/`, `*.pem`, `*.key`, `id_rsa*`, `.netrc`, `.git-credentials`, `auth.json`), which asks first. `--yolo` skips all prompts.
|
||||
|
||||
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 `<session>.sub/`; `hx stats` lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
|
||||
The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) 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 `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
|
||||
|
||||
A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens.
|
||||
|
||||
|
||||
@@ -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(());
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user