From 164671a0c5b819abb219c823d234da85a1b6ec76 Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Sat, 28 Nov 2026 00:17:41 +0100 Subject: [PATCH] Subagents: read-only explore, custom agents, background runs, limits - explore's bash only runs commands the permit classifier calls read-only - custom kinds from /agents/*.md and .hx/agents/*.md - task(background=true) + task(wait=[ids]); finished answers handed over at turn end - answers over 8 KB saved to .sub/NNN-kind.answer.md - subagent_parallel / subagent_max_turns / subagent_max_tokens / subagent_timeout_secs Co-Authored-By: Claude Sonnet 5.5 --- README.md | 3 +- crates/hx-cli/src/config.sample.toml | 6 +- crates/hx-cli/src/main.rs | 66 ++- crates/hx-core/src/permit.rs | 7 +- crates/hx-core/src/subagent.rs | 723 +++++++++++++++++++++++++-- crates/hx-tui/src/agents.rs | 6 +- crates/hx-tui/src/lib.rs | 14 +- 7 files changed, 769 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 2083e92..0daac8e 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ max_tokens = 16384 # mouse = true # wheel scrolling; false keeps terminal text selection # codemode = false # add the `codemode` tool: JS scripts that call other tools in a sandbox # explore_model = "claude-haiku-4-5" # model for read-only `task` subagents; default: cheapest tier of the provider +# subagent_parallel = 3 / subagent_max_turns = 40 / subagent_max_tokens / subagent_timeout_secs # subagent limits (see Subagents) # system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended ## Sandbox: bash, LSP servers, lens and test runners run under bwrap (Linux) / sandbox-exec (macOS). @@ -116,7 +117,7 @@ Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt; Auto permissions (`--auto`, `permissions = "auto"`, `/auto [on|off|log]`): nothing prompts for the usual work, and dangerous calls are refused without asking. A refused call returns `blocked by auto mode: ` to the model (also over a stored "always" rule); `/auto log` lists the last 20. Per call, in order: (1) rules block `rm -rf` of home/root/project root/outside the project, `sudo`, raw disk writes and filesystem creation, download piped to a shell, force push, push to main/master, sending `.env`/keys over the network, `npm|cargo publish`, `docker push`, `kubectl delete`, `terraform destroy`, SQL `DROP`, writes to `/etc`, `~/.ssh`, shell rc files, `.git/hooks`; (2) rules allow routine work inside the project (build/test/format, local git, `mkdir`/`mv`/`cp`/`rm` in the project, `write`/`edit` of project files); (3) everything else (unknown binaries, `curl`, `python -c`, `$(..)`, redirects, paths outside the project) goes to one cheap-model request (Haiku/Luna, ~300 input tokens, 20 s timeout) that answers ALLOW or BLOCK; if that fails or is unavailable the normal prompt appears. `--yolo` / `/yolo` still skip everything. With the `claude_cli` provider claude's tools appear on the event bus (`tool_call` / `tool_result`; hx names `bash{command}`, `write|edit|read{path}`, other tools under claude's name), so extensions can block them (a `block` denies the call with its reason) and NDJSON / `hx stats` see them. Reads are asked too (`--settings` `permissions.ask`; Bash too, claude auto-runs read-only commands like `ls` without asking otherwise). In `-p` there is no prompt and everything is allowed, unless `permissions = "deny"` (every unanswered call is denied) or `permissions = "extensions-only"` (allowed only while a live `tool_call` extension exists). The same rules apply to claude's tool calls, but no model judge runs (unclear ones ask). Pattern rules are not a sandbox: combine with `[sandbox]` for confinement. -Each `task` call asks for permission (`[a]` allows that kind for the project); `subagents = false` or `--no-subagents` removes the tool. 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 `.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. +Each `task` call asks for permission (`[a]` allows that kind for the project); `subagents = false` or `--no-subagents` removes the tool. 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`, `skill`, and `bash` restricted to read-only commands: writes, redirects and installs are refused, not asked) on the provider's cheapest model (`explore_model` in config); **custom agents:** `/agents/.md` and `/.hx/agents/.md` (project wins) add kinds to `task`: frontmatter `description`, `tools` (list or comma string; default: all of the parent's, unknown names ignored), `model` (default: parent's, cheapest for `readonly`), `readonly: true` (explore's tool set), `max_turns`; the body is the system prompt. Agents that can edit run with the lens, like `general`. The permission rule is `task:`; **background:** `task(prompt|prompts, background=true)` returns the subagent ids at once and the parent keeps working; finished answers are handed to it at the end of its next turn, or it blocks for them with `task(wait=[ids])` (`[]` = all uncollected; needs no new approval). Answers longer than 8 KB are cut in the result and the full text is saved to `.sub/NNN-.answer.md` (path in the result); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel (`subagent_parallel`), none can start another, a parent abort stops them. Limits: `subagent_max_turns` (default 40), `subagent_max_tokens` (total tokens a subagent may spend) and `subagent_timeout_secs` (per run, counted once it has a slot) stop a child that goes over; it then fails with that reason, and the parent sees it as a failed `task`. Their sessions are written to `.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. diff --git a/crates/hx-cli/src/config.sample.toml b/crates/hx-cli/src/config.sample.toml index fc55b31..488fe2d 100644 --- a/crates/hx-cli/src/config.sample.toml +++ b/crates/hx-cli/src/config.sample.toml @@ -7,7 +7,11 @@ # codex_model = "gpt-5.6-sol" # default: Codex's top-listed model # subagents = false # do not offer the `task` tool (default true; every call asks first) # explore_model = "claude-haiku-4-5" # read-only `task` subagents; default: cheapest tier of the provider -# remember_model = true # reuse the last model picked with /model or /provider +# subagent_parallel = 3 # subagents running at once +# subagent_max_turns = 40 # turn limit per subagent (an agent file's max_turns wins) +# subagent_max_tokens = 500000 # stop a subagent that spends more tokens than this; default: no limit +# subagent_timeout_secs = 600 # stop a subagent run after this long; default: no limit +# remember_model = true # reuse the last model picked with /model or /provider # compact_at = 900000 # auto-compact at this many tokens; default: 90% of the context window # max_tokens = 16384 # permissions = "ask" # ask | auto (refuse dangerous calls, run safe ones) | yolo (nothing asks) diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index cc71aff..1e60843 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -156,6 +156,10 @@ struct Config { max_tokens: Option, explore_model: Option, subagents: Option, + subagent_parallel: Option, + subagent_max_turns: Option, + subagent_max_tokens: Option, + subagent_timeout_secs: Option, codemode: Option, mouse: Option, sessions_dir: Option, @@ -220,6 +224,10 @@ impl Config { max_tokens: o.max_tokens.or(c.max_tokens), explore_model: o.explore_model.or(c.explore_model), subagents: o.subagents.or(c.subagents), + subagent_parallel: o.subagent_parallel.or(c.subagent_parallel), + subagent_max_turns: o.subagent_max_turns.or(c.subagent_max_turns), + subagent_max_tokens: o.subagent_max_tokens.or(c.subagent_max_tokens), + subagent_timeout_secs: o.subagent_timeout_secs.or(c.subagent_timeout_secs), codemode: o.codemode.or(c.codemode), mouse: o.mouse.or(c.mouse), sessions_dir: o.sessions_dir.or(c.sessions_dir), @@ -734,7 +742,16 @@ async fn main() -> Result<()> { rows.extend(skill_rows); let mut specs = reg.specs(); if !cli.no_subagents && cfg.subagents != Some(false) { - specs.push(hx_core::subagent::spec()); + let (defs, _) = hx_core::subagent::load_agents(&hx_core::subagent::agent_dirs( + &hx_core::context::hx_home(), + &cwd, + )); + let mut kinds = hx_core::subagent::builtin_kinds(); + for d in defs { + kinds.retain(|k| k.0 != d.name); + kinds.push((d.name, d.description)); + } + specs.push(hx_core::subagent::spec_for(&kinds)); } specs.sort_by_key(|t| { std::cmp::Reverse(serde_json::to_string(t).map_or(0, |s| s.len())) @@ -1037,13 +1054,19 @@ async fn main() -> Result<()> { if !cli.no_subagents && cfg.subagents != Some(false) { let mut general = agent.tools.clone(); general.retain(|n| n != "ask_user" && n != "exit_plan"); + let base = general.clone(); let mut explore = agent.tools.clone(); explore.retain(|n| hx_core::subagent::EXPLORE_TOOLS.contains(&n)); + if let Some(b) = explore.get("bash") { + explore.add(hx_core::subagent::ReadOnlyBash(b)); + } let role = |model: String, tools, base: &str| hx_core::subagent::Role { provider: provider(kind).expect("provider worked above"), model, tools, system: format!("{base}{tail}"), + hooks: false, + max_turns: None, }; let cheap = cfg .explore_model @@ -1051,19 +1074,56 @@ async fn main() -> Result<()> { .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(cheap.clone(), explore, hx_core::subagent::EXPLORE_PROMPT), role( agent.model().to_string(), general, hx_core::subagent::GENERAL_PROMPT, ), path.with_extension("sub"), - 3, + cfg.subagent_parallel.unwrap_or(3), ); + if let Some(n) = cfg.subagent_max_turns { + task.max_turns = n; + } + task.max_tokens = cfg.subagent_max_tokens; + task.timeout = cfg + .subagent_timeout_secs + .map(std::time::Duration::from_secs); if let Some(l) = &lens_ref { task.hooks.push(Arc::new(ArcHook(l.clone()))); } + let (defs, warns) = hx_core::subagent::load_agents(&hx_core::subagent::agent_dirs( + &context::hx_home(), + &cwd, + )); + for w in warns { + eprintln!("hx: agent {w}"); + } + for d in defs { + let tools = hx_core::subagent::agent_tools(&base, &d); + let (model, default_prompt) = if d.readonly { + (cheap.clone(), hx_core::subagent::EXPLORE_PROMPT) + } else { + (agent.model().to_string(), hx_core::subagent::GENERAL_PROMPT) + }; + let mut r = role( + d.model.clone().unwrap_or(model), + tools, + if d.system.is_empty() { + default_prompt + } else { + &d.system + }, + ); + r.hooks = hx_core::subagent::edits(&r.tools); + r.max_turns = d.max_turns; + task.add_kind(d.name, d.description, r); + } agent.tools.add(task); + agent + .bus + .add(hx_core::subagent::Notify(agent.cx.state.clone())); } if CLAUDE_CLI.get().is_none() && let (Ok(p), Some(model)) = ( diff --git a/crates/hx-core/src/permit.rs b/crates/hx-core/src/permit.rs index 703e34a..1d25c42 100644 --- a/crates/hx-core/src/permit.rs +++ b/crates/hx-core/src/permit.rs @@ -151,7 +151,7 @@ pub(crate) fn split_cmd(cmd: &str) -> Option> { Some(segs) } -fn readonly_cmd(cmd: &str) -> bool { +pub fn readonly_cmd(cmd: &str) -> bool { split_cmd(cmd).is_some_and(|s| s.iter().all(readonly_seg)) } @@ -181,7 +181,10 @@ pub fn needs_permit(tool: &str, args: &serde_json::Value) -> bool { match tool { "bash" => !readonly_cmd(a("command").trim()), "read" => secret(a("path")), - "web_fetch" | "task" => true, + "task" => { + !(args["wait"].is_array() && args["prompt"].is_null() && args["prompts"].is_null()) + } + "web_fetch" => true, _ => gated(tool), } } diff --git a/crates/hx-core/src/subagent.rs b/crates/hx-core/src/subagent.rs index f208387..ffe3fd4 100644 --- a/crates/hx-core/src/subagent.rs +++ b/crates/hx-core/src/subagent.rs @@ -16,14 +16,17 @@ pub struct Role { pub model: String, pub tools: Registry, pub system: String, + pub hooks: bool, + pub max_turns: Option, } pub struct Task { - pub explore: Role, - pub general: Role, + roles: Vec<(String, String, Role)>, pub dir: PathBuf, pub hooks: Vec>, pub max_turns: u32, + pub max_tokens: Option, + pub timeout: Option, sem: Arc, n: AtomicUsize, } @@ -38,7 +41,7 @@ pub enum Status { pub struct Shared { pub id: usize, - pub kind: &'static str, + pub kind: String, pub model: String, pub prompt: String, pub started: Instant, @@ -48,9 +51,24 @@ pub struct Shared { pub usage: Mutex, inbox: Mutex>, rolled: Mutex, + stop: Mutex>, + timeout: Option, + runs: AtomicUsize, + background: bool, + result: Mutex>, + collected: std::sync::atomic::AtomicBool, } impl Shared { + fn stop_with(&self, why: String) { + let mut s = self.stop.lock().unwrap_or_else(|e| e.into_inner()); + if s.is_none() { + *s = Some(why); + } + } + fn stopped(&self) -> Option { + self.stop.lock().unwrap_or_else(|e| e.into_inner()).clone() + } pub fn status(&self) -> Status { self.status .lock() @@ -72,6 +90,7 @@ pub struct Sub { abort: crate::agent::AbortHandle, state: Arc, sem: Arc, + dir: PathBuf, } #[derive(Default)] @@ -140,7 +159,15 @@ fn diff(a: &Usage, b: &Usage) -> Usage { } } -struct Live(Arc, Option>); +struct Live( + Arc, + Option>, + Option<(u64, crate::agent::AbortHandle)>, +); + +fn total(u: &Usage) -> u64 { + u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens +} #[async_trait] impl Hook for Live { @@ -150,11 +177,21 @@ impl Hook for Live { self.0.calls.fetch_add(1, Ordering::Relaxed); } Event::Stream(StreamEvent::Done { usage, .. }) => { - self.0 - .usage - .lock() - .unwrap_or_else(|e| e.into_inner()) - .add(usage); + let spent = { + let mut u = self.0.usage.lock().unwrap_or_else(|e| e.into_inner()); + u.add(usage); + total(&u) + }; + if let Some((max, h)) = &self.2 + && spent > *max + { + self.0.stop_with(format!( + "token budget exceeded ({}k of {}k)", + spent / 1000, + max / 1000 + )); + h.abort(); + } } _ => {} } @@ -189,14 +226,29 @@ impl Sub { } *st = Status::Running; *self.sh.ended.lock().unwrap_or_else(|e| e.into_inner()) = None; + *self.sh.stop.lock().unwrap_or_else(|e| e.into_inner()) = None; } let me = self.clone(); tokio::spawn(async move { let _permit = me.sem.acquire().await; + me.arm(); let _ = me.drive(text).await; }); } + fn arm(&self) { + let Some(t) = self.sh.timeout else { return }; + let (sh, abort) = (self.sh.clone(), self.abort.clone()); + let run = sh.runs.fetch_add(1, Ordering::Relaxed) + 1; + tokio::spawn(async move { + tokio::time::sleep(t).await; + if sh.status() == Status::Running && sh.runs.load(Ordering::Relaxed) == run { + sh.stop_with(format!("timeout after {}s", t.as_secs())); + abort.abort(); + } + }); + } + async fn drive(&self, mut p: String) -> Result { let mut a = self.agent.lock().await; loop { @@ -222,7 +274,10 @@ impl Sub { } *st = match &r { Ok(_) => Status::Done, - Err(Error::Aborted) => Status::Aborted, + Err(Error::Aborted) => match self.sh.stopped() { + Some(why) => Status::Failed(why), + None => Status::Aborted, + }, Err(e) => Status::Failed(e.to_string()), }; *self.sh.ended.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now()); @@ -231,43 +286,276 @@ impl Sub { } } +pub struct ReadOnlyBash(pub Arc); + +#[async_trait] +impl Tool for ReadOnlyBash { + fn spec(&self) -> ToolSpec { + self.0.spec() + } + async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { + let cmd = a["command"].as_str().unwrap_or_default().trim(); + if !crate::permit::readonly_cmd(cmd) { + return ToolResult::err( + "read-only subagent: only read-only commands (rg, fd, ls, cat, git log/diff/show, ...; no redirects or `$()`) are allowed", + ); + } + self.0.call(a, cx).await + } +} + pub const EXPLORE_TOOLS: &[&str] = &["read", "lsp", "bash", "skill"]; 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, and run the narrowest relevant check (build, test, lint) after editing. 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 { + pub fn new(mut explore: Role, mut general: Role, dir: PathBuf, parallel: usize) -> Self { + explore.hooks = false; + general.hooks = true; Self { - explore, - general, + roles: vec![ + ("explore".into(), BUILTIN[0].1.into(), explore), + ("general".into(), BUILTIN[1].1.into(), general), + ], dir: dir.clone(), hooks: vec![], max_turns: 40, + max_tokens: None, + timeout: None, sem: Arc::new(Semaphore::new(parallel.max(1))), n: AtomicUsize::new(std::fs::read_dir(&dir).map_or(0, |d| d.count())), } } + + pub fn add_kind(&mut self, name: String, desc: String, role: Role) { + match self.roles.iter_mut().find(|r| r.0 == name) { + Some(r) => *r = (name, desc, role), + None => self.roles.push((name, desc, role)), + } + } + + pub fn kinds(&self) -> Vec<(String, String)> { + self.roles + .iter() + .map(|r| (r.0.clone(), r.1.clone())) + .collect() + } } -pub fn spec() -> ToolSpec { +const BUILTIN: [(&str, &str); 2] = [ + ("explore", "read-only research on a cheaper model (default)"), + ("general", "same tools as you, may edit"), +]; + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct AgentDef { + pub name: String, + pub description: String, + pub tools: Vec, + pub model: Option, + pub readonly: bool, + pub max_turns: Option, + pub system: String, +} + +#[derive(serde::Deserialize, Default)] +#[serde(untagged)] +enum Names { + #[default] + None, + One(String), + Many(Vec), +} + +#[derive(serde::Deserialize, Default)] +struct AgentFront { + name: Option, + description: Option, + #[serde(default)] + tools: Names, + model: Option, + readonly: Option, + max_turns: Option, +} + +pub fn agent_dirs(home: &std::path::Path, cwd: &std::path::Path) -> Vec { + vec![home.join("agents"), cwd.join(".hx/agents")] +} + +pub fn parse_agent(path: &std::path::Path, s: &str) -> Result { + let (fm, body) = s + .strip_prefix("---") + .and_then(|r| r.split_once("\n---")) + .map_or(("", s), |(f, b)| { + (f, b.split_once('\n').map_or("", |x| x.1)) + }); + let f: AgentFront = if fm.trim().is_empty() { + AgentFront::default() + } else { + serde_norway::from_str(fm).map_err(|e| e.to_string())? + }; + let name = f.name.unwrap_or_else(|| { + path.file_stem() + .unwrap_or_default() + .to_string_lossy() + .into() + }); + if name.is_empty() + || !name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + { + return Err(format!( + "bad agent name `{name}` (use letters, digits, - _)" + )); + } + let tools = match f.tools { + Names::None => vec![], + Names::One(s) => s.split(',').map(|t| t.trim().to_string()).collect(), + Names::Many(v) => v, + }; + Ok(AgentDef { + name, + description: f + .description + .unwrap_or_default() + .split_whitespace() + .collect::>() + .join(" "), + tools: tools.into_iter().filter(|t| !t.is_empty()).collect(), + model: f.model.filter(|m| !m.trim().is_empty()), + readonly: f.readonly.unwrap_or(false), + max_turns: f.max_turns, + system: body.trim().to_string(), + }) +} + +pub fn load_agents(dirs: &[PathBuf]) -> (Vec, Vec) { + let mut out: Vec = vec![]; + let mut warn = vec![]; + for dir in dirs { + let Ok(rd) = std::fs::read_dir(dir) else { + continue; + }; + let mut paths: Vec<_> = rd + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "md") && p.is_file()) + .collect(); + paths.sort(); + for p in paths { + let Ok(s) = std::fs::read_to_string(&p) else { + continue; + }; + match parse_agent(&p, &s) { + Ok(a) => { + out.retain(|x| x.name != a.name); + out.push(a); + } + Err(e) => warn.push(format!("{}: skipped: {e}", p.display())), + } + } + } + (out, warn) +} + +pub fn agent_tools(base: &Registry, def: &AgentDef) -> Registry { + let mut t = base.clone(); + if !def.tools.is_empty() { + t.retain(|n| def.tools.iter().any(|x| x == n)); + } + if def.readonly { + t.retain(|n| EXPLORE_TOOLS.contains(&n)); + if let Some(b) = t.get("bash") { + t.add(ReadOnlyBash(b)); + } + } + t +} + +pub fn edits(t: &Registry) -> bool { + t.get("edit").is_some() || t.get("write").is_some() +} + +pub fn builtin_kinds() -> Vec<(String, String)> { + BUILTIN + .iter() + .map(|(n, d)| (n.to_string(), d.to_string())) + .collect() +} + +pub fn spec_for(kinds: &[(String, String)]) -> ToolSpec { + let list: Vec = kinds + .iter() + .enumerate() + .map(|(i, (n, d))| { + let d = if d.is_empty() { "custom agent" } else { d }; + format!("kind={n}{}: {d}.", if i == 0 { " (default)" } else { "" }) + }) + .collect(); + let names: Vec<&str> = kinds.iter().map(|k| k.0.as_str()).collect(); ToolSpec { name: "task".into(), - description: "Run a subagent in a fresh context; you get back only its final answer. The user is asked to approve every call: use it only when the user asked for subagents or parallel work, or when a search would clearly put >10k tokens in your context. Do ordinary discovery (read, grep, lsp, bash) yourself in this session. kind=explore (default): read-only research on a cheaper model. 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. For 2+ independent subtasks pass `prompts` (array); they run in parallel.".into(), + description: format!( + "Run a subagent in a fresh context; you get back only its final answer. The user is asked to approve every call: use it only when the user asked for subagents or parallel work, or when a search would clearly put >10k tokens in your context. Do ordinary discovery (read, grep, lsp, bash) yourself in this session. {} The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers. For 2+ independent subtasks pass `prompts` (array); they run in parallel. With background=true the call returns at once with the subagent ids and you keep working; their answers are handed to you at the end of a turn, or call task(wait=[ids]) (empty array = all) to block for them.", + list.join(" ") + ), 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"]}}, - }), + "prompt":{"type":"string"}, + "background":{"type":"boolean","description":"start and return immediately"}, + "wait":{"type":"array","items":{"type":"integer"},"description":"block until these background subagents answered; [] = all uncollected"}, + "prompts":{"type":"array","items":{"type":"string"},"description":"several independent subtasks: one subagent each, run in parallel, answers returned numbered"}, + "kind":{"type":"string","enum":names}}, + }), } } #[async_trait] impl Tool for Task { fn spec(&self) -> ToolSpec { - spec() + spec_for(&self.kinds()) } async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { + if a["prompt"].is_null() && a["prompts"].is_null() { + if let Some(w) = a["wait"].as_array() { + let ids: Vec = w + .iter() + .filter_map(|v| v.as_u64()) + .map(|n| n as usize) + .collect(); + return self.wait(&ids, cx).await; + } + } + if a["background"].as_bool() == Some(true) { + let ps: Vec<&str> = match a["prompts"].as_array() { + Some(ps) => ps.iter().filter_map(|p| p.as_str()).collect(), + None => vec![a["prompt"].as_str().unwrap_or_default()], + }; + let mut started = vec![]; + for p in ps { + match self.start(p, a["kind"].as_str(), true, cx) { + Ok(sub) => { + let (me, p) = (sub.clone(), p.to_string()); + tokio::spawn(async move { + let permit = me.sem.acquire().await; + me.arm(); + let r = me.drive(p).await; + drop(permit); + let out = me.finish(r); + *me.sh.result.lock().unwrap_or_else(|e| e.into_inner()) = + Some((out.content, out.is_error)); + }); + started.push(format!("{} ({})", sub.sh.id, sub.sh.kind)); + } + Err(e) => return e, + } + } + return ToolResult::ok(format!( + "started in the background: subagent {}. Their answers are reported to you at the end of a turn, or collect them with task(wait=[ids]).", + started.join(", ") + )); + } let Some(ps) = a["prompts"].as_array() else { return self .run( @@ -298,24 +586,74 @@ impl Tool for Task { } 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)")), - }; - let aborted = || cx.state.abort.get().is_some_and(|r| *r.borrow()); - if aborted() { - return ToolResult::err("aborted"); + async fn wait(&self, ids: &[usize], cx: &ToolCtx) -> ToolResult { + let subs: Vec> = cx + .state + .subs + .list() + .into_iter() + .filter(|s| { + s.sh.background + && if ids.is_empty() { + !s.sh.collected.load(Ordering::Relaxed) + } else { + ids.contains(&s.sh.id) + } + }) + .collect(); + if subs.is_empty() { + return ToolResult::err("no such background subagent"); } - let Ok(_permit) = self.sem.acquire().await else { - return ToolResult::err("subagents unavailable"); + let (mut out, mut err) = (String::new(), true); + for s in subs { + let r = loop { + if let Some(r) = + s.sh.result + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + { + break r; + } + if cx.state.abort.get().is_some_and(|r| *r.borrow()) { + return ToolResult::err("aborted"); + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + }; + s.sh.collected.store(true, Ordering::Relaxed); + err &= r.1; + out.push_str(&format!("## {} ({})\n{}\n\n", s.sh.id, s.sh.kind, r.0)); + } + ToolResult { + content: out, + is_error: err, + images: vec![], + } + } + + fn start( + &self, + prompt: &str, + kind: Option<&str>, + background: bool, + cx: &ToolCtx, + ) -> Result, ToolResult> { + let want = kind.unwrap_or(&self.roles[0].0); + let Some((kind, _, role)) = self.roles.iter().find(|r| r.0 == want) else { + let names: Vec<&str> = self.roles.iter().map(|r| r.0.as_str()).collect(); + return Err(ToolResult::err(format!( + "unknown kind `{want}` ({})", + names.join(" | ") + ))); }; + if cx.state.abort.get().is_some_and(|r| *r.borrow()) { + return Err(ToolResult::err("aborted")); + } let id = self.n.fetch_add(1, Ordering::Relaxed) + 1; let path = self.dir.join(format!("{id:03}-{kind}.jsonl")); let session = match Session::open(&path) { Ok(s) => s, - Err(e) => return ToolResult::err(format!("subagent session: {e}")), + Err(e) => return Err(ToolResult::err(format!("subagent session: {e}"))), }; let (mut child, handle) = Agent::new( role.provider.clone(), @@ -328,10 +666,10 @@ impl Task { ); child.set_model(role.model.clone()); child.set_system(role.system.clone()); - child.set_max_turns(self.max_turns); + child.set_max_turns(role.max_turns.unwrap_or(self.max_turns)); let sh = Arc::new(Shared { id, - kind, + kind: kind.clone(), model: role.model.clone(), prompt: prompt.to_string(), started: Instant::now(), @@ -341,11 +679,19 @@ impl Task { usage: Mutex::default(), inbox: Mutex::default(), rolled: Mutex::default(), + stop: Mutex::new(None), + timeout: self.timeout, + runs: AtomicUsize::new(0), + background, + result: Mutex::new(None), + collected: Default::default(), }); - child - .bus - .add(Live(sh.clone(), cx.state.subs.events.get().cloned())); - if kind == "general" { + child.bus.add(Live( + sh.clone(), + cx.state.subs.events.get().cloned(), + self.max_tokens.map(|m| (m, handle.clone())), + )); + if role.hooks { for h in &self.hooks { child.bus.add_arc(h.clone()); } @@ -356,17 +702,38 @@ impl Task { abort: handle, state: cx.state.clone(), sem: self.sem.clone(), + dir: self.dir.clone(), }); cx.state.subs.add(sub.clone()); cx.state.subs.watch(&cx.state); - if aborted() { + Ok(sub) + } + + async fn run(&self, prompt: &str, kind: Option<&str>, cx: &ToolCtx) -> ToolResult { + let sub = match self.start(prompt, kind, false, cx) { + Ok(s) => s, + Err(e) => return e, + }; + let Ok(_permit) = self.sem.acquire().await else { + return ToolResult::err("subagents unavailable"); + }; + if cx.state.abort.get().is_some_and(|r| *r.borrow()) { sub.abort(); } + sub.arm(); let r = sub.drive(prompt.to_string()).await; + sub.finish(r) + } +} + +impl Sub { + fn finish(&self, r: Result) -> ToolResult { + let sh = &self.sh; let u = sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone(); let tok = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens; let stats = format!( - "[task {kind} · {} tool calls · {}k tok · {}s]", + "[task {} · {} tool calls · {}k tok · {}s]", + sh.kind, sh.calls.load(Ordering::Relaxed), tok / 1000, sh.elapsed().as_secs() @@ -375,16 +742,58 @@ impl Task { Ok(m) => { let mut t = m.text(); if t.len() > MAX_RESULT { + let p = self.dir.join(format!("{:03}-{}.answer.md", sh.id, sh.kind)); + let saved = std::fs::write(&p, &t).is_ok(); let mut i = MAX_RESULT; while !t.is_char_boundary(i) { i -= 1; } t.truncate(i); t.push_str("\n[... answer cut ...]"); + if saved { + t.push_str(&format!("\nfull answer: {}", p.display())); + } } ToolResult::ok(format!("{t}\n{stats}")) } - Err(e) => ToolResult::err(format!("subagent failed: {e}\n{stats}")), + Err(e) => { + let why = sh.stopped().unwrap_or_else(|| e.to_string()); + ToolResult::err(format!("subagent failed: {why}\n{stats}")) + } + } + } +} + +pub struct Notify(pub Arc); + +#[async_trait] +impl Hook for Notify { + async fn on(&self, ev: &Event) -> HookAction { + if !matches!(ev, Event::TurnEnd | Event::AgentEnd) { + return HookAction::Continue; + } + let mut out = vec![]; + for s in self.0.subs.list() { + if !s.sh.background || s.sh.collected.load(Ordering::Relaxed) { + continue; + } + if let Some(r) = + s.sh.result + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + { + s.sh.collected.store(true, Ordering::Relaxed); + out.push(format!( + "background subagent {} ({}) finished:\n{}", + s.sh.id, s.sh.kind, r.0 + )); + } + } + if out.is_empty() { + HookAction::Continue + } else { + HookAction::Inject(out.join("\n\n")) } } } @@ -468,9 +877,211 @@ mod tests { model: model.into(), tools, system: "child".into(), + hooks: false, + max_turns: None, } } + #[test] + fn agent_files_parse_override_and_filter_tools() { + let d = tempfile::tempdir().unwrap(); + let (a, b) = (d.path().join("a"), d.path().join("b")); + std::fs::create_dir_all(&a).unwrap(); + std::fs::create_dir_all(&b).unwrap(); + std::fs::write( + a.join("rev.md"), + "---\ndescription: reviews\ntools: [read, nope]\nmax_turns: 5\n---\nBe strict.\n", + ) + .unwrap(); + std::fs::write( + b.join("rev.md"), + "---\ndescription: project review\ntools: read, bash\nreadonly: true\nmodel: m\n---\nP\n", + ) + .unwrap(); + std::fs::write(b.join("bad name.md"), "x").unwrap(); + let (defs, warn) = load_agents(&[a, b]); + assert_eq!(warn.len(), 1, "{warn:?}"); + assert_eq!(defs.len(), 1); + let r = &defs[0]; + assert_eq!( + (r.name.as_str(), r.description.as_str(), r.system.as_str()), + ("rev", "project review", "P") + ); + assert_eq!(r.tools, ["read", "bash"]); + assert!(r.readonly && r.model.as_deref() == Some("m")); + let mut base = Registry::default(); + base.add(Echo); + base.add(Bash); + let t = agent_tools(&base, r); + assert!(t.get("read").is_some() && t.get("bash").is_some()); + let t = agent_tools( + &base, + &AgentDef { + tools: vec!["read".into(), "nope".into()], + ..Default::default() + }, + ); + assert!(t.get("read").is_some() && t.get("bash").is_none()); + assert!(!edits(&t)); + } + + #[tokio::test] + async fn background_returns_at_once_then_wait_and_notify_deliver() { + let d = tempfile::tempdir().unwrap(); + let p = Arc::new(Script( + Mutex::new(vec![text("first"), text("second")]), + 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"],"background":true}), &cx) + .await; + assert!( + !r.is_error && r.content.contains("started in the background"), + "{r:?}" + ); + assert_eq!(cx.state.subs.list().len(), 2); + let w = t.call(json!({"wait":[1]}), &cx).await; + assert!( + !w.is_error && w.content.starts_with("## 1 (explore)\n"), + "{w:?}" + ); + let n = Notify(cx.state.clone()); + let mut got = None; + for _ in 0..100 { + if let HookAction::Inject(m) = n.on(&Event::TurnEnd).await { + got = Some(m); + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + let m = got.expect("notified"); + assert!( + m.contains("background subagent 2") && !m.contains("subagent 1"), + "{m}" + ); + assert!(matches!(n.on(&Event::TurnEnd).await, HookAction::Continue)); + assert!(t.call(json!({"wait":[9]}), &cx).await.is_error); + } + + #[tokio::test] + async fn token_budget_stops_child() { + let d = tempfile::tempdir().unwrap(); + let p = Arc::new(Script( + Mutex::new(vec![call("read", json!({}))]), + Default::default(), + )); + let mut t = Task::new( + role(&p, "cheap"), + role(&p, "main"), + d.path().join("s.sub"), + 1, + ); + t.max_tokens = Some(500); + let cx = ToolCtx { + cwd: d.path().into(), + state: Default::default(), + }; + let r = t.call(json!({"prompt":"a"}), &cx).await; + assert!( + r.is_error && r.content.contains("token budget exceeded"), + "{r:?}" + ); + assert!(matches!( + cx.state.subs.get(1).unwrap().sh.status(), + Status::Failed(w) if w.contains("token budget") + )); + } + + struct Hang; + #[async_trait] + impl Provider for Hang { + async fn stream( + &self, + _: Request, + ) -> hx_ai::Result>> { + Ok(futures::stream::pending().boxed()) + } + } + + #[tokio::test] + async fn timeout_stops_child() { + let d = tempfile::tempdir().unwrap(); + let mut r = role(&Arc::new(Script(Mutex::default(), Default::default())), "m"); + r.provider = Arc::new(Hang); + let mut r2 = role(&Arc::new(Script(Mutex::default(), Default::default())), "m"); + r2.provider = Arc::new(Hang); + let mut t = Task::new(r, r2, d.path().join("s.sub"), 1); + t.timeout = Some(std::time::Duration::from_millis(100)); + let cx = ToolCtx { + cwd: d.path().into(), + state: Default::default(), + }; + let r = tokio::time::timeout( + std::time::Duration::from_secs(5), + t.call(json!({"prompt":"a"}), &cx), + ) + .await + .expect("timeout must end the child"); + assert!(r.is_error && r.content.contains("timeout after"), "{r:?}"); + } + + #[tokio::test] + async fn long_answer_is_saved_to_a_file() { + let d = tempfile::tempdir().unwrap(); + let big = "y".repeat(20_000); + let p = Arc::new(Script(Mutex::new(vec![text(&big)]), 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(), + }; + let r = t.call(json!({"prompt":"a"}), &cx).await; + assert!(r.content.contains("full answer: "), "{}", r.content); + let f = d.path().join("s.sub/001-explore.answer.md"); + assert_eq!(std::fs::read_to_string(f).unwrap(), big); + } + + #[tokio::test] + async fn custom_kind_is_listed_and_runs_with_its_role() { + let d = tempfile::tempdir().unwrap(); + let p = Arc::new(Script(Mutex::new(vec![text("ok")]), Default::default())); + let mut t = Task::new( + role(&p, "cheap"), + role(&p, "main"), + d.path().join("s.sub"), + 1, + ); + let mut r = role(&p, "mine"); + r.max_turns = Some(3); + t.add_kind("rev".into(), "reviews".into(), r); + let s = Tool::spec(&t); + assert_eq!(s.input_schema["properties"]["kind"]["enum"][2], "rev"); + assert!(s.description.contains("kind=rev: reviews.")); + let cx = ToolCtx { + cwd: d.path().into(), + state: Default::default(), + }; + let r = t.call(json!({"prompt":"a","kind":"rev"}), &cx).await; + assert!(r.content.contains("[task rev"), "{}", r.content); + assert_eq!(p.1.lock().unwrap()[0].model, "mine"); + assert!(d.path().join("s.sub/001-rev.jsonl").exists()); + } + #[tokio::test] async fn child_runs_returns_answer_and_usage() { let d = tempfile::tempdir().unwrap(); @@ -561,6 +1172,36 @@ mod tests { assert!(d.path().join("s.sub/001-general.jsonl").exists()); } + struct Bash; + #[async_trait] + impl Tool for Bash { + fn spec(&self) -> ToolSpec { + ToolSpec { + name: "bash".into(), + description: "".into(), + input_schema: json!({"type":"object"}), + } + } + async fn call(&self, _: Value, _: &ToolCtx) -> ToolResult { + ToolResult::ok("ran") + } + } + + #[tokio::test] + async fn readonly_bash_refuses_writes() { + let cx = ToolCtx { + cwd: ".".into(), + state: Default::default(), + }; + let t = ReadOnlyBash(Arc::new(Bash)); + assert!(t.call(json!({"command":"echo x > f"}), &cx).await.is_error); + assert!(t.call(json!({"command":"rm -rf x"}), &cx).await.is_error); + assert_eq!( + t.call(json!({"command":"rg foo"}), &cx).await.content, + "ran" + ); + } + #[tokio::test] async fn parent_abort_stops_child() { let d = tempfile::tempdir().unwrap(); diff --git a/crates/hx-tui/src/agents.rs b/crates/hx-tui/src/agents.rs index 503ff25..60a4ace 100644 --- a/crates/hx-tui/src/agents.rs +++ b/crates/hx-tui/src/agents.rs @@ -10,7 +10,7 @@ use std::time::Duration; #[derive(Clone, Debug, PartialEq)] pub struct Row { pub id: usize, - pub kind: &'static str, + pub kind: String, pub prompt: String, pub status: Status, pub elapsed: Duration, @@ -23,7 +23,7 @@ pub fn row(s: &Sub) -> Row { let u = s.sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone(); Row { id: s.sh.id, - kind: s.sh.kind, + kind: s.sh.kind.clone(), prompt: s.sh.prompt.lines().next().unwrap_or_default().to_string(), status: s.sh.status(), elapsed: s.sh.elapsed(), @@ -204,7 +204,7 @@ mod tests { fn r(id: usize, st: Status) -> Row { Row { id, - kind: "explore", + kind: "explore".into(), prompt: "grep the auth middleware for token expiry checks".into(), status: st, elapsed: Duration::from_secs(72), diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index d45168d..3841f86 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -199,10 +199,7 @@ impl App { }; let key = format!("{} {}", s.sh.model, st); if self.seen_subs.get(&s.sh.id) != Some(&key) { - self.log.push( - format!("{} {}", s.sh.kind, s.sh.model), - st, - ); + self.log.push(format!("{} {}", s.sh.kind, s.sh.model), st); self.seen_subs.insert(s.sh.id, key); } } @@ -211,7 +208,12 @@ impl App { fn sync_lens_log(&mut self, new: &[String]) { let state = |x: &str| { x.split_once(" @ ") - .map(|(n, r)| (n.to_string(), r.rsplit_once(": ").map_or("", |p| p.1).to_string())) + .map(|(n, r)| { + ( + n.to_string(), + r.rsplit_once(": ").map_or("", |p| p.1).to_string(), + ) + }) .unwrap_or_else(|| (x.to_string(), String::new())) }; for x in new { @@ -2417,6 +2419,8 @@ mod tests { model: "m".into(), tools: Default::default(), system: String::new(), + hooks: false, + max_turns: None, }; let task = hx_core::subagent::Task::new(role(), role(), d.path().join("s.sub"), 1); let cx = ToolCtx {