diff --git a/CUSTOM_DISTROS.md b/CUSTOM_DISTROS.md index be9373337..9e555c0a0 100644 --- a/CUSTOM_DISTROS.md +++ b/CUSTOM_DISTROS.md @@ -673,19 +673,18 @@ prompt: | 3. Synthesize findings from both subagents into a unified report. ``` -#### Parallel Subagent Execution +#### Multiple Subagents -Use `async: true` to run delegates in parallel, then collect each result with `load(source: "")`: +Issue several `delegate` calls in one response; each returns its subagent's result when it finishes: ```yaml prompt: | - Run these analyses in parallel: + Run these analyses: - delegate(instructions: "Count lines of code by language", async: true) - delegate(instructions: "Find all TODO comments", async: true) - delegate(instructions: "List external dependencies", async: true) + delegate(instructions: "Count lines of code by language") + delegate(instructions: "Find all TODO comments") + delegate(instructions: "List external dependencies") - Use load(source: "") for each returned task id. Then combine the results into a codebase health report. ``` @@ -801,8 +800,7 @@ prompt: | 2. **Parallelize independent tasks** - Multiple subagent calls in one message run concurrently 3. **Use `sequential_when_repeated: true`** - For tasks that shouldn't run in parallel (e.g., database migrations) 4. **Scope extensions appropriately** - Give subagents only the tools they need -5. **Use background delegation for independent work** - Pass `async: true` to `delegate`, then collect results with `load(source: "")` -6. **Handle failures gracefully** - Design workflows to continue even if one subagent fails +5. **Handle failures gracefully** - Design workflows to continue even if one subagent fails ### Technical Details diff --git a/crates/goose-cli/src/cli.rs b/crates/goose-cli/src/cli.rs index c73fa1a0f..d75b7fd45 100644 --- a/crates/goose-cli/src/cli.rs +++ b/crates/goose-cli/src/cli.rs @@ -1146,7 +1146,7 @@ enum Command { /// Disable the Rust-driven parallel orchestrator and fall back to /// the single-prompt path that asks the main agent to delegate - /// each check via `delegate(... async: true ...)`. The default + /// each check via `delegate(...)`. The default /// orchestrator dispatches one `goose run` subprocess per check /// (capped at 4 concurrent), bounding wall-clock to the slowest /// single check rather than waiting on the model to issue diff --git a/crates/goose-cli/src/commands/review/default_review_prompt.md b/crates/goose-cli/src/commands/review/default_review_prompt.md index 4a83d2cfb..8de7d7210 100644 --- a/crates/goose-cli/src/commands/review/default_review_prompt.md +++ b/crates/goose-cli/src/commands/review/default_review_prompt.md @@ -74,13 +74,12 @@ Alongside the correctness pass, walk every changed hunk and call out: ## Checks -If the request below lists subagent **checks**, **dispatch them all in -parallel** before doing anything else. For each check: +If the request below lists subagent **checks**, delegate each one before +doing your own pass. For each check: ``` delegate( instructions = , - async = true, # IMPORTANT: parallelize model = , max_turns = , ) @@ -94,14 +93,7 @@ tools at all. Treat the per-check `tools` column in the request as informational guidance for the subagent's prompt, not as an extensions filter. -This returns a `taskId` immediately. After dispatching every check, call -`load(taskId)` once per check to wait for the results. **Do not** issue -the next `delegate` call after the previous one has completed — that is -sequential and slow; we want every check executing concurrently. - -Run your own correctness pass while the subagents are in flight, so the -wall-clock time is bounded by the slowest single check rather than by -their sum. +Each `delegate` call returns the subagent's findings when it finishes. Each subagent must include the originating check's `name` in the `check` field of every finding so attribution is preserved end-to-end. diff --git a/crates/goose-cli/src/commands/review/handler.rs b/crates/goose-cli/src/commands/review/handler.rs index 2572602a2..633bbb417 100644 --- a/crates/goose-cli/src/commands/review/handler.rs +++ b/crates/goose-cli/src/commands/review/handler.rs @@ -41,7 +41,7 @@ pub struct ReviewOptions { pub quiet: bool, /// Disable the Rust-driven parallel orchestrator and fall back to the /// single-prompt path that asks the main agent to delegate checks via - /// `delegate(... async: true ...)`. Useful when comparing against the + /// `delegate(...)`. Useful when comparing against the /// in-process behavior or running on a model that handles dispatch /// reliably on its own. Checks with an explicit tool allowlist require /// the default orchestrator and are rejected on this path. diff --git a/crates/goose-cli/src/commands/review/orchestrator.rs b/crates/goose-cli/src/commands/review/orchestrator.rs index 151bd181f..d01e314ab 100644 --- a/crates/goose-cli/src/commands/review/orchestrator.rs +++ b/crates/goose-cli/src/commands/review/orchestrator.rs @@ -1,7 +1,7 @@ //! Deterministic, Rust-driven orchestration for `goose review`. //! //! The default in-process review path lets the LLM decide whether to -//! dispatch each check as a real subagent (`delegate(... async: true)`) +//! dispatch each check as a real subagent (`delegate(...)`) //! or to inline the work itself. That decision is non-deterministic and //! is the dominant source of variance we see between runs (16s in the //! best case, 60s+ when the model dispatches everything as a separate diff --git a/crates/goose/src/agents/agent.rs b/crates/goose/src/agents/agent.rs index 9cfe23786..5b9994248 100644 --- a/crates/goose/src/agents/agent.rs +++ b/crates/goose/src/agents/agent.rs @@ -1762,7 +1762,7 @@ impl Agent { &self.current_goose_mode, &self.tool_inspection_manager, )), - Arc::new(DoctorOperation), + Arc::new(DoctorOperation::new(self.config.session_manager.clone())), Arc::new(ProjectOperation), Arc::new(SkillOperation::new( self.hook_manager.clone(), @@ -2260,6 +2260,27 @@ impl Agent { } } + // Doctor repairs the provider by writing it to the session, not to this agent, and must + // run even when restoring the session's provider is what fails. + let is_doctor = + crate::agents::execute_commands::parse_slash_command(&message_text_for_trace) + .is_some_and(|parsed| parsed.command == "doctor"); + let session = session_manager + .get_session(&session_config.id, false) + .await?; + let live_provider_name = self + .provider + .lock() + .await + .as_ref() + .map(|provider| provider.get_name().to_string()); + if !is_doctor + && session.provider_name.is_some() + && session.provider_name != live_provider_name + { + self.restore_provider_from_session(&session).await?; + } + if use_state_machine { tracing::info!("dispatching reply via experimental state machine"); return self diff --git a/crates/goose/src/agents/execute_commands.rs b/crates/goose/src/agents/execute_commands.rs index 3e7bc234b..1c5fd7fd8 100644 --- a/crates/goose/src/agents/execute_commands.rs +++ b/crates/goose/src/agents/execute_commands.rs @@ -157,7 +157,11 @@ impl Agent { "compact" => self.handle_compact_command(session_id).await, "clear" => self.handle_clear_command(session_id).await, "skills" => self.handle_skills_command(session_id).await, - "doctor" => Ok(Some(crate::doctor::run(self, session_id).await?)), + "doctor" => { + let session_manager = &self.config.session_manager; + let session = session_manager.get_session(session_id, false).await?; + Ok(Some(crate::doctor::run(session_manager, &session).await?)) + } "status" => self.handle_status_command(session_id).await, "goal" => self.handle_goal_command(params_str).await, "grind" => self.handle_grind_command(params_str).await, @@ -582,7 +586,9 @@ mod tests { use super::*; use crate::conversation::message::MessageContent; use crate::recipe::Response; + use crate::session::extension_data::{EnabledExtensionsState, ExtensionData, ExtensionState}; use serde_json::json; + use std::sync::Arc; #[test] fn parse_slash_command_splits_on_literal_space() { @@ -680,10 +686,42 @@ mod tests { } #[tokio::test] async fn doctor_refuses_without_enabling_developer() { - let agent = Agent::new(); + let data_dir = tempfile::tempdir().unwrap(); + let session_manager = Arc::new(crate::session::SessionManager::new( + data_dir.path().to_path_buf(), + )); + let agent = Agent::with_config(crate::agents::AgentConfig::new( + Arc::clone(&session_manager), + Arc::new(crate::config::PermissionManager::new( + data_dir.path().to_path_buf(), + )), + None, + crate::config::GooseMode::default(), + false, + crate::agents::GoosePlatform::GooseCli, + )); + let session = session_manager + .create_session( + data_dir.path().to_path_buf(), + "doctor-test".to_string(), + crate::session::SessionType::Hidden, + crate::config::GooseMode::default(), + ) + .await + .unwrap(); + let mut extension_data = ExtensionData::default(); + EnabledExtensionsState::new(Vec::new()) + .to_extension_data(&mut extension_data) + .unwrap(); + session_manager + .update(&session.id) + .extension_data(extension_data) + .apply() + .await + .unwrap(); let response = agent - .execute_command("/doctor", "doctor-disabled-legacy-test") + .execute_command("/doctor", &session.id) .await .expect("doctor command should succeed") .expect("doctor command should return a message"); @@ -692,11 +730,5 @@ mod tests { response.as_concat_text(), crate::doctor::DEVELOPER_EXTENSION_REQUIRED_MESSAGE ); - assert!( - !agent - .extension_manager - .is_extension_enabled(crate::agents::platform_extensions::developer::EXTENSION_NAME) - .await - ); } } diff --git a/crates/goose/src/agents/platform_extensions/mod.rs b/crates/goose/src/agents/platform_extensions/mod.rs index 185d6dd4d..78fc99144 100644 --- a/crates/goose/src/agents/platform_extensions/mod.rs +++ b/crates/goose/src/agents/platform_extensions/mod.rs @@ -8,7 +8,6 @@ pub mod chatrecall; pub mod code_execution; pub mod developer; pub mod ext_manager; -pub mod orchestrator; #[cfg(feature = "scheduler")] pub mod scheduler; pub mod summarize; @@ -186,20 +185,6 @@ pub static PLATFORM_EXTENSIONS: Lazy }, ); - map.insert( - orchestrator::EXTENSION_NAME, - PlatformExtensionDef { - name: orchestrator::EXTENSION_NAME, - display_name: "Orchestrator", - description: - "Manage agent sessions: list, view, start, send messages, interrupt, and stop agents", - default_enabled: false, - unprefixed_tools: false, - hidden: true, - client_factory: |ctx| Some(Box::new(orchestrator::OrchestratorClient::new(ctx).unwrap())), - }, - ); - map.insert( tom::EXTENSION_NAME, PlatformExtensionDef { diff --git a/crates/goose/src/agents/platform_extensions/orchestrator.rs b/crates/goose/src/agents/platform_extensions/orchestrator.rs deleted file mode 100644 index 5b6ce4d8e..000000000 --- a/crates/goose/src/agents/platform_extensions/orchestrator.rs +++ /dev/null @@ -1,1061 +0,0 @@ -use crate::agents::extension::PlatformExtensionContext; -use crate::agents::mcp_client::{Error, McpClientTrait}; -use crate::agents::tool_execution::ToolCallContext; -use crate::agents::{AgentEvent, SessionConfig}; -use crate::config::{Config, GooseMode}; -use crate::context_mgmt::format_message_for_compacting; -use crate::conversation::message::Message; -use crate::conversation::Conversation; -use crate::execution::manager::AgentManager; -use crate::providers; -use crate::providers::base::Provider; -use crate::session::extension_data::EnabledExtensionsState; -use crate::session::session_manager::{Session, SessionType}; -use anyhow::Result; -use async_trait::async_trait; -use futures::StreamExt; -use rmcp::model::{ - CallToolResult, ContentBlock, Implementation, InitializeResult, JsonObject, ListToolsResult, - ServerCapabilities, Tool, -}; -use schemars::{schema_for, JsonSchema}; -use serde::{Deserialize, Serialize}; -use std::path::PathBuf; -use std::sync::Arc; -use tokio_util::sync::CancellationToken; - -pub static EXTENSION_NAME: &str = "orchestrator"; - -struct CancelTokenGuard { - manager: Arc, - session_id: String, - disarmed: bool, -} - -impl CancelTokenGuard { - fn new(manager: Arc, session_id: String) -> Self { - Self { - manager, - session_id, - disarmed: false, - } - } - - fn disarm(&mut self) { - self.disarmed = true; - } -} - -impl Drop for CancelTokenGuard { - fn drop(&mut self) { - if !self.disarmed { - let manager = self.manager.clone(); - let session_id = self.session_id.clone(); - tokio::spawn(async move { - manager.unregister_cancel_token(&session_id).await; - }); - } - } -} - -const DEFAULT_LIST_LIMIT: usize = 10; - -#[derive(Debug, Serialize, Deserialize, JsonSchema)] -struct ListSessionsParams { - /// Filter by session type: "user", "sub_agent", "scheduled", "hidden", "terminal", "gateway". - /// If omitted, returns all session types. - session_type: Option, - /// Maximum number of sessions to return (most recent first). Defaults to 10. - last_n: Option, -} - -#[derive(Debug, Serialize, Deserialize, JsonSchema)] -struct ViewSessionParams { - /// The session ID to inspect - session_id: String, - /// How to view the conversation: "first_last" returns the first and last message, - /// "summarize" calls the LLM to produce a summary. If omitted, returns first and last. - mode: Option, -} - -#[derive(Debug, Serialize, Deserialize, JsonSchema)] -struct StartAgentParams { - /// Working directory for the new agent session - working_dir: String, - /// Human-readable name for the session - name: Option, - // TODO: add a "model_tier" parameter (e.g. "fast" vs "normal") to let the orchestrator - // choose between a fast/cheap model and the default one. For now we inherit the - // orchestrator's own provider and model. -} - -#[derive(Debug, Serialize, Deserialize, JsonSchema)] -struct SendMessageParams { - /// The session ID of the agent to send a message to - session_id: String, - /// The message text to send - message: String, -} - -#[derive(Debug, Serialize, Deserialize, JsonSchema)] -struct InterruptAgentParams { - /// The session ID of the agent to interrupt - session_id: String, -} - -pub struct OrchestratorClient { - info: InitializeResult, - context: PlatformExtensionContext, -} - -impl OrchestratorClient { - pub fn new(context: PlatformExtensionContext) -> Result { - let info = InitializeResult::new(ServerCapabilities::builder().enable_tools().build()) - .with_server_info( - Implementation::new(EXTENSION_NAME, "1.0.0").with_title("Orchestrator"), - ) - .with_instructions( - "Manage agent sessions: list, view, start, send messages, and interrupt agents.", - ); - - Ok(Self { info, context }) - } - - async fn get_agent_manager(&self) -> Result, String> { - AgentManager::instance() - .await - .map_err(|e| format!("Failed to get agent manager: {}", e)) - } - - async fn get_provider(&self) -> Result, String> { - self.context - .provider - .lock() - .await - .as_ref() - .cloned() - .ok_or_else(|| "Provider not available".to_string()) - } - - async fn handle_list_sessions( - &self, - arguments: Option, - ) -> Result { - let type_filter = arguments - .as_ref() - .and_then(|args| args.get("session_type")) - .and_then(|v| v.as_str()); - - let limit = arguments - .as_ref() - .and_then(|args| args.get("last_n")) - .and_then(|v| v.as_u64()) - .map(|v| v as usize) - .unwrap_or(DEFAULT_LIST_LIMIT); - - let manager = self.get_agent_manager().await?; - - let mut sessions = if let Some(type_str) = type_filter { - let session_type: SessionType = type_str - .parse() - .map_err(|e| format!("Invalid session type '{}': {}", type_str, e))?; - self.context - .session_manager - .list_sessions_by_types(&[session_type]) - .await - .map_err(|e| format!("Failed to list sessions: {}", e))? - } else { - self.context - .session_manager - .list_sessions() - .await - .map_err(|e| format!("Failed to list sessions: {}", e))? - }; - - // Most recent first - sessions.sort_by_key(|session| std::cmp::Reverse(session.updated_at)); - let total = sessions.len(); - sessions.truncate(limit); - - if sessions.is_empty() { - return Ok(CallToolResult::success(vec![ContentBlock::text( - "No sessions found.", - )])); - } - - let active_ids = manager.list_active_session_ids().await; - - let mut lines = vec![format!( - "Showing {} of {} session(s):\n", - sessions.len(), - total - )]; - for session in &sessions { - let is_loaded = active_ids.contains(&session.id); - let is_busy = if is_loaded { - manager.is_session_busy(&session.id).await - } else { - false - }; - - let status = if is_busy { - "🔄 busy" - } else if is_loaded { - "✓ loaded" - } else { - "○ idle" - }; - - lines.push(format!( - "- **{}** ({})\n Type: {} | Status: {} | Messages: {} | Updated: {}", - session.name, - session.id, - session.session_type, - status, - session.message_count, - session.updated_at.format("%Y-%m-%d %H:%M"), - )); - } - - Ok(CallToolResult::success(vec![ContentBlock::text( - lines.join("\n"), - )])) - } - - async fn handle_view_session( - &self, - session_id_for_llm: &str, - arguments: Option, - ) -> Result { - let args = arguments.ok_or("Missing arguments")?; - let session_id = extract_string(&args, "session_id")?; - let mode = args - .get("mode") - .and_then(|v| v.as_str()) - .unwrap_or("first_last"); - - let session = self - .context - .session_manager - .get_session(&session_id, true) - .await - .map_err(|e| format!("Session '{}' not found: {}", session_id, e))?; - - let manager = self.get_agent_manager().await?; - let is_busy = manager.is_session_busy(&session_id).await; - - let mut output = vec![format!( - "# Session: {} ({})\n\nType: {} | Status: {} | Working dir: {}\nMessages: {} | Updated: {}\n", - session.name, - session.id, - session.session_type, - if is_busy { "🔄 busy" } else { "idle" }, - session.working_dir.display(), - session.message_count, - session.updated_at.format("%Y-%m-%d %H:%M"), - )]; - - match mode { - "first_last" => { - if let Some(conversation) = &session.conversation { - let messages = agent_visible_session_messages(conversation); - if messages.is_empty() { - output.push("No messages in this session.".to_string()); - } else { - output.push("## First message\n".to_string()); - output.push(format_message_for_compacting(&messages[0])); - - if messages.len() > 1 { - output.push(format!("\n*({} messages omitted)*\n", messages.len() - 2)); - output.push("## Last message\n".to_string()); - output - .push(format_message_for_compacting(&messages[messages.len() - 1])); - } - } - } else { - output.push("No messages in this session.".to_string()); - } - } - "summarize" => { - if let Some(conversation) = &session.conversation { - let messages = conversation.messages(); - if messages.is_empty() { - output.push("No messages to summarize.".to_string()); - } else { - let summary = self - .summarize_conversation(session_id_for_llm, messages) - .await?; - output.push(format!("## Summary\n\n{}", summary)); - } - } else { - output.push("No messages to summarize.".to_string()); - } - } - other => { - return Err(format!( - "Unknown mode '{}'. Use 'first_last' or 'summarize'.", - other - )); - } - } - - Ok(CallToolResult::success(vec![ContentBlock::text( - output.join("\n"), - )])) - } - - async fn summarize_conversation( - &self, - session_id: &str, - messages: &[Message], - ) -> Result { - let provider = self.get_provider().await?; - - let conversation_text = agent_visible_session_messages(&Conversation::new_unvalidated( - messages.iter().cloned(), - )) - .iter() - .map(format_message_for_compacting) - .collect::>() - .join("\n"); - - let system = - "You are a helpful assistant. Summarize the following conversation concisely, \ - capturing the key topics, decisions, and current state. Be brief."; - - let user_message = Message::user().with_text(format!( - "Summarize this conversation ({} messages):\n\n{}", - messages.len(), - conversation_text - )); - - let model_config = self.context.model_config_for_session(session_id).await?; - let (response, _usage) = crate::model_config::complete_one_shot( - provider.as_ref(), - &model_config, - session_id, - system, - &[user_message], - &[], - ) - .await - .map_err(|e| format!("LLM summarization failed: {}", e))?; - - Ok(response - .content - .iter() - .filter_map(|c| { - if let crate::conversation::message::MessageContent::Text(t) = c { - Some(t.text.clone()) - } else { - None - } - }) - .collect::>() - .join("\n")) - } - - async fn handle_start_agent( - &self, - session_id: &str, - arguments: Option, - ) -> Result { - self.authorize_start_agent(session_id).await?; - let caller = self.caller_session(session_id).await?; - - let args = arguments.ok_or("Missing arguments")?; - let working_dir = extract_string(&args, "working_dir")?; - let name = args - .get("name") - .and_then(|v| v.as_str()) - .unwrap_or("Orchestrated Agent") - .to_string(); - - let raw_path = PathBuf::from(&working_dir); - let path = if raw_path.is_absolute() { - raw_path - } else { - caller.working_dir.join(&raw_path) - }; - - let path = path - .canonicalize() - .map_err(|e| format!("Invalid working directory '{}': {}", working_dir, e))?; - - if !path.is_dir() { - return Err(format!("'{}' is not a directory", working_dir)); - } - - let mode = GooseMode::default(); - - let session = self - .context - .session_manager - .create_session(path, name.clone(), SessionType::User, mode) - .await - .map_err(|e| format!("Failed to create session: {}", e))?; - - let manager = self.get_agent_manager().await?; - let agent = manager - .get_or_create_agent(session.id.clone()) - .await - .map_err(|e| format!("Failed to create agent: {}", e))?; - - let parent_provider = self.get_provider().await?; - let extensions = EnabledExtensionsState::extensions_or_default( - Some(&caller.extension_data), - Config::global(), - ); - let model_config = self.context.model_config_for_session(session_id).await?; - let provider = providers::create(parent_provider.get_name(), extensions) - .await - .map_err(|e| format!("Failed to create provider for new agent: {}", e))?; - agent - .update_provider(provider, model_config, &session.id) - .await - .map_err(|e| format!("Failed to set provider on new agent: {}", e))?; - - Ok(CallToolResult::success(vec![ContentBlock::text(format!( - "Started agent session '{}' with ID: {}\n\nUse send_message with this session_id to interact with it.", - name, session.id - ))])) - } - - async fn authorize_start_agent(&self, session_id: &str) -> Result<(), String> { - if self.caller_session(session_id).await?.session_type == SessionType::SubAgent { - return Err("Delegated tasks cannot start agent sessions".to_string()); - } - Ok(()) - } - - async fn caller_session(&self, session_id: &str) -> Result { - self.context - .session_manager - .get_session(session_id, false) - .await - .map_err(|error| format!("Failed to get caller session: {error}")) - } - - async fn authorize_send_message( - &self, - caller_session_id: &str, - target_session_id: &str, - ) -> Result<(), String> { - let caller = self.caller_session(caller_session_id).await?; - - if target_session_id == caller_session_id { - return Err("Cannot send a message to the orchestrator's own session".into()); - } - - if caller.session_type != SessionType::SubAgent { - return Ok(()); - } - - let caller_parent_id = caller - .parent_session_id - .as_deref() - .ok_or("Delegated tasks without a parent session cannot send messages")?; - let target = self - .context - .session_manager - .get_session(target_session_id, false) - .await - .map_err(|error| format!("Failed to get target session: {error}"))?; - if target.session_type != SessionType::SubAgent - || target.parent_session_id.as_deref() != Some(caller_parent_id) - { - return Err( - "Delegated tasks can only send messages to sibling delegated sessions".into(), - ); - } - - Ok(()) - } - - async fn handle_send_message( - &self, - parent_session_id: &str, - parent_cancel: &CancellationToken, - arguments: Option, - ) -> Result { - let args = arguments.ok_or("Missing arguments")?; - let session_id = extract_string(&args, "session_id")?; - let message_text = extract_string(&args, "message")?; - - self.authorize_send_message(parent_session_id, &session_id) - .await?; - - let manager = self.get_agent_manager().await?; - - let agent = manager - .get_or_create_agent(session_id.clone()) - .await - .map_err(|e| format!("Failed to get agent for session '{}': {}", session_id, e))?; - - if agent.provider().await.is_err() { - if let Ok(parent_provider) = self.get_provider().await { - let caller = self.caller_session(parent_session_id).await?; - let extensions = EnabledExtensionsState::extensions_or_default( - Some(&caller.extension_data), - Config::global(), - ); - let model_config = self - .context - .model_config_for_session(parent_session_id) - .await?; - if let Ok(provider) = - providers::create(parent_provider.get_name(), extensions).await - { - agent - .update_provider(provider, model_config, &session_id) - .await - .map_err(|e| format!("Failed to set provider: {}", e))?; - } - } - } - - let cancel_token = CancellationToken::new(); - manager - .try_register_cancel_token(&session_id, cancel_token.clone()) - .await - .map_err(|_| { - format!( - "Session '{}' is currently busy. Use interrupt_agent first, or wait.", - session_id - ) - })?; - - let mut guard = CancelTokenGuard::new(manager.clone(), session_id.clone()); - - let user_message = Message::user().with_text(&message_text); - let session_config = SessionConfig { - id: session_id.clone(), - schedule_id: None, - max_turns: None, - retry_config: None, - }; - - let mut stream = agent - .reply( - user_message, - session_config, - crate::agents::state_machine::enabled(), - Some(cancel_token.clone()), - ) - .await - .map_err(|e| format!("Failed to start reply: {}", e))?; - - let mut response_parts: Vec = Vec::new(); - let mut cancelled = false; - - loop { - tokio::select! { - _ = parent_cancel.cancelled() => { - cancel_token.cancel(); - cancelled = true; - break; - } - event = stream.next() => { - match event { - Some(Ok(AgentEvent::Message(msg))) => { - let text = msg.as_concat_text(); - if !text.is_empty() { - response_parts.push(text); - } - } - Some(Ok(_)) => {} - Some(Err(e)) => { - response_parts.push(format!("Error during agent processing: {}", e)); - break; - } - None => break, - } - } - } - } - - drop(stream); - if cancel_token.is_cancelled() { - agent.cancel_foreground_subagents(&session_id).await; - } - guard.disarm(); - manager.unregister_cancel_token(&session_id).await; - - if cancelled { - return Err("Cancelled by parent session".into()); - } - - if response_parts.is_empty() { - Ok(CallToolResult::success(vec![ContentBlock::text( - "Agent completed without producing text output.", - )])) - } else { - Ok(CallToolResult::success(vec![ContentBlock::text(format!( - "## Response from session {}\n\n{}", - session_id, - response_parts.join("\n\n") - ))])) - } - } - - async fn handle_interrupt_agent( - &self, - arguments: Option, - ) -> Result { - let args = arguments.ok_or("Missing arguments")?; - let session_id = extract_string(&args, "session_id")?; - - let manager = self.get_agent_manager().await?; - - manager - .cancel_session(&session_id) - .await - .map_err(|e| format!("Failed to interrupt session '{}': {}", session_id, e))?; - - Ok(CallToolResult::success(vec![ContentBlock::text(format!( - "Interrupted agent session '{}'.", - session_id - ))])) - } -} - -fn agent_visible_session_messages(conversation: &Conversation) -> Vec { - conversation - .agent_visible_messages() - .into_iter() - .filter(|message| !message.is_turn_context()) - .collect() -} - -#[async_trait] -impl McpClientTrait for OrchestratorClient { - async fn list_tools( - &self, - session_id: &str, - _next_cursor: Option, - _cancel_token: CancellationToken, - ) -> Result { - let mut tools = vec![ - Tool::new( - "list_sessions".to_string(), - "List agent sessions with their status (loaded, busy, idle). Returns the most recent 10 by default. Optionally filter by session type." - .to_string(), - schema::(), - ), - Tool::new( - "view_session".to_string(), - "View a session's details and conversation. Mode 'first_last' (default) returns the first and last message. Mode 'summarize' calls the LLM to produce a conversation summary." - .to_string(), - schema::(), - ), - ]; - - if self.authorize_start_agent(session_id).await.is_ok() { - tools.push(Tool::new( - "start_agent".to_string(), - "Start a new agent session with its own working directory. Inherits the current provider and model. Returns a session_id for future interaction." - .to_string(), - schema::(), - )); - } - - tools.extend([ - Tool::new( - "send_message".to_string(), - "Send a message to an existing agent session and get the response. Returns an error if the agent is currently busy." - .to_string(), - schema::(), - ), - Tool::new( - "interrupt_agent".to_string(), - "Interrupt a busy agent by cancelling its current operation." - .to_string(), - schema::(), - ), - ]); - - Ok(ListToolsResult { - tools, - next_cursor: None, - meta: None, - ..Default::default() - }) - } - - async fn call_tool( - &self, - ctx: &ToolCallContext, - name: &str, - arguments: Option, - cancel_token: CancellationToken, - ) -> Result { - let result = match name { - "list_sessions" => self.handle_list_sessions(arguments).await, - "view_session" => self.handle_view_session(&ctx.session_id, arguments).await, - "start_agent" => self.handle_start_agent(&ctx.session_id, arguments).await, - "send_message" => { - self.handle_send_message(&ctx.session_id, &cancel_token, arguments) - .await - } - "interrupt_agent" => self.handle_interrupt_agent(arguments).await, - _ => Err(format!("Unknown tool: {}", name)), - }; - - match result { - Ok(result) => Ok(result), - Err(error) => Ok(CallToolResult::error(vec![ContentBlock::text(format!( - "Error: {}", - error - ))])), - } - } - - fn get_info(&self) -> Option<&InitializeResult> { - Some(&self.info) - } -} - -fn schema() -> JsonObject { - let mut obj = serde_json::to_value(schema_for!(T)) - .map(|v| v.as_object().unwrap().clone()) - .expect("valid schema"); - obj.entry("properties") - .or_insert_with(|| serde_json::json!({})); - obj -} - -fn extract_string(args: &JsonObject, key: &str) -> Result { - args.get(key) - .and_then(|v| v.as_str()) - .map(|s| s.to_string()) - .ok_or_else(|| format!("Missing or invalid '{}'", key)) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::conversation::message::MessageContent; - use crate::session::SessionManager; - use rmcp::model::{Annotations, Role, TextContent}; - - fn client_for(session_manager: Arc) -> OrchestratorClient { - OrchestratorClient::new(PlatformExtensionContext { - extension_manager: None, - provider: Arc::new(tokio::sync::Mutex::new(None)), - session_manager, - scheduler: None, - use_login_shell_path: false, - }) - .unwrap() - } - - async fn create_session( - session_manager: &SessionManager, - working_dir: &std::path::Path, - session_type: SessionType, - ) -> crate::session::Session { - session_manager - .create_session( - working_dir.to_path_buf(), - "orchestrator test".to_string(), - session_type, - GooseMode::default(), - ) - .await - .unwrap() - } - - async fn create_subagent_session( - session_manager: &SessionManager, - working_dir: &std::path::Path, - parent_session_id: &str, - ) -> crate::session::Session { - let session = create_session(session_manager, working_dir, SessionType::SubAgent).await; - session_manager - .update(&session.id) - .parent_session_id(Some(parent_session_id.to_string())) - .apply() - .await - .unwrap(); - session_manager - .get_session(&session.id, false) - .await - .unwrap() - } - - async fn start_agent( - client: &OrchestratorClient, - session_id: &str, - working_dir: &std::path::Path, - ) -> CallToolResult { - let arguments = serde_json::json!({ - "working_dir": working_dir.to_string_lossy(), - }) - .as_object() - .unwrap() - .clone(); - client - .call_tool( - &ToolCallContext::new(session_id.to_string(), None, None), - "start_agent", - Some(arguments), - CancellationToken::default(), - ) - .await - .unwrap() - } - - fn send_message_arguments(session_id: &str) -> JsonObject { - serde_json::json!({ - "session_id": session_id, - "message": "invoke a privileged tool", - }) - .as_object() - .unwrap() - .clone() - } - - #[test] - fn first_last_projection_drops_hidden_endpoints_and_content() { - let user_only = |text: &str| { - MessageContent::Text( - TextContent::new(text) - .with_annotations(Annotations::default().with_audience(vec![Role::User])), - ) - }; - let conversation = Conversation::new_unvalidated([ - Message::assistant().with_content(user_only("hidden first")), - Message::user().with_text("visible first"), - Message::assistant() - .with_content(user_only("hidden block")) - .with_text("visible last"), - Message::assistant().with_content(user_only("hidden last")), - ]); - - let messages = agent_visible_session_messages(&conversation); - - assert_eq!(messages.len(), 2); - assert_eq!(messages[0].as_concat_text(), "visible first"); - assert_eq!(messages[1].as_concat_text(), "visible last"); - } - - #[tokio::test] - async fn subagent_direct_call_cannot_persist_peer_user_session() { - let temp_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let subagent = - create_session(&session_manager, temp_dir.path(), SessionType::SubAgent).await; - let client = client_for(Arc::clone(&session_manager)); - - let result = start_agent(&client, &subagent.id, temp_dir.path()).await; - - assert!(result.is_error.unwrap_or(false)); - assert!(session_manager - .list_sessions_by_types(&[SessionType::User]) - .await - .unwrap() - .is_empty()); - } - - #[tokio::test] - async fn start_agent_listing_is_scoped_to_authorized_callers() { - let temp_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let user = create_session(&session_manager, temp_dir.path(), SessionType::User).await; - let subagent = - create_session(&session_manager, temp_dir.path(), SessionType::SubAgent).await; - let client = client_for(Arc::clone(&session_manager)); - - assert!(client.authorize_start_agent(&user.id).await.is_ok()); - let user_tools = client - .list_tools(&user.id, None, CancellationToken::default()) - .await - .unwrap(); - assert!(user_tools - .tools - .iter() - .any(|tool| tool.name == "start_agent")); - - for session_id in [&subagent.id, "missing-session"] { - let tools = client - .list_tools(session_id, None, CancellationToken::default()) - .await - .unwrap(); - assert!(tools.tools.iter().all(|tool| tool.name != "start_agent")); - assert!(tools.tools.iter().any(|tool| tool.name == "send_message")); - } - - assert!(client - .authorize_start_agent("missing-session") - .await - .is_err()); - } - - #[tokio::test] - async fn unknown_caller_cannot_persist_user_session() { - let temp_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let client = client_for(Arc::clone(&session_manager)); - - let result = start_agent(&client, "missing-session", temp_dir.path()).await; - - assert!(result.is_error.unwrap_or(false)); - assert!(session_manager - .list_sessions_by_types(&[SessionType::User]) - .await - .unwrap() - .is_empty()); - } - - #[tokio::test] - async fn subagent_cannot_send_message_to_parent_user_session() { - let temp_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let user = create_session(&session_manager, temp_dir.path(), SessionType::User).await; - let subagent = create_subagent_session(&session_manager, temp_dir.path(), &user.id).await; - let client = client_for(Arc::clone(&session_manager)); - - let error = client - .handle_send_message( - &subagent.id, - &CancellationToken::default(), - Some(send_message_arguments(&user.id)), - ) - .await - .unwrap_err(); - - assert_eq!( - error, - "Delegated tasks can only send messages to sibling delegated sessions" - ); - assert_eq!( - session_manager - .get_session(&user.id, true) - .await - .unwrap() - .message_count, - 0 - ); - } - - #[tokio::test] - async fn subagent_can_send_message_to_sibling_session() { - let temp_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let parent = create_session(&session_manager, temp_dir.path(), SessionType::User).await; - let caller = create_subagent_session(&session_manager, temp_dir.path(), &parent.id).await; - let target = create_subagent_session(&session_manager, temp_dir.path(), &parent.id).await; - let client = client_for(Arc::clone(&session_manager)); - - assert!(client - .authorize_send_message(&caller.id, &target.id) - .await - .is_ok()); - } - - #[tokio::test] - async fn subagent_cannot_send_message_across_delegation_trees() { - let temp_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let caller_parent = - create_session(&session_manager, temp_dir.path(), SessionType::User).await; - let target_parent = - create_session(&session_manager, temp_dir.path(), SessionType::User).await; - let caller = - create_subagent_session(&session_manager, temp_dir.path(), &caller_parent.id).await; - let target = - create_subagent_session(&session_manager, temp_dir.path(), &target_parent.id).await; - let client = client_for(Arc::clone(&session_manager)); - - let error = client - .handle_send_message( - &caller.id, - &CancellationToken::default(), - Some(send_message_arguments(&target.id)), - ) - .await - .unwrap_err(); - - assert_eq!( - error, - "Delegated tasks can only send messages to sibling delegated sessions" - ); - assert_eq!( - session_manager - .get_session(&target.id, true) - .await - .unwrap() - .message_count, - 0 - ); - } - - #[tokio::test] - async fn subagent_cannot_send_message_to_descendant_session() { - let temp_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let parent = create_session(&session_manager, temp_dir.path(), SessionType::User).await; - let caller = create_subagent_session(&session_manager, temp_dir.path(), &parent.id).await; - let descendant = - create_subagent_session(&session_manager, temp_dir.path(), &caller.id).await; - let client = client_for(Arc::clone(&session_manager)); - - let error = client - .authorize_send_message(&caller.id, &descendant.id) - .await - .unwrap_err(); - - assert_eq!( - error, - "Delegated tasks can only send messages to sibling delegated sessions" - ); - } - - #[tokio::test] - async fn subagent_without_parent_cannot_send_message() { - let temp_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let caller = create_session(&session_manager, temp_dir.path(), SessionType::SubAgent).await; - let target = create_session(&session_manager, temp_dir.path(), SessionType::SubAgent).await; - let client = client_for(Arc::clone(&session_manager)); - - let error = client - .authorize_send_message(&caller.id, &target.id) - .await - .unwrap_err(); - - assert_eq!( - error, - "Delegated tasks without a parent session cannot send messages" - ); - } - - #[tokio::test] - async fn user_can_send_message_to_user_session() { - let temp_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let caller = create_session(&session_manager, temp_dir.path(), SessionType::User).await; - let target = create_session(&session_manager, temp_dir.path(), SessionType::User).await; - let client = client_for(Arc::clone(&session_manager)); - - assert!(client - .authorize_send_message(&caller.id, &target.id) - .await - .is_ok()); - } - - #[tokio::test] - async fn unknown_caller_cannot_send_message() { - let temp_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let target = create_session(&session_manager, temp_dir.path(), SessionType::User).await; - let client = client_for(Arc::clone(&session_manager)); - - let error = client - .authorize_send_message("missing-session", &target.id) - .await - .unwrap_err(); - - assert!(error.starts_with("Failed to get caller session:")); - } -} diff --git a/crates/goose/src/agents/platform_extensions/summon.rs b/crates/goose/src/agents/platform_extensions/summon.rs index aff08a989..151a88f5d 100644 --- a/crates/goose/src/agents/platform_extensions/summon.rs +++ b/crates/goose/src/agents/platform_extensions/summon.rs @@ -1,7 +1,7 @@ use crate::agents::extension::PlatformExtensionContext; use crate::agents::final_output_tool::FinalOutputTool; use crate::agents::mcp_client::{Error, McpClientTrait}; -use crate::agents::subagent_handler::{run_subagent_task, OnMessageCallback, SubagentRunParams}; +use crate::agents::subagent_handler::{run_subagent_task, SubagentRunParams}; use crate::agents::subagent_task_config::{TaskConfig, DEFAULT_SUBAGENT_MAX_TURNS}; use crate::agents::tool_execution::{ToolCallContext, ToolCallNotificationEmitter}; use crate::agents::AgentConfig; @@ -18,56 +18,24 @@ use crate::sources::parse_frontmatter; use crate::utils::safe_truncate; use anyhow::Result; use async_trait::async_trait; -use goose_agent::operation::messages_since_kickoff; use goose_sdk_types::custom_requests::{SourceEntry, SourceType}; use rmcp::model::{ CallToolResult, ContentBlock, Implementation, InitializeResult, JsonObject, ListToolsResult, - MetaObject, Role, ServerCapabilities, ServerNotification, Tool, + MetaObject, ServerCapabilities, ServerNotification, Tool, }; use serde::Deserialize; use std::collections::HashMap; use std::future::Future; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; -use std::sync::Arc; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; +use std::time::{Duration, Instant}; use tokio::sync::Mutex; - -use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; -use tracing::{info, warn}; +use tracing::warn; pub static EXTENSION_NAME: &str = "summon"; const SUBAGENT_DESCRIPTION_BUDGET: usize = 160; -const TASK_LABEL_BUDGET: usize = 60; - -fn durable_assistant_turn_count(conversation: &crate::conversation::Conversation) -> u32 { - let Ok(messages) = messages_since_kickoff(conversation) else { - return 0; - }; - let mut turns = 0; - let mut in_assistant_block = false; - for message in messages.iter().rev() { - // Compaction summaries and continuation prompts are assistant-role - // scaffolding, but are not user-visible task turns. Ignore them - // without merging across a hidden user replay below. - if message.role == Role::Assistant && !message.is_user_visible() { - continue; - } - if message.role == Role::Assistant { - if !in_assistant_block { - turns += 1; - in_assistant_block = true; - } - } else { - in_assistant_block = false; - } - } - turns -} - fn kind_plural(kind: SourceType) -> &'static str { match kind { SourceType::Subrecipe => "Subrecipes", @@ -89,8 +57,6 @@ pub struct DelegateParams { pub max_turns: Option, pub context: Option, pub working_dir: Option, - #[serde(default)] - pub r#async: bool, } struct SubagentConfig { @@ -100,49 +66,6 @@ struct SubagentConfig { working_dir: PathBuf, max_turns: usize, } - -pub struct BackgroundTask { - pub id: String, - pub description: String, - pub started_at: Instant, - pub turns: Arc, - pub last_activity: Arc, - pub handle: JoinHandle>, - pub cancellation_token: CancellationToken, - completion_token: CancellationToken, - notification_sink: SharedNotificationSink, -} - -fn spawn_background_task(future: F) -> (JoinHandle>, CancellationToken) -where - F: Future> + Send + 'static, -{ - let completion_token = CancellationToken::new(); - let completion_guard = completion_token.clone().drop_guard(); - let handle = tokio::spawn(async move { - let _completion_guard = completion_guard; - future.await - }); - (handle, completion_token) -} - -pub struct CompletedTask { - pub id: String, - pub description: String, - pub result: Result, - pub turns_taken: u32, - pub duration: Duration, - pub completed_at: Instant, - notification_sink: SharedNotificationSink, -} - -enum NotificationSink { - Buffer(Vec), - Emitter(ToolCallNotificationEmitter), -} - -type SharedNotificationSink = Arc>; - async fn yield_to_outer_tool_stream() { // The outer select may have polled its receiver before this future queues a // notification. Keep the result pending for the following select pass so @@ -151,43 +74,6 @@ async fn yield_to_outer_tool_stream() { tokio::task::yield_now().await; } -impl NotificationSink { - fn route(&mut self, notification: ServerNotification) { - match self { - Self::Buffer(buffer) => buffer.push(notification), - Self::Emitter(emitter) => emitter.emit_best_effort(notification), - } - } - - async fn attach(&mut self, emitter: Option) { - let Some(emitter) = emitter else { - return; - }; - while let Self::Buffer(buffered) = self { - let Some(notification) = buffered.first().cloned() else { - break; - }; - emitter.emit_best_effort(notification); - yield_to_outer_tool_stream().await; - buffered.remove(0); - } - *self = Self::Emitter(emitter); - } - - fn detach(&mut self) { - if matches!(self, Self::Emitter(_)) { - *self = Self::Buffer(Vec::new()); - } - } - - fn buffered_len(&self) -> usize { - match self { - Self::Buffer(buffer) => buffer.len(), - Self::Emitter(_) => 0, - } - } -} - fn merge_subrecipe_parameters( fixed_values: Option<&HashMap>, provided_parameters: Option<&HashMap>, @@ -205,15 +91,6 @@ fn merge_subrecipe_parameters( merged } -/// Result from handle_load_task_result with structured metadata for the caller -#[derive(Debug)] -struct TaskLoadResult { - content: Vec, - status: &'static str, - turns: Option, - duration_secs: Option, -} - #[derive(Debug, Deserialize)] struct AgentMetadata { name: String, @@ -498,79 +375,20 @@ fn build_subagent_instructions(sources: &[SourceEntry]) -> String { instructions: ...)`, which runs it as an isolated subagent and \ returns its result. Use `load(source: \"\")` instead if you \ only want to read the subagent's instructions into your own \ - context. For long-running work, pass `async: true` to `delegate` — \ - it returns a task id immediately, and you collect the result later \ - with `load(source: \"\")`, which waits for completion.", + context.", )); out } -fn round_duration(d: Duration) -> String { - let secs = d.as_secs(); - if secs < 60 { - format!("{}s", (secs / 10) * 10) - } else { - format!("{}m", secs / 60) - } -} - -fn current_epoch_millis() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_millis() as u64 -} - -/// Get maximum number of concurrent background tasks -fn max_background_tasks() -> usize { - Config::global() - .get_param::("GOOSE_MAX_BACKGROUND_TASKS") - .unwrap_or(5) -} - -fn completed_task_ttl() -> Duration { - let secs = Config::global() - .get_param::("GOOSE_COMPLETED_TASK_TTL_SECS") - .unwrap_or(600); - Duration::from_secs(secs) -} - -fn is_session_id(s: &str) -> bool { - let parts: Vec<&str> = s.split('_').collect(); - parts.len() == 2 && parts[0].len() == 8 && parts[0].chars().all(|c| c.is_ascii_digit()) -} - pub struct SummonClient { info: InitializeResult, context: PlatformExtensionContext, source_cache: Mutex>, - background_tasks: BackgroundTasks, - completed_tasks: Mutex>, } type CachedSources = (Instant, PathBuf, Vec); -struct BackgroundTasks(Mutex>); - -impl std::ops::Deref for BackgroundTasks { - type Target = Mutex>; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Drop for BackgroundTasks { - fn drop(&mut self) { - if let Ok(tasks) = self.0.try_lock() { - for task in tasks.values() { - task.cancellation_token.cancel(); - } - } - } -} - impl SummonClient { pub fn new(context: PlatformExtensionContext) -> Result { let info = InitializeResult::new(ServerCapabilities::builder().enable_tools().build()) @@ -580,8 +398,6 @@ impl SummonClient { info, context, source_cache: Mutex::new(None), - background_tasks: BackgroundTasks(Mutex::new(HashMap::new())), - completed_tasks: Mutex::new(HashMap::new()), }) } @@ -616,22 +432,8 @@ impl SummonClient { Ok(session) } - fn notification_sink(emitter: Option) -> SharedNotificationSink { - Arc::new(Mutex::new(match emitter { - Some(emitter) => NotificationSink::Emitter(emitter), - None => NotificationSink::Buffer(Vec::new()), - })) - } - - async fn attach_notification_emitter( - sink: &SharedNotificationSink, - emitter: Option, - ) { - sink.lock().await.attach(emitter).await; - } - async fn run_subagent_with_notifications( - sink: SharedNotificationSink, + emitter: Option, run_subagent: Run, ) -> Result where @@ -647,14 +449,18 @@ impl SummonClient { biased; result = &mut run => { while let Ok(notification) = notification_rx.try_recv() { - sink.lock().await.route(notification); + if let Some(emitter) = &emitter { + emitter.emit_best_effort(notification); + } yield_to_outer_tool_stream().await; } yield_to_outer_tool_stream().await; return result; } Some(notification) = notification_rx.recv() => { - sink.lock().await.route(notification); + if let Some(emitter) = &emitter { + emitter.emit_best_effort(notification); + } yield_to_outer_tool_stream().await; } } @@ -668,16 +474,6 @@ impl SummonClient { "source": { "type": "string", "description": "Name of the source to load. If omitted, lists all available sources." - }, - "cancel": { - "type": "boolean", - "default": false, - "description": "For running background tasks: cancel and return output." - }, - "peek": { - "type": "boolean", - "default": false, - "description": "For running background tasks: check progress without blocking. Returns durable assistant-turn count, idle time, and recent tool activity." } } }); @@ -686,15 +482,10 @@ impl SummonClient { "load", "Load knowledge into your current context or discover available sources.\n\n\ Call with no arguments to list all available sources (subrecipes, recipes, agents).\n\ - Call with a source name to load its content into your context.\n\ - For background tasks: load(source: \"task_id\") waits for the task and returns the result.\n\ - To cancel a running task: load(source: \"task_id\", cancel: true) stops and returns output.\n\ - To check progress: load(source: \"task_id\", peek: true) returns status without blocking.\n\n\ + Call with a source name to load its content into your context.\n\n\ Examples:\n\ - load() → Lists available sources\n\ - - load(source: \"deploy\") → Loads the deploy recipe\n\ - - load(source: \"20260219_1\") → Waits for background task, then returns result\n\ - - load(source: \"20260219_1\", peek: true) → Check task progress without waiting" + - load(source: \"deploy\") → Loads the deploy recipe" .to_string(), schema.as_object().unwrap().clone(), ) @@ -746,11 +537,6 @@ impl SummonClient { "working_dir": { "type": "string", "description": "Working directory for the delegate. Must be within the parent session's working directory. Defaults to the parent's working directory." - }, - "async": { - "type": "boolean", - "default": false, - "description": "Run in background (default: false)." } } }); @@ -765,10 +551,9 @@ impl SummonClient { Effective Delegation:\n\ - Delegates know only instructions + source content\n\ - Delegates cannot coordinate. Same-file work = conflicts.\n\ - - Parallel: async: true, then load(taskId) to wait and get results. Single: sync.\n\n\ - Research (read-only): parallelize freely - delegates explore and report back.\n\ - Work (writes): partition files strictly - no two delegates touch the same file.\n\n\ - Decompose → async delegates → load(taskId) for each → synthesize." + - You get a delegate's result back once it finishes.\n\n\ + Research (read-only): delegates explore and report back.\n\ + Work (writes): partition files strictly - no two delegates touch the same file." .to_string(), schema.as_object().unwrap().clone(), ) @@ -955,27 +740,12 @@ impl SummonClient { session_id: &str, working_dir: &Path, arguments: Option, - notification_emitter: Option, ) -> Result { - self.cleanup_completed_tasks().await; - let source_name = arguments .as_ref() .and_then(|args| args.get("source")) .and_then(|v| v.as_str()); - let cancel = arguments - .as_ref() - .and_then(|args| args.get("cancel")) - .and_then(|v| v.as_bool()) - .unwrap_or(false); - - let peek = arguments - .as_ref() - .and_then(|args| args.get("peek")) - .and_then(|v| v.as_bool()) - .unwrap_or(false); - if source_name.is_none() { return self .handle_load_discovery(session_id, working_dir) @@ -985,219 +755,11 @@ impl SummonClient { let name = source_name.unwrap(); - if is_session_id(name) { - let task_result = self - .handle_load_task_result(name, cancel, peek, notification_emitter) - .await?; - let mut meta = MetaObject::new(); - meta.0.insert( - "subagent_session_id".to_string(), - serde_json::Value::String(name.to_string()), - ); - meta.0.insert( - "task_status".to_string(), - serde_json::Value::String(task_result.status.to_string()), - ); - if let Some(turns) = task_result.turns { - meta.0.insert( - "turns_taken".to_string(), - serde_json::Value::Number(turns.into()), - ); - } - if let Some(secs) = task_result.duration_secs { - meta.0.insert( - "duration_secs".to_string(), - serde_json::Value::Number(secs.into()), - ); - } - return Ok(CallToolResult::success(task_result.content).with_meta(Some(meta))); - } - self.handle_load_source(session_id, name, working_dir) .await .map(CallToolResult::success) } - async fn handle_load_task_result( - &self, - task_id: &str, - cancel: bool, - peek: bool, - notification_emitter: Option, - ) -> Result { - let mut completed = self.completed_tasks.lock().await; - - let completed_entry = completed.get(task_id).map(|task| { - ( - task.result.clone(), - task.description.clone(), - task.duration, - task.turns_taken, - Arc::clone(&task.notification_sink), - ) - }); - - if let Some((result, description, duration, turns_taken, notification_sink)) = - completed_entry - { - if !peek { - Self::attach_notification_emitter(¬ification_sink, notification_emitter).await; - completed.remove(task_id); - } - let status_key = match &result { - Ok(_) => "completed", - Err(e) if e.starts_with("Task panicked:") => "panicked", - Err(_) => "failed", - }; - let status = match status_key { - "completed" => "✓ Completed", - "panicked" => "✗ Panicked", - _ => "✗ Failed", - }; - let output = match result { - Ok(output) => output, - Err(error) => format!("Error: {}", error), - }; - return Ok(TaskLoadResult { - content: vec![ContentBlock::text(format!( - "# Background Task Result: {}\n\n\ - **Task:** {}\n\ - **Status:** {}\n\ - **Duration:** {} ({} turns)\n\n\ - ## Output\n\n{}", - task_id, - description, - status, - round_duration(duration), - turns_taken, - output - ))], - status: status_key, - turns: Some(turns_taken), - duration_secs: Some(duration.as_secs()), - }); - } - - let mut running = self.background_tasks.lock().await; - drop(completed); - if running.contains_key(task_id) { - if peek { - let task = running.get(task_id).unwrap(); - let elapsed = task.started_at.elapsed(); - let turns = Arc::clone(&task.turns); - let last_activity = Arc::clone(&task.last_activity); - let description = task.description.clone(); - let notification_sink = Arc::clone(&task.notification_sink); - - drop(running); - - let turns_taken = self.refresh_task_turns(task_id, &turns).await; - let now = current_epoch_millis(); - let last_activity_at = last_activity.load(Ordering::Relaxed); - let idle_ms = if last_activity_at == 0 { - u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX) - } else { - now.saturating_sub(last_activity_at) - }; - let buffered_count = notification_sink.lock().await.buffered_len(); - - let mut output = format!( - "# Background Task Status: {}\n\n**Task:** {}\n**Status:** ⏳ Running\n**Elapsed:** {}\n**Turns taken:** {}\n**Idle:** {}\n**Buffered tool calls:** {}", - task_id, - description, - round_duration(elapsed), - turns_taken, - round_duration(Duration::from_millis(idle_ms)), - buffered_count, - ); - - if buffered_count == 0 && last_activity_at == 0 { - output.push_str("\n\n_Task is initialising (no tool activity yet)._"); - } - - return Ok(TaskLoadResult { - content: vec![ContentBlock::text(output)], - status: "running", - turns: Some(turns_taken), - duration_secs: Some(elapsed.as_secs()), - }); - } - - if cancel { - let notification_sink = - Arc::clone(&running.get(task_id).unwrap().notification_sink); - Self::attach_notification_emitter(¬ification_sink, notification_emitter).await; - let task = running.remove(task_id).unwrap(); - drop(running); - task.cancellation_token.cancel(); - - let mut handle = task.handle; - let output = tokio::select! { - result = &mut handle => { - match result { - Ok(Ok(s)) => s, - Ok(Err(e)) => format!("Error: {}", e), - Err(e) => format!("Task panicked: {}", e), - } - } - _ = tokio::time::sleep(Duration::from_secs(5)) => { - handle.abort(); - "Task did not stop in time (aborted)".to_string() - } - }; - let duration = task.started_at.elapsed(); - let turns_taken = self.refresh_task_turns(task_id, &task.turns).await; - - return Ok(TaskLoadResult { - content: vec![ContentBlock::text(format!( - "# Background Task Result: {}\n\n\ - **Task:** {}\n\ - **Status:** ⊘ Cancelled\n\ - **Duration:** {} ({} turns)\n\n\ - ## Output\n\n{}", - task_id, - task.description, - round_duration(duration), - turns_taken, - output - ))], - status: "cancelled", - turns: Some(turns_taken), - duration_secs: Some(duration.as_secs()), - }); - } - - // Wait for the running task to complete, keeping the tool call - // alive so notifications (subagent tool calls) stream in real time. - let task = running.get(task_id).unwrap(); - let notification_sink = Arc::clone(&task.notification_sink); - let completion_token = task.completion_token.clone(); - drop(running); - Self::attach_notification_emitter(¬ification_sink, notification_emitter).await; - - tokio::select! { - _ = self.wait_for_background_task_completion(task_id, &completion_token) => { - self.cleanup_completed_tasks().await; - return Box::pin( - self.handle_load_task_result(task_id, false, false, None) - ) - .await; - } - _ = tokio::time::sleep(Duration::from_secs(300)) => { - notification_sink.lock().await.detach(); - - return Err(format!( - "Task '{task_id}' is still running after waiting 5 min. \ - Use load(source: \"{task_id}\") to wait again, or \ - load(source: \"{task_id}\", cancel: true) to stop." - )); - } - } - } - - Err(format!("Task '{}' not found.", task_id)) - } - async fn handle_load_discovery( &self, session_id: &str, @@ -1209,9 +771,8 @@ impl SummonClient { } let sources = self.get_sources(session_id, working_dir).await; - let completed = self.completed_tasks.lock().await; - if sources.is_empty() && completed.is_empty() { + if sources.is_empty() { return Ok(vec![ContentBlock::text( "No sources available for load/delegate.\n\n\ Sources are discovered from:\n\ @@ -1224,23 +785,6 @@ impl SummonClient { let mut output = String::from("Available sources for load/delegate:\n"); - if !completed.is_empty() { - output.push_str("\nCompleted Tasks (awaiting retrieval):\n"); - let mut sorted_completed: Vec<_> = completed.values().collect(); - sorted_completed.sort_by_key(|t| &t.id); - for task in sorted_completed { - let status = if task.result.is_ok() { - "completed" - } else { - "failed" - }; - output.push_str(&format!( - "• {} - \"{}\" ({})\n", - task.id, task.description, status - )); - } - } - for kind in [SourceType::Subrecipe, SourceType::Recipe, SourceType::Agent] { let kind_sources: Vec<_> = sources.iter().filter(|s| s.source_type == kind).collect(); if !kind_sources.is_empty() { @@ -1325,8 +869,6 @@ impl SummonClient { notification_emitter: Option, from_state_machine: bool, ) -> Result { - self.cleanup_completed_tasks().await; - let params: DelegateParams = arguments .map(|args| serde_json::from_value(serde_json::Value::Object(args))) .transpose() @@ -1347,27 +889,10 @@ impl SummonClient { return Err("Delegated tasks cannot spawn further delegations".to_string()); } - // TODO: When retiring the legacy loop, remove the async parameter and background-task - // options/guidance in create_delegate_tool and create_load_tool. In - // build_subagent_instructions, remove only the "For long-running work" sentence. - // Keep the remaining guidance. - // Context: https://github.com/aaif-goose/goose/pull/12632 if from_state_machine { return self.handle_foreground_delegate(params, &session).await; } - if params.r#async { - let (content, task_id) = self - .handle_async_delegate(session_id, params, session) - .await?; - let mut meta = MetaObject::new(); - meta.0.insert( - "subagent_session_id".to_string(), - serde_json::Value::String(task_id), - ); - return Ok(CallToolResult::success(content).with_meta(Some(meta))); - } - let recipe = self .build_delegate_recipe(¶ms, session_id, working_dir) .await?; @@ -1408,18 +933,15 @@ impl SummonClient { return_last_only: true, session_id: subagent_session.id, cancellation_token: Some(cancellation_token), - on_message: None, notification_tx: None, }; - let result = Self::run_subagent_with_notifications( - Self::notification_sink(notification_emitter), - move |notification_tx| { + let result = + Self::run_subagent_with_notifications(notification_emitter, move |notification_tx| { let mut params = params; params.notification_tx = Some(notification_tx); run_subagent_task(params) - }, - ) - .await; + }) + .await; let mut meta = MetaObject::new(); meta.0.insert( @@ -1982,252 +1504,6 @@ impl SummonClient { }) .unwrap_or(DEFAULT_SUBAGENT_MAX_TURNS) } - - /// Count durable, user-visible assistant blocks in the active task turn, - /// excluding assistant-only compaction scaffolding. - async fn refresh_task_turns(&self, task_id: &str, cached_turns: &AtomicU32) -> u32 { - match self - .context - .session_manager - .get_session(task_id, true) - .await - { - Ok(session) => { - let turns = session - .conversation - .as_ref() - .map(durable_assistant_turn_count) - .unwrap_or_default(); - cached_turns.store(turns, Ordering::Relaxed); - turns - } - Err(error) => { - warn!( - "Failed to refresh turn count for background task {}: {}", - task_id, error - ); - cached_turns.load(Ordering::Relaxed) - } - } - } - - async fn refresh_running_task_turns(&self) -> HashMap { - let tasks: Vec<_> = self - .background_tasks - .lock() - .await - .values() - .map(|task| (task.id.clone(), Arc::clone(&task.turns))) - .collect(); - let mut refreshed = HashMap::with_capacity(tasks.len()); - for (id, turns) in tasks { - let count = self.refresh_task_turns(&id, &turns).await; - refreshed.insert(id, count); - } - refreshed - } - - async fn wait_for_background_task_completion( - &self, - task_id: &str, - completion_token: &CancellationToken, - ) { - completion_token.cancelled().await; - loop { - let finished_or_moved = self - .background_tasks - .lock() - .await - .get(task_id) - .map(|task| task.handle.is_finished()) - .unwrap_or(true); - if finished_or_moved { - return; - } - tokio::task::yield_now().await; - } - } - - async fn cleanup_completed_tasks(&self) { - let finished: Vec<(String, Arc)> = self - .background_tasks - .lock() - .await - .iter() - .filter(|(_, task)| task.handle.is_finished()) - .map(|(id, task)| (id.clone(), Arc::clone(&task.turns))) - .collect(); - - let mut refreshed = HashMap::with_capacity(finished.len()); - for (id, turns) in &finished { - let count = self.refresh_task_turns(id, turns).await; - refreshed.insert(id.clone(), count); - } - - // Keep the same lock order as task lookup so the running -> completed - // transition is atomic from callers' perspective. - let mut completed = self.completed_tasks.lock().await; - let mut tasks = self.background_tasks.lock().await; - for (id, _) in finished { - let Some(task) = tasks.remove(&id) else { - continue; - }; - let turns_taken = refreshed - .remove(&id) - .unwrap_or_else(|| task.turns.load(Ordering::Relaxed)); - let duration = task.started_at.elapsed(); - - let result = match task.handle.await { - Ok(Ok(output)) => { - info!("Background task {} completed successfully", id); - Ok(output) - } - Ok(Err(e)) => { - warn!("Background task {} failed: {}", id, e); - Err(e.to_string()) - } - Err(e) => { - warn!("Background task {} panicked: {}", id, e); - Err(format!("Task panicked: {}", e)) - } - }; - - completed.insert( - id.clone(), - CompletedTask { - id, - description: task.description, - result, - turns_taken, - duration, - completed_at: Instant::now(), - notification_sink: task.notification_sink, - }, - ); - } - - let ttl = completed_task_ttl(); - completed.retain(|_id, task| task.completed_at.elapsed() <= ttl); - } - - fn get_task_description(params: &DelegateParams) -> String { - match (¶ms.source, ¶ms.instructions) { - (Some(source), Some(instructions)) => format!("{}: {}", source, instructions), - (Some(source), None) => source.clone(), - (None, Some(instructions)) => instructions.clone(), - (None, None) => "Unknown task".to_string(), - } - } - - async fn handle_async_delegate( - &self, - session_id: &str, - params: DelegateParams, - session: crate::session::Session, - ) -> Result<(Vec, String), String> { - let task_count = self.background_tasks.lock().await.len(); - let max_tasks = max_background_tasks(); - if task_count >= max_tasks { - return Err(format!( - "Maximum {} background tasks already running. Wait for completion or use sync mode.", - max_tasks - )); - } - - let working_dir = session.working_dir.clone(); - let recipe = self - .build_delegate_recipe(¶ms, session_id, &working_dir) - .await?; - - let task_config = self - .build_task_config(¶ms, &recipe, &session) - .await - .map_err(|e| format!("Failed to build task config: {}", e))?; - - let description = safe_truncate(&Self::get_task_description(¶ms), TASK_LABEL_BUDGET); - - // Subagents must use Auto until get_agent_messages forwards - // ActionRequired messages to the parent. Until then, any mode - // that requires approval will hang on the subagent's confirmation_rx. - let mut agent_config = AgentConfig::new( - self.context.session_manager.clone(), - crate::config::permission::PermissionManager::instance(), - None, - GooseMode::Auto, - true, // disable session naming for subagents - crate::agents::GoosePlatform::GooseCli, - ) - .with_use_login_shell_path(self.context.use_login_shell_path); - agent_config.is_subagent = true; - - let subagent_session = self - .create_subagent_session( - &task_config.parent_working_dir, - &task_config.parent_session_id, - description.clone(), - ) - .await?; - - let task_id = subagent_session.id.clone(); - - let turns = Arc::new(AtomicU32::new(0)); - let last_activity = Arc::new(AtomicU64::new(0)); - - let last_activity_clone = Arc::clone(&last_activity); - - let on_message: OnMessageCallback = Arc::new(move |_msg| { - last_activity_clone.store(current_epoch_millis(), Ordering::Relaxed); - }); - - let task_token = CancellationToken::new(); - let task_token_clone = task_token.clone(); - - let notification_sink = Self::notification_sink(None); - let task_notification_sink = Arc::clone(¬ification_sink); - - let (handle, completion_token) = spawn_background_task(async move { - let params = SubagentRunParams { - config: agent_config, - recipe, - task_config, - return_last_only: true, - session_id: subagent_session.id, - cancellation_token: Some(task_token_clone), - on_message: Some(on_message), - notification_tx: None, - }; - Self::run_subagent_with_notifications(task_notification_sink, move |notification_tx| { - let mut params = params; - params.notification_tx = Some(notification_tx); - run_subagent_task(params) - }) - .await - }); - - let task = BackgroundTask { - id: task_id.clone(), - description: description.clone(), - started_at: Instant::now(), - turns, - last_activity, - handle, - cancellation_token: task_token, - completion_token, - notification_sink, - }; - - self.background_tasks - .lock() - .await - .insert(task_id.clone(), task); - - let content = vec![ContentBlock::text(format!( - "Task {} started in background: \"{}\"\n\ - Continue with other work. When you need the result, use load(source: \"{}\").", - task_id, description, task_id - ))]; - Ok((content, task_id)) - } } #[async_trait] @@ -2238,8 +1514,6 @@ impl McpClientTrait for SummonClient { _next_cursor: Option, _cancellation_token: CancellationToken, ) -> Result { - self.cleanup_completed_tasks().await; - let is_subagent = self .context .session_manager @@ -2272,15 +1546,7 @@ impl McpClientTrait for SummonClient { let session_id = &ctx.session_id; let working_dir = self.working_dir(ctx); match name { - "load" => match self - .handle_load( - session_id, - &working_dir, - arguments, - ctx.notification_emitter().cloned(), - ) - .await - { + "load" => match self.handle_load(session_id, &working_dir, arguments).await { Ok(result) => Ok(result), Err(error) => Ok(CallToolResult::error(vec![ContentBlock::text(format!( "Error: {}", @@ -2322,75 +1588,6 @@ impl McpClientTrait for SummonClient { let instructions = build_subagent_instructions(&sources); (!instructions.is_empty()).then_some(instructions) } - - async fn get_moim(&self, _session_id: &str, _tools: &[Tool]) -> Option { - self.cleanup_completed_tasks().await; - let refreshed_turns = self.refresh_running_task_turns().await; - - let completed = self.completed_tasks.lock().await; - let running = self.background_tasks.lock().await; - - if running.is_empty() && completed.is_empty() { - return None; - } - - let mut lines = vec!["Background tasks:".to_string()]; - let now = current_epoch_millis(); - - let mut sorted_running: Vec<_> = running.values().collect(); - sorted_running.sort_by_key(|task| &task.id); - - for task in sorted_running { - let elapsed = task.started_at.elapsed(); - let last_activity_at = task.last_activity.load(Ordering::Relaxed); - let idle_ms = if last_activity_at == 0 { - u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX) - } else { - now.saturating_sub(last_activity_at) - }; - - lines.push(format!( - "• {}: \"{}\" - running {}, {} turns, idle {}", - task.id, - task.description, - round_duration(elapsed), - refreshed_turns - .get(&task.id) - .copied() - .unwrap_or_else(|| task.turns.load(Ordering::Relaxed)), - round_duration(Duration::from_millis(idle_ms)), - )); - } - - let mut sorted_completed: Vec<_> = completed.values().collect(); - sorted_completed.sort_by_key(|task| &task.id); - - for task in sorted_completed { - let status = if task.result.is_ok() { - "completed" - } else { - "failed" - }; - lines.push(format!( - "• {}: \"{}\" - {} in {} ({} turns) - use load(\"{}\") to get result", - task.id, - task.description, - status, - round_duration(task.duration), - task.turns_taken, - task.id - )); - } - - if !running.is_empty() { - lines.push( - "\n→ Use load(source: \"\") to wait for a task, or load(source: \"\", cancel: true) to stop it" - .to_string(), - ); - } - - Some(lines.join("\n")) - } } /// Resolve a requested `working_dir` override against the parent session @@ -2450,29 +1647,6 @@ mod tests { } } - async fn create_test_subagent_session( - session_manager: &crate::session::SessionManager, - working_dir: &Path, - messages: &[Message], - ) -> String { - let session = session_manager - .create_session( - working_dir.to_path_buf(), - "Background task".to_string(), - SessionType::SubAgent, - GooseMode::Auto, - ) - .await - .unwrap(); - for message in messages { - session_manager - .add_message(&session.id, message) - .await - .unwrap(); - } - session.id - } - #[tokio::test] #[serial] async fn foreground_delegate_persists_child_without_creating_provider() { @@ -2504,7 +1678,6 @@ mod tests { SummonClient::new(create_test_context_with_session_manager(manager.clone())).unwrap(); let args = serde_json::json!({ "instructions": "Review the change", - "async": true, "provider": "openai", "model": "test-model", "extensions": [], @@ -2707,35 +1880,6 @@ mod tests { assert!(!text.text.contains("new instructions")); } - #[tokio::test] - async fn background_tasks_are_cancelled_when_the_client_drops() { - let client = SummonClient::new(create_test_context()).unwrap(); - let cancellation_token = CancellationToken::new(); - let task_token = cancellation_token.clone(); - let handle = tokio::spawn(async move { - task_token.cancelled().await; - Ok("cancelled".to_string()) - }); - client.background_tasks.lock().await.insert( - "task".to_string(), - BackgroundTask { - id: "task".to_string(), - description: "task".to_string(), - started_at: Instant::now(), - turns: Arc::new(AtomicU32::new(0)), - last_activity: Arc::new(AtomicU64::new(current_epoch_millis())), - handle, - cancellation_token: cancellation_token.clone(), - completion_token: CancellationToken::new(), - notification_sink: buffered_notification_sink(Vec::new()), - }, - ); - - drop(client); - - assert!(cancellation_token.is_cancelled()); - } - #[test] fn test_agent_frontmatter_parsing() { let agent = r#"--- @@ -3127,43 +2271,6 @@ You review code."#; assert!(result.is_error.unwrap_or(false)); } - #[test] - fn test_duration_rounding_for_moim() { - assert_eq!(round_duration(Duration::from_secs(5)), "0s"); - assert_eq!(round_duration(Duration::from_secs(15)), "10s"); - assert_eq!(round_duration(Duration::from_secs(59)), "50s"); - - assert_eq!(round_duration(Duration::from_secs(60)), "1m"); - assert_eq!(round_duration(Duration::from_secs(90)), "1m"); - assert_eq!(round_duration(Duration::from_secs(120)), "2m"); - } - - #[test] - fn test_task_description_formatting() { - let make_params = |source: Option<&str>, instructions: Option<&str>| DelegateParams { - source: source.map(String::from), - instructions: instructions.map(String::from), - ..Default::default() - }; - - assert_eq!( - SummonClient::get_task_description(&make_params(Some("recipe"), None)), - "recipe" - ); - assert_eq!( - SummonClient::get_task_description(&make_params(None, Some("do stuff"))), - "do stuff" - ); - assert_eq!( - SummonClient::get_task_description(&make_params(Some("r"), Some("task"))), - "r: task" - ); - assert_eq!( - SummonClient::get_task_description(&make_params(None, None)), - "Unknown task" - ); - } - #[tokio::test] async fn test_context_injected_into_adhoc_recipe() { let temp_dir = TempDir::new().unwrap(); @@ -3552,14 +2659,6 @@ You review code."#; ); } - fn extract_text(content: &ContentBlock) -> &str { - use rmcp::model::ContentBlock; - match content { - ContentBlock::Text(t) => t.text.as_str(), - _ => panic!("Expected text content"), - } - } - #[tokio::test] #[serial] async fn test_resolve_model_config_env_var_overrides_params_model() { @@ -3832,45 +2931,32 @@ You review code."#; (ToolCallNotificationEmitter::new(sender), receiver) } - fn buffered_notification_sink( - notifications: Vec, - ) -> SharedNotificationSink { - Arc::new(Mutex::new(NotificationSink::Buffer(notifications))) - } - - #[test] - fn test_is_session_id() { - assert!(is_session_id("20260204_1")); - assert!(is_session_id("20260204_42")); - assert!(is_session_id("20260204_999")); - assert!(!is_session_id("task_12345_0001")); - assert!(!is_session_id("my-recipe")); - assert!(!is_session_id("2026020_1")); - assert!(!is_session_id("20260204")); - } - #[tokio::test] async fn test_notification_sinks_isolate_concurrent_delegate_calls() { let (emitter_a, mut notifications_a) = notification_channel(); let (emitter_b, mut notifications_b) = notification_channel(); - let sink_a = SummonClient::notification_sink(Some(emitter_a)); - let sink_b = SummonClient::notification_sink(Some(emitter_b)); let (result_a, result_b) = tokio::join!( - SummonClient::run_subagent_with_notifications(sink_a, |notification_tx| async move { - notification_tx - .send(test_tool_notification("inner-a", "subagent-a")) - .unwrap(); - tokio::task::yield_now().await; - Ok("delegate-a".to_string()) - }), - SummonClient::run_subagent_with_notifications(sink_b, |notification_tx| async move { - notification_tx - .send(test_tool_notification("inner-b", "subagent-b")) - .unwrap(); - tokio::task::yield_now().await; - Ok("delegate-b".to_string()) - }) + SummonClient::run_subagent_with_notifications( + Some(emitter_a), + |notification_tx| async move { + notification_tx + .send(test_tool_notification("inner-a", "subagent-a")) + .unwrap(); + tokio::task::yield_now().await; + Ok("delegate-a".to_string()) + } + ), + SummonClient::run_subagent_with_notifications( + Some(emitter_b), + |notification_tx| async move { + notification_tx + .send(test_tool_notification("inner-b", "subagent-b")) + .unwrap(); + tokio::task::yield_now().await; + Ok("delegate-b".to_string()) + } + ) ); assert_eq!(result_a.unwrap(), "delegate-a"); assert_eq!(result_b.unwrap(), "delegate-b"); @@ -3896,13 +2982,12 @@ You review code."#; for _ in 0..32 { let (emitter, notifications) = notification_channel(); - let sink = SummonClient::notification_sink(Some(emitter)); let mut output = tool_stream( ReceiverStream::new(notifications), futures::stream::empty(), async move { let result = SummonClient::run_subagent_with_notifications( - sink, + Some(emitter), |notification_tx| async move { for command in ["inner-live-0", "inner-live-1", "inner-live-2"] { notification_tx @@ -3942,834 +3027,4 @@ You review code."#; assert!(output.next().await.is_none()); } } - - #[tokio::test] - async fn test_async_completion_before_load_replays_notifications() { - use crate::agents::tool_execution::{tool_stream, ToolStreamItem}; - use tokio_stream::wrappers::ReceiverStream; - - let client = Arc::new(SummonClient::new(create_test_context()).unwrap()); - let task_id = "20260204_1"; - let buffered = vec![test_tool_notification("inner-completed", task_id)]; - client.completed_tasks.lock().await.insert( - task_id.to_string(), - CompletedTask { - id: task_id.to_string(), - description: "Completed task".to_string(), - result: Ok("done".to_string()), - turns_taken: 1, - duration: Duration::from_secs(1), - completed_at: Instant::now(), - notification_sink: buffered_notification_sink(buffered), - }, - ); - let (emitter, notifications) = notification_channel(); - let load_client = Arc::clone(&client); - let mut output = tool_stream( - ReceiverStream::new(notifications), - futures::stream::empty(), - async move { - let result = load_client - .handle_load_task_result(task_id, false, false, Some(emitter)) - .await - .unwrap(); - Ok::<_, rmcp::model::ErrorData>(CallToolResult::success(result.content)) - }, - ); - - let ToolStreamItem::Message(notification) = output.next().await.unwrap() else { - panic!("buffered notification must be emitted before the load result"); - }; - assert_eq!( - notification_subagent_id(¬ification).as_deref(), - Some(task_id) - ); - assert_eq!( - notification_command(¬ification).as_deref(), - Some("inner-completed") - ); - let ToolStreamItem::Result(result) = output.next().await.unwrap() else { - panic!("load result must follow buffered notifications"); - }; - assert!(result.is_ok()); - assert!(output.next().await.is_none()); - assert!(!client.completed_tasks.lock().await.contains_key(task_id)); - } - - #[tokio::test] - async fn test_cancelled_completed_load_remains_retrievable() { - let client = Arc::new(SummonClient::new(create_test_context()).unwrap()); - let task_id = "20260204_1"; - client.completed_tasks.lock().await.insert( - task_id.to_string(), - CompletedTask { - id: task_id.to_string(), - description: "Completed task".to_string(), - result: Ok("done".to_string()), - turns_taken: 1, - duration: Duration::from_secs(1), - completed_at: Instant::now(), - notification_sink: buffered_notification_sink(vec![ - test_tool_notification("inner-0", task_id), - test_tool_notification("inner-1", task_id), - ]), - }, - ); - let (emitter, mut notifications) = notification_channel(); - let load_client = Arc::clone(&client); - let load = tokio::spawn(async move { - load_client - .handle_load_task_result(task_id, false, false, Some(emitter)) - .await - }); - - let first = notifications.recv().await.unwrap(); - assert_eq!(notification_command(&first).as_deref(), Some("inner-0")); - load.abort(); - assert!(load.await.unwrap_err().is_cancelled()); - assert!(client.completed_tasks.lock().await.contains_key(task_id)); - - let (retry_emitter, mut retry_notifications) = notification_channel(); - let result = client - .handle_load_task_result(task_id, false, false, Some(retry_emitter)) - .await - .unwrap(); - - assert_eq!(result.status, "completed"); - for command in ["inner-0", "inner-1"] { - let notification = retry_notifications.try_recv().unwrap(); - assert_eq!( - notification_command(¬ification).as_deref(), - Some(command) - ); - } - assert!(retry_notifications.try_recv().is_err()); - assert!(!client.completed_tasks.lock().await.contains_key(task_id)); - } - - #[tokio::test] - async fn test_buffered_replay_preserves_order_and_emitter_capacity() { - let sink = buffered_notification_sink( - (0..33) - .map(|index| test_tool_notification(&format!("inner-{index}"), "subagent")) - .collect(), - ); - let (emitter, mut notifications) = notification_channel(); - - SummonClient::attach_notification_emitter(&sink, Some(emitter)).await; - - for index in 0..32 { - let notification = notifications.try_recv().unwrap(); - assert_eq!( - notification_command(¬ification), - Some(format!("inner-{index}")) - ); - } - assert!(notifications.try_recv().is_err()); - } - - #[tokio::test] - async fn test_load_completes_when_caller_does_not_consume_notifications() { - let client = SummonClient::new(create_test_context()).unwrap(); - let task_id = "20260204_1"; - client.completed_tasks.lock().await.insert( - task_id.to_string(), - CompletedTask { - id: task_id.to_string(), - description: "Completed task".to_string(), - result: Ok("done".to_string()), - turns_taken: 1, - duration: Duration::from_secs(1), - completed_at: Instant::now(), - notification_sink: buffered_notification_sink( - (0..64) - .map(|index| test_tool_notification(&format!("inner-{index}"), task_id)) - .collect(), - ), - }, - ); - let (emitter, _notifications) = notification_channel(); - - let result = tokio::time::timeout( - Duration::from_secs(1), - client.handle_load_task_result(task_id, false, false, Some(emitter)), - ) - .await - .expect("load must not wait for a notification consumer") - .unwrap(); - - assert_eq!(result.status, "completed"); - } - - #[tokio::test] - async fn test_async_task_result_lifecycle() { - let client = SummonClient::new(create_test_context()).unwrap(); - let temp_dir = TempDir::new().unwrap(); - - let result = client - .handle_load_task_result("20260204_999", false, false, None) - .await; - assert!(result.is_err()); - assert!(result.unwrap_err().contains("not found")); - - { - let notification_sink = - buffered_notification_sink(vec![test_tool_notification("req1", "20260204_1")]); - let (handle, completion_token) = spawn_background_task(async { - tokio::time::sleep(Duration::from_millis(50)).await; - Ok("done".to_string()) - }); - - let mut running = client.background_tasks.lock().await; - running.insert( - "20260204_1".to_string(), - BackgroundTask { - id: "20260204_1".to_string(), - description: "Running task".to_string(), - started_at: Instant::now(), - turns: Arc::new(AtomicU32::new(2)), - last_activity: Arc::new(AtomicU64::new(current_epoch_millis())), - handle, - cancellation_token: CancellationToken::new(), - completion_token, - notification_sink, - }, - ); - } - - let (emitter, mut notifications) = notification_channel(); - let (result, notification) = tokio::join!( - client.handle_load_task_result("20260204_1", false, false, Some(emitter)), - notifications.recv() - ); - let result = result.expect("load should wait and return result"); - let text = extract_text(&result.content[0]); - assert!(text.contains("Completed")); - assert!(text.contains("done")); - - let notif = notification.expect("load emitter should receive buffered notification"); - if let ServerNotification::LoggingMessageNotification(log) = notif { - let params = serde_json::to_value(&log.params).unwrap(); - let data = params.get("data").and_then(|v| v.as_object()).unwrap(); - assert_eq!( - data.get("subagent_id").and_then(|v| v.as_str()), - Some("20260204_1") - ); - } else { - panic!("expected logging notification"); - } - - { - let mut completed = client.completed_tasks.lock().await; - completed.insert( - "20260204_2".to_string(), - CompletedTask { - id: "20260204_2".to_string(), - description: "Successful task".to_string(), - result: Ok("Task completed successfully with output".to_string()), - turns_taken: 5, - duration: Duration::from_secs(60), - completed_at: Instant::now(), - notification_sink: buffered_notification_sink(Vec::new()), - }, - ); - completed.insert( - "20260204_3".to_string(), - CompletedTask { - id: "20260204_3".to_string(), - description: "Failed task".to_string(), - result: Err("Something went wrong".to_string()), - turns_taken: 3, - duration: Duration::from_secs(30), - completed_at: Instant::now(), - notification_sink: buffered_notification_sink(Vec::new()), - }, - ); - } - - let moim = client.get_moim("test", &[]).await.unwrap(); - assert!(moim.contains("20260204_2")); - assert!(moim.contains("20260204_3")); - assert!(moim.contains(r#"use load("20260204_2") to get result"#)); - assert!(moim.contains(r#"use load("20260204_3") to get result"#)); - - let discovery = client - .handle_load_discovery("test", temp_dir.path()) - .await - .unwrap(); - let discovery_text = extract_text(&discovery[0]); - assert!(discovery_text.contains("Completed Tasks (awaiting retrieval)")); - assert!(discovery_text.contains("20260204_2")); - assert!(discovery_text.contains("20260204_3")); - - let result = client - .handle_load_task_result("20260204_2", false, false, None) - .await - .unwrap(); - let text = extract_text(&result.content[0]); - assert!(text.contains("20260204_2")); - assert!(text.contains("Successful task")); - assert!(text.contains("✓ Completed")); - assert!(text.contains("1m")); - assert!(text.contains("5 turns")); - assert!(text.contains("Task completed successfully with output")); - assert_eq!(result.status, "completed"); - assert_eq!(result.turns, Some(5)); - - assert!(!client - .completed_tasks - .lock() - .await - .contains_key("20260204_2")); - - let result = client - .handle_load_task_result("20260204_3", false, false, None) - .await - .unwrap(); - let text = extract_text(&result.content[0]); - assert!(text.contains("✗ Failed")); - assert!(text.contains("Error: Something went wrong")); - assert_eq!(result.status, "failed"); - - let result = client - .handle_load_task_result("20260204_3", false, false, None) - .await; - assert!(result.is_err()); - assert!(result.unwrap_err().contains("not found")); - - // All tasks consumed -- moim should be empty - assert!(client.get_moim("test", &[]).await.is_none()); - } - - #[tokio::test] - async fn test_completed_task_uses_durable_tool_turns_in_metadata() { - let temp_dir = TempDir::new().unwrap(); - let session_manager = Arc::new(crate::session::SessionManager::new( - temp_dir.path().join("sessions"), - )); - let task_id = create_test_subagent_session( - &session_manager, - temp_dir.path(), - &[ - Message::user().with_text("Inspect the project"), - Message::assistant().with_tool_request( - "tool-1", - Ok(rmcp::model::CallToolRequestParams::new("test_tool")), - ), - Message::user().with_tool_response( - "tool-1", - Ok(CallToolResult::success(vec![ContentBlock::text("done")])), - ), - Message::assistant().with_text("Inspection complete"), - ], - ) - .await; - let client = - SummonClient::new(create_test_context_with_session_manager(session_manager)).unwrap(); - - let handle = tokio::spawn(async { Ok("Inspection complete".to_string()) }); - while !handle.is_finished() { - tokio::task::yield_now().await; - } - client.background_tasks.lock().await.insert( - task_id.clone(), - BackgroundTask { - id: task_id.clone(), - description: "Inspect the project".to_string(), - started_at: Instant::now(), - // Simulate hundreds of streamed message events for two durable turns. - turns: Arc::new(AtomicU32::new(554)), - last_activity: Arc::new(AtomicU64::new(current_epoch_millis())), - handle, - cancellation_token: CancellationToken::new(), - completion_token: CancellationToken::new(), - notification_sink: buffered_notification_sink(Vec::new()), - }, - ); - - let arguments = serde_json::json!({"source": task_id}) - .as_object() - .unwrap() - .clone(); - let result = client - .handle_load("parent", temp_dir.path(), Some(arguments), None) - .await - .unwrap(); - let text = extract_text(&result.content[0]); - let meta = result.meta.unwrap(); - - assert!(text.contains("(2 turns)")); - assert_eq!(meta.0.get("turns_taken"), Some(&serde_json::json!(2))); - assert_eq!( - meta.0.get("task_status"), - Some(&serde_json::json!("completed")) - ); - } - - #[test] - fn test_durable_turn_count_ignores_compaction_scaffolding() { - let compacted_tool_loop = crate::conversation::Conversation::new_unvalidated(vec![ - Message::user() - .with_text("Previous task") - .with_visibility(true, false), - Message::assistant() - .with_text("Previous result") - .with_visibility(true, false), - Message::user() - .with_text("Inspect the project") - .with_visibility(true, false), - Message::assistant() - .with_tool_request( - "tool-1", - Ok(rmcp::model::CallToolRequestParams::new("test_tool")), - ) - .with_visibility(true, false), - Message::user() - .with_tool_response( - "tool-1", - Ok(CallToolResult::success(vec![ContentBlock::text("done")])), - ) - .with_visibility(true, false), - // A later compaction archives its earlier agent-only scaffold. - Message::assistant() - .with_text("") - .with_visibility(false, false), - Message::user() - .with_text("Inspect the project") - .with_visibility(false, false), - Message::assistant() - .with_text("") - .with_text("Continue from the compacted context") - .agent_only(), - Message::user() - .with_text("Inspect the project") - .agent_only(), - Message::assistant().with_text("Inspection complete"), - ]); - assert_eq!(durable_assistant_turn_count(&compacted_tool_loop), 2); - - // Keep the hidden projected user message as a role boundary. Dropping - // every agent-only message would merge the failed and retried replies. - let compacted_retry = crate::conversation::Conversation::new_unvalidated(vec![ - Message::user() - .with_text("Inspect the project") - .with_visibility(true, false), - Message::assistant() - .with_text("Context window exceeded") - .with_visibility(true, false), - Message::assistant().with_text("").agent_only(), - Message::user() - .with_text("Inspect the project") - .agent_only(), - Message::assistant().with_text("Inspection complete"), - ]); - assert_eq!(durable_assistant_turn_count(&compacted_retry), 2); - } - - #[tokio::test] - async fn test_cancel_running_task() { - let temp_dir = TempDir::new().unwrap(); - let session_manager = Arc::new(crate::session::SessionManager::new( - temp_dir.path().join("sessions"), - )); - let task_id = create_test_subagent_session( - &session_manager, - temp_dir.path(), - &[Message::user().with_text("Analyse the project")], - ) - .await; - let task_session_manager = Arc::clone(&session_manager); - let client = - SummonClient::new(create_test_context_with_session_manager(session_manager)).unwrap(); - let token = CancellationToken::new(); - let notification_sink = buffered_notification_sink(Vec::new()); - let task_notification_sink = Arc::clone(¬ification_sink); - let task_token = token.clone(); - let task_notification_id = task_id.clone(); - - { - let mut running = client.background_tasks.lock().await; - running.insert( - task_id.clone(), - BackgroundTask { - id: task_id.clone(), - description: "Cancellable task".to_string(), - started_at: Instant::now(), - // This stale event count must be replaced after cancellation. - turns: Arc::new(AtomicU32::new(3)), - last_activity: Arc::new(AtomicU64::new(current_epoch_millis())), - handle: tokio::spawn(async move { - task_token.cancelled().await; - task_session_manager - .add_message( - &task_notification_id, - &Message::assistant().with_text("Partial result"), - ) - .await - .unwrap(); - task_notification_sink - .lock() - .await - .route(test_tool_notification("cancel", &task_notification_id)); - Ok("cancelled gracefully".to_string()) - }), - cancellation_token: token.clone(), - completion_token: CancellationToken::new(), - notification_sink, - }, - ); - } - - let (emitter, mut notifications) = notification_channel(); - let (result, notification) = tokio::join!( - client.handle_load_task_result(&task_id, true, false, Some(emitter)), - notifications.recv() - ); - let result = result.unwrap(); - let text = extract_text(&result.content[0]); - assert!(text.contains("Cancelled")); - assert!(text.contains(&task_id)); - assert!(text.contains("Cancellable task")); - assert!(text.contains("cancelled gracefully")); - assert_eq!(result.status, "cancelled"); - assert_eq!(result.turns, Some(1)); - assert_eq!( - notification_subagent_id(¬ification.unwrap()).as_deref(), - Some(task_id.as_str()) - ); - assert!(token.is_cancelled()); - assert!(!client.background_tasks.lock().await.contains_key(&task_id)); - } - - #[tokio::test] - async fn test_cancelled_running_load_remains_retrievable() { - let client = Arc::new(SummonClient::new(create_test_context()).unwrap()); - let token = CancellationToken::new(); - let task_id = "20260204_1"; - let task_token = token.clone(); - - client.background_tasks.lock().await.insert( - task_id.to_string(), - BackgroundTask { - id: task_id.to_string(), - description: "Cancellable task".to_string(), - started_at: Instant::now(), - turns: Arc::new(AtomicU32::new(1)), - last_activity: Arc::new(AtomicU64::new(current_epoch_millis())), - handle: tokio::spawn(async move { - task_token.cancelled().await; - Ok("cancelled gracefully".to_string()) - }), - cancellation_token: token.clone(), - completion_token: CancellationToken::new(), - notification_sink: buffered_notification_sink(vec![ - test_tool_notification("inner-0", task_id), - test_tool_notification("inner-1", task_id), - ]), - }, - ); - - let (emitter, mut notifications) = notification_channel(); - let load_client = Arc::clone(&client); - let load = tokio::spawn(async move { - load_client - .handle_load_task_result(task_id, true, false, Some(emitter)) - .await - }); - - let first = notifications.recv().await.unwrap(); - assert_eq!(notification_command(&first).as_deref(), Some("inner-0")); - load.abort(); - assert!(load.await.unwrap_err().is_cancelled()); - assert!(client.background_tasks.lock().await.contains_key(task_id)); - assert!(!token.is_cancelled()); - - let (retry_emitter, mut retry_notifications) = notification_channel(); - let result = client - .handle_load_task_result(task_id, true, false, Some(retry_emitter)) - .await - .unwrap(); - - assert_eq!(result.status, "cancelled"); - assert!(token.is_cancelled()); - assert!(!client.background_tasks.lock().await.contains_key(task_id)); - - let commands: Vec = std::iter::from_fn(|| retry_notifications.try_recv().ok()) - .filter_map(|notification| notification_command(¬ification)) - .collect(); - assert!( - commands == ["inner-0", "inner-1"] || commands == ["inner-1"], - "retry must replay the remaining notifications, with at-least-once delivery allowed" - ); - } - - #[tokio::test] - async fn test_cancelled_waiting_load_remains_retrievable() { - let client = Arc::new(SummonClient::new(create_test_context()).unwrap()); - let task_id = "20260204_1"; - let (finish_tx, finish_rx) = tokio::sync::oneshot::channel(); - let (handle, completion_token) = spawn_background_task(async move { - finish_rx.await.unwrap(); - Ok("done".to_string()) - }); - - client.background_tasks.lock().await.insert( - task_id.to_string(), - BackgroundTask { - id: task_id.to_string(), - description: "Running task".to_string(), - started_at: Instant::now(), - turns: Arc::new(AtomicU32::new(1)), - last_activity: Arc::new(AtomicU64::new(current_epoch_millis())), - handle, - cancellation_token: CancellationToken::new(), - completion_token, - notification_sink: buffered_notification_sink(vec![ - test_tool_notification("inner-0", task_id), - test_tool_notification("inner-1", task_id), - ]), - }, - ); - - let (emitter, mut notifications) = notification_channel(); - let load_client = Arc::clone(&client); - let load = tokio::spawn(async move { - load_client - .handle_load_task_result(task_id, false, false, Some(emitter)) - .await - }); - - let first = notifications.recv().await.unwrap(); - assert_eq!(notification_command(&first).as_deref(), Some("inner-0")); - load.abort(); - assert!(load.await.unwrap_err().is_cancelled()); - assert!(client.background_tasks.lock().await.contains_key(task_id)); - - finish_tx.send(()).unwrap(); - let (retry_emitter, mut retry_notifications) = notification_channel(); - let result = client - .handle_load_task_result(task_id, false, false, Some(retry_emitter)) - .await - .unwrap(); - - assert_eq!(result.status, "completed"); - assert!(!client.background_tasks.lock().await.contains_key(task_id)); - - let commands: Vec = std::iter::from_fn(|| retry_notifications.try_recv().ok()) - .filter_map(|notification| notification_command(¬ification)) - .collect(); - assert!( - commands == ["inner-0", "inner-1"] || commands == ["inner-1"], - "retry must replay the remaining notifications, with at-least-once delivery allowed" - ); - } - - #[tokio::test] - async fn test_dropped_waiting_load_during_turn_refresh_remains_retrievable() { - let temp_dir = TempDir::new().unwrap(); - let session_manager = Arc::new(crate::session::SessionManager::new( - temp_dir.path().join("sessions"), - )); - let task_id = create_test_subagent_session( - &session_manager, - temp_dir.path(), - &[ - Message::user().with_text("Analyse the project"), - Message::assistant().with_text("done"), - ], - ) - .await; - let client = SummonClient::new(create_test_context_with_session_manager(Arc::clone( - &session_manager, - ))) - .unwrap(); - - let (handle, completion_token) = spawn_background_task(async { Ok("done".to_string()) }); - while !handle.is_finished() { - tokio::task::yield_now().await; - } - client.background_tasks.lock().await.insert( - task_id.clone(), - BackgroundTask { - id: task_id.clone(), - description: "Finished task".to_string(), - started_at: Instant::now(), - turns: Arc::new(AtomicU32::new(1)), - last_activity: Arc::new(AtomicU64::new(current_epoch_millis())), - handle, - cancellation_token: CancellationToken::new(), - completion_token, - notification_sink: buffered_notification_sink(Vec::new()), - }, - ); - - let pool = session_manager.storage().pool().await.unwrap().clone(); - let mut held_connections = Vec::new(); - for _ in 0..pool.options().get_max_connections() { - held_connections.push(pool.acquire().await.unwrap()); - } - tokio::task::yield_now().await; - - let mut load = Box::pin(client.handle_load_task_result(&task_id, false, false, None)); - let first_poll = std::future::poll_fn(|cx| { - std::task::Poll::Ready(std::future::Future::poll(load.as_mut(), cx)) - }) - .await; - assert!(first_poll.is_pending()); - drop(load); - - assert!( - client.completed_tasks.lock().await.contains_key(&task_id) - || client.background_tasks.lock().await.contains_key(&task_id), - "cancelling a load must not orphan a completed task" - ); - - drop(held_connections); - let result = client - .handle_load_task_result(&task_id, false, false, None) - .await - .unwrap(); - assert_eq!(result.status, "completed"); - assert_eq!(result.turns, Some(1)); - assert!(extract_text(&result.content[0]).contains("done")); - assert!(!client.completed_tasks.lock().await.contains_key(&task_id)); - assert!(!client.background_tasks.lock().await.contains_key(&task_id)); - } - - #[tokio::test] - async fn test_peek_running_task() { - let temp_dir = TempDir::new().unwrap(); - let session_manager = Arc::new(crate::session::SessionManager::new( - temp_dir.path().join("sessions"), - )); - let task_id = create_test_subagent_session( - &session_manager, - temp_dir.path(), - &[Message::user().with_text("Analyse the project")], - ) - .await; - let client = SummonClient::new(create_test_context_with_session_manager(Arc::clone( - &session_manager, - ))) - .unwrap(); - let last_activity = Arc::new(AtomicU64::new(0)); - - { - let mut running = client.background_tasks.lock().await; - running.insert( - task_id.clone(), - BackgroundTask { - id: task_id.clone(), - description: "Long running analysis".to_string(), - started_at: Instant::now(), - // Simulate the old stream-event counter after seven fragments. - turns: Arc::new(AtomicU32::new(7)), - last_activity: Arc::clone(&last_activity), - handle: tokio::spawn(async { - tokio::time::sleep(Duration::from_secs(1000)).await; - Ok("eventual result".to_string()) - }), - cancellation_token: CancellationToken::new(), - completion_token: CancellationToken::new(), - notification_sink: buffered_notification_sink(Vec::new()), - }, - ); - } - - let result = client - .handle_load_task_result(&task_id, false, true, None) - .await - .unwrap(); - assert!(extract_text(&result.content[0]).contains("Task is initialising")); - - // Activity can arrive before the assistant block is durably persisted. - last_activity.store(current_epoch_millis(), Ordering::Relaxed); - let result = client - .handle_load_task_result(&task_id, false, true, None) - .await - .unwrap(); - let text = extract_text(&result.content[0]); - assert_eq!(result.turns, Some(0)); - assert!(!text.contains("Task is initialising")); - - for index in 0..7 { - session_manager - .add_message( - &task_id, - &Message::assistant().with_text(format!("fragment {index}")), - ) - .await - .unwrap(); - } - - // Peek should return status without removing the task - let result = client - .handle_load_task_result(&task_id, false, true, None) - .await - .unwrap(); - let text = extract_text(&result.content[0]); - assert!(text.contains("Running")); - assert!(text.contains("Long running analysis")); - assert!(text.contains("**Turns taken:** 1")); - assert_eq!(result.turns, Some(1)); - - let moim = client.get_moim("test", &[]).await.unwrap(); - assert!(moim.contains("1 turns")); - - // Task should still be in background_tasks (not consumed) - assert!(client.background_tasks.lock().await.contains_key(&task_id)); - } - - #[tokio::test] - async fn test_peek_nonexistent_task() { - let client = SummonClient::new(create_test_context()).unwrap(); - - let result = client - .handle_load_task_result("20260204_999", false, true, None) - .await; - assert!(result.is_err()); - assert!(result.unwrap_err().contains("not found")); - } - - #[tokio::test] - async fn test_peek_completed_task_returns_result() { - let client = SummonClient::new(create_test_context()).unwrap(); - - { - let mut completed = client.completed_tasks.lock().await; - completed.insert( - "20260204_1".to_string(), - CompletedTask { - id: "20260204_1".to_string(), - description: "Finished task".to_string(), - result: Ok("final output".to_string()), - turns_taken: 4, - duration: Duration::from_secs(30), - completed_at: Instant::now(), - notification_sink: buffered_notification_sink(Vec::new()), - }, - ); - } - - // Peek on a completed task should return the full result (same as non-peek) - let result = client - .handle_load_task_result("20260204_1", false, true, None) - .await - .unwrap(); - let text = extract_text(&result.content[0]); - assert!(text.contains("Completed")); - assert!(text.contains("final output")); - - // Peek must be non-destructive: the result is still retrievable afterwards. - assert!(client - .completed_tasks - .lock() - .await - .contains_key("20260204_1")); - let result = client - .handle_load_task_result("20260204_1", false, false, None) - .await - .unwrap(); - assert!(extract_text(&result.content[0]).contains("final output")); - } } diff --git a/crates/goose/src/agents/snapshots/goose__agents__prompt_manager__tests__all_platform_extensions.snap b/crates/goose/src/agents/snapshots/goose__agents__prompt_manager__tests__all_platform_extensions.snap index 8661969ca..154eb54dc 100644 --- a/crates/goose/src/agents/snapshots/goose__agents__prompt_manager__tests__all_platform_extensions.snap +++ b/crates/goose/src/agents/snapshots/goose__agents__prompt_manager__tests__all_platform_extensions.snap @@ -114,10 +114,6 @@ Use write and edit to efficiently make changes. Test and verify as appropriate. When running Python scripts or commands, always use `python3` instead of `python`. -## orchestrator - -### Instructions -Manage agent sessions: list, view, start, send messages, and interrupt agents. ## scheduler ### Instructions diff --git a/crates/goose/src/agents/state_machine/ops_doctor.rs b/crates/goose/src/agents/state_machine/ops_doctor.rs index b0ae1b1b4..07d82d6a6 100644 --- a/crates/goose/src/agents/state_machine/ops_doctor.rs +++ b/crates/goose/src/agents/state_machine/ops_doctor.rs @@ -1,5 +1,7 @@ //! Runs session diagnostics and feeds repair context back into the turn. +use std::sync::Arc; + use anyhow::{anyhow, Result}; use async_trait::async_trait; use rmcp::model::Role; @@ -10,9 +12,17 @@ use crate::agents::state_machine::{ }; use crate::conversation::message::Message; use crate::conversation::Conversation; -use crate::session::Session; +use crate::session::{Session, SessionManager}; -pub struct DoctorOperation; +pub struct DoctorOperation { + session_manager: Arc, +} + +impl DoctorOperation { + pub fn new(session_manager: Arc) -> Self { + Self { session_manager } + } +} #[async_trait] impl Operation for DoctorOperation { @@ -39,12 +49,7 @@ impl Operation for DoctorOperation { .id .clone() .ok_or_else(|| anyhow!("Persisted slash command message has no id"))?; - // Doctor still needs the legacy Agent, so keep that lookup contained at this boundary. - let agent = crate::execution::manager::AgentManager::instance() - .await? - .get_or_create_agent(session.id.clone()) - .await?; - let result = match crate::doctor::run(&agent, &session.id).await { + let result = match crate::doctor::run(&self.session_manager, session).await { Ok(message) => message, Err(error) => Message::assistant().with_text(error.to_string()), }; diff --git a/crates/goose/src/agents/state_machine/tests/mod.rs b/crates/goose/src/agents/state_machine/tests/mod.rs index 9f81b5be2..9e4a0fc4f 100644 --- a/crates/goose/src/agents/state_machine/tests/mod.rs +++ b/crates/goose/src/agents/state_machine/tests/mod.rs @@ -6,6 +6,7 @@ use self::pipeline::{test_pipeline, MAX_TURNS}; use crate::agents::state_machine; use crate::agents::state_machine::ops_retry::NUDGED; use crate::agents::state_machine::Emitter; +use crate::session::extension_data::{EnabledExtensionsState, ExtensionData, ExtensionState}; mod agent_reply; mod calculator_extension; @@ -113,13 +114,13 @@ async fn bang_shell_requests_the_shell_tool() -> Result<()> { #[tokio::test] async fn doctor_refuses_without_developer_before_inference() -> Result<()> { let (pipeline, api) = test_pipeline().await?; - let agent = crate::execution::manager::AgentManager::instance() - .await? - .get_or_create_agent(pipeline.session_id.clone()) - .await?; - agent - .extension_manager - .remove_extension(crate::agents::platform_extensions::developer::EXTENSION_NAME) + let mut extension_data = ExtensionData::default(); + EnabledExtensionsState::new(Vec::new()).to_extension_data(&mut extension_data)?; + pipeline + .session_manager + .update(&pipeline.session_id) + .extension_data(extension_data) + .apply() .await?; let result = pipeline.run(["/doctor"]).await?; @@ -130,12 +131,6 @@ async fn doctor_refuses_without_developer_before_inference() -> Result<()> { crate::doctor::DEVELOPER_EXTENSION_REQUIRED_MESSAGE, ); assert_eq!(api.call_count(), 0); - assert!( - !agent - .extension_manager - .is_extension_enabled(crate::agents::platform_extensions::developer::EXTENSION_NAME) - .await - ); Ok(()) } diff --git a/crates/goose/src/agents/state_machine/tests/pipeline.rs b/crates/goose/src/agents/state_machine/tests/pipeline.rs index 13cff42b4..f60067c47 100644 --- a/crates/goose/src/agents/state_machine/tests/pipeline.rs +++ b/crates/goose/src/agents/state_machine/tests/pipeline.rs @@ -149,7 +149,7 @@ impl TestPipeline { &self.goose_mode, &self.tool_inspection_manager, )), - Arc::new(DoctorOperation), + Arc::new(DoctorOperation::new(self.session_manager.clone())), Arc::new(ProjectOperation), Arc::new(SkillOperation::new( self.hook_manager.clone(), diff --git a/crates/goose/src/agents/subagent_handler.rs b/crates/goose/src/agents/subagent_handler.rs index 5c597dc45..e9a29f6f5 100644 --- a/crates/goose/src/agents/subagent_handler.rs +++ b/crates/goose/src/agents/subagent_handler.rs @@ -28,8 +28,6 @@ use std::sync::Arc; use tokio_util::sync::CancellationToken; use tracing::{debug, info}; -pub type OnMessageCallback = Arc; - #[derive(Serialize)] pub struct SubagentPromptContext { pub max_turns: usize, @@ -48,7 +46,6 @@ pub struct SubagentRunParams { pub return_last_only: bool, pub session_id: String, pub cancellation_token: Option, - pub on_message: Option, pub notification_tx: Option>, } @@ -339,7 +336,6 @@ fn get_agent_messages(params: SubagentRunParams) -> AgentMessagesFuture { task_config, session_id, cancellation_token, - on_message, notification_tx, .. } = params; @@ -424,9 +420,6 @@ fn get_agent_messages(params: SubagentRunParams) -> AgentMessagesFuture { while let Some(message_result) = stream.next().await { match message_result { Ok(AgentEvent::Message(msg)) => { - if let Some(ref callback) = on_message { - callback(&msg); - } if let Some(ref tx) = notification_tx { for content in &msg.content { if let Some(notif) = create_tool_notification(content, &session_id) { diff --git a/crates/goose/src/doctor.rs b/crates/goose/src/doctor.rs index 0060953b2..f2cc338bb 100644 --- a/crates/goose/src/doctor.rs +++ b/crates/goose/src/doctor.rs @@ -6,8 +6,10 @@ use crate::config::Config; use crate::conversation::message::Message; use crate::providers; use crate::providers::base::Provider; +use crate::session::extension_data::EnabledExtensionsState; use crate::session::{ - config_path, latest_llm_log_path, read_capped, read_tail, recent_cli_log_paths, SystemInfo, + config_path, latest_llm_log_path, read_capped, read_tail, recent_cli_log_paths, Session, + SessionManager, SystemInfo, }; use goose_providers::errors::ProviderError; @@ -17,17 +19,20 @@ Enable it for this session and run `/doctor` again:\n\ - CLI: `/builtin developer`\n\ - Desktop: select **Developer** in the session extension selector."; -pub async fn run(agent: &crate::agents::Agent, session_id: &str) -> anyhow::Result { - if let Some(message) = require_developer_extension(agent).await { +pub async fn run(session_manager: &SessionManager, session: &Session) -> anyhow::Result { + if let Some(message) = require_developer_extension(session) { return Ok(message); } - if let Some(msg) = ensure_working_provider(agent, session_id).await? { + if let Some(msg) = ensure_working_provider(session_manager, &session.id).await? { return Ok(msg); } let info = SystemInfo::collect(); - let extensions = agent.list_extensions().await; + let extensions: Vec = session_extensions(session) + .iter() + .map(ExtensionConfig::name) + .collect(); let mut prompt = format!( "I ran /doctor because something seems off. Here's my system info:\n\n\ @@ -64,11 +69,12 @@ pub async fn run(agent: &crate::agents::Agent, session_id: &str) -> anyhow::Resu Ok(Message::user().with_text(prompt)) } -async fn require_developer_extension(agent: &crate::agents::Agent) -> Option { - let has_developer = agent - .extension_manager - .get_extension_configs() - .await +fn session_extensions(session: &Session) -> Vec { + EnabledExtensionsState::extensions_or_default(Some(&session.extension_data), Config::global()) +} + +fn require_developer_extension(session: &Session) -> Option { + let has_developer = session_extensions(session) .iter() .any(is_developer_platform_config); @@ -83,7 +89,7 @@ fn is_developer_platform_config(config: &ExtensionConfig) -> bool { } async fn ensure_working_provider( - agent: &crate::agents::Agent, + session_manager: &SessionManager, session_id: &str, ) -> anyhow::Result> { let config = Config::global(); @@ -106,12 +112,12 @@ async fn ensure_working_provider( log.push(format!("Looking for alternative models on {} ...", pname)); if let Some((working, model_config)) = try_other_models(pname, mname, &mut log).await { let new_model = model_config.model_name.clone(); - save_and_set(agent, session_id, working, model_config).await?; + save_and_set(session_manager, session_id, working, model_config).await?; let preamble = log.join("\n"); return Ok(Some(Message::assistant().with_text(format!( "**Goose Doctor**\n\n{}\n\n\ Your configured model wasn't working, so I switched to \ - **{} / {}**. You can continue chatting now.", + **{} / {}**. Your next message will use it.", preamble, pname, new_model, )))); } @@ -124,11 +130,11 @@ async fn ensure_working_provider( if let Some((working, model_config)) = try_other_providers(skip, &mut log).await { let name = working.get_name().to_string(); let model = model_config.model_name.clone(); - save_and_set(agent, session_id, working, model_config).await?; + save_and_set(session_manager, session_id, working, model_config).await?; let preamble = log.join("\n"); return Ok(Some(Message::assistant().with_text(format!( "**Goose Doctor**\n\n{}\n\n\ - Switched to **{} / {}**. You can continue chatting now.", + Switched to **{} / {}**. Your next message will use it.", preamble, name, model, )))); } @@ -142,15 +148,18 @@ async fn ensure_working_provider( } async fn save_and_set( - agent: &crate::agents::Agent, + session_manager: &SessionManager, session_id: &str, provider: Arc, model_config: goose_providers::model::ModelConfig, ) -> anyhow::Result<()> { let config = Config::global(); crate::config::set_active_provider(config, provider.get_name(), &model_config.model_name)?; - agent - .update_provider(provider, model_config, session_id) + session_manager + .update(session_id) + .provider_name(provider.get_name()) + .model_config(model_config) + .apply() .await } @@ -282,52 +291,26 @@ fn describe_error(e: &ProviderError) -> String { #[cfg(test)] mod tests { use super::*; + use crate::session::extension_data::ExtensionState; - #[tokio::test] - async fn developer_requirement_accepts_enabled_extension() { - let data_dir = tempfile::tempdir().unwrap(); - let session_manager = Arc::new(crate::session::SessionManager::new( - data_dir.path().to_path_buf(), - )); - let agent = crate::agents::Agent::with_config(crate::agents::AgentConfig::new( - Arc::clone(&session_manager), - Arc::new(crate::config::PermissionManager::new( - data_dir.path().to_path_buf(), - )), - None, - crate::config::GooseMode::default(), - false, - crate::agents::GoosePlatform::GooseCli, - )); - let session = agent - .config - .session_manager - .create_session( - std::env::current_dir().unwrap(), - "doctor-test".to_string(), - crate::session::SessionType::Hidden, - crate::config::GooseMode::default(), - ) - .await + #[test] + fn developer_requirement_reads_session_extensions() { + let mut session = Session::default(); + EnabledExtensionsState::new(Vec::new()) + .to_extension_data(&mut session.extension_data) .unwrap(); - agent - .extension_manager - .add_extension( - ExtensionConfig::Platform { - name: developer::EXTENSION_NAME.to_string(), - description: "Developer tools".to_string(), - display_name: Some("Developer".to_string()), - bundled: None, - available_tools: vec![], - }, - None, - None, - Some(&session.id), - ) - .await - .expect("developer extension should load"); + assert!(require_developer_extension(&session).is_some()); - assert!(require_developer_extension(&agent).await.is_none()); + EnabledExtensionsState::new(vec![ExtensionConfig::Platform { + name: developer::EXTENSION_NAME.to_string(), + description: "Developer tools".to_string(), + display_name: Some("Developer".to_string()), + bundled: None, + available_tools: vec![], + }]) + .to_extension_data(&mut session.extension_data) + .unwrap(); + assert!(require_developer_extension(&session).is_none()); } #[test] diff --git a/crates/goose/tests/acp_custom_requests_test.rs b/crates/goose/tests/acp_custom_requests_test.rs index f13d59ee4..0d8bbe597 100644 --- a/crates/goose/tests/acp_custom_requests_test.rs +++ b/crates/goose/tests/acp_custom_requests_test.rs @@ -613,7 +613,7 @@ fn test_steer_session_adds_input_to_active_prompt() { // steer queued before the turn ends keeps the loop alive (it flips // `exit_chat` back to false), so a second provider request fires whose // body must now contain the steered text. - let openai = OpenAiFixture::new( + let openai = OpenAiFixture::with_response_delay( vec![ ( "start work".to_string(), @@ -625,6 +625,7 @@ fn test_steer_session_adds_input_to_active_prompt() { ), ], Arc::new(IgnoreSessionId), + Duration::from_millis(500), ) .await; let mut conn = AcpServerConnection::new(TestConnectionConfig::default(), openai).await; diff --git a/crates/goose/tests/acp_fixtures/mod.rs b/crates/goose/tests/acp_fixtures/mod.rs index e486a5e27..4111cf560 100644 --- a/crates/goose/tests/acp_fixtures/mod.rs +++ b/crates/goose/tests/acp_fixtures/mod.rs @@ -29,6 +29,7 @@ use std::collections::VecDeque; use std::future::Future; use std::path::{Path, PathBuf}; use std::sync::{Arc, LazyLock, Mutex}; +use std::time::Duration; use tokio::task::JoinHandle; use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt}; use wiremock::matchers::{method, path}; @@ -221,6 +222,14 @@ impl OpenAiFixture { pub async fn new( exchanges: Vec<(String, &'static str)>, expected_session_id: Arc, + ) -> Self { + Self::with_response_delay(exchanges, expected_session_id, Duration::ZERO).await + } + + pub async fn with_response_delay( + exchanges: Vec<(String, &'static str)>, + expected_session_id: Arc, + delay: Duration, ) -> Self { let mock_server = MockServer::start().await; let queue = Arc::new(Mutex::new(VecDeque::from(exchanges.clone()))); @@ -262,7 +271,8 @@ impl OpenAiFixture { q.pop_front(); return ResponseTemplate::new(200) .insert_header("content-type", "text/event-stream") - .set_body_string(response); + .set_body_string(response) + .set_delay(delay); } drop(q); diff --git a/documentation/docs/guides/environment-variables.md b/documentation/docs/guides/environment-variables.md index fcd9ce5f7..50c923a06 100644 --- a/documentation/docs/guides/environment-variables.md +++ b/documentation/docs/guides/environment-variables.md @@ -137,7 +137,6 @@ These variables control how goose manages conversation sessions and context. | `GOOSE_MAX_TURNS` | [Maximum number of turns](/docs/guides/sessions/smart-context-management#maximum-turns) allowed without user input | Integer (e.g., 10, 50, 100) | 1000 | | `GOOSE_GATEWAY_MAX_TURNS` | Maximum number of turns for gateway sessions (e.g., Telegram). Overrides `GOOSE_MAX_TURNS` for gateway traffic only, so chat platforms can keep a stricter cap than CLI/desktop sessions. | Integer (e.g., 5, 10, 25) | Falls back to `GOOSE_MAX_TURNS`, then 5 | | `GOOSE_SUBAGENT_MAX_TURNS` | Sets the maximum turns allowed for a [subagent](/docs/guides/context-engineering/subagents) to complete before timeout. Can be overridden by [`settings.max_turns`](/docs/guides/recipes/recipe-reference#settings) in recipes or subagent tool calls. | Integer (e.g., 25) | 25 | -| `GOOSE_MAX_BACKGROUND_TASKS` | Sets the maximum number of concurrent background [subagent](/docs/guides/context-engineering/subagents) tasks goose can run at once | Integer (e.g., 1, 5, 10) | 5 | | `CONTEXT_FILE_NAMES` | Specifies custom filenames for [hint/context files](/docs/guides/context-engineering/using-goosehints#custom-context-files) | JSON array of strings (e.g., `["CLAUDE.md", ".goosehints"]`) | `[".goosehints", "AGENTS.md"]` | | `GOOSE_DISABLE_SESSION_NAMING` | Disables automatic AI-generated session naming; avoids the background model call and keeps the default "CLI Session" (goose CLI) or "New Chat" (goose Desktop) | "1", "true" (case-insensitive) to enable | false | | `GOOSE_PROMPT_EDITOR` | [External editor](/docs/guides/goose-cli-commands#external-editor-mode) to use for composing prompts instead of CLI input | Editor command (e.g., "vim", "code --wait") | Unset (uses CLI input) | diff --git a/documentation/docs/mcp/summon-mcp.md b/documentation/docs/mcp/summon-mcp.md index 399897556..076f49cf0 100644 --- a/documentation/docs/mcp/summon-mcp.md +++ b/documentation/docs/mcp/summon-mcp.md @@ -104,9 +104,6 @@ load() load(source: "release-notes") delegate(source: "release-notes") delegate(instructions: "Review these docs and report stale links") -delegate(source: "release-notes", async: true) -load(source: "20260219_1", peek: true) -load(source: "20260219_1") ``` -Calling `load()` with no arguments lists available sources. For background tasks, `delegate(..., async: true)` returns a task id, and `load(source: "")` waits for the result. +Calling `load()` with no arguments lists available sources. `delegate` waits for the subagent to finish and returns its result. diff --git a/goose-self-test.yaml b/goose-self-test.yaml index 54e2dd477..e9cd70cf8 100644 --- a/goose-self-test.yaml +++ b/goose-self-test.yaml @@ -13,7 +13,7 @@ activities: - Analyze code structure and parsing capabilities - Test extension discovery and management - Test load tool for knowledge injection and discovery - - Test delegate tool for task delegation (sync and async) + - Test delegate tool for task delegation - Test multi-turn thinking preservation for providers that reject replayed reasoning_content - Test Z.AI Coding Plan streamed tool calls and interruption recovery - Validate ACP thinking-effort discovery, forwarding, and provider switching @@ -89,8 +89,8 @@ instructions: | Test the unified delegation and knowledge-loading tools: - Load tool for discovery and knowledge injection - Delegate tool for synchronous task delegation - - Delegate tool for asynchronous background tasks - - Parallel delegate execution + - Delegate tool for multi-turn and turn-limited tasks + - Multiple delegates in one message - Nested delegation prevention (critical security test) ### Phase 4: Advanced Self-Testing @@ -244,87 +244,48 @@ prompt: | ``` Verify the delegate completes and returns a summary of its work. - ### Parallel Delegate Test + ### Multiple Delegates Test {% if parallel_tests == "true" %} - **Important**: Synchronous delegates always run in serial, even when called in the same tool call message. - Async delegates (`async: true`) run in parallel when called in the same tool call message. + **Important**: Delegates called in the same tool call message run concurrently. - First, test sync delegates (will run sequentially): Make these 3 delegate calls in a single message: 1. `delegate(instructions: "Sleep 2 seconds, then create /tmp/sync_parallel_1.txt with timestamp from 'date +%H:%M:%S'")` 2. `delegate(instructions: "Sleep 2 seconds, then create /tmp/sync_parallel_2.txt with timestamp from 'date +%H:%M:%S'")` 3. `delegate(instructions: "Sleep 2 seconds, then create /tmp/sync_parallel_3.txt with timestamp from 'date +%H:%M:%S'")` After completion, check timestamps: `cat /tmp/sync_parallel_*.txt` - **Expected**: Timestamps should be ~6+ seconds apart (sequential execution). + **Expected**: Timestamps should be within ~5 seconds of each other (concurrent execution). - Then, test async delegates (will run in parallel): - Make these 3 delegate calls in a single message: - 1. `delegate(instructions: "Sleep 2 seconds, then create /tmp/async_parallel_1.txt with timestamp from 'date +%H:%M:%S'", async: true)` - 2. `delegate(instructions: "Sleep 2 seconds, then create /tmp/async_parallel_2.txt with timestamp from 'date +%H:%M:%S'", async: true)` - 3. `delegate(instructions: "Sleep 2 seconds, then create /tmp/async_parallel_3.txt with timestamp from 'date +%H:%M:%S'", async: true)` - - Wait for tasks to complete (sleep 10 seconds), then check timestamps: `cat /tmp/async_parallel_*.txt` - **Expected**: Timestamps should be within ~5 seconds of each other (parallel execution). - - Document both results to validate the parallel execution behavior. + Document the result to validate the execution behavior. {% endif %} - ### Async Delegate Test (Background Execution) - This tests background task execution with MOIM status monitoring. + ### Multi-Turn Delegate Test + This tests that a delegate runs to completion over several turns before returning. - 1. Spawn a background delegate that takes multiple turns: + 1. Delegate a task that takes multiple turns: ``` - delegate(instructions: "Run 'sleep 1' command 10 times, one per turn. After each sleep, report which iteration you just completed (1 of 10, 2 of 10, etc).", async: true) + delegate(instructions: "Run 'sleep 1' command 5 times, one per turn. After each sleep, report which iteration you just completed (1 of 5, 2 of 5, etc).") ``` - 2. After spawning, the delegate runs in the background. You (the main agent) should: - - Sleep for 2 seconds: `sleep 2` - - Check the MOIM (it will show background task status with turns and time) - - **Say out loud** what you observe: "The background task has completed X turns and has been running for Y seconds" - - Repeat: sleep 2 seconds, check MOIM, report status out loud - - Continue until the background task disappears from MOIM (indicating completion) + 2. Verify the call only returns after the delegate has finished, and that its result reports all 5 iterations. - 3. Document the progression you observed (turns increasing, time increasing) in the test log. + 3. Document the returned summary in the test log. This validates: - - Async delegate spawning returns immediately - - MOIM accurately reports background task status - - Turn counting works correctly - - Task cleanup happens when complete + - The delegate call blocks until the subagent finishes + - Multi-turn subagent work is reflected in the returned result - ### Async Delegate Cancellation Test - This tests the ability to stop a running background task mid-execution. + ### Delegate Turn Limit Test + This tests that a delegate stops when it reaches its turn limit. - 1. Spawn a slow background task: + 1. Delegate a task that needs more turns than allowed: ``` - delegate(instructions: "Run 'sleep 2' fifteen times, reporting progress after each.", async: true) - ``` - Note the task ID returned (e.g., "20260204_42"). - - 2. Wait 8 seconds: `sleep 8` - - 3. Check MOIM and confirm the task is running with some turns completed. - - 4. Cancel the task: - ``` - load(source: "", cancel: true) + delegate(instructions: "Run 'sleep 1' ten times, one per turn, reporting progress after each.", max_turns: 3) ``` - 5. Verify the response shows: - - "⊘ Cancelled" status - - Partial output (some iterations completed) - - Duration and turn count + 2. Verify the call returns before all ten iterations complete, reporting either partial progress or that the turn limit was reached. - 6. Check MOIM again - the task should be gone (not in running or completed). - - 7. Try to retrieve the cancelled task: - ``` - load(source: "") - ``` - **Expected**: Error "Task '' not found." - - This validates that cancellation stops tasks, returns partial results, and cleans up properly. + This validates that `max_turns` bounds a delegate and that control returns to the parent. ### Source-Based Delegate Test If `load()` discovered any recipes or skills, test delegating with a source: @@ -531,8 +492,8 @@ prompt: | • Extensions: [✓/✗] • Load tool: [✓/✗] • Delegate (sync): [✓/✗] - • Delegate (async): [✓/✗] - • Delegate cancellation: [✓/✗] + • Delegate (multi-turn): [✓/✗] + • Delegate turn limit: [✓/✗] • Nested delegation blocked: [✓/✗] ⚠️ Issues Found: