From 9a918a5fbe3d2994fd4dccf4360e1e30a47c2570 Mon Sep 17 00:00:00 2001 From: Hakula Chen Date: Tue, 1 Dec 2026 18:18:18 +0800 Subject: [PATCH 1/3] feat(ox-core): add unified Agent SpawnSpec and invoke_subagent tool --- crates/ox-core/src/lib.rs | 1 + crates/ox-core/src/subagent.rs | 629 +++++++++++++++++++++++++++++++++ docs/README.md | 1 + docs/reference/subagents.md | 39 ++ 4 files changed, 670 insertions(+) create mode 100644 crates/ox-core/src/subagent.rs create mode 100644 docs/reference/subagents.md diff --git a/crates/ox-core/src/lib.rs b/crates/ox-core/src/lib.rs index 7364d8a43..4385cd3cf 100644 --- a/crates/ox-core/src/lib.rs +++ b/crates/ox-core/src/lib.rs @@ -11,4 +11,5 @@ pub mod plugin; pub mod prompt; pub mod session; pub mod skills; +pub mod subagent; pub mod tools; diff --git a/crates/ox-core/src/subagent.rs b/crates/ox-core/src/subagent.rs new file mode 100644 index 000000000..183e4dd65 --- /dev/null +++ b/crates/ox-core/src/subagent.rs @@ -0,0 +1,629 @@ +//! Unified subagent spawning (`Agent` + [`SpawnSpec`]) and the `invoke_subagent` tool. + +use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::Arc; + +use async_trait::async_trait; +use futures_util::StreamExt as _; +use serde::Deserialize; +use serde_json::{Value, json}; +use thiserror::Error; + +use crate::agent::{Agent, AgentConfig, AgentEvent, AgentStopReason, DEFAULT_MAX_TURNS}; +use crate::client::{Usage, Wire}; +use crate::hooks::HookRunner; +use crate::message::{ContentBlock, Message, Role, ToolSpec}; +use crate::tools::{Tool, ToolContext, ToolError, ToolOutput, ToolRegistry}; + +/// Default maximum nesting depth for subagent delegation. +pub const DEFAULT_MAX_DEPTH: usize = 3; + +/// Initial conversation context for a spawned [`Agent`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum SpawnContext { + /// Start with a clean conversation containing only the spawn prompt. + #[default] + Fresh, + /// Continue from an existing message history with the spawn prompt appended. + Fork(Vec), +} + +/// Lifecycle policy for a spawned [`Agent`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum SpawnLifecycle { + /// Run to completion and return the final output. + #[default] + OneShot, + /// Run to completion and preserve the full message history for follow-up turns. + Persistent, +} + +/// Specification describing how to spawn an [`Agent`] for a delegated task. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SpawnSpec { + /// User prompt that starts the spawned agent's run. + pub prompt: String, + /// Conversation history policy (`Fresh` or `Fork`). + pub context: SpawnContext, + /// Lifecycle policy (`OneShot` or `Persistent`). + pub lifecycle: SpawnLifecycle, + /// Working directory for tool execution. + pub cwd: PathBuf, + /// Optional model override; falls back to the spawner's default model. + pub model: Option, + /// Optional system instruction override. + pub system_prompt: Option, + /// Optional allowlist of tool names exposed to the spawned agent. + pub allowed_tools: Option>, + /// Optional turn cap override; falls back to the spawner's default turn cap. + pub max_turns: Option, + /// Optional nesting depth cap override; falls back to the spawner's default depth cap. + pub max_depth: Option, +} + +impl SpawnSpec { + /// Creates a [`SpawnSpec`] with [`SpawnContext::Fresh`] and [`SpawnLifecycle::OneShot`]. + pub fn new(prompt: impl Into, cwd: impl Into) -> Self { + Self { + prompt: prompt.into(), + context: SpawnContext::Fresh, + lifecycle: SpawnLifecycle::OneShot, + cwd: cwd.into(), + model: None, + system_prompt: None, + allowed_tools: None, + max_turns: None, + max_depth: None, + } + } +} + +/// Errors produced when spawning or running a subagent. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum SpawnError { + /// Spawning would exceed the configured nesting depth limit. + #[error("subagent depth limit reached ({depth} >= {max_depth})")] + MaxDepthExceeded { + /// Current nesting depth of the caller. + depth: usize, + /// Configured maximum nesting depth. + max_depth: usize, + }, + + /// The spawned agent reported a runtime or wire error. + #[error("subagent error: {0}")] + AgentError(String), + + /// The agent event stream ended before emitting a terminal event. + #[error("subagent stream ended unexpectedly without completion")] + UnexpectedEnd, +} + +/// Outcome of a completed subagent run. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SpawnResult { + /// Final assistant text produced by the spawned agent. + pub text: String, + /// Total token usage summed across all turns of the run. + pub usage: Usage, + /// Total number of model turns executed. + pub turns: usize, + /// Reason the spawned agent loop terminated. + pub stop_reason: AgentStopReason, + /// Full conversation history from the run. + pub messages: Vec, +} + +/// Factory that spawns real [`Agent`] instances from a [`SpawnSpec`]. +#[derive(Clone)] +pub struct AgentSpawner { + wire: Arc, + tools: Arc, + default_model: String, + default_max_turns: usize, + default_max_depth: usize, + current_depth: usize, + hooks: HookRunner, +} + +impl AgentSpawner { + /// Creates a new [`AgentSpawner`] with [`DEFAULT_MAX_TURNS`] and [`DEFAULT_MAX_DEPTH`]. + pub fn new( + wire: Arc, + tools: Arc, + default_model: impl Into, + ) -> Self { + Self { + wire, + tools, + default_model: default_model.into(), + default_max_turns: DEFAULT_MAX_TURNS, + default_max_depth: DEFAULT_MAX_DEPTH, + current_depth: 0, + hooks: HookRunner::default(), + } + } + + /// Overrides the default maximum turns for spawned agents. + #[must_use] + pub fn with_max_turns(mut self, max_turns: usize) -> Self { + self.default_max_turns = max_turns; + self + } + + /// Overrides the default maximum nesting depth for spawned agents. + #[must_use] + pub fn with_max_depth(mut self, max_depth: usize) -> Self { + self.default_max_depth = max_depth; + self + } + + /// Sets the current nesting depth (used when constructing child spawners). + #[must_use] + pub fn with_depth(mut self, depth: usize) -> Self { + self.current_depth = depth; + self + } + + /// Attaches a [`HookRunner`] passed to every spawned [`Agent`]. + #[must_use] + pub fn with_hooks(mut self, hooks: HookRunner) -> Self { + self.hooks = hooks; + self + } + + /// Spawns an [`Agent`] configured by `spec`, runs it to completion, and collects its output. + pub async fn spawn(&self, spec: SpawnSpec) -> Result { + let max_depth = spec.max_depth.unwrap_or(self.default_max_depth); + if self.current_depth >= max_depth { + return Err(SpawnError::MaxDepthExceeded { + depth: self.current_depth, + max_depth, + }); + } + + let child_tools = self.build_child_registry(spec.allowed_tools.as_deref(), max_depth); + let tool_ctx = ToolContext::new(spec.cwd); + + let mut config = AgentConfig::new(spec.model.unwrap_or_else(|| self.default_model.clone())); + config.system = spec.system_prompt; + config.max_turns = spec.max_turns.unwrap_or(self.default_max_turns); + + let agent = Agent::new(Arc::clone(&self.wire), child_tools, tool_ctx, config) + .with_hooks(self.hooks.clone()); + + let mut messages = match spec.context { + SpawnContext::Fresh => Vec::new(), + SpawnContext::Fork(history) => history, + }; + messages.push(Message::user(spec.prompt)); + + let mut stream = agent.run(messages); + let mut usage = Usage::default(); + let mut fallback_text = String::new(); + + while let Some(event) = stream.next().await { + match event { + AgentEvent::TextDelta(delta) => fallback_text.push_str(&delta), + + AgentEvent::TurnUsage(turn_usage) => add_usage(&mut usage, turn_usage), + + AgentEvent::Done { + reason, + turns, + messages, + } => { + let text = extract_final_assistant_text(&messages).unwrap_or(fallback_text); + let returned_messages = match spec.lifecycle { + SpawnLifecycle::OneShot => Vec::new(), + SpawnLifecycle::Persistent => messages, + }; + return Ok(SpawnResult { + text, + usage, + turns, + stop_reason: reason, + messages: returned_messages, + }); + } + + AgentEvent::Error(err) => return Err(SpawnError::AgentError(err)), + + AgentEvent::ThinkingDelta(_) + | AgentEvent::ToolCallStart { .. } + | AgentEvent::ToolResult { .. } => {} + } + } + + Err(SpawnError::UnexpectedEnd) + } + + fn build_child_registry( + &self, + allowed_tools: Option<&[String]>, + max_depth: usize, + ) -> Arc { + let allowed_set: Option> = + allowed_tools.map(|list| list.iter().map(String::as_str).collect()); + let mut child = ToolRegistry::new(); + + for tool_spec in self.tools.specs() { + if let Some(allowed) = &allowed_set + && !allowed.contains(tool_spec.name.as_str()) + { + continue; + } + + if tool_spec.name == INVOKE_SUBAGENT_TOOL_NAME { + let child_spawner = self + .clone() + .with_depth(self.current_depth + 1) + .with_max_depth(max_depth); + child.register(Arc::new(InvokeSubagentTool::new(child_spawner))); + } else if let Some(tool) = self.tools.get(&tool_spec.name) { + child.register(tool); + } + } + + Arc::new(child) + } +} + +/// Spawns an [`Agent`] via `spawner` using `spec`. +pub async fn spawn_agent( + spawner: &AgentSpawner, + spec: SpawnSpec, +) -> Result { + spawner.spawn(spec).await +} + +/// Tool name registered by [`InvokeSubagentTool`]. +pub const INVOKE_SUBAGENT_TOOL_NAME: &str = "invoke_subagent"; + +/// Built-in tool that delegates a self-contained task to a spawned [`Agent`]. +pub struct InvokeSubagentTool { + spawner: AgentSpawner, +} + +impl InvokeSubagentTool { + /// Creates an [`InvokeSubagentTool`] backed by `spawner`. + pub fn new(spawner: AgentSpawner) -> Self { + Self { spawner } + } +} + +#[derive(Debug, Deserialize)] +struct InvokeSubagentArgs { + prompt: String, + model: Option, + system_prompt: Option, + allowed_tools: Option>, + max_turns: Option, +} + +#[async_trait] +impl Tool for InvokeSubagentTool { + fn spec(&self) -> ToolSpec { + ToolSpec { + name: INVOKE_SUBAGENT_TOOL_NAME.to_owned(), + description: + "Delegate a self-contained task to a fresh subagent and return its final response." + .to_owned(), + input_schema: json!({ + "type": "object", + "properties": { + "prompt": { + "type": "string", + "description": "Self-contained task instructions for the subagent." + }, + "model": { + "type": "string", + "description": "Optional model override for the subagent." + }, + "system_prompt": { + "type": "string", + "description": "Optional system prompt override for the subagent." + }, + "allowed_tools": { + "type": "array", + "items": { "type": "string" }, + "description": "Optional allowlist of tool names available to the subagent." + }, + "max_turns": { + "type": "integer", + "minimum": 1, + "description": "Optional maximum number of model turns for the subagent." + } + }, + "required": ["prompt"], + "additionalProperties": false + }), + } + } + + async fn execute(&self, ctx: &ToolContext, args: Value) -> Result { + let parsed: InvokeSubagentArgs = + serde_json::from_value(args).map_err(|err| ToolError::InvalidArgs(err.to_string()))?; + + if parsed.prompt.trim().is_empty() { + return Err(ToolError::InvalidArgs( + "prompt must not be empty".to_owned(), + )); + } + + if let Some(0) = parsed.max_turns { + return Err(ToolError::InvalidArgs( + "max_turns must be at least 1".to_owned(), + )); + } + + let mut spec = SpawnSpec::new(parsed.prompt, ctx.cwd.clone()); + spec.model = parsed.model; + spec.system_prompt = parsed.system_prompt; + spec.allowed_tools = parsed.allowed_tools; + spec.max_turns = parsed.max_turns; + + match spawn_agent(&self.spawner, spec).await { + Ok(result) => Ok(ToolOutput::ok(result.text)), + Err(err) => Ok(ToolOutput::error(err.to_string())), + } + } +} + +fn add_usage(total: &mut Usage, delta: Usage) { + total.input_tokens += delta.input_tokens; + total.output_tokens += delta.output_tokens; + total.reasoning_tokens += delta.reasoning_tokens; + total.cache_read_tokens += delta.cache_read_tokens; + total.cache_write_tokens += delta.cache_write_tokens; +} + +fn extract_final_assistant_text(messages: &[Message]) -> Option { + let assistant = messages.iter().rev().find(|m| m.role == Role::Assistant)?; + let mut out = String::new(); + for block in &assistant.content { + if let ContentBlock::Text { text } = block { + out.push_str(text); + } + } + Some(out) +} + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::sync::Mutex; + + use futures_util::stream; + use tempfile::tempdir; + + use crate::client::{ClientError, EventStream, Request, ResponseEvent, StopReason}; + + use super::*; + + type ScriptedTurn = Result>, ClientError>; + + struct ScriptedWire { + turns: Mutex>, + requests: Mutex>, + } + + impl ScriptedWire { + fn new(turns: Vec) -> Self { + Self { + turns: Mutex::new(turns.into()), + requests: Mutex::new(Vec::new()), + } + } + + fn recorded_requests(&self) -> Vec { + self.requests.lock().unwrap().clone() + } + } + + #[async_trait] + impl Wire for ScriptedWire { + async fn stream(&self, request: Request) -> Result { + self.requests.lock().unwrap().push(request); + let turn = self + .turns + .lock() + .unwrap() + .pop_front() + .expect("unexpected extra wire turn"); + let events = turn?; + Ok(Box::pin(stream::iter(events))) + } + } + + fn text_turn( + text: &str, + input_tokens: u64, + output_tokens: u64, + ) -> Vec> { + vec![ + Ok(ResponseEvent::TextDelta(text.to_owned())), + Ok(ResponseEvent::Usage(Usage { + input_tokens, + output_tokens, + ..Usage::default() + })), + Ok(ResponseEvent::Done(StopReason::EndTurn)), + ] + } + + #[tokio::test] + async fn spawn_fresh_oneshot_collects_text_and_usage() { + let dir = tempdir().unwrap(); + let wire = Arc::new(ScriptedWire::new(vec![Ok(text_turn("done!", 12, 8))])); + let tools = Arc::new(ToolRegistry::with_defaults()); + let spawner = AgentSpawner::new(wire.clone(), tools, "claude-sonnet-4-6"); + + let spec = SpawnSpec::new("summarize repo", dir.path()); + let result = spawn_agent(&spawner, spec).await.unwrap(); + + assert_eq!(result.text, "done!"); + assert_eq!(result.turns, 1); + assert_eq!( + result.stop_reason, + AgentStopReason::Completed(StopReason::EndTurn) + ); + assert_eq!(result.usage.input_tokens, 12); + assert_eq!(result.usage.output_tokens, 8); + assert_eq!(result.messages, Vec::::new()); + + let requests = wire.recorded_requests(); + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].model, "claude-sonnet-4-6"); + assert_eq!(requests[0].messages.len(), 1); + } + + #[tokio::test] + async fn spawn_fork_persistent_preserves_history_and_overrides() { + let dir = tempdir().unwrap(); + let wire = Arc::new(ScriptedWire::new(vec![Ok(text_turn("continued", 20, 10))])); + let tools = Arc::new(ToolRegistry::with_defaults()); + let spawner = AgentSpawner::new(wire.clone(), tools, "claude-sonnet-4-6") + .with_max_turns(4) + .with_hooks(HookRunner::default()); + + let mut spec = SpawnSpec::new("next step", dir.path()); + spec.context = SpawnContext::Fork(vec![Message::user("prior turn")]); + spec.lifecycle = SpawnLifecycle::Persistent; + spec.model = Some("gpt-5.4".to_owned()); + spec.system_prompt = Some("be concise".to_owned()); + spec.allowed_tools = Some(vec!["read".to_owned()]); + spec.max_turns = Some(2); + + let result = spawner.spawn(spec).await.unwrap(); + + assert_eq!(result.text, "continued"); + assert_eq!(result.messages.len(), 3); + + let requests = wire.recorded_requests(); + assert_eq!(requests[0].model, "gpt-5.4"); + assert_eq!(requests[0].system.as_deref(), Some("be concise")); + let tool_names: Vec<&str> = requests[0].tools.iter().map(|t| t.name.as_str()).collect(); + assert_eq!(tool_names, vec!["read"]); + } + + #[tokio::test] + async fn spawn_enforces_max_depth() { + let dir = tempdir().unwrap(); + let wire = Arc::new(ScriptedWire::new(vec![])); + let tools = Arc::new(ToolRegistry::new()); + let spawner = AgentSpawner::new(wire, tools, "claude-sonnet-4-6") + .with_max_depth(2) + .with_depth(2); + + let err = spawner + .spawn(SpawnSpec::new("recurse", dir.path())) + .await + .unwrap_err(); + assert_eq!( + err, + SpawnError::MaxDepthExceeded { + depth: 2, + max_depth: 2, + } + ); + } + + #[tokio::test] + async fn spawn_propagates_wire_error() { + let dir = tempdir().unwrap(); + let wire = Arc::new(ScriptedWire::new(vec![Err(ClientError::StreamParse( + "boom".to_owned(), + ))])); + let tools = Arc::new(ToolRegistry::new()); + let spawner = AgentSpawner::new(wire, tools, "claude-sonnet-4-6"); + + let err = spawner + .spawn(SpawnSpec::new("fail", dir.path())) + .await + .unwrap_err(); + assert!(matches!(err, SpawnError::AgentError(msg) if msg.contains("boom"))); + } + + #[tokio::test] + async fn invoke_subagent_tool_runs_and_enforces_nested_depth() { + let dir = tempdir().unwrap(); + let wire = Arc::new(ScriptedWire::new(vec![ + Ok(vec![ + Ok(ResponseEvent::ToolCall { + id: "call_nested".to_owned(), + name: INVOKE_SUBAGENT_TOOL_NAME.to_owned(), + arguments: json!({ "prompt": "go deeper" }), + thought_signature: None, + }), + Ok(ResponseEvent::Done(StopReason::ToolUse)), + ]), + Ok(text_turn("handled depth limit", 5, 3)), + ])); + + let mut base_tools = ToolRegistry::with_defaults(); + let spawner = AgentSpawner::new( + wire.clone(), + Arc::new(ToolRegistry::with_defaults()), + "claude-sonnet-4-6", + ) + .with_max_depth(1); + base_tools.register(Arc::new(InvokeSubagentTool::new(spawner))); + + let root_spawner = + AgentSpawner::new(wire, Arc::new(base_tools), "claude-sonnet-4-6").with_max_depth(1); + let tool = InvokeSubagentTool::new(root_spawner); + + assert_eq!(tool.spec().name, INVOKE_SUBAGENT_TOOL_NAME); + + let ctx = ToolContext::new(dir.path()); + let output = tool + .execute( + &ctx, + json!({ + "prompt": "outer task", + "model": "claude-sonnet-4-6", + "system_prompt": "delegate if needed", + "allowed_tools": ["invoke_subagent", "read"], + "max_turns": 3 + }), + ) + .await + .unwrap(); + + assert!(!output.is_error); + assert_eq!(output.content, "handled depth limit"); + } + + #[tokio::test] + async fn invoke_subagent_tool_rejects_invalid_args_and_returns_depth_error() { + let dir = tempdir().unwrap(); + let wire = Arc::new(ScriptedWire::new(vec![])); + let tools = Arc::new(ToolRegistry::new()); + let spawner = AgentSpawner::new(wire, tools, "claude-sonnet-4-6") + .with_max_depth(1) + .with_depth(1); + let tool = InvokeSubagentTool::new(spawner); + let ctx = ToolContext::new(dir.path()); + + let empty_err = tool + .execute(&ctx, json!({ "prompt": " " })) + .await + .unwrap_err(); + assert!(matches!(empty_err, ToolError::InvalidArgs(_))); + + let zero_turns_err = tool + .execute(&ctx, json!({ "prompt": "hi", "max_turns": 0 })) + .await + .unwrap_err(); + assert!(matches!(zero_turns_err, ToolError::InvalidArgs(_))); + + let depth_out = tool + .execute(&ctx, json!({ "prompt": "blocked" })) + .await + .unwrap(); + assert!(depth_out.is_error); + assert!(depth_out.content.contains("depth limit reached")); + } +} diff --git a/docs/README.md b/docs/README.md index df9433b2b..a4ed5316d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,6 +24,7 @@ Documentation for `oxide-code` (`ox`) is organized into three user-facing bucket | [Models](reference/models.md) | Data-driven model catalog TOML schema and tier profiles | | [Skills](reference/skills.md) | `SKILL.md` discovery roots, frontmatter schema, and `load_skill` | | [Statusline](reference/statusline.md) | Built-in statusline segments and external ANSI command protocol | +| [Subagents](reference/subagents.md) | Unified `Agent` + `SpawnSpec` delegation and `invoke_subagent` | | [System Prompt](reference/system-prompt.md) | Named system prompt sections and declarative Markdown overrides | | [Themes](reference/themes.md) | Built-in palettes and custom TOML theme file schema | diff --git a/docs/reference/subagents.md b/docs/reference/subagents.md new file mode 100644 index 000000000..bb43e8151 --- /dev/null +++ b/docs/reference/subagents.md @@ -0,0 +1,39 @@ +# Subagents + +`ox-core` delegates self-contained tasks through the unified `Agent` and `SpawnSpec` abstraction in `ox_core::subagent`. A spawned subagent is a regular `Agent` instance with its own `ToolContext`, optional tool allowlist, and depth limit. + +## `SpawnSpec` + +`SpawnSpec` configures how `AgentSpawner::spawn` (or `spawn_agent`) runs a child `Agent`: + +| Field | Type | Default | Purpose | +| --------------- | --------------------- | ------------------------- | ------------------------------------------------------------------ | +| `prompt` | `String` | Required | Initial user prompt sent to the spawned agent | +| `context` | `SpawnContext` | `SpawnContext::Fresh` | `Fresh` for a clean history, or `Fork(Vec)` to continue | +| `lifecycle` | `SpawnLifecycle` | `SpawnLifecycle::OneShot` | `OneShot` drops history on return, `Persistent` returns `messages` | +| `cwd` | `PathBuf` | Required | Working directory for the child `ToolContext` | +| `model` | `Option` | Spawner default | Wire model identifier override | +| `system_prompt` | `Option` | `None` | Optional system instruction override | +| `allowed_tools` | `Option>` | All registered tools | Optional allowlist of tool names exposed to the child agent | +| `max_turns` | Optional integer | Spawner default (`32`) | Maximum model turns before the child loop stops | +| `max_depth` | Optional integer | Spawner default (`3`) | Maximum nesting depth for recursive delegation | + +## Depth Enforcement and Tool Filtering + +`AgentSpawner` tracks `current_depth` (starting at `0`) and rejects any spawn where `current_depth >= max_depth` with `SpawnError::MaxDepthExceeded`. + +When `allowed_tools` is set, only tools whose names appear in the allowlist are copied into the child `ToolRegistry`. If `invoke_subagent` is included in the child registry, `AgentSpawner` automatically re-registers it with `current_depth + 1` so nested subagents inherit the remaining depth budget. + +## `invoke_subagent` Tool + +`InvokeSubagentTool` implements `Tool` under the name `invoke_subagent` so any `Agent` can delegate tasks through the same `AgentSpawner` pipeline. + +| Argument | Type | Required | Notes | +| --------------- | ----------------- | -------- | ----------------------------------------------- | +| `prompt` | `string` | Yes | Non-empty task instructions for the subagent | +| `model` | `string` | No | Model override for this delegation | +| `system_prompt` | `string` | No | System prompt override for this delegation | +| `allowed_tools` | `array` | No | Allowlist of tool names exposed to the subagent | +| `max_turns` | `integer` (`>=1`) | No | Maximum number of model turns for the subagent | + +On success, `invoke_subagent` returns the child's final assistant text. Validation errors return `ToolError::InvalidArgs`, while runtime or depth-limit failures return a tool error output so the parent model can recover. From 2c0ae6b6050f3b6af4db2a4ad2e09cb6e41fd7c8 Mon Sep 17 00:00:00 2001 From: Hakula Chen Date: Tue, 1 Dec 2026 18:24:58 +0800 Subject: [PATCH 2/3] fix(ox-core): narrow child spawner tool registry and address PR #983 review --- .cspell/words.txt | 1 + crates/ox-core/src/subagent.rs | 87 ++++++++++++++++++++++++++++++---- docs/reference/subagents.md | 4 +- 3 files changed, 82 insertions(+), 10 deletions(-) diff --git a/.cspell/words.txt b/.cspell/words.txt index 2653904e4..1125471ff 100644 --- a/.cspell/words.txt +++ b/.cspell/words.txt @@ -25,5 +25,6 @@ shfmt stdenv substituters taplo +usize WakaTime xhigh diff --git a/crates/ox-core/src/subagent.rs b/crates/ox-core/src/subagent.rs index 183e4dd65..9d496cebe 100644 --- a/crates/ox-core/src/subagent.rs +++ b/crates/ox-core/src/subagent.rs @@ -50,15 +50,15 @@ pub struct SpawnSpec { pub lifecycle: SpawnLifecycle, /// Working directory for tool execution. pub cwd: PathBuf, - /// Optional model override; falls back to the spawner's default model. + /// Optional model override. Falls back to the spawner's default model. pub model: Option, /// Optional system instruction override. pub system_prompt: Option, /// Optional allowlist of tool names exposed to the spawned agent. pub allowed_tools: Option>, - /// Optional turn cap override; falls back to the spawner's default turn cap. + /// Optional turn cap override. Falls back to the spawner's default turn cap. pub max_turns: Option, - /// Optional nesting depth cap override; falls back to the spawner's default depth cap. + /// Optional nesting depth cap override. Falls back to the spawner's default depth cap. pub max_depth: Option, } @@ -247,6 +247,7 @@ impl AgentSpawner { let allowed_set: Option> = allowed_tools.map(|list| list.iter().map(String::as_str).collect()); let mut child = ToolRegistry::new(); + let mut include_invoke = false; for tool_spec in self.tools.specs() { if let Some(allowed) = &allowed_set @@ -256,16 +257,31 @@ impl AgentSpawner { } if tool_spec.name == INVOKE_SUBAGENT_TOOL_NAME { - let child_spawner = self - .clone() - .with_depth(self.current_depth + 1) - .with_max_depth(max_depth); - child.register(Arc::new(InvokeSubagentTool::new(child_spawner))); + include_invoke = true; } else if let Some(tool) = self.tools.get(&tool_spec.name) { child.register(tool); } } + if include_invoke { + let mut narrowed = ToolRegistry::new(); + for tool_spec in child.specs() { + if let Some(tool) = child.get(&tool_spec.name) { + narrowed.register(tool); + } + } + if let Some(parent_invoke) = self.tools.get(INVOKE_SUBAGENT_TOOL_NAME) { + narrowed.register(parent_invoke); + } + + let mut child_spawner = self + .clone() + .with_depth(self.current_depth + 1) + .with_max_depth(max_depth); + child_spawner.tools = Arc::new(narrowed); + child.register(Arc::new(InvokeSubagentTool::new(child_spawner))); + } + Arc::new(child) } } @@ -294,6 +310,7 @@ impl InvokeSubagentTool { } #[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] struct InvokeSubagentArgs { prompt: String, model: Option, @@ -619,6 +636,12 @@ mod tests { .unwrap_err(); assert!(matches!(zero_turns_err, ToolError::InvalidArgs(_))); + let unknown_field_err = tool + .execute(&ctx, json!({ "prompt": "hi", "extra": true })) + .await + .unwrap_err(); + assert!(matches!(unknown_field_err, ToolError::InvalidArgs(_))); + let depth_out = tool .execute(&ctx, json!({ "prompt": "blocked" })) .await @@ -626,4 +649,52 @@ mod tests { assert!(depth_out.is_error); assert!(depth_out.content.contains("depth limit reached")); } + + #[tokio::test] + async fn nested_subagent_cannot_widen_allowed_tools() { + let dir = tempdir().unwrap(); + let wire = Arc::new(ScriptedWire::new(vec![ + Ok(vec![ + Ok(ResponseEvent::ToolCall { + id: "call_grandchild".to_owned(), + name: INVOKE_SUBAGENT_TOOL_NAME.to_owned(), + arguments: json!({ + "prompt": "grandchild task", + "allowed_tools": ["bash", "read"] + }), + thought_signature: None, + }), + Ok(ResponseEvent::Done(StopReason::ToolUse)), + ]), + Ok(text_turn("grandchild done", 4, 2)), + Ok(text_turn("child done", 6, 3)), + ])); + + let mut base_tools = ToolRegistry::with_defaults(); + let placeholder = AgentSpawner::new( + wire.clone(), + Arc::new(ToolRegistry::with_defaults()), + "claude-sonnet-4-6", + ); + base_tools.register(Arc::new(InvokeSubagentTool::new(placeholder))); + + let root_spawner = + AgentSpawner::new(wire.clone(), Arc::new(base_tools), "claude-sonnet-4-6") + .with_max_depth(3); + + let mut spec = SpawnSpec::new("child task", dir.path()); + spec.allowed_tools = Some(vec![ + INVOKE_SUBAGENT_TOOL_NAME.to_owned(), + "read".to_owned(), + ]); + + let result = root_spawner.spawn(spec).await.unwrap(); + assert_eq!(result.text, "child done"); + + let requests = wire.recorded_requests(); + assert_eq!(requests.len(), 3); + let grandchild_tools: Vec<&str> = + requests[1].tools.iter().map(|t| t.name.as_str()).collect(); + assert_eq!(grandchild_tools, vec!["read"]); + } } diff --git a/docs/reference/subagents.md b/docs/reference/subagents.md index bb43e8151..70fde3f48 100644 --- a/docs/reference/subagents.md +++ b/docs/reference/subagents.md @@ -15,8 +15,8 @@ | `model` | `Option` | Spawner default | Wire model identifier override | | `system_prompt` | `Option` | `None` | Optional system instruction override | | `allowed_tools` | `Option>` | All registered tools | Optional allowlist of tool names exposed to the child agent | -| `max_turns` | Optional integer | Spawner default (`32`) | Maximum model turns before the child loop stops | -| `max_depth` | Optional integer | Spawner default (`3`) | Maximum nesting depth for recursive delegation | +| `max_turns` | `Option` | Spawner default (`32`) | Maximum model turns before the child loop stops | +| `max_depth` | `Option` | Spawner default (`3`) | Maximum nesting depth for recursive delegation | ## Depth Enforcement and Tool Filtering From 757981ad9d2a795866b3f3bf9e69fe21d7df5b7d Mon Sep 17 00:00:00 2001 From: Hakula Chen Date: Tue, 1 Dec 2026 18:53:04 +0800 Subject: [PATCH 3/3] test(ox-core): update subagent test model IDs --- crates/ox-core/src/subagent.rs | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/ox-core/src/subagent.rs b/crates/ox-core/src/subagent.rs index 9d496cebe..541eb3920 100644 --- a/crates/ox-core/src/subagent.rs +++ b/crates/ox-core/src/subagent.rs @@ -475,7 +475,7 @@ mod tests { let dir = tempdir().unwrap(); let wire = Arc::new(ScriptedWire::new(vec![Ok(text_turn("done!", 12, 8))])); let tools = Arc::new(ToolRegistry::with_defaults()); - let spawner = AgentSpawner::new(wire.clone(), tools, "claude-sonnet-4-6"); + let spawner = AgentSpawner::new(wire.clone(), tools, "claude-sonnet-5-5"); let spec = SpawnSpec::new("summarize repo", dir.path()); let result = spawn_agent(&spawner, spec).await.unwrap(); @@ -492,7 +492,7 @@ mod tests { let requests = wire.recorded_requests(); assert_eq!(requests.len(), 1); - assert_eq!(requests[0].model, "claude-sonnet-4-6"); + assert_eq!(requests[0].model, "claude-sonnet-5-5"); assert_eq!(requests[0].messages.len(), 1); } @@ -501,14 +501,14 @@ mod tests { let dir = tempdir().unwrap(); let wire = Arc::new(ScriptedWire::new(vec![Ok(text_turn("continued", 20, 10))])); let tools = Arc::new(ToolRegistry::with_defaults()); - let spawner = AgentSpawner::new(wire.clone(), tools, "claude-sonnet-4-6") + let spawner = AgentSpawner::new(wire.clone(), tools, "claude-sonnet-5-5") .with_max_turns(4) .with_hooks(HookRunner::default()); let mut spec = SpawnSpec::new("next step", dir.path()); spec.context = SpawnContext::Fork(vec![Message::user("prior turn")]); spec.lifecycle = SpawnLifecycle::Persistent; - spec.model = Some("gpt-5.4".to_owned()); + spec.model = Some("gpt-6.2-sol".to_owned()); spec.system_prompt = Some("be concise".to_owned()); spec.allowed_tools = Some(vec!["read".to_owned()]); spec.max_turns = Some(2); @@ -519,7 +519,7 @@ mod tests { assert_eq!(result.messages.len(), 3); let requests = wire.recorded_requests(); - assert_eq!(requests[0].model, "gpt-5.4"); + assert_eq!(requests[0].model, "gpt-6.2-sol"); assert_eq!(requests[0].system.as_deref(), Some("be concise")); let tool_names: Vec<&str> = requests[0].tools.iter().map(|t| t.name.as_str()).collect(); assert_eq!(tool_names, vec!["read"]); @@ -530,7 +530,7 @@ mod tests { let dir = tempdir().unwrap(); let wire = Arc::new(ScriptedWire::new(vec![])); let tools = Arc::new(ToolRegistry::new()); - let spawner = AgentSpawner::new(wire, tools, "claude-sonnet-4-6") + let spawner = AgentSpawner::new(wire, tools, "claude-sonnet-5-5") .with_max_depth(2) .with_depth(2); @@ -554,7 +554,7 @@ mod tests { "boom".to_owned(), ))])); let tools = Arc::new(ToolRegistry::new()); - let spawner = AgentSpawner::new(wire, tools, "claude-sonnet-4-6"); + let spawner = AgentSpawner::new(wire, tools, "claude-sonnet-5-5"); let err = spawner .spawn(SpawnSpec::new("fail", dir.path())) @@ -583,13 +583,13 @@ mod tests { let spawner = AgentSpawner::new( wire.clone(), Arc::new(ToolRegistry::with_defaults()), - "claude-sonnet-4-6", + "claude-sonnet-5-5", ) .with_max_depth(1); base_tools.register(Arc::new(InvokeSubagentTool::new(spawner))); let root_spawner = - AgentSpawner::new(wire, Arc::new(base_tools), "claude-sonnet-4-6").with_max_depth(1); + AgentSpawner::new(wire, Arc::new(base_tools), "claude-sonnet-5-5").with_max_depth(1); let tool = InvokeSubagentTool::new(root_spawner); assert_eq!(tool.spec().name, INVOKE_SUBAGENT_TOOL_NAME); @@ -600,7 +600,7 @@ mod tests { &ctx, json!({ "prompt": "outer task", - "model": "claude-sonnet-4-6", + "model": "claude-sonnet-5-5", "system_prompt": "delegate if needed", "allowed_tools": ["invoke_subagent", "read"], "max_turns": 3 @@ -618,7 +618,7 @@ mod tests { let dir = tempdir().unwrap(); let wire = Arc::new(ScriptedWire::new(vec![])); let tools = Arc::new(ToolRegistry::new()); - let spawner = AgentSpawner::new(wire, tools, "claude-sonnet-4-6") + let spawner = AgentSpawner::new(wire, tools, "claude-sonnet-5-5") .with_max_depth(1) .with_depth(1); let tool = InvokeSubagentTool::new(spawner); @@ -674,12 +674,12 @@ mod tests { let placeholder = AgentSpawner::new( wire.clone(), Arc::new(ToolRegistry::with_defaults()), - "claude-sonnet-4-6", + "claude-sonnet-5-5", ); base_tools.register(Arc::new(InvokeSubagentTool::new(placeholder))); let root_spawner = - AgentSpawner::new(wire.clone(), Arc::new(base_tools), "claude-sonnet-4-6") + AgentSpawner::new(wire.clone(), Arc::new(base_tools), "claude-sonnet-5-5") .with_max_depth(3); let mut spec = SpawnSpec::new("child task", dir.path());