Subagents: task tool (explore on cheap model, general), child sessions, usage roll-up, stats
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s

This commit is contained in:
hermes committed 2026-10-02 11:57:59 +00:00
1 parent 6b980591ed
commit 359a5058d7
14 files changed
+525 -2

No files matched your search

+6
View File
@@ -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 `<session>.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 `<dir>/<name>/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: <reason>`) |
| `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` |
+12
View File
@@ -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<String> {
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
+39 -1
View File
@@ -75,6 +75,8 @@ struct Config {
/// Auto-compact threshold in estimated tokens.
compact_at: Option<usize>,
max_tokens: Option<u32>,
/// Model for read-only `task` subagents; default: the provider's cheapest tier (Haiku / Luna).
explore_model: Option<String>,
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
system_prompt: Option<String>,
lsp: Option<LspCfg>,
@@ -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(
+17
View File
@@ -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() {
+4
View File
@@ -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",
}
}
}
+5
View File
@@ -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 {
+36
View File
@@ -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();
+347
View File
@@ -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:?}");
}
}
+4
View File
@@ -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()
}
+3
View File
@@ -323,6 +323,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
Ui::Choose(q, reply) => app.choose = Some((choose::Choose::new(q), reply)),
Ui::Ev(e) => {
if let Event::SubUsage(u) = &e {
app.st.usage.add(u);
}
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
app.st.quota = Some(q.clone());
}
+6
View File
@@ -166,6 +166,12 @@ fn outcome(name: &str, content: &str, err: bool) -> String {
.rsplit_once('(')
.map_or("ok".into(), |(_, r)| r.trim_end_matches(')').to_string()),
"read" => format!("{} lines", content.lines().count()),
// `[task explore · 12 tool calls · 41k tok · 38s]` is the last line of a task result
"task" => content
.lines()
.last()
.and_then(|l| l.strip_prefix("[task ")?.strip_suffix(']'))
.map_or("ok".into(), str::to_string),
_ => "ok".into(),
}
}
+1
View File
@@ -19,3 +19,4 @@ sh tests/m5_e2e.sh
sh tests/m6_e2e.sh
python3 tests/tui_lspinstall.py | grep -q FAIL && { echo "tui lsp install FAIL"; exit 1; } || echo "tui lsp install ok"
sh tests/m7_e2e.sh
sh tests/m8_e2e.sh
+3 -1
View File
@@ -1,7 +1,7 @@
"""Scripted fake of the Anthropic SSE API for end-to-end tests of `hx -p`.
Turn 1: tool_use write hello.txt. Turn 2: tool_use bash cat. Turn 3: final text.
Usage: python3 tests/fake_anthropic.py PORT
Usage: python3 tests/fake_anthropic.py PORT [TURNS.json]
"""
import http.server, json, sys
@@ -10,6 +10,8 @@ TURNS = [
[("tool_use", {"id": "t2", "name": "Bash", "input": {"command": "cat hello.txt"}})],
[("text", "Done: file says hi from hx.")],
]
if len(sys.argv) > 2: # optional scripted turns: JSON [[["tool_use", {...}] | ["text", "..."], ...], ...]
TURNS = [[tuple(b) for b in t] for t in json.load(open(sys.argv[2]))]
LOG = []
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# M8 e2e: the parent calls `task`; the child (own session, cheap model) reads a file and answers;
# only the answer reaches the parent; child usage is logged under <session>.sub/.
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
tmp=$(mktemp -d)
trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT
mkdir -p "$tmp/home/.hx" "$tmp/repo"
echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json"
printf '[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml"
echo "secret is 42" > "$tmp/repo/note.txt"
cat > "$tmp/turns.json" <<'J'
[[["tool_use", {"id": "p1", "name": "Task", "input": {"prompt": "what is in note.txt?"}}]],
[["tool_use", {"id": "c1", "name": "Read", "input": {"path": "note.txt"}}]],
[["text", "note.txt says: secret is 42"]],
[["text", "Parent done."]]]
J
cd "$tmp/repo"
export HOME="$tmp/home"
port=$((20000 + $$ % 20000))
python3 "$root/tests/fake_anthropic.py" $port "$tmp/turns.json" & srv=$!
export HX_BASE_URL="http://127.0.0.1:$port"
sleep 0.5
"$root/target/debug/hx" -p "go" -s "$tmp/s.jsonl" > "$tmp/out" 2> "$tmp/err" || { echo "FAIL run"; cat "$tmp/err"; exit 1; }
grep -q "Parent done." "$tmp/out" || { echo "FAIL parent text"; cat "$tmp/out" "$tmp/err"; exit 1; }
curl -s "http://127.0.0.1:$port/log" > "$tmp/log"
python3 - "$tmp/log" "$tmp/s.jsonl" <<'PY' || { echo "FAIL requests"; exit 1; }
import json, sys
log = json.load(open(sys.argv[1]))
assert len(log) == 4, len(log)
parent, child1, child2, parent2 = [r["body"] for r in log]
assert "haiku" in child1["model"] and "sonnet" in parent["model"], (child1["model"], parent["model"])
assert child1["messages"][0]["content"][0]["text"] == "what is in note.txt?"
assert {t["name"] for t in child1["tools"]} == {"Read", "Bash"}, [t["name"] for t in child1["tools"]]
assert "Task" in {t["name"] for t in parent["tools"]}
# parent got only the child's answer (+ stats line), not the Read result
res = json.dumps(parent2["messages"][-1])
assert "secret is 42" in res and "[task explore" in res
PY
ls "$tmp/s.sub/001-explore.jsonl" > /dev/null || { echo "FAIL child session"; exit 1; }
"$root/target/debug/hx" stats "$tmp/s.jsonl" | grep -q "subagents (1 runs" || { echo "FAIL stats"; exit 1; }
echo "m8 e2e ok"