Remove background subagents and orchestrator; make Doctor session-only (#12729)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Douwe Osinga
2026-10-07 02:23:16 +00:00
committed by GitHub
parent d2fe88f413
commit 8f72d2d305
21 changed files with 223 additions and 3061 deletions
+7 -9
View File
@@ -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: "<task_id>")`:
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: "<task_id>") 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: "<task_id>")`
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
+1 -1
View File
@@ -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
@@ -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 = <check body>,
async = true, # IMPORTANT: parallelize
model = <check model>,
max_turns = <check turn_limit>,
)
@@ -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.
@@ -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.
@@ -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
+22 -1
View File
@@ -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
+41 -9
View File
@@ -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
);
}
}
@@ -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<HashMap<&'static str, PlatformExtensionDef>
},
);
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 {
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -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
@@ -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<SessionManager>,
}
impl DoctorOperation {
pub fn new(session_manager: Arc<SessionManager>) -> Self {
Self { session_manager }
}
}
#[async_trait]
impl Operation<Session, GooseEffect> for DoctorOperation {
@@ -39,12 +49,7 @@ impl Operation<Session, GooseEffect> 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()),
};
@@ -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(())
}
@@ -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(),
@@ -28,8 +28,6 @@ use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use tracing::{debug, info};
pub type OnMessageCallback = Arc<dyn Fn(&Message) + Send + Sync>;
#[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<CancellationToken>,
pub on_message: Option<OnMessageCallback>,
pub notification_tx: Option<tokio::sync::mpsc::UnboundedSender<ServerNotification>>,
}
@@ -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) {
+44 -61
View File
@@ -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<Message> {
if let Some(message) = require_developer_extension(agent).await {
pub async fn run(session_manager: &SessionManager, session: &Session) -> anyhow::Result<Message> {
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<String> = 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<Message> {
let has_developer = agent
.extension_manager
.get_extension_configs()
.await
fn session_extensions(session: &Session) -> Vec<ExtensionConfig> {
EnabledExtensionsState::extensions_or_default(Some(&session.extension_data), Config::global())
}
fn require_developer_extension(session: &Session) -> Option<Message> {
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<Option<Message>> {
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<dyn Provider>,
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]
@@ -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;
+11 -1
View File
@@ -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<dyn ExpectedSessionId>,
) -> 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<dyn ExpectedSessionId>,
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);
@@ -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) |
+1 -4
View File
@@ -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: "<task_id>")` waits for the result.
Calling `load()` with no arguments lists available sources. `delegate` waits for the subagent to finish and returns its result.
+23 -62
View File
@@ -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: "<task_id>", 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: "<task_id>")
```
**Expected**: Error "Task '<task_id>' 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: