feat(subagent): resume failed or cancelled delegates (#13015)
This commit is contained in:
@@ -38,11 +38,10 @@ pub enum SubagentUpdate {
|
||||
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
|
||||
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
|
||||
pub trait SubagentRunner<S>: MaybeSend + MaybeSync {
|
||||
fn started_subagent_session_ids(
|
||||
&self,
|
||||
parent_session: &S,
|
||||
conversation: &Conversation,
|
||||
) -> Vec<String>;
|
||||
/// Returns every subagent session ID that `message` asks to run, even if that subagent
|
||||
/// has already run. `SubagentOperation` calls this for every message in the parent
|
||||
/// conversation and decides which still need to run.
|
||||
fn requested_subagent_session_ids(&self, parent_session: &S, message: &Message) -> Vec<String>;
|
||||
|
||||
async fn start(
|
||||
&self,
|
||||
@@ -76,19 +75,6 @@ fn finished_subagent_session_ids(message: &Message) -> impl Iterator<Item = &str
|
||||
delivered.into_iter().chain(cancelled)
|
||||
}
|
||||
|
||||
fn pending_subagents(conversation: &Conversation, started: Vec<String>) -> Vec<String> {
|
||||
let mut seen: HashSet<String> = conversation
|
||||
.messages()
|
||||
.iter()
|
||||
.flat_map(finished_subagent_session_ids)
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
started
|
||||
.into_iter()
|
||||
.filter(|subagent_session_id| seen.insert(subagent_session_id.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn subagent_label(subagent_session_id: &str) -> String {
|
||||
format!("Subagent {subagent_session_id}")
|
||||
}
|
||||
@@ -122,7 +108,7 @@ fn subagent_cancelled_message(subagent_session_ids: &[String]) -> Option<Message
|
||||
.iter()
|
||||
.map(|subagent_session_id| {
|
||||
format!(
|
||||
"{} was cancelled before it finished and will not run again.",
|
||||
"{} was cancelled before it finished.",
|
||||
subagent_label(subagent_session_id)
|
||||
)
|
||||
})
|
||||
@@ -184,6 +170,22 @@ impl<S> SubagentOperation<S> {
|
||||
self
|
||||
}
|
||||
|
||||
fn pending_subagents(&self, session: &S, conversation: &Conversation) -> Vec<String> {
|
||||
let mut pending: Vec<String> = Vec::new();
|
||||
for message in conversation.messages() {
|
||||
for subagent_session_id in finished_subagent_session_ids(message) {
|
||||
pending.retain(|pending_id| pending_id != subagent_session_id);
|
||||
}
|
||||
for subagent_session_id in self.runner.requested_subagent_session_ids(session, message)
|
||||
{
|
||||
if !pending.contains(&subagent_session_id) {
|
||||
pending.push(subagent_session_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
pending
|
||||
}
|
||||
|
||||
fn deliver<E: From<Message>>(
|
||||
&self,
|
||||
subagent_session_id: &str,
|
||||
@@ -216,11 +218,7 @@ where
|
||||
emit: &Emitter,
|
||||
) -> Vec<E> {
|
||||
let mut stopped = std::mem::take(&mut *self.running.lock().await);
|
||||
let pending = pending_subagents(
|
||||
conversation,
|
||||
self.runner
|
||||
.started_subagent_session_ids(session, conversation),
|
||||
);
|
||||
let pending = self.pending_subagents(session, conversation);
|
||||
let mut effects = Vec::new();
|
||||
let mut delivered = HashSet::new();
|
||||
let finished = std::iter::from_fn(|| loop {
|
||||
@@ -257,11 +255,7 @@ where
|
||||
conversation: &Conversation,
|
||||
emit: &Emitter,
|
||||
) -> Result<OperationResult<E>> {
|
||||
let pending = pending_subagents(
|
||||
conversation,
|
||||
self.runner
|
||||
.started_subagent_session_ids(session, conversation),
|
||||
);
|
||||
let pending = self.pending_subagents(session, conversation);
|
||||
let remaining = pending.len().saturating_sub(1);
|
||||
|
||||
let mut running = self.running.lock().await;
|
||||
|
||||
@@ -48,7 +48,6 @@ struct FakeRunner {
|
||||
children: Mutex<HashMap<String, Child>>,
|
||||
started: Mutex<Vec<String>>,
|
||||
events: Mutex<Vec<String>>,
|
||||
started_subagent_session_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl FakeRunner {
|
||||
@@ -79,12 +78,16 @@ impl FakeRunner {
|
||||
|
||||
#[async_trait]
|
||||
impl SubagentRunner<Parent> for FakeRunner {
|
||||
fn started_subagent_session_ids(
|
||||
fn requested_subagent_session_ids(
|
||||
&self,
|
||||
_parent_session: &Parent,
|
||||
_conversation: &Conversation,
|
||||
message: &Message,
|
||||
) -> Vec<String> {
|
||||
self.started_subagent_session_ids.clone()
|
||||
message
|
||||
.as_concat_text()
|
||||
.strip_prefix("start ")
|
||||
.map(|ids| ids.split(' ').map(str::to_string).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn start(
|
||||
@@ -151,18 +154,8 @@ fn shown(rx: &mut mpsc::UnboundedReceiver<AgentEvent>) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn kickoff() -> Message {
|
||||
Message::user().with_text("go")
|
||||
}
|
||||
|
||||
fn fake(subagent_session_ids: &[&str]) -> FakeRunner {
|
||||
FakeRunner {
|
||||
started_subagent_session_ids: subagent_session_ids
|
||||
.iter()
|
||||
.map(|id| id.to_string())
|
||||
.collect(),
|
||||
..FakeRunner::default()
|
||||
}
|
||||
fn start(subagent_session_ids: &[&str]) -> Message {
|
||||
Message::user().with_text(format!("start {}", subagent_session_ids.join(" ")))
|
||||
}
|
||||
|
||||
fn appended(effects: Vec<ConversationEffect>) -> Vec<Message> {
|
||||
@@ -234,10 +227,10 @@ async fn stop_with(
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_finished_subagent_is_delivered_without_running() {
|
||||
let runner = Arc::new(fake(&["a"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
runner.finished("a", SubagentOutcome::Completed("done".into()));
|
||||
let operation = operation(&runner);
|
||||
let mut messages = vec![kickoff()];
|
||||
let mut messages = vec![start(&["a"])];
|
||||
|
||||
let delivered = run_once(&operation, &messages).await;
|
||||
|
||||
@@ -253,11 +246,11 @@ async fn a_finished_subagent_is_delivered_without_running() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn running_subagents_are_delivered_one_per_pass_and_started_once() {
|
||||
let runner = Arc::new(fake(&["a", "b"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
let a = runner.running("a");
|
||||
let b = runner.running("b");
|
||||
let operation = operation(&runner);
|
||||
let mut messages = vec![kickoff()];
|
||||
let mut messages = vec![start(&["a", "b"])];
|
||||
|
||||
b.finish(SubagentOutcome::Completed("b done".into()));
|
||||
let delivered = run_once(&operation, &messages).await;
|
||||
@@ -284,11 +277,11 @@ async fn running_subagents_are_delivered_one_per_pass_and_started_once() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_already_finished_subagent_does_not_hold_back_the_others() {
|
||||
let runner = Arc::new(fake(&["a", "b"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
runner.finished("a", SubagentOutcome::Completed("a done".into()));
|
||||
let _b = runner.running("b");
|
||||
|
||||
let delivered = run_once(&operation(&runner), &[kickoff()]).await;
|
||||
let delivered = run_once(&operation(&runner), &[start(&["a", "b"])]).await;
|
||||
|
||||
assert_eq!(texts(&delivered), ["Subagent a completed: a done"]);
|
||||
assert_eq!(runner.started(), ["a", "b"]);
|
||||
@@ -297,17 +290,17 @@ async fn an_already_finished_subagent_does_not_hold_back_the_others() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_subagent_cancelled_elsewhere_is_reported_and_not_restarted() {
|
||||
let runner = Arc::new(fake(&["a"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
let a = runner.running("a");
|
||||
let operation = operation(&runner);
|
||||
let mut messages = vec![kickoff()];
|
||||
let mut messages = vec![start(&["a"])];
|
||||
|
||||
a.finish(SubagentOutcome::Cancelled);
|
||||
let delivered = run_once(&operation, &messages).await;
|
||||
|
||||
assert_eq!(
|
||||
texts(&delivered),
|
||||
["Subagent a was cancelled before it finished and will not run again."]
|
||||
["Subagent a was cancelled before it finished."]
|
||||
);
|
||||
messages.extend(delivered);
|
||||
assert!(run_once(&operation, &messages).await.is_empty());
|
||||
@@ -316,12 +309,12 @@ async fn a_subagent_cancelled_elsewhere_is_reported_and_not_restarted() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_delivers_finished_subagents_and_cancels_running_and_queued_children() {
|
||||
let runner = Arc::new(fake(&["a", "b", "c"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
let a = runner.running("a");
|
||||
let b = runner.running("b");
|
||||
runner.finished("c", SubagentOutcome::Completed("c done".into()));
|
||||
let operation = operation(&runner).with_max_concurrency(NonZeroUsize::new(2).unwrap());
|
||||
let mut messages = vec![kickoff()];
|
||||
let mut messages = vec![start(&["a", "b", "c"])];
|
||||
|
||||
interrupt(&operation, &messages);
|
||||
assert_eq!(runner.started(), ["a", "b"]);
|
||||
@@ -334,8 +327,8 @@ async fn stop_delivers_finished_subagents_and_cancels_running_and_queued_childre
|
||||
texts(&saved),
|
||||
[
|
||||
"Subagent a completed: a done",
|
||||
"Subagent b was cancelled before it finished and will not run again.\n\
|
||||
Subagent c was cancelled before it finished and will not run again.",
|
||||
"Subagent b was cancelled before it finished.\n\
|
||||
Subagent c was cancelled before it finished.",
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -350,16 +343,42 @@ async fn stop_delivers_finished_subagents_and_cancels_running_and_queued_childre
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_repeated_id_starts_once() {
|
||||
let runner = Arc::new(fake(&["x", "x"]));
|
||||
runner.finished("x", SubagentOutcome::Failed("boom\ndetails".into()));
|
||||
async fn a_subagent_started_twice_before_it_finishes_runs_once() {
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
runner.finished("x", SubagentOutcome::Completed("done".into()));
|
||||
let operation = operation(&runner);
|
||||
let mut messages = vec![start(&["x"]), start(&["x"])];
|
||||
|
||||
let delivered = run_once(&operation(&runner), &[kickoff()]).await;
|
||||
let delivered = run_once(&operation, &messages).await;
|
||||
assert_eq!(texts(&delivered), ["Subagent x completed: done"]);
|
||||
messages.extend(delivered);
|
||||
|
||||
assert_eq!(texts(&delivered), ["Subagent x failed: boom\ndetails"]);
|
||||
assert!(run_once(&operation, &messages).await.is_empty());
|
||||
assert_eq!(runner.started(), ["x"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_subagent_started_again_runs_until_it_finishes() {
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
runner.finished("x", SubagentOutcome::Failed("boom\ndetails".into()));
|
||||
let operation = operation(&runner);
|
||||
let mut messages = vec![start(&["x"])];
|
||||
|
||||
let delivered = run_once(&operation, &messages).await;
|
||||
assert_eq!(texts(&delivered), ["Subagent x failed: boom\ndetails"]);
|
||||
messages.extend(delivered);
|
||||
assert!(run_once(&operation, &messages).await.is_empty());
|
||||
|
||||
messages.push(start(&["x"]));
|
||||
runner.finished("x", SubagentOutcome::Completed("done".into()));
|
||||
let delivered = run_once(&operation, &messages).await;
|
||||
assert_eq!(texts(&delivered), ["Subagent x completed: done"]);
|
||||
messages.extend(delivered);
|
||||
|
||||
assert!(run_once(&operation, &messages).await.is_empty());
|
||||
assert_eq!(runner.started(), ["x", "x"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_the_notes_goose_saves_today() {
|
||||
let mut delivered = Message::user()
|
||||
@@ -374,9 +393,9 @@ async fn reads_the_notes_goose_saves_today() {
|
||||
cancelled
|
||||
.metadata
|
||||
.set_operation_note("foreground_subagent", "cancelled", json!(["b"]));
|
||||
let messages = vec![kickoff(), delivered, cancelled];
|
||||
let messages = vec![start(&["a", "b", "c"]), delivered, cancelled];
|
||||
|
||||
let runner = Arc::new(fake(&["a", "b", "c"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
runner.finished("c", SubagentOutcome::Completed("c done".into()));
|
||||
let delivered = run_once(&operation(&runner), &messages).await;
|
||||
|
||||
@@ -386,14 +405,14 @@ async fn reads_the_notes_goose_saves_today() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn messages_from_a_running_subagent_reach_the_parent_before_its_result() {
|
||||
let runner = Arc::new(fake(&["a"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
let a = runner.running("a");
|
||||
let operation = operation(&runner);
|
||||
let (emit, mut rx) = watched_emitter();
|
||||
|
||||
a.to_parent("may I run cargo test?");
|
||||
a.finish(SubagentOutcome::Completed("done".into()));
|
||||
let delivered = run_once_with(&operation, &[kickoff()], &emit).await;
|
||||
let delivered = run_once_with(&operation, &[start(&["a"])], &emit).await;
|
||||
|
||||
assert_eq!(shown(&mut rx), ["may I run cargo test?"]);
|
||||
assert_eq!(texts(&delivered), ["Subagent a completed: done"]);
|
||||
@@ -401,10 +420,10 @@ async fn messages_from_a_running_subagent_reach_the_parent_before_its_result() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_subagent_whose_updates_end_without_an_outcome_has_failed() {
|
||||
let runner = Arc::new(fake(&["a"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
drop(runner.running("a"));
|
||||
|
||||
let delivered = run_once(&operation(&runner), &[kickoff()]).await;
|
||||
let delivered = run_once(&operation(&runner), &[start(&["a"])]).await;
|
||||
|
||||
assert_eq!(
|
||||
texts(&delivered),
|
||||
@@ -414,7 +433,7 @@ async fn a_subagent_whose_updates_end_without_an_outcome_has_failed() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn updates_after_the_outcome_are_ignored() {
|
||||
let runner = Arc::new(fake(&["a"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
let a = runner.running("a");
|
||||
let operation = operation(&runner);
|
||||
let (emit, mut rx) = watched_emitter();
|
||||
@@ -422,7 +441,7 @@ async fn updates_after_the_outcome_are_ignored() {
|
||||
a.finish(SubagentOutcome::Completed("done".into()));
|
||||
a.to_parent("too late");
|
||||
a.finish(SubagentOutcome::Failed("again".into()));
|
||||
let delivered = run_once_with(&operation, &[kickoff()], &emit).await;
|
||||
let delivered = run_once_with(&operation, &[start(&["a"])], &emit).await;
|
||||
|
||||
assert_eq!(texts(&delivered), ["Subagent a completed: done"]);
|
||||
assert!(shown(&mut rx).is_empty());
|
||||
@@ -431,10 +450,10 @@ async fn updates_after_the_outcome_are_ignored() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_skips_messages_queued_ahead_of_a_finished_result() {
|
||||
let runner = Arc::new(fake(&["a"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
let a = runner.running("a");
|
||||
let operation = operation(&runner);
|
||||
let messages = [kickoff()];
|
||||
let messages = [start(&["a"])];
|
||||
let (emit, mut rx) = watched_emitter();
|
||||
|
||||
interrupt(&operation, &messages);
|
||||
@@ -448,12 +467,12 @@ async fn stop_skips_messages_queued_ahead_of_a_finished_result() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrency_limit_queues_subagents_until_a_slot_is_available() {
|
||||
let runner = Arc::new(fake(&["a", "b", "c"]));
|
||||
let runner = Arc::new(FakeRunner::default());
|
||||
let a = runner.running("a");
|
||||
let b = runner.running("b");
|
||||
let c = runner.running("c");
|
||||
let operation = operation(&runner).with_max_concurrency(NonZeroUsize::new(2).unwrap());
|
||||
let mut messages = vec![kickoff()];
|
||||
let mut messages = vec![start(&["a", "b", "c"])];
|
||||
|
||||
interrupt(&operation, &messages);
|
||||
assert_eq!(runner.started(), ["a", "b"]);
|
||||
|
||||
@@ -54,8 +54,11 @@ pub struct DelegateParams {
|
||||
pub max_turns: Option<usize>,
|
||||
pub context: Option<String>,
|
||||
pub working_dir: Option<String>,
|
||||
pub resume: Option<String>,
|
||||
}
|
||||
|
||||
const DEFAULT_RESUME_INSTRUCTIONS: &str = "Continue the task from where you left off.";
|
||||
|
||||
struct SubagentConfig {
|
||||
provider_name: String,
|
||||
model_config: goose_providers::model::ModelConfig,
|
||||
@@ -315,6 +318,19 @@ pub fn discover_filesystem_sources(working_dir: &Path) -> Vec<SourceEntry> {
|
||||
sources
|
||||
}
|
||||
|
||||
fn delegated_result(text: String, subagent_id: &str) -> CallToolResult {
|
||||
let mut meta = MetaObject::new();
|
||||
meta.0.insert(
|
||||
"subagent_session_id".to_string(),
|
||||
serde_json::Value::String(subagent_id.to_string()),
|
||||
);
|
||||
meta.0.insert(
|
||||
DELEGATED_META_KEY.to_string(),
|
||||
serde_json::Value::Bool(true),
|
||||
);
|
||||
CallToolResult::success(vec![ContentBlock::text(text)]).with_meta(Some(meta))
|
||||
}
|
||||
|
||||
fn build_instructions_with_context(context: &str, instructions: &str) -> String {
|
||||
let mut result = format!("# Reference Context\n\n{}", context);
|
||||
if !instructions.is_empty() {
|
||||
@@ -462,7 +478,7 @@ impl SummonClient {
|
||||
"properties": {
|
||||
"instructions": {
|
||||
"type": "string",
|
||||
"description": "Task instructions. Required for ad-hoc tasks."
|
||||
"description": "Task instructions. Required for ad-hoc tasks. With `resume`, an optional message for the subagent."
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
@@ -502,6 +518,10 @@ 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."
|
||||
},
|
||||
"resume": {
|
||||
"type": "string",
|
||||
"description": "Subagent ID of a failed or cancelled delegate to continue. Only `instructions` can be combined with it."
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -512,7 +532,8 @@ impl SummonClient {
|
||||
Modes:\n\
|
||||
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\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\
|
||||
Effective Delegation:\n\
|
||||
- Delegates know only instructions + source content\n\
|
||||
- Delegates cannot coordinate. Same-file work = conflicts.\n\
|
||||
@@ -837,7 +858,10 @@ impl SummonClient {
|
||||
.map_err(|e| format!("Invalid parameters: {}", e))?
|
||||
.unwrap_or_default();
|
||||
|
||||
self.validate_delegate_params(¶ms)?;
|
||||
match params.resume {
|
||||
Some(_) => self.validate_resume_params(¶ms)?,
|
||||
None => self.validate_delegate_params(¶ms)?,
|
||||
}
|
||||
|
||||
let mut session = self
|
||||
.context
|
||||
@@ -851,9 +875,53 @@ impl SummonClient {
|
||||
return Err("Delegated tasks cannot spawn further delegations".to_string());
|
||||
}
|
||||
|
||||
if let Some(subagent_id) = ¶ms.resume {
|
||||
return self
|
||||
.resume_subagent(subagent_id, params.instructions, &session.id)
|
||||
.await;
|
||||
}
|
||||
self.create_subagent(params, &session).await
|
||||
}
|
||||
|
||||
async fn resume_subagent(
|
||||
&self,
|
||||
subagent_id: &str,
|
||||
instructions: Option<String>,
|
||||
parent_id: &str,
|
||||
) -> Result<CallToolResult, String> {
|
||||
let session_manager = &self.context.session_manager;
|
||||
let subagent = session_manager
|
||||
.get_session(subagent_id, true)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to load subagent {subagent_id}: {e}"))?;
|
||||
if subagent.session_type != SessionType::SubAgent
|
||||
|| subagent.parent_session_id.as_deref() != Some(parent_id)
|
||||
{
|
||||
return Err(format!(
|
||||
"Subagent {subagent_id} does not belong to this session"
|
||||
));
|
||||
}
|
||||
if subagent
|
||||
.conversation
|
||||
.as_ref()
|
||||
.and_then(|conversation| FinalOutputTool::successful_output(conversation.messages()))
|
||||
.is_some()
|
||||
{
|
||||
return Err(format!("Subagent {subagent_id} already completed"));
|
||||
}
|
||||
|
||||
let instructions = instructions.unwrap_or_else(|| DEFAULT_RESUME_INSTRUCTIONS.to_string());
|
||||
session_manager
|
||||
.add_message(subagent_id, &Message::user().with_text(instructions))
|
||||
.await
|
||||
.map_err(|e| format!("Failed to save the resume instructions: {e}"))?;
|
||||
|
||||
Ok(delegated_result(
|
||||
format!("Resumed subagent {subagent_id}"),
|
||||
subagent_id,
|
||||
))
|
||||
}
|
||||
|
||||
async fn create_subagent(
|
||||
&self,
|
||||
params: DelegateParams,
|
||||
@@ -938,20 +1006,35 @@ impl SummonClient {
|
||||
.await
|
||||
.map_err(|e| format!("Failed to save delegate task: {e}"))?;
|
||||
|
||||
let mut meta = MetaObject::new();
|
||||
meta.0.insert(
|
||||
"subagent_session_id".to_string(),
|
||||
serde_json::Value::String(child.id.clone()),
|
||||
);
|
||||
meta.0.insert(
|
||||
DELEGATED_META_KEY.to_string(),
|
||||
serde_json::Value::Bool(true),
|
||||
);
|
||||
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
|
||||
"Delegated to subagent {}",
|
||||
child.id
|
||||
))])
|
||||
.with_meta(Some(meta)))
|
||||
Ok(delegated_result(
|
||||
format!("Delegated to subagent {}", child.id),
|
||||
&child.id,
|
||||
))
|
||||
}
|
||||
|
||||
fn validate_resume_params(&self, params: &DelegateParams) -> Result<(), String> {
|
||||
let conflicting: Vec<&str> = [
|
||||
("source", params.source.is_some()),
|
||||
("parameters", params.parameters.is_some()),
|
||||
("extensions", params.extensions.is_some()),
|
||||
("provider", params.provider.is_some()),
|
||||
("model", params.model.is_some()),
|
||||
("temperature", params.temperature.is_some()),
|
||||
("context", params.context.is_some()),
|
||||
("working_dir", params.working_dir.is_some()),
|
||||
("max_turns", params.max_turns.is_some()),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(name, set)| set.then_some(name))
|
||||
.collect();
|
||||
if !conflicting.is_empty() {
|
||||
return Err(format!(
|
||||
"'resume' only accepts 'instructions'; remove {}",
|
||||
conflicting.join(", ")
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_delegate_params(&self, params: &DelegateParams) -> Result<(), String> {
|
||||
@@ -1664,6 +1747,173 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
async fn create_session(
|
||||
manager: &crate::session::SessionManager,
|
||||
temp_dir: &TempDir,
|
||||
session_type: SessionType,
|
||||
parent_id: Option<&str>,
|
||||
) -> Result<Session> {
|
||||
let session = manager
|
||||
.create_session(
|
||||
temp_dir.path().to_path_buf(),
|
||||
"session".to_string(),
|
||||
session_type,
|
||||
GooseMode::Auto,
|
||||
)
|
||||
.await?;
|
||||
manager
|
||||
.update(&session.id)
|
||||
.parent_session_id(parent_id.map(str::to_owned))
|
||||
.apply()
|
||||
.await?;
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
async fn resume(
|
||||
client: &SummonClient,
|
||||
session_id: &str,
|
||||
args: serde_json::Value,
|
||||
) -> Result<CallToolResult, String> {
|
||||
client
|
||||
.handle_delegate(session_id, Path::new(""), args.as_object().cloned())
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delegate_resume_continues_the_saved_subagent() -> 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 subagent =
|
||||
create_session(&manager, &temp_dir, SessionType::SubAgent, Some(&parent.id)).await?;
|
||||
let client = SummonClient::new(create_test_context_with_session_manager(manager.clone()))?;
|
||||
|
||||
let result = resume(
|
||||
&client,
|
||||
&parent.id,
|
||||
serde_json::json!({
|
||||
"resume": subagent.id,
|
||||
"instructions": "Finish the summary"
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let meta = result.meta.as_ref().unwrap();
|
||||
assert_eq!(
|
||||
meta.0.get(DELEGATED_META_KEY),
|
||||
Some(&serde_json::json!(true))
|
||||
);
|
||||
assert_eq!(
|
||||
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");
|
||||
|
||||
resume(
|
||||
&client,
|
||||
&parent.id,
|
||||
serde_json::json!({"resume": subagent.id}),
|
||||
)
|
||||
.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);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delegate_resume_rejects_subagents_it_cannot_resume() -> 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 other_parent = create_session(&manager, &temp_dir, SessionType::User, None).await?;
|
||||
let subagent =
|
||||
create_session(&manager, &temp_dir, SessionType::SubAgent, Some(&parent.id)).await?;
|
||||
let others = create_session(
|
||||
&manager,
|
||||
&temp_dir,
|
||||
SessionType::SubAgent,
|
||||
Some(&other_parent.id),
|
||||
)
|
||||
.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?;
|
||||
let client = SummonClient::new(create_test_context_with_session_manager(manager.clone()))?;
|
||||
|
||||
for (session_id, args, expected) in [
|
||||
(
|
||||
&parent.id,
|
||||
serde_json::json!({"resume": others.id}),
|
||||
"does not belong to this session",
|
||||
),
|
||||
(
|
||||
&parent.id,
|
||||
serde_json::json!({"resume": completed.id}),
|
||||
"already completed",
|
||||
),
|
||||
(
|
||||
&parent.id,
|
||||
serde_json::json!({"resume": "missing"}),
|
||||
"Failed to load subagent missing",
|
||||
),
|
||||
(
|
||||
&subagent.id,
|
||||
serde_json::json!({"resume": subagent.id}),
|
||||
"Delegated tasks cannot spawn further delegations",
|
||||
),
|
||||
(
|
||||
&parent.id,
|
||||
serde_json::json!({"resume": subagent.id, "model": "other"}),
|
||||
"'resume' only accepts 'instructions'; remove model",
|
||||
),
|
||||
(
|
||||
&parent.id,
|
||||
serde_json::json!({"resume": subagent.id, "max_turns": 5}),
|
||||
"'resume' only accepts 'instructions'; remove max_turns",
|
||||
),
|
||||
] {
|
||||
let error = resume(&client, session_id, args.clone()).await.unwrap_err();
|
||||
assert!(error.contains(expected), "{args}: {error}");
|
||||
}
|
||||
let untouched = manager.get_session(&subagent.id, true).await?;
|
||||
assert!(untouched.conversation.as_ref().unwrap().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn instructions_follow_the_calling_working_dir() {
|
||||
let old_working_dir = TempDir::new().unwrap();
|
||||
|
||||
@@ -8,7 +8,6 @@ use crate::agents::final_output_tool::FinalOutputTool;
|
||||
use crate::agents::state_machine::Emitter;
|
||||
use crate::agents::subagent_handler::ForegroundSubagentRunner;
|
||||
use crate::conversation::message::{Message, MessageContent, SystemNotificationType};
|
||||
use crate::conversation::Conversation;
|
||||
use crate::session::{Session, SessionType};
|
||||
use crate::utils::safe_truncate;
|
||||
|
||||
@@ -87,18 +86,15 @@ fn readable_output(output: &str) -> String {
|
||||
|
||||
#[async_trait]
|
||||
impl SubagentRunner<Session> for ForegroundSubagentRunner {
|
||||
fn started_subagent_session_ids(
|
||||
fn requested_subagent_session_ids(
|
||||
&self,
|
||||
parent_session: &Session,
|
||||
conversation: &Conversation,
|
||||
message: &Message,
|
||||
) -> Vec<String> {
|
||||
if parent_session.session_type == SessionType::SubAgent {
|
||||
return Vec::new();
|
||||
}
|
||||
conversation
|
||||
.messages()
|
||||
.iter()
|
||||
.flat_map(|message| delegated_subagent_ids(&message.content))
|
||||
delegated_subagent_ids(&message.content)
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
@@ -167,6 +163,7 @@ mod tests {
|
||||
ConversationEffect, GooseEffect, Operation, OperationResult, RunStatus,
|
||||
};
|
||||
use crate::config::GooseMode;
|
||||
use crate::conversation::Conversation;
|
||||
use crate::session::SessionManager;
|
||||
use goose_agent::machine::EffectHandler;
|
||||
|
||||
@@ -311,22 +308,18 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn successful_foreground_delegations_are_the_started_subagents() -> Result<()> {
|
||||
async fn a_message_starts_its_successful_foreground_delegations() -> Result<()> {
|
||||
let fixture = fixture().await?;
|
||||
let mut failed_delegate = delegate_result("failed", true);
|
||||
failed_delegate.is_error = Some(true);
|
||||
let conversation = Conversation::new_unvalidated(vec![
|
||||
Message::user().with_text("delegate"),
|
||||
Message::user()
|
||||
.with_tool_response("a", Ok(delegate_result("first", true)))
|
||||
.with_tool_response("b", Ok(delegate_result("background", false)))
|
||||
.with_tool_response("c", Ok(failed_delegate))
|
||||
.with_tool_response(
|
||||
"d",
|
||||
Ok(CallToolResult::success(vec![ContentBlock::text("done")])),
|
||||
),
|
||||
delegate_message("second"),
|
||||
]);
|
||||
let mixed = Message::user()
|
||||
.with_tool_response("a", Ok(delegate_result("first", true)))
|
||||
.with_tool_response("b", Ok(delegate_result("background", false)))
|
||||
.with_tool_response("c", Ok(failed_delegate))
|
||||
.with_tool_response(
|
||||
"d",
|
||||
Ok(CallToolResult::success(vec![ContentBlock::text("done")])),
|
||||
);
|
||||
let mut parent = fixture
|
||||
.manager
|
||||
.get_session(&fixture.parent_id, false)
|
||||
@@ -334,12 +327,19 @@ mod tests {
|
||||
let runner = fixture.runner();
|
||||
|
||||
assert_eq!(
|
||||
runner.started_subagent_session_ids(&parent, &conversation),
|
||||
["first", "second"]
|
||||
runner.requested_subagent_session_ids(&parent, &mixed),
|
||||
["first"]
|
||||
);
|
||||
assert_eq!(
|
||||
runner.requested_subagent_session_ids(&parent, &delegate_message("second")),
|
||||
["second"]
|
||||
);
|
||||
assert!(runner
|
||||
.requested_subagent_session_ids(&parent, &Message::user().with_text("delegate"))
|
||||
.is_empty());
|
||||
parent.session_type = SessionType::SubAgent;
|
||||
assert!(runner
|
||||
.started_subagent_session_ids(&parent, &conversation)
|
||||
.requested_subagent_session_ids(&parent, &mixed)
|
||||
.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use serde_json::json;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::calculator_extension::{delayed_value, value, CalculatorExtension, ADD};
|
||||
use super::dummy_api::{DummyApi, ProviderFeatures};
|
||||
use super::dummy_api::{ApiCall, DummyApi, ProviderFeatures};
|
||||
use super::pipeline::calculator_extension;
|
||||
use crate::acp::server::GooseAcpAgent;
|
||||
use crate::agents::extension::ExtensionConfig;
|
||||
@@ -1324,13 +1324,16 @@ async fn concurrent_subagents_get_their_own_answers_for_the_same_tool_call_id()
|
||||
fn install_hook_log(
|
||||
agent: &mut Arc<Agent>,
|
||||
events: &[&str],
|
||||
delay_seconds: u64,
|
||||
) -> Result<(tempfile::TempDir, std::path::PathBuf)> {
|
||||
let hook_dir = tempfile::tempdir()?;
|
||||
let plugin_dir = hook_dir.path().join("test-plugin");
|
||||
std::fs::create_dir_all(plugin_dir.join("hooks"))?;
|
||||
let log_command = json!([{ "hooks": [{
|
||||
"type": "command",
|
||||
"command": "payload=$(cat); printf '%s\\n' \"$payload\" >> \"$PLUGIN_ROOT/hook.log\""
|
||||
"command": format!(
|
||||
"payload=$(cat); sleep {delay_seconds}; printf '%s\\n' \"$payload\" >> \"$PLUGIN_ROOT/hook.log\""
|
||||
)
|
||||
}] }]);
|
||||
let hooks: serde_json::Map<String, serde_json::Value> = events
|
||||
.iter()
|
||||
@@ -1370,7 +1373,7 @@ async fn cancelling_the_parent_ends_a_waiting_subagent() -> Result<()> {
|
||||
("OPENAI_BASE_PATH", Some("chat/completions")),
|
||||
("OPENAI_CUSTOM_HEADERS", Some("")),
|
||||
]);
|
||||
let (_hook_dir, hook_log) = install_hook_log(&mut agent, &["SessionEnd"])?;
|
||||
let (_hook_dir, hook_log) = install_hook_log(&mut agent, &["SessionEnd"], 0)?;
|
||||
agent
|
||||
.config
|
||||
.session_manager
|
||||
@@ -1379,19 +1382,7 @@ async fn cancelling_the_parent_ends_a_waiting_subagent() -> Result<()> {
|
||||
.apply()
|
||||
.await?;
|
||||
enable_developer(&agent, &session_id).await?;
|
||||
agent
|
||||
.extension_manager
|
||||
.enable(
|
||||
&session_id,
|
||||
ExtensionConfig::Platform {
|
||||
name: "summon".to_string(),
|
||||
description: "Delegate work".to_string(),
|
||||
display_name: None,
|
||||
bundled: None,
|
||||
available_tools: Vec::new(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
enable_summon(&agent, &session_id).await?;
|
||||
api.on("hand this off").call(
|
||||
"delegate",
|
||||
json!({ "instructions": "wait for approval", "max_turns": 3 }),
|
||||
@@ -1399,38 +1390,7 @@ async fn cancelling_the_parent_ends_a_waiting_subagent() -> Result<()> {
|
||||
api.on("wait for approval")
|
||||
.call("shell", json!({ "command": "echo never" }));
|
||||
|
||||
let cancel = CancellationToken::new();
|
||||
let mut stream = agent
|
||||
.reply(
|
||||
Message::user().with_text("hand this off"),
|
||||
SessionConfig {
|
||||
id: session_id.clone(),
|
||||
schedule_id: None,
|
||||
max_turns: Some(3),
|
||||
},
|
||||
Some(cancel.clone()),
|
||||
)
|
||||
.await?;
|
||||
while let Some(event) = stream.next().await {
|
||||
let AgentEvent::Message(message) = event? else {
|
||||
continue;
|
||||
};
|
||||
for content in &message.content {
|
||||
let MessageContent::ActionRequired(action) = content else {
|
||||
continue;
|
||||
};
|
||||
let ActionRequiredData::ToolConfirmation { id, tool_name, .. } = &action.data else {
|
||||
continue;
|
||||
};
|
||||
if tool_name == "shell" {
|
||||
cancel.cancel();
|
||||
} else {
|
||||
agent
|
||||
.submit_tool_confirmation(&session_id, id, Permission::AllowOnce)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
reply_approving(&agent, &session_id, "hand this off", Some("shell")).await?;
|
||||
|
||||
let subagent_id = tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
@@ -1454,6 +1414,223 @@ async fn cancelling_the_parent_ends_a_waiting_subagent() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn enable_summon(agent: &Arc<Agent>, session_id: &str) -> Result<()> {
|
||||
agent
|
||||
.extension_manager
|
||||
.enable(
|
||||
session_id,
|
||||
ExtensionConfig::Platform {
|
||||
name: "summon".to_string(),
|
||||
description: "Delegate work".to_string(),
|
||||
display_name: None,
|
||||
bundled: None,
|
||||
available_tools: Vec::new(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delegated_subagent_id(agent: &Arc<Agent>, session_id: &str) -> Result<String> {
|
||||
let session = agent
|
||||
.config
|
||||
.session_manager
|
||||
.get_session(session_id, true)
|
||||
.await?;
|
||||
session
|
||||
.conversation
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.messages()
|
||||
.iter()
|
||||
.flat_map(|message| &message.content)
|
||||
.find_map(|content| {
|
||||
let MessageContent::ToolResponse(response) = content else {
|
||||
return None;
|
||||
};
|
||||
let meta = response.tool_result.as_ref().ok()?.meta.as_ref()?;
|
||||
meta.0
|
||||
.get("subagent_session_id")?
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
})
|
||||
.ok_or_else(|| anyhow::anyhow!("no delegated subagent"))
|
||||
}
|
||||
|
||||
async fn parent_texts(agent: &Arc<Agent>, session_id: &str) -> Result<Vec<String>> {
|
||||
let session = agent
|
||||
.config
|
||||
.session_manager
|
||||
.get_session(session_id, true)
|
||||
.await?;
|
||||
Ok(session
|
||||
.conversation
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.messages()
|
||||
.iter()
|
||||
.map(Message::as_concat_text)
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn reply_approving(
|
||||
agent: &Arc<Agent>,
|
||||
session_id: &str,
|
||||
text: &str,
|
||||
stop_at_tool: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let cancel = CancellationToken::new();
|
||||
let mut stream = agent
|
||||
.reply(
|
||||
Message::user().with_text(text),
|
||||
SessionConfig {
|
||||
id: session_id.to_string(),
|
||||
schedule_id: None,
|
||||
max_turns: Some(3),
|
||||
},
|
||||
Some(cancel.clone()),
|
||||
)
|
||||
.await?;
|
||||
while let Some(event) = stream.next().await {
|
||||
let AgentEvent::Message(message) = event? else {
|
||||
continue;
|
||||
};
|
||||
for content in &message.content {
|
||||
let MessageContent::ActionRequired(action) = content else {
|
||||
continue;
|
||||
};
|
||||
let ActionRequiredData::ToolConfirmation { id, tool_name, .. } = &action.data else {
|
||||
continue;
|
||||
};
|
||||
if Some(tool_name.as_str()) == stop_at_tool {
|
||||
cancel.cancel();
|
||||
} else {
|
||||
agent
|
||||
.submit_tool_confirmation(session_id, id, Permission::AllowOnce)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn resume_until_completed(
|
||||
agent: &Arc<Agent>,
|
||||
api: &DummyApi,
|
||||
session_id: &str,
|
||||
subagent_id: &str,
|
||||
) -> Result<ApiCall> {
|
||||
api.on("resume it").call(
|
||||
"delegate",
|
||||
json!({ "resume": subagent_id, "instructions": "finish the count" }),
|
||||
);
|
||||
api.on("finish the count").call(
|
||||
crate::agents::final_output_tool::FINAL_OUTPUT_TOOL_NAME,
|
||||
json!({ "summary": "counted after resume" }),
|
||||
);
|
||||
api.on("counted after resume").reply("all done");
|
||||
reply_approving(agent, session_id, "resume it", None).await?;
|
||||
|
||||
assert!(parent_texts(agent, session_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(
|
||||
|text| text.starts_with(&format!("Subagent {subagent_id} completed"))
|
||||
&& text.contains("counted after resume")
|
||||
));
|
||||
api.calls()
|
||||
.into_iter()
|
||||
.find(|call| {
|
||||
call.session_id() == Some(subagent_id) && call.input_contains("finish the count")
|
||||
})
|
||||
.ok_or_else(|| anyhow::anyhow!("the resumed subagent did not call the model"))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_subagent_that_ran_out_of_turns_finishes_after_resume() -> Result<()> {
|
||||
let (agent, api, session_id, _temp_dir) = agent_with_dummy_api().await?;
|
||||
let host = api.uri();
|
||||
let _guard = env_lock::lock_env([
|
||||
("OPENAI_API_KEY", Some("fake-openai-no-keyring")),
|
||||
("OPENAI_HOST", Some(host.as_str())),
|
||||
("OPENAI_BASE_PATH", Some("chat/completions")),
|
||||
("OPENAI_CUSTOM_HEADERS", Some("")),
|
||||
]);
|
||||
enable_developer(&agent, &session_id).await?;
|
||||
enable_summon(&agent, &session_id).await?;
|
||||
api.on("hand this off").call(
|
||||
"delegate",
|
||||
json!({ "instructions": "count the files", "max_turns": 1 }),
|
||||
);
|
||||
api.on("count the files")
|
||||
.call("shell", json!({ "command": "echo partial-progress" }));
|
||||
api.on("max turns reached")
|
||||
.reply("the subagent ran out of turns");
|
||||
|
||||
reply_approving(&agent, &session_id, "hand this off", None).await?;
|
||||
let subagent_id = delegated_subagent_id(&agent, &session_id).await?;
|
||||
assert!(
|
||||
parent_texts(&agent, &session_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|text| text
|
||||
.starts_with(&format!("Subagent {subagent_id} failed: max turns reached")))
|
||||
);
|
||||
|
||||
let resumed_request = resume_until_completed(&agent, &api, &session_id, &subagent_id).await?;
|
||||
assert!(resumed_request.input_contains("partial-progress"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stopped_subagent_is_released_before_a_slow_session_end_hook_and_resumes() -> Result<()> {
|
||||
let (mut agent, api, session_id, _temp_dir) = agent_with_dummy_api().await?;
|
||||
let host = api.uri();
|
||||
let _guard = env_lock::lock_env([
|
||||
("OPENAI_API_KEY", Some("fake-openai-no-keyring")),
|
||||
("OPENAI_HOST", Some(host.as_str())),
|
||||
("OPENAI_BASE_PATH", Some("chat/completions")),
|
||||
("OPENAI_CUSTOM_HEADERS", Some("")),
|
||||
]);
|
||||
let (_hook_dir, hook_log) = install_hook_log(&mut agent, &["SessionEnd"], 2)?;
|
||||
agent
|
||||
.config
|
||||
.session_manager
|
||||
.update(&session_id)
|
||||
.goose_mode(GooseMode::Approve)
|
||||
.apply()
|
||||
.await?;
|
||||
enable_developer(&agent, &session_id).await?;
|
||||
enable_summon(&agent, &session_id).await?;
|
||||
api.on("hand this off").call(
|
||||
"delegate",
|
||||
json!({ "instructions": "wait for approval", "max_turns": 3 }),
|
||||
);
|
||||
api.on("wait for approval")
|
||||
.call("shell", json!({ "command": "echo never" }));
|
||||
|
||||
reply_approving(&agent, &session_id, "hand this off", Some("shell")).await?;
|
||||
let subagent_id = delegated_subagent_id(&agent, &session_id).await?;
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while agent.tracks_confirmations_for(&subagent_id)
|
||||
|| !agent
|
||||
.extension_manager
|
||||
.scope_lease(&subagent_id)
|
||||
.await
|
||||
.configs()
|
||||
.is_empty()
|
||||
{
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
assert!(hook_sessions(&hook_log, "SessionEnd").is_empty());
|
||||
|
||||
let resumed_request = resume_until_completed(&agent, &api, &session_id, &subagent_id).await?;
|
||||
assert!(resumed_request.answers_every_tool_call_next());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_parent_tool_call_id_that_looks_forwarded_is_still_the_parents() -> Result<()> {
|
||||
let (agent, api, session_id, _temp_dir) = agent_with_dummy_api().await?;
|
||||
|
||||
@@ -223,10 +223,10 @@ impl Drop for SubagentEnding {
|
||||
}
|
||||
|
||||
async fn end_subagent(agent: &Agent, subagent_id: &str) {
|
||||
agent.release_session(subagent_id).await;
|
||||
agent
|
||||
.emit_hook(crate::hooks::HookEvent::SessionEnd, subagent_id)
|
||||
.await;
|
||||
agent.release_session(subagent_id).await;
|
||||
}
|
||||
|
||||
fn forwarded(
|
||||
|
||||
@@ -695,6 +695,9 @@ function ToolCallView({
|
||||
return `capturing screen`;
|
||||
|
||||
case 'delegate': {
|
||||
if (args.resume) {
|
||||
return `resuming subagent ${getStringValue(args.resume)}`;
|
||||
}
|
||||
if (args.instructions) {
|
||||
const instr = getStringValue(args.instructions);
|
||||
const truncated = instr.length > 80 ? instr.substring(0, 80) + '…' : instr;
|
||||
|
||||
Reference in New Issue
Block a user