feat(subagent): resume completed delegates with a follow-up (#13106)

This commit is contained in:
Lifei Zhou
2026-11-04 00:18:44 +00:00
committed by GitHub
parent 238026cd11
commit 71dd9a9aa2
4 changed files with 201 additions and 63 deletions
@@ -1,5 +1,7 @@
use crate::agents::state_machine::messages_since_kickoff;
use crate::agents::tool_execution::ToolCallResult;
use crate::conversation::message::{Message, MessageContent};
use crate::conversation::Conversation;
use crate::recipe::Response;
use indoc::formatdoc;
use rmcp::model::{
@@ -52,6 +54,12 @@ impl FinalOutputTool {
})
}
pub(crate) fn latest_turn_output(conversation: &Conversation) -> Option<String> {
messages_since_kickoff(conversation)
.ok()
.and_then(Self::successful_output)
}
pub(crate) fn successful_output(messages: &[Message]) -> Option<String> {
let successful_responses: HashSet<&str> = messages
.iter()
@@ -478,7 +478,7 @@ impl SummonClient {
"properties": {
"instructions": {
"type": "string",
"description": "Task instructions. Required for ad-hoc tasks. With `resume`, an optional message for the subagent."
"description": "Task instructions. Required for ad-hoc tasks. With `resume`, a message for the subagent, required when resuming a completed delegate."
},
"source": {
"type": "string",
@@ -521,7 +521,7 @@ impl SummonClient {
},
"resume": {
"type": "string",
"description": "Subagent ID of a failed or cancelled delegate to continue. Only `instructions` can be combined with it."
"description": "Subagent ID of an earlier delegate to continue. Only `instructions` can be combined with it."
}
}
});
@@ -533,7 +533,7 @@ impl SummonClient {
1. Ad-hoc: Provide `instructions` for a custom task\n\
2. Source-based: Provide `source` name to run a subrecipe, recipe, or agent\n\
3. Combined: Pair a source with a task (e.g., source: \"deploy\", instructions: \"deploy to staging\")\n\
4. Resume: Provide `resume` with the subagent ID of a failed or cancelled delegate to continue it instead of starting over. If the user says to continue after a stop, resume the ones from the latest stop unless they name others. Completed delegates cannot be resumed.\n\n\
4. Resume: Provide `resume` with the subagent ID of a failed or cancelled delegate to continue it instead of starting over. If the user says to continue after a stop, resume the ones from the latest stop unless they name others. A completed delegate can be resumed with `instructions` holding a follow-up; it keeps its earlier context.\n\n\
Effective Delegation:\n\
- Delegates know only instructions + source content\n\
- Delegates cannot coordinate. Same-file work = conflicts.\n\
@@ -901,15 +901,17 @@ impl SummonClient {
"Subagent {subagent_id} does not belong to this session"
));
}
if subagent
let completed = subagent
.conversation
.as_ref()
.and_then(|conversation| FinalOutputTool::successful_output(conversation.messages()))
.is_some()
{
return Err(format!("Subagent {subagent_id} already completed"));
.and_then(FinalOutputTool::latest_turn_output)
.is_some();
let instructions = instructions.filter(|text| !text.trim().is_empty());
if instructions.is_none() && completed {
return Err(format!(
"Subagent {subagent_id} already completed; provide `instructions` with a follow-up to resume it"
));
}
let instructions = instructions.unwrap_or_else(|| DEFAULT_RESUME_INSTRUCTIONS.to_string());
session_manager
.add_message(subagent_id, &Message::user().with_text(instructions))
@@ -1781,6 +1783,56 @@ mod tests {
.await
}
async fn last_message(
manager: &crate::session::SessionManager,
session_id: &str,
) -> Result<String> {
let session = manager.get_session(session_id, true).await?;
Ok(session
.conversation
.unwrap()
.last()
.unwrap()
.as_concat_text())
}
async fn complete_task(
manager: &crate::session::SessionManager,
subagent_id: &str,
) -> Result<()> {
manager
.add_message(subagent_id, &Message::user().with_text("Write a summary"))
.await?;
let arguments = serde_json::json!({"summary": "done"})
.as_object()
.unwrap()
.clone();
manager
.add_message(
subagent_id,
&Message::assistant().with_tool_request(
"final-output-call",
Ok(rmcp::model::CallToolRequestParams::new(
crate::agents::final_output_tool::FINAL_OUTPUT_TOOL_NAME,
)
.with_arguments(arguments)),
),
)
.await?;
manager
.add_message(
subagent_id,
&Message::user().with_tool_response(
"final-output-call",
Ok(CallToolResult::success(vec![ContentBlock::text(
crate::agents::final_output_tool::FINAL_OUTPUT_SUCCESS_MESSAGE,
)])),
),
)
.await?;
Ok(())
}
#[tokio::test]
async fn delegate_resume_continues_the_saved_subagent() -> Result<()> {
let temp_dir = TempDir::new()?;
@@ -1811,9 +1863,10 @@ mod tests {
meta.0.get("subagent_session_id"),
Some(&serde_json::json!(subagent.id))
);
let resumed = manager.get_session(&subagent.id, true).await?;
let last = resumed.conversation.as_ref().unwrap().last().unwrap();
assert_eq!(last.as_concat_text(), "Finish the summary");
assert_eq!(
last_message(&manager, &subagent.id).await?,
"Finish the summary"
);
resume(
&client,
@@ -1822,9 +1875,51 @@ mod tests {
)
.await
.map_err(anyhow::Error::msg)?;
let resumed = manager.get_session(&subagent.id, true).await?;
let last = resumed.conversation.as_ref().unwrap().last().unwrap();
assert_eq!(last.as_concat_text(), DEFAULT_RESUME_INSTRUCTIONS);
assert_eq!(
last_message(&manager, &subagent.id).await?,
DEFAULT_RESUME_INSTRUCTIONS
);
Ok(())
}
#[tokio::test]
async fn delegate_resume_gives_a_completed_subagent_its_follow_up() -> Result<()> {
let temp_dir = TempDir::new()?;
let manager = Arc::new(crate::session::SessionManager::new(
temp_dir.path().to_path_buf(),
));
let parent = create_session(&manager, &temp_dir, SessionType::User, None).await?;
let completed =
create_session(&manager, &temp_dir, SessionType::SubAgent, Some(&parent.id)).await?;
complete_task(&manager, &completed.id).await?;
let unanswered =
create_session(&manager, &temp_dir, SessionType::SubAgent, Some(&parent.id)).await?;
complete_task(&manager, &unanswered.id).await?;
manager
.add_message(
&unanswered.id,
&Message::user().with_text("Also cover the tests"),
)
.await?;
let client = SummonClient::new(create_test_context_with_session_manager(manager.clone()))?;
for (subagent_id, args, expected) in [
(
&completed.id,
serde_json::json!({"resume": completed.id, "instructions": "Also cover the tests"}),
"Also cover the tests",
),
(
&unanswered.id,
serde_json::json!({"resume": unanswered.id}),
DEFAULT_RESUME_INSTRUCTIONS,
),
] {
resume(&client, &parent.id, args)
.await
.map_err(anyhow::Error::msg)?;
assert_eq!(last_message(&manager, subagent_id).await?, expected);
}
Ok(())
}
@@ -1847,33 +1942,7 @@ mod tests {
.await?;
let completed =
create_session(&manager, &temp_dir, SessionType::SubAgent, Some(&parent.id)).await?;
let arguments = serde_json::json!({"summary": "done"})
.as_object()
.unwrap()
.clone();
manager
.add_message(
&completed.id,
&Message::assistant().with_tool_request(
"final-output-call",
Ok(rmcp::model::CallToolRequestParams::new(
crate::agents::final_output_tool::FINAL_OUTPUT_TOOL_NAME,
)
.with_arguments(arguments)),
),
)
.await?;
manager
.add_message(
&completed.id,
&Message::user().with_tool_response(
"final-output-call",
Ok(CallToolResult::success(vec![ContentBlock::text(
crate::agents::final_output_tool::FINAL_OUTPUT_SUCCESS_MESSAGE,
)])),
),
)
.await?;
complete_task(&manager, &completed.id).await?;
let client = SummonClient::new(create_test_context_with_session_manager(manager.clone()))?;
for (session_id, args, expected) in [
@@ -1885,7 +1954,12 @@ mod tests {
(
&parent.id,
serde_json::json!({"resume": completed.id}),
"already completed",
"already completed; provide `instructions` with a follow-up",
),
(
&parent.id,
serde_json::json!({"resume": completed.id, "instructions": " "}),
"already completed; provide `instructions` with a follow-up",
),
(
&parent.id,
@@ -2,6 +2,7 @@ use async_trait::async_trait;
use futures::future;
use futures::stream::{self, BoxStream, StreamExt};
use goose_agent::subagent::{SubagentOutcome, SubagentRunner, SubagentUpdate};
use rmcp::model::Role;
use tokio_util::sync::CancellationToken;
use crate::agents::final_output_tool::FinalOutputTool;
@@ -30,6 +31,21 @@ fn start_notice(subagent_id: &str, task: Option<&str>) -> String {
format!("Running subagent {subagent_id}{snippet}")
}
fn is_resume(subagent: &Session) -> bool {
subagent.conversation.as_ref().is_some_and(|conversation| {
conversation
.messages()
.iter()
.filter(|message| {
message.role == Role::User
&& !message.is_tool_response()
&& message.is_user_visible()
})
.count()
> 1
})
}
fn finished_notice(
subagent_id: &str,
outcome: &SubagentOutcome,
@@ -119,16 +135,20 @@ impl SubagentRunner<Session> for ForegroundSubagentRunner {
if let Some(output) = subagent
.conversation
.as_ref()
.and_then(|conversation| FinalOutputTool::successful_output(conversation.messages()))
.and_then(FinalOutputTool::latest_turn_output)
{
return ended(SubagentOutcome::Completed(output));
}
let task = subagent
.recipe
.as_ref()
.and_then(|recipe| recipe.prompt.as_deref());
let notice =
SubagentUpdate::ToParent(inline_notice(start_notice(subagent_session_id, task)));
let notice = if is_resume(&subagent) {
format!("Resuming subagent {subagent_session_id}")
} else {
let task = subagent
.recipe
.as_ref()
.and_then(|recipe| recipe.prompt.as_deref());
start_notice(subagent_session_id, task)
};
let notice = SubagentUpdate::ToParent(inline_notice(notice));
Box::pin(stream::once(future::ready(notice)).chain(self.spawn(subagent, cancel)))
}
@@ -236,6 +256,9 @@ mod tests {
.parent_session_id(Some(parent_id.to_string()))
.apply()
.await?;
manager
.add_message(&subagent.id, &Message::user().with_text("Write a summary"))
.await?;
manager
.add_message(parent_id, &delegate_message(&subagent.id))
.await?;
@@ -511,6 +534,43 @@ mod tests {
Ok(())
}
#[tokio::test]
async fn a_completed_subagent_given_a_follow_up_runs_again() -> Result<()> {
let fixture = fixture().await?;
save_final_output(&fixture.manager, &fixture.subagent_id).await?;
fixture
.manager
.add_message(
&fixture.subagent_id,
&Message::user().with_text("Also cover the tests"),
)
.await?;
let parent = fixture
.manager
.get_session(&fixture.parent_id, false)
.await?;
let updates: Vec<_> = fixture
.runner()
.start(&parent, &fixture.subagent_id, CancellationToken::new())
.await
.collect()
.await;
let Some(SubagentUpdate::ToParent(notice)) = updates.first() else {
panic!("expected a start notice");
};
assert!(matches!(
notice.content.as_slice(),
[MessageContent::SystemNotification(notification)]
if notification.msg == format!("Resuming subagent {}", fixture.subagent_id)
));
assert!(matches!(
updates.last(),
Some(SubagentUpdate::Finished(SubagentOutcome::Failed(reason)))
if reason.contains("has no saved recipe")
));
Ok(())
}
#[tokio::test]
async fn subagents_of_another_session_are_reported_without_running() -> Result<()> {
let fixture = fixture().await?;
+9 -13
View File
@@ -1,13 +1,10 @@
use crate::{
agents::{
final_output_tool::FinalOutputTool,
state_machine::{trailing_error, MAX_TURNS_MESSAGE},
state_machine::{messages_since_kickoff, trailing_error, MAX_TURNS_MESSAGE},
AgentEvent, SessionConfig, StateMachineServices,
},
conversation::{
message::{ActionRequiredData, Message, MessageContent},
Conversation,
},
conversation::message::{ActionRequiredData, Message, MessageContent},
prompt_template::render_template,
session::extension_data::{EnabledExtensionsState, ExtensionState},
session::{Session, SessionManager, SessionType},
@@ -155,10 +152,11 @@ impl ForegroundSubagentRunner {
Ok(subagent) => subagent,
Err(error) => return SubagentOutcome::Failed(error.to_string()),
};
let messages = subagent.conversation.as_ref().map(Conversation::messages);
if let Some(output) =
messages.and_then(|messages| FinalOutputTool::successful_output(messages))
{
let conversation = subagent.conversation.as_ref();
let latest_turn = conversation
.and_then(|conversation| messages_since_kickoff(conversation).ok())
.unwrap_or_default();
if let Some(output) = FinalOutputTool::successful_output(latest_turn) {
return SubagentOutcome::Completed(output);
}
if stopped {
@@ -167,12 +165,10 @@ impl ForegroundSubagentRunner {
if let Err(error) = run_result {
return SubagentOutcome::Failed(error.to_string());
}
if let Some(error) = subagent.conversation.as_ref().and_then(trailing_error) {
if let Some(error) = conversation.and_then(trailing_error) {
return SubagentOutcome::Failed(format!("{error:?}"));
}
SubagentOutcome::Failed(failure_reason(
messages.map(Vec::as_slice).unwrap_or_default(),
))
SubagentOutcome::Failed(failure_reason(latest_turn))
}
}