From 3bd852002903e016ff30947e973f76e2fcfcf90f Mon Sep 17 00:00:00 2001 From: Lifei Zhou Date: Fri, 9 Oct 2026 21:01:04 +0000 Subject: [PATCH] agent-loop: changed yield_to_customer to next enum (#12789) --- crates/goose-agent/README.md | 6 +- crates/goose-agent/src/machine.rs | 55 ++++++++++--------- crates/goose-agent/src/operation.rs | 15 +++-- crates/goose-agent/tests/tool_operation.rs | 3 +- crates/goose/src/agents/state_machine/mod.rs | 2 +- .../state_machine/ops_foreground_subagent.rs | 4 +- .../goose/src/agents/state_machine/session.rs | 14 +---- .../tests/compaction_lifecycle.rs | 9 +-- .../agents/state_machine/tests/pipeline.rs | 45 ++++++++------- crates/goose/tests/state_machine_api.rs | 8 +-- 10 files changed, 82 insertions(+), 79 deletions(-) diff --git a/crates/goose-agent/README.md b/crates/goose-agent/README.md index 96372d1d2..691cc6142 100644 --- a/crates/goose-agent/README.md +++ b/crates/goose-agent/README.md @@ -26,8 +26,10 @@ is a function of the persisted conversation, not of in-memory loop state. boundaries. Their schemas are sent to inference and matching calls are dispatched against the current session. - **`StateMachine<'a, S, E>`** — holds `Vec>` and a `CancellationToken`. - `step()` runs one pass, `apply()` writes effects back, `run()` loops until a - step yields to the client or no step applies. + `step()` runs one pass and returns a `StepResult` whose `applied_step` names + the step that applied (`None` if none did) and whose `status` says whether the + run is `Continuing`, `Yielded` to the client, or `Cancelled`; `apply()` writes + effects back; `run()` loops while `status` is `Continuing`. - **`ConversationEffect`** — the default effect type: `AppendMessage`, `ReplaceConversation`, `PatchToolRequestMeta`, `SetMessageVisibility`. Bring your own by implementing `MachineEffect`. diff --git a/crates/goose-agent/src/machine.rs b/crates/goose-agent/src/machine.rs index 475037724..423bdc6d9 100644 --- a/crates/goose-agent/src/machine.rs +++ b/crates/goose-agent/src/machine.rs @@ -9,7 +9,7 @@ use tokio_util::sync::CancellationToken; use crate::operation::{ messages_since_kickoff, ConversationEffect, Emitter, Inference, InferenceInput, MachineEffect, - Operation, OperationResult, StepResult, + Operation, OperationResult, RunStatus, StepResult, }; use goose_provider_types::conversation::message::{Message, MessageContent}; use goose_provider_types::conversation::Conversation; @@ -58,6 +58,14 @@ pub struct StateMachine<'a, S, E = ConversationEffect> { interrupted_step: Mutex>, } +fn empty_result(status: RunStatus) -> StepResult { + StepResult { + effects: Vec::new(), + applied_step: None, + status, + } +} + fn interrupted_response(messages: &[Message]) -> Option { let answered = messages .iter() @@ -110,7 +118,7 @@ where } } - pub async fn step(&self, session: &S, emit: &Emitter) -> Result>> { + pub async fn step(&self, session: &S, emit: &Emitter) -> Result> { let conversation = session .conversation() .ok_or_else(|| anyhow!("state-machine session loaded without conversation"))?; @@ -118,7 +126,7 @@ where for (index, step) in self.steps.iter().enumerate() { let name = step.operation().name(); if self.cancel.is_cancelled() { - return Ok(None); + return Ok(empty_result(RunStatus::Cancelled)); } let execution = async { match step { @@ -158,44 +166,46 @@ where Some(Err(error)) if !self.cancel.is_cancelled() => return Err(error), _ => { *self.interrupted_step.lock().unwrap() = Some(index); - return Ok(None); + return Ok(empty_result(RunStatus::Cancelled)); } }; match result { OperationResult::NotApplicable => {} OperationResult::Applied(mut result) => { + tracing::debug!(step = name, "applied step"); result.applied_step = Some(name); for effect in &mut result.effects { effect.ensure_message_ids(); } if self.cancel.is_cancelled() { - result.yield_to_client = true; + result.status = RunStatus::Cancelled; } - return Ok(Some(result)); + return Ok(result); } } } - Ok(None) + Ok(empty_result(RunStatus::Yielded)) } pub async fn apply( &self, runtime: &R, session: &S, - result: &mut StepResult, + effects: &mut [E], emit: &Emitter, ) -> Result<()> where R: EffectHandler, { - for effect in &mut result.effects { + if effects.is_empty() { + return Ok(()); + } + for effect in effects.iter_mut() { effect.ensure_message_ids(); } - runtime - .apply_effects(session, &mut result.effects, emit) - .await + runtime.apply_effects(session, effects, emit).await } pub async fn run(&self, runtime: &R, session_id: &str, emit: &Emitter) -> Result @@ -204,12 +214,12 @@ where { loop { let session = runtime.load(session_id).await?; - let Some(mut result) = self.step(&session, emit).await? else { - break; - }; - self.apply(runtime, &session, &mut result, emit).await?; - if result.yield_to_client { - break; + let mut result = self.step(&session, emit).await?; + self.apply(runtime, &session, &mut result.effects, emit) + .await?; + match result.status { + RunStatus::Continuing => {} + RunStatus::Yielded | RunStatus::Cancelled => break, } } self.finalize(runtime, session_id, emit).await @@ -278,7 +288,7 @@ where runtime: &R, session_id: &str, session: S, - effects: Vec, + mut effects: Vec, emit: &Emitter, ) -> Result where @@ -287,12 +297,7 @@ where if effects.is_empty() { return Ok(session); } - let mut result = StepResult { - effects, - applied_step: None, - yield_to_client: true, - }; - self.apply(runtime, &session, &mut result, emit).await?; + self.apply(runtime, &session, &mut effects, emit).await?; runtime.load(session_id).await } } diff --git a/crates/goose-agent/src/operation.rs b/crates/goose-agent/src/operation.rs index 53360da06..426d73ed2 100644 --- a/crates/goose-agent/src/operation.rs +++ b/crates/goose-agent/src/operation.rs @@ -164,10 +164,17 @@ pub trait Inference: Operation Result>; } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RunStatus { + Continuing, + Yielded, + Cancelled, +} + pub struct StepResult { pub effects: Vec, pub applied_step: Option<&'static str>, - pub yield_to_client: bool, + pub status: RunStatus, } pub enum OperationResult { @@ -183,7 +190,7 @@ pub fn applied(effects: impl IntoIterator) -> Result() -> Result> { Ok(OperationResult::Applied(StepResult { effects: Vec::new(), applied_step: None, - yield_to_client: true, + status: RunStatus::Yielded, })) } @@ -199,7 +206,7 @@ pub fn yielded_with(effects: impl IntoIterator) -> Result Resul state_machine::StateMachine::new(Vec::new(), tokio_util::sync::CancellationToken::new()); let (tx, _rx) = tokio::sync::mpsc::unbounded_channel(); let emit = state_machine::Emitter::new(tx, tokio_util::sync::CancellationToken::new()); - let apply = async |effects: Vec| -> Result<()> { + let apply = async |mut effects: Vec| -> Result<()> { let session = pipeline.session().await?; - let mut result = state_machine::StepResult { - effects, - applied_step: None, - yield_to_client: false, - }; machine .apply( pipeline.session_manager.as_ref(), &session, - &mut result, + &mut effects, &emit, ) .await diff --git a/crates/goose/src/agents/state_machine/tests/pipeline.rs b/crates/goose/src/agents/state_machine/tests/pipeline.rs index 9d7e17b1b..c1c46f21b 100644 --- a/crates/goose/src/agents/state_machine/tests/pipeline.rs +++ b/crates/goose/src/agents/state_machine/tests/pipeline.rs @@ -18,9 +18,10 @@ use crate::agents::state_machine::{ BangShellOperation, CompactionOperation, DoctorOperation, Emitter, ExitOnErrorOperation, ForegroundSubagentOperation, GooseEffect, GooseInferenceProvider, GooseInferenceRequestPreparer, InferenceRunner, MaxTurnsOperation, Operation, ProjectOperation, - RecipeOperation, RetryOperation, SkillOperation, SlashCommandOperation, StateMachine, - StatusOperation, SteerOperation, SteerQueue, Step, StopHookOperation, ToolApprovalOperation, - ToolExecutionOperation, ToolPairCompactionOperation, UnknownToolOperation, + RecipeOperation, RetryOperation, RunStatus, SkillOperation, SlashCommandOperation, + StateMachine, StatusOperation, SteerOperation, SteerQueue, Step, StopHookOperation, + ToolApprovalOperation, ToolExecutionOperation, ToolPairCompactionOperation, + UnknownToolOperation, }; use crate::agents::subagent_handler::ForegroundSubagentRunner; use crate::agents::AgentEvent; @@ -440,21 +441,25 @@ impl TestPipeline { loop { let session = self.session().await?; let machine = self.machine(cancel.clone()); - let Some(mut result) = machine.step(&session, &emit).await? else { - break; - }; + let mut result = machine.step(&session, &emit).await?; machine - .apply(self.session_manager.as_ref(), &session, &mut result, &emit) + .apply( + self.session_manager.as_ref(), + &session, + &mut result.effects, + &emit, + ) .await?; - applied_steps += 1; + if result.applied_step.is_some() { + applied_steps += 1; + } while let Ok(event) = rx.try_recv() { events.push(event); } - let yield_to_client = result.yield_to_client; drop(machine); self = self.reconstruct().await?; - if yield_to_client { + if result.status != RunStatus::Continuing { break; } } @@ -648,16 +653,18 @@ impl TestPipeline { } } }; - let Some(ref mut result) = result else { - break; - }; machine - .apply(self.session_manager.as_ref(), &session, result, &emit) + .apply( + self.session_manager.as_ref(), + &session, + &mut result.effects, + &emit, + ) .await?; while let Ok(event) = rx.try_recv() { events.push(event); } - if result.yield_to_client { + if result.status != RunStatus::Continuing { break; } } @@ -1128,21 +1135,19 @@ pub(super) async fn run_machine(pipeline: &TestPipeline) -> Result Result<()> { ); let session = session_manager.get_session(&session.id, true).await?; - let mut result = machine.step(&session, &emit).await?.unwrap(); + let mut result = machine.step(&session, &emit).await?; assert!(matches!( result.effects.first(), Some(GooseEffect::Conversation( @@ -124,9 +124,9 @@ async fn custom_pipeline_supports_step_apply_run_and_usage() -> Result<()> { )) if message.id.is_some() )); machine - .apply(&session_manager, &session, &mut result, &emit) + .apply(&session_manager, &session, &mut result.effects, &emit) .await?; - assert!(result.yield_to_client); + assert_eq!(result.status, RunStatus::Yielded); let session = session_manager.get_session(&session.id, true).await?; let persisted = session .conversation