From 3b094d7afe681f78db63f3ce0b95d5124fc3341c Mon Sep 17 00:00:00 2001 From: Douwe Osinga Date: Thu, 8 Oct 2026 18:13:09 +0000 Subject: [PATCH] Delete the legacy agent loop (#12760) Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 6 - CONTRIBUTING.md | 6 - crates/goose-agent/src/inference.rs | 46 +- crates/goose-cli/src/cli.rs | 3 +- crates/goose-cli/src/commands/configure.rs | 2 +- crates/goose-cli/src/session/builder.rs | 11 +- crates/goose-cli/src/session/mod.rs | 36 +- .../src/conversation/message.rs | 60 +- crates/goose/examples/agent.rs | 12 +- crates/goose/src/acp/server.rs | 29 +- crates/goose/src/acp/server/live_voice.rs | 10 - crates/goose/src/acp/server/load_session.rs | 12 +- crates/goose/src/acp/server/tools.rs | 14 +- crates/goose/src/agents/agent.rs | 3727 +---------------- crates/goose/src/agents/execute_commands.rs | 578 +-- .../src/agents/extension_manager/lease.rs | 18 +- .../goose/src/agents/extension_manager/mod.rs | 207 +- crates/goose/src/agents/gen_ai_telemetry.rs | 18 - crates/goose/src/agents/mod.rs | 1 - crates/goose/src/agents/moim.rs | 82 +- .../platform_extensions/code_execution.rs | 13 +- .../agents/platform_extensions/ext_manager.rs | 8 +- .../src/agents/platform_extensions/summon.rs | 397 +- crates/goose/src/agents/prompt_manager.rs | 34 +- crates/goose/src/agents/reply_parts.rs | 664 +-- crates/goose/src/agents/retry.rs | 343 +- .../state_machine/inference_preparation.rs | 12 +- crates/goose/src/agents/state_machine/mod.rs | 9 +- .../state_machine/ops_empty_response.rs | 56 + .../agents/state_machine/ops_entry_hook.rs | 35 +- .../goose/src/agents/state_machine/ops_llm.rs | 188 +- .../src/agents/state_machine/ops_recipe.rs | 3 +- .../src/agents/state_machine/ops_skills.rs | 3 +- .../agents/state_machine/ops_slash_command.rs | 2 +- .../src/agents/state_machine/ops_steer.rs | 2 +- .../agents/state_machine/ops_tool_approval.rs | 10 +- .../agents/state_machine/ops_toolcalling.rs | 23 +- .../goose/src/agents/state_machine/session.rs | 34 +- .../agents/state_machine/tests/agent_reply.rs | 130 +- .../tests/compaction_lifecycle.rs | 38 +- .../agents/state_machine/tests/dummy_api.rs | 72 +- .../state_machine/tests/hooks_lifecycle.rs | 10 + .../src/agents/state_machine/tests/mod.rs | 59 + .../agents/state_machine/tests/pipeline.rs | 54 +- .../tests/prompt_skill_lifecycle.rs | 9 + .../state_machine/tests/provider_lifecycle.rs | 98 +- .../tests/recipe_scheduling_lifecycle.rs | 71 + .../state_machine/tests/tool_lifecycle.rs | 11 +- crates/goose/src/agents/subagent_handler.rs | 304 +- .../src/agents/tool_confirmation_router.rs | 182 - crates/goose/src/agents/tool_execution.rs | 125 +- crates/goose/src/agents/types.rs | 3 - crates/goose/src/execution/manager.rs | 73 - crates/goose/src/gateway/handler.rs | 8 +- crates/goose/src/scheduler/full.rs | 9 +- crates/goose/src/session/session_manager.rs | 131 +- crates/goose/src/tool_call_labels.rs | 5 - .../goose/tests/acp_custom_requests_test.rs | 25 +- crates/goose/tests/acp_server_test.rs | 40 +- crates/goose/tests/agent.rs | 1201 +----- crates/goose/tests/compaction.rs | 433 +- crates/goose/tests/mcp_integration_test.rs | 9 +- crates/goose/tests/providers.rs | 14 +- .../src/acp/__tests__/liveVoice.test.ts | 27 +- ui/desktop/src/acp/liveVoice.ts | 8 +- ui/desktop/src/acp/prompt.ts | 7 +- .../components/settings/AgentLoopSettings.tsx | 222 +- ui/desktop/src/i18n/messages/de.json | 3 - ui/desktop/src/i18n/messages/en.json | 3 - ui/desktop/src/i18n/messages/es.json | 3 - ui/desktop/src/i18n/messages/fr.json | 3 - ui/desktop/src/i18n/messages/hi.json | 3 - ui/desktop/src/i18n/messages/id.json | 3 - ui/desktop/src/i18n/messages/it.json | 3 - ui/desktop/src/i18n/messages/ja.json | 3 - ui/desktop/src/i18n/messages/ko.json | 3 - ui/desktop/src/i18n/messages/ms.json | 3 - ui/desktop/src/i18n/messages/pt.json | 3 - ui/desktop/src/i18n/messages/ru.json | 3 - ui/desktop/src/i18n/messages/tr.json | 3 - ui/desktop/src/i18n/messages/vi.json | 3 - ui/desktop/src/i18n/messages/zh-CN.json | 3 - ui/desktop/src/i18n/messages/zh-TW.json | 3 - ui/desktop/src/main.ts | 1 - ui/desktop/src/utils/settings.ts | 2 - 85 files changed, 1257 insertions(+), 8886 deletions(-) create mode 100644 crates/goose/src/agents/state_machine/ops_empty_response.rs delete mode 100644 crates/goose/src/agents/tool_confirmation_router.rs diff --git a/AGENTS.md b/AGENTS.md index e0156d769..0c458a912 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,12 +36,6 @@ Write issue and pull request comments for humans, not as exhaustive work logs. - Use short paragraphs or bullets, and include implementation details only when they affect a decision or review. - Prefer one clear summary over multiple incremental comments. -## Agent Loop Migration - -We are replacing the legacy agent loop in `crates/goose/src/agents/agent.rs` with the state machine in `crates/goose/src/agents/state_machine/`. The state-machine path is enabled with `GOOSE_STATE_MACHINE=1`. - -Until the migration is complete, changes to agent-loop behavior must be implemented and tested in both paths. When reviewing code, check whether a change to either path also applies to the other and flag missing parity. - ## Setup ```bash source bin/activate-hermit diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a18268339..065bfdf59 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -60,12 +60,6 @@ Pull requests that do not implement a Ready issue will be closed. Automated depe Don't open many pull requests in quick succession. Submit them in order of preference and wait for them to land before opening more. -## Agent Loop Migration - -We are replacing the legacy agent loop in `crates/goose/src/agents/agent.rs` with the state machine in `crates/goose/src/agents/state_machine/`. The state-machine path is enabled with `GOOSE_STATE_MACHINE=1`. - -Until the migration is complete, changes to agent-loop behavior must be implemented and tested in both paths. Pull requests should explain how parity between the two paths was verified. - ## AI Code Reviews We use codex as an AI code reviewer. AI code reviewing has come a long way and more often than not points diff --git a/crates/goose-agent/src/inference.rs b/crates/goose-agent/src/inference.rs index ca0c6ae05..042b450c4 100644 --- a/crates/goose-agent/src/inference.rs +++ b/crates/goose-agent/src/inference.rs @@ -17,8 +17,8 @@ use goose_provider_types::model::ModelConfig; use tracing_futures::Instrument; use crate::operation::{ - applied, messages_since_kickoff, not_applicable, trailing_error, yielded_with, Emitter, - Inference, InferenceInput, Operation, OperationResult, + applied, messages_since_kickoff, not_applicable, trailing_error, Emitter, Inference, + InferenceInput, Operation, OperationResult, }; use goose_provider_types::maybe_send::{MaybeSend, MaybeSync}; @@ -71,8 +71,21 @@ pub trait InferenceEffect: From + MaybeSend + 'static { fn record_usage(usage: ProviderUsage) -> Self; } -const EMPTY_RESPONSE_MESSAGE: &str = +pub const EMPTY_RESPONSE_MESSAGE: &str = "The model returned an empty response. Please resend your message to continue."; +const MAX_EMPTY_RESPONSE_RETRIES: usize = 3; +const EMPTY_RESPONSE_NOTE_SCOPE: &str = "inference"; +const EMPTY_RESPONSE_NOTE: &str = "empty_response"; + +/// The model's response stayed empty after retries. The fallback message is stored +/// hidden so that operations owning the end of a turn (recipe retries, final output) +/// can take over; when none does, it is revealed to the user. +pub fn is_empty_response_marker(message: &Message) -> bool { + message + .metadata + .operation_note(EMPTY_RESPONSE_NOTE_SCOPE, EMPTY_RESPONSE_NOTE) + .is_some() +} const CANCELLED_TOOL_RESPONSE: &str = "Tool call was cancelled before execution"; fn is_thinking(content: &MessageContent) -> bool { @@ -425,6 +438,8 @@ impl Inference for InferenceRunner<'_, S let conversation_for_provider = Conversation::new_unvalidated( merge_consecutive_messages_for_request(fixed.messages().clone()), ); + let mut empty_responses = 0; + let accumulator = loop { let stream = self .provider .stream( @@ -529,12 +544,27 @@ impl Inference for InferenceRunner<'_, S .iter() .any(|message| message.metadata.output_token_limit_reached) && accumulator.iter().all(is_empty_response); - if empty_response { - let message = Message::assistant().with_text(EMPTY_RESPONSE_MESSAGE); - let message = emit.message(message).await; - usage_effects.push(E::from(message)); - return yielded_with(usage_effects); + if !empty_response { + break accumulator; } + if empty_responses < MAX_EMPTY_RESPONSE_RETRIES { + empty_responses += 1; + tracing::warn!( + "Provider returned an empty response; retrying ({empty_responses}/{MAX_EMPTY_RESPONSE_RETRIES})" + ); + continue; + } + let mut marker = Message::assistant() + .with_text(EMPTY_RESPONSE_MESSAGE) + .with_visibility(false, false); + marker.metadata.set_operation_note( + EMPTY_RESPONSE_NOTE_SCOPE, + EMPTY_RESPONSE_NOTE, + serde_json::Value::Bool(true), + ); + usage_effects.push(E::from(marker)); + return applied(usage_effects); + }; if ends_with_successful_tool_response(conversation.messages()) && !accumulator diff --git a/crates/goose-cli/src/cli.rs b/crates/goose-cli/src/cli.rs index d75b7fd45..76eacdebc 100644 --- a/crates/goose-cli/src/cli.rs +++ b/crates/goose-cli/src/cli.rs @@ -1508,7 +1508,6 @@ async fn handle_mcp_probe(extension_command: String, script_path: Option std::sync::Arc::new(SessionManager::instance()), goose::config::permission::PermissionManager::instance(), None, - config.get_goose_mode().unwrap_or_default(), true, GoosePlatform::GooseCli, ); @@ -1557,7 +1556,7 @@ async fn handle_mcp_probe(extension_command: String, script_path: Option std::env::current_dir()?, "MCP Probe".to_string(), goose::session::session_manager::SessionType::Hidden, - agent.config.goose_mode, + config.get_goose_mode().unwrap_or_default(), ) .await?; let session_id = session.id.as_str(); diff --git a/crates/goose-cli/src/commands/configure.rs b/crates/goose-cli/src/commands/configure.rs index f9fef71d5..9ad24e8bf 100644 --- a/crates/goose-cli/src/commands/configure.rs +++ b/crates/goose-cli/src/commands/configure.rs @@ -1794,7 +1794,7 @@ pub async fn configure_tool_permissions_dialog() -> anyhow::Result<()> { std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")), "Tool Permission Configuration".to_string(), SessionType::Hidden, - agent.config.goose_mode, + config.get_goose_mode().unwrap_or_default(), ) .await?; diff --git a/crates/goose-cli/src/session/builder.rs b/crates/goose-cli/src/session/builder.rs index e383c4d4c..4080d7b4b 100644 --- a/crates/goose-cli/src/session/builder.rs +++ b/crates/goose-cli/src/session/builder.rs @@ -689,8 +689,12 @@ pub async fn build_session(session_config: SessionBuilderConfig) -> CliSession { process::exit(1); } - let session_id = - resolve_session_id(&session_config, &session_manager, agent.config.goose_mode).await; + let session_id = resolve_session_id( + &session_config, + &session_manager, + config.get_goose_mode().unwrap_or_default(), + ) + .await; if session_config.container.is_some() { session_manager @@ -824,7 +828,7 @@ pub async fn build_session(session_config: SessionBuilderConfig) -> CliSession { }); agent - .update_goose_mode(agent.config.goose_mode, &session_id) + .update_goose_mode(config.get_goose_mode().unwrap_or_default(), &session_id) .await .unwrap_or_else(|e| { output::render_error(&format!("Failed to set session mode: {}", e)); @@ -883,7 +887,6 @@ pub async fn build_session(session_config: SessionBuilderConfig) -> CliSession { session_config.scheduled_job_id.clone(), session_config.max_turns, edit_mode, - recipe.and_then(|r| r.retry.clone()), session_config.output_format.clone(), session_config.stats, session_config.interactive, diff --git a/crates/goose-cli/src/session/mod.rs b/crates/goose-cli/src/session/mod.rs index fbf30f0be..ef4f95440 100644 --- a/crates/goose-cli/src/session/mod.rs +++ b/crates/goose-cli/src/session/mod.rs @@ -33,7 +33,6 @@ use goose::utils::safe_truncate; use anyhow::Result; use completion::GooseCompleter; use goose::agents::extension::{Envs, ExtensionConfig, PLATFORM_EXTENSIONS}; -use goose::agents::types::RetryConfig; use goose::agents::{ context_management_unsupported_message, Agent, SessionConfig, COMPACT_TRIGGERS, }; @@ -241,7 +240,6 @@ pub struct CliSession { scheduled_job_id: Option, max_turns: Option, edit_mode: Option, - retry_config: Option, output_format: String, stats: bool, /// Background extension loader; drained exclusively by @@ -292,7 +290,6 @@ impl CliSession { scheduled_job_id: Option, max_turns: Option, edit_mode: Option, - retry_config: Option, output_format: String, stats: bool, refresh_completions: bool, @@ -330,7 +327,6 @@ impl CliSession { scheduled_job_id, max_turns, edit_mode, - retry_config, output_format, stats, extension_loading, @@ -559,10 +555,7 @@ impl CliSession { /// Start an interactive session, optionally with an initial message pub async fn interactive(&mut self, prompt: Option) -> Result<()> { - let banners = self - .agent - .emit_hook_with_banners(goose::hooks::HookEvent::SessionStart, &self.session_id) - .await; + let banners = self.agent.emit_session_start(&self.session_id).await?; if !banners.is_empty() { output::display_banner(&banners); } @@ -1125,23 +1118,21 @@ impl CliSession { } }; - let extension_configs = self.agent.get_extension_configs().await; + let extension_configs = self.agent.get_extension_configs(&self.session_id).await; self.agent .emit_hook(goose::hooks::HookEvent::SessionEnd, &self.session_id) .await; self.agent.discard_pending_steers(&self.session_id).await; + self.agent.extension_manager.release(&self.session_id).await; self.agent.config.providers.release(&self.session_id); self.session_id = new_session_id; self.messages.clear(); - if let Err(e) = self - .agent - .update_goose_mode(self.agent.goose_mode().await, &self.session_id) - .await - { + let mode = self.agent.goose_mode(&self.session_id).await?; + if let Err(e) = self.agent.update_goose_mode(mode, &self.session_id).await { output::render_error(&format!("Failed to apply the current mode: {}", e)); } @@ -1149,14 +1140,6 @@ impl CliSession { output::goose_mode_message("Restarting extensions for the new session..."); } - // MCP clients pin themselves to the first session id they see a request for, so - // extensions must be torn down and re-added under the new session id. - for name in self.agent.list_extensions().await { - if let Err(e) = self.agent.remove_extension(&name, &self.session_id).await { - output::render_extension_error(&name, &e.to_string()); - } - } - let mut unavailable = Vec::new(); for config in extension_configs { let name = config.name(); @@ -1185,8 +1168,7 @@ impl CliSession { let session_manager = &self.agent.config.session_manager; let old_session = session_manager.get_session(&self.session_id, false).await?; let new_session_id = - create_successor_session(session_manager, &old_session, self.agent.goose_mode().await) - .await?; + create_successor_session(session_manager, &old_session, old_session.goose_mode).await?; self.agent.persist_extension_state(&new_session_id).await?; Ok(new_session_id) } @@ -1311,7 +1293,6 @@ impl CliSession { id: self.session_id.clone(), schedule_id: self.scheduled_job_id.clone(), max_turns: self.max_turns, - retry_config: self.retry_config.clone(), }; let user_message = self .messages @@ -1330,7 +1311,6 @@ impl CliSession { .reply( user_message.clone(), session_config.clone(), - goose::agents::state_machine::enabled(), Some(cancel_token.clone()), ) .await?; @@ -1455,7 +1435,7 @@ impl CliSession { self.messages.push(response_message.clone()); // Elicitation responses return an empty stream - the response // unblocks the waiting tool call via ActionRequiredManager - let _ = self.agent.reply(response_message, session_config.clone(), goose::agents::state_machine::enabled(), Some(cancel_token.clone())).await?; + let _ = self.agent.reply(response_message, session_config.clone(), Some(cancel_token.clone())).await?; if should_cancel { cancel_token_clone.cancel(); drop(stream); @@ -3212,7 +3192,6 @@ mod tests { Arc::new(session_manager), Arc::new(goose::config::PermissionManager::new(data_dir.clone())), None, - GooseMode::default(), // Disable background session naming so the test agent starts no // provider-dependent tasks. true, @@ -3234,7 +3213,6 @@ mod tests { None, None, None, - None, "text".to_string(), false, refresh_completions, diff --git a/crates/goose-provider-types/src/conversation/message.rs b/crates/goose-provider-types/src/conversation/message.rs index d3bf3bb30..76719c2f2 100644 --- a/crates/goose-provider-types/src/conversation/message.rs +++ b/crates/goose-provider-types/src/conversation/message.rs @@ -1268,6 +1268,19 @@ impl Message { pub fn from_provider_error(err: &crate::errors::ProviderError) -> Self { use crate::errors::ProviderError; + if let ProviderError::CreditsExhausted { top_up_url, .. } = err { + let message = if top_up_url.is_some() { + "Please add credits to your account, then resend your message to continue." + } else { + "Please check your account with your provider to add more credits, then resend your message to continue." + }; + return Message::assistant().with_system_notification_with_data( + SystemNotificationType::CreditsExhausted, + message, + serde_json::json!({ "top_up_url": top_up_url }), + ); + } + let text = match err { ProviderError::NetworkError(_) => { format!("{err}\n\nPlease resend your message to try again.") @@ -1275,6 +1288,17 @@ impl Message { ProviderError::ContextLengthExceeded(_) => { format!("{err}\n\nThe conversation is too long for the model's context window.") } + ProviderError::Refusal { details, category } => { + let category = category + .as_deref() + .map(|category| format!("\n\nCategory: {category}")) + .unwrap_or_default(); + format!( + "The provider refused this request.\n\n{details}{category}\n\n\ + Please start a new session to continue — resending this conversation \ + is likely to be refused again." + ) + } _ => format!( "Ran into this error: {err}.\n\n\ Please retry if you think this is a transient or recoverable error." @@ -1284,9 +1308,15 @@ impl Message { } pub fn error_kind(&self) -> Option { - self.content - .iter() - .find_map(|content| content.as_error().map(|error| error.kind)) + self.content.iter().find_map(|content| match content { + MessageContentBlock::Error(error) => Some(error.kind), + MessageContentBlock::SystemNotification(notification) + if notification.notification_type == SystemNotificationType::CreditsExhausted => + { + Some(MessageErrorKind::CreditsExhausted) + } + _ => None, + }) } pub fn with_visibility(mut self, user_visible: bool, agent_visible: bool) -> Self { @@ -1417,7 +1447,7 @@ mod document_tests { mod tests { use crate::conversation::message::{ ActionRequiredData, Message, MessageContentBlock, MessageErrorKind, MessageMetadata, - ProviderMetadata, ToolResponse, + ProviderMetadata, SystemNotificationType, ToolResponse, }; use crate::errors::ProviderError; use base64::Engine; @@ -1440,6 +1470,28 @@ mod tests { assert!(!message.is_agent_visible()); } + #[test] + fn provider_credits_error_preserves_top_up_url_and_is_terminal() { + let message = Message::from_provider_error(&ProviderError::CreditsExhausted { + details: "credits exhausted".to_string(), + top_up_url: Some("https://example.com/top-up".to_string()), + }); + + assert_eq!( + message.error_kind(), + Some(MessageErrorKind::CreditsExhausted) + ); + let notification = message.content[0].as_system_notification().unwrap(); + assert_eq!( + notification.notification_type, + SystemNotificationType::CreditsExhausted + ); + assert_eq!( + notification.data.as_ref().unwrap()["top_up_url"], + "https://example.com/top-up" + ); + } + #[test] fn test_sanitize_with_text() { let malicious = "Hello\u{E0041}\u{E0042}\u{E0043}world"; // Invisible "ABC" diff --git a/crates/goose/examples/agent.rs b/crates/goose/examples/agent.rs index fbb43007b..48a8e2870 100644 --- a/crates/goose/examples/agent.rs +++ b/crates/goose/examples/agent.rs @@ -43,7 +43,7 @@ async fn main() -> anyhow::Result<()> { agent.add_extension(config, &session.id).await?; println!("Extensions:"); - for extension in agent.list_extensions().await { + for extension in agent.list_extensions(&session.id).await { println!(" {}", extension); } @@ -51,20 +51,12 @@ async fn main() -> anyhow::Result<()> { id: session.id, schedule_id: None, max_turns: None, - retry_config: None, }; let user_message = Message::user() .with_text("can you summarize the readme.md in this dir using just a haiku?"); - let mut stream = agent - .reply( - user_message, - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; + let mut stream = agent.reply(user_message, session_config, None).await?; while let Some(Ok(AgentEvent::Message(message))) = stream.next().await { println!("{}", serde_json::to_string_pretty(&message)?); diff --git a/crates/goose/src/acp/server.rs b/crates/goose/src/acp/server.rs index 645cc86df..df0e5c143 100644 --- a/crates/goose/src/acp/server.rs +++ b/crates/goose/src/acp/server.rs @@ -411,13 +411,6 @@ fn extract_timeout_from_meta(meta: &Option) -> Option { .and_then(|v| v.as_u64()) } -fn use_state_machine_from_meta(meta: Option<&Meta>) -> bool { - meta.and_then(|meta| meta.get("goose")) - .and_then(|goose| goose.get("unrolledAgentLoop")) - .and_then(|value| value.as_bool()) - .unwrap_or_else(crate::agents::state_machine::enabled) -} - #[derive(Debug, Default, Deserialize)] struct ClientCapabilitiesMeta { #[serde(default)] @@ -958,7 +951,6 @@ impl GooseAcpAgent { Arc::clone(&session_manager), Arc::clone(&permission_manager), options.scheduler, - Config::global().get_goose_mode().unwrap_or_default(), options.disable_session_naming, options.goose_platform.clone(), ); @@ -1085,7 +1077,7 @@ impl GooseAcpAgent { if !agent .extension_manager - .is_extension_enabled("developer") + .is_extension_enabled(&session.id, "developer") .await { return; @@ -1114,7 +1106,7 @@ impl GooseAcpAgent { let developer_config = agent .extension_manager - .get_extension_configs() + .get_extension_configs(&session.id) .await .into_iter() .find(|extension| extension.name() == "developer") @@ -1122,7 +1114,7 @@ impl GooseAcpAgent { agent .extension_manager - .add_client(developer_config, client, info) + .add_client(&session.id, developer_config, client, info) .await; } @@ -2302,21 +2294,14 @@ impl GooseAcpAgent { } let user_message = Self::convert_acp_prompt_to_message(&args.prompt); - let use_state_machine = use_state_machine_from_meta(args.meta.as_ref()); let session_config = SessionConfig { id: session_id.clone(), schedule_id: None, max_turns: None, - retry_config: None, }; let stream = match agent - .reply( - user_message, - session_config, - use_state_machine, - Some(cancel_token.clone()), - ) + .reply(user_message, session_config, Some(cancel_token.clone())) .await { Ok(stream) => stream, @@ -2467,7 +2452,10 @@ impl GooseAcpAgent { .await .internal_err_ctx("Failed to resolve model config")?; let current_model = current_model_config.model_name.clone(); - let goose_mode = agent.goose_mode().await; + let goose_mode = agent + .goose_mode(&session_id.0) + .await + .internal_err_ctx("Failed to read goose mode")?; let inventory = self .provider_inventory .entry_for_provider(&provider_name) @@ -3799,7 +3787,6 @@ print(\"hello, world\") server.session_manager.clone(), server.permission_manager.clone(), None, - GooseMode::Auto, true, GoosePlatform::GooseCli, ))); diff --git a/crates/goose/src/acp/server/live_voice.rs b/crates/goose/src/acp/server/live_voice.rs index bb82c471e..ad467b024 100644 --- a/crates/goose/src/acp/server/live_voice.rs +++ b/crates/goose/src/acp/server/live_voice.rs @@ -31,12 +31,6 @@ impl GooseAcpAgent { &self, req: LiveVoiceAvailabilityRequest, ) -> Result { - if !use_state_machine_from_meta(req.meta.as_ref()) { - return Ok(LiveVoiceAvailabilityResponse { - status: LiveVoiceStatus::Unavailable, - message: "Live voice is unavailable while Use Legacy Agent Loop is enabled".into(), - }); - } let mode = match req.session_id.as_deref() { Some(session_id) => self.load_live_voice_session(session_id).await?.goose_mode, None => crate::config::Config::global() @@ -65,9 +59,6 @@ impl GooseAcpAgent { cx: &ConnectionTo, req: LiveVoiceStartRequest, ) -> Result { - if !use_state_machine_from_meta(req.meta.as_ref()) { - return Err(map_live_voice_error(LiveVoiceError::Unavailable)); - } let offer = WebRtcOffer::new(req.offer_sdp) .ok_or_else(agent_client_protocol::Error::invalid_params)?; let session_id = req.session_id.clone(); @@ -258,7 +249,6 @@ impl GooseAcpAgent { id: session_id.clone(), schedule_id: None, max_turns: None, - retry_config: None, }; let input_message = Message::user().with_text(format!("{LIVE_DELEGATION_INSTRUCTION}\n\n{input}")); diff --git a/crates/goose/src/acp/server/load_session.rs b/crates/goose/src/acp/server/load_session.rs index 890896ebb..80487b2ff 100644 --- a/crates/goose/src/acp/server/load_session.rs +++ b/crates/goose/src/acp/server/load_session.rs @@ -275,7 +275,6 @@ impl GooseAcpAgent { id: session_id.to_string(), schedule_id: None, max_turns: None, - retry_config: None, }; let stream = match agent .resume_state_machine_turn(session_config, cancel_token.clone()) @@ -457,12 +456,11 @@ impl GooseAcpAgent { .as_ref() .map(pending_tool_confirmations) .unwrap_or_default(); - let should_resume_state_machine = crate::agents::state_machine::enabled() - && (!pending_confirmations.is_empty() - || session - .conversation - .as_ref() - .is_some_and(has_unapplied_tool_confirmation_response)); + let should_resume_state_machine = !pending_confirmations.is_empty() + || session + .conversation + .as_ref() + .is_some_and(has_unapplied_tool_confirmation_response); if should_resume_state_machine { self.start_resumed_state_machine_turn( cx, diff --git a/crates/goose/src/acp/server/tools.rs b/crates/goose/src/acp/server/tools.rs index 67f74eda5..df04d8028 100644 --- a/crates/goose/src/acp/server/tools.rs +++ b/crates/goose/src/acp/server/tools.rs @@ -12,7 +12,10 @@ impl GooseAcpAgent { ) -> Result { let session_id = &req.session_id; let agent = self.get_session_agent(&req.session_id).await?; - let goose_mode = agent.goose_mode().await; + let goose_mode = agent + .goose_mode(session_id) + .await + .internal_err_ctx("Failed to read goose mode")?; let permission_manager = self.permission_manager(); let mut tools: Vec = agent @@ -95,11 +98,6 @@ impl GooseAcpAgent { params }; - if agent.goose_mode().await != GooseMode::Auto { - return Err(agent_client_protocol::Error::invalid_params() - .data("app tool calls require auto mode")); - } - let session = self .session_manager .get_session(session_id, false) @@ -108,6 +106,10 @@ impl GooseAcpAgent { agent_client_protocol::Error::resource_not_found(Some(session_id.to_string())) .data(format!("Session not found: {}", session_id)) })?; + if session.goose_mode != GooseMode::Auto { + return Err(agent_client_protocol::Error::invalid_params() + .data("app tool calls require auto mode")); + } let container = session.container; let tool_result = agent diff --git a/crates/goose/src/agents/agent.rs b/crates/goose/src/agents/agent.rs index 025f7391b..f4c416db8 100644 --- a/crates/goose/src/agents/agent.rs +++ b/crates/goose/src/agents/agent.rs @@ -1,47 +1,31 @@ use std::collections::HashMap; use std::fmt; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use anyhow::{anyhow, Context, Result}; use futures::stream::BoxStream; -use futures::{stream, FutureExt, StreamExt, TryStreamExt}; -use goose_agent::inference::ends_with_successful_tool_response; +use futures::{StreamExt, TryStreamExt}; use tracing_futures::Instrument; -use super::final_output_tool::FinalOutputTool; use super::gen_ai_telemetry; use super::mcp_client::GooseMcpHostInfo; use super::tool_confirmation_coordinator::{ ActiveTurnGuard, ConfirmationAnswer, ToolConfirmationCoordinator, }; -use super::tool_confirmation_router::ToolConfirmationRouter; -use super::tool_execution::{ - tool_stream, ApprovalToolContext, ToolCallResult, ToolStream, ToolStreamItem, - CHAT_MODE_TOOL_SKIPPED_RESPONSE, DECLINED_RESPONSE, -}; use crate::action_required_manager::ElicitationOutcome; use crate::agents::extension::{ExtensionConfig, ExtensionResult}; -use crate::agents::extension_manager::{ - CallRequest, ExtensionLease, ExtensionManager, ExtensionManagerCapabilities, -}; -use crate::agents::final_output_tool::{ - structured_output_unsupported_message, FINAL_OUTPUT_CONTINUATION_MESSAGE, - FINAL_OUTPUT_TOOL_NAME, -}; -use crate::agents::prompt_manager::PromptManager; +use crate::agents::extension_manager::{ExtensionManager, ExtensionManagerCapabilities}; use crate::agents::provider_manager::ProviderManager; -use crate::agents::retry::{RetryManager, RetryResult}; use crate::agents::state_machine::ops_recipe; use crate::agents::state_machine::{ has_unapplied_tool_confirmation_response, pending_tool_confirmations, persist_tool_confirmation_decision, run_goose, subagent_cancelled_message, BangShellOperation, - CompactionOperation, DoctorOperation, Emitter, EntryHookOperation, ExitOnErrorOperation, - ForegroundSubagentOperation, GooseEffect, GooseInferenceProvider, + CompactionOperation, DoctorOperation, Emitter, EmptyResponseOperation, EntryHookOperation, + ExitOnErrorOperation, ForegroundSubagentOperation, GooseEffect, GooseInferenceProvider, GooseInferenceRequestPreparer, InferenceRunner, MaxTurnsOperation, Operation, ProjectOperation, RecipeOperation, RetryOperation, SkillOperation, SlashCommandOperation, StateMachine, StatusOperation, SteerOperation, SteerQueue, Step, StopHookOperation, ToolApprovalOperation, - ToolExecutionOperation, ToolPairCompactionOperation, UnknownToolOperation, MAX_TURNS_MESSAGE, + ToolExecutionOperation, ToolPairCompactionOperation, UnknownToolOperation, }; use crate::agents::subagent_handler::ForegroundSubagentRunner; use crate::agents::types::{ @@ -51,16 +35,9 @@ use crate::agents::AgentEvent; use crate::config::extensions::name_to_key; use crate::config::permission::PermissionManager; use crate::config::{Config, GooseMode}; -use crate::context_mgmt::{ - check_if_compaction_needed, compact_messages, DEFAULT_COMPACTION_THRESHOLD, -}; -use crate::conversation::message::{ - ActionRequiredData, InferenceMetadata, Message, MessageContent, MessageUsage, ProviderMetadata, - SystemNotificationType, -}; -use crate::conversation::{debug_conversation_fix, fix_conversation, Conversation}; +use crate::context_mgmt::DEFAULT_COMPACTION_THRESHOLD; +use crate::conversation::message::{ActionRequiredData, Message, MessageContent}; use crate::permission::permission_inspector::PermissionInspector; -use crate::permission::permission_judge::PermissionCheckResult; use crate::permission::{Permission, PermissionConfirmation}; use crate::providers::base::{PermissionRouting, Provider}; use crate::scheduler_trait::SchedulerTrait; @@ -68,28 +45,19 @@ use crate::security::adversary_inspector::AdversaryInspector; use crate::security::egress_inspector::EgressInspector; use crate::security::security_inspector::SecurityInspector; use crate::session::extension_data::{EnabledExtensionsState, ExtensionState}; -use crate::session::{GoalState, Session, SessionManager, SessionNameUpdate}; +use crate::session::{Session, SessionManager, SessionNameUpdate}; use crate::tool_inspection::ToolInspectionManager; use crate::tool_monitor::RepetitionInspector; -use crate::utils::is_token_cancelled; -use goose_providers::conversation::token_usage::{ProviderUsage, Usage}; use goose_providers::errors::ProviderError; use goose_providers::thinking::{ThinkingEffort, ThinkingEffortSupport}; -use rmcp::model::{ - CallToolRequestParams, CallToolResult, ContentBlock, ElicitationAction, ErrorCode, ErrorData, - GetPromptResult, Prompt, Tool, -}; +use rmcp::model::{ElicitationAction, GetPromptResult, Prompt, Tool}; use serde_json::Value; use tokio::sync::{mpsc, Mutex}; use tokio_util::sync::CancellationToken; -use tracing::{debug, error, info, instrument, warn}; +use tracing::{error, instrument, warn}; const DEFAULT_MAX_TURNS: u32 = 1000; const DEFAULT_STOP_HOOK_BLOCK_CAP: u32 = 8; -const COMPACTION_PROGRESS_TEXT: &str = "goose is compacting the conversation..."; -const MAX_EMPTY_TURN_RETRIES: u32 = 3; -const EMPTY_TURN_MESSAGE: &str = - "The model returned an empty response. Please resend your message to continue."; fn provider_creation_error(error: anyhow::Error, context: impl fmt::Display) -> anyhow::Error { let message = format!("{context}: {error}"); @@ -117,78 +85,6 @@ fn normalize_legacy_provider_thinking_effort( model_config.with_default_thinking_effort(Config::global().get_goose_thinking_effort()) } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ToolCategory { - Shell, - Read, - Write, - Other, -} - -fn categorize_tool(tool_name: &str) -> ToolCategory { - let local = tool_name.rsplit("__").next().unwrap_or(tool_name); - match local { - "shell" | "bash" | "exec" | "run" => ToolCategory::Shell, - "read" | "view" | "cat" | "read_file" => ToolCategory::Read, - "write" | "edit" | "patch" | "write_file" | "edit_file" => ToolCategory::Write, - _ => ToolCategory::Other, - } -} - -fn extract_string_arg(input: &Value, keys: &[&str]) -> Option { - let obj = input.as_object()?; - for k in keys { - if let Some(s) = obj.get(*k).and_then(|v| v.as_str()) { - if !s.is_empty() { - return Some(s.to_string()); - } - } - } - None -} - -pub(crate) fn stop_hook_denial_context_message(plugin: &str, reason: &str) -> Message { - let nudge = format!( - "Stop hook `{plugin}` blocked ending this turn: - -{reason} - -Address this policy hook denial before trying to stop again." - ); - Message::user() - .with_text(nudge) - .with_visibility(false, true) -} - -pub(crate) fn stop_hook_denial_notification(plugin: &str) -> Message { - Message::assistant().with_system_notification( - SystemNotificationType::InlineMessage, - format!("Stop hook `{plugin}` blocked ending this turn."), - ) -} - -pub(crate) fn stop_hook_block_cap_warning(plugin: &str, cap: u32) -> Message { - Message::assistant().with_system_notification( - SystemNotificationType::InlineMessage, - format!( - "Stop hook `{plugin}` blocked the turn from ending more than {cap} consecutive times — overriding and ending turn to avoid an infinite loop. Set GOOSE_STOP_HOOK_BLOCK_CAP to raise this limit." - ), - ) -} - -/// Context needed for the reply function -pub struct ReplyContext { - session: Session, - lease: Arc, - pub conversation: Conversation, - pub tools: Vec, - pub toolshim_tools: Vec, - pub system_prompt: String, - pub goose_mode: GooseMode, - pub tool_call_cut_off: usize, - pub model_config: goose_providers::model::ModelConfig, -} - #[derive(Debug, Clone, serde::Serialize)] pub struct ExtensionLoadResult { pub name: String, @@ -217,7 +113,6 @@ pub struct AgentConfig { pub session_manager: Arc, pub permission_manager: Arc, pub scheduler_service: Option>, - pub goose_mode: GooseMode, pub disable_session_naming: bool, pub goose_platform: GoosePlatform, pub mcp_host_info: Option, @@ -234,7 +129,6 @@ impl AgentConfig { session_manager: Arc, permission_manager: Arc, scheduler_service: Option>, - goose_mode: GooseMode, disable_session_naming: bool, goose_platform: GoosePlatform, ) -> Self { @@ -242,7 +136,6 @@ impl AgentConfig { session_manager, permission_manager, scheduler_service, - goose_mode, disable_session_naming, goose_platform, mcp_host_info: None, @@ -285,113 +178,35 @@ fn resolve_use_login_shell_path(explicit: Option, platform: &GoosePlatform /// The main goose Agent pub struct Agent { pub config: AgentConfig, - pub(super) current_goose_mode: Mutex, pub extension_manager: Arc, - pub(super) final_output_tool: Arc>>, - pub(super) prompt_manager: Mutex, - pub(super) tool_confirmation_router: ToolConfirmationRouter, tool_confirmation_coordinator: ToolConfirmationCoordinator, - pub(super) retry_manager: RetryManager, pub(super) tool_inspection_manager: ToolInspectionManager, pub(super) hook_manager: crate::hooks::HookManager, - session_start_emitted: AtomicBool, #[cfg(test)] pub(super) stop_hook_block_cap_override: Option, steer_queues: Mutex>, } -fn ensure_message_event_id(event: AgentEvent) -> AgentEvent { +fn user_event(event: AgentEvent) -> Option { match event { - AgentEvent::Message(message) => AgentEvent::Message(message.with_generated_id_if_missing()), - other => other, + AgentEvent::Message(message) => { + let had_content = !message.content.is_empty(); + let projected = message + .with_generated_id_if_missing() + .user_visible_content(); + (!had_content || !projected.content.is_empty()) + .then_some(AgentEvent::Message(projected)) + } + other => Some(other), } } -fn push_message_with_id(messages: &mut Conversation, message: Message) -> Message { - let message = message.with_generated_id_if_missing(); - messages.push(message.clone()); - message -} - -async fn persist_message_with_id( - session_manager: &SessionManager, - session_id: &str, - message: Message, -) -> Result { - let message = message.with_generated_id_if_missing(); - session_manager.add_message(session_id, &message).await?; - Ok(message) -} - -async fn persist_and_push_message_with_id( - session_manager: &SessionManager, - session_id: &str, - conversation: &mut Conversation, - message: Message, -) -> Result { - let message = persist_message_with_id(session_manager, session_id, message).await?; - conversation.push(message.clone()); - Ok(message) -} - -async fn persist_turn_context_if_changed( - session_manager: &SessionManager, - session_id: &str, - conversation: &mut Conversation, - turn_context: Option, -) -> Result<()> { - let Some(turn_context) = turn_context else { - return Ok(()); - }; - if conversation - .messages() - .iter() - .rev() - .find(|message| message.is_turn_context()) - .is_some_and(|current| current.as_concat_text() == turn_context.as_concat_text()) - { - return Ok(()); - } - persist_and_push_message_with_id(session_manager, session_id, conversation, turn_context) - .await?; - Ok(()) -} - -fn project_message_for_user_event(message: &Message) -> Message { - message.user_visible_content() -} - fn agent_visible_message_text(message: &Message) -> String { message.agent_visible_content().as_concat_text() } -fn attach_turn_usage( - messages: &mut Conversation, - usage: &ProviderUsage, - preferred_message_id: Option<&str>, -) -> Option<(Option, MessageUsage)> { - let message_index = preferred_message_id - .and_then(|preferred_message_id| { - messages.messages().iter().rposition(|message| { - message.role == rmcp::model::Role::Assistant - && message.id.as_deref() == Some(preferred_message_id) - }) - }) - .or_else(|| { - messages - .messages() - .iter() - .rposition(|message| message.role == rmcp::model::Role::Assistant) - })?; - let message = &mut messages.messages_mut()[message_index]; - let has_user_visible_content = !message.user_visible_content().content.is_empty(); - let message_usage = MessageUsage::from_provider_usage(usage, false); - message.metadata.usage = Some(Box::new(message_usage.clone())); - has_user_visible_content.then(|| (message.id.clone(), message_usage)) -} - impl Default for Agent { fn default() -> Self { Self::new() @@ -418,7 +233,6 @@ impl Agent { Arc::new(SessionManager::instance()), PermissionManager::instance(), None, - config.get_goose_mode().unwrap_or_default(), config.get_goose_disable_session_naming().unwrap_or(false), GoosePlatform::GooseCli, )) @@ -428,7 +242,6 @@ impl Agent { let providers = config.providers.clone(); let goose_platform = config.goose_platform.clone(); - let initial_mode = config.goose_mode; let explicit_mcp_host_info = config.mcp_host_info.clone(); let mcpui = explicit_mcp_host_info .as_ref() @@ -456,7 +269,6 @@ impl Agent { let is_subagent = config.is_subagent; Self { config, - current_goose_mode: Mutex::new(initial_mode), extension_manager: Arc::new(ExtensionManager::new( providers.clone(), session_manager, @@ -465,11 +277,7 @@ impl Agent { capabilities, use_login_shell_path, )), - final_output_tool: Arc::new(Mutex::new(None)), - prompt_manager: Mutex::new(PromptManager::new()), - tool_confirmation_router: ToolConfirmationRouter::new(), tool_confirmation_coordinator: ToolConfirmationCoordinator::new(), - retry_manager: RetryManager::new(), tool_inspection_manager: Self::create_tool_inspection_manager( permission_manager, providers, @@ -483,7 +291,6 @@ impl Agent { use_login_shell_path, ) }, - session_start_emitted: AtomicBool::new(false), #[cfg(test)] stop_hook_block_cap_override: None, steer_queues: Mutex::new(HashMap::new()), @@ -509,17 +316,6 @@ impl Agent { self.stop_hook_block_cap_override = Some(cap); } - pub(crate) fn stop_hook_block_cap(&self) -> u32 { - #[cfg(test)] - if let Some(cap) = self.stop_hook_block_cap_override { - return cap; - } - - Config::global() - .get_param::("GOOSE_STOP_HOOK_BLOCK_CAP") - .unwrap_or(DEFAULT_STOP_HOOK_BLOCK_CAP) - } - pub async fn emit_hook(&self, event: crate::hooks::HookEvent, session_id: &str) { if !self.hook_manager.has_hooks(event) { return; @@ -529,61 +325,25 @@ impl Agent { .await; } - pub async fn emit_hook_with_banners( - &self, - event: crate::hooks::HookEvent, - session_id: &str, - ) -> Vec { - if event == crate::hooks::HookEvent::SessionStart { - self.session_start_emitted.store(true, Ordering::Release); - } + /// Fires `SessionStart` for a client opening the session and returns the hooks' + /// banners, which the client shows before the first prompt. + pub async fn emit_session_start(&self, session_id: &str) -> Result> { + let event = crate::hooks::HookEvent::SessionStart; if !self.hook_manager.has_hooks(event) { - return Vec::new(); + return Ok(Vec::new()); } - self.hook_manager + let banners = self + .hook_manager .emit_collecting_banners(event, crate::hooks::HookContext::new(event, session_id)) - .await - } - - fn stop_hook_context( - session_id: &str, - last_assistant_message: &str, - working_dir: &str, - ) -> crate::hooks::HookContext { - crate::hooks::HookContext::new(crate::hooks::HookEvent::Stop, session_id) - .with_last_assistant_message(last_assistant_message.to_string()) - .with_working_dir(working_dir.to_string()) - } - - pub(crate) async fn emit_stop_hook( - &self, - session_id: &str, - last_assistant_message: &str, - working_dir: &str, - ) { - if !self.hook_manager.has_hooks(crate::hooks::HookEvent::Stop) { - return; - } - self.hook_manager - .emit( - crate::hooks::HookEvent::Stop, - Self::stop_hook_context(session_id, last_assistant_message, working_dir), - ) .await; - } - - pub(crate) async fn emit_stop_hook_blocking( - &self, - session_id: &str, - last_assistant_message: &str, - working_dir: &str, - ) -> crate::hooks::HookDecision { - self.hook_manager - .emit_blocking( - crate::hooks::HookEvent::Stop, - Self::stop_hook_context(session_id, last_assistant_message, working_dir), + self.config + .session_manager + .add_message( + session_id, + &crate::agents::state_machine::session_start_message(&banners), ) - .await + .await?; + Ok(banners) } pub async fn steer(&self, session_id: &str, message: Message) { @@ -598,27 +358,6 @@ impl Agent { self.steer_queues.lock().await.remove(session_id); } - pub(crate) async fn has_pending_steers(&self, session_id: &str) -> bool { - let queue = self.steer_queues.lock().await.get(session_id).cloned(); - match queue { - Some(queue) => !queue.lock().await.is_empty(), - None => false, - } - } - - pub(crate) async fn drain_pending_steers(&self, session_id: &str) -> Vec { - let queue = self.steer_queues.lock().await.get(session_id).cloned(); - match queue { - Some(queue) => queue - .lock() - .await - .drain(..) - .map(Message::with_steer) - .collect(), - None => Vec::new(), - } - } - async fn steer_queue(&self, session_id: &str) -> SteerQueue { self.steer_queues .lock() @@ -628,170 +367,6 @@ impl Agent { .clone() } - async fn emit_pre_tool_extended_hooks( - &self, - tool_name: &str, - tool_input: Option<&Value>, - session: &Session, - ) { - let working_dir = session.working_dir.to_string_lossy().to_string(); - match categorize_tool(tool_name) { - ToolCategory::Shell => { - if let Some(cmd) = tool_input.and_then(|v| extract_string_arg(v, &["command"])) { - self.emit_with_matcher( - crate::hooks::HookEvent::BeforeShellExecution, - &session.id, - &cmd, - tool_name, - tool_input.cloned(), - &working_dir, - ) - .await; - } - } - ToolCategory::Read => { - if let Some(path) = - tool_input.and_then(|v| extract_string_arg(v, &["path", "file", "file_path"])) - { - self.emit_with_matcher( - crate::hooks::HookEvent::BeforeReadFile, - &session.id, - &path, - tool_name, - tool_input.cloned(), - &working_dir, - ) - .await; - } - } - ToolCategory::Write | ToolCategory::Other => {} - } - } - - async fn emit_with_matcher( - &self, - event: crate::hooks::HookEvent, - session_id: &str, - matcher_context: &str, - tool_name: &str, - tool_input: Option, - working_dir: &str, - ) { - if !self.hook_manager.has_hooks(event) { - return; - } - let mut ctx = crate::hooks::HookContext::new(event, session_id) - .with_tool(tool_name.to_string(), tool_input) - .with_working_dir(working_dir.to_string()); - ctx.matcher_context = Some(matcher_context.to_string()); - self.hook_manager.emit(event, ctx).await; - } - - /// Observation-only record of what the `PreToolUse` chain decided. Carries - /// no veto: the decision has already been made by the time this runs. - async fn emit_pre_tool_use_result( - &self, - session: &Session, - tool_call_id: &str, - tool_name: &str, - tool_input: Option<&Value>, - outcome: &crate::hooks::HookChainOutcome, - ) { - if !self - .hook_manager - .has_hooks(crate::hooks::HookEvent::PreToolUseResult) - { - return; - } - let ctx = - crate::hooks::HookContext::new(crate::hooks::HookEvent::PreToolUseResult, &session.id) - .with_tool(tool_name.to_string(), tool_input.cloned()) - .with_tool_call_id(tool_call_id) - .with_working_dir(session.working_dir.to_string_lossy().to_string()) - .with_pre_tool_use_outcome(outcome); - self.hook_manager.emit_pre_tool_use_result(ctx).await; - } - - fn with_post_tool_hook( - &self, - result: ToolCallResult, - tool_call: &CallToolRequestParams, - session: &Session, - tool_call_id: &str, - ) -> ToolCallResult { - let hook_manager = self.hook_manager.clone(); - let session_id = session.id.clone(); - let working_dir = session.working_dir.to_string_lossy().to_string(); - let tool_name = tool_call.name.to_string(); - let tool_call_id = tool_call_id.to_string(); - let tool_input = tool_call - .arguments - .as_ref() - .map(|a| serde_json::Value::Object(a.clone())); - let category = categorize_tool(&tool_name); - let span = tracing::Span::current(); - let capture_message_content = gen_ai_telemetry::capture_message_content(); - - let fut = async move { - let processed_result = - super::large_response_handler::process_tool_response(result.result.await); - if capture_message_content { - let output = gen_ai_telemetry::tool_result_json(&processed_result); - span.record("output", output.as_str()); - } - gen_ai_telemetry::record_tool_result(&span, &processed_result); - let event = match &processed_result { - Ok(call_result) if call_result.is_error != Some(true) => { - crate::hooks::HookEvent::PostToolUse - } - _ => crate::hooks::HookEvent::PostToolUseFailure, - }; - - if hook_manager.has_hooks(event) { - let ctx = crate::hooks::HookContext::new(event, &session_id) - .with_tool(tool_name.clone(), tool_input.clone()) - .with_tool_call_id(tool_call_id.as_str()) - .with_working_dir(working_dir.clone()); - hook_manager.emit(event, ctx).await; - } - - if event == crate::hooks::HookEvent::PostToolUse { - let extended = match category { - ToolCategory::Shell => Some(( - crate::hooks::HookEvent::AfterShellExecution, - tool_input - .as_ref() - .and_then(|v| extract_string_arg(v, &["command"])), - )), - ToolCategory::Write => Some(( - crate::hooks::HookEvent::AfterFileEdit, - tool_input - .as_ref() - .and_then(|v| extract_string_arg(v, &["path", "file", "file_path"])), - )), - _ => None, - }; - if let Some((ext_event, Some(matcher))) = extended { - if hook_manager.has_hooks(ext_event) { - let mut ctx = crate::hooks::HookContext::new(ext_event, &session_id) - .with_tool(tool_name, tool_input) - .with_working_dir(working_dir); - ctx.matcher_context = Some(matcher); - hook_manager.emit(ext_event, ctx).await; - } - } - } - - processed_result - }; - - ToolCallResult { - notification_stream: result.notification_stream, - action_required_stream: result.action_required_stream, - result: Box::new(fut.boxed()), - } - } - /// Create a tool inspection manager with default inspectors fn create_tool_inspection_manager( permission_manager: Arc, @@ -823,173 +398,6 @@ impl Agent { tool_inspection_manager } - /// Reset the retry attempts counter to 0 - pub async fn reset_retry_attempts(&self) { - self.retry_manager.reset_attempts().await; - } - - /// Increment the retry attempts counter and return the new value - pub async fn increment_retry_attempts(&self) -> u32 { - self.retry_manager.increment_attempts().await - } - - /// Get the current retry attempts count - pub async fn get_retry_attempts(&self) -> u32 { - self.retry_manager.get_attempts().await - } - - async fn handle_retry_logic( - &self, - messages: &mut Conversation, - session_config: &SessionConfig, - initial_messages: &[Message], - ) -> Result { - let result = self - .retry_manager - .handle_retry_logic(messages, session_config, initial_messages) - .await?; - if matches!(result, RetryResult::Retried) { - if let Some(tool) = self.final_output_tool.lock().await.as_mut() { - tool.final_output = None; - } - } - Ok(result) - } - async fn load_project_instructions(&self, session: &Session) -> Option { - let project_id = session.project_id.as_deref()?; - let entry = crate::sources::read_project(project_id).ok()?; - let mut parts = Vec::new(); - parts.push(format!("# Project: {}", entry.name)); - if !entry.description.is_empty() { - parts.push(entry.description.clone()); - } - if !entry.content.is_empty() { - parts.push(entry.content.clone()); - } - Some(parts.join("\n\n")) - } - - async fn prepare_reply_context( - &self, - session: &Session, - unfixed_conversation: Conversation, - ) -> Result { - let unfixed_messages = unfixed_conversation.messages().clone(); - let (conversation, issues) = fix_conversation(unfixed_conversation.clone()); - if !issues.is_empty() { - debug!( - "Conversation issue fixed: {}", - debug_conversation_fix( - unfixed_messages.as_slice(), - conversation.messages(), - &issues - ) - ); - } - let (session, lease, tools, toolshim_tools, system_prompt, model_config) = - self.prepare_tools_and_prompt(session).await?; - - let goose_mode = *self.current_goose_mode.lock().await; - - let tool_call_cut_off = match Config::global().get_param::("GOOSE_TOOL_CALL_CUTOFF") - { - Ok(v) => v, - Err(_) => { - let context_limit = match self.config.providers.provider_for(&session).await { - Ok(provider) => crate::context_limit::get_context_limit( - provider.as_ref(), - &model_config.model_name, - ) - .await - .unwrap_or(goose_providers::model::DEFAULT_CONTEXT_LIMIT), - Err(_) => goose_providers::model::DEFAULT_CONTEXT_LIMIT, - }; - let compaction_threshold = Config::global() - .get_param::("GOOSE_AUTO_COMPACT_THRESHOLD") - .unwrap_or(crate::context_mgmt::DEFAULT_COMPACTION_THRESHOLD); - crate::context_mgmt::compute_tool_call_cutoff(context_limit, compaction_threshold) - } - }; - - Ok(ReplyContext { - session, - lease, - conversation, - tools, - toolshim_tools, - system_prompt, - goose_mode, - tool_call_cut_off, - model_config, - }) - } - - async fn handle_approved_and_denied_tools( - &self, - lease: &ExtensionLease, - permission_check_result: &PermissionCheckResult, - request_to_response_map: &mut HashMap, - cancel_token: Option, - session: &Session, - ) -> Result> { - let mut tool_futures: Vec<(String, ToolStream)> = Vec::new(); - - // Handle pre-approved and read-only tools - for request in &permission_check_result.approved { - if let Ok(tool_call) = request.tool_call.clone() { - let (req_id, tool_result) = self - .dispatch_tool_call_on( - lease, - tool_call, - request.id.clone(), - cancel_token.clone(), - session, - ) - .await; - - tool_futures.push(( - req_id, - match tool_result { - Ok(result) => tool_stream( - result - .notification_stream - .unwrap_or_else(|| Box::new(stream::empty())), - result - .action_required_stream - .unwrap_or_else(|| Box::new(stream::empty())), - result.result, - ), - Err(e) => tool_stream( - Box::new(stream::empty()), - Box::new(stream::empty()), - futures::future::ready(Err(e)), - ), - }, - )); - } - } - - Self::handle_denied_tools(permission_check_result, request_to_response_map); - Ok(tool_futures) - } - - fn handle_denied_tools( - permission_check_result: &PermissionCheckResult, - request_to_response_map: &mut HashMap, - ) { - for request in &permission_check_result.denied { - if let Some(response) = request_to_response_map.get_mut(&request.id) { - response.add_tool_response_with_metadata( - request.id.clone(), - Ok(CallToolResult::error(vec![ - rmcp::model::ContentBlock::text(DECLINED_RESPONSE), - ])), - request.metadata.as_ref(), - ); - } - } - } - pub async fn provider(&self, session_id: &str) -> Result> { let session = self .config @@ -1025,166 +433,13 @@ impl Agent { } } - pub async fn dispatch_tool_call( - &self, - tool_call: CallToolRequestParams, - request_id: String, - cancellation_token: Option, - session: &Session, - ) -> (String, Result) { - let lease = self.resolve_lease(&session.id, &session.working_dir).await; - self.dispatch_tool_call_on(&lease, tool_call, request_id, cancellation_token, session) - .await - } - - #[instrument( - name = "dispatch_tool_call", - skip(self, lease, tool_call, request_id, cancellation_token, session), - fields( - input, - output, - session.id = %session.id, - gen_ai.conversation.id = %session.id, - gen_ai.operation.name = "execute_tool", - gen_ai.tool.name = %tool_call.name, - gen_ai.tool.call.id = %request_id, - gen_ai.tool.call.arguments = tracing::field::Empty, - gen_ai.tool.call.result = tracing::field::Empty, - error.type = tracing::field::Empty, - ) - )] - pub(super) async fn dispatch_tool_call_on( - &self, - lease: &ExtensionLease, - tool_call: CallToolRequestParams, - request_id: String, - cancellation_token: Option, - session: &Session, - ) -> (String, Result) { - if gen_ai_telemetry::capture_message_content() { - let input_summary = serde_json::json!({ - "tool": tool_call.name, - "arguments": tool_call.arguments, - }); - tracing::Span::current().record("input", tracing::field::display(&input_summary)); - } - gen_ai_telemetry::record_tool_arguments(&tracing::Span::current(), &tool_call); - - self.prompt_manager - .lock() - .await - .record_tool_arguments(&tool_call.arguments, &session.working_dir); - - let tool_input_for_hooks = tool_call - .arguments - .as_ref() - .map(|a| serde_json::Value::Object(a.clone())); - - let pre_tool_outcome = if self - .hook_manager - .has_hooks(crate::hooks::HookEvent::PreToolUse) - { - let ctx = - crate::hooks::HookContext::new(crate::hooks::HookEvent::PreToolUse, &session.id) - .with_tool(tool_call.name.to_string(), tool_input_for_hooks.clone()) - .with_tool_call_id(request_id.as_str()) - .with_working_dir(session.working_dir.to_string_lossy().to_string()); - self.hook_manager - .emit_blocking_with_outcome(crate::hooks::HookEvent::PreToolUse, ctx) - .await - } else { - crate::hooks::HookChainOutcome::allow(false) - }; - - // Emitted before the denial returns, so an observer sees the denial - // before the model receives the refusal. Best effort, like every other - // hook emission: a subscriber that fails or is absent changes nothing. - self.emit_pre_tool_use_result( - session, - request_id.as_str(), - &tool_call.name, - tool_input_for_hooks.as_ref(), - &pre_tool_outcome, - ) - .await; - - if let Some(denial) = pre_tool_outcome.denial() { - tracing::Span::current().record("error.type", denial.error_type); - return ( - request_id, - Err(ErrorData::new( - ErrorCode::INTERNAL_ERROR, - denial.message, - None, - )), - ); - } - - self.emit_pre_tool_extended_hooks(&tool_call.name, tool_input_for_hooks.as_ref(), session) - .await; - - if tool_call.name == FINAL_OUTPUT_TOOL_NAME { - return if let Some(final_output_tool) = self.final_output_tool.lock().await.as_mut() { - let result = final_output_tool.execute_tool_call(tool_call.clone()).await; - let result = self.with_post_tool_hook(result, &tool_call, session, &request_id); - (request_id, Ok(result)) - } else { - // This method has always reported a missing final-output tool as - // the outer error. Keep that contract and emit the failure - // observation directly, the same event the wrapper would emit. - let error = ErrorData::new( - ErrorCode::INTERNAL_ERROR, - "Final output tool not defined".to_string(), - None, - ); - let failure = crate::hooks::HookEvent::PostToolUseFailure; - if self.hook_manager.has_hooks(failure) { - let ctx = crate::hooks::HookContext::new(failure, &session.id) - .with_tool(tool_call.name.to_string(), tool_input_for_hooks.clone()) - .with_tool_call_id(request_id.as_str()) - .with_working_dir(session.working_dir.to_string_lossy().to_string()); - self.hook_manager.emit(failure, ctx).await; - } - (request_id, Err(error)) - }; - } - - debug!("WAITING_TOOL_START: {}", tool_call.name); - let container = session.container.clone(); - let result = lease - .call( - tool_call.clone(), - CallRequest::new(request_id.clone()).with_container(container.clone()), - cancellation_token.unwrap_or_default(), - ) - .await; - let result = result.unwrap_or_else(|error_data| { - #[cfg(feature = "telemetry")] - crate::posthog::emit_error( - "tool_execution_failed", - &format!("{}: {}", tool_call.name, error_data), - ); - ToolCallResult::from(Err(error_data)) - }); - let result = self - .extension_manager - .applying_mutation(result, container, &session.id); - - debug!("WAITING_TOOL_END: {}", tool_call.name); - - let result = self.with_post_tool_hook(result, &tool_call, session, &request_id); - (request_id, Ok(result)) - } - - pub async fn save_extension_state(&self, session: &SessionConfig) -> Result<()> { - self.persist_extension_state(&session.id).await - } - /// Save current extension state to session by session_id pub async fn persist_extension_state(&self, session_id: &str) -> Result<()> { self.persist_extension_configs( session_id, - self.extension_manager.get_extension_configs().await, + self.extension_manager + .get_extension_configs(session_id) + .await, ) .await } @@ -1264,7 +519,7 @@ impl Agent { if agent_ref .extension_manager - .is_extension_enabled(&name) + .is_extension_enabled(&session_id_clone, &name) .await { tracing::debug!("Extension {} already loaded, skipping", name); @@ -1368,7 +623,7 @@ impl Agent { async move { let name = config.name().to_string(); match ext_manager - .add_extension(config, working_dir, container.as_ref(), Some(&sid)) + .add_extension(config, working_dir, container.as_ref(), &sid) .await { Ok(_) => ExtensionLoadResult { @@ -1418,7 +673,7 @@ impl Agent { extension, Some(session.working_dir), session.container.as_ref(), - Some(session_id), + session_id, ) .await?; @@ -1441,18 +696,6 @@ impl Agent { .await } - pub(crate) async fn resolve_lease( - &self, - session_id: &str, - working_dir: &std::path::Path, - ) -> Arc { - Arc::new( - self.extension_manager - .current_lease(session_id, Some(working_dir)) - .await, - ) - } - pub async fn list_tools(&self, session_id: &str, extension_name: Option) -> Vec { let include_final_output = extension_name.is_none(); let lease = self.extension_manager.current_lease(session_id, None).await; @@ -1496,7 +739,9 @@ impl Agent { return Ok(false); } - self.extension_manager.remove_extension_by_key(key).await?; + self.extension_manager + .remove_extension_by_key(session_id, key) + .await?; // Persist extension state after successful removal self.persist_extension_state(session_id) @@ -1509,15 +754,14 @@ impl Agent { Ok(true) } - pub async fn list_extensions(&self) -> Vec { - self.extension_manager - .list_extensions() - .await - .expect("Failed to list extensions") + pub async fn list_extensions(&self, session_id: &str) -> Vec { + self.extension_manager.list_extensions(session_id).await } - pub async fn get_extension_configs(&self) -> Vec { - self.extension_manager.get_extension_configs().await + pub async fn get_extension_configs(&self, session_id: &str) -> Vec { + self.extension_manager + .get_extension_configs(session_id) + .await } pub async fn submit_tool_confirmation( @@ -1569,17 +813,6 @@ impl Agent { return Ok(()); } - if self - .tool_confirmation_router - .deliver(session_id, request_id, confirmation) - .await - { - if state.contains_request(request_id) { - state.record_answer(request_id, ConfirmationAnswer::LiveHandled)?; - } - return Ok(()); - } - if state.contains_request(request_id) { persist_tool_confirmation_decision( self.config.session_manager.as_ref(), @@ -1618,33 +851,6 @@ impl Agent { false } - pub async fn handle_confirmation( - &self, - session_id: &str, - request_id: String, - confirmation: PermissionConfirmation, - ) { - if self - .try_route_tool_confirmation_to_provider(session_id, &request_id, &confirmation) - .await - { - return; - } - if !self - .tool_confirmation_router - .deliver(session_id, &request_id, confirmation) - .await - { - error!("Failed to deliver confirmation"); - } - } - - pub async fn supports_action_required_permissions(&self, session_id: &str) -> bool { - self.provider(session_id).await.is_ok_and(|provider| { - provider.permission_routing() == PermissionRouting::ActionRequired - }) - } - pub(super) async fn create_state_machine( &self, provider: Arc, @@ -1710,10 +916,7 @@ impl Agent { tool_call_cutoff, tool_pair_compaction_enabled, )), - Arc::new(ToolApprovalOperation::new( - &self.current_goose_mode, - &self.tool_inspection_manager, - )), + Arc::new(ToolApprovalOperation::new(&self.tool_inspection_manager)), Arc::new(DoctorOperation::new(self.config.session_manager.clone())), Arc::new(ProjectOperation), Arc::new(SkillOperation::new( @@ -1735,7 +938,6 @@ impl Agent { self.hook_manager.clone(), )), Arc::new(ToolExecutionOperation::new( - &self.current_goose_mode, self.extension_manager.clone(), self.hook_manager.clone(), Arc::clone(&extension_lease), @@ -1745,6 +947,7 @@ impl Agent { std::time::Duration::from_secs(retry_timeout), std::time::Duration::from_secs(on_failure_timeout), )), + Arc::new(EmptyResponseOperation), Arc::new(StopHookOperation::new( self.hook_manager.clone(), stop_hook_block_cap, @@ -1756,8 +959,6 @@ impl Agent { let request_preparer = GooseInferenceRequestPreparer { extension_manager: Arc::clone(&self.extension_manager), extension_lease, - goose_mode: &self.current_goose_mode, - prompt_manager: &self.prompt_manager, tool_inspection_manager: &self.tool_inspection_manager, context_limit, }; @@ -1909,10 +1110,6 @@ impl Agent { session_config: SessionConfig, cancel: CancellationToken, ) -> Result>>> { - if !super::state_machine::enabled() { - return Ok(None); - } - let session = self .config .session_manager @@ -2095,11 +1292,13 @@ impl Agent { let events = self .reply_with_state_machine(user_message, session_config, Some(cancel_token)) .await?; - Ok(Box::pin(events.map_ok(ensure_message_event_id))) + Ok(Box::pin(events.try_filter_map(|event| async move { + Ok(user_event(event)) + }))) } #[instrument( - skip(self, user_message, session_config, use_state_machine, cancel_token), + skip(self, user_message, session_config, cancel_token), fields( user_message, trace_input, @@ -2117,28 +1316,22 @@ impl Agent { &self, user_message: Message, session_config: SessionConfig, - use_state_machine: bool, cancel_token: Option, ) -> Result>> { let reply_span = tracing::Span::current(); let session_id = session_config.id.clone(); let events = crate::session_context::with_session_id( Some(session_id.clone()), - self.reply_impl( - user_message, - session_config, - use_state_machine, - cancel_token, - ), + self.reply_impl(user_message, session_config, cancel_token), ) .await?; let events = crate::session_context::with_session_id_stream(Some(session_id), events); - // This is the single live-event identity boundary. Callers that intentionally stream + // This is the single live-event boundary. Callers that intentionally stream // multiple events for one logical message must assign their shared ID before this point. Ok(Box::pin( events - .map_ok(ensure_message_event_id) + .try_filter_map(|event| async move { Ok(user_event(event)) }) .instrument(reply_span), )) } @@ -2147,7 +1340,6 @@ impl Agent { &self, user_message: Message, session_config: SessionConfig, - use_state_machine: bool, cancel_token: Option, ) -> Result>> { let user_message = user_message.with_generated_id_if_missing(); @@ -2200,1450 +1392,8 @@ impl Agent { } } - if use_state_machine { - tracing::info!("dispatching reply via experimental state machine"); - return self - .reply_with_state_machine(user_message, session_config, cancel_token) - .await; - } - - let message_text = message_text_for_trace; - - let session = session_manager - .get_session(&session_config.id, true) - .await?; - tracing::Span::current() - .record("gen_ai.agent.name", gen_ai_telemetry::agent_name(&session)); - let is_first_agent_turn = session - .conversation - .as_ref() - .map(|conversation| { - conversation.messages().iter().all(|message| { - !message.is_agent_visible() - || message.agent_visible_content().content.is_empty() - }) - }) - .unwrap_or(true); - - if !user_message.is_agent_visible() - || user_message.agent_visible_content().content.is_empty() - { - let user_visibility = user_message.is_user_visible(); - let user_message = user_message.with_visibility(user_visibility, false); - session_manager - .add_message(&session_config.id, &user_message) - .await?; - return Ok(Box::pin(futures::stream::empty())); - } - - if is_first_agent_turn && !self.session_start_emitted.swap(true, Ordering::AcqRel) { - self.emit_hook(crate::hooks::HookEvent::SessionStart, &session_config.id) - .await; - } - - if self - .hook_manager - .has_hooks(crate::hooks::HookEvent::UserPromptSubmit) - { - let ctx = crate::hooks::HookContext::new( - crate::hooks::HookEvent::UserPromptSubmit, - &session_config.id, - ) - .with_message(message_text.clone()); - self.hook_manager - .emit(crate::hooks::HookEvent::UserPromptSubmit, ctx) - .await; - } - - let command_result = self - .execute_command(&message_text, &session_config.id) - .await; - - let mut command_preamble: Vec = Vec::new(); - - match command_result { - Err(e) => { - let error_message = Message::assistant() - .with_text(e.to_string()) - .with_visibility(true, false); - return Ok(Box::pin(stream::once(async move { - Ok(AgentEvent::Message(error_message)) - }))); - } - Ok(Some(response)) - if response.role == rmcp::model::Role::Assistant - && crate::agents::execute_commands::command_starts_turn(&message_text) => - { - let response = response.with_generated_id_if_missing(); - - // Setting a goal/grind should immediately start a turn so the - // agent begins pursuing it, rather than waiting for the next - // user prompt. Record the command and its confirmation as - // user-visible only, then inject an agent-visible kickoff and - // fall through into the reply loop. - session_manager - .add_message( - &session_config.id, - &user_message.clone().with_visibility(true, false), - ) - .await?; - session_manager - .add_message( - &session_config.id, - &response.clone().with_visibility(true, false), - ) - .await?; - let goal_text = crate::agents::execute_commands::parse_slash_command(&message_text) - .map(|parsed| parsed.params_str.to_string()) - .unwrap_or_default(); - let kickoff = Message::user() - .with_text(format!( - "Start working toward this goal now:\n\n**Goal:** {goal_text}" - )) - .with_visibility(false, true); - session_manager - .add_message(&session_config.id, &kickoff) - .await?; - - command_preamble = vec![ - AgentEvent::Message(user_message.clone()), - AgentEvent::Message(response.clone()), - ]; - } - Ok(Some(response)) if response.role == rmcp::model::Role::Assistant => { - let response = response.with_generated_id_if_missing(); - - session_manager - .add_message( - &session_config.id, - &user_message.clone().with_visibility(true, false), - ) - .await?; - session_manager - .add_message( - &session_config.id, - &response.clone().with_visibility(true, false), - ) - .await?; - - // Check if this was a command that modifies conversation history - let modifies_history = crate::agents::execute_commands::COMPACT_TRIGGERS - .contains(&message_text.trim()) - || message_text.trim() == "/clear"; - - return Ok(Box::pin(async_stream::try_stream! { - yield AgentEvent::Message(user_message); - yield AgentEvent::Message(response); - - // After commands that modify history, notify UI that history was replaced - if modifies_history { - let updated_session = session_manager.get_session(&session_config.id, true) - .await - .map_err(|e| anyhow!("Failed to fetch updated session: {}", e))?; - let updated_conversation = updated_session - .conversation - .ok_or_else(|| anyhow!("Session has no conversation after history modification"))?; - yield AgentEvent::HistoryReplaced(updated_conversation); - } - })); - } - Ok(Some(resolved_message)) => { - session_manager - .add_message( - &session_config.id, - &user_message.clone().with_visibility(true, false), - ) - .await?; - session_manager - .add_message( - &session_config.id, - &resolved_message.clone().with_visibility(false, true), - ) - .await?; - } - Ok(None) => { - session_manager - .add_message(&session_config.id, &user_message) - .await?; - } - } - let session = session_manager - .get_session(&session_config.id, true) - .await?; - let conversation = session - .conversation - .clone() - .ok_or_else(|| anyhow::anyhow!("Session {} has no conversation", session_config.id))?; - - let final_output_tool = ops_recipe::final_output_tool(&session)?; - let has_final_output_tool = final_output_tool.is_some(); - *self.final_output_tool.lock().await = final_output_tool; - if has_final_output_tool { - let provider = self.provider(&session_config.id).await?; - if !provider.supports_builtin_tools() { - let provider_name = provider.get_name(); - warn!( - provider = %provider_name, - "Recipe declares structured response, but this provider can't receive the final_output tool; failing before inference" - ); - let message = Message::assistant() - .with_text(structured_output_unsupported_message(provider_name)) - .with_generated_id_if_missing(); - session_manager - .add_message(&session_config.id, &message) - .await?; - - return Ok(Box::pin(async_stream::try_stream! { - for event in command_preamble { - yield event; - } - yield AgentEvent::Message(message); - })); - } - } - - let needs_auto_compact = check_if_compaction_needed( - self.provider(&session_config.id).await?.as_ref(), - &conversation, - None, - &session, - ) - .await?; - - let conversation_to_compact = conversation.clone(); - let reply_span = tracing::Span::current(); - reply_span.record("gen_ai.agent.name", gen_ai_telemetry::agent_name(&session)); - - Ok(Box::pin(async_stream::try_stream! { - for event in command_preamble { - yield event; - } - - let final_conversation = if !needs_auto_compact { - conversation - } else { - let config = Config::global(); - let threshold = config - .get_param::("GOOSE_AUTO_COMPACT_THRESHOLD") - .unwrap_or(DEFAULT_COMPACTION_THRESHOLD); - let threshold_percentage = (threshold * 100.0) as u32; - - let inline_msg = format!( - "Exceeded auto-compact threshold of {}%. Performing auto-compaction...", - threshold_percentage - ); - - yield AgentEvent::Message( - Message::assistant().with_system_notification( - SystemNotificationType::InlineMessage, - inline_msg, - ) - ); - - yield AgentEvent::Message( - Message::assistant().with_system_notification( - SystemNotificationType::ProgressMessage, - COMPACTION_PROGRESS_TEXT, - ) - ); - - let compact_model_config = self.model_config_for_session(&session_config.id).await?; - match compact_messages( - self.provider(&session_config.id).await?.as_ref(), - &compact_model_config, - &session_config.id, - &conversation_to_compact, - false, - ) - .await - { - Ok(compaction) => { - let compacted_conversation = compaction.conversation; - session_manager.replace_conversation(&session_config.id, &compacted_conversation).await?; - self.update_session_metrics(&session_config.id, session_config.schedule_id.clone(), &compaction.usage, Some(compaction.retained_context_tokens)).await?; - - yield AgentEvent::HistoryReplaced(compacted_conversation.clone()); - - yield AgentEvent::Message( - Message::assistant().with_system_notification( - SystemNotificationType::InlineMessage, - "Compaction complete", - ) - ); - - compacted_conversation - } - Err(e) => { - yield AgentEvent::Message( - Message::assistant().with_text( - format!("Ran into this error trying to compact: {e}.\n\nPlease try again or create a new session") - ) - ); - return; - } - } - }; - - let parent_span = tracing::Span::current(); - let mut reply_stream = self.reply_internal(final_conversation, session_config, session, cancel_token, parent_span.clone()).await?; - while let Some(event) = reply_stream.next().await { - yield event?; - } - })) - } - - async fn reply_internal( - &self, - conversation: Conversation, - session_config: SessionConfig, - session: Session, - cancel_token: Option, - reply_span: tracing::Span, - ) -> Result>> { - let context = self.prepare_reply_context(&session, conversation).await?; - let ReplyContext { - session, - lease: mut inference_lease, - mut conversation, - mut tools, - mut toolshim_tools, - mut system_prompt, - tool_call_cut_off, - goose_mode, - model_config, - } = context; - - let project_addendum = self.load_project_instructions(&session).await; - if let Some(project_addendum) = &project_addendum { - system_prompt = format!("{system_prompt}\n\n{project_addendum}"); - } - - self.reset_retry_attempts().await; - - let provider = self.provider(&session_config.id).await?; - let provider_name = provider.get_name().to_string(); - let saved_provider_session_id = - super::latest_provider_session_id(conversation.messages(), &provider_name); - if let Some(saved_provider_session_id) = saved_provider_session_id { - if let Err(error) = provider.resume(saved_provider_session_id).await { - warn!( - provider = provider_name, - %error, - "Could not resume provider session; continuing with a handoff" - ); - } - } - - let requested_model = model_config.model_name.clone(); - let resolved_model = provider - .fetch_model_info(&requested_model) + self.reply_with_state_machine(user_message, session_config, cancel_token) .await - .ok() - .and_then(|model_info| model_info.resolved_model); - let provider_session_id = provider.provider_session_id(); - let inference = Some(InferenceMetadata { - provider: provider_name.clone(), - requested_model, - resolved_model, - provider_session_id, - }); - let session_manager = self.config.session_manager.clone(); - let session_id = session_config.id.clone(); - if !self.config.disable_session_naming { - let provider = provider.clone(); - let manager_for_spawn = session_manager.clone(); - let session_name_update_tx = self.config.session_name_update_tx.clone(); - tokio::spawn(async move { - match manager_for_spawn - .maybe_update_name(&session_id, provider) - .await - { - Ok(Some(update)) => { - if let Some(tx) = session_name_update_tx { - if tx.send(update).is_err() { - warn!("Failed to publish generated session name"); - } - } - } - Ok(None) => {} - Err(e) => warn!("Failed to generate session description: {}", e), - } - }); - } - - // Count tool calls present before this reply — everything added during - // the reply loop is part of the current turn and should not be summarized. - let pre_turn_tool_count = conversation - .messages() - .iter() - .flat_map(|m| m.content.iter()) - .filter(|c| matches!(c, MessageContent::ToolRequest(_))) - .count(); - - let reply_stream_span = tracing::info_span!( - parent: &reply_span, - "reply_stream", - trace_output = tracing::field::Empty, - session.id = %session_config.id, - session.user = %crate::session_context::session_user(), - session.host = %crate::session_context::session_host(), - session.agent_type = "goose", - gen_ai.operation.name = "invoke_agent", - gen_ai.agent.name = tracing::field::Empty, - gen_ai.conversation.id = %session_config.id, - gen_ai.request.model = %model_config.model_name, - gen_ai.request.temperature = tracing::field::Empty, - gen_ai.request.max_tokens = tracing::field::Empty, - gen_ai.provider.name = %provider_name, - gen_ai.input.messages = tracing::field::Empty, - gen_ai.output.messages = tracing::field::Empty, - gen_ai.response.finish_reasons = tracing::field::Empty, - gen_ai.response.id = tracing::field::Empty, - gen_ai.usage.input_tokens = tracing::field::Empty, - gen_ai.usage.output_tokens = tracing::field::Empty, - ); - gen_ai_telemetry::record_request_params(&reply_stream_span, &model_config); - reply_stream_span.record("gen_ai.agent.name", gen_ai_telemetry::agent_name(&session)); - if gen_ai_telemetry::capture_message_content() { - if let Some(last_user_msg) = conversation - .messages() - .iter() - .rev() - .find(|m| m.role == rmcp::model::Role::User) - { - reply_stream_span.record( - "gen_ai.input.messages", - gen_ai_telemetry::simple_input_json(&last_user_msg.as_concat_text()).as_str(), - ); - } - } - let inner = Box::pin(async_stream::try_stream! { - let mut session = session; - let mut turns_taken = 0u32; - let max_turns = session_config.max_turns.unwrap_or_else(|| { - Config::global() - .get_param::("GOOSE_MAX_TURNS") - .unwrap_or(DEFAULT_MAX_TURNS) - }); - let mut compaction_attempts = 0; - let mut empty_turn_retries = 0u32; - let mut retrying_after_empty_turn = false; - let mut last_assistant_text = String::new(); - let mut turn_total_usage = Usage::default(); - let mut goal_check_pending = false; - let mut tool_pair_summarization_done = false; - let mut stop_hook_handled_for_exit = false; - let mut retrying_after_stop_hook_denial = false; - let mut consecutive_stop_hook_blocks = 0u32; - let stop_hook_block_cap = self.stop_hook_block_cap(); - let mut can_drain_pending_steers = false; - let turn_start = chrono::Local::now(); - let turn_start_compaction_info = - super::moim::compute_compaction_info(&session_config.id, &self.extension_manager) - .await; - - persist_turn_context_if_changed( - &session_manager, - &session_config.id, - &mut conversation, - super::moim::turn_context_message( - &session_config.id, - &self.extension_manager, - &inference_lease, - turns_taken, - max_turns, - turn_start, - turn_start_compaction_info.clone(), - ) - .await, - ) - .await?; - // Snapshot after the turn-context append so a retry keeps the sent prefix. - let initial_messages = conversation.messages().clone(); - - let mut first_inference = true; - loop { - if is_token_cancelled(&cancel_token) { - break; - } - - // Rebuilt before every provider call, same as the state - // machine, so the lease dispatch resolves against is the - // one this inference was shown. - if first_inference { - first_inference = false; - } else { - let fallback_session = session_manager - .get_session(&session_config.id, false) - .await?; - (session, inference_lease, tools, toolshim_tools, system_prompt, _) = self - .prepare_tools_and_prompt(&fallback_session) - .await?; - let project_addendum = self.load_project_instructions(&session).await; - if let Some(project_addendum) = &project_addendum { - system_prompt = format!("{system_prompt}\n\n{project_addendum}"); - } - persist_turn_context_if_changed( - &session_manager, - &session_config.id, - &mut conversation, - super::moim::turn_context_message( - &session_config.id, - &self.extension_manager, - &inference_lease, - turns_taken, - max_turns, - turn_start, - turn_start_compaction_info.clone(), - ) - .await, - ) - .await?; - } - - if can_drain_pending_steers { - for message in self.drain_pending_steers(&session_config.id).await { - let message_text = agent_visible_message_text(&message); - if self - .hook_manager - .has_hooks(crate::hooks::HookEvent::UserPromptSubmit) - { - let ctx = crate::hooks::HookContext::new( - crate::hooks::HookEvent::UserPromptSubmit, - &session_config.id, - ) - .with_message(message_text); - self.hook_manager - .emit(crate::hooks::HookEvent::UserPromptSubmit, ctx) - .await; - } - let message = persist_and_push_message_with_id( - &session_manager, - &session_config.id, - &mut conversation, - message, - ) - .await?; - yield AgentEvent::Message(message); - } - } - - let final_output = { - let mut guard = self.final_output_tool.lock().await; - guard.as_mut().and_then(|fot| fot.final_output.take()) - }; - if let Some(output) = final_output { - last_assistant_text = output.clone(); - let message = Message::assistant() - .with_text(output) - .with_generated_id_if_missing(); - yield AgentEvent::Message(message.clone()); - session_manager.add_message(&session_config.id, &message).await?; - conversation.push(message); - - match self - .emit_stop_hook_blocking(&session_config.id, &last_assistant_text, &session.working_dir.to_string_lossy()) - .await - { - crate::hooks::HookDecision::Allow => { - stop_hook_handled_for_exit = true; - break; - } - crate::hooks::HookDecision::Deny { reason, plugin } => { - consecutive_stop_hook_blocks += 1; - if consecutive_stop_hook_blocks > stop_hook_block_cap { - let message = persist_message_with_id( - &session_manager, - &session_config.id, - stop_hook_block_cap_warning(&plugin, stop_hook_block_cap), - ) - .await?; - yield AgentEvent::Message(message); - stop_hook_handled_for_exit = true; - break; - } - persist_and_push_message_with_id( - &session_manager, - &session_config.id, - &mut conversation, - stop_hook_denial_context_message(&plugin, &reason), - ) - .await?; - yield AgentEvent::Message(stop_hook_denial_notification(&plugin)); - retrying_after_stop_hook_denial = true; - continue; - } - } - } - - if retrying_after_stop_hook_denial { - retrying_after_stop_hook_denial = false; - } else if retrying_after_empty_turn { - retrying_after_empty_turn = false; - } else { - turns_taken += 1; - } - if turns_taken > max_turns { - last_assistant_text = MAX_TURNS_MESSAGE.to_string(); - yield AgentEvent::Message(Message::assistant().with_text(last_assistant_text.clone())); - break; - } - - let mut stream = crate::agents::reply_parts::stream_response_from_provider( - self.provider(&session_config.id).await?, - model_config.clone(), - &session_config.id, - &system_prompt, - conversation.messages(), - &tools, - &toolshim_tools, - ).await?; - last_assistant_text.clear(); - - let current_turn_tool_count = conversation.messages().iter() - .flat_map(|m| m.content.iter()) - .filter(|c| matches!(c, MessageContent::ToolRequest(_))) - .count() - .saturating_sub(pre_turn_tool_count); - - let tool_pair_summarization_task = if tool_pair_summarization_done { - None - } else { - crate::context_mgmt::maybe_summarize_tool_pairs( - self.provider(&session_config.id).await?, - model_config.clone(), - session_config.id.clone(), - conversation.clone(), - tool_call_cut_off, - current_turn_tool_count, - ) - }; - - let mut no_tools_called = true; - let mut messages_to_add = Conversation::default(); - let mut did_recovery_compact_this_iteration = false; - let mut exit_chat = false; - let mut provider_errored = false; - let mut provider_produced_content = false; - let mut provider_reached_output_token_limit = false; - let mut pending_final_output: Option = None; - let mut pending_turn_usage: Option = None; - let mut preferred_turn_usage_message_id: Option = None; - - // Track whether this provider turn has already emitted visible - // thinking so a later tool-call chunk can suppress replayed - // reasoning without hiding final-only non-streaming thoughts. - let mut surfaced_thinking_in_turn = false; - - loop { - let next = if let Some(cancel_token) = &cancel_token { - tokio::select! { - biased; - _ = cancel_token.cancelled() => break, - next = stream.next() => next, - } - } else { - stream.next().await - }; - let Some(next) = next else { - break; - }; - - if exit_chat { - break; - } - - match next { - Ok((response, usage)) => { - compaction_attempts = 0; - - if let Some(ref usage) = usage { - let enriched = self.update_session_metrics(&session_config.id, session_config.schedule_id.clone(), usage, None).await?; - yield AgentEvent::Usage(enriched.clone()); - turn_total_usage += enriched.usage; - pending_turn_usage = Some(enriched); - } - - if let Some(response) = response { - provider_reached_output_token_limit |= - response.metadata.output_token_limit_reached; - - if !response.content.is_empty() - && response.content.iter().all(|content| { - matches!(content, MessageContent::SystemNotification(_)) - }) - { - yield AgentEvent::Message(response); - tokio::task::yield_now().await; - continue; - } - - provider_produced_content |= response.content.iter().any(|content| { - match content { - MessageContent::Text(text) => !text.text.is_empty(), - MessageContent::Image(image) => !image.data.is_empty(), - MessageContent::Thinking(thinking) => { - !thinking.thinking.is_empty() - || !thinking.signature.is_empty() - } - MessageContent::RedactedThinking(thinking) => { - !thinking.data.is_empty() - } - MessageContent::SystemNotification(notification) => { - !notification.msg.is_empty() - } - _ => true, - } - }); - - let (tool_requests, filtered_response) = self - .categorize_tool_requests( - &response, - &tools, - &toolshim_tools, - surfaced_thinking_in_turn, - ); - - let filtered_response = if let Some(inference) = inference.as_ref() { - filtered_response.with_inference(inference.clone()) - } else { - filtered_response - }; - let response = if let Some(inference) = inference.as_ref() { - response.with_inference(inference.clone()) - } else { - response - }; - - surfaced_thinking_in_turn |= filtered_response.content.iter().any( - |content| { - matches!( - content, - MessageContent::Thinking(_) - | MessageContent::RedactedThinking(_) - ) - }, - ); - - if !filtered_response.content.is_empty() - || filtered_response.metadata.output_token_limit_reached - { - yield AgentEvent::Message(filtered_response.clone()); - tokio::task::yield_now().await; - } - - if tool_requests.is_empty() { - let text = if response.is_user_visible() { - filtered_response - .user_visible_content() - .as_concat_text() - } else { - String::new() - }; - if !text.is_empty() { - last_assistant_text.push_str(&text); - } - messages_to_add.push(response); - continue; - } - - let mut request_to_response_map = HashMap::new(); - let mut request_metadata: HashMap> = HashMap::new(); - for request in &tool_requests { - request_to_response_map.insert(request.id.clone(), Message::user().with_generated_id()); - request_metadata.insert(request.id.clone(), request.metadata.clone()); - } - - if goose_mode == GooseMode::Chat { - for request in &tool_requests { - // An unparseable tool call should surface the parse error - // (added in the Err branch below), not a successful skip — - // otherwise the model sees a malformed call as "skipped OK" - // and can't correct the arguments. - if request.tool_call.is_err() { - continue; - } - if let Some(response) = request_to_response_map.get_mut(&request.id) { - response.add_tool_response_with_metadata( - request.id.clone(), - Ok(CallToolResult::success(vec![ContentBlock::text(CHAT_MODE_TOOL_SKIPPED_RESPONSE)])), - request.metadata.as_ref(), - ); - } - } - } else { - // Run all tool inspectors - let inspection_results = self.tool_inspection_manager - .inspect_tools( - &session_config.id, - &tool_requests, - conversation.messages(), - goose_mode, - ) - .await?; - - let permission_check_result = self.tool_inspection_manager - .process_inspection_results_with_permission_inspector( - &tool_requests, - &inspection_results, - ) - .unwrap_or_else(|| { - let mut result = PermissionCheckResult { - approved: vec![], - needs_approval: vec![], - denied: vec![], - }; - result.needs_approval.extend(tool_requests.iter().cloned()); - result - }); - - let mut tool_futures = self.handle_approved_and_denied_tools( - &inference_lease, - &permission_check_result, - &mut request_to_response_map, - cancel_token.clone(), - &session, - ).await?; - - { - let mut tool_approval_stream = self.handle_approval_tool_requests( - &permission_check_result.needs_approval, - ApprovalToolContext { - lease: &inference_lease, - tool_futures: &mut tool_futures, - request_to_response_map: &mut request_to_response_map, - cancellation_token: cancel_token.clone(), - session: &session, - inspection_results: &inspection_results, - }, - ); - - while let Some(msg) = tool_approval_stream.try_next().await? { - yield AgentEvent::Message(msg); - } - } - - let with_id = tool_futures - .into_iter() - .map(|(request_id, stream)| { - stream.map(move |item| (request_id.clone(), item)) - }) - .collect::>(); - - let mut combined = stream::select_all(with_id); - loop { - if is_token_cancelled(&cancel_token) { - break; - } - - tokio::select! { - biased; - - tool_item = combined.next() => { - match tool_item { - Some((request_id, item)) => { - match item { - ToolStreamItem::ActionRequired(msg) => { - let msg = msg.with_generated_id_if_missing(); - if let Err(e) = session_manager.add_message(&session_config.id, &msg).await { - warn!("Failed to save elicitation message to session: {}", e); - } - yield AgentEvent::Message(msg); - } - ToolStreamItem::Result(output) => { - if let Ok(ref call_result) = output { - if let Some(ref meta) = call_result.meta { - if let Some(notification_data) = meta.0.get("platform_notification") { - if let Some(method) = notification_data.get("method").and_then(|v| v.as_str()) { - let params = notification_data.get("params").cloned(); - let custom_notification = rmcp::model::CustomNotification::new( - method.to_string(), - params, - ); - - let server_notification = rmcp::model::ServerNotification::CustomNotification(custom_notification); - yield AgentEvent::McpNotification((request_id.clone(), server_notification)); - } - } - } - } - - if let Some(response) = request_to_response_map.get_mut(&request_id) { - let metadata = request_metadata.get(&request_id).and_then(|m| m.as_ref()); - response.add_tool_response_with_metadata(request_id, output, metadata); - } - } - ToolStreamItem::Message(msg) => { - yield AgentEvent::McpNotification((request_id, msg)); - } - } - } - None => break, - } - } - - _ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {} - } - } - - } - - // DeepSeek and Kimi need the turn's thinking on every split - // tool-call message; fix_conversation removes the signed copies. - let is_thinking = |c: &MessageContent| { - matches!( - c, - MessageContent::Thinking(_) - | MessageContent::RedactedThinking(_) - ) - }; - let prior_thinking: Vec = messages_to_add - .iter() - .filter(|m| m.role == response.role) - .flat_map(|m| m.content.iter()) - .filter(|c| is_thinking(c)) - .cloned() - .collect(); - let direct_thinking: Vec = response - .content - .iter() - .filter(|c| is_thinking(c) && !prior_thinking.contains(c)) - .cloned() - .collect(); - let mut turn_thinking = prior_thinking; - turn_thinking.extend(direct_thinking.iter().cloned()); - - let response_message_id = response - .id - .as_deref() - .expect("provider stream responses have IDs"); - let is_response_message = |message: &Message| { - message.id.as_deref() == Some(response_message_id) - }; - let first_tool_call_id = tool_requests - .first() - .map(|request| request.id.as_str()); - // A same-id prefix at the tail coalesces with the first request on - // push, so tool-pair hiding removes the thinking with the call. - let carrier_tool_call_id = match messages_to_add.messages().last() { - Some(last) if is_response_message(last) => first_tool_call_id, - _ if messages_to_add.iter().any(is_response_message) => None, - _ => first_tool_call_id, - }; - preferred_turn_usage_message_id = - Some(response_message_id.to_owned()); - - for (index, request) in tool_requests.iter().enumerate() { - let mut request_msg = - if carrier_tool_call_id == Some(request.id.as_str()) { - Message::assistant().with_id(response_message_id) - } else { - Message::assistant().with_generated_id() - }; - - let thinking = if index == 0 { - &direct_thinking - } else { - &turn_thinking - }; - for thinking in thinking { - request_msg = request_msg.with_content(thinking.clone()); - } - - // For an unparseable tool call (Err), store a valid - // placeholder Ok tool-call in history instead of the Err. This - // keeps the conversation well-formed through EVERY provider - // formatter's normal Ok path — so we don't have to special-case - // each formatter's Err arm — and preserves provider metadata - // (e.g. thought signatures), which is passed through below and - // copied by the Ok path. The actual parse error rides on the - // paired tool response. - let history_tool_call = match &request.tool_call { - Ok(_) => request.tool_call.clone(), - Err(_) => Ok(CallToolRequestParams::new( - "unparseable_tool_call", - ) - .with_arguments(serde_json::Map::new())), - }; - request_msg = request_msg - .with_tool_request_with_metadata( - request.id.clone(), - history_tool_call, - request.metadata.as_ref(), - request.tool_meta.clone(), - ); - - let final_response = match &request.tool_call { - Ok(_) => request_to_response_map - .remove(&request.id) - .unwrap_or_else(|| Message::user().with_generated_id()), - Err(error) => { - error!("Tool call could not be parsed: {error}"); - let mut response = request_to_response_map - .remove(&request.id) - .unwrap_or_else(|| Message::user().with_generated_id()); - // Only feed the parse error back if this id isn't - // already answered. In Chat mode the skip branch above - // already added a tool response for it; adding another - // here would duplicate the tool_call_id (which strict - // providers reject). - let already_answered = response.content.iter().any(|c| { - matches!(c, MessageContent::ToolResponse(r) if r.id == request.id) - }); - if !already_answered { - response.add_tool_response_with_metadata( - request.id.clone(), - Err(error.clone()), - request.metadata.as_ref(), - ); - } - response - } - }; - - // Response placeholder is created before tools run, so clamp request to avoid inverted ordering. - if request_msg.created > final_response.created { - request_msg.created = final_response.created; - } - messages_to_add.push(request_msg); - yield AgentEvent::Message(project_message_for_user_event(&final_response)); - messages_to_add.push(final_response); - } - - no_tools_called = false; - } - } - #[allow(unused_variables)] - Err(ref provider_err @ ProviderError::ContextLengthExceeded(_)) => { - provider_errored = true; - #[cfg(feature = "telemetry")] - crate::posthog::emit_error(provider_err.telemetry_type(), &provider_err.to_string()); - compaction_attempts += 1; - - if compaction_attempts >= 2 { - error!("Context limit exceeded after compaction - prompt too large"); - yield AgentEvent::Message( - Message::assistant().with_system_notification( - SystemNotificationType::InlineMessage, - "Unable to continue: Context limit still exceeded after compaction. Try using a shorter message, a model with a larger context window, or start a new session." - ) - ); - break; - } - - yield AgentEvent::Message( - Message::assistant().with_system_notification( - SystemNotificationType::InlineMessage, - "Context limit reached. Compacting to continue conversation...", - ) - ); - yield AgentEvent::Message( - Message::assistant().with_system_notification( - SystemNotificationType::ProgressMessage, - COMPACTION_PROGRESS_TEXT, - ) - ); - - match compact_messages( - self.provider(&session_config.id).await?.as_ref(), - &model_config, - &session_config.id, - &conversation, - false, - ) - .await - { - Ok(compaction) => { - session_manager.replace_conversation(&session_config.id, &compaction.conversation).await?; - self.update_session_metrics(&session_config.id, session_config.schedule_id.clone(), &compaction.usage, Some(compaction.retained_context_tokens)).await?; - conversation = compaction.conversation; - did_recovery_compact_this_iteration = true; - yield AgentEvent::HistoryReplaced(conversation.clone()); - break; - } - Err(e) => { - #[cfg(feature = "telemetry")] - crate::posthog::emit_error("compaction_failed", &e.to_string()); - error!("Compaction failed: {}", e); - yield AgentEvent::Message( - Message::assistant().with_text( - format!("Ran into this error trying to compact: {e}.\n\nPlease try again or create a new session") - ) - ); - break; - } - } - } - Err(ref provider_err @ ProviderError::CreditsExhausted { details: _, ref top_up_url }) => { - provider_errored = true; - #[cfg(feature = "telemetry")] - crate::posthog::emit_error(provider_err.telemetry_type(), &provider_err.to_string()); - error!("Error: {}", provider_err); - - let user_msg = if top_up_url.is_some() { - "Please add credits to your account, then resend your message to continue.".to_string() - } else { - "Please check your account with your provider to add more credits, then resend your message to continue.".to_string() - }; - - let notification_data = serde_json::json!({ - "top_up_url": top_up_url, - }); - - yield AgentEvent::Message( - Message::assistant().with_system_notification_with_data( - SystemNotificationType::CreditsExhausted, - user_msg, - notification_data, - ) - ); - break; - } - Err(ref provider_err @ ProviderError::Refusal { ref details, ref category }) => { - provider_errored = true; - #[cfg(feature = "telemetry")] - crate::posthog::emit_error(provider_err.telemetry_type(), &provider_err.to_string()); - error!("Error: {}", provider_err); - - let category = category.as_deref().map(|c| format!("\n\nCategory: {c}")).unwrap_or_default(); - yield AgentEvent::Message(Message::assistant().with_text(format!( - "The provider refused this request.\n\n{details}{category}\n\nPlease start a new session to continue — resending this conversation is likely to be refused again." - ))); - // A refusal is terminal: skip goal/grind nudges and - // recipe retry_config, which would resend the same - // refused conversation. - exit_chat = true; - break; - } - Err(ref provider_err @ ProviderError::Authentication(_)) => { - provider_errored = true; - #[cfg(feature = "telemetry")] - crate::posthog::emit_error(provider_err.telemetry_type(), &provider_err.to_string()); - error!("Error: {}", provider_err); - let message = persist_and_push_message_with_id( - &session_manager, - &session_config.id, - &mut conversation, - Message::from_provider_error(provider_err), - ) - .await?; - yield AgentEvent::Message(message); - break; - } - Err(ref provider_err @ ProviderError::NetworkError(_)) => { - provider_errored = true; - #[cfg(feature = "telemetry")] - crate::posthog::emit_error(provider_err.telemetry_type(), &provider_err.to_string()); - error!("Error: {}", provider_err); - yield AgentEvent::Message( - Message::assistant().with_text( - format!("{provider_err}\n\nPlease resend your message to try again.") - ) - ); - break; - } - Err(ref provider_err) => { - provider_errored = true; - #[cfg(feature = "telemetry")] - crate::posthog::emit_error(provider_err.telemetry_type(), &provider_err.to_string()); - error!("Error: {}", provider_err); - yield AgentEvent::Message( - Message::assistant().with_text( - format!("Ran into this error: {provider_err}.\n\nPlease retry if you think this is a transient or recoverable error.") - ) - ); - break; - } - } - } - can_drain_pending_steers = true; - - self.prompt_manager - .lock() - .await - .load_subdirectory_hints(&session.working_dir); - - // An empty provider response — no tool calls, no text, and no error - // or recovery compaction that legitimately produces no assistant - // output — must never be persisted: strict providers reject a - // conversation that contains an empty assistant turn. Drop it here - // regardless of what the match below decides to do about the turn - // (final-output nudge, steer, goal/grind, retry, or fallback). - let empty_response = no_tools_called - && !exit_chat - && !provider_errored - && !did_recovery_compact_this_iteration - && !provider_reached_output_token_limit - && !provider_produced_content - && last_assistant_text.is_empty(); - - if empty_response { - messages_to_add = Conversation::default(); - } else { - empty_turn_retries = 0; - } - - if no_tools_called && !exit_chat { - // Lock, extract state, drop guard before branching — handle_retry_logic - // also locks final_output_tool and tokio::sync::Mutex is not reentrant. - let final_output = { - let mut guard = self.final_output_tool.lock().await; - guard.as_mut().map(|fot| fot.final_output.take()) - }; - - match final_output { - Some(None) => { - warn!("Final output tool has not been called yet. Continuing agent loop."); - let message = push_message_with_id( - &mut messages_to_add, - Message::user().with_text(FINAL_OUTPUT_CONTINUATION_MESSAGE).agent_only(), - ); - yield AgentEvent::Message(message); - } - Some(Some(output)) => { - pending_final_output = Some(output); - exit_chat = true; - } - None if did_recovery_compact_this_iteration => { - // continue from last user message after recovery compact - } - None if self.has_pending_steers(&session_config.id).await => {} - None if GoalState::of(&session).goal.is_some() && !goal_check_pending => { - goal_check_pending = true; - let goal = GoalState::of(&session).goal.unwrap(); - let nudge = format!( - "Before finishing, check whether the following goal has been fully met:\n\n\ - **Goal:** {goal}\n\n\ - If not, continue working toward it." - ); - let message = Message::user().with_text(&nudge) - .with_visibility(false, true); - push_message_with_id(&mut messages_to_add, message); - yield AgentEvent::Message( - Message::assistant().with_system_notification( - SystemNotificationType::InlineMessage, - format!("Goal: {goal}"), - ) - ); - } - - None if GoalState::of(&session).grind.is_some() => { - let grind = GoalState::of(&session).grind.unwrap(); - let nudge = format!( - "Keep working. The grind goal is not yet complete:\n\n\ - **Goal:** {grind}\n\n\ - Continue until it is fully done." - ); - let message = Message::user().with_text(&nudge) - .with_visibility(false, true); - push_message_with_id(&mut messages_to_add, message); - yield AgentEvent::Message( - Message::assistant().with_system_notification( - SystemNotificationType::InlineMessage, - format!("Grind: {grind}"), - ) - ); - } - - None => { - session_manager - .set_extension_state(&session_config.id, &GoalState::default()) - .await?; - // Recipe retry logic owns the turn whenever a - // retry_config is present: it runs success checks, - // on_failure, and max_retries. Only when no recipe - // retry is configured (Skipped) does the empty-turn - // fallback apply. - match self.handle_retry_logic(&mut conversation, &session_config, &initial_messages).await { - Ok(RetryResult::Retried) => { - info!("Retry logic triggered, restarting agent loop"); - messages_to_add = Conversation::default(); - session_manager.replace_conversation(&session_config.id, &conversation).await?; - yield AgentEvent::HistoryReplaced(conversation.clone()); - } - Ok(RetryResult::Skipped) - if empty_response - && !ends_with_successful_tool_response(conversation.messages()) => { - // No recipe retry configured, and this empty - // turn would otherwise fall through to a - // silent exit. Retry a bounded number of - // times, then surface a visible message so - // the user is never left with no response. - if empty_turn_retries < MAX_EMPTY_TURN_RETRIES { - empty_turn_retries += 1; - retrying_after_empty_turn = true; - warn!( - "Provider returned an empty response; retrying ({}/{})", - empty_turn_retries, MAX_EMPTY_TURN_RETRIES - ); - } else { - warn!("Provider returned an empty response after retries; ending turn"); - last_assistant_text = EMPTY_TURN_MESSAGE.to_string(); - let message = push_message_with_id( - &mut messages_to_add, - Message::assistant().with_text(EMPTY_TURN_MESSAGE), - ); - yield AgentEvent::Message(message); - exit_chat = true; - } - } - Ok(RetryResult::MaxAttemptsReached(message)) => { - // Surface and persist the failure message - // through the normal path so recipes don't - // exit silently when retries are exhausted. - let message = push_message_with_id(&mut messages_to_add, message); - last_assistant_text = message.as_concat_text(); - yield AgentEvent::Message(message); - exit_chat = true; - } - Ok(_) => { - exit_chat = true; - } - Err(e) => { - error!("Retry logic failed: {}", e); - yield AgentEvent::Message( - Message::assistant().with_text( - format!("Retry logic encountered an error: {}", e) - ) - ); - exit_chat = true; - } - } - } - } - } - - if is_token_cancelled(&cancel_token) { - if let Some(ref task) = tool_pair_summarization_task { - task.abort(); - } - } - - if let Some(task) = tool_pair_summarization_task { - tool_pair_summarization_done = true; - if let Ok(summaries) = task.await { - for (summary_msg, tool_id) in summaries { - let matching_ids: Vec = conversation.messages() - .iter() - .filter(|msg| { - msg.id.is_some() && msg.content.iter().any(|c| match c { - MessageContent::ToolRequest(req) => req.id == tool_id, - MessageContent::ToolResponse(resp) => resp.id == tool_id, - _ => false, - }) - }) - .filter_map(|msg| msg.id.clone()) - .collect(); - - if matching_ids.len() == 2 { - for id in &matching_ids { - session_manager.update_message_metadata(&session_config.id, id, |metadata| { - metadata.with_agent_invisible() - }).await?; - } - session_manager.add_message(&session_config.id, &summary_msg).await?; - } else { - warn!("Expected a tool request/reply pair, but found {} matching messages", - matching_ids.len()); - } - } - } - } - - if let Some(output) = pending_final_output.take() { - preferred_turn_usage_message_id = None; - last_assistant_text = output.clone(); - let message = push_message_with_id( - &mut messages_to_add, - Message::assistant().with_text(output), - ); - yield AgentEvent::Message(message); - } - - let mut messages_to_add = if let Some(ref inference) = inference { - Conversation::new_unvalidated( - messages_to_add - .into_iter() - .map(|message| message.with_inference_if_assistant(inference.clone())), - ) - } else { - messages_to_add - }; - - if let Some(usage) = pending_turn_usage.take() { - if let Some((message_id, usage)) = attach_turn_usage( - &mut messages_to_add, - &usage, - preferred_turn_usage_message_id.as_deref(), - ) { - yield AgentEvent::MessageUsage { message_id, usage }; - } - } - - for msg in &messages_to_add { - session_manager.add_message(&session_config.id, msg).await?; - } - conversation.extend(messages_to_add); - - if exit_chat && self.has_pending_steers(&session_config.id).await { - exit_chat = false; - } - - if exit_chat { - match self - .emit_stop_hook_blocking(&session_config.id, &last_assistant_text, &session.working_dir.to_string_lossy()) - .await - { - crate::hooks::HookDecision::Allow => { - stop_hook_handled_for_exit = true; - break; - } - crate::hooks::HookDecision::Deny { reason, plugin } => { - consecutive_stop_hook_blocks += 1; - if consecutive_stop_hook_blocks > stop_hook_block_cap { - let message = persist_message_with_id( - &session_manager, - &session_config.id, - stop_hook_block_cap_warning(&plugin, stop_hook_block_cap), - ) - .await?; - yield AgentEvent::Message(message); - stop_hook_handled_for_exit = true; - break; - } - persist_and_push_message_with_id( - &session_manager, - &session_config.id, - &mut conversation, - stop_hook_denial_context_message(&plugin, &reason), - ) - .await?; - yield AgentEvent::Message(stop_hook_denial_notification(&plugin)); - retrying_after_stop_hook_denial = true; - } - } - } - - tokio::task::yield_now().await; - } - - if !last_assistant_text.is_empty() - && gen_ai_telemetry::capture_message_content() - { - tracing::Span::current().record("trace_output", last_assistant_text.as_str()); - let output_json = gen_ai_telemetry::simple_output_json(&last_assistant_text); - tracing::Span::current().record("gen_ai.output.messages", output_json.as_str()); - reply_span.record("gen_ai.output.messages", output_json.as_str()); - } - gen_ai_telemetry::record_usage(&tracing::Span::current(), &turn_total_usage); - gen_ai_telemetry::record_usage(&reply_span, &turn_total_usage); - - if !stop_hook_handled_for_exit { - self.emit_stop_hook(&session_config.id, &last_assistant_text, &session.working_dir.to_string_lossy()).await; - } - drop(inference_lease); - }.instrument(reply_stream_span)); - Ok(inner) } /// Pins `provider` to the session instead of letting the provider manager @@ -3732,7 +1482,6 @@ impl Agent { .await .map_err(|e| anyhow::anyhow!("Provider rejected mode update: {e}"))?; } - *self.current_goose_mode.lock().await = mode; self.config .session_manager .clone() @@ -3743,8 +1492,13 @@ impl Agent { .context("Failed to persist goose_mode to session") } - pub async fn goose_mode(&self) -> GooseMode { - *self.current_goose_mode.lock().await + pub async fn goose_mode(&self, session_id: &str) -> Result { + Ok(self + .config + .session_manager + .get_session(session_id, false) + .await? + .goose_mode) } /// Apply a thinking-effort selection. `effort` is the raw option value: a @@ -3826,8 +1580,6 @@ impl Agent { } } - *self.current_goose_mode.lock().await = session.goose_mode; - if crate::providers::get_from_registry(&provider_name) .await .is_ok() @@ -3911,16 +1663,13 @@ impl Agent { #[cfg(test)] mod tests { use super::*; - use crate::agents::gen_ai_telemetry::{self, test_support::SpanFieldCapture}; - use crate::agents::mcp_client::{Error as McpClientError, McpClientTrait}; - use crate::agents::ToolCallContext; + + use crate::conversation::message::InferenceMetadata; use crate::plugins::discovery::{DiscoveredPlugin, PluginScope}; - use crate::providers::base::{ - stream_from_single_message, MessageStream, ModelInfo, PermissionRouting, - }; + use crate::providers::base::{stream_from_single_message, MessageStream, ModelInfo}; use crate::session::session_manager::SessionType; use goose_providers::conversation::token_usage::{ProviderUsage, Usage}; - use rmcp::model::{Annotations, Role, TextContent, Tool}; + use rmcp::model::Tool; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; use tempfile::TempDir; @@ -3936,295 +1685,6 @@ mod tests { } } - fn platform_extension(name: &str) -> ExtensionConfig { - ExtensionConfig::Platform { - name: name.to_string(), - description: String::new(), - display_name: None, - bundled: None, - available_tools: Vec::new(), - } - } - - struct LeaseValueClient(&'static str); - - #[async_trait::async_trait] - impl McpClientTrait for LeaseValueClient { - async fn list_tools( - &self, - _session_id: &str, - _next_cursor: Option, - _cancellation_token: CancellationToken, - ) -> std::result::Result { - Ok(rmcp::model::ListToolsResult::with_all_items(vec![ - Tool::new( - "value".to_string(), - "Return the client value".to_string(), - Arc::new(serde_json::Map::new()), - ), - ])) - } - - async fn call_tool( - &self, - _ctx: &ToolCallContext, - _name: &str, - _arguments: Option, - _cancellation_token: CancellationToken, - ) -> std::result::Result { - Ok(CallToolResult::success(vec![ContentBlock::text(self.0)])) - } - - fn get_info(&self) -> Option<&rmcp::model::InitializeResult> { - None - } - - async fn get_moim(&self, _session_id: &str, _tools: &[Tool]) -> Option { - Some(format!("{}", self.0)) - } - } - - struct RefreshingLeaseProvider { - manager: std::sync::Mutex>>, - turn_contexts: std::sync::Mutex>, - call_count: AtomicUsize, - } - - impl RefreshingLeaseProvider { - fn new() -> Self { - Self { - manager: std::sync::Mutex::new(None), - turn_contexts: std::sync::Mutex::new(Vec::new()), - call_count: AtomicUsize::new(0), - } - } - } - - #[async_trait::async_trait] - impl crate::providers::base::Provider for RefreshingLeaseProvider { - async fn stream( - &self, - _model_config: &goose_providers::model::ModelConfig, - _system_prompt: &str, - messages: &[Message], - _tools: &[Tool], - ) -> Result { - self.turn_contexts.lock().unwrap().push( - messages - .iter() - .map(Message::as_concat_text) - .collect::>() - .join("\n"), - ); - let call = self.call_count.fetch_add(1, Ordering::SeqCst); - let message = if call == 0 { - let manager = self - .manager - .lock() - .unwrap() - .clone() - .expect("extension manager unavailable"); - manager - .add_client( - platform_extension("changing"), - Arc::new(LeaseValueClient("second")), - None, - ) - .await; - Message::assistant().with_tool_request( - "refresh-context", - Ok(CallToolRequestParams::new("changing__value")), - ) - } else { - Message::assistant().with_text("done") - }; - Ok(stream_from_single_message( - message, - ProviderUsage::new("mock-model".to_string(), Usage::default()), - )) - } - - fn get_name(&self) -> &str { - "refreshing-lease" - } - - async fn get_context_limit(&self, _model: &str, _override_limit: Option) -> usize { - 100_000 - } - } - - #[tokio::test] - async fn overlapping_dispatches_use_their_inference_lease() { - let (agent, session, _data_dir) = tracing_test_agent_and_session().await; - agent - .extension_manager - .add_client( - persisted_builtin("changing"), - Arc::new(LeaseValueClient("first")), - None, - ) - .await; - let first_lease = agent.resolve_lease(&session.id, &session.working_dir).await; - - agent - .extension_manager - .add_client( - persisted_builtin("changing"), - Arc::new(LeaseValueClient("second")), - None, - ) - .await; - let second_lease = agent.resolve_lease(&session.id, &session.working_dir).await; - - let first = agent.dispatch_tool_call_on( - &first_lease, - CallToolRequestParams::new("changing__value"), - "first-call".to_string(), - None, - &session, - ); - let second = agent.dispatch_tool_call_on( - &second_lease, - CallToolRequestParams::new("changing__value"), - "second-call".to_string(), - None, - &session, - ); - let ((_, first), (_, second)) = tokio::join!(first, second); - let first = first.unwrap().result.await.unwrap(); - let second = second.unwrap().result.await.unwrap(); - - assert_eq!(first.content[0].as_text().unwrap().text, "first"); - assert_eq!(second.content[0].as_text().unwrap().text, "second"); - } - - #[tokio::test] - async fn legacy_inference_refreshes_extension_context() -> Result<()> { - let temp_dir = tempfile::tempdir()?; - let provider = Arc::new(RefreshingLeaseProvider::new()); - let (agent, session_id) = create_test_agent( - temp_dir.path().join("data"), - crate::hooks::HookManager::from_plugins_for_test(vec![]), - provider.clone(), - ) - .await?; - *provider.manager.lock().unwrap() = Some(Arc::clone(&agent.extension_manager)); - - let mut stream = agent - .reply( - Message::user().with_text("refresh extension context"), - SessionConfig { - id: session_id, - schedule_id: None, - max_turns: Some(100), - retry_config: None, - }, - false, - None, - ) - .await?; - while let Some(event) = stream.next().await { - event?; - } - - let contexts = provider.turn_contexts.lock().unwrap(); - assert_eq!(contexts.len(), 2); - assert!(!contexts[0].contains("second")); - assert!(contexts[1].contains("second")); - Ok(()) - } - - #[tokio::test] - async fn inference_context_uses_the_lease_session_snapshot() -> Result<()> { - let temp_dir = tempfile::tempdir()?; - let new_working_dir = temp_dir.path().join("moved"); - std::fs::create_dir(&new_working_dir)?; - std::fs::write( - new_working_dir.join("AGENTS.md"), - "instructions from the moved directory", - )?; - let (agent, session_id) = create_test_agent( - temp_dir.path().join("data"), - crate::hooks::HookManager::from_plugins_for_test(vec![]), - Arc::new(RefreshingLeaseProvider::new()), - ) - .await?; - let stale_session = agent - .config - .session_manager - .get_session(&session_id, false) - .await?; - agent - .extension_manager - .add_client( - persisted_builtin("changing"), - Arc::new(LeaseValueClient("value")), - None, - ) - .await; - agent - .update_extension_working_dir(&session_id, &new_working_dir) - .await?; - - let (session, lease, tools, _, system_prompt, _) = - agent.prepare_tools_and_prompt(&stale_session).await?; - - assert_eq!(session.working_dir, new_working_dir); - assert_eq!(lease.working_dir(), Some(session.working_dir.as_path())); - assert!(tools.iter().any(|tool| tool.name == "changing__value")); - assert!(system_prompt.contains("instructions from the moved directory")); - Ok(()) - } - - #[tokio::test] - async fn mangled_manage_extensions_call_applies_its_mutation() { - let (agent, session, _data_dir) = tracing_test_agent_and_session().await; - agent - .add_extension( - ExtensionConfig::Platform { - name: "extensionmanager".to_string(), - description: String::new(), - display_name: None, - bundled: None, - available_tools: Vec::new(), - }, - &session.id, - ) - .await - .unwrap(); - let lease = agent.resolve_lease(&session.id, &session.working_dir).await; - let tool_call = - CallToolRequestParams::new("functions.extensionmanager__manage_extensions".to_string()) - .with_arguments(rmcp::object!({ - "action": "enable", - "extension_name": "analyze", - })); - - let (_, result) = agent - .dispatch_tool_call_on(&lease, tool_call, "manage".to_string(), None, &session) - .await; - result.unwrap().result.await.unwrap(); - - assert!(agent - .extension_manager - .list_extensions() - .await - .unwrap() - .contains(&"analyze".to_string())); - let stored_session = agent - .config - .session_manager - .get_session(&session.id, false) - .await - .unwrap(); - let stored_extensions = - EnabledExtensionsState::from_extension_data(&stored_session.extension_data).unwrap(); - assert!(stored_extensions - .extensions - .iter() - .any(|config| config.key() == "analyze")); - } - #[test] fn persisted_extension_identity_must_be_unique_before_removal() { let session_extension = persisted_builtin("session-only"); @@ -4261,33 +1721,6 @@ mod tests { })); } - #[test] - fn provider_session_id_comes_from_latest_inference() { - let messages = vec![ - Message::assistant().with_inference(InferenceMetadata { - provider: "codex-acp".to_string(), - requested_model: "current".to_string(), - resolved_model: None, - provider_session_id: Some("codex-session".to_string()), - }), - Message::assistant().with_inference(InferenceMetadata { - provider: "claude-acp".to_string(), - requested_model: "current".to_string(), - resolved_model: None, - provider_session_id: Some("claude-session".to_string()), - }), - ]; - - assert_eq!( - super::super::latest_provider_session_id(&messages, "claude-acp"), - Some("claude-session") - ); - assert_eq!( - super::super::latest_provider_session_id(&messages, "codex-acp"), - None - ); - } - #[derive(Debug, Default)] struct SessionContextProvider { calls: std::sync::Mutex)>>, @@ -4350,7 +1783,6 @@ mod tests { Arc::clone(&session_manager), Arc::new(PermissionManager::new(temp_dir.path().join("permissions"))), None, - GooseMode::default(), true, GoosePlatform::GooseCli, )); @@ -4395,7 +1827,6 @@ mod tests { id: session.id.clone(), schedule_id: None, max_turns: Some(1), - retry_config: None, }; (agent, provider, session_config, temp_dir) @@ -4423,12 +1854,7 @@ mod tests { let (agent, provider, session_config, _temp_dir) = session_context_agent().await; let session_id = session_config.id.clone(); let mut events = agent - .reply( - Message::user().with_text("continue"), - session_config, - false, - None, - ) + .reply(Message::user().with_text("continue"), session_config, None) .await .unwrap(); while let Some(event) = events.next().await { @@ -4474,7 +1900,6 @@ mod tests { Arc::clone(&session_manager), Arc::new(PermissionManager::new(data_path)), None, - GooseMode::default(), false, GoosePlatform::GooseCli, )); @@ -4490,155 +1915,6 @@ mod tests { (agent, session, data_dir) } - async fn capture_tool_dispatch_fields( - capture_setting: Option<&'static str>, - ) -> serde_json::Map { - use goose_test_support::otel::clear_otel_env; - use rmcp::object; - - let _env = match capture_setting { - Some(value) => { - clear_otel_env(&[(gen_ai_telemetry::CAPTURE_MESSAGE_CONTENT_ENV, value)]) - } - None => clear_otel_env(&[]), - }; - let capture = SpanFieldCapture::new("dispatch_tool_call"); - let _subscriber = capture.clone().set_default(); - let (agent, session, _data_dir) = tracing_test_agent_and_session().await; - let tool_call = CallToolRequestParams::new( - crate::agents::platform_extensions::scheduler::MANAGE_SCHEDULE_TOOL_NAME_COMPLETE, - ) - .with_arguments(object!({ - "action": "list", - "api_key": "tool-input-super-secret-token", - })); - - let (_, result) = agent - .dispatch_tool_call(tool_call, "call-secret".to_string(), None, &session) - .await; - let _ = result.unwrap().result.await; - capture.fields() - } - - #[tokio::test] - async fn tool_arguments_are_not_traced_without_content_capture() { - for capture_setting in [None, Some("false")] { - let fields = capture_tool_dispatch_fields(capture_setting).await; - let recorded = serde_json::to_string(&fields).unwrap(); - - assert!(!recorded.contains("tool-input-super-secret-token")); - assert!(!fields.contains_key("input")); - assert!(!fields.contains_key("gen_ai.tool.call.arguments")); - assert_eq!(fields["gen_ai.operation.name"], "execute_tool"); - assert_eq!(fields["gen_ai.tool.call.id"], "call-secret"); - } - } - - #[tokio::test] - async fn tool_dispatch_records_gen_ai_span_attributes() { - use goose_test_support::otel::clear_otel_env; - use rmcp::object; - - let _env = clear_otel_env(&[(gen_ai_telemetry::CAPTURE_MESSAGE_CONTENT_ENV, "true")]); - let capture = SpanFieldCapture::new("dispatch_tool_call"); - let _subscriber = capture.clone().set_default(); - let (agent, session, _data_dir) = tracing_test_agent_and_session().await; - let tool_name = - crate::agents::platform_extensions::scheduler::MANAGE_SCHEDULE_TOOL_NAME_COMPLETE; - let tool_call = - CallToolRequestParams::new(tool_name).with_arguments(object!({ "action": "list" })); - - let (request_id, result) = agent - .dispatch_tool_call( - tool_call, - "call-42".to_string(), - Some(CancellationToken::new()), - &session, - ) - .await; - assert_eq!(request_id, "call-42"); - let result = result.unwrap(); - assert!(result.result.await.is_err()); - - let fields = capture.fields(); - assert_eq!(fields["gen_ai.operation.name"], "execute_tool"); - assert_eq!(fields["gen_ai.tool.name"], tool_name); - assert_eq!(fields["gen_ai.tool.call.id"], "call-42"); - assert_eq!(fields["gen_ai.conversation.id"], session.id); - let input: Value = serde_json::from_str(fields["input"].as_str().unwrap()).unwrap(); - assert_eq!(input["arguments"]["action"], "list"); - let arguments: Value = - serde_json::from_str(fields["gen_ai.tool.call.arguments"].as_str().unwrap()).unwrap(); - assert_eq!(arguments["action"], "list"); - let output: Value = serde_json::from_str(fields["output"].as_str().unwrap()).unwrap(); - assert_eq!(output["status"], "error"); - assert!(!fields.contains_key("gen_ai.tool.call.result")); - } - - #[tokio::test] - async fn successful_tool_result_is_recorded_after_execution() { - use goose_test_support::otel::clear_otel_env; - use rmcp::model::ContentBlock; - - let _env = clear_otel_env(&[(gen_ai_telemetry::CAPTURE_MESSAGE_CONTENT_ENV, "true")]); - let capture = SpanFieldCapture::new("successful_tool"); - let _subscriber = capture.clone().set_default(); - let (agent, session, _data_dir) = tracing_test_agent_and_session().await; - let tool_call = CallToolRequestParams::new("test_tool"); - let span = tracing::info_span!( - "successful_tool", - output = tracing::field::Empty, - gen_ai.tool.call.result = tracing::field::Empty, - ); - let entered = span.enter(); - let result = agent.with_post_tool_hook( - ToolCallResult::from(Ok(CallToolResult::success(vec![ContentBlock::text( - "done", - )]))), - &tool_call, - &session, - "call-post-hook", - ); - drop(entered); - drop(span); - - assert!(result.result.await.is_ok()); - let fields = capture.fields(); - let result: Value = - serde_json::from_str(fields["gen_ai.tool.call.result"].as_str().unwrap()).unwrap(); - assert_eq!(result["content"][0]["text"], "done"); - let output: Value = serde_json::from_str(fields["output"].as_str().unwrap()).unwrap(); - assert_eq!(output["status"], "success"); - } - - #[test] - fn ensure_message_event_id_assigns_missing_ids_and_preserves_existing_ids() { - let generated = - ensure_message_event_id(AgentEvent::Message(Message::assistant().with_text("hello"))); - let AgentEvent::Message(generated_message) = generated else { - panic!("expected message event"); - }; - let generated_id = generated_message - .id - .as_deref() - .expect("generated message id"); - assert!(generated_id.starts_with("msg_")); - - let preserved = ensure_message_event_id(AgentEvent::Message( - Message::assistant() - .with_id("provider-message-id") - .with_text("hello"), - )); - let AgentEvent::Message(preserved_message) = preserved else { - panic!("expected message event"); - }; - assert_eq!(preserved_message.id.as_deref(), Some("provider-message-id")); - - let non_message = - ensure_message_event_id(AgentEvent::HistoryReplaced(Conversation::empty())); - assert!(matches!(non_message, AgentEvent::HistoryReplaced(_))); - } - #[test] fn resolve_use_login_shell_path_defaults_by_platform() { assert!(resolve_use_login_shell_path( @@ -4663,28 +1939,6 @@ mod tests { )); } - #[test] - fn user_event_projection_preserves_hidden_tool_response_wrapper() { - use rmcp::model::{Annotations, ContentBlock, Role, TextContent}; - - let hidden_only = Message::user().with_tool_response( - "tool-1", - Ok(CallToolResult::success(vec![ContentBlock::Text( - TextContent::new("provider-only") - .with_annotations(Annotations::default().with_audience(vec![Role::Assistant])), - )])), - ); - - let projected = project_message_for_user_event(&hidden_only); - let result = projected.content[0] - .as_tool_response() - .expect("hidden tool response wrapper") - .tool_result - .as_ref() - .expect("successful hidden tool result"); - assert!(result.content.is_empty()); - } - #[test] fn agent_visible_message_text_excludes_user_only_blocks() { use rmcp::model::{Annotations, Role, TextContent}; @@ -4762,7 +2016,6 @@ mod tests { .await .unwrap(); - // Known request_id → provider handles it, confirmation_router NOT called agent .submit_tool_confirmation( &session.id, @@ -4773,42 +2026,16 @@ mod tests { .unwrap(); assert_eq!(provider.handled.lock().await.len(), 1); - // Unknown request_id → provider returns false, falls through to confirmation_router - // Register first so deliver() has somewhere to send - let rx = agent - .tool_confirmation_router - .register(session.id.clone(), "unknown".to_string()) - .await; - agent + let error = agent .submit_tool_confirmation( &session.id, "unknown", crate::permission::Permission::DenyOnce, ) .await - .unwrap(); + .unwrap_err(); + assert!(error.to_string().contains("unknown or stale")); assert_eq!(provider.handled.lock().await.len(), 2); - // Verify the fallthrough went to confirmation_router - let conf = rx.await.unwrap(); - assert_eq!(conf.permission, crate::permission::Permission::DenyOnce); - } - - #[tokio::test] - async fn test_submit_tool_confirmation_routes_to_legacy() { - let (agent, session, _data_dir) = tracing_test_agent_and_session().await; - // No provider set → Noop routing, goes straight to confirmation_router - // Register first so deliver() has somewhere to send - let rx = agent - .tool_confirmation_router - .register(session.id.clone(), "any".to_string()) - .await; - agent - .submit_tool_confirmation(&session.id, "any", crate::permission::Permission::AllowOnce) - .await - .unwrap(); - - let conf = rx.await.unwrap(); - assert_eq!(conf.permission, crate::permission::Permission::AllowOnce); } enum EffortOutcome { @@ -5340,48 +2567,6 @@ echo start >> "$PLUGIN_ROOT/hook.log" } } - struct VisibilityTextProvider; - - #[async_trait::async_trait] - impl crate::providers::base::Provider for VisibilityTextProvider { - async fn stream( - &self, - _model_config: &goose_providers::model::ModelConfig, - _system_prompt: &str, - _messages: &[Message], - _tools: &[Tool], - ) -> Result { - let usage = ProviderUsage::new("mock-model".to_string(), Usage::default()); - let mixed_audience = Message::assistant() - .with_content(MessageContent::Text( - TextContent::new("assistant-only block ").with_annotations( - Annotations::default().with_audience(vec![Role::Assistant]), - ), - )) - .with_content(MessageContent::Text( - TextContent::new("visible last") - .with_annotations(Annotations::default().with_audience(vec![Role::User])), - )); - - Ok(Box::pin(futures::stream::iter(vec![ - Ok((Some(Message::assistant().with_text("visible first ")), None)), - Ok(( - Some( - Message::assistant() - .with_text("internal message ") - .agent_only(), - ), - None, - )), - Ok((Some(mixed_audience), Some(usage))), - ]))) - } - - fn get_name(&self) -> &str { - "visibility-text" - } - } - struct OutputLimitMarkerProvider { include_content: bool, call_count: AtomicUsize, @@ -5472,30 +2657,22 @@ echo start >> "$PLUGIN_ROOT/hook.log" id: session_id, schedule_id: None, max_turns: Some(10), - retry_config: Some(crate::agents::types::RetryConfig { - max_retries: 3, - checks: vec![crate::agents::types::SuccessCheck::Shell { - command: "false".to_string(), - }], - on_failure: None, - timeout_seconds: None, - on_failure_timeout_seconds: None, - }), }; let reply_stream = agent - .reply( - Message::user().with_text("hi"), - session_config, - crate::agents::state_machine::enabled(), - None, - ) + .reply(Message::user().with_text("hi"), session_config, None) .await?; tokio::pin!(reply_stream); let mut emitted_refusal_id = None; while let Some(event) = reply_stream.next().await { if let AgentEvent::Message(message) = event? { - if message.as_concat_text().contains("provider refused") { + if message.content.iter().any(|content| { + content.as_error().is_some_and(|error| { + error + .message + .contains("Please start a new session to continue") + }) + }) { emitted_refusal_id = message.id; } } @@ -5523,7 +2700,6 @@ echo start >> "$PLUGIN_ROOT/hook.log" session_manager.clone(), permission_manager, None, - GooseMode::Auto, true, GoosePlatform::GooseCli, ); @@ -5547,119 +2723,6 @@ echo start >> "$PLUGIN_ROOT/hook.log" Ok((agent, session.id)) } - struct TraceContentProvider; - - #[async_trait::async_trait] - impl crate::providers::base::Provider for TraceContentProvider { - async fn stream( - &self, - _model_config: &goose_providers::model::ModelConfig, - _system_prompt: &str, - _messages: &[Message], - _tools: &[Tool], - ) -> Result { - let message = Message::assistant().with_text("output-super-secret-token"); - let usage = ProviderUsage::new("mock-model".to_string(), Usage::default()); - Ok(stream_from_single_message(message, usage)) - } - - fn get_name(&self) -> &str { - "trace-content" - } - } - - async fn capture_legacy_reply_fields( - span_name: &'static str, - capture_setting: Option<&'static str>, - ) -> Result> { - use goose_test_support::otel::clear_otel_env; - - let mut overrides = vec![("GOOSE_STATE_MACHINE", "0")]; - if let Some(value) = capture_setting { - overrides.push((gen_ai_telemetry::CAPTURE_MESSAGE_CONTENT_ENV, value)); - } - let _env = clear_otel_env(&overrides); - let capture = SpanFieldCapture::new(span_name); - let _subscriber = capture.clone().set_default(); - let temp_dir = tempfile::tempdir()?; - let hook_manager = crate::hooks::HookManager::from_plugins_for_test(vec![]); - let (agent, session_id) = create_test_agent( - temp_dir.path().join("data"), - hook_manager, - Arc::new(TraceContentProvider), - ) - .await?; - let session_config = SessionConfig { - id: session_id, - schedule_id: None, - max_turns: Some(1), - retry_config: None, - }; - let reply_stream = agent - .reply( - Message::user().with_text("input-super-secret-token"), - session_config, - false, - None, - ) - .await?; - tokio::pin!(reply_stream); - while let Some(event) = reply_stream.next().await { - event?; - } - - Ok(capture.fields()) - } - - #[tokio::test] - async fn legacy_reply_trace_omits_content_without_capture() -> Result<()> { - for capture_setting in [None, Some("false")] { - let reply_fields = capture_legacy_reply_fields("reply", capture_setting).await?; - let reply_json = serde_json::to_string(&reply_fields)?; - assert!(!reply_json.contains("super-secret-token")); - assert!(!reply_fields.contains_key("user_message")); - assert!(!reply_fields.contains_key("trace_input")); - assert!(!reply_fields.contains_key("gen_ai.input.messages")); - assert!(!reply_fields.contains_key("gen_ai.output.messages")); - - let stream_fields = - capture_legacy_reply_fields("reply_stream", capture_setting).await?; - let stream_json = serde_json::to_string(&stream_fields)?; - assert!(!stream_json.contains("super-secret-token")); - assert!(!stream_fields.contains_key("trace_output")); - assert!(!stream_fields.contains_key("gen_ai.input.messages")); - assert!(!stream_fields.contains_key("gen_ai.output.messages")); - } - Ok(()) - } - - #[tokio::test] - async fn legacy_reply_trace_retains_content_with_capture() -> Result<()> { - let reply_fields = capture_legacy_reply_fields("reply", Some("true")).await?; - assert_eq!(reply_fields["user_message"], "input-super-secret-token"); - assert_eq!(reply_fields["trace_input"], "input-super-secret-token"); - assert!(reply_fields["gen_ai.input.messages"] - .as_str() - .unwrap() - .contains("input-super-secret-token")); - assert!(reply_fields["gen_ai.output.messages"] - .as_str() - .unwrap() - .contains("output-super-secret-token")); - - let stream_fields = capture_legacy_reply_fields("reply_stream", Some("true")).await?; - assert_eq!(stream_fields["trace_output"], "output-super-secret-token"); - assert!(stream_fields["gen_ai.input.messages"] - .as_str() - .unwrap() - .contains("input-super-secret-token")); - assert!(stream_fields["gen_ai.output.messages"] - .as_str() - .unwrap() - .contains("output-super-secret-token")); - Ok(()) - } - async fn create_stop_hook_test_agent( env: &StopHookTestEnv, stop_hook_block_cap: u32, @@ -5680,15 +2743,9 @@ echo start >> "$PLUGIN_ROOT/hook.log" id: session_id.to_string(), schedule_id: None, max_turns: Some(10), - retry_config: None, }; let reply_stream = agent - .reply( - Message::user().with_text(text), - session_config, - crate::agents::state_machine::enabled(), - None, - ) + .reply(Message::user().with_text(text), session_config, None) .await?; tokio::pin!(reply_stream); @@ -5800,89 +2857,6 @@ echo start >> "$PLUGIN_ROOT/hook.log" Ok(()) } - #[tokio::test] - async fn skipped_user_message_does_not_enter_empty_response_retry_loop() -> Result<()> { - use rmcp::model::{Annotations, Role, TextContent}; - - let env = SessionStartHookTestEnv::new()?; - let provider = Arc::new(CountingTextProvider::new()); - let hook_manager = env.hook_manager(); - let (agent, session_id) = - create_test_agent(env.data_dir(), hook_manager, provider.clone()).await?; - let session_config = SessionConfig { - id: session_id.clone(), - schedule_id: None, - max_turns: Some(10), - retry_config: None, - }; - let user_only_content = MessageContent::Text( - TextContent::new("user-only") - .with_annotations(Annotations::default().with_audience(vec![Role::User])), - ); - - let mut stream = agent - .reply( - Message::user().with_content(user_only_content), - session_config, - crate::agents::state_machine::enabled(), - None, - ) - .await?; - - assert!(stream.next().await.is_none()); - assert_eq!(provider.call_count.load(Ordering::SeqCst), 0); - assert_eq!(env.hook_invocations(), 0); - let session = agent - .config - .session_manager - .get_session(&session_id, true) - .await?; - let conversation = session.conversation.unwrap(); - assert_eq!(conversation.messages().len(), 1); - assert!(!conversation.messages()[0].is_agent_visible()); - - let visible_session_config = SessionConfig { - id: session_id.clone(), - schedule_id: None, - max_turns: Some(10), - retry_config: None, - }; - let mut visible_stream = agent - .reply( - Message::user().with_text("agent-visible"), - visible_session_config, - crate::agents::state_machine::enabled(), - None, - ) - .await?; - while let Some(event) = visible_stream.next().await { - event?; - } - assert_eq!(provider.call_count.load(Ordering::SeqCst), 1); - assert_eq!(env.hook_invocations(), 1); - - let final_session_config = SessionConfig { - id: session_id, - schedule_id: None, - max_turns: Some(10), - retry_config: None, - }; - let mut final_stream = agent - .reply( - Message::user().with_text("second-agent-visible"), - final_session_config, - crate::agents::state_machine::enabled(), - None, - ) - .await?; - while let Some(event) = final_stream.next().await { - event?; - } - assert_eq!(provider.call_count.load(Ordering::SeqCst), 2); - assert_eq!(env.hook_invocations(), 1); - Ok(()) - } - #[tokio::test] async fn stop_hook_block_cap_allows_configured_consecutive_blocks_then_overrides() -> Result<()> { @@ -6005,26 +2979,6 @@ echo start >> "$PLUGIN_ROOT/hook.log" Ok(()) } - #[tokio::test] - async fn stop_hook_payload_excludes_non_user_visible_assistant_content() -> Result<()> { - let env = StopHookTestEnv::new(RECORD_PAYLOAD_SCRIPT)?; - let provider = Arc::new(VisibilityTextProvider); - let (agent, session_id) = - create_test_agent(env.data_dir(), env.hook_manager(), provider).await?; - - run_stop_hook_test_turn(&agent, &session_id, "hello").await?; - - let payload = env.stop_payload()?; - assert_eq!( - payload - .get("last_assistant_message") - .and_then(Value::as_str), - Some("visible first visible last") - ); - - Ok(()) - } - #[tokio::test] async fn test_tool_inspection_manager_has_all_inspectors() -> Result<()> { let agent = Agent::new(); @@ -6051,519 +3005,4 @@ echo start >> "$PLUGIN_ROOT/hook.log" Ok(()) } - - #[tokio::test] - async fn discard_pending_steers_clears_queued_messages() { - let agent = Agent::new(); - let session_id = "session-discard"; - - agent - .steer(session_id, Message::user().with_text("queued steer")) - .await; - assert!(agent.has_pending_steers(session_id).await); - - agent.discard_pending_steers(session_id).await; - - assert!( - !agent.has_pending_steers(session_id).await, - "discarding must drop steers orphaned by a cancelled run so they cannot leak into a later prompt" - ); - assert!(agent.drain_pending_steers(session_id).await.is_empty()); - } - - #[test] - fn categorize_tool_recognizes_conventional_names() { - assert_eq!(categorize_tool("developer__shell"), ToolCategory::Shell); - assert_eq!(categorize_tool("filesystem__write"), ToolCategory::Write); - assert_eq!(categorize_tool("filesystem__edit"), ToolCategory::Write); - assert_eq!(categorize_tool("filesystem__read"), ToolCategory::Read); - assert_eq!(categorize_tool("filesystem__view"), ToolCategory::Read); - assert_eq!(categorize_tool("filesystem__cat"), ToolCategory::Read); - assert_eq!(categorize_tool("scheduler__list"), ToolCategory::Other); - assert_eq!(categorize_tool("shell"), ToolCategory::Shell); - } - - #[test] - fn extract_string_arg_picks_first_present_key() { - let input = serde_json::json!({ "file_path": "/tmp/a.txt", "path": "/tmp/b.txt" }); - assert_eq!( - extract_string_arg(&input, &["path", "file", "file_path"]).as_deref(), - Some("/tmp/b.txt") - ); - let input = serde_json::json!({ "file_path": "/tmp/a.txt" }); - assert_eq!( - extract_string_arg(&input, &["path", "file", "file_path"]).as_deref(), - Some("/tmp/a.txt") - ); - let input = serde_json::json!({ "other": 1 }); - assert!(extract_string_arg(&input, &["path"]).is_none()); - let input = serde_json::json!({ "path": "" }); - assert!(extract_string_arg(&input, &["path"]).is_none()); - } - - #[test] - fn attach_turn_usage_targets_last_assistant_message() { - let usage = ProviderUsage::new( - "test-model".to_string(), - Usage::new(Some(1200), Some(340), None), - ); - let mut conversation = Conversation::new_unvalidated([ - Message::user().with_text("hi"), - Message::assistant().with_id("a1").with_text("first"), - Message::user().with_text("again"), - Message::assistant().with_id("a2").with_text("second"), - ]); - - let (message_id, attached) = - attach_turn_usage(&mut conversation, &usage, None).expect("usage should attach"); - - assert_eq!(message_id.as_deref(), Some("a2")); - assert_eq!(attached.input_tokens, Some(1200)); - assert_eq!(attached.output_tokens, Some(340)); - assert!(!attached.is_compaction, "turn usage is not a compaction"); - - let messages = conversation.messages(); - let stored = messages[3] - .metadata - .usage - .as_deref() - .expect("usage must be stored on the last assistant message"); - assert_eq!(*stored, attached); - assert!( - messages[1].metadata.usage.is_none(), - "earlier assistant message must not receive the usage" - ); - } - - #[test] - fn attach_turn_usage_returns_none_without_assistant_message() { - let usage = ProviderUsage::new("test-model".to_string(), Usage::default()); - let mut conversation = Conversation::new_unvalidated([Message::user().with_text("hi")]); - - assert!(attach_turn_usage(&mut conversation, &usage, None).is_none()); - assert!( - conversation.messages()[0].metadata.usage.is_none(), - "user message must stay untouched" - ); - } - - #[test] - fn attach_turn_usage_suppresses_notification_for_assistant_only_message() { - use rmcp::model::{Annotations, Role, TextContent}; - - let usage = ProviderUsage::new( - "test-model".to_string(), - Usage::new(Some(1200), Some(340), None), - ); - let assistant_only = TextContent::new("provider-only state") - .with_annotations(Annotations::default().with_audience(vec![Role::Assistant])); - let mut conversation = Conversation::new_unvalidated([ - Message::user().with_text("hi"), - Message::assistant() - .with_id("hidden") - .with_content(MessageContent::Text(assistant_only)), - ]); - - assert!(attach_turn_usage(&mut conversation, &usage, None).is_none()); - - let stored = conversation.messages()[1] - .metadata - .usage - .as_deref() - .expect("usage must remain stored on the hidden assistant message"); - assert_eq!(stored.input_tokens, Some(1200)); - assert_eq!(stored.output_tokens, Some(340)); - } - - /// Plugin fixture that can register several events at once, each with its - /// own matcher and script, and read back the JSON payloads a script recorded. - struct RecordingHookEnv { - _temp_dir: TempDir, - plugin_dir: PathBuf, - } - - /// (event name, matcher or "" for none, script file name, script body) - type HookSpec<'a> = (&'a str, &'a str, &'a str, &'a str); - - impl RecordingHookEnv { - fn new(specs: &[HookSpec<'_>]) -> Self { - Self::with_on_failure(specs, "") - } - - fn blocking_on_failure(specs: &[HookSpec<'_>]) -> Self { - Self::with_on_failure(specs, r#", "on_failure": "block""#) - } - - fn with_on_failure(specs: &[HookSpec<'_>], on_failure: &str) -> Self { - let temp_dir = tempfile::tempdir().unwrap(); - let plugin_dir = temp_dir.path().join("test-plugin"); - std::fs::create_dir_all(plugin_dir.join("hooks")).unwrap(); - let entries: Vec = specs - .iter() - .map(|(event, matcher, script, _)| { - let matcher = if matcher.is_empty() { - String::new() - } else { - format!(r#""matcher": "{matcher}", "#) - }; - format!( - r#""{event}": [{{{matcher}"hooks": [{{"type": "command", "command": "sh ${{PLUGIN_ROOT}}/{script}"{on_failure}}}]}}]"# - ) - }) - .collect(); - std::fs::write( - plugin_dir.join("hooks/hooks.json"), - format!(r#"{{"hooks": {{{}}}}}"#, entries.join(", ")), - ) - .unwrap(); - for (_, _, script, script_body) in specs { - std::fs::write(plugin_dir.join(script), script_body).unwrap(); - } - Self { - _temp_dir: temp_dir, - plugin_dir, - } - } - - fn hook_manager(&self) -> crate::hooks::HookManager { - crate::hooks::HookManager::from_plugins_for_test(vec![DiscoveredPlugin { - name: "test-plugin".into(), - root: self.plugin_dir.clone(), - scope: PluginScope::Project, - }]) - } - - fn payloads(&self, log: &str) -> Vec { - std::fs::read_to_string(self.plugin_dir.join(log)) - .unwrap_or_default() - .lines() - .filter(|line| !line.trim().is_empty()) - .map(|line| serde_json::from_str(line).unwrap()) - .collect() - } - } - - const RECORD_PRE_SCRIPT: &str = "#!/bin/sh\ncat >> \"$PLUGIN_ROOT/pre.log\"\nprintf '\\n' >> \"$PLUGIN_ROOT/pre.log\"\nexit 0\n"; - const RECORD_RESULT_SCRIPT: &str = "#!/bin/sh\ncat >> \"$PLUGIN_ROOT/result.log\"\nprintf '\\n' >> \"$PLUGIN_ROOT/result.log\"\nexit 0\n"; - const RECORD_POST_SCRIPT: &str = "#!/bin/sh\ncat >> \"$PLUGIN_ROOT/post.log\"\nprintf '\\n' >> \"$PLUGIN_ROOT/post.log\"\nexit 0\n"; - const RECORD_POST_FAILURE_SCRIPT: &str = "#!/bin/sh\ncat >> \"$PLUGIN_ROOT/postfail.log\"\nprintf '\\n' >> \"$PLUGIN_ROOT/postfail.log\"\nexit 0\n"; - const DENY_AND_RECORD_SCRIPT: &str = "#!/bin/sh\ncat >> \"$PLUGIN_ROOT/pre.log\"\nprintf '\\n' >> \"$PLUGIN_ROOT/pre.log\"\necho \"blocked by test policy\" >&2\nexit 2\n"; - /// Logs its stdin like the others, writes nothing to stdout, and exits - /// non-zero. That is a hook that ran but never returned a decision. - const ABNORMAL_EXIT_AND_RECORD_SCRIPT: &str = - "#!/bin/sh\ncat >> \"$PLUGIN_ROOT/pre.log\"\nprintf '\\n' >> \"$PLUGIN_ROOT/pre.log\"\necho boom >&2\nexit 3\n"; - const HOOK_FAILURE_REFUSAL: &str = - "Tool call blocked because policy hook `test-plugin` could not complete: \ - the hook exited with status 3 and no usable decision. \ - That hook is configured to block on failure."; - - async fn agent_with_hooks( - hook_manager: crate::hooks::HookManager, - ) -> (Agent, Session, TempDir) { - let data_dir = TempDir::new().unwrap(); - let data_path = data_dir.path().to_path_buf(); - let session_manager = Arc::new(SessionManager::new(data_path.clone())); - let mut agent = Agent::with_config(AgentConfig::new( - Arc::clone(&session_manager), - Arc::new(PermissionManager::new(data_path)), - None, - GooseMode::default(), - false, - GoosePlatform::GooseCli, - )); - agent.set_hook_manager_for_test(hook_manager); - let session = session_manager - .create_session( - std::env::current_dir().unwrap(), - "pre-tool-use-result".to_string(), - SessionType::Hidden, - GooseMode::default(), - ) - .await - .unwrap(); - (agent, session, data_dir) - } - - fn shell_call() -> CallToolRequestParams { - use rmcp::object; - CallToolRequestParams::new("developer__shell") - .with_arguments(object!({ "command": "echo hi" })) - } - - /// deny-invisible: the tool never dispatches, neither post event fires, and a - /// PreToolUseResult subscriber still sees the denial with blocked_by and reason. - #[tokio::test] - async fn pre_tool_use_result_observes_denial_that_post_hooks_never_see() { - let env = RecordingHookEnv::new(&[ - ("PreToolUse", "", "pre.sh", DENY_AND_RECORD_SCRIPT), - ("PreToolUseResult", "", "result.sh", RECORD_RESULT_SCRIPT), - ("PostToolUse", "", "post.sh", RECORD_POST_SCRIPT), - ( - "PostToolUseFailure", - "", - "postfail.sh", - RECORD_POST_FAILURE_SCRIPT, - ), - ]); - let (agent, session, _data_dir) = agent_with_hooks(env.hook_manager()).await; - - let (request_id, result) = agent - .dispatch_tool_call(shell_call(), "call-deny-1".to_string(), None, &session) - .await; - - assert_eq!(request_id, "call-deny-1"); - let Err(error) = result else { - panic!("a denied call must not dispatch"); - }; - assert!(error.message.contains("denied by policy hook")); - - assert!( - env.payloads("post.log").is_empty(), - "PostToolUse must not fire for a denied call" - ); - assert!( - env.payloads("postfail.log").is_empty(), - "PostToolUseFailure must not fire for a denied call" - ); - - let results = env.payloads("result.log"); - assert_eq!(results.len(), 1); - assert_eq!(results[0]["event"], "PreToolUseResult"); - assert_eq!(results[0]["decision"], "deny"); - assert_eq!(results[0]["policy_evaluated"], true); - assert_eq!(results[0]["blocked_by"], "test-plugin"); - assert_eq!(results[0]["reason"], "blocked by test policy"); - assert_eq!(results[0]["tool_call_id"], "call-deny-1"); - } - - /// repeated identical calls: two calls with the same name and input in one - /// session correlate to their outcomes by tool_call_id, not by name plus input. - #[tokio::test] - async fn repeated_identical_calls_correlate_by_tool_call_id() { - let env = RecordingHookEnv::new(&[ - ("PreToolUse", "", "pre.sh", RECORD_PRE_SCRIPT), - ("PreToolUseResult", "", "result.sh", RECORD_RESULT_SCRIPT), - ("PostToolUse", "", "post.sh", RECORD_POST_SCRIPT), - ( - "PostToolUseFailure", - "", - "postfail.sh", - RECORD_POST_FAILURE_SCRIPT, - ), - ]); - let (agent, session, _data_dir) = agent_with_hooks(env.hook_manager()).await; - - for id in ["call-1", "call-2"] { - let (_, result) = agent - .dispatch_tool_call(shell_call(), id.to_string(), None, &session) - .await; - let Ok(handle) = result else { - panic!("dispatch must return a result handle"); - }; - let _ = handle.result.await; - } - - let pres = env.payloads("pre.log"); - let results = env.payloads("result.log"); - let outcomes = env.payloads("postfail.log"); - assert_eq!(pres.len(), 2); - assert_eq!(results.len(), 2); - assert_eq!(outcomes.len(), 2); - - for payloads in [&pres, &results, &outcomes] { - assert_eq!(payloads[0]["tool_name"], payloads[1]["tool_name"]); - assert_eq!(payloads[0]["tool_input"], payloads[1]["tool_input"]); - } - - let ids: Vec<&str> = results - .iter() - .map(|payload| payload["tool_call_id"].as_str().unwrap()) - .collect(); - assert_eq!(ids, vec!["call-1", "call-2"]); - assert_ne!( - ids[0], ids[1], - "identical name and input must still carry distinct ids" - ); - - for (index, id) in ids.iter().enumerate() { - assert_eq!( - pres[index]["tool_call_id"], results[index]["tool_call_id"], - "PreToolUse and PreToolUseResult must carry one id per call" - ); - assert_eq!( - outcomes - .iter() - .filter(|payload| payload["tool_call_id"] == *id) - .count(), - 1, - "each call must pair with exactly one outcome by id" - ); - } - } - - /// no matching hook: a PreToolUse rule is registered but its matcher does not - /// match, so nothing runs and the event reports allow with policy_evaluated false. - #[tokio::test] - async fn pre_tool_use_result_reports_allow_and_unevaluated_when_no_hook_matches() { - let env = RecordingHookEnv::new(&[ - ( - "PreToolUse", - "a_tool_name_that_never_matches", - "pre.sh", - DENY_AND_RECORD_SCRIPT, - ), - ("PreToolUseResult", "", "result.sh", RECORD_RESULT_SCRIPT), - ]); - let (agent, session, _data_dir) = agent_with_hooks(env.hook_manager()).await; - - let (_, result) = agent - .dispatch_tool_call(shell_call(), "call-allow-1".to_string(), None, &session) - .await; - let Ok(handle) = result else { - panic!("dispatch must return a result handle"); - }; - let _ = handle.result.await; - - assert!( - env.payloads("pre.log").is_empty(), - "the non-matching rule must not run" - ); - let results = env.payloads("result.log"); - assert_eq!(results.len(), 1); - assert_eq!(results[0]["decision"], "allow"); - assert_eq!(results[0]["policy_evaluated"], false); - assert!(results[0].get("blocked_by").is_none()); - assert!(results[0].get("reason").is_none()); - assert_eq!(results[0]["tool_call_id"], "call-allow-1"); - } - - /// sole abnormal hook: the only matching PreToolUse hook runs, writes nothing - /// to stdout and exits non-zero, so it never returned a decision. Execution - /// stays fail-open and the event reports allow with policy_evaluated false. - #[tokio::test] - async fn pre_tool_use_result_reports_unevaluated_when_the_only_hook_exits_without_a_decision() { - let env = RecordingHookEnv::new(&[ - ("PreToolUse", "", "pre.sh", ABNORMAL_EXIT_AND_RECORD_SCRIPT), - ("PreToolUseResult", "", "result.sh", RECORD_RESULT_SCRIPT), - ]); - let (agent, session, _data_dir) = agent_with_hooks(env.hook_manager()).await; - - let (_, result) = agent - .dispatch_tool_call(shell_call(), "call-abnormal-1".to_string(), None, &session) - .await; - let Ok(handle) = result else { - panic!("dispatch must stay fail-open and return a result handle"); - }; - let _ = handle.result.await; - - assert_eq!( - env.payloads("pre.log").len(), - 1, - "the matching hook must still run", - ); - let results = env.payloads("result.log"); - assert_eq!(results.len(), 1); - assert_eq!(results[0]["decision"], "allow"); - assert_eq!(results[0]["policy_evaluated"], false); - assert_eq!(results[0]["tool_call_id"], "call-abnormal-1"); - } - - /// inactive final output: the tool is not installed, so nothing executes. The - /// outer error stays the one this method has always returned, and the failure - /// is still observed exactly once, carrying the request id. - #[tokio::test] - async fn inactive_final_output_keeps_the_outer_error_and_emits_one_failure_event() { - use rmcp::object; - - let env = RecordingHookEnv::new(&[ - ("PreToolUseResult", "", "result.sh", RECORD_RESULT_SCRIPT), - ("PostToolUse", "", "post.sh", RECORD_POST_SCRIPT), - ( - "PostToolUseFailure", - "", - "postfail.sh", - RECORD_POST_FAILURE_SCRIPT, - ), - ]); - // agent_with_hooks creates a session without a recipe, so the tool is - // inactive here without any extra setup. - let (agent, session, _data_dir) = agent_with_hooks(env.hook_manager()).await; - - let call = CallToolRequestParams::new(FINAL_OUTPUT_TOOL_NAME) - .with_arguments(object!({ "answer": "unused" })); - let (_, result) = agent - .dispatch_tool_call(call, "call-inactive-1".to_string(), None, &session) - .await; - - let Err(error) = result else { - panic!("an inactive final-output tool must report the outer error"); - }; - assert_eq!(error.message, "Final output tool not defined"); - assert_eq!(error.code, ErrorCode::INTERNAL_ERROR); - - let failures = env.payloads("postfail.log"); - assert_eq!( - failures.len(), - 1, - "the failure must be observed exactly once", - ); - assert_eq!(failures[0]["tool_call_id"], "call-inactive-1"); - assert_eq!(failures[0]["tool_name"], FINAL_OUTPUT_TOOL_NAME); - assert!( - env.payloads("post.log").is_empty(), - "PostToolUse must not fire for a tool that never ran", - ); - } - - #[tokio::test] - async fn pre_tool_use_hook_failure_allows_by_default() { - let env = RecordingHookEnv::new(&[ - ("PreToolUse", "", "pre.sh", ABNORMAL_EXIT_AND_RECORD_SCRIPT), - ("PreToolUseResult", "", "result.sh", RECORD_RESULT_SCRIPT), - ]); - let (agent, session, _data_dir) = agent_with_hooks(env.hook_manager()).await; - - let (_, result) = agent - .dispatch_tool_call(shell_call(), "call-open-1".to_string(), None, &session) - .await; - assert!(result.is_ok(), "a broken hook must not block the call"); - - assert_eq!(env.payloads("pre.log").len(), 1); - let results = env.payloads("result.log"); - assert_eq!(results.len(), 1); - assert_eq!(results[0]["decision"], "allow"); - assert_eq!(results[0]["cause"], "hook_failure"); - assert_eq!(results[0]["policy_evaluated"], false); - } - - #[tokio::test] - async fn pre_tool_use_hook_failure_blocks_when_configured() { - let env = RecordingHookEnv::blocking_on_failure(&[ - ("PreToolUse", "", "pre.sh", ABNORMAL_EXIT_AND_RECORD_SCRIPT), - ("PreToolUseResult", "", "result.sh", RECORD_RESULT_SCRIPT), - ("PostToolUse", "", "post.sh", RECORD_POST_SCRIPT), - ]); - let (agent, session, _data_dir) = agent_with_hooks(env.hook_manager()).await; - - let (_, result) = agent - .dispatch_tool_call(shell_call(), "call-closed-1".to_string(), None, &session) - .await; - - let Err(error) = result else { - panic!("a fail-closed hook failure must not dispatch"); - }; - assert_eq!(error.message, HOOK_FAILURE_REFUSAL); - assert!( - env.payloads("post.log").is_empty(), - "PostToolUse must not fire for a blocked call" - ); - - let results = env.payloads("result.log"); - assert_eq!(results.len(), 1); - assert_eq!(results[0]["decision"], "deny"); - assert_eq!(results[0]["cause"], "hook_failure"); - assert_eq!(results[0]["policy_evaluated"], false); - assert_eq!(results[0]["blocked_by"], "test-plugin"); - assert_eq!(results[0]["tool_call_id"], "call-closed-1"); - } } diff --git a/crates/goose/src/agents/execute_commands.rs b/crates/goose/src/agents/execute_commands.rs index 7edd91faa..1d7dbcbef 100644 --- a/crates/goose/src/agents/execute_commands.rs +++ b/crates/goose/src/agents/execute_commands.rs @@ -1,15 +1,7 @@ -use std::collections::HashMap; use std::path::Path; -use anyhow::{anyhow, Result}; - -use crate::context_mgmt::compact_messages; -use crate::conversation::message::Message; -use crate::recipe::Recipe; -use crate::session::GoalState; use crate::slash_commands::{recipe_slash_command, skill_slash_command}; -use super::final_output_tool::FinalOutputTool; use super::Agent; pub fn slash_commands_enabled() -> bool { @@ -134,482 +126,11 @@ pub fn command_starts_turn(message_text: &str) -> bool { && !is_clear_goal_param(parsed.params_str) } -impl Agent { - pub async fn execute_command( - &self, - message_text: &str, - session_id: &str, - ) -> Result> { - let Some(parsed) = parse_slash_command(message_text) else { - return Ok(None); - }; - - let command = parsed.command; - let params_str = parsed.params_str; - - let params: Vec<&str> = if params_str.is_empty() { - vec![] - } else { - params_str.split_whitespace().collect() - }; - - match command { - "prompts" => self.handle_prompts_command(¶ms, session_id).await, - "prompt" => self.handle_prompt_command(¶ms, session_id).await, - "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" => { - 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, session_id).await, - "grind" => self.handle_grind_command(params_str, session_id).await, - _ => { - if let Some(message) = self - .handle_recipe_command(command, params_str, session_id) - .await? - { - #[cfg(feature = "telemetry")] - crate::posthog::emit_custom_slash_command_used(); - return Ok(Some(message)); - } - - self.handle_skill_command(command, params_str, session_id) - .await - } - } - } - - async fn handle_compact_command(&self, session_id: &str) -> Result> { - let provider = self.provider(session_id).await?; - if provider.manages_own_context() { - return Err(anyhow!(context_management_unsupported_message( - "compact", - provider.get_name() - ))); - } - - let manager = self.config.session_manager.clone(); - let session = manager.get_session(session_id, true).await?; - let conversation = session - .conversation - .ok_or_else(|| anyhow!("Session has no conversation"))?; - - let model_config = self.model_config_for_session(session_id).await?; - let compaction = compact_messages( - provider.as_ref(), - &model_config, - session_id, - &conversation, - true, // is_manual_compact - ) - .await?; - - manager - .replace_conversation(session_id, &compaction.conversation) - .await?; - - self.update_session_metrics( - session_id, - session.schedule_id, - &compaction.usage, - Some(compaction.retained_context_tokens), - ) - .await?; - - Ok(Some(user_only_assistant_text("Compaction complete"))) - } - - async fn handle_clear_command(&self, session_id: &str) -> Result> { - use crate::conversation::Conversation; - - let provider = self.provider(session_id).await?; - if provider.manages_own_context() { - return Err(anyhow!(context_management_unsupported_message( - "clear", - provider.get_name() - ))); - } - - let manager = self.config.session_manager.clone(); - manager - .replace_conversation(session_id, &Conversation::default()) - .await?; - - manager - .update(session_id) - .usage(goose_providers::conversation::token_usage::Usage::new( - Some(0), - Some(0), - Some(0), - )) - .apply() - .await?; - - Ok(Some(user_only_assistant_text("Conversation cleared"))) - } - - async fn handle_skills_command(&self, session_id: &str) -> Result> { - let working_dir = self - .config - .session_manager - .get_session(session_id, false) - .await - .ok() - .map(|s| s.working_dir); - let output = skill_slash_command::format_installed_skills(working_dir.as_deref()); - Ok(Some(Message::assistant().with_text(output))) - } - - async fn handle_status_command(&self, session_id: &str) -> Result> { - let provider = self.provider(session_id).await?; - let model_config = self.model_config_for_session(session_id).await?; - let context_limit = - crate::context_limit::get_context_limit(provider.as_ref(), &model_config.model_name) - .await?; - - let goose_mode = self.goose_mode().await; - - let metadata = self - .config - .session_manager - .get_session(session_id, false) - .await - .ok(); - - // `usage` is the current context-window usage (reset by /compact); - // `accumulated_usage` is the lifetime sum across all responses. The context - // percentage must use the former, or it inflates and pegs at 100% in any - // long or post-compaction session. - let context_tokens = metadata - .as_ref() - .and_then(|s| s.usage.total_tokens) - .unwrap_or(0) - .max(0) as usize; - let lifetime_tokens = metadata - .as_ref() - .and_then(|s| s.accumulated_usage.total_tokens) - .unwrap_or(0) - .max(0) as usize; - - let context_pct = if context_limit > 0 { - let pct = ((context_tokens as f64 / context_limit as f64) * 100.0).round() as usize; - format!("{}%", pct.min(100)) - } else { - "N/A".to_string() - }; - - let text = format!( - "**Session status**\n\n\ - - Model: {}\n\ - - Provider: {}\n\ - - Mode: {}\n\ - - Tokens (lifetime): {}\n\ - - Context: {} / {} tokens ({})", - model_config.model_name, - provider.get_name(), - goose_mode, - lifetime_tokens, - context_tokens, - context_limit, - context_pct, - ); - - Ok(Some(user_only_assistant_text(text))) - } - - async fn handle_prompts_command( - &self, - params: &[&str], - session_id: &str, - ) -> Result> { - let extension_filter = params.first().map(|s| s.to_string()); - - let prompts = self.list_extension_prompts(session_id).await; - - if let Some(filter) = &extension_filter { - if !prompts.contains_key(filter) { - let error_msg = format!("Extension '{}' not found", filter); - return Ok(Some(Message::assistant().with_text(error_msg))); - } - } - - let filtered_prompts: HashMap> = prompts - .into_iter() - .filter(|(ext, _)| extension_filter.as_ref().is_none_or(|f| f == ext)) - .map(|(extension, prompt_list)| { - let names = prompt_list.into_iter().map(|p| p.name).collect(); - (extension, names) - }) - .collect(); - - let mut output = String::new(); - if filtered_prompts.is_empty() { - output.push_str("No prompts available.\n"); - } else { - output.push_str("Available prompts:\n\n"); - for (extension, prompt_names) in filtered_prompts { - output.push_str(&format!("**{}**:\n", extension)); - for name in prompt_names { - output.push_str(&format!(" - {}\n", name)); - } - output.push('\n'); - } - } - - Ok(Some(Message::assistant().with_text(output))) - } - - async fn handle_prompt_command( - &self, - params: &[&str], - session_id: &str, - ) -> Result> { - if params.is_empty() { - return Ok(Some( - Message::assistant().with_text("Prompt name argument is required"), - )); - } - - let prompt_name = params[0].to_string(); - let is_info = params.get(1).map(|s| *s == "--info").unwrap_or(false); - - if is_info { - let prompts = self.list_extension_prompts(session_id).await; - let mut prompt_info = None; - - for (extension, prompt_list) in prompts { - if let Some(prompt) = prompt_list.iter().find(|p| p.name == prompt_name) { - let mut output = format!("**Prompt: {}**\n\n", prompt.name); - if let Some(desc) = &prompt.description { - output.push_str(&format!("Description: {}\n\n", desc)); - } - output.push_str(&format!("Extension: {}\n\n", extension)); - - if let Some(args) = &prompt.arguments { - output.push_str("Arguments:\n"); - for arg in args { - output.push_str(&format!(" - {}", arg.name)); - if let Some(desc) = &arg.description { - output.push_str(&format!(": {}", desc)); - } - output.push('\n'); - } - } - - prompt_info = Some(output); - break; - } - } - - return Ok(Some(Message::assistant().with_text( - prompt_info.unwrap_or_else(|| format!("Prompt '{}' not found", prompt_name)), - ))); - } - - let mut arguments = HashMap::new(); - for param in params.iter().skip(1) { - if let Some((key, value)) = param.split_once('=') { - let value = value.trim_matches('"'); - arguments.insert(key.to_string(), value.to_string()); - } - } - - let arguments_value = serde_json::to_value(arguments) - .map_err(|e| anyhow!("Failed to serialize arguments: {}", e))?; - - match self - .get_prompt(session_id, &prompt_name, arguments_value) - .await - { - Ok(prompt_result) => { - for (i, prompt_message) in prompt_result.messages.into_iter().enumerate() { - let msg = Message::from(prompt_message); - - let expected_role = if i % 2 == 0 { - rmcp::model::Role::User - } else { - rmcp::model::Role::Assistant - }; - - if msg.role != expected_role { - let error_msg = format!( - "Expected {:?} message at position {}, but found {:?}", - expected_role, i, msg.role - ); - return Ok(Some(Message::assistant().with_text(error_msg))); - } - - self.config - .session_manager - .clone() - .add_message(session_id, &msg) - .await?; - } - - let last_message = self - .config - .session_manager - .get_session(session_id, true) - .await? - .conversation - .ok_or_else(|| anyhow!("No conversation found"))? - .last() - .cloned() - .ok_or_else(|| anyhow!("No messages in conversation"))?; - - Ok(Some(last_message)) - } - Err(e) => Ok(Some( - Message::assistant().with_text(format!("Error getting prompt: {}", e)), - )), - } - } - - async fn handle_recipe_command( - &self, - command: &str, - params_str: &str, - session_id: &str, - ) -> Result> { - match recipe_slash_command::resolve_command(command, params_str) { - Ok(None) => Ok(None), - Ok(Some((recipe, prompt))) => { - self.apply_resolved_recipe_command(command, recipe, prompt, session_id) - .await - } - Err(text) => Ok(Some(Message::assistant().with_text(text))), - } - } - - async fn apply_resolved_recipe_command( - &self, - command: &str, - recipe: Recipe, - prompt: String, - session_id: &str, - ) -> Result> { - if let Some(Err(error)) = recipe.response.clone().map(FinalOutputTool::try_new) { - return Ok(Some( - Message::assistant().with_text(format!("Recipe /{command} is not valid: {error}")), - )); - } - self.config - .session_manager - .update(session_id) - .recipe(Some(recipe)) - .apply() - .await?; - Ok(Some(Message::user().with_text(prompt))) - } - - async fn handle_skill_command( - &self, - command: &str, - params_str: &str, - session_id: &str, - ) -> Result> { - let working_dir = self - .config - .session_manager - .get_session(session_id, false) - .await - .ok() - .map(|session| session.working_dir); - - match skill_slash_command::resolve_command(command, params_str, working_dir.as_deref()) { - Ok(None) => Ok(None), - Ok(Some(prompt)) => Ok(Some(Message::user().with_text(prompt))), - Err(text) => Ok(Some(Message::assistant().with_text(text))), - } - } - - async fn handle_goal_command( - &self, - params_str: &str, - session_id: &str, - ) -> Result> { - let session_manager = &self.config.session_manager; - let mut state = GoalState::of(&session_manager.get_session(session_id, false).await?); - if params_str.is_empty() { - let text = match state.goal { - Some(goal) => format!("Current goal: {goal}"), - None => "No goal set. Use `/goal ` to set one.".to_string(), - }; - return Ok(Some(Message::assistant().with_text(text))); - } - - if is_clear_goal_param(params_str) { - state.goal = None; - session_manager - .set_extension_state(session_id, &state) - .await?; - return Ok(Some( - Message::assistant().with_text("Goal cleared. The agent will finish normally."), - )); - } - - let goal = params_str.to_string(); - state.goal = Some(goal.clone()); - session_manager - .set_extension_state(session_id, &state) - .await?; - Ok(Some(Message::assistant().with_text(format!( - "Goal set. The agent will verify this goal is met before finishing:\n\n> {goal}" - )))) - } - - async fn handle_grind_command( - &self, - params_str: &str, - session_id: &str, - ) -> Result> { - let session_manager = &self.config.session_manager; - let mut state = GoalState::of(&session_manager.get_session(session_id, false).await?); - if params_str.is_empty() { - let text = match state.grind { - Some(goal) => format!("Current grind goal: {goal}"), - None => "No grind goal set. Use `/grind ` to set one.".to_string(), - }; - return Ok(Some(Message::assistant().with_text(text))); - } - - if is_clear_goal_param(params_str) { - state.grind = None; - session_manager - .set_extension_state(session_id, &state) - .await?; - return Ok(Some( - Message::assistant().with_text("Grind cleared. The agent will finish normally."), - )); - } - - let goal = params_str.to_string(); - state.grind = Some(goal.clone()); - session_manager - .set_extension_state(session_id, &state) - .await?; - Ok(Some(Message::assistant().with_text(format!( - "Grind goal set. The agent will keep working until max_turns is reached:\n\n> {goal}" - )))) - } -} - -fn user_only_assistant_text(text: impl Into) -> Message { - Message::assistant().with_text(text).user_only() -} +impl Agent {} #[cfg(test)] 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() { @@ -648,107 +169,10 @@ mod tests { assert!(!command_starts_turn("just a normal message")); } - #[test] - fn user_only_assistant_text_is_durable_text_not_system_notification() { - let message = user_only_assistant_text("Conversation cleared"); - - assert!(message.metadata.user_visible); - assert!(!message.metadata.agent_visible); - assert_eq!(message.role, rmcp::model::Role::Assistant); - assert!(matches!( - message.content.as_slice(), - [MessageContent::Text(text)] if text.text == "Conversation cleared" - )); - } - #[test] fn status_is_registered_as_a_builtin_command() { assert!(list_commands() .iter() .any(|command| command.name == "status")); } - #[tokio::test] - async fn invalid_rendered_recipe_schema_returns_assistant_response() { - let agent = Agent::new(); - let recipe = Recipe::builder() - .title("Invalid rendered schema") - .description("Invalid rendered schema") - .instructions("Return structured output") - .response(Response { - json_schema: Some(json!({ - "type": "object", - "properties": { - "result": { - "type": "string", - "pattern": "[" - } - } - })), - }) - .build() - .expect("recipe shape is otherwise valid"); - - let response = agent - .apply_resolved_recipe_command( - "invalid-rendered-schema", - recipe, - "Return structured output".to_string(), - "unused-session", - ) - .await - .unwrap() - .unwrap(); - - assert_eq!(response.role, rmcp::model::Role::Assistant); - assert!(response - .as_concat_text() - .contains("Recipe /invalid-rendered-schema is not valid")); - } - #[tokio::test] - async fn doctor_refuses_without_enabling_developer() { - 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", &session.id) - .await - .expect("doctor command should succeed") - .expect("doctor command should return a message"); - - assert_eq!( - response.as_concat_text(), - crate::doctor::DEVELOPER_EXTENSION_REQUIRED_MESSAGE - ); - } } diff --git a/crates/goose/src/agents/extension_manager/lease.rs b/crates/goose/src/agents/extension_manager/lease.rs index ecb7d46aa..04d43f049 100644 --- a/crates/goose/src/agents/extension_manager/lease.rs +++ b/crates/goose/src/agents/extension_manager/lease.rs @@ -662,7 +662,6 @@ impl ExtensionLease { tool_call_id, notification_emitter, container, - from_state_machine, } = request; let client = resolved.extension.client.clone(); let action_required_stream = self.action_required_stream(tool_call_id.as_deref()).await; @@ -671,17 +670,17 @@ impl ExtensionLease { notification_emitter, tool_call_id.as_deref(), ); - let mut call_context = ToolCallContext::new( + let call_context = ToolCallContext::new( self.scope_id.clone(), self.working_dir.clone(), tool_call_id, ) .with_container(container) .with_extension_lease(Arc::new(self.clone())); - call_context.from_state_machine = from_state_machine; - if let Some(emitter) = emitter { - call_context = call_context.with_notification_emitter(emitter); - } + let call_context = match emitter { + Some(emitter) => call_context.with_notification_emitter(emitter), + None => call_context, + }; let mcp_app_call = McpAppCall::from_resolved(&resolved, self.hydrate_mcp_apps); let server_name = resolved.server_name.to_string(); @@ -770,7 +769,6 @@ pub struct CallRequest { pub(crate) tool_call_id: Option, pub(crate) notification_emitter: Option, pub(crate) container: Option, - pub(crate) from_state_machine: bool, } impl CallRequest { @@ -785,11 +783,6 @@ impl CallRequest { self.container = container; self } - - pub(crate) fn with_state_machine(mut self) -> Self { - self.from_state_machine = true; - self - } } impl From<&ToolCallContext> for CallRequest { @@ -798,7 +791,6 @@ impl From<&ToolCallContext> for CallRequest { tool_call_id: ctx.tool_call_request_id.clone(), notification_emitter: ctx.notification_emitter().cloned(), container: ctx.container().cloned(), - from_state_machine: ctx.from_state_machine, } } } diff --git a/crates/goose/src/agents/extension_manager/mod.rs b/crates/goose/src/agents/extension_manager/mod.rs index 02787fa55..aacca7967 100644 --- a/crates/goose/src/agents/extension_manager/mod.rs +++ b/crates/goose/src/agents/extension_manager/mod.rs @@ -2,6 +2,7 @@ use chrono::{DateTime, Utc}; use futures::FutureExt; use futures::Stream; use indexmap::IndexMap; +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::atomic::{AtomicU64, Ordering}; @@ -284,7 +285,7 @@ pub(crate) const TRUSTED_TOOL_UPDATE_META_KEY: &str = "__goose_tool_update_meta" /// Manages goose extensions / MCP clients and their interactions pub struct ExtensionManager { - extensions: Mutex>>, + scopes: Mutex>>>, mutation_lock: Mutex<()>, directory_lock: RwLock<()>, context: PlatformExtensionContext, @@ -508,7 +509,7 @@ impl ExtensionManager { use_login_shell_path: bool, ) -> Self { Self { - extensions: Mutex::new(IndexMap::new()), + scopes: Mutex::new(HashMap::new()), mutation_lock: Mutex::new(()), directory_lock: RwLock::new(()), context: PlatformExtensionContext { @@ -556,11 +557,12 @@ impl ExtensionManager { pub async fn resolve(&self, set: &ExtensionSet) -> ExtensionLease { let _guard = self.directory_lock.read().await; let members = { - let extensions = self.extensions.lock().await; + let scopes = self.scopes.lock().await; + let extensions = scopes.get(set.scope_id()); set.extensions() .iter() .filter_map(|config| { - let running = extensions.get(&config.key())?; + let running = extensions?.get(&config.key())?; if running.config != *config || !running.serves(set.working_dir.as_deref()) { warn!( extension = %config.key(), @@ -620,10 +622,12 @@ impl ExtensionManager { working_dir: Option<&Path>, ) -> ExtensionLease { let mut extensions = self - .extensions + .scopes .lock() .await - .values() + .get(session_id) + .into_iter() + .flat_map(IndexMap::values) .filter(|extension| extension.serves(working_dir)) .cloned() .collect::>(); @@ -637,26 +641,22 @@ impl ExtensionManager { ) } - /// Add an extension with an optional working directory. - /// If working_dir is None, falls back to current_dir. pub async fn add_extension( self: &Arc, config: ExtensionConfig, - working_dir: Option, + fallback_working_dir: Option, container: Option<&Container>, - session_id: Option<&str>, + session_id: &str, ) -> ExtensionResult<()> { let _guard = self.directory_lock.read().await; - let working_dir = match session_id { - Some(session_id) => Some( - self.context - .session_manager - .get_session(session_id, false) - .await - .map_err(|error| ExtensionError::SetupError(error.to_string()))? - .working_dir, - ), - None => working_dir, + let working_dir = match self + .context + .session_manager + .get_session(session_id, false) + .await + { + Ok(session) => Some(session.working_dir), + Err(_) => fallback_working_dir, }; self.add_extension_if_current(config, working_dir, container, session_id, None) .await @@ -667,7 +667,7 @@ impl ExtensionManager { config: ExtensionConfig, working_dir: Option, container: Option<&Container>, - session_id: Option<&str>, + session_id: &str, expected: Option<&Arc>, ) -> ExtensionResult<()> { let sanitized_name = config.key(); @@ -688,7 +688,13 @@ impl ExtensionManager { _ => working_dir.clone().unwrap_or_default(), }; - if let Some(existing) = self.extensions.lock().await.get(&sanitized_name) { + if let Some(existing) = self + .scopes + .lock() + .await + .get(session_id) + .and_then(|extensions| extensions.get(&sanitized_name)) + { if existing.config == config && existing.resolved_config == resolved_config && existing.working_dir == working_dir @@ -769,9 +775,7 @@ impl ExtensionManager { .. } => { let mut envs = envs.get_env(); - if let Some(sid) = session_id { - envs.insert("AGENT_SESSION_ID".to_string(), sid.to_string()); - } + envs.insert("AGENT_SESSION_ID".to_string(), session_id.to_string()); Box::new( stdio::connect( cmd, @@ -787,7 +791,8 @@ impl ExtensionManager { let server_info = client.get_info().cloned(); - let mut extensions = self.extensions.lock().await; + let mut scopes = self.scopes.lock().await; + let extensions = scopes.entry(session_id.to_string()).or_default(); if expected.is_some_and(|expected| { !extensions .get(&sanitized_name) @@ -808,7 +813,7 @@ impl ExtensionManager { tools: Mutex::new(None), }), ); - Self::invalidate_extension_manager_tools(&extensions); + Self::invalidate_extension_manager_tools(extensions); Ok(()) } @@ -835,15 +840,15 @@ impl ExtensionManager { config, Some(session.working_dir.clone()), container, - Some(session_id), + session_id, None, ) .await } - ExtensionMutation::Disable { name } => self.remove_extension(&name).await, + ExtensionMutation::Disable { name } => self.remove_extension(session_id, &name).await, }?; - EnabledExtensionsState::new(self.get_extension_configs().await) + EnabledExtensionsState::new(self.get_extension_configs(session_id).await) .to_extension_data(&mut session.extension_data) .map_err(|error| ExtensionError::SetupError(error.to_string()))?; self.context @@ -886,12 +891,14 @@ impl ExtensionManager { pub async fn add_client( &self, + session_id: &str, config: ExtensionConfig, client: McpClientBox, info: Option, ) { let key = config.key(); - let mut extensions = self.extensions.lock().await; + let mut scopes = self.scopes.lock().await; + let extensions = scopes.entry(session_id.to_string()).or_default(); extensions.insert( key.clone(), Arc::new(Extension { @@ -905,24 +912,36 @@ impl ExtensionManager { tools: Mutex::new(None), }), ); - Self::invalidate_extension_manager_tools(&extensions); + Self::invalidate_extension_manager_tools(extensions); } - pub async fn remove_extension(&self, name: &str) -> ExtensionResult<()> { - let sanitized_name = name_to_key(name); - self.remove_extension_by_key(&sanitized_name).await?; + pub async fn remove_extension(&self, session_id: &str, name: &str) -> ExtensionResult<()> { + self.remove_extension_by_key(session_id, &name_to_key(name)) + .await?; Ok(()) } - pub async fn remove_extension_by_key(&self, key: &str) -> ExtensionResult { - let mut extensions = self.extensions.lock().await; + pub async fn remove_extension_by_key( + &self, + session_id: &str, + key: &str, + ) -> ExtensionResult { + let mut scopes = self.scopes.lock().await; + let Some(extensions) = scopes.get_mut(session_id) else { + return Ok(false); + }; let removed = extensions.shift_remove(key).is_some(); if removed { - Self::invalidate_extension_manager_tools(&extensions); + Self::invalidate_extension_manager_tools(extensions); } Ok(removed) } + /// Drops the session's extensions. Processes stop once no lease holds them. + pub async fn release(&self, session_id: &str) { + self.scopes.lock().await.remove(session_id); + } + pub async fn update_working_dir( self: &Arc, new_dir: &Path, @@ -946,24 +965,22 @@ impl ExtensionManager { .map_err(|error| ExtensionError::SetupError(error.to_string()))?; } let extensions = self - .extensions - .lock() + .running(session_id) .await - .values() + .into_iter() .filter(|extension| { extension .working_dir .as_ref() .is_some_and(|working_dir| working_dir != new_dir) }) - .cloned() .collect::>(); for extension in extensions { self.add_extension_if_current( extension.config.clone(), Some(new_dir.to_path_buf()), container, - Some(session_id), + session_id, Some(&extension), ) .await?; @@ -971,21 +988,36 @@ impl ExtensionManager { Ok(()) } - pub async fn list_extensions(&self) -> ExtensionResult> { - Ok(self.extensions.lock().await.keys().cloned().collect()) - } - - pub async fn is_extension_enabled(&self, name: &str) -> bool { - let normalized = name_to_key(name); - self.extensions.lock().await.contains_key(&normalized) - } - - pub async fn get_extension_configs(&self) -> Vec { - self.extensions + async fn running(&self, session_id: &str) -> Vec> { + self.scopes .lock() .await - .values() - .map(|ext| ext.config.clone()) + .get(session_id) + .map(|extensions| extensions.values().cloned().collect()) + .unwrap_or_default() + } + + pub async fn list_extensions(&self, session_id: &str) -> Vec { + self.running(session_id) + .await + .into_iter() + .map(|extension| extension.key.clone()) + .collect() + } + + pub async fn is_extension_enabled(&self, session_id: &str, name: &str) -> bool { + let key = name_to_key(name); + self.running(session_id) + .await + .iter() + .any(|extension| extension.key == key) + } + + pub async fn get_extension_configs(&self, session_id: &str) -> Vec { + self.running(session_id) + .await + .into_iter() + .map(|extension| extension.config.clone()) .collect() } } @@ -1029,7 +1061,7 @@ mod tests { bundled: None, available_tools, }; - self.add_client(config, client, None).await; + self.add_client("session", config, client, None).await; } } @@ -1314,7 +1346,7 @@ mod tests { .await; let (sender, mut receiver) = mpsc::channel(1); let ctx = ToolCallContext::new( - "nested-session".to_string(), + "session".to_string(), None, Some("nested-request".to_string()), ) @@ -1557,11 +1589,12 @@ mod tests { .add_mock_extension("ext_a".to_string(), Arc::new(MockClient {})) .await; - let same = ExtensionSet::new("s", None, vec![builtin_config("ext_a", vec![])]).unwrap(); + let same = + ExtensionSet::new("session", None, vec![builtin_config("ext_a", vec![])]).unwrap(); assert!(extension_manager.resolve(&same).await.is_enabled("ext_a")); let narrower = ExtensionSet::new( - "s", + "session", None, vec![builtin_config("ext_a", vec!["tool".to_string()])], ) @@ -1601,25 +1634,26 @@ mod tests { }, None, None, - Some(&session.id), + &session.id, ) .await .unwrap(); manager .add_client( + &session.id, builtin_config("external", vec![]), Arc::new(MockClient {}), None, ) .await; - let before = manager.extensions.lock().await.clone(); + let before = manager.scopes.lock().await[&session.id].clone(); manager .update_working_dir(new_working_dir.path(), None, &session.id) .await .unwrap(); - let after = manager.extensions.lock().await.clone(); + let after = manager.scopes.lock().await[&session.id].clone(); for key in ["developer", "external"] { assert!( Arc::ptr_eq(&before[key], &after[key]), @@ -1648,17 +1682,11 @@ mod tests { available_tools: vec![], }; extension_manager - .add_client(config.clone(), Arc::new(MockClient {}), None) + .add_client("session", config.clone(), Arc::new(MockClient {}), None) .await; - let stale = extension_manager - .extensions - .lock() - .await - .get("developer") - .unwrap() - .clone(); + let stale = extension_manager.scopes.lock().await["session"]["developer"].clone(); extension_manager - .remove_extension("developer") + .remove_extension("session", "developer") .await .unwrap(); @@ -1667,13 +1695,17 @@ mod tests { config, Some(new_working_dir.path().to_path_buf()), None, - Some("session"), + "session", Some(&stale), ) .await .unwrap(); - assert!(!extension_manager.is_extension_enabled("developer").await); + assert!( + !extension_manager + .is_extension_enabled("session", "developer") + .await + ); } #[test] @@ -1707,7 +1739,7 @@ mod tests { }, None, None, - None, + "session", ) .await .unwrap(); @@ -1728,6 +1760,7 @@ mod tests { ); extension_manager .add_client( + "session", builtin_config("resources", vec![]), Arc::new(MockClient {}), Some(resource_info), @@ -1744,7 +1777,7 @@ mod tests { .any(|tool| tool.name == "extensionmanager__list_resources")); extension_manager - .remove_extension("resources") + .remove_extension("session", "resources") .await .unwrap(); let tools = extension_manager @@ -1774,7 +1807,7 @@ mod tests { }, None, None, - None, + "session", ) .await .unwrap(); @@ -1785,6 +1818,7 @@ mod tests { ); extension_manager .add_client( + "session", builtin_config("resources", vec![]), Arc::new(ResourceClient { label: "old" }), Some(resource_info.clone()), @@ -1792,7 +1826,7 @@ mod tests { .await; let lease = extension_manager.current_lease("session", None).await; extension_manager - .remove_extension("resources") + .remove_extension("session", "resources") .await .unwrap(); assert!(lease @@ -1803,6 +1837,7 @@ mod tests { extension_manager .add_client( + "session", builtin_config("resources", vec![]), Arc::new(ResourceClient { label: "new" }), Some(resource_info), @@ -1858,20 +1893,14 @@ mod tests { extension_manager .add_mock_extension("dynamic".to_string(), tools_client.clone()) .await; - let tools_version = extension_manager.extensions.lock().await["dynamic"] + let tools_version = extension_manager.scopes.lock().await["session"]["dynamic"] .tools_version .clone(); let manager = Arc::new(extension_manager); let first_fetch = { let manager = manager.clone(); - tokio::spawn(async move { - manager - .current_lease("test-session", None) - .await - .tools() - .await - }) + tokio::spawn(async move { manager.current_lease("session", None).await.tools().await }) }; let _started = tools_client.first_fetch_started.acquire().await.unwrap(); @@ -1881,11 +1910,7 @@ mod tests { let stale_result = first_fetch.await.unwrap(); assert!(stale_result.iter().any(|tool| tool.name == "dynamic__old")); - let refreshed = manager - .current_lease("test-session", None) - .await - .tools() - .await; + let refreshed = manager.current_lease("session", None).await.tools().await; assert!(refreshed.iter().any(|tool| tool.name == "dynamic__new")); assert_eq!(tools_client.calls.load(Ordering::SeqCst), 2); } diff --git a/crates/goose/src/agents/gen_ai_telemetry.rs b/crates/goose/src/agents/gen_ai_telemetry.rs index eb0ecefbd..bd19e8930 100644 --- a/crates/goose/src/agents/gen_ai_telemetry.rs +++ b/crates/goose/src/agents/gen_ai_telemetry.rs @@ -114,24 +114,6 @@ pub(super) fn agent_name(session: &Session) -> &str { .map_or("goose", |recipe| recipe.title.as_str()) } -pub(super) fn tool_result_json(result: &ToolResult) -> String { - match result { - Ok(result) if result.is_error != Some(true) => json!({ - "status": "success", - "value": result, - }), - Ok(result) => json!({ - "status": "error", - "value": result, - }), - Err(error) => json!({ - "status": "error", - "error": error.to_string(), - }), - } - .to_string() -} - pub(super) fn successful_tool_result_json(result: &ToolResult) -> Option { match result { Ok(result) if result.is_error != Some(true) => { diff --git a/crates/goose/src/agents/mod.rs b/crates/goose/src/agents/mod.rs index f5f01efb0..5cc626223 100644 --- a/crates/goose/src/agents/mod.rs +++ b/crates/goose/src/agents/mod.rs @@ -23,7 +23,6 @@ pub mod subagent_execution_tool; pub(crate) mod subagent_handler; pub(crate) mod subagent_task_config; mod tool_confirmation_coordinator; -mod tool_confirmation_router; pub mod tool_execution; mod tool_schema_normalize; pub mod types; diff --git a/crates/goose/src/agents/moim.rs b/crates/goose/src/agents/moim.rs index 7b6b47dfe..0e276fabc 100644 --- a/crates/goose/src/agents/moim.rs +++ b/crates/goose/src/agents/moim.rs @@ -34,47 +34,6 @@ pub fn system_prompt_block() -> Option { } } -pub(super) async fn compute_compaction_info( - session_id: &str, - extension_manager: &ExtensionManager, -) -> Option { - let session = extension_manager - .get_context() - .session_manager - .get_session(session_id, false) - .await - .ok(); - let session_model_config = session - .as_ref() - .and_then(|session| session.model_config.clone()); - let context_limit = match (session.as_ref(), session_model_config.as_ref()) { - (Some(session), Some(model_config)) => { - match extension_manager - .get_context() - .providers - .provider_for(session) - .await - { - Ok(provider) => crate::context_limit::get_context_limit( - provider.as_ref(), - &model_config.model_name, - ) - .await - .ok(), - Err(_) => None, - } - } - _ => None, - }; - let total_tokens = session - .as_ref() - .and_then(|session| session.usage.total_tokens); - let compaction_threshold = crate::config::Config::global() - .get_param::("GOOSE_AUTO_COMPACT_THRESHOLD") - .unwrap_or(crate::context_mgmt::DEFAULT_COMPACTION_THRESHOLD); - compaction_remaining_line(total_tokens, context_limit, compaction_threshold) -} - pub async fn turn_context_message( session_id: &str, extension_manager: &ExtensionManager, @@ -196,29 +155,6 @@ fn escape_xml_text(value: &str) -> String { .replace('>', ">") } -fn compaction_remaining_line( - total_tokens: Option, - context_limit: Option, - threshold: f64, -) -> Option { - let total_tokens = total_tokens?; - let context_limit = context_limit?; - - if total_tokens <= 0 || context_limit == 0 || threshold <= 0.0 || threshold >= 1.0 { - return None; - } - - let compaction_at = (context_limit as f64 * threshold) as i32; - if compaction_at <= 0 || (total_tokens as f64 / compaction_at as f64) < 0.5 { - return None; - } - - Some(format!( - "~{}k tokens remaining", - compaction_at.saturating_sub(total_tokens) / 1000 - )) -} - fn turn_budget_part(turns_taken: u32, max_turns: u32) -> Option { if max_turns == 0 || turns_taken.saturating_mul(2) < max_turns { return None; @@ -347,11 +283,21 @@ mod tests { #[tokio::test] async fn turn_context_uses_the_inference_lease() { let (session_id, em, _tmp) = session_and_manager().await; - em.add_client(moim_extension(), Arc::new(MoimClient("old context")), None) - .await; + em.add_client( + &session_id, + moim_extension(), + Arc::new(MoimClient("old context")), + None, + ) + .await; let lease = em.current_lease(&session_id, None).await; - em.add_client(moim_extension(), Arc::new(MoimClient("new context")), None) - .await; + em.add_client( + &session_id, + moim_extension(), + Arc::new(MoimClient("new context")), + None, + ) + .await; let message = turn_context_message(&session_id, &em, &lease, 0, 100, chrono::Local::now(), None) diff --git a/crates/goose/src/agents/platform_extensions/code_execution.rs b/crates/goose/src/agents/platform_extensions/code_execution.rs index 3131e4861..61e88e0be 100644 --- a/crates/goose/src/agents/platform_extensions/code_execution.rs +++ b/crates/goose/src/agents/platform_extensions/code_execution.rs @@ -804,6 +804,7 @@ mod tests { let manager = Arc::new(ExtensionManager::with_data_dir(temp.path().join("manager"))); manager .add_client( + "test-session", ExtensionConfig::Builtin { name: "visibility".to_string(), description: "Visibility test tools".to_string(), @@ -857,7 +858,7 @@ mod tests { }, Some(session.working_dir.clone()), None, - Some(&session.id), + &session.id, ) .await .unwrap(); @@ -900,7 +901,7 @@ mod tests { }, Some(session.working_dir.clone()), None, - Some(&session.id), + &session.id, ) .await .unwrap(); @@ -909,7 +910,10 @@ mod tests { .current_lease(&session.id, Some(&session.working_dir)) .await, ); - manager.remove_extension("extensionmanager").await.unwrap(); + manager + .remove_extension(&session.id, "extensionmanager") + .await + .unwrap(); let callback = create_tool_callback( ToolCallContext::new( session.id.clone(), @@ -931,9 +935,8 @@ mod tests { .unwrap(); assert!(manager - .list_extensions() + .list_extensions(&session.id) .await - .unwrap() .contains(&"analyze".to_string())); let stored_session = manager .get_context() diff --git a/crates/goose/src/agents/platform_extensions/ext_manager.rs b/crates/goose/src/agents/platform_extensions/ext_manager.rs index 81a597af6..a9f8ae277 100644 --- a/crates/goose/src/agents/platform_extensions/ext_manager.rs +++ b/crates/goose/src/agents/platform_extensions/ext_manager.rs @@ -592,7 +592,7 @@ mod tests { "the mutation is for the loop, not the model" ); assert!( - !manager.is_extension_enabled("developer").await, + !manager.is_extension_enabled(&user_id, "developer").await, "the tool declares the change; the loop applies it" ); @@ -668,6 +668,10 @@ mod tests { let unknown_enable = manage(&client, "missing-session", "enable").await; assert!(unknown_enable.is_error.unwrap_or(false)); - assert!(!manager.is_extension_enabled("developer").await); + assert!( + !manager + .is_extension_enabled(&subagent_id, "developer") + .await + ); } } diff --git a/crates/goose/src/agents/platform_extensions/summon.rs b/crates/goose/src/agents/platform_extensions/summon.rs index 80b4db394..52b24bc92 100644 --- a/crates/goose/src/agents/platform_extensions/summon.rs +++ b/crates/goose/src/agents/platform_extensions/summon.rs @@ -1,10 +1,8 @@ use crate::agents::extension::PlatformExtensionContext; use crate::agents::final_output_tool::FinalOutputTool; use crate::agents::mcp_client::{Error, McpClientTrait}; -use crate::agents::subagent_handler::{run_subagent_task, SubagentRunParams}; -use crate::agents::subagent_task_config::{TaskConfig, DEFAULT_SUBAGENT_MAX_TURNS}; -use crate::agents::tool_execution::{ToolCallContext, ToolCallNotificationEmitter}; -use crate::agents::AgentConfig; +use crate::agents::subagent_task_config::DEFAULT_SUBAGENT_MAX_TURNS; +use crate::agents::tool_execution::ToolCallContext; use crate::config::paths::Paths; use crate::config::{Config, GooseMode}; use crate::conversation::message::Message; @@ -21,11 +19,10 @@ use async_trait::async_trait; use goose_sdk_types::custom_requests::{SourceEntry, SourceType}; use rmcp::model::{ CallToolResult, ContentBlock, Implementation, InitializeResult, JsonObject, ListToolsResult, - MetaObject, ServerCapabilities, ServerNotification, Tool, + MetaObject, ServerCapabilities, Tool, }; use serde::Deserialize; use std::collections::HashMap; -use std::future::Future; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use tokio::sync::Mutex; @@ -66,13 +63,6 @@ struct SubagentConfig { working_dir: PathBuf, max_turns: usize, } -async fn yield_to_outer_tool_stream() { - // The outer select may have polled its receiver before this future queues a - // notification. Keep the result pending for the following select pass so - // the now-ready receiver is observed before the terminal result. - tokio::task::yield_now().await; - tokio::task::yield_now().await; -} fn merge_subrecipe_parameters( fixed_values: Option<&HashMap>, @@ -432,41 +422,6 @@ impl SummonClient { Ok(session) } - async fn run_subagent_with_notifications( - emitter: Option, - run_subagent: Run, - ) -> Result - where - Run: FnOnce(tokio::sync::mpsc::UnboundedSender) -> RunFuture, - RunFuture: Future>, - { - let (notification_tx, mut notification_rx) = tokio::sync::mpsc::unbounded_channel(); - let run = run_subagent(notification_tx); - tokio::pin!(run); - - loop { - tokio::select! { - biased; - result = &mut run => { - while let Ok(notification) = notification_rx.try_recv() { - if let Some(emitter) = &emitter { - emitter.emit_best_effort(notification); - } - yield_to_outer_tool_stream().await; - } - yield_to_outer_tool_stream().await; - return result; - } - Some(notification) = notification_rx.recv() => { - if let Some(emitter) = &emitter { - emitter.emit_best_effort(notification); - } - yield_to_outer_tool_stream().await; - } - } - } - } - fn create_load_tool(&self) -> Tool { let schema = serde_json::json!({ "type": "object", @@ -865,9 +820,6 @@ impl SummonClient { session_id: &str, working_dir: &Path, arguments: Option, - cancellation_token: CancellationToken, - notification_emitter: Option, - from_state_machine: bool, ) -> Result { let params: DelegateParams = arguments .map(|args| serde_json::from_value(serde_json::Value::Object(args))) @@ -889,76 +841,7 @@ impl SummonClient { return Err("Delegated tasks cannot spawn further delegations".to_string()); } - if from_state_machine { - return self.handle_foreground_delegate(params, &session).await; - } - - let recipe = self - .build_delegate_recipe(¶ms, session_id, working_dir) - .await?; - - let task_config = self - .build_task_config(¶ms, &recipe, &session) - .await - .map_err(|e| format!("Failed to build task config: {}", e))?; - - // Subagents must use Auto until get_agent_messages forwards - // ActionRequired messages to the parent. Until then, any mode - // that requires approval will hang on the subagent's confirmation_rx. - let mut agent_config = AgentConfig::new( - self.context.session_manager.clone(), - crate::config::permission::PermissionManager::instance(), - None, - GooseMode::Auto, - true, // disable session naming for subagents - crate::agents::GoosePlatform::GooseCli, - ) - .with_use_login_shell_path(self.context.use_login_shell_path); - agent_config.is_subagent = true; - - let subagent_session = self - .create_subagent_session( - &task_config.parent_working_dir, - &task_config.parent_session_id, - "Delegated task".to_string(), - ) - .await?; - - let subagent_session_id = subagent_session.id.clone(); - - let params = SubagentRunParams { - config: agent_config, - recipe, - task_config, - return_last_only: true, - session_id: subagent_session.id, - cancellation_token: Some(cancellation_token), - notification_tx: None, - }; - let result = - Self::run_subagent_with_notifications(notification_emitter, move |notification_tx| { - let mut params = params; - params.notification_tx = Some(notification_tx); - run_subagent_task(params) - }) - .await; - - let mut meta = MetaObject::new(); - meta.0.insert( - "subagent_session_id".to_string(), - serde_json::Value::String(subagent_session_id), - ); - - match result { - Ok(text) => { - Ok(CallToolResult::success(vec![ContentBlock::text(text)]).with_meta(Some(meta))) - } - Err(e) => Ok(CallToolResult::error(vec![ContentBlock::text(format!( - "Delegation failed: {}", - e - ))]) - .with_meta(Some(meta))), - } + self.handle_foreground_delegate(params, &session).await } async fn handle_foreground_delegate( @@ -1262,37 +1145,6 @@ impl SummonClient { .map_err(|e| format!("Failed to build recipe from agent: {}", e)) } - async fn build_task_config( - &self, - params: &DelegateParams, - recipe: &Recipe, - session: &crate::session::Session, - ) -> Result { - let config = self - .resolve_subagent_config(params, recipe, session) - .await?; - let provider = match providers::get_from_registry(&config.provider_name).await { - Ok(entry) => entry.create(config.extensions.clone()).await?, - Err(error) => match self.context.providers.provider_for(session).await { - Ok(provider) - if provider.get_name() == config.provider_name - && !provider.manages_own_context() => - { - provider - } - _ => return Err(error), - }, - }; - Ok(TaskConfig { - provider, - model_config: config.model_config, - parent_session_id: session.id.clone(), - parent_working_dir: config.working_dir, - extensions: config.extensions, - max_turns: Some(config.max_turns), - }) - } - async fn resolve_subagent_config( &self, params: &DelegateParams, @@ -1541,7 +1393,7 @@ impl McpClientTrait for SummonClient { ctx: &ToolCallContext, name: &str, arguments: Option, - cancellation_token: CancellationToken, + _cancellation_token: CancellationToken, ) -> Result { let session_id = &ctx.session_id; let working_dir = self.working_dir(ctx); @@ -1555,14 +1407,7 @@ impl McpClientTrait for SummonClient { }, "delegate" => { match self - .handle_delegate( - session_id, - &working_dir, - arguments, - cancellation_token, - ctx.notification_emitter().cloned(), - ctx.from_state_machine, - ) + .handle_delegate(session_id, &working_dir, arguments) .await { Ok(result) => Ok(result), @@ -1621,8 +1466,7 @@ fn resolve_working_dir(parent_dir: &Path, requested: &str) -> Result = Arc::new( - crate::providers::testprovider::TestProvider::new_replaying( - temp_dir.path().join("records.json").display().to_string(), - ) - .unwrap(), - ); - let context = create_test_context(); - let providers = context.providers.clone(); - let client = SummonClient::new(context).unwrap(); - let session = crate::session::Session { - id: "unregistered-parent".to_string(), - provider_name: Some(parent_provider.get_name().to_string()), - model_config: Some(goose_providers::model::ModelConfig::new("test-model")), - working_dir: temp_dir.path().to_path_buf(), - ..Default::default() - }; - providers - .set_provider(&session.id, Arc::clone(&parent_provider)) - .await; - - let params = DelegateParams { - instructions: Some("Review the change".to_string()), - extensions: Some(Vec::new()), - provider: Some(parent_provider.get_name().to_string()), - model: Some("test-model".to_string()), - ..Default::default() - }; - let task_config = client - .build_task_config(¶ms, &empty_recipe(), &session) - .await - .unwrap(); - - assert!(Arc::ptr_eq(&parent_provider, &task_config.provider)); - let error = client - .handle_foreground_delegate(params, &session) - .await - .unwrap_err(); - assert!(error.contains("cannot be reconstructed for a foreground subagent")); - } - - #[tokio::test] - #[serial] - async fn test_build_task_config_recreates_registered_parent_provider() { - let temp_dir = TempDir::new().unwrap(); - let parent_provider = providers::create("openai", Vec::new()).await.unwrap(); - let client = SummonClient::new(create_test_context()).unwrap(); - let session = crate::session::Session { - provider_name: Some(parent_provider.get_name().to_string()), - model_config: Some(goose_providers::model::ModelConfig::new("test-model")), - working_dir: temp_dir.path().to_path_buf(), - ..Default::default() - }; - let params = DelegateParams { - extensions: Some(Vec::new()), - provider: Some(parent_provider.get_name().to_string()), - model: Some("test-model".to_string()), - ..Default::default() - }; - - let task_config = client - .build_task_config(¶ms, &empty_recipe(), &session) - .await - .unwrap(); - - assert!(!Arc::ptr_eq(&parent_provider, &task_config.provider)); - assert!(task_config.extensions.is_empty()); - } - const PARENT_MODEL: &str = "claude-3-5-sonnet-20241022"; const OVERRIDE_MODEL: &str = "claude-opus-4-6"; const PROVIDER: &str = "anthropic"; @@ -2883,150 +2648,4 @@ You review code."#; .to_string() .contains("No model configured for provider 'lmstudio'")); } - - fn test_tool_notification(request_id: &str, subagent_id: &str) -> ServerNotification { - use crate::agents::subagent_handler::create_tool_notification; - use crate::conversation::message::MessageContent; - use rmcp::model::CallToolRequestParams; - - let tool_call = CallToolRequestParams::new("developer__shell").with_arguments( - serde_json::json!({"command": request_id}) - .as_object() - .unwrap() - .clone(), - ); - let content = MessageContent::tool_request(request_id, Ok(tool_call)); - create_tool_notification(&content, subagent_id).unwrap() - } - - fn notification_subagent_id(notification: &ServerNotification) -> Option { - let ServerNotification::LoggingMessageNotification(log) = notification else { - return None; - }; - serde_json::to_value(&log.params) - .ok()? - .get("data")? - .get("subagent_id")? - .as_str() - .map(str::to_string) - } - - fn notification_command(notification: &ServerNotification) -> Option { - let ServerNotification::LoggingMessageNotification(log) = notification else { - return None; - }; - serde_json::to_value(&log.params) - .ok()? - .get("data")? - .get("tool_call")? - .get("arguments")? - .get("command")? - .as_str() - .map(str::to_string) - } - - fn notification_channel() -> ( - ToolCallNotificationEmitter, - tokio::sync::mpsc::Receiver, - ) { - let (sender, receiver) = tokio::sync::mpsc::channel(32); - (ToolCallNotificationEmitter::new(sender), receiver) - } - - #[tokio::test] - async fn test_notification_sinks_isolate_concurrent_delegate_calls() { - let (emitter_a, mut notifications_a) = notification_channel(); - let (emitter_b, mut notifications_b) = notification_channel(); - - let (result_a, result_b) = tokio::join!( - SummonClient::run_subagent_with_notifications( - Some(emitter_a), - |notification_tx| async move { - notification_tx - .send(test_tool_notification("inner-a", "subagent-a")) - .unwrap(); - tokio::task::yield_now().await; - Ok("delegate-a".to_string()) - } - ), - SummonClient::run_subagent_with_notifications( - Some(emitter_b), - |notification_tx| async move { - notification_tx - .send(test_tool_notification("inner-b", "subagent-b")) - .unwrap(); - tokio::task::yield_now().await; - Ok("delegate-b".to_string()) - } - ) - ); - assert_eq!(result_a.unwrap(), "delegate-a"); - assert_eq!(result_b.unwrap(), "delegate-b"); - - let notification_a = notifications_a.recv().await.unwrap(); - let notification_b = notifications_b.recv().await.unwrap(); - assert_eq!( - notification_subagent_id(¬ification_a).as_deref(), - Some("subagent-a") - ); - assert_eq!( - notification_subagent_id(¬ification_b).as_deref(), - Some("subagent-b") - ); - assert!(notifications_a.try_recv().is_err()); - assert!(notifications_b.try_recv().is_err()); - } - - #[tokio::test] - async fn test_live_notifications_precede_delegate_result() { - use crate::agents::tool_execution::{tool_stream, ToolStreamItem}; - use tokio_stream::wrappers::ReceiverStream; - - for _ in 0..32 { - let (emitter, notifications) = notification_channel(); - let mut output = tool_stream( - ReceiverStream::new(notifications), - futures::stream::empty(), - async move { - let result = SummonClient::run_subagent_with_notifications( - Some(emitter), - |notification_tx| async move { - for command in ["inner-live-0", "inner-live-1", "inner-live-2"] { - notification_tx - .send(test_tool_notification(command, "subagent-live")) - .unwrap(); - } - Ok("delegate-result".to_string()) - }, - ) - .await - .unwrap(); - Ok::<_, rmcp::model::ErrorData>(CallToolResult::success(vec![ - ContentBlock::text(result), - ])) - }, - ); - - let mut commands = Vec::new(); - let result = loop { - match output.next().await.unwrap() { - ToolStreamItem::Message(notification) => { - assert_eq!( - notification_subagent_id(¬ification).as_deref(), - Some("subagent-live") - ); - commands.push(notification_command(¬ification).unwrap()); - } - ToolStreamItem::Result(result) => break result, - ToolStreamItem::ActionRequired(_) => { - panic!("delegate must not request an action") - } - } - }; - - assert_eq!(commands, ["inner-live-0", "inner-live-1", "inner-live-2"]); - assert!(result.is_ok()); - assert!(output.next().await.is_none()); - } - } } diff --git a/crates/goose/src/agents/prompt_manager.rs b/crates/goose/src/agents/prompt_manager.rs index bb8e5afcd..48dac6672 100644 --- a/crates/goose/src/agents/prompt_manager.rs +++ b/crates/goose/src/agents/prompt_manager.rs @@ -6,7 +6,7 @@ use serde::Serialize; use crate::agents::{extension::ExtensionInfo, moim}; use crate::hints::load_hints::build_gitignore; -use crate::hints::{get_context_filenames, load_hint_files, SubdirectoryHintTracker}; +use crate::hints::{get_context_filenames, load_hint_files}; use crate::session::Session; use crate::{ config::{Config, GooseMode}, @@ -16,9 +16,7 @@ use crate::{ use std::path::Path; pub struct PromptManager { - subdirectory_hints: IndexMap, current_date_timestamp: String, - subdirectory_hint_tracker: SubdirectoryHintTracker, } impl Default for PromptManager { @@ -152,8 +150,7 @@ impl<'a> SystemPromptBuilder<'a, PromptManager> { "You are a general-purpose AI agent called goose, created by Block".to_string() }); - let mut system_prompt_extras = self.manager.subdirectory_hints.clone(); - system_prompt_extras.extend(self.prompt_extras); + let mut system_prompt_extras = self.prompt_extras; // Add hints if provided if let Some(hints) = self.hints { @@ -188,48 +185,25 @@ impl<'a> SystemPromptBuilder<'a, PromptManager> { impl PromptManager { pub fn new() -> Self { PromptManager { - subdirectory_hints: IndexMap::new(), // Use the fixed current date time so that prompt cache can be used. // Filtering to an hour to balance user time accuracy and multi session prompt cache hits. current_date_timestamp: Utc::now().format("%Y-%m-%d %H:00 %:z").to_string(), - subdirectory_hint_tracker: SubdirectoryHintTracker::new(), } } #[cfg(test)] pub fn with_timestamp(dt: DateTime) -> Self { PromptManager { - subdirectory_hints: IndexMap::new(), current_date_timestamp: dt.format("%Y-%m-%d %H:%M:%S %:z").to_string(), - subdirectory_hint_tracker: SubdirectoryHintTracker::new(), } } - pub fn record_tool_arguments( - &mut self, - arguments: &Option>, - working_dir: &Path, - ) { - self.subdirectory_hint_tracker - .record_tool_arguments(arguments, working_dir); - } - - pub fn load_subdirectory_hints(&mut self, working_dir: &Path) -> bool { - let new_hints = self.subdirectory_hint_tracker.load_new_hints(working_dir); - let has_new = !new_hints.is_empty(); - for (key, content) in new_hints { - self.subdirectory_hints.insert(key, content); - } - has_new - } - pub fn build_system_prompt( - &mut self, + &self, session: &Session, prompt_parts: Vec<(String, String)>, goose_mode: GooseMode, ) -> String { - self.load_subdirectory_hints(&session.working_dir); self.builder() .with_session(session) .with_prompt_extras(prompt_parts) @@ -325,7 +299,7 @@ mod tests { #[test] fn composed_prompt_uses_contributions_instead_of_the_extension_catalog() { - let mut manager = PromptManager::new(); + let manager = PromptManager::new(); let working_dir = tempfile::tempdir().unwrap(); let session = Session { diff --git a/crates/goose/src/agents/reply_parts.rs b/crates/goose/src/agents/reply_parts.rs index 9f90d8457..90750847e 100644 --- a/crates/goose/src/agents/reply_parts.rs +++ b/crates/goose/src/agents/reply_parts.rs @@ -1,34 +1,27 @@ use anyhow::Result; use goose_providers::errors::ProviderError; use regex::Regex; -use std::{collections::HashSet, sync::Arc}; +use std::sync::Arc; use async_stream::try_stream; use futures::stream::StreamExt; use serde_json::{json, Value}; use tracing::debug; -use super::super::agents::Agent; use super::gen_ai_telemetry; -use crate::agents::extension_manager::{get_tool_owner, recover_mangled_tool_name, ExtensionLease}; -#[cfg(feature = "code-mode")] -use crate::agents::platform_extensions::code_execution; -use crate::agents::state_machine::ops_recipe; -use crate::config::{Config, GooseMode}; -use crate::conversation::message::{Message, MessageContent, MessageUsage, ToolRequest}; +use crate::config::Config; +use crate::conversation::message::{Message, MessageContent}; use crate::conversation::{fix_conversation, merge_consecutive_messages_for_request, Conversation}; #[cfg(test)] use crate::providers::base::stream_from_single_message; use crate::providers::base::{MessageStream, Provider}; -use crate::providers::canonical_cost::resolve_usage_cost; use crate::providers::toolshim::{ augment_message_with_selected_tool_interpreter, convert_tool_messages_to_text, modify_system_prompt_for_tool_json, sanitize_residual_markers, }; -use crate::session::Session; -use goose_providers::conversation::token_usage::{ProviderStats, ProviderUsage, Usage}; +use goose_providers::conversation::token_usage::{ProviderStats, ProviderUsage}; use goose_providers::model::ModelConfig; -use rmcp::model::{ErrorData, Tool}; +use rmcp::model::Tool; use tracing::warn; async fn enhance_model_error( @@ -115,7 +108,9 @@ pub(crate) fn coerce_tool_arguments( ) -> Option> { let args = arguments?; - let properties = tool_schema.get("properties").and_then(|p| p.as_object())?; + let Some(properties) = tool_schema.get("properties").and_then(|p| p.as_object()) else { + return Some(args); + }; let mut coerced = serde_json::Map::new(); @@ -186,80 +181,6 @@ fn is_mergeable_assistant_chunk(message: &Message) -> bool { }) } -fn ensure_unique_tool_names(tools: &[Tool]) -> Result<()> { - let mut names = HashSet::new(); - for tool in tools { - if !names.insert(tool.name.as_ref()) { - anyhow::bail!("multiple tools registered '{}'", tool.name); - } - } - Ok(()) -} - -impl Agent { - pub async fn prepare_tools_and_prompt( - &self, - fallback_session: &Session, - ) -> Result<( - Session, - Arc, - Vec, - Vec, - String, - ModelConfig, - )> { - let (session, lease) = self - .extension_manager - .current_session_snapshot(fallback_session) - .await; - let lease = Arc::new(lease); - let mut tools = lease.tools().await; - if let Some(final_output_tool) = ops_recipe::final_output_tool(&session)? { - tools.push(final_output_tool.tool()); - } - ensure_unique_tool_names(&tools)?; - - #[cfg(feature = "code-mode")] - let code_execution_active = lease.is_enabled(code_execution::EXTENSION_NAME); - #[cfg(not(feature = "code-mode"))] - let code_execution_active = false; - - let tools = prepare_inference_tools(tools, code_execution_active); - - let extensions_info = lease.instructions().await; - let model_config = self.effective_model_config_for_session(&session.id).await?; - - let goose_mode = *self.current_goose_mode.lock().await; - - if goose_mode == GooseMode::SmartApprove { - self.tool_inspection_manager.apply_tool_annotations(&tools); - } - - let prompt_manager = self.prompt_manager.lock().await; - let system_prompt = prompt_manager - .builder() - .with_session(&session) - .with_prompt_extras(ops_recipe::recipe_prompt_parts(&session)?) - .with_extensions(extensions_info.into_iter()) - .with_code_execution_mode(code_execution_active) - .with_hints(&session.working_dir) - .with_goose_mode(goose_mode) - .build(); - - let (tools, toolshim_tools, system_prompt) = - prepare_tools_for_provider(tools, system_prompt, &model_config); - - Ok(( - session, - lease, - tools, - toolshim_tools, - system_prompt, - model_config, - )) - } -} - pub(crate) fn prepare_inference_tools( mut tools: Vec, code_execution_active: bool, @@ -601,205 +522,6 @@ pub(crate) async fn stream_response_from_provider( })) } -impl Agent { - pub(crate) fn categorize_tool_requests( - &self, - response: &Message, - tools: &[Tool], - toolshim_tools: &[Tool], - suppress_replayed_thinking: bool, - ) -> (Vec, Message) { - let model_visible_tools = tools - .iter() - .chain(toolshim_tools.iter()) - .collect::>(); - - // Precomputed once per response so a model-mangled tool name (GLM, - // Minimax — see #9486) is canonicalized to the real advertised name - // HERE, before permission inspection or PreToolUse hooks run on it - // downstream. Canonicalizing later (e.g. only at dispatch time) would - // let a mangled name dodge policy checks keyed to the canonical tool - // name while still executing the real tool underneath. - let tool_owners: Vec<(&str, Option)> = model_visible_tools - .iter() - .map(|t| (t.name.as_ref(), get_tool_owner(t))) - .collect(); - - // First collect all tool requests with coercion applied - let tool_requests: Vec = response - .content - .iter() - .filter_map(|content| { - if let MessageContent::ToolRequest(req) = content { - let mut coerced_req = req.clone(); - let externally_dispatched = coerced_req.was_executed_externally(); - let mut unadvertised_name = None; - - if let Ok(ref mut tool_call) = coerced_req.tool_call { - if !model_visible_tools.iter().any(|t| t.name == tool_call.name) { - if let Some(recovered) = recover_mangled_tool_name( - &tool_call.name, - tool_owners.iter().map(|(n, o)| (*n, o.as_deref())), - ) { - tool_call.name = recovered.into(); - } - } - - if let Some(tool) = model_visible_tools - .iter() - .find(|t| t.name == tool_call.name) - { - let schema_value = Value::Object(tool.input_schema.as_ref().clone()); - tool_call.arguments = - coerce_tool_arguments(tool_call.arguments.clone(), &schema_value); - - if let Some(ref meta) = tool.meta { - // Merge registry meta into existing tool_meta; - // existing keys win so provider markers (e.g. - // goose.external_dispatch) survive coercion. - let new_meta = serde_json::to_value(meta).ok(); - coerced_req.tool_meta = - match (coerced_req.tool_meta.take(), new_meta) { - ( - Some(Value::Object(mut existing)), - Some(Value::Object(new)), - ) => { - for (k, v) in new { - existing.entry(k).or_insert(v); - } - Some(Value::Object(existing)) - } - (None, new) => new, - (existing, _) => existing, - }; - } - } else if !externally_dispatched { - unadvertised_name = Some(tool_call.name.to_string()); - } - } - - if let Some(name) = unadvertised_name { - coerced_req.tool_call = Err(ErrorData::invalid_request( - format!("Tool '{name}' was not advertised for this model turn"), - None, - )); - } - - Some(coerced_req) - } else { - None - } - }) - .collect(); - - // Providers should emit unique tool-call ids within a turn, but a - // malformed or malicious provider can repeat one. Keep only the first - // occurrence of each id, in the order the provider sent them, so tools - // aren't executed twice and duplicate tool_results don't pollute the - // conversation history. - let mut seen_ids = std::collections::HashSet::new(); - let tool_requests: Vec = tool_requests - .into_iter() - .filter(|req| seen_ids.insert(req.id.clone())) - .collect(); - - let has_tool_requests = !tool_requests.is_empty(); - let should_suppress_replayed_thinking = suppress_replayed_thinking && has_tool_requests; - - // When a response contains tool calls, keep reasoning in the original - // message for provider/state purposes but only suppress it from the - // user-visible filtered message if the caller already surfaced - // thinking earlier in this provider turn. That avoids replaying full - // accumulated reasoning after streamed thought chunks while still - // preserving final-only non-streaming thoughts. - let mut filtered_content = Vec::new(); - let mut deduped_requests = tool_requests.iter(); - let mut next_request = deduped_requests.next(); - - for content in &response.content { - match content { - MessageContent::ToolRequest(req) => { - // Drop content for requests removed during dedup so duplicate - // ids don't survive into the filtered (history) message. - let Some(coerced_req) = next_request.filter(|r| r.id == req.id) else { - continue; - }; - next_request = deduped_requests.next(); - - filtered_content.push(MessageContent::ToolRequest(coerced_req.clone())); - } - MessageContent::Thinking(_) | MessageContent::RedactedThinking(_) - if should_suppress_replayed_thinking => {} - _ => { - if let Some(content) = user_visible_provider_content(content) { - filtered_content.push(content); - } - } - } - } - - let mut filtered_message = - Message::new(response.role.clone(), response.created, filtered_content); - filtered_message.metadata.output_token_limit_reached = - response.metadata.output_token_limit_reached; - - // Preserve the ID if it exists - if let Some(id) = response.id.clone() { - filtered_message = filtered_message.with_id(id); - } - - let tool_requests = tool_requests - .into_iter() - .filter(|request| !request.was_executed_externally()) - .collect(); - - (tool_requests, filtered_message) - } - - /// `post_compaction_context_tokens` is `Some` when this usage came from a - /// compaction call: the value (the retained summary size, not the billable - /// output) becomes the session's new context baseline. - pub(crate) async fn update_session_metrics( - &self, - session_id: &str, - schedule_id: Option, - usage: &ProviderUsage, - post_compaction_context_tokens: Option, - ) -> Result { - let manager = self.config.session_manager.clone(); - let session = manager.get_session(session_id, false).await?; - - let (chunk_cost, cost_source) = resolve_usage_cost(session.provider_name.as_deref(), usage); - - let mut enriched = usage.clone(); - enriched.cost = chunk_cost; - enriched.cost_source = cost_source; - let ledger = - MessageUsage::from_provider_usage(&enriched, post_compaction_context_tokens.is_some()); - - let current_usage = match post_compaction_context_tokens { - Some(retained) => Usage::new(Some(retained), None, Some(retained)), - None => usage.usage, - }; - - manager - .record_usage_metrics( - session_id, - schedule_id, - current_usage, - &usage.model, - &ledger, - ) - .await?; - - Ok(enriched) - } -} - -fn user_visible_provider_content(content: &MessageContent) -> Option { - content.user_visible_content() -} - /// Check whether a tool should be callable by an app based on MCP Apps visibility metadata. /// /// Per the MCP Apps spec (2026-01-26), if `_meta.ui.visibility` is present and does not @@ -1355,360 +1077,6 @@ mod tests { Ok(()) } - #[test] - fn categorize_tool_requests_keeps_thinking_when_not_previously_streamed() { - let agent = crate::agents::Agent::new(); - let tool = Tool::new("test_tool", "a test tool", object!({ "type": "object" })); - let mut response = Message::assistant() - .with_thinking("final-only reasoning", "") - .with_tool_request( - "tool-1", - Ok(rmcp::model::CallToolRequestParams::new("test_tool")), - ); - response.metadata.output_token_limit_reached = true; - - let (tool_requests, filtered_message) = - agent.categorize_tool_requests(&response, &[tool], &[], false); - - assert_eq!(tool_requests.len(), 1); - assert!(filtered_message.metadata.output_token_limit_reached); - assert_eq!(filtered_message.content.len(), 2); - assert!(matches!( - filtered_message.content[0], - MessageContent::Thinking(_) - )); - assert!(matches!( - filtered_message.content[1], - MessageContent::ToolRequest(_) - )); - } - - #[test] - fn categorize_tool_requests_drops_replayed_thinking_after_streaming() { - let agent = crate::agents::Agent::new(); - let tool = Tool::new("test_tool", "a test tool", object!({ "type": "object" })); - let response = Message::assistant() - .with_thinking("replayed reasoning", "") - .with_tool_request( - "tool-1", - Ok(rmcp::model::CallToolRequestParams::new("test_tool")), - ); - - let (tool_requests, filtered_message) = - agent.categorize_tool_requests(&response, &[tool], &[], true); - - assert_eq!(tool_requests.len(), 1); - assert_eq!(filtered_message.content.len(), 1); - assert!(matches!( - filtered_message.content[0], - MessageContent::ToolRequest(_) - )); - } - - #[test] - fn categorize_tool_requests_excludes_assistant_only_text_from_user_events() { - let agent = crate::agents::Agent::new(); - let assistant_only = TextContent::new("assistant-only") - .with_annotations(Annotations::default().with_audience(vec![Role::Assistant])); - let response = Message::assistant() - .with_content(MessageContent::Text(assistant_only)) - .with_text("user-visible") - .with_thinking("visible reasoning", ""); - - let (_, filtered_message) = agent.categorize_tool_requests(&response, &[], &[], false); - - assert_eq!(response.as_concat_text(), "assistant-only\nuser-visible"); - assert_eq!(filtered_message.as_concat_text(), "user-visible"); - assert!(filtered_message - .content - .iter() - .any(|content| matches!(content, MessageContent::Thinking(_)))); - } - - #[test] - fn categorize_tool_requests_skips_externally_dispatched_and_preserves_marker() { - // External requests must (1) survive coercion with goose.external_dispatch - // intact, (2) be excluded from dispatch, (3) stay in filtered_message. - use crate::conversation::message::TOOL_META_EXTERNAL_DISPATCH_KEY; - - let agent = crate::agents::Agent::new(); - - let registry_tool = Tool::new("test_tool", "a test tool", object!({ "type": "object" })) - .with_meta(rmcp::model::MetaObject( - serde_json::json!({ "ui": { "visibility": ["model"] } }) - .as_object() - .unwrap() - .clone(), - )); - - let response = Message::assistant() - .with_tool_request_with_metadata( - "tool-1", - Ok(rmcp::model::CallToolRequestParams::new("test_tool")), - None, - Some(serde_json::json!({ TOOL_META_EXTERNAL_DISPATCH_KEY: true })), - ) - .with_tool_request_with_metadata( - "tool-2", - Ok(rmcp::model::CallToolRequestParams::new("external_only")), - None, - Some(serde_json::json!({ TOOL_META_EXTERNAL_DISPATCH_KEY: true })), - ); - - let (tool_requests, filtered_message) = - agent.categorize_tool_requests(&response, &[registry_tool], &[], false); - - assert!( - tool_requests.is_empty(), - "external request leaked into tool requests: {tool_requests:?}" - ); - assert_eq!(filtered_message.content.len(), 2); - let tool_req = match &filtered_message.content[0] { - MessageContent::ToolRequest(req) => req, - other => panic!("expected ToolRequest, got {other:?}"), - }; - assert!( - tool_req.was_executed_externally(), - "goose.external_dispatch marker was clobbered by coercion; merged tool_meta = {:?}", - tool_req.tool_meta - ); - let merged = tool_req - .tool_meta - .as_ref() - .and_then(|v| v.as_object()) - .expect("tool_meta should be an object after merge"); - assert!( - merged.contains_key("ui"), - "registry tool meta keys were dropped; merged tool_meta = {merged:?}" - ); - assert!(filtered_message.content[1] - .as_tool_request() - .is_some_and(ToolRequest::was_executed_externally)); - assert!(filtered_message.content[1] - .as_tool_request() - .is_some_and(|request| request.tool_call.is_ok())); - } - - #[test] - fn categorize_tool_requests_rejects_unadvertised_executable_tools() { - let agent = crate::agents::Agent::new(); - let response = Message::assistant() - .with_tool_request( - "app-only", - Ok(rmcp::model::CallToolRequestParams::new("app_only")), - ) - .with_tool_request( - "off-list", - Ok(rmcp::model::CallToolRequestParams::new("unadvertised")), - ); - - let (tool_requests, filtered_message) = - agent.categorize_tool_requests(&response, &[], &[], false); - - assert_eq!(tool_requests.len(), 2); - assert!(tool_requests - .iter() - .all(|request| request.tool_call.is_err())); - assert_eq!( - filtered_message - .content - .iter() - .filter_map(MessageContent::as_tool_request) - .count(), - 2 - ); - } - - #[test] - fn categorize_tool_requests_dispatches_advertised_tools() { - let agent = crate::agents::Agent::new(); - let regular_tool = Tool::new( - "regular_tool", - "a regular tool", - object!({ "type": "object" }), - ); - let additional_tool = Tool::new( - "additional_tool", - "an additional tool", - object!({ "type": "object" }), - ); - let toolshim_tool = Tool::new( - "toolshim_tool", - "a toolshim tool", - object!({ "type": "object" }), - ); - let response = Message::assistant() - .with_tool_request( - "regular", - Ok(rmcp::model::CallToolRequestParams::new("regular_tool")), - ) - .with_tool_request( - "toolshim", - Ok(rmcp::model::CallToolRequestParams::new("toolshim_tool")), - ) - .with_tool_request( - "additional", - Ok(rmcp::model::CallToolRequestParams::new("additional_tool")), - ); - - let (tool_requests, _) = agent.categorize_tool_requests( - &response, - &[regular_tool, additional_tool], - &[toolshim_tool], - false, - ); - - assert_eq!(tool_requests.len(), 3); - } - - #[test] - fn categorize_tool_requests_canonicalizes_mangled_unprefixed_tool_name() { - // GLM's documented reproduction (#9486): a default Developer-extension - // tool is advertised unprefixed ("shell"), owner only in metadata, and - // the model emits "developer.shell". This must be rewritten to the - // canonical "shell" here — before permission inspection and PreToolUse - // hooks ever see the request — or policy checks keyed to the real tool - // name can be bypassed by a mangled name that later dispatch recovers - // (see PR #10230 follow-up review). - let agent = crate::agents::Agent::new(); - - let shell_tool = Tool::new( - "shell", - "run a shell command", - object!({ "type": "object" }), - ) - .with_meta(rmcp::model::MetaObject( - serde_json::json!({ "goose_extension": "developer" }) - .as_object() - .unwrap() - .clone(), - )); - - let response = Message::assistant().with_tool_request( - "tool-1", - Ok(rmcp::model::CallToolRequestParams::new("developer.shell")), - ); - - let (tool_requests, _) = - agent.categorize_tool_requests(&response, &[shell_tool], &[], false); - - assert_eq!(tool_requests.len(), 1); - let tool_call = tool_requests[0] - .tool_call - .as_ref() - .expect("mangled-but-recoverable name must not become an Err"); - assert_eq!( - tool_call.name, "shell", - "mangled name must be canonicalized before inspection/dispatch" - ); - } - - #[test] - fn categorize_tool_requests_canonicalizes_mangled_non_extension_manager_tool_name() { - // recipe__final_output is appended by Agent::list_tools outside the - // extension manager (see #9486 review); it must recover the same way. - let agent = crate::agents::Agent::new(); - - let final_output_tool = Tool::new( - "recipe__final_output", - "submit the final structured output", - object!({ "type": "object" }), - ); - - let response = Message::assistant().with_tool_request( - "tool-1", - Ok(rmcp::model::CallToolRequestParams::new( - "recipe.final_output", - )), - ); - - let (tool_requests, _) = - agent.categorize_tool_requests(&response, &[final_output_tool], &[], false); - - assert_eq!(tool_requests.len(), 1); - let tool_call = tool_requests[0] - .tool_call - .as_ref() - .expect("mangled-but-recoverable name must not become an Err"); - assert_eq!(tool_call.name, "recipe__final_output"); - } - - #[test] - fn categorize_tool_requests_rejects_unrecoverable_unadvertised_name() { - let agent = crate::agents::Agent::new(); - let tool = Tool::new( - "shell", - "run a shell command", - object!({ "type": "object" }), - ); - - let response = Message::assistant().with_tool_request( - "tool-1", - Ok(rmcp::model::CallToolRequestParams::new( - "totally_unknown_tool", - )), - ); - - let (tool_requests, filtered_message) = - agent.categorize_tool_requests(&response, &[tool], &[], false); - - assert_eq!(tool_requests.len(), 1); - assert!(tool_requests[0].tool_call.is_err()); - let tool_call = filtered_message.content[0] - .as_tool_request() - .unwrap() - .tool_call - .as_ref() - .unwrap_err(); - assert!(tool_call.message.contains("totally_unknown_tool")); - } - - #[test] - fn categorize_tool_requests_dedups_duplicate_ids_in_provider_order() { - // A malformed provider repeats id "dup". The first occurrence wins, the - // later duplicate is dropped from both the dispatch bucket and the - // filtered (history) message, and unique ids are kept. - let agent = crate::agents::Agent::new(); - - let response = Message::assistant() - .with_tool_request( - "dup", - Ok(rmcp::model::CallToolRequestParams::new("first_tool")), - ) - .with_tool_request( - "dup", - Ok(rmcp::model::CallToolRequestParams::new("second_tool")), - ) - .with_tool_request( - "unique", - Ok(rmcp::model::CallToolRequestParams::new("third_tool")), - ); - let tools = [ - Tool::new("first_tool", "first", object!({ "type": "object" })), - Tool::new("second_tool", "second", object!({ "type": "object" })), - Tool::new("third_tool", "third", object!({ "type": "object" })), - ]; - - let (tool_requests, filtered_message) = - agent.categorize_tool_requests(&response, &tools, &[], false); - - let kept: Vec<(&str, &str)> = tool_requests - .iter() - .map(|r| (r.id.as_str(), r.tool_call.as_ref().unwrap().name.as_ref())) - .collect(); - assert_eq!(kept, vec![("dup", "first_tool"), ("unique", "third_tool")]); - - let filtered_ids: Vec<&str> = filtered_message - .content - .iter() - .filter_map(|c| match c { - MessageContent::ToolRequest(req) => Some(req.id.as_str()), - _ => None, - }) - .collect(); - assert_eq!(filtered_ids, vec!["dup", "unique"]); - } - fn make_tool_with_meta(meta_json: Option) -> Tool { let mut tool = Tool::new("test_tool", "a test tool", object!({ "type": "object" })); if let Some(v) = meta_json { @@ -2124,18 +1492,4 @@ mod tests { } #[cfg(test)] -mod duplicate_tool_tests { - use super::*; - - #[test] - fn rejects_duplicate_tool_names_for_legacy_inference() { - let schema = Arc::new(serde_json::Map::new()); - let tools = vec![ - Tool::new("duplicate", "first", schema.clone()), - Tool::new("duplicate", "second", schema), - ]; - - let error = ensure_unique_tool_names(&tools).unwrap_err(); - assert_eq!(error.to_string(), "multiple tools registered 'duplicate'"); - } -} +mod duplicate_tool_tests {} diff --git a/crates/goose/src/agents/retry.rs b/crates/goose/src/agents/retry.rs index 6dcd00f63..21c53e862 100644 --- a/crates/goose/src/agents/retry.rs +++ b/crates/goose/src/agents/retry.rs @@ -1,196 +1,16 @@ use anyhow::Result; use std::process::Stdio; -use std::sync::Arc; use std::time::Duration; use tokio::io::{AsyncRead, AsyncReadExt}; use tokio::process::Command; -use tokio::sync::Mutex; use tracing::{debug, info, warn}; use crate::subprocess::SubprocessExt; -use crate::agents::types::SessionConfig; -use crate::agents::types::{ - RetryConfig, SuccessCheck, DEFAULT_ON_FAILURE_TIMEOUT_SECONDS, DEFAULT_RETRY_TIMEOUT_SECONDS, -}; -use crate::config::Config; -use crate::conversation::message::Message; -use crate::conversation::Conversation; -use crate::tool_monitor::RepetitionInspector; - -/// Result of a retry logic evaluation -#[derive(Debug, Clone, PartialEq)] -pub enum RetryResult { - /// No retry configuration or session available, retry logic skipped - Skipped, - /// Maximum retry attempts reached, cannot retry further. Carries the - /// user-facing failure message so the caller can yield and persist it. - MaxAttemptsReached(Message), - /// Success checks passed, no retry needed - SuccessChecksPassed, - /// Retry is needed and will be performed - Retried, -} - -/// Environment variable for configuring retry timeout globally -const GOOSE_RECIPE_RETRY_TIMEOUT_SECONDS: &str = "GOOSE_RECIPE_RETRY_TIMEOUT_SECONDS"; - -/// Environment variable for configuring on_failure timeout globally -const GOOSE_RECIPE_ON_FAILURE_TIMEOUT_SECONDS: &str = "GOOSE_RECIPE_ON_FAILURE_TIMEOUT_SECONDS"; +use crate::agents::types::SuccessCheck; const MAX_COMMAND_STDERR_BYTES: usize = 8 * 1024; -/// Manages retry state and operations for agent execution -#[derive(Debug)] -pub struct RetryManager { - /// Current number of retry attempts - attempts: Arc>, - /// Optional repetition inspector for reset operations - repetition_inspector: Option>>>, -} - -impl Default for RetryManager { - fn default() -> Self { - Self::new() - } -} - -impl RetryManager { - /// Create a new retry manager - pub fn new() -> Self { - Self { - attempts: Arc::new(Mutex::new(0)), - repetition_inspector: None, - } - } - - /// Create a new retry manager with repetition inspector - pub fn with_repetition_inspector( - repetition_inspector: Arc>>, - ) -> Self { - Self { - attempts: Arc::new(Mutex::new(0)), - repetition_inspector: Some(repetition_inspector), - } - } - - /// Reset the retry attempts counter to 0 - pub async fn reset_attempts(&self) { - let mut attempts = self.attempts.lock().await; - *attempts = 0; - - // Reset repetition inspector if available - if let Some(inspector) = &self.repetition_inspector { - if let Some(inspector) = inspector.lock().await.as_mut() { - inspector.reset(); - } - } - } - - /// Increment the retry attempts counter and return the new value - pub async fn increment_attempts(&self) -> u32 { - let mut attempts = self.attempts.lock().await; - *attempts += 1; - *attempts - } - - /// Get the current retry attempts count - pub async fn get_attempts(&self) -> u32 { - *self.attempts.lock().await - } - - async fn reset_status_for_retry(messages: &mut Conversation, initial_messages: &[Message]) { - *messages = Conversation::new_unvalidated(initial_messages.to_vec()); - info!("Reset message history to initial state for retry"); - } - - pub async fn handle_retry_logic( - &self, - messages: &mut Conversation, - session_config: &SessionConfig, - initial_messages: &[Message], - ) -> Result { - let Some(retry_config) = &session_config.retry_config else { - return Ok(RetryResult::Skipped); - }; - - let success = execute_success_checks(&retry_config.checks, retry_config).await?; - - if success { - info!("All success checks passed, no retry needed"); - return Ok(RetryResult::SuccessChecksPassed); - } - - let current_attempts = self.get_attempts().await; - if current_attempts >= retry_config.max_retries { - let error_msg = Message::assistant().with_text(format!( - "Maximum retry attempts ({}) exceeded. Unable to complete the task successfully.", - retry_config.max_retries - )); - warn!( - "Maximum retry attempts ({}) exceeded", - retry_config.max_retries - ); - #[cfg(feature = "telemetry")] - crate::posthog::emit_error( - "retry_max_exceeded", - &format!("Max retries ({}) exceeded", retry_config.max_retries), - ); - return Ok(RetryResult::MaxAttemptsReached(error_msg)); - } - - if let Some(on_failure_cmd) = &retry_config.on_failure { - info!("Executing on_failure command: {}", on_failure_cmd); - execute_on_failure_command(on_failure_cmd, retry_config).await?; - } - - Self::reset_status_for_retry(messages, initial_messages).await; - - let new_attempts = self.increment_attempts().await; - info!("Incrementing retry attempts to {}", new_attempts); - - Ok(RetryResult::Retried) - } -} - -/// Get the configured timeout duration for retry operations -/// retry_config.timeout_seconds -> env var -> default -fn get_retry_timeout(retry_config: &RetryConfig) -> Duration { - let timeout_seconds = retry_config - .timeout_seconds - .or_else(|| { - let config = Config::global(); - config.get_param(GOOSE_RECIPE_RETRY_TIMEOUT_SECONDS).ok() - }) - .unwrap_or(DEFAULT_RETRY_TIMEOUT_SECONDS); - - Duration::from_secs(timeout_seconds) -} - -/// Get the configured timeout duration for on_failure operations -/// retry_config.on_failure_timeout_seconds -> env var -> default -fn get_on_failure_timeout(retry_config: &RetryConfig) -> Duration { - let timeout_seconds = retry_config - .on_failure_timeout_seconds - .or_else(|| { - let config = Config::global(); - config - .get_param(GOOSE_RECIPE_ON_FAILURE_TIMEOUT_SECONDS) - .ok() - }) - .unwrap_or(DEFAULT_ON_FAILURE_TIMEOUT_SECONDS); - - Duration::from_secs(timeout_seconds) -} - -/// Execute all success checks and return true if all pass -pub async fn execute_success_checks( - checks: &[SuccessCheck], - retry_config: &RetryConfig, -) -> Result { - execute_success_checks_with_timeout(checks, get_retry_timeout(retry_config)).await -} - pub async fn execute_success_checks_with_timeout( checks: &[SuccessCheck], timeout: Duration, @@ -219,7 +39,7 @@ pub async fn execute_success_checks_with_timeout( } /// Execute a shell command with cross-platform compatibility and mandatory timeout -pub async fn execute_shell_command( +pub(crate) async fn execute_shell_command( command: &str, timeout: std::time::Duration, ) -> Result { @@ -311,11 +131,6 @@ where } } -/// Execute an on_failure command and return an error if it fails -pub async fn execute_on_failure_command(command: &str, retry_config: &RetryConfig) -> Result<()> { - execute_on_failure_command_with_timeout(command, get_on_failure_timeout(retry_config)).await -} - pub async fn execute_on_failure_command_with_timeout( command: &str, timeout: Duration, @@ -361,69 +176,6 @@ pub async fn execute_on_failure_command_with_timeout( #[cfg(test)] mod tests { use super::*; - use crate::agents::types::SuccessCheck; - - fn create_test_retry_config() -> RetryConfig { - RetryConfig { - max_retries: 3, - checks: vec![], - on_failure: None, - timeout_seconds: Some(60), - on_failure_timeout_seconds: Some(120), - } - } - - #[test] - fn test_retry_result_enum() { - let max_attempts = RetryResult::MaxAttemptsReached(Message::assistant().with_text("done")); - assert_ne!(RetryResult::Skipped, max_attempts); - assert_ne!(RetryResult::Skipped, RetryResult::SuccessChecksPassed); - assert_ne!(RetryResult::Skipped, RetryResult::Retried); - assert_ne!(max_attempts, RetryResult::SuccessChecksPassed); - assert_ne!(max_attempts, RetryResult::Retried); - assert_ne!(RetryResult::SuccessChecksPassed, RetryResult::Retried); - - let result = RetryResult::Retried; - let cloned = result.clone(); - assert_eq!(result, cloned); - - let debug_str = format!("{:?}", max_attempts); - assert!(debug_str.contains("MaxAttemptsReached")); - } - - #[tokio::test] - async fn test_execute_success_checks_all_pass() { - let checks = vec![ - SuccessCheck::Shell { - command: "echo 'test'".to_string(), - }, - SuccessCheck::Shell { - command: "true".to_string(), - }, - ]; - let retry_config = create_test_retry_config(); - - let result = execute_success_checks(&checks, &retry_config).await; - assert!(result.is_ok()); - assert!(result.unwrap()); - } - - #[tokio::test] - async fn test_execute_success_checks_one_fails() { - let checks = vec![ - SuccessCheck::Shell { - command: "echo 'test'".to_string(), - }, - SuccessCheck::Shell { - command: "false".to_string(), - }, - ]; - let retry_config = create_test_retry_config(); - - let result = execute_success_checks(&checks, &retry_config).await; - assert!(result.is_ok()); - assert!(!result.unwrap()); - } #[tokio::test] async fn test_execute_shell_command_success() { @@ -467,20 +219,6 @@ mod tests { assert_eq!(capture_tail(reader).await.unwrap(), diagnostic); } - #[tokio::test] - async fn test_execute_on_failure_command_success() { - let retry_config = create_test_retry_config(); - let result = execute_on_failure_command("echo 'cleanup'", &retry_config).await; - assert!(result.is_ok()); - } - - #[tokio::test] - async fn test_execute_on_failure_command_failure() { - let retry_config = create_test_retry_config(); - let result = execute_on_failure_command("false", &retry_config).await; - assert!(result.is_err()); - } - #[tokio::test] async fn test_shell_command_timeout() { let timeout = std::time::Duration::from_millis(100); @@ -492,81 +230,4 @@ mod tests { assert!(result.is_err()); } - - #[tokio::test] - async fn test_get_retry_timeout_uses_config_default() { - let retry_config = RetryConfig { - max_retries: 1, - checks: vec![], - on_failure: None, - timeout_seconds: None, - on_failure_timeout_seconds: None, - }; - - let timeout = get_retry_timeout(&retry_config); - assert_eq!(timeout, Duration::from_secs(DEFAULT_RETRY_TIMEOUT_SECONDS)); - } - - #[tokio::test] - async fn test_get_retry_timeout_uses_retry_config() { - let retry_config = RetryConfig { - max_retries: 1, - checks: vec![], - on_failure: None, - timeout_seconds: Some(120), - on_failure_timeout_seconds: None, - }; - - let timeout = get_retry_timeout(&retry_config); - assert_eq!(timeout, Duration::from_secs(120)); - } - - #[tokio::test] - async fn test_get_on_failure_timeout_uses_config_default() { - let retry_config = RetryConfig { - max_retries: 1, - checks: vec![], - on_failure: None, - timeout_seconds: None, - on_failure_timeout_seconds: None, - }; - - let timeout = get_on_failure_timeout(&retry_config); - assert_eq!( - timeout, - Duration::from_secs(DEFAULT_ON_FAILURE_TIMEOUT_SECONDS) - ); - } - - #[tokio::test] - async fn test_get_on_failure_timeout_uses_retry_config() { - let retry_config = RetryConfig { - max_retries: 1, - checks: vec![], - on_failure: None, - timeout_seconds: None, - on_failure_timeout_seconds: Some(900), - }; - - let timeout = get_on_failure_timeout(&retry_config); - assert_eq!(timeout, Duration::from_secs(900)); - } - - #[tokio::test] - async fn test_on_failure_timeout_different_from_retry_timeout() { - let retry_config = RetryConfig { - max_retries: 1, - checks: vec![], - on_failure: None, - timeout_seconds: Some(60), - on_failure_timeout_seconds: Some(300), - }; - - let retry_timeout = get_retry_timeout(&retry_config); - let on_failure_timeout = get_on_failure_timeout(&retry_config); - - assert_eq!(retry_timeout, Duration::from_secs(60)); - assert_eq!(on_failure_timeout, Duration::from_secs(300)); - assert_ne!(retry_timeout, on_failure_timeout); - } } diff --git a/crates/goose/src/agents/state_machine/inference_preparation.rs b/crates/goose/src/agents/state_machine/inference_preparation.rs index fe804ff0d..187e327bc 100644 --- a/crates/goose/src/agents/state_machine/inference_preparation.rs +++ b/crates/goose/src/agents/state_machine/inference_preparation.rs @@ -13,13 +13,10 @@ use goose_agent::operation::{messages_since_kickoff, InferenceInput}; use goose_providers::conversation::message::Message; use goose_providers::conversation::Conversation; use std::sync::{Arc, Mutex as StdMutex}; -use tokio::sync::Mutex; pub struct GooseInferenceRequestPreparer<'a> { pub(crate) extension_manager: Arc, pub(crate) extension_lease: Arc>>>, - pub(crate) goose_mode: &'a Mutex, - pub(crate) prompt_manager: &'a Mutex, pub(crate) tool_inspection_manager: &'a ToolInspectionManager, pub(crate) context_limit: usize, } @@ -64,18 +61,15 @@ impl InferenceRequestPreparer for GooseInferenceRequestPreparer<'_> { #[cfg(not(feature = "code-mode"))] let code_execution_mode = false; - let goose_mode = *self.goose_mode.lock().await; + let goose_mode = session.goose_mode; if goose_mode == GooseMode::SmartApprove { self.tool_inspection_manager .apply_tool_annotations(&input.tools); } let tools = crate::agents::reply_parts::prepare_inference_tools(input.tools, code_execution_mode); - let system_prompt = self.prompt_manager.lock().await.build_system_prompt( - session, - input.prompt_parts, - goose_mode, - ); + let system_prompt = + PromptManager::new().build_system_prompt(session, input.prompt_parts, goose_mode); let turn = messages_since_kickoff(conversation)?; let turn_start = turn .first() diff --git a/crates/goose/src/agents/state_machine/mod.rs b/crates/goose/src/agents/state_machine/mod.rs index fa51f7160..838af05e8 100644 --- a/crates/goose/src/agents/state_machine/mod.rs +++ b/crates/goose/src/agents/state_machine/mod.rs @@ -10,6 +10,7 @@ mod inference_preparation; mod ops_bang_shell; mod ops_compaction; mod ops_doctor; +mod ops_empty_response; mod ops_entry_hook; mod ops_exit_on_error; mod ops_foreground_subagent; @@ -73,6 +74,8 @@ pub(super) use inference_preparation::GooseInferenceRequestPreparer; pub(super) use ops_bang_shell::BangShellOperation; pub(super) use ops_compaction::CompactionOperation; pub(super) use ops_doctor::DoctorOperation; +pub(super) use ops_empty_response::EmptyResponseOperation; +pub(crate) use ops_entry_hook::session_start_message; pub(super) use ops_entry_hook::EntryHookOperation; pub(super) use ops_exit_on_error::ExitOnErrorOperation; pub(super) use ops_foreground_subagent::{subagent_cancelled_message, ForegroundSubagentOperation}; @@ -90,9 +93,3 @@ pub(super) use ops_tool_approval::ToolApprovalOperation; pub(super) use ops_tool_pair_compaction::ToolPairCompactionOperation; pub(super) use ops_toolcalling::ToolExecutionOperation; pub(super) use ops_unknown_tool::UnknownToolOperation; - -pub fn enabled() -> bool { - std::env::var("GOOSE_STATE_MACHINE") - .map(|v| matches!(v.as_str(), "1" | "true" | "TRUE" | "yes")) - .unwrap_or(false) -} diff --git a/crates/goose/src/agents/state_machine/ops_empty_response.rs b/crates/goose/src/agents/state_machine/ops_empty_response.rs new file mode 100644 index 000000000..2b970d3c6 --- /dev/null +++ b/crates/goose/src/agents/state_machine/ops_empty_response.rs @@ -0,0 +1,56 @@ +//! Reveals the empty-response fallback when nothing else took over the turn. + +use anyhow::{anyhow, Result}; +use async_trait::async_trait; +use goose_agent::inference::is_empty_response_marker; + +use crate::agents::state_machine::effects::GooseEffect; +use crate::agents::state_machine::{ + applied, messages_since_kickoff, not_applicable, ConversationEffect, Emitter, Operation, + OperationResult, +}; +use crate::conversation::Conversation; +use crate::session::Session; + +pub struct EmptyResponseOperation; + +#[async_trait] +impl Operation for EmptyResponseOperation { + fn name(&self) -> &'static str { + "empty_response" + } + + async fn run( + &self, + session: &Session, + conversation: &Conversation, + emit: &Emitter, + ) -> Result> { + let Some(fallback) = messages_since_kickoff(conversation)? + .last() + .filter(|message| is_empty_response_marker(message) && !message.is_user_visible()) + else { + return not_applicable(); + }; + if session + .recipe + .as_ref() + .is_some_and(|recipe| recipe.retry.is_some()) + { + return not_applicable(); + } + + let message_id = fallback + .id + .clone() + .ok_or_else(|| anyhow!("Persisted empty-response fallback has no id"))?; + emit.message(fallback.clone().with_visibility(true, true)) + .await; + applied([ConversationEffect::SetMessageVisibility { + message_id, + user_visible: true, + agent_visible: true, + } + .into()]) + } +} diff --git a/crates/goose/src/agents/state_machine/ops_entry_hook.rs b/crates/goose/src/agents/state_machine/ops_entry_hook.rs index 59cf8bbdd..b7540b245 100644 --- a/crates/goose/src/agents/state_machine/ops_entry_hook.rs +++ b/crates/goose/src/agents/state_machine/ops_entry_hook.rs @@ -10,6 +10,30 @@ use crate::conversation::Conversation; use crate::hooks::{HookContext, HookEvent, HookManager}; use crate::session::Session; +const OPERATION_NAME: &str = "entry_hook"; +const SESSION_START_NOTE: &str = "session_start"; + +/// Records that a client fired `SessionStart` when it opened the session, so the first +/// turn does not fire it again. Hidden from the user when the hooks printed no banner. +pub(crate) fn session_start_message(banners: &[String]) -> Message { + let mut message = Message::assistant(); + if !banners.is_empty() { + message = message.with_text(banners.join("\n")); + } + let mut message = message.with_visibility(!banners.is_empty(), false); + message + .metadata + .set_operation_note(OPERATION_NAME, SESSION_START_NOTE, true.into()); + message +} + +fn is_session_start_message(message: &Message) -> bool { + message + .metadata + .operation_note(OPERATION_NAME, SESSION_START_NOTE) + .is_some() +} + pub struct EntryHookOperation { hook_manager: HookManager, } @@ -23,7 +47,7 @@ impl EntryHookOperation { #[async_trait] impl Operation for EntryHookOperation { fn name(&self) -> &'static str { - "entry_hook" + OPERATION_NAME } async fn run( @@ -44,9 +68,10 @@ impl Operation for EntryHookOperation { let messages_before_kickoff = &conversation.messages()[..conversation.len() - messages.len()]; if !messages_before_kickoff.iter().any(|message| { - message.role == rmcp::model::Role::User - && message.is_user_visible() - && !message.is_tool_response() + is_session_start_message(message) + || (message.role == rmcp::model::Role::User + && message.is_user_visible() + && !message.is_tool_response()) }) { self.hook_manager .emit( @@ -59,7 +84,7 @@ impl Operation for EntryHookOperation { let prompt = messages .first() - .map(Message::as_concat_text) + .map(|message| message.agent_visible_content().as_concat_text()) .unwrap_or_default(); if !prompt.is_empty() { self.hook_manager diff --git a/crates/goose/src/agents/state_machine/ops_llm.rs b/crates/goose/src/agents/state_machine/ops_llm.rs index 748564054..fa1317401 100644 --- a/crates/goose/src/agents/state_machine/ops_llm.rs +++ b/crates/goose/src/agents/state_machine/ops_llm.rs @@ -72,10 +72,12 @@ fn enrich_unclaimed_tool_errors(messages: &[Message], tools: &[rmcp::model::Tool messages } -fn canonicalize_tool_request_names( - message: &mut Message, - advertised_tools: &[(String, Option)], -) { +fn prepare_tool_requests(message: &mut Message, advertised_tools: &[rmcp::model::Tool]) { + let tool_owners = advertised_tools + .iter() + .map(|tool| (tool.name.as_ref(), get_tool_owner(tool))) + .collect::>(); + for content in &mut message.content { let goose_providers::conversation::message::MessageContent::ToolRequest(request) = content else { @@ -84,15 +86,45 @@ fn canonicalize_tool_request_names( let Ok(tool_call) = &mut request.tool_call else { continue; }; - let Some(recovered) = recover_mangled_tool_name( - &tool_call.name, - advertised_tools - .iter() - .map(|(name, owner)| (name.as_str(), owner.as_deref())), - ) else { + if !advertised_tools + .iter() + .any(|tool| tool.name == tool_call.name) + { + if let Some(recovered) = recover_mangled_tool_name( + &tool_call.name, + tool_owners + .iter() + .map(|(name, owner)| (*name, owner.as_deref())), + ) { + tool_call.name = recovered.into(); + } + } + + let Some(tool) = advertised_tools + .iter() + .find(|tool| tool.name == tool_call.name) + else { continue; }; - tool_call.name = recovered.into(); + let schema = serde_json::Value::Object(tool.input_schema.as_ref().clone()); + tool_call.arguments = + crate::agents::reply_parts::coerce_tool_arguments(tool_call.arguments.clone(), &schema); + + let Some(meta) = &tool.meta else { + continue; + }; + let Ok(serde_json::Value::Object(meta)) = serde_json::to_value(meta) else { + continue; + }; + match request.tool_meta.as_mut() { + Some(serde_json::Value::Object(existing)) => { + for (key, value) in meta { + existing.entry(key).or_insert(value); + } + } + None => request.tool_meta = Some(serde_json::Value::Object(meta)), + Some(_) => {} + } } } @@ -124,19 +156,19 @@ impl Provider for GooseInferenceProvider { system.to_string(), model_config, ); - let advertised_tool_descriptors = tools + let advertised_tools = tools .iter() .chain(toolshim_tools.iter()) - .map(|tool| (tool.name.to_string(), get_tool_owner(tool))) + .cloned() .collect::>(); - let mut advertised_tools = advertised_tool_descriptors + let mut advertised_tool_names = advertised_tools .iter() - .map(|(name, _)| name.clone()) + .map(|tool| tool.name.to_string()) .collect::>(); - advertised_tools.sort_unstable(); - advertised_tools.dedup(); + advertised_tool_names.sort_unstable(); + advertised_tool_names.dedup(); let advertised_tools_note = serde_json::Value::Array( - advertised_tools + advertised_tool_names .into_iter() .map(serde_json::Value::String) .collect(), @@ -155,7 +187,7 @@ impl Provider for GooseInferenceProvider { Ok(Box::pin(stream.map(move |result| { result.map(|(message, usage)| { let message = message.map(|mut message| { - canonicalize_tool_request_names(&mut message, &advertised_tool_descriptors); + prepare_tool_requests(&mut message, &advertised_tools); if message.role == rmcp::model::Role::Assistant { message.metadata.set_operation_note( LLM_OPERATION_NAME, @@ -182,17 +214,19 @@ impl Provider for GooseInferenceProvider { #[cfg(test)] mod canonicalization_tests { use super::*; - use rmcp::model::CallToolRequestParams; + use rmcp::{model::CallToolRequestParams, object}; fn request(name: &str) -> Message { Message::assistant() .with_tool_request("request", Ok(CallToolRequestParams::new(name.to_string()))) } + fn tool_request(message: &Message) -> &goose_providers::conversation::message::ToolRequest { + message.content[0].as_tool_request().unwrap() + } + fn tool_name(message: &Message) -> &str { - message.content[0] - .as_tool_request() - .unwrap() + tool_request(message) .tool_call .as_ref() .unwrap() @@ -202,37 +236,131 @@ mod canonicalization_tests { #[test] fn canonicalizes_mangled_names_against_advertised_tools() { - let advertised = vec![("developer__shell".to_string(), None)]; + let advertised = vec![rmcp::model::Tool::new( + "developer__shell", + "run a shell command", + object!({ "type": "object" }), + )]; let mut message = request("developer.shell"); - canonicalize_tool_request_names(&mut message, &advertised); + prepare_tool_requests(&mut message, &advertised); assert_eq!(tool_name(&message), "developer__shell"); } #[test] fn canonicalizes_owner_qualified_unprefixed_tool_aliases() { - let advertised = vec![("shell".to_string(), Some("developer".to_string()))]; + let advertised = vec![rmcp::model::Tool::new( + "shell", + "run a shell command", + object!({ "type": "object" }), + ) + .with_meta(rmcp::model::MetaObject(object!({ + "goose_extension": "developer" + })))]; let mut message = request("developer.shell"); - canonicalize_tool_request_names(&mut message, &advertised); + prepare_tool_requests(&mut message, &advertised); assert_eq!(tool_name(&message), "shell"); let mut message = request("developer__shell"); - canonicalize_tool_request_names(&mut message, &advertised); + prepare_tool_requests(&mut message, &advertised); assert_eq!(tool_name(&message), "shell"); } #[test] fn leaves_unrecoverable_names_unmodified() { - let advertised = vec![("developer__shell".to_string(), None)]; + let advertised = vec![rmcp::model::Tool::new( + "developer__shell", + "run a shell command", + object!({ "type": "object" }), + )]; let mut message = request("developer.shell!"); - canonicalize_tool_request_names(&mut message, &advertised); + prepare_tool_requests(&mut message, &advertised); assert_eq!(tool_name(&message), "developer.shell!"); } + + #[test] + fn coerces_arguments_and_merges_tool_metadata() { + use crate::conversation::message::TOOL_META_EXTERNAL_DISPATCH_KEY; + + let advertised = vec![rmcp::model::Tool::new( + "set_enabled", + "set a flag", + object!({ + "type": "object", + "properties": { + "count": { "type": "integer" }, + "enabled": { "type": "boolean" } + } + }), + ) + .with_meta(rmcp::model::MetaObject(object!({ + "ui": { "visibility": ["model"] } + })))]; + let mut message = Message::assistant().with_tool_request_with_metadata( + "request", + Ok( + CallToolRequestParams::new("set_enabled").with_arguments(object!({ + "count": "4", + "enabled": "true" + })), + ), + None, + Some(serde_json::json!({ TOOL_META_EXTERNAL_DISPATCH_KEY: true })), + ); + + prepare_tool_requests(&mut message, &advertised); + + let request = tool_request(&message); + let arguments = request + .tool_call + .as_ref() + .unwrap() + .arguments + .as_ref() + .unwrap(); + assert_eq!(arguments["count"], 4); + assert_eq!(arguments["enabled"], true); + assert!(request.was_executed_externally()); + assert_eq!( + request.tool_meta.as_ref().unwrap()["ui"]["visibility"][0], + "model" + ); + } + + #[test] + fn preserves_arguments_for_map_schemas() { + let advertised = vec![rmcp::model::Tool::new( + "add_values", + "add named values", + object!({ + "type": "object", + "additionalProperties": { "type": "integer" } + }), + )]; + let mut message = Message::assistant().with_tool_request( + "request", + Ok(CallToolRequestParams::new("add_values") + .with_arguments(object!({ "left": 2, "right": 3 }))), + ); + + prepare_tool_requests(&mut message, &advertised); + + assert_eq!( + tool_request(&message) + .tool_call + .as_ref() + .unwrap() + .arguments + .as_ref() + .unwrap(), + &object!({ "left": 2, "right": 3 }) + ); + } } diff --git a/crates/goose/src/agents/state_machine/ops_recipe.rs b/crates/goose/src/agents/state_machine/ops_recipe.rs index 48b2d1b48..94cbe0cd5 100644 --- a/crates/goose/src/agents/state_machine/ops_recipe.rs +++ b/crates/goose/src/agents/state_machine/ops_recipe.rs @@ -217,8 +217,7 @@ impl Operation for RecipeOperation { let span = tool_span(&tool_call.name, &request.id, &session.id); // `recipe__final_output` is executed here rather than by // ToolExecutionOperation, which is registered after this one. Run the - // same hook lifecycle it would have run, so the state machine and the - // legacy loop agree on what a final-output call emits. + // same hook lifecycle it would have run there. let tool_input = tool_call .arguments .as_ref() diff --git a/crates/goose/src/agents/state_machine/ops_skills.rs b/crates/goose/src/agents/state_machine/ops_skills.rs index d0760f739..97c51c74b 100644 --- a/crates/goose/src/agents/state_machine/ops_skills.rs +++ b/crates/goose/src/agents/state_machine/ops_skills.rs @@ -366,8 +366,7 @@ impl Operation for SkillOperation { let span = tool_span(&tool_call.name, &request.id, &session.id); // `load_skill` is executed here rather than by // ToolExecutionOperation, which is registered after this one. - // Run the same hook lifecycle it would have run, so the state - // machine and the legacy loop agree on what a skill load emits. + // Run the same hook lifecycle it would have run there. let tool_input = tool_call .arguments .as_ref() diff --git a/crates/goose/src/agents/state_machine/ops_slash_command.rs b/crates/goose/src/agents/state_machine/ops_slash_command.rs index e5d9f77ae..2969d352f 100644 --- a/crates/goose/src/agents/state_machine/ops_slash_command.rs +++ b/crates/goose/src/agents/state_machine/ops_slash_command.rs @@ -61,10 +61,10 @@ impl Operation for SlashCommandOperation<'_> { let Some(user_message) = messages.first() else { return not_applicable(); }; - let message_text = user_message.as_concat_text(); if messages.len() != 1 { return not_applicable(); } + let message_text = user_message.agent_visible_content().as_concat_text(); let Some(command) = parse_slash_command(&message_text) else { return not_applicable(); }; diff --git a/crates/goose/src/agents/state_machine/ops_steer.rs b/crates/goose/src/agents/state_machine/ops_steer.rs index 570703eb6..e108136d5 100644 --- a/crates/goose/src/agents/state_machine/ops_steer.rs +++ b/crates/goose/src/agents/state_machine/ops_steer.rs @@ -66,7 +66,7 @@ impl Operation for SteerOperation { let mut effects = Vec::with_capacity(pending.len()); for message in pending { let context = HookContext::new(HookEvent::UserPromptSubmit, &session.id) - .with_message(message.as_concat_text()); + .with_message(message.agent_visible_content().as_concat_text()); self.hook_manager .emit(HookEvent::UserPromptSubmit, context) .await; diff --git a/crates/goose/src/agents/state_machine/ops_tool_approval.rs b/crates/goose/src/agents/state_machine/ops_tool_approval.rs index 113bfecee..5ec98ed80 100644 --- a/crates/goose/src/agents/state_machine/ops_tool_approval.rs +++ b/crates/goose/src/agents/state_machine/ops_tool_approval.rs @@ -19,22 +19,16 @@ use crate::session::Session; use crate::tool_inspection::{ get_security_finding_id_from_results, InspectionAction, ToolInspectionManager, }; -use tokio::sync::Mutex; pub const TOOL_EXECUTABLE_KEY: &str = "goose.executable"; pub struct ToolApprovalOperation<'a> { - goose_mode: &'a Mutex, tool_inspection_manager: &'a ToolInspectionManager, } impl<'a> ToolApprovalOperation<'a> { - pub fn new( - goose_mode: &'a Mutex, - tool_inspection_manager: &'a ToolInspectionManager, - ) -> Self { + pub fn new(tool_inspection_manager: &'a ToolInspectionManager) -> Self { Self { - goose_mode, tool_inspection_manager, } } @@ -52,7 +46,7 @@ impl Operation for ToolApprovalOperation<'_> { conversation: &Conversation, _emit: &Emitter, ) -> Result> { - let goose_mode = *self.goose_mode.lock().await; + let goose_mode = session.goose_mode; if goose_mode == GooseMode::Chat { return not_applicable(); } diff --git a/crates/goose/src/agents/state_machine/ops_toolcalling.rs b/crates/goose/src/agents/state_machine/ops_toolcalling.rs index 5e0d8ca03..85e0eed07 100644 --- a/crates/goose/src/agents/state_machine/ops_toolcalling.rs +++ b/crates/goose/src/agents/state_machine/ops_toolcalling.rs @@ -28,7 +28,6 @@ use crate::session::Session; pub(super) const EXPIRED_APPROVAL_RESPONSE: &str = "Tool approval expired because its extension lease is no longer available. Request the tool again."; use std::sync::{Arc, Mutex as StdMutex}; -use tokio::sync::Mutex; use tokio_util::sync::CancellationToken; use tracing_futures::Instrument; @@ -78,6 +77,7 @@ pub(super) fn tool_span(tool_name: &str, tool_call_id: &str, session_id: &str) - "gen_ai.operation.name" = "execute_tool", "gen_ai.tool.name" = %tool_name, "gen_ai.tool.call.id" = %tool_call_id, + "gen_ai.conversation.id" = %session_id, "gen_ai.tool.call.arguments" = tracing::field::Empty, "gen_ai.tool.call.result" = tracing::field::Empty, "error.type" = tracing::field::Empty, @@ -314,22 +314,19 @@ pub(super) fn with_post_tool_hooks( } } -pub struct ToolExecutionOperation<'a> { - goose_mode: &'a Mutex, +pub struct ToolExecutionOperation { extension_manager: Arc, hook_manager: HookManager, lease: Arc>>>, } -impl<'a> ToolExecutionOperation<'a> { +impl ToolExecutionOperation { pub fn new( - goose_mode: &'a Mutex, extension_manager: Arc, hook_manager: HookManager, lease: Arc>>>, ) -> Self { Self { - goose_mode, extension_manager, hook_manager, lease, @@ -405,9 +402,7 @@ impl<'a> ToolExecutionOperation<'a> { let result = lease .call( tool_call.clone(), - CallRequest::new(request_id.clone()) - .with_container(session.container.clone()) - .with_state_machine(), + CallRequest::new(request_id.clone()).with_container(session.container.clone()), cancellation_token, ) .await; @@ -772,7 +767,7 @@ fn approval_denied(permission: Option<&crate::permission::Permission>) -> bool { } #[async_trait] -impl Operation for ToolExecutionOperation<'_> { +impl Operation for ToolExecutionOperation { fn name(&self) -> &'static str { "tool_execution" } @@ -816,7 +811,11 @@ impl Operation for ToolExecutionOperation<'_> { conversation: &Conversation, ) -> Result> { let mut hints = SubdirectoryHintTracker::new(); - for message in conversation.messages() { + for message in conversation + .messages() + .iter() + .filter(|message| message.is_agent_visible()) + { for content in &message.content { if let MessageContent::ToolRequest(request) = content { if let Ok(tool_call) = &request.tool_call { @@ -936,7 +935,7 @@ impl Operation for ToolExecutionOperation<'_> { return not_applicable(); } - if *self.goose_mode.lock().await == GooseMode::Chat { + if session.goose_mode == GooseMode::Chat { let mut response = Message::user(); for (request, disposition) in &pending { let result = match disposition { diff --git a/crates/goose/src/agents/state_machine/session.rs b/crates/goose/src/agents/state_machine/session.rs index 19ab84a1d..602147345 100644 --- a/crates/goose/src/agents/state_machine/session.rs +++ b/crates/goose/src/agents/state_machine/session.rs @@ -115,7 +115,7 @@ impl EffectHandler for SessionManager { } } - for effect in effects { + for (index, effect) in effects.iter().enumerate() { match effect { GooseEffect::Conversation(ConversationEffect::AppendMessage(message)) => { if contains_tool_confirmation_request(message) { @@ -140,8 +140,11 @@ impl EffectHandler for SessionManager { conversation, )) | GooseEffect::CompactConversation { conversation, .. } => { - emit.emit(AgentEvent::HistoryReplaced(conversation.clone())) - .await; + emit.emit(AgentEvent::HistoryReplaced(replaced_history( + conversation, + &effects[index + 1..], + ))) + .await; } GooseEffect::RecordUsage(usage) => { emit.emit(AgentEvent::Usage(usage.clone())).await @@ -153,6 +156,31 @@ impl EffectHandler for SessionManager { } } +/// Clients swap in the replaced history, so it includes what the same batch appends +/// after the replacement; those messages were already shown live and would otherwise +/// vanish (a `/clear` would leave nothing). +fn replaced_history(replacement: &Conversation, later_effects: &[GooseEffect]) -> Conversation { + let mut messages = replacement.messages().clone(); + messages.extend( + later_effects + .iter() + .take_while(|effect| { + !matches!( + effect, + GooseEffect::Conversation(ConversationEffect::ReplaceConversation(_)) + | GooseEffect::CompactConversation { .. } + ) + }) + .filter_map(|effect| match effect { + GooseEffect::Conversation(ConversationEffect::AppendMessage(message)) => { + Some(message.clone()) + } + _ => None, + }), + ); + Conversation::new_unvalidated(messages) +} + impl EffectUsage for SessionManager { fn usage( &self, diff --git a/crates/goose/src/agents/state_machine/tests/agent_reply.rs b/crates/goose/src/agents/state_machine/tests/agent_reply.rs index 9251220c9..be9dfbd0d 100644 --- a/crates/goose/src/agents/state_machine/tests/agent_reply.rs +++ b/crates/goose/src/agents/state_machine/tests/agent_reply.rs @@ -18,7 +18,6 @@ use super::calculator_extension::{delayed_value, value, CalculatorExtension, ADD use super::dummy_api::{DummyApi, ProviderFeatures}; use crate::acp::server::GooseAcpAgent; use crate::agents::extension::ExtensionConfig; -use crate::agents::final_output_tool::{FINAL_OUTPUT_CONTINUATION_MESSAGE, FINAL_OUTPUT_TOOL_NAME}; use crate::agents::mcp_client::McpClientTrait; use crate::agents::state_machine::ops_toolcalling::EXPIRED_APPROVAL_RESPONSE; use crate::agents::{Agent, AgentConfig, AgentEvent, GoosePlatform, SessionConfig}; @@ -59,7 +58,6 @@ async fn agent_with_dummy_api() -> Result<(Agent, Arc, String, tempfil session_manager, Arc::new(PermissionManager::new(temp_dir.path().join("permissions"))), None, - GooseMode::Auto, true, GoosePlatform::GooseCli, )); @@ -92,6 +90,7 @@ async fn agent_with_calculator() -> Result<( agent .extension_manager .add_client( + &session_id, calculator_config(), calculator.clone(), calculator.get_info().cloned(), @@ -162,102 +161,8 @@ async fn stream_messages( Ok(messages) } -#[tokio::test] -async fn both_loops_execute_every_tool_from_the_last_allowed_reply() -> Result<()> { - for use_state_machine in [false, true] { - let (agent, api, session_id, calculator, _temp_dir) = agent_with_calculator().await?; - agent - .update_goose_mode(GooseMode::Auto, &session_id) - .await?; - api.on("add twice") - .calls([("first_add", ADD, value(1)), ("second_add", ADD, value(2))]); - - let messages = stream_messages( - agent - .reply( - Message::user().with_text("add twice"), - SessionConfig { - id: session_id, - schedule_id: None, - max_turns: Some(1), - retry_config: None, - }, - use_state_machine, - None, - ) - .await?, - ) - .await?; - - assert_eq!(api.call_count(), 1); - assert_eq!(calculator.total(), 3); - assert_eq!( - messages.last().unwrap().as_concat_text(), - crate::agents::state_machine::MAX_TURNS_MESSAGE - ); - } - Ok(()) -} - -#[tokio::test] -async fn both_loops_keep_recipe_continuations_within_the_turn_budget() -> Result<()> { - for use_state_machine in [false, true] { - let (agent, api, session_id, _temp_dir) = agent_with_dummy_api().await?; - let recipe = crate::recipe::Recipe::builder() - .title("Structured output") - .description("Return structured output") - .instructions("Use the final output tool") - .response(crate::recipe::Response { - json_schema: Some(json!({ "type": "object" })), - }) - .build() - .expect("valid recipe"); - agent - .config - .session_manager - .update(&session_id) - .recipe(Some(recipe)) - .apply() - .await?; - api.on("compute the answer").reply("thinking about it"); - api.on(FINAL_OUTPUT_CONTINUATION_MESSAGE) - .call(FINAL_OUTPUT_TOOL_NAME, json!({ "result": "42" })); - - let messages = stream_messages( - agent - .reply( - Message::user().with_text("compute the answer"), - SessionConfig { - id: session_id, - schedule_id: None, - max_turns: Some(1), - retry_config: None, - }, - use_state_machine, - None, - ) - .await?, - ) - .await?; - - assert_eq!(api.call_count(), 1); - assert_eq!( - messages.last().unwrap().as_concat_text(), - crate::agents::state_machine::MAX_TURNS_MESSAGE - ); - let continuation = messages - .iter() - .find(|message| message.as_concat_text() == FINAL_OUTPUT_CONTINUATION_MESSAGE) - .expect("recipe continuation"); - assert!(!continuation.is_user_visible()); - assert!(continuation.is_agent_visible()); - } - Ok(()) -} - #[tokio::test] async fn state_machine_confirmation_through_agent_resumes_tool_call() -> Result<()> { - let _guard = env_lock::lock_env([("GOOSE_STATE_MACHINE", Some("1"))]); let (mut agent, api, session_id, calculator, temp_dir) = agent_with_calculator().await?; let hook_dir = tempfile::tempdir()?; let plugin_dir = hook_dir.path().join("test-plugin"); @@ -282,13 +187,11 @@ async fn state_machine_confirmation_through_agent_resumes_tool_call() -> Result< id: session_id, schedule_id: None, max_turns: Some(2), - retry_config: None, }; let mut stream = agent .reply( Message::user().with_text("add one"), session_config.clone(), - true, Some(CancellationToken::new()), ) .await?; @@ -342,6 +245,7 @@ async fn state_machine_confirmation_through_agent_resumes_tool_call() -> Result< agent .extension_manager .add_client( + &session_config.id, calculator_config(), replacement.clone(), replacement.get_info().cloned(), @@ -498,7 +402,6 @@ async fn state_machine_confirmation_through_agent_resumes_tool_call() -> Result< #[tokio::test] async fn state_machine_skill_approval_uses_its_leased_working_dir() -> Result<()> { - let _guard = env_lock::lock_env([("GOOSE_STATE_MACHINE", Some("1"))]); let (agent, api, session_id, old_working_dir) = agent_with_dummy_api().await?; install_skill(old_working_dir.path(), "OLD_SKILL_CONTENT")?; agent @@ -514,13 +417,11 @@ async fn state_machine_skill_approval_uses_its_leased_working_dir() -> Result<() id: session_id, schedule_id: None, max_turns: Some(2), - retry_config: None, }; let mut stream = agent .reply( Message::user().with_text("load review"), session_config.clone(), - true, Some(CancellationToken::new()), ) .await?; @@ -569,7 +470,6 @@ async fn state_machine_skill_approval_uses_its_leased_working_dir() -> Result<() #[tokio::test] async fn state_machine_rejects_resumed_skill_approval_without_its_lease() -> Result<()> { - let _guard = env_lock::lock_env([("GOOSE_STATE_MACHINE", Some("1"))]); let (agent, api, session_id, working_dir) = agent_with_dummy_api().await?; install_skill(working_dir.path(), "SKILL_MUST_NOT_LOAD")?; agent @@ -585,13 +485,11 @@ async fn state_machine_rejects_resumed_skill_approval_without_its_lease() -> Res id: session_id, schedule_id: None, max_turns: Some(2), - retry_config: None, }; let mut stream = agent .reply( Message::user().with_text("load review"), session_config.clone(), - true, Some(CancellationToken::new()), ) .await?; @@ -628,7 +526,6 @@ async fn state_machine_rejects_resumed_skill_approval_without_its_lease() -> Res #[tokio::test] async fn state_machine_rejects_resumed_approval_without_its_lease() -> Result<()> { - let _guard = env_lock::lock_env([("GOOSE_STATE_MACHINE", Some("1"))]); let (agent, api, session_id, calculator, _temp_dir) = agent_with_calculator().await?; let agent = Arc::new(agent); @@ -639,13 +536,11 @@ async fn state_machine_rejects_resumed_approval_without_its_lease() -> Result<() id: session_id, schedule_id: None, max_turns: Some(2), - retry_config: None, }; let mut stream = agent .reply( Message::user().with_text("add one"), session_config.clone(), - true, Some(CancellationToken::new()), ) .await?; @@ -693,7 +588,6 @@ async fn state_machine_rejects_resumed_approval_without_its_lease() -> Result<() #[tokio::test] async fn state_machine_rejects_resumed_bang_shell_without_its_lease() -> Result<()> { - let _guard = env_lock::lock_env([("GOOSE_STATE_MACHINE", Some("1"))]); let (agent, api, session_id, _temp_dir) = agent_with_dummy_api().await?; api.on(EXPIRED_APPROVAL_RESPONSE).reply("request it again"); enable_developer(&agent, &session_id).await?; @@ -705,13 +599,11 @@ async fn state_machine_rejects_resumed_bang_shell_without_its_lease() -> Result< id: session_id, schedule_id: None, max_turns: Some(2), - retry_config: None, }; let mut stream = agent .reply( Message::user().with_text("!echo should-not-run"), session_config.clone(), - true, Some(CancellationToken::new()), ) .await?; @@ -763,7 +655,6 @@ async fn reply_streams_the_turn_and_ends() -> Result<()> { id: session_id.clone(), schedule_id: None, max_turns: Some(1), - retry_config: None, }; let stream = agent .reply_with_state_machine( @@ -799,13 +690,11 @@ async fn bang_shell_uses_state_machine_when_explicitly_enabled() -> Result<()> { id: session_id, schedule_id: None, max_turns: Some(2), - retry_config: None, }; let stream = agent .reply( Message::user().with_text("!echo hello"), session_config, - true, Some(CancellationToken::new()), ) .await?; @@ -848,9 +737,7 @@ async fn reply_messages( id: session_id, schedule_id: None, max_turns: Some(2), - retry_config: None, }, - crate::agents::state_machine::enabled(), Some(CancellationToken::new()), ) .await?; @@ -993,20 +880,7 @@ async fn assert_bang_shell_uses_only_user_visible_content() -> Result<()> { Ok(()) } -#[tokio::test] -async fn bang_shell_not_executed_in_legacy_loop() -> Result<()> { - let _guard = env_lock::lock_env([("GOOSE_STATE_MACHINE", None::<&str>)]); - let (agent, api, session_id, _temp_dir) = agent_with_dummy_api().await?; - api.on("!echo hello").reply("treated as text"); - let messages = - reply_messages(&agent, session_id, Message::user().with_text("!echo hello")).await?; - assert!(shell_commands(&messages).is_empty()); - assert_eq!(api.call_count(), 1); - Ok(()) -} - #[tokio::test] async fn bang_shell_visibility_is_enforced_when_state_machine_is_enabled() -> Result<()> { - let _guard = env_lock::lock_env([("GOOSE_STATE_MACHINE", Some("1"))]); assert_bang_shell_uses_only_user_visible_content().await } diff --git a/crates/goose/src/agents/state_machine/tests/compaction_lifecycle.rs b/crates/goose/src/agents/state_machine/tests/compaction_lifecycle.rs index 907f60c8f..2bbbdef5b 100644 --- a/crates/goose/src/agents/state_machine/tests/compaction_lifecycle.rs +++ b/crates/goose/src/agents/state_machine/tests/compaction_lifecycle.rs @@ -48,6 +48,8 @@ async fn proactive_and_manual_compaction_continue_with_replaced_usage() -> Resul let first_manual = pipeline.run(["/compact"]).await?; let second_manual = pipeline.run(["/compact"]).await?; first_manual.assert_emitted("Compaction complete"); + let (replaced, stored) = first_manual.replaced_and_stored_ids(); + assert_eq!(replaced, stored); assert_eq!(first_manual.history_replacements(), 1); assert_eq!(second_manual.history_replacements(), 1); @@ -69,6 +71,8 @@ async fn proactive_and_manual_compaction_continue_with_replaced_usage() -> Resul let cleared = pipeline.run(["/clear"]).await?; assert_eq!(cleared.history_replacements(), 1); assert_eq!(cleared.conversation().messages().len(), 2); + let (replaced, stored) = cleared.replaced_and_stored_ids(); + assert_eq!(replaced, stored); assert!(cleared .conversation() .messages() @@ -234,13 +238,41 @@ async fn text_that_looks_like_a_context_error_does_not_compact() -> Result<()> { } #[tokio::test] -async fn a_context_error_compacts_and_the_session_survives_a_failed_retry() -> Result<()> { +async fn context_errors_compact_and_retry() -> Result<()> { let (pipeline, api) = test_pipeline().await?; - api.on("real error").context_limit_error("too long"); + api.on("overflow once").context_limit_error("too long"); api.on(SUMMARIZE_HISTORY).reply("summary"); api.on("Your context was compacted") - .server_error("provider unavailable"); + .reply("recovered after compaction"); + let recovered = pipeline.run(["overflow once"]).await?; + recovered.assert_message(-1, Agent, "recovered after compaction"); + assert_eq!(recovered.history_replacements(), 1); + + let calls = api.calls(); + assert_eq!(calls.len(), 3); + let (summary, retry) = (&calls[1], &calls[2]); + let usage = &recovered.session.usage; + let output_tokens = "recovered after compaction".chars().count() as i32; + assert_eq!(usage.input_tokens, Some(retry.input_tokens())); + assert_eq!(usage.output_tokens, Some(output_tokens)); + assert_eq!( + usage.total_tokens, + Some(retry.input_tokens() + output_tokens) + ); + assert_eq!( + recovered.session.accumulated_usage.total_tokens, + Some( + summary.input_tokens() + "summary".len() as i32 + retry.input_tokens() + output_tokens + ) + ); + + api.on("Your context was compacted") + .server_error("provider unavailable"); + api.on(SUMMARIZE_HISTORY).reply("summary"); + api.on("real error") + .context_limit_error("too long") + .times(1); let failed_after_compaction = pipeline.run(["real error"]).await?; assert_eq!(failed_after_compaction.history_replacements(), 1); assert_eq!( diff --git a/crates/goose/src/agents/state_machine/tests/dummy_api.rs b/crates/goose/src/agents/state_machine/tests/dummy_api.rs index b5c3b4825..48bcfb13f 100644 --- a/crates/goose/src/agents/state_machine/tests/dummy_api.rs +++ b/crates/goose/src/agents/state_machine/tests/dummy_api.rs @@ -41,7 +41,7 @@ enum ApiResponse { Mixed { reasoning: String, text: Option, - call: Option, + calls: Vec, }, NoChoices, OutputLimit, @@ -65,6 +65,7 @@ struct ApiRule { matcher: ApiMatcher, response: ApiResponse, gate: Option, + remaining: Option, } enum ApiMatcher { @@ -179,6 +180,12 @@ impl ApiCall { .map(|tool| &tool["function"]["parameters"]) } + pub(super) fn messages(&self) -> &[Value] { + self.body["messages"] + .as_array() + .expect("OpenAI request messages") + } + pub(super) fn input_has_image(&self, mime_type: &str, data: &str) -> bool { let expected = format!("data:{mime_type};base64,{data}"); self.body["messages"] @@ -240,6 +247,7 @@ impl DummyApi { matcher, response, gate: None, + remaining: None, }); rules.len() - 1 } @@ -249,6 +257,7 @@ impl DummyApi { matcher, response, gate: Some(gate), + remaining: None, }); } } @@ -288,7 +297,7 @@ impl<'a> ApiRuleBuilder<'a> { self.configured(ApiResponse::Mixed { reasoning: text.into(), text: None, - call: None, + calls: Vec::new(), }) } @@ -369,6 +378,11 @@ impl<'a> ApiRuleBuilder<'a> { } impl<'a> ConfiguredResponse<'a> { + pub(super) fn times(self, count: usize) -> Self { + self.api.state.rules.lock().unwrap()[self.rule].remaining = Some(count); + self + } + pub(super) fn reply(self, text: impl Into) -> Self { let mut rules = self.api.state.rules.lock().unwrap(); let ApiResponse::Mixed { @@ -385,10 +399,10 @@ impl<'a> ConfiguredResponse<'a> { pub(super) fn call(self, name: impl Into, arguments: Value) -> Self { let mut rules = self.api.state.rules.lock().unwrap(); - let ApiResponse::Mixed { call, .. } = &mut rules[self.rule].response else { + let ApiResponse::Mixed { calls, .. } = &mut rules[self.rule].response else { panic!("call can only follow reasoning"); }; - *call = Some(ApiToolCall { + calls.push(ApiToolCall { id: String::new(), name: name.into(), arguments: arguments.to_string(), @@ -403,10 +417,10 @@ impl<'a> ConfiguredResponse<'a> { arguments: impl Into, ) -> Self { let mut rules = self.api.state.rules.lock().unwrap(); - let ApiResponse::Mixed { call, .. } = &mut rules[self.rule].response else { + let ApiResponse::Mixed { calls, .. } = &mut rules[self.rule].response else { panic!("malformed_call can only follow reasoning"); }; - *call = Some(ApiToolCall { + calls.push(ApiToolCall { id: String::new(), name: name.into(), arguments: arguments.into(), @@ -454,17 +468,23 @@ impl DummyApiState { let input = request_input(&body); let system = request_system(&body); let (response, gate) = { - let rules = self.rules.lock().unwrap(); + let mut rules = self.rules.lock().unwrap(); let rule = rules - .iter() + .iter_mut() .rev() - .find(|rule| match &rule.matcher { - ApiMatcher::InputContains(needle) => input.contains(needle), - ApiMatcher::SystemContains(needle) => system.contains(needle), + .find(|rule| { + rule.remaining != Some(0) + && match &rule.matcher { + ApiMatcher::InputContains(needle) => input.contains(needle), + ApiMatcher::SystemContains(needle) => system.contains(needle), + } }) .unwrap_or_else(|| { panic!("dummy API has no rule matching input {input:?}, system {system:?}") }); + if let Some(remaining) = &mut rule.remaining { + *remaining -= 1; + } (rule.response.clone(), rule.gate.clone()) }; if let Some(gate) = gate { @@ -521,26 +541,24 @@ impl DummyApiState { ApiResponse::Mixed { reasoning, text, - mut call, + mut calls, } => { - if let Some(call) = &mut call { + let suffix = id.strip_prefix("chatcmpl-test-").unwrap(); + for (index, call) in calls.iter_mut().enumerate() { assert_tool_advertised(&body, &call.name); - call.id = format!( - "dummy-tool-call-{}", - id.strip_prefix("chatcmpl-test-").unwrap() - ); + call.id = format!("dummy-tool-call-{suffix}-{index}"); } let output_tokens = reasoning.chars().count() + text.as_deref().unwrap_or_default().chars().count() - + call - .as_ref() + + calls + .iter() .map(|call| call.name.chars().count() + call.arguments.chars().count()) - .unwrap_or_default(); + .sum::(); sse_response(mixed_events( &meta(output_tokens as i32), &reasoning, text.as_deref(), - call.as_ref(), + &calls, )) } ApiResponse::NoChoices => sse_response(no_choices_events(&id, model)), @@ -857,7 +875,7 @@ fn mixed_events( meta: &ResponseMeta, reasoning: &str, text: Option<&str>, - call: Option<&ApiToolCall>, + calls: &[ApiToolCall], ) -> String { let ResponseMeta { id, model, .. } = meta; let mut events = String::new(); @@ -893,14 +911,8 @@ fn mixed_events( ); } } - if let Some(call) = call { - push_tool_call_events( - &mut events, - id, - model, - std::slice::from_ref(call), - Some(reasoning), - ); + if !calls.is_empty() { + push_tool_call_events(&mut events, id, model, calls, Some(reasoning)); } else { push_event( &mut events, diff --git a/crates/goose/src/agents/state_machine/tests/hooks_lifecycle.rs b/crates/goose/src/agents/state_machine/tests/hooks_lifecycle.rs index 614d5e50a..a4a582162 100644 --- a/crates/goose/src/agents/state_machine/tests/hooks_lifecycle.rs +++ b/crates/goose/src/agents/state_machine/tests/hooks_lifecycle.rs @@ -298,6 +298,16 @@ async fn session_prompt_and_tool_hooks_fire_at_their_boundaries() -> Result<()> assert_eq!(session_start.invocations(), 1); assert_eq!(api.call_count(), 2); + let opened_by_client = HookTestEnv::new("SessionStart", LOG_AND_ALLOW_SCRIPT); + let (pipeline, api) = test_pipeline().await?; + let pipeline = pipeline.with_hook_manager(opened_by_client.hook_manager()); + pipeline + .seed([crate::agents::state_machine::session_start_message(&[])]) + .await?; + api.on("first").reply("ok"); + pipeline.run(["first"]).await?; + assert_eq!(opened_by_client.invocations(), 0); + let prompt_submit = HookTestEnv::new("UserPromptSubmit", LOG_AND_ALLOW_SCRIPT); let (pipeline, api) = test_pipeline().await?; let pipeline = pipeline.with_hook_manager(prompt_submit.hook_manager()); diff --git a/crates/goose/src/agents/state_machine/tests/mod.rs b/crates/goose/src/agents/state_machine/tests/mod.rs index 2729fd3ec..6fa024a42 100644 --- a/crates/goose/src/agents/state_machine/tests/mod.rs +++ b/crates/goose/src/agents/state_machine/tests/mod.rs @@ -100,6 +100,50 @@ async fn state_machine_trace_retains_content_with_capture() -> Result<()> { Ok(()) } +async fn capture_tool_span_fields( + capture_setting: Option<&'static str>, +) -> Result<(serde_json::Map, String)> { + use crate::agents::gen_ai_telemetry::{ + test_support::SpanFieldCapture, CAPTURE_MESSAGE_CONTENT_ENV, + }; + use goose_test_support::otel::clear_otel_env; + + let _env = match capture_setting { + Some(value) => clear_otel_env(&[(CAPTURE_MESSAGE_CONTENT_ENV, value)]), + None => clear_otel_env(&[]), + }; + let capture = SpanFieldCapture::new("execute_tool"); + let _subscriber = capture.clone().set_default(); + let (pipeline, api) = test_pipeline().await?; + api.on("add the secret").calls([( + "call-secret", + ADD, + serde_json::json!({ "value": 1, "note": "tool-input-super-secret-token" }), + )]); + api.on("result: 1").reply("done"); + + pipeline.run(["add the secret"]).await?; + Ok((capture.fields(), pipeline.session_id.clone())) +} + +#[tokio::test] +async fn tool_span_records_gen_ai_attributes_and_gates_arguments() -> Result<()> { + for capture_setting in [None, Some("false")] { + let (fields, session_id) = capture_tool_span_fields(capture_setting).await?; + assert!(!serde_json::to_string(&fields)?.contains("tool-input-super-secret-token")); + assert_eq!(fields["gen_ai.operation.name"], "execute_tool"); + assert_eq!(fields["gen_ai.tool.name"], ADD); + assert_eq!(fields["gen_ai.tool.call.id"], "call-secret"); + assert_eq!(fields["gen_ai.conversation.id"], session_id.as_str()); + } + + let (fields, _) = capture_tool_span_fields(Some("true")).await?; + let arguments: serde_json::Value = + serde_json::from_str(fields["gen_ai.tool.call.arguments"].as_str().unwrap())?; + assert_eq!(arguments["note"], "tool-input-super-secret-token"); + Ok(()) +} + #[tokio::test] async fn bang_shell_requests_the_shell_tool() -> Result<()> { let (pipeline, api) = test_pipeline().await?; @@ -281,5 +325,20 @@ async fn slash_commands_yield_or_fall_through_to_inference() -> Result<()> { assert!(command.is_user_visible()); assert!(command.is_agent_visible()); + pipeline + .set_goal(Some("finish the migration".to_string())) + .await; + let shown = pipeline.run(["/goal"]).await?; + shown.assert_message(-1, Agent, "Current goal: finish the migration"); + assert_eq!( + pipeline.get_goal().await.as_deref(), + Some("finish the migration") + ); + + let cleared = pipeline.run(["/goal clear"]).await?; + cleared.assert_message(-1, Agent, "Goal cleared"); + assert!(pipeline.get_goal().await.is_none()); + assert_eq!(api.call_count(), 1); + Ok(()) } diff --git a/crates/goose/src/agents/state_machine/tests/pipeline.rs b/crates/goose/src/agents/state_machine/tests/pipeline.rs index f395ea87c..79beadfe6 100644 --- a/crates/goose/src/agents/state_machine/tests/pipeline.rs +++ b/crates/goose/src/agents/state_machine/tests/pipeline.rs @@ -4,7 +4,6 @@ use std::sync::{Arc, Mutex as StdMutex}; use anyhow::Result; use rmcp::model::ElicitationAction; use tokio::sync::mpsc; -use tokio::sync::Mutex as TokioMutex; use tokio_util::sync::CancellationToken; use super::calculator_extension::CalculatorExtension; @@ -15,7 +14,6 @@ use crate::agents::extension_manager::{ ExtensionLease, ExtensionManager, ExtensionManagerCapabilities, }; use crate::agents::mcp_client::McpClientTrait; -use crate::agents::prompt_manager::PromptManager; use crate::agents::state_machine::{ BangShellOperation, CompactionOperation, DoctorOperation, Emitter, EntryHookOperation, ExitOnErrorOperation, ForegroundSubagentOperation, GooseEffect, GooseInferenceProvider, @@ -94,8 +92,6 @@ pub(super) struct TestPipeline { model_config: ModelConfig, extension_manager: Arc, extension_lease: Arc>>>, - goose_mode: TokioMutex, - prompt_manager: TokioMutex, tool_inspection_manager: ToolInspectionManager, permission_manager: Arc, hook_manager: HookManager, @@ -142,10 +138,7 @@ impl TestPipeline { tool_call_cutoff, !self.provider_features.manages_own_context, )), - Arc::new(ToolApprovalOperation::new( - &self.goose_mode, - &self.tool_inspection_manager, - )), + Arc::new(ToolApprovalOperation::new(&self.tool_inspection_manager)), Arc::new(DoctorOperation::new(self.session_manager.clone())), Arc::new(ProjectOperation), Arc::new(SkillOperation::new( @@ -161,7 +154,6 @@ impl TestPipeline { self.hook_manager.clone(), )), Arc::new(ToolExecutionOperation::new( - &self.goose_mode, self.extension_manager.clone(), self.hook_manager.clone(), Arc::clone(&extension_lease), @@ -182,8 +174,6 @@ impl TestPipeline { let request_preparer = GooseInferenceRequestPreparer { extension_manager: Arc::clone(&self.extension_manager), extension_lease, - goose_mode: &self.goose_mode, - prompt_manager: &self.prompt_manager, tool_inspection_manager: &self.tool_inspection_manager, context_limit: self.model_config.context_limit(), }; @@ -212,7 +202,6 @@ impl TestPipeline { } pub(super) async fn with_goose_mode(self, mode: GooseMode) -> Self { - *self.goose_mode.lock().await = mode; self.session_manager .update(&self.session_id) .goose_mode(mode) @@ -298,7 +287,7 @@ impl TestPipeline { extension, Some(self.working_dir.clone()), None, - Some(&self.session_id), + &self.session_id, ) .await?; } @@ -317,6 +306,15 @@ impl TestPipeline { GoalState::of(&self.session().await.unwrap()).goal } + pub(super) async fn set_goal(&self, goal: Option) { + let mut state = GoalState::of(&self.session().await.unwrap()); + state.goal = goal; + self.session_manager + .set_extension_state(&self.session_id, &state) + .await + .unwrap(); + } + pub(super) async fn set_grind(&self, grind: Option) { let mut state = GoalState::of(&self.session().await.unwrap()); state.grind = grind; @@ -508,7 +506,7 @@ impl TestPipeline { pub(super) async fn remove_extension(&self, name: &str) -> Result<()> { self.extension_manager - .remove_extension(name) + .remove_extension(&self.session_id, name) .await .map_err(anyhow::Error::from) } @@ -525,7 +523,7 @@ impl TestPipeline { }, Some(self.working_dir.clone()), None, - Some(&self.session_id), + &self.session_id, ) .await .map_err(anyhow::Error::from) @@ -819,8 +817,6 @@ async fn build_test_pipeline( model_config, extension_manager, extension_lease: Arc::new(StdMutex::new(None)), - goose_mode: TokioMutex::new(session.goose_mode), - prompt_manager: TokioMutex::new(PromptManager::new()), tool_inspection_manager, permission_manager, hook_manager: HookManager::default(), @@ -862,6 +858,7 @@ async fn build_test_pipeline( if extension.name() == "calculator" { extension_manager .add_client( + &session_id, extension, calculator.clone(), calculator.get_info().cloned(), @@ -873,7 +870,7 @@ async fn build_test_pipeline( extension, Some(session.working_dir.clone()), None, - Some(&session_id), + &session_id, ) .await?; } @@ -946,6 +943,27 @@ impl TestRun { Self { session, events } } + /// Ids of the last history a client was told to swap in, and of what was stored. + pub(super) fn replaced_and_stored_ids(&self) -> (Vec, Vec) { + let ids = |conversation: &Conversation| { + conversation + .messages() + .iter() + .map(|message| message.id.clone().unwrap()) + .collect() + }; + let replaced = self + .events + .iter() + .rev() + .find_map(|event| match event { + AgentEvent::HistoryReplaced(conversation) => Some(conversation), + _ => None, + }) + .expect("history replaced"); + (ids(replaced), ids(self.conversation())) + } + pub(super) fn conversation(&self) -> &Conversation { self.session .conversation diff --git a/crates/goose/src/agents/state_machine/tests/prompt_skill_lifecycle.rs b/crates/goose/src/agents/state_machine/tests/prompt_skill_lifecycle.rs index 1686f40e7..7595b90b5 100644 --- a/crates/goose/src/agents/state_machine/tests/prompt_skill_lifecycle.rs +++ b/crates/goose/src/agents/state_machine/tests/prompt_skill_lifecycle.rs @@ -38,6 +38,15 @@ async fn prompt_and_skill_lifecycle() -> Result<()> { assert!(!calls[calls.len() - 2].system_contains("NESTED_PROJECT_INSTRUCTION")); assert!(calls[calls.len() - 1].system_contains("NESTED_PROJECT_INSTRUCTION")); + api.on("Please summarize the conversation history") + .reply("summary"); + pipeline.run(["/compact"]).await?; + api.on("after compaction").reply("continuing"); + pipeline.run(["after compaction"]).await?; + let after_compaction = api.calls().pop().unwrap(); + assert!(after_compaction.system_contains("ROOT_PROJECT_INSTRUCTION")); + assert!(!after_compaction.system_contains("NESTED_PROJECT_INSTRUCTION")); + let skill_dir = pipeline.working_dir().join(".agents/skills/review"); std::fs::create_dir_all(&skill_dir)?; std::fs::write( diff --git a/crates/goose/src/agents/state_machine/tests/provider_lifecycle.rs b/crates/goose/src/agents/state_machine/tests/provider_lifecycle.rs index 6692735f1..81da93778 100644 --- a/crates/goose/src/agents/state_machine/tests/provider_lifecycle.rs +++ b/crates/goose/src/agents/state_machine/tests/provider_lifecycle.rs @@ -8,6 +8,7 @@ use crate::agents::AgentEvent; use crate::conversation::fix_conversation; use crate::conversation::message::{Message, MessageContent, MessageErrorKind}; use crate::conversation::Conversation; +use rmcp::model::{Annotations, Role, TextContent}; #[tokio::test] async fn provider_lifecycle() -> Result<()> { @@ -73,7 +74,7 @@ async fn provider_lifecycle() -> Result<()> { .conversation() .messages() .iter() - .filter(|message| message.role == rmcp::model::Role::Assistant) + .filter(|message| message.role == Role::Assistant) .all(|message| { message .metadata @@ -198,6 +199,76 @@ async fn provider_lifecycle() -> Result<()> { result.assert_message(-2, ToolResponse, "result: 6"); result.assert_message(-1, Agent, "The total is 6."); + api.on("add one and two at once") + .reasoning("Both additions are independent.") + .reply("Adding both.") + .call(ADD, value(1)) + .call(ADD, value(2)); + api.on("Adding both.").reply("Both added."); + let result = pipeline.run(["add one and two at once"]).await?; + result.assert_message(-1, Agent, "Both added."); + let tool_turns: Vec<&Message> = result + .conversation() + .messages() + .iter() + .filter(|message| { + message + .content + .iter() + .any(|content| matches!(content, MessageContent::ToolRequest(_))) + }) + .collect(); + let tool_turn = *tool_turns.last().unwrap(); + assert!( + matches!( + tool_turn.content.as_slice(), + [ + MessageContent::Thinking(_), + MessageContent::Text(_), + MessageContent::ToolRequest(_), + MessageContent::ToolRequest(_) + ] + ), + "parallel tool calls must share the reasoning's message: {:#?}", + tool_turn.content + ); + let emitted_tool_turn = result + .events + .iter() + .find_map(|event| match event { + AgentEvent::Message(message) + if message + .content + .iter() + .any(|content| matches!(content, MessageContent::ToolRequest(_))) => + { + Some(message) + } + _ => None, + }) + .expect("emitted parallel tool calls"); + assert_eq!(emitted_tool_turn.id, tool_turn.id); + assert!(result.events.iter().any(|event| matches!( + event, + AgentEvent::MessageUsage { message_id, .. } if message_id == &tool_turn.id + ))); + + let follow_up = api.calls().pop().unwrap(); + let assistant_tool_calls: Vec<&serde_json::Value> = follow_up + .messages() + .iter() + .filter(|message| { + message["tool_calls"] + .as_array() + .is_some_and(|c| c.len() == 2) + }) + .collect(); + assert_eq!(assistant_tool_calls.len(), 1, "{:#?}", follow_up.messages()); + assert_eq!( + assistant_tool_calls[0]["reasoning_content"], + "Both additions are independent." + ); + assert!(result.session.usage.total_tokens.is_none()); assert!(result .session @@ -218,9 +289,30 @@ async fn provider_lifecycle() -> Result<()> { result.assert_message(-1, Agent, "recovered from no choices"); api.on("return an empty reply").reply(""); + let calls_before = api.call_count(); let result = pipeline.run(["return an empty reply"]).await?; + assert_eq!(api.call_count() - calls_before, 4); result.assert_message(-1, Agent, "model returned an empty response"); + api.on("empty twice").reply("recovered after empty replies"); + api.on("empty twice").reply("").times(2); + let calls_before = api.call_count(); + let result = pipeline.run(["empty twice"]).await?; + assert_eq!(api.call_count() - calls_before, 3); + result.assert_message(-1, Agent, "recovered after empty replies"); + + let calls_before = api.call_count(); + let user_only = Message::user().with_content(MessageContent::Text( + TextContent::new("only for the user") + .with_annotations(Annotations::default().with_audience(vec![Role::User])), + )); + let result = pipeline.run_message(user_only).await?; + assert_eq!(api.call_count(), calls_before); + assert_eq!( + result.conversation().last().unwrap().as_concat_text(), + "only for the user" + ); + api.on("after empty reply") .reply("recovered from empty reply"); let result = pipeline.run(["after empty reply"]).await?; @@ -286,7 +378,7 @@ async fn usage_and_provider_errors_survive_persistence() -> Result<()> { .conversation() .messages() .iter() - .find(|message| message.role == rmcp::model::Role::Assistant) + .find(|message| message.role == Role::Assistant) .expect("assistant response"); assert_eq!( assistant @@ -346,7 +438,7 @@ async fn requested_model_is_recorded_without_resolved_model() -> Result<()> { .conversation() .messages() .iter() - .find(|message| message.role == rmcp::model::Role::Assistant) + .find(|message| message.role == Role::Assistant) .and_then(|message| message.metadata.inference.as_ref()) .expect("assistant inference metadata"); diff --git a/crates/goose/src/agents/state_machine/tests/recipe_scheduling_lifecycle.rs b/crates/goose/src/agents/state_machine/tests/recipe_scheduling_lifecycle.rs index 3d803f4d4..49f17e3d6 100644 --- a/crates/goose/src/agents/state_machine/tests/recipe_scheduling_lifecycle.rs +++ b/crates/goose/src/agents/state_machine/tests/recipe_scheduling_lifecycle.rs @@ -305,6 +305,77 @@ async fn recipe_retry_and_final_output_run_to_completion() -> Result<()> { Ok(()) } +#[tokio::test] +async fn empty_responses_hand_the_turn_to_recipe_operations() -> Result<()> { + let shows_empty_fallback = |conversation: &crate::conversation::Conversation| { + conversation.iter().any(|message| { + message.is_user_visible() && message.as_concat_text().contains("empty response") + }) + }; + let retry = |check: &str| RetryConfig { + max_retries: 1, + checks: vec![SuccessCheck::Shell { + command: check.to_string(), + }], + on_failure: None, + timeout_seconds: None, + on_failure_timeout_seconds: None, + }; + + let (pipeline, api) = test_pipeline().await?; + api.on("compute the answer").reply(""); + api.on(FINAL_OUTPUT_CONTINUATION_MESSAGE) + .call(FINAL_OUTPUT_TOOL_NAME, json!({ "result": "42" })); + let recipe = Recipe::builder() + .title("Structured output") + .description("Return structured output") + .instructions("Compute the answer") + .response(Response { + json_schema: Some(json!({ + "type": "object", + "properties": { "result": { "type": "string" } }, + "required": ["result"] + })), + }) + .build() + .expect("valid recipe"); + pipeline.set_recipe(recipe).await?; + let nudged = pipeline.run(["compute the answer"]).await?; + nudged.assert_message(-1, Agent, r#"{"result":"42"}"#); + assert!(!shows_empty_fallback(nudged.conversation())); + + let (pipeline, api) = test_pipeline().await?; + api.on("check the work").reply(""); + let recipe = Recipe::builder() + .title("passing retry") + .description("passing retry") + .prompt("check the work") + .retry(retry("true")) + .build() + .expect("valid recipe"); + pipeline.set_recipe(recipe).await?; + let passed = pipeline.run(["check the work"]).await?; + assert!(!shows_empty_fallback(passed.conversation())); + + let (pipeline, api) = test_pipeline().await?; + api.on("never succeed").reply(""); + let recipe = Recipe::builder() + .title("failing retry") + .description("failing retry") + .prompt("never succeed") + .retry(retry("exit 1")) + .build() + .expect("valid recipe"); + pipeline.set_recipe(recipe).await?; + let (_pipeline, exhausted, _) = pipeline + .run_reconstructing_each_step("never succeed") + .await?; + exhausted.assert_message(-1, Error, "Maximum retry attempts (1) exceeded"); + assert!(!shows_empty_fallback(exhausted.conversation())); + + Ok(()) +} + #[cfg(feature = "code-mode")] #[tokio::test] async fn unadvertised_final_output_is_neither_approved_nor_executed() -> Result<()> { diff --git a/crates/goose/src/agents/state_machine/tests/tool_lifecycle.rs b/crates/goose/src/agents/state_machine/tests/tool_lifecycle.rs index d2ba89c06..cdabe7033 100644 --- a/crates/goose/src/agents/state_machine/tests/tool_lifecycle.rs +++ b/crates/goose/src/agents/state_machine/tests/tool_lifecycle.rs @@ -20,14 +20,21 @@ async fn basic_tool_calling() -> Result<()> { let (pipeline, api) = test_pipeline().await?; api.on("add one").call(ADD, value(1)); api.on("result: 1").reply("The total is 1"); + api.on("add a numeric string") + .call(ADD, json!({ "value": "4" })); + api.on("result: 5").reply("The total is 5"); api.on("hello").reply("hi there!"); - let result = pipeline.run(["add one", "hello"]).await?; + let result = pipeline + .run(["add one", "add a numeric string", "hello"]) + .await?; result.assert_message(2, ToolResponse, ""); result.assert_message(3, Agent, "The total is 1"); + result.assert_message(6, ToolResponse, "result: 5"); + result.assert_message(7, Agent, "The total is 5"); result.assert_message(-1, Agent, "hi there!"); - assert_eq!(api.call_count(), 3); + assert_eq!(api.call_count(), 5); Ok(()) } diff --git a/crates/goose/src/agents/subagent_handler.rs b/crates/goose/src/agents/subagent_handler.rs index c359a6d93..8e662ef4c 100644 --- a/crates/goose/src/agents/subagent_handler.rs +++ b/crates/goose/src/agents/subagent_handler.rs @@ -2,31 +2,22 @@ use crate::{ agents::{ final_output_tool::FinalOutputTool, state_machine::{trailing_error, MAX_TURNS_MESSAGE}, - subagent_task_config::TaskConfig, - Agent, AgentConfig, AgentEvent, GoosePlatform, SessionConfig, + Agent, AgentConfig, GoosePlatform, SessionConfig, }, config::permission::PermissionManager, - conversation::{ - message::{Message, MessageContent}, - Conversation, - }, + conversation::{message::Message, Conversation}, prompt_template::render_template, - recipe::Recipe, session::extension_data::{EnabledExtensionsState, ExtensionState}, session::{Session, SessionManager, SessionType}, }; use anyhow::{anyhow, Result}; use futures::future::BoxFuture; use futures::StreamExt; -use rmcp::model::{ErrorCode, ErrorData, Notification, Role, ServerNotification}; -#[expect(deprecated)] -use rmcp::model::{LoggingLevel, LoggingMessageNotificationParam}; +use rmcp::model::Role; use serde::Serialize; -use std::future::Future; -use std::pin::Pin; use std::sync::Arc; use tokio_util::sync::CancellationToken; -use tracing::{debug, info}; +use tracing::debug; #[derive(Serialize)] pub struct SubagentPromptContext { @@ -35,36 +26,6 @@ pub struct SubagentPromptContext { pub available_tools: String, } -type AgentMessagesFuture = - Pin)>> + Send>>; - -pub struct SubagentRunParams { - pub config: AgentConfig, - pub recipe: Recipe, - pub task_config: TaskConfig, - pub return_last_only: bool, - pub session_id: String, - pub cancellation_token: Option, - pub notification_tx: Option>, -} - -pub async fn run_subagent_task(params: SubagentRunParams) -> Result { - let return_last_only = params.return_last_only; - let (messages, final_output) = get_agent_messages(params).await.map_err(|e| { - ErrorData::new( - ErrorCode::INTERNAL_ERROR, - format!("Failed to execute task: {}", e), - None, - ) - })?; - - if let Some(output) = final_output { - return Ok(output); - } - - Ok(extract_response_text(&messages, return_last_only)) -} - pub(crate) async fn from_foreground_subagent_session( session_manager: Arc, session: &Session, @@ -104,7 +65,6 @@ pub(crate) async fn from_foreground_subagent_session( session_manager, PermissionManager::instance(), None, - session.goose_mode, true, GoosePlatform::GooseCli, ) @@ -133,7 +93,6 @@ pub(crate) async fn from_foreground_subagent_session( id: session_id.to_string(), schedule_id: None, max_turns: Some(max_turns as u32), - retry_config: recipe.retry.clone(), }; Ok((agent, session_config)) } @@ -264,187 +223,8 @@ fn failure_reason(messages: &[Message]) -> String { } } -fn extract_response_text(messages: &Conversation, return_last_only: bool) -> String { - if return_last_only { - messages - .messages() - .last() - .and_then(|message| { - message.content.iter().find_map(|content| match content { - crate::conversation::message::MessageContent::Text(text_content) => { - Some(text_content.text.clone()) - } - _ => None, - }) - }) - .unwrap_or_else(|| String::from("No text content in last message")) - } else { - let all_text_content: Vec = messages - .iter() - .flat_map(|message| { - message.content.iter().filter_map(|content| match content { - crate::conversation::message::MessageContent::Text(text_content) => { - Some(text_content.text.clone()) - } - crate::conversation::message::MessageContent::ToolResponse(tool_response) => { - if let Ok(result) = &tool_response.tool_result { - let texts: Vec = result - .content - .iter() - .filter_map(|content| { - if let rmcp::model::ContentBlock::Text(raw_text_content) = - content - { - Some(raw_text_content.text.clone()) - } else { - None - } - }) - .collect(); - if !texts.is_empty() { - Some(format!("Tool result: {}", texts.join("\n"))) - } else { - None - } - } else { - None - } - } - _ => None, - }) - }) - .collect(); - - all_text_content.join("\n") - } -} - pub const SUBAGENT_TOOL_REQUEST_TYPE: &str = "subagent_tool_request"; -fn get_agent_messages(params: SubagentRunParams) -> AgentMessagesFuture { - Box::pin(async move { - let SubagentRunParams { - config, - recipe, - task_config, - session_id, - cancellation_token, - notification_tx, - .. - } = params; - - let user_task = recipe - .prompt - .clone() - .unwrap_or_else(|| "Begin.".to_string()); - - let agent = Arc::new(Agent::with_config(config)); - - agent - .update_provider( - task_config.provider.clone(), - task_config.model_config.clone(), - &session_id, - ) - .await - .map_err(|e| anyhow!("Failed to set provider on sub agent: {}", e))?; - - for extension in &task_config.extensions { - if let Err(e) = agent.add_extension(extension.clone(), &session_id).await { - debug!( - "Failed to add extension '{}' to subagent: {}", - extension.name(), - e - ); - } - } - - let has_response_schema = recipe.response.is_some(); - let session_manager = &agent.config.session_manager; - session_manager - .update(&session_id) - .recipe(Some(recipe.clone())) - .apply() - .await?; - - let max_turns = task_config - .max_turns - .expect("TaskConfig always sets max_turns"); - let subagent_prompt = build_subagent_prompt(&agent, max_turns, &session_id).await?; - session_manager - .update(&session_id) - .system_prompt_override(Some(subagent_prompt)) - .apply() - .await?; - - let user_message = - Message::user().with_text(format!("Subagent ID: {session_id}\n\n{user_task}")); - let mut conversation = Conversation::new_unvalidated(vec![user_message.clone()]); - - if let Some(activities) = recipe.activities { - for activity in activities { - info!("Recipe activity: {}", activity); - } - } - let session_config = SessionConfig { - id: session_id.clone(), - schedule_id: None, - max_turns: task_config.max_turns.map(|v| v as u32), - retry_config: recipe.retry, - }; - - let mut stream = - crate::session_context::with_session_id(Some(session_id.to_string()), async { - agent - .reply( - user_message, - session_config, - crate::agents::state_machine::enabled(), - cancellation_token, - ) - .await - }) - .await - .map_err(|e| anyhow!("Failed to get reply from agent: {}", e))?; - - while let Some(message_result) = stream.next().await { - match message_result { - Ok(AgentEvent::Message(msg)) => { - if let Some(ref tx) = notification_tx { - for content in &msg.content { - if let Some(notif) = create_tool_notification(content, &session_id) { - if tx.send(notif).is_err() { - debug!( - "Notification receiver dropped for subagent {}", - session_id - ); - } - } - } - } - conversation.push(msg); - } - Ok(AgentEvent::Usage(_)) => {} - Ok(AgentEvent::MessageUsage { .. }) => {} - Ok(AgentEvent::McpNotification(_)) => {} - Ok(AgentEvent::HistoryReplaced(updated_conversation)) => { - conversation = updated_conversation; - } - Err(e) => { - tracing::error!("Error receiving message from subagent: {}", e); - break; - } - } - } - - let final_output = has_response_schema - .then(|| FinalOutputTool::successful_output(conversation.messages())) - .flatten(); - - Ok((conversation, final_output)) - }) -} - async fn build_subagent_prompt( agent: &Agent, max_turns: usize, @@ -469,83 +249,11 @@ async fn build_subagent_prompt( .map_err(|e| anyhow!("Failed to render subagent system prompt: {}", e)) } -#[expect(deprecated)] -pub fn create_tool_notification( - content: &MessageContent, - subagent_id: &str, -) -> Option { - if let MessageContent::ToolRequest(req) = content { - let tool_call = req.tool_call.as_ref().ok()?; - - Some(ServerNotification::LoggingMessageNotification( - Notification::new( - LoggingMessageNotificationParam::new( - LoggingLevel::Info, - serde_json::json!({ - "type": SUBAGENT_TOOL_REQUEST_TYPE, - "subagent_id": subagent_id, - "tool_call": { - "name": tool_call.name, - "arguments": tool_call.arguments - } - }), - ) - .with_logger(format!("subagent:{}", subagent_id)), - ), - )) - } else { - None - } -} - #[cfg(test)] mod tests { - use super::{create_tool_notification, failure_reason, SUBAGENT_TOOL_REQUEST_TYPE}; + use super::failure_reason; use crate::agents::state_machine::MAX_TURNS_MESSAGE; - use crate::conversation::message::{Message, MessageContent}; - use rmcp::model::{CallToolRequestParams, ServerNotification}; - use serde_json::json; - - #[test] - #[expect(deprecated)] - fn create_tool_notification_for_tool_request() { - let tool_call = CallToolRequestParams::new("developer__shell".to_string()) - .with_arguments(json!({"command": "ls"}).as_object().unwrap().clone()); - let content = MessageContent::tool_request("req1", Ok(tool_call)); - let notification = - create_tool_notification(&content, "session_1").expect("expected notification"); - - let ServerNotification::LoggingMessageNotification(log_notif) = notification else { - panic!("expected logging notification"); - }; - let data = log_notif - .params - .data - .as_object() - .expect("expected object data"); - assert_eq!( - data.get("type").and_then(|v| v.as_str()), - Some(SUBAGENT_TOOL_REQUEST_TYPE) - ); - assert_eq!( - data.get("subagent_id").and_then(|v| v.as_str()), - Some("session_1") - ); - let tool_call = data - .get("tool_call") - .and_then(|v| v.as_object()) - .expect("expected tool_call object"); - assert_eq!( - tool_call.get("name").and_then(|v| v.as_str()), - Some("developer__shell") - ); - } - - #[test] - fn create_tool_notification_ignores_non_tool_request() { - let content = MessageContent::text("hello"); - assert!(create_tool_notification(&content, "session_1").is_none()); - } + use crate::conversation::message::Message; #[test] fn failure_reason_describes_how_the_subagent_stopped() { diff --git a/crates/goose/src/agents/tool_confirmation_router.rs b/crates/goose/src/agents/tool_confirmation_router.rs deleted file mode 100644 index 31283424b..000000000 --- a/crates/goose/src/agents/tool_confirmation_router.rs +++ /dev/null @@ -1,182 +0,0 @@ -use std::collections::HashMap; - -use tokio::sync::{oneshot, Mutex}; -use tracing::warn; - -use crate::permission::PermissionConfirmation; - -pub(super) struct ToolConfirmationRouter { - pending: Mutex>>, -} - -impl ToolConfirmationRouter { - pub(super) fn new() -> Self { - Self { - pending: Mutex::new(HashMap::new()), - } - } - - pub(super) async fn register( - &self, - session_id: String, - request_id: String, - ) -> oneshot::Receiver { - let (tx, rx) = oneshot::channel(); - let mut pending = self.pending.lock().await; - pending.retain(|_, sender| !sender.is_closed()); - pending.insert((session_id, request_id), tx); - rx - } - - pub(super) async fn deliver( - &self, - session_id: &str, - request_id: &str, - confirmation: PermissionConfirmation, - ) -> bool { - let key = (session_id.to_string(), request_id.to_string()); - if let Some(tx) = self.pending.lock().await.remove(&key) { - if tx.send(confirmation).is_err() { - warn!( - request_id = %request_id, - "Confirmation receiver was dropped (task cancelled)" - ); - false - } else { - true - } - } else { - false - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::permission::permission_confirmation::PrincipalType; - use crate::permission::Permission; - - fn test_confirmation() -> PermissionConfirmation { - PermissionConfirmation { - principal_type: PrincipalType::Tool, - permission: Permission::AllowOnce, - } - } - - #[tokio::test] - async fn test_register_then_deliver() { - let router = ToolConfirmationRouter::new(); - let rx = router - .register("session_1".to_string(), "req_1".to_string()) - .await; - assert!( - router - .deliver("session_1", "req_1", test_confirmation()) - .await - ); - let confirmation = rx.await.unwrap(); - assert_eq!(confirmation.permission, Permission::AllowOnce); - } - - #[tokio::test] - async fn test_deliver_unknown_request() { - let router = ToolConfirmationRouter::new(); - assert!( - !router - .deliver("session_1", "unknown", test_confirmation()) - .await - ); - } - - #[tokio::test] - async fn test_request_cannot_be_delivered_from_another_session() { - let router = ToolConfirmationRouter::new(); - let _rx = router - .register("session_1".to_string(), "req_1".to_string()) - .await; - - assert!( - !router - .deliver("session_2", "req_1", test_confirmation()) - .await - ); - assert_eq!(router.pending.lock().await.len(), 1); - } - - #[tokio::test] - async fn test_cancelled_receiver() { - let router = ToolConfirmationRouter::new(); - let rx = router - .register("session_1".to_string(), "req_1".to_string()) - .await; - drop(rx); // simulate task cancellation - assert!( - !router - .deliver("session_1", "req_1", test_confirmation()) - .await - ); - } - - #[tokio::test] - async fn test_stale_entries_pruned_on_register() { - let router = ToolConfirmationRouter::new(); - let rx = router - .register("session_1".to_string(), "req_1".to_string()) - .await; - drop(rx); // simulate task cancellation — entry is now stale - - assert_eq!(router.pending.lock().await.len(), 1); - - let _rx2 = router - .register("session_1".to_string(), "req_2".to_string()) - .await; - assert_eq!(router.pending.lock().await.len(), 1); // only req_2 remains - assert!(router - .pending - .lock() - .await - .contains_key(&("session_1".to_string(), "req_2".to_string()))); - } - - #[tokio::test] - async fn test_concurrent_requests_out_of_order() { - use std::sync::Arc; - - let router = Arc::new(ToolConfirmationRouter::new()); - - // Register two requests - let rx1 = router - .register("session_1".to_string(), "req_1".to_string()) - .await; - let rx2 = router - .register("session_1".to_string(), "req_2".to_string()) - .await; - - // Deliver in reverse order - assert!( - router - .deliver( - "session_1", - "req_2", - PermissionConfirmation { - principal_type: PrincipalType::Tool, - permission: Permission::DenyOnce, - } - ) - .await - ); - assert_eq!(router.pending.lock().await.len(), 1); - assert!( - router - .deliver("session_1", "req_1", test_confirmation()) - .await - ); - assert_eq!(router.pending.lock().await.len(), 0); - - let c1 = rx1.await.unwrap(); - assert_eq!(c1.permission, Permission::AllowOnce); - let c2 = rx2.await.unwrap(); - assert_eq!(c2.permission, Permission::DenyOnce); - } -} diff --git a/crates/goose/src/agents/tool_execution.rs b/crates/goose/src/agents/tool_execution.rs index a3a50d0a4..fa45529e0 100644 --- a/crates/goose/src/agents/tool_execution.rs +++ b/crates/goose/src/agents/tool_execution.rs @@ -1,22 +1,16 @@ -use async_stream::try_stream; -use futures::stream::{self, BoxStream}; use futures::{Stream, StreamExt}; use rmcp::model::CallToolResult; -use std::collections::HashMap; use std::future::Future; use std::pin::Pin; use std::sync::Arc; use tokio::sync::mpsc; -use tokio_util::sync::CancellationToken; use std::path::PathBuf; use crate::agents::container::Container; -use crate::config::permission::PermissionLevel; use crate::conversation::message::Message; use crate::mcp_utils::ToolResult; -use crate::permission::Permission; -use rmcp::model::{ContentBlock, ServerNotification}; +use rmcp::model::ServerNotification; #[derive(Clone)] pub(crate) struct ToolCallNotificationEmitter { @@ -40,7 +34,6 @@ pub struct ToolCallContext { pub session_id: String, pub working_dir: Option, pub tool_call_request_id: Option, - pub(crate) from_state_machine: bool, container: Option, extension_lease: Option>, notification_emitter: Option, @@ -56,7 +49,6 @@ impl ToolCallContext { session_id, working_dir, tool_call_request_id, - from_state_machine: false, container: None, extension_lease: None, notification_emitter: None, @@ -118,9 +110,6 @@ impl From> for ToolCallResult { use crate::agents::extension_manager::ExtensionLease; use crate::agents::Agent; -use crate::conversation::message::ToolRequest; -use crate::session::Session; -use crate::tool_inspection::get_security_finding_id_from_results; pub(super) enum ToolStreamItem { ActionRequired(Message), @@ -131,15 +120,6 @@ pub(super) enum ToolStreamItem { pub(super) type ToolStream = Pin>> + Send>>; -pub(super) struct ApprovalToolContext<'a> { - pub lease: &'a ExtensionLease, - pub tool_futures: &'a mut Vec<(String, ToolStream)>, - pub request_to_response_map: &'a mut HashMap, - pub cancellation_token: Option, - pub session: &'a Session, - pub inspection_results: &'a [crate::tool_inspection::InspectionResult], -} - pub(super) fn tool_stream(rx: S, action_required_rx: A, done: F) -> ToolStream where S: Stream + Send + Unpin + 'static, @@ -181,105 +161,4 @@ pub const CHAT_MODE_TOOL_SKIPPED_RESPONSE: &str = "Let the user know the tool ca 2. **Outline Steps** - Break down the steps.\n \ If needed, adjust the explanation based on user preferences or questions."; -impl Agent { - pub(super) fn handle_approval_tool_requests<'a>( - &'a self, - tool_requests: &'a [ToolRequest], - context: ApprovalToolContext<'a>, - ) -> BoxStream<'a, anyhow::Result> { - let ApprovalToolContext { - lease, - tool_futures, - request_to_response_map, - cancellation_token, - session, - inspection_results, - } = context; - try_stream! { - for request in tool_requests.iter() { - if let Ok(tool_call) = request.tool_call.clone() { - let security_message = inspection_results.iter() - .find(|result| result.tool_request_id == request.id) - .and_then(|result| { - if let crate::tool_inspection::InspectionAction::RequireApproval(Some(message)) = &result.action { - Some(message.clone()) - } else { - None - } - }); - - let confirmation_rx = self - .tool_confirmation_router - .register(session.id.clone(), request.id.clone()) - .await; - - let action_required_msg = Message::assistant() - .with_action_required( - request.id.clone(), - tool_call.name.to_string().clone(), - tool_call.arguments.clone().unwrap_or_default(), - security_message, - ) - .user_only(); - yield action_required_msg; - - let confirmation = confirmation_rx.await - .map_err(|_| anyhow::anyhow!("Confirmation channel closed for request {}", request.id))?; - - if let Some(finding_id) = get_security_finding_id_from_results(&request.id, inspection_results) { - let action = match confirmation.permission { - Permission::AllowOnce | Permission::AlwaysAllow => "ALLOW", - _ => "BLOCK", - }; - tracing::info!( - monotonic_counter.goose.prompt_injection_user_decisions = 1, - security.event_type = "user_decision", - security.action = action, - security.finding_id = %finding_id, - tool.request_id = %request.id, - user.decision = ?confirmation.permission, - "security finding: user decision" - ); - } - - if confirmation.permission == Permission::AllowOnce || confirmation.permission == Permission::AlwaysAllow { - let (req_id, tool_result) = self.dispatch_tool_call_on(lease, tool_call.clone(), request.id.clone(), cancellation_token.clone(), session).await; - - tool_futures.push((req_id, match tool_result { - Ok(result) => tool_stream( - result.notification_stream.unwrap_or_else(|| Box::new(stream::empty())), - result.action_required_stream.unwrap_or_else(|| Box::new(stream::empty())), - result.result, - ), - Err(e) => tool_stream( - Box::new(stream::empty()), - Box::new(stream::empty()), - futures::future::ready(Err(e)), - ), - })); - - if confirmation.permission == Permission::AlwaysAllow { - self.tool_inspection_manager - .update_permission_manager(&tool_call.name, PermissionLevel::AlwaysAllow) - .await; - } - } else { - if let Some(response) = request_to_response_map.get_mut(&request.id) { - response.add_tool_response_with_metadata( - request.id.clone(), - Ok(CallToolResult::error(vec![ContentBlock::text(DECLINED_RESPONSE)])), - request.metadata.as_ref(), - ); - } - - if confirmation.permission == Permission::AlwaysDeny { - self.tool_inspection_manager - .update_permission_manager(&tool_call.name, PermissionLevel::NeverAllow) - .await; - } - } - } - } - }.boxed() - } -} +impl Agent {} diff --git a/crates/goose/src/agents/types.rs b/crates/goose/src/agents/types.rs index 998079fdf..552cd088c 100644 --- a/crates/goose/src/agents/types.rs +++ b/crates/goose/src/agents/types.rs @@ -70,9 +70,6 @@ pub struct SessionConfig { pub schedule_id: Option, /// Maximum number of turns (iterations) allowed without user input pub max_turns: Option, - /// Retry configuration for automated validation and recovery - #[serde(skip_serializing_if = "Option::is_none")] - pub retry_config: Option, } #[cfg(test)] diff --git a/crates/goose/src/execution/manager.rs b/crates/goose/src/execution/manager.rs index d2d583ff0..357f2ca49 100644 --- a/crates/goose/src/execution/manager.rs +++ b/crates/goose/src/execution/manager.rs @@ -67,13 +67,11 @@ impl AgentManager { let max_sessions = config .get_goose_max_active_agents() .unwrap_or(DEFAULT_MAX_SESSION); - let default_mode = config.get_goose_mode().unwrap_or_default(); let session_manager = Arc::new(SessionManager::instance()); let agent_config = AgentConfig::new( session_manager, PermissionManager::instance(), None, - default_mode, config.get_goose_disable_session_naming().unwrap_or(false), GoosePlatform::GooseDesktop, ); @@ -177,19 +175,7 @@ impl AgentManager { } } - let mut mode = self.agent_config.goose_mode; - if let Ok(session) = self - .agent_config - .session_manager - .get_session(session_id, false) - .await - { - mode = session.goose_mode; - info!(goose_mode = %mode, session_id = %session_id, "Session loaded"); - } - let mut config = self.agent_config.clone(); - config.goose_mode = mode; config.mcp_host_info = runtime_context.mcp_host_info; config.use_login_shell_path = runtime_context.use_login_shell_path; config.session_name_update_tx = runtime_context.session_name_update_tx; @@ -368,7 +354,6 @@ mod tests { use tempfile::TempDir; use goose_test_support::McpFixture; - use test_case::test_case; use tokio::sync::Barrier; use crate::agents::extension::{Envs, ExtensionConfig}; @@ -385,7 +370,6 @@ mod tests { session_manager, PermissionManager::instance(), None, - GooseMode::default(), false, GoosePlatform::GooseDesktop, ); @@ -610,7 +594,6 @@ mod tests { session_manager, PermissionManager::instance(), None, - GooseMode::default(), false, GoosePlatform::GooseDesktop, ); @@ -637,29 +620,6 @@ mod tests { assert!(locks.contains_key("c")); } - #[test_case(GooseMode::Approve ; "approve")] - #[test_case(GooseMode::Chat ; "chat")] - #[test_case(GooseMode::SmartApprove ; "smart_approve")] - #[tokio::test] - async fn test_agent_inherits_session_mode(mode: GooseMode) { - let temp_dir = TempDir::new().unwrap(); - let manager = create_test_manager(&temp_dir).await; - - let session = manager - .session_manager() - .create_session( - temp_dir.path().to_path_buf(), - "test".into(), - crate::session::SessionType::User, - mode, - ) - .await - .unwrap(); - - let agent = manager.get_or_create_agent(session.id).await.unwrap(); - assert_eq!(agent.goose_mode().await, mode); - } - #[tokio::test] async fn test_final_output_tool_restored_after_lru_eviction() { use crate::agents::final_output_tool::FINAL_OUTPUT_TOOL_NAME; @@ -672,7 +632,6 @@ mod tests { Arc::clone(&session_manager), PermissionManager::instance(), None, - GooseMode::default(), false, GoosePlatform::GooseDesktop, ); @@ -753,36 +712,4 @@ mod tests { "final_output_tool must be restored after LRU eviction" ); } - - #[tokio::test] - async fn test_session_mode_isolation() { - let temp_dir = TempDir::new().unwrap(); - let manager = create_test_manager(&temp_dir).await; - let sm = manager.session_manager(); - - let s1 = sm - .create_session( - temp_dir.path().to_path_buf(), - "s1".into(), - crate::session::SessionType::User, - GooseMode::Approve, - ) - .await - .unwrap(); - let s2 = sm - .create_session( - temp_dir.path().to_path_buf(), - "s2".into(), - crate::session::SessionType::User, - GooseMode::Auto, - ) - .await - .unwrap(); - - let a1 = manager.get_or_create_agent(s1.id).await.unwrap(); - let a2 = manager.get_or_create_agent(s2.id).await.unwrap(); - - assert_eq!(a1.goose_mode().await, GooseMode::Approve); - assert_eq!(a2.goose_mode().await, GooseMode::Auto); - } } diff --git a/crates/goose/src/gateway/handler.rs b/crates/goose/src/gateway/handler.rs index 8a9f81bca..5beaf33c0 100644 --- a/crates/goose/src/gateway/handler.rs +++ b/crates/goose/src/gateway/handler.rs @@ -543,16 +543,10 @@ impl GatewayHandler { id: session_id.to_string(), schedule_id: None, max_turns: Some(max_turns), - retry_config: None, }; let mut stream = match agent - .reply( - user_message, - session_config, - crate::agents::state_machine::enabled(), - Some(cancel_for_reply), - ) + .reply(user_message, session_config, Some(cancel_for_reply)) .await { Ok(s) => s, diff --git a/crates/goose/src/scheduler/full.rs b/crates/goose/src/scheduler/full.rs index d28c3d33b..f2e6c719b 100644 --- a/crates/goose/src/scheduler/full.rs +++ b/crates/goose/src/scheduler/full.rs @@ -861,7 +861,6 @@ async fn execute_job( session_manager, PermissionManager::instance(), None, - GooseMode::Auto, true, GoosePlatform::GooseCli, )); @@ -974,16 +973,10 @@ async fn execute_job( id: session.id.clone(), schedule_id: Some(job.id.clone()), max_turns: None, - retry_config: None, }; let stream = agent - .reply( - user_message, - session_config, - crate::agents::state_machine::enabled(), - Some(cancel_token.clone()), - ) + .reply(user_message, session_config, Some(cancel_token.clone())) .await?; use futures::StreamExt; diff --git a/crates/goose/src/session/session_manager.rs b/crates/goose/src/session/session_manager.rs index 649e13340..cac8564d3 100644 --- a/crates/goose/src/session/session_manager.rs +++ b/crates/goose/src/session/session_manager.rs @@ -2899,94 +2899,33 @@ impl SessionStorage { use crate::conversation::message::MessageContent; let pool = self.pool().await?; - let rows = sqlx::query_as::<_, (Option, String)>( - "SELECT message_id, content_json FROM messages \ + let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?; + let rows = sqlx::query_as::<_, (i64, String)>( + "SELECT id, content_json FROM messages \ WHERE session_id = ? \ ORDER BY id DESC \ LIMIT 100", ) .bind(session_id) - .fetch_all(pool) - .await?; - - for (message_id, content_json) in rows { - let content: Vec = serde_json::from_str(&content_json)?; - let contains_tool_request = content.iter().any(|block| { - matches!( - block, - MessageContent::ToolRequest(tool_request) - if tool_request.id == tool_call_id - ) - }); - if contains_tool_request { - let Some(message_id) = message_id else { - return Ok(()); - }; - return self - .update_tool_request_meta_by_message_id( - session_id, - &message_id, - tool_call_id, - patch, - ) - .await; - } - } - - Ok(()) - } - - /// Patch `tool_meta` on a specific `ToolRequest` within a stored message's - /// `content_json`. Finds the row(s) with matching `message_id`, scans each - /// row's content for a `ToolRequest` with the given `tool_call_id`, and - /// merges `patch` into its `tool_meta`. Uses `BEGIN IMMEDIATE` so - /// concurrent writers serialize correctly. - async fn update_tool_request_meta_by_message_id( - &self, - session_id: &str, - message_id: &str, - tool_call_id: &str, - patch: serde_json::Value, - ) -> Result<()> { - use crate::conversation::message::MessageContent; - - let pool = self.pool().await?; - let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?; - - let rows = sqlx::query_as::<_, (i64, String)>( - "SELECT id, content_json FROM messages \ - WHERE session_id = ? AND message_id = ? \ - ORDER BY id ASC", - ) - .bind(session_id) - .bind(message_id) .fetch_all(&mut *tx) .await?; for (row_id, content_json) in rows { let mut content: Vec = serde_json::from_str(&content_json)?; - let mut found = false; - for block in &mut content { - if let MessageContent::ToolRequest(tr) = block { - if tr.id == tool_call_id { - tr.tool_meta = Some(merge_tool_meta(tr.tool_meta.take(), &patch)); - found = true; - break; - } - } - } - if !found { + let Some(tool_request) = content.iter_mut().find_map(|block| match block { + MessageContent::ToolRequest(request) if request.id == tool_call_id => Some(request), + _ => None, + }) else { continue; - } + }; + tool_request.tool_meta = Some(merge_tool_meta(tool_request.tool_meta.take(), &patch)); - let updated_json = serde_json::to_string(&content)?; sqlx::query("UPDATE messages SET content_json = ? WHERE id = ?") - .bind(updated_json) + .bind(serde_json::to_string(&content)?) .bind(row_id) .execute(&mut *tx) .await?; - tx.commit().await?; - return Ok(()); + break; } tx.commit().await?; @@ -3402,6 +3341,54 @@ mod tests { assert_eq!(texts, ["appended first", "built first"]); } + #[tokio::test] + async fn tool_request_meta_patches_the_latest_reused_tool_call() { + let temp_dir = TempDir::new().unwrap(); + let sm = SessionManager::new(temp_dir.path().to_path_buf()); + let session = sm + .create_session( + PathBuf::from("/tmp/test"), + "Reused ids".to_string(), + SessionType::User, + GooseMode::default(), + ) + .await + .unwrap(); + let tool_call = || { + Message::assistant() + .with_id("chatcmpl-recorded") + .with_tool_request( + "call_0", + Ok(rmcp::model::CallToolRequestParams::new("tool")), + ) + }; + sm.add_message(&session.id, &tool_call()).await.unwrap(); + sm.add_message(&session.id, &tool_call()).await.unwrap(); + + sm.update_tool_request_meta( + &session.id, + "call_0", + serde_json::json!({ "patched": true }), + ) + .await + .unwrap(); + + let conversation = sm + .get_session(&session.id, true) + .await + .unwrap() + .conversation + .expect("session has a conversation"); + let patched: Vec = conversation + .messages() + .iter() + .flat_map(|message| &message.content) + .filter_map(MessageContent::as_tool_request) + .map(|request| request.tool_meta.is_some()) + .collect(); + assert_eq!(patched, [false, true]); + } + #[tokio::test] async fn test_messages_session_created_index_avoids_disk_sort() { use sqlx::Row; diff --git a/crates/goose/src/tool_call_labels.rs b/crates/goose/src/tool_call_labels.rs index 47b1544b1..2a3ea84cf 100644 --- a/crates/goose/src/tool_call_labels.rs +++ b/crates/goose/src/tool_call_labels.rs @@ -484,7 +484,6 @@ mod tests { session_manager.clone(), permission_manager, None, - GooseMode::Auto, true, GoosePlatform::GooseCli, )); @@ -558,7 +557,6 @@ mod tests { session_manager.clone(), permission_manager, None, - GooseMode::Auto, true, GoosePlatform::GooseCli, )); @@ -714,7 +712,6 @@ mod tests { session_manager.clone(), permission_manager, None, - GooseMode::Auto, true, GoosePlatform::GooseCli, )); @@ -759,7 +756,6 @@ mod tests { session_manager.clone(), permission_manager, None, - GooseMode::Auto, true, GoosePlatform::GooseCli, )); @@ -804,7 +800,6 @@ mod tests { session_manager.clone(), permission_manager, None, - GooseMode::Auto, true, GoosePlatform::GooseCli, )); diff --git a/crates/goose/tests/acp_custom_requests_test.rs b/crates/goose/tests/acp_custom_requests_test.rs index c4275be1c..f9be293f6 100644 --- a/crates/goose/tests/acp_custom_requests_test.rs +++ b/crates/goose/tests/acp_custom_requests_test.rs @@ -205,8 +205,7 @@ fn test_live_voice_availability_is_bound_to_an_accessible_main_session() { conn.cx(), "_goose/unstable/session/live-voice/availability", serde_json::json!({ - "sessionId": session.session_id().0, - "_meta": { "goose": { "unrolledAgentLoop": true } } + "sessionId": session.session_id().0 }), ) .await @@ -237,28 +236,11 @@ fn test_live_voice_availability_is_bound_to_an_accessible_main_session() { .await .unwrap(); - let legacy_loop = send_custom( - conn.cx(), - "_goose/unstable/session/live-voice/availability", - serde_json::json!({ - "sessionId": session.session_id().0, - "_meta": { "goose": { "unrolledAgentLoop": false } } - }), - ) - .await - .unwrap(); - assert_eq!(legacy_loop["status"], "unavailable"); - assert_eq!( - legacy_loop["message"], - "Live voice is unavailable while Use Legacy Agent Loop is enabled" - ); - let response = send_custom( conn.cx(), "_goose/unstable/session/live-voice/availability", serde_json::json!({ - "sessionId": session.session_id().0, - "_meta": { "goose": { "unrolledAgentLoop": true } } + "sessionId": session.session_id().0 }), ) .await @@ -270,8 +252,7 @@ fn test_live_voice_availability_is_bound_to_an_accessible_main_session() { conn.cx(), "_goose/unstable/session/live-voice/availability", serde_json::json!({ - "sessionId": "not-loaded-on-this-connection", - "_meta": { "goose": { "unrolledAgentLoop": true } } + "sessionId": "not-loaded-on-this-connection" }), ) .await; diff --git a/crates/goose/tests/acp_server_test.rs b/crates/goose/tests/acp_server_test.rs index 998b03185..37304fa62 100644 --- a/crates/goose/tests/acp_server_test.rs +++ b/crates/goose/tests/acp_server_test.rs @@ -1212,32 +1212,10 @@ fn test_prompt_mcp() { run_test(async { run_prompt_mcp::().await }); } -/// Selects the agent loop until dropped. Only use inside `run_test`: it holds the -/// ACP test lock, so no other test in this binary observes the override. -struct AgentLoopOverride(Option); - -impl AgentLoopOverride { - fn new(state_machine: bool) -> Self { - let previous = std::env::var_os("GOOSE_STATE_MACHINE"); - std::env::set_var("GOOSE_STATE_MACHINE", if state_machine { "1" } else { "0" }); - Self(previous) - } -} - -impl Drop for AgentLoopOverride { - fn drop(&mut self) { - match self.0.take() { - Some(previous) => std::env::set_var("GOOSE_STATE_MACHINE", previous), - None => std::env::remove_var("GOOSE_STATE_MACHINE"), - } - } -} - /// Two provider calls separated by a tool call. The canned responses report 2469 /// and then 2631 total tokens, so 2469 can only arrive in an update sent while /// the prompt is still running. -async fn assert_usage_updates_during_prompt(state_machine: bool) { - let _agent_loop = AgentLoopOverride::new(state_machine); +async fn assert_usage_updates_during_prompt() { let prompt = "Use the get_code tool and output only its result."; let mcp = McpFixture::new().await; let openai = OpenAiFixture::new( @@ -1280,22 +1258,12 @@ async fn assert_usage_updates_during_prompt(state_machine: bool) { ); tokio::time::sleep(std::time::Duration::from_millis(20)).await; } - assert_eq!( - used, - [2469, 2631, 2631], - "state_machine={state_machine}, agent text: {}", - output.text - ); + assert_eq!(used, [2469, 2631, 2631], "agent text: {}", output.text); } #[test] -fn test_prompt_usage_updates_during_turn_legacy_loop() { - run_test(async { assert_usage_updates_during_prompt(false).await }); -} - -#[test] -fn test_prompt_usage_updates_during_turn_state_machine() { - run_test(async { assert_usage_updates_during_prompt(true).await }); +fn test_prompt_usage_updates_during_turn() { + run_test(async { assert_usage_updates_during_prompt().await }); } #[test] diff --git a/crates/goose/tests/agent.rs b/crates/goose/tests/agent.rs index fedeaa149..779ed7f44 100644 --- a/crates/goose/tests/agent.rs +++ b/crates/goose/tests/agent.rs @@ -20,7 +20,7 @@ mod tests { use goose::agents::ExtensionConfig; use goose::agents::{AgentConfig, ScheduleTool}; use goose::config::permission::PermissionManager; - use goose::config::GooseMode; + use goose::scheduler::{ScheduledJob, SchedulerError, ValidatedScheduleRecipe}; use goose::scheduler_trait::SchedulerTrait; use goose::session::{Session, SessionManager}; @@ -141,7 +141,7 @@ mod tests { }, None, None, - None, + "test-session-id", ) .await .unwrap(); @@ -247,7 +247,6 @@ mod tests { session_manager, permission_manager, Some(mock_scheduler), - GooseMode::Auto, false, GoosePlatform::GooseCli, ); @@ -291,7 +290,6 @@ mod tests { session_manager, permission_manager, Some(mock_scheduler), - GooseMode::Auto, false, GoosePlatform::GooseCli, ); @@ -349,7 +347,6 @@ mod tests { session_manager, permission_manager, Some(mock_scheduler), - GooseMode::Auto, false, GoosePlatform::GooseCli, ); @@ -428,38 +425,7 @@ mod tests { #[cfg(test)] mod retry_tests { use super::*; - use goose::agents::types::{RetryConfig, SuccessCheck}; - - #[tokio::test] - async fn test_retry_success_check_execution() -> Result<()> { - use goose::agents::retry::execute_success_checks; - - let retry_config = RetryConfig { - max_retries: 3, - checks: vec![], - on_failure: None, - timeout_seconds: Some(30), - on_failure_timeout_seconds: Some(60), - }; - - let success_checks = vec![SuccessCheck::Shell { - command: "echo 'test'".to_string(), - }]; - - let result = execute_success_checks(&success_checks, &retry_config).await; - assert!(result.is_ok(), "Success check should pass"); - assert!(result.unwrap(), "Command should succeed"); - - let fail_checks = vec![SuccessCheck::Shell { - command: "false".to_string(), - }]; - - let result = execute_success_checks(&fail_checks, &retry_config).await; - assert!(result.is_ok(), "Success check execution should not error"); - assert!(!result.unwrap(), "Command should fail"); - - Ok(()) - } + use goose::agents::types::RetryConfig; #[tokio::test] async fn test_retry_logic_with_validation_errors() -> Result<()> { @@ -482,24 +448,6 @@ mod tests { Ok(()) } - - #[tokio::test] - async fn test_retry_attempts_counter_reset() -> Result<()> { - let agent = Agent::new(); - - agent.reset_retry_attempts().await; - let initial_attempts = agent.get_retry_attempts().await; - assert_eq!(initial_attempts, 0); - - let new_attempts = agent.increment_retry_attempts().await; - assert_eq!(new_attempts, 1); - - agent.reset_retry_attempts().await; - let reset_attempts = agent.get_retry_attempts().await; - assert_eq!(reset_attempts, 0); - - Ok(()) - } } #[cfg(test)] @@ -608,17 +556,9 @@ mod tests { id: session_id.clone(), schedule_id: None, max_turns: Some(1), - retry_config: None, }; - let reply_stream = agent - .reply( - user_message, - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; + let reply_stream = agent.reply(user_message, session_config, None).await?; tokio::pin!(reply_stream); let mut responses = Vec::new(); @@ -672,192 +612,6 @@ mod tests { } } - #[cfg(test)] - mod unparseable_tool_call_tests { - use super::*; - use async_trait::async_trait; - use goose::agents::{AgentConfig, SessionConfig}; - use goose::config::permission::PermissionManager; - use goose::config::GooseMode; - use goose::conversation::message::{Message, MessageContent}; - use goose::providers::base::{ - stream_from_single_message, MessageStream, Provider, ProviderDef, ProviderMetadata, - }; - use goose::session::session_manager::SessionType; - use goose::session::SessionManager; - use goose_providers::conversation::token_usage::{ProviderUsage, Usage}; - use goose_providers::errors::ProviderError; - use goose_providers::model::ModelConfig; - use rmcp::model::{ErrorCode, ErrorData, Tool}; - use std::path::PathBuf; - use std::sync::atomic::{AtomicUsize, Ordering}; - use tempfile::TempDir; - - /// First turn returns a tool request that failed to parse (mirroring what - /// the decoders emit for non-object arguments), subsequent turns return - /// plain text so the loop can finish. - struct UnparseableToolProvider { - call_count: AtomicUsize, - } - - impl UnparseableToolProvider { - fn new() -> Self { - Self { - call_count: AtomicUsize::new(0), - } - } - } - - impl goose::providers::base::ProviderDescriptor for UnparseableToolProvider { - fn metadata() -> ProviderMetadata { - ProviderMetadata { - name: "mock-unparseable".to_string(), - display_name: "Mock Unparseable Provider".to_string(), - description: "Mock provider for unparseable tool call tests".to_string(), - default_model: "mock-model".to_string(), - known_models: vec![], - model_doc_link: "".to_string(), - config_keys: vec![], - setup_steps: vec![], - setup: None, - deprecated: None, - } - } - } - - impl ProviderDef for UnparseableToolProvider { - type Provider = Self; - - fn from_env( - _extensions: Vec, - _tls_config: Option, - ) -> futures::future::BoxFuture<'static, anyhow::Result> { - Box::pin(async { Ok(Self::new()) }) - } - } - - #[async_trait] - impl Provider for UnparseableToolProvider { - async fn stream( - &self, - _model_config: &ModelConfig, - _system_prompt: &str, - _messages: &[Message], - _tools: &[Tool], - ) -> Result { - let n = self.call_count.fetch_add(1, Ordering::SeqCst); - let message = if n == 0 { - let error = ErrorData::new( - ErrorCode::INVALID_PARAMS, - "Tool arguments must be a JSON object".to_string(), - None, - ); - Message::assistant().with_tool_request("call_bad", Err(error)) - } else { - Message::assistant().with_text("Recovered after the bad tool call.") - }; - - let usage = ProviderUsage::new( - "mock-model".to_string(), - Usage::new(Some(10), Some(5), Some(15)), - ); - Ok(stream_from_single_message(message, usage)) - } - - fn get_name(&self) -> &str { - "mock-unparseable" - } - } - - /// An unparseable tool call should be fed back to the model as a tool - /// response error so it can retry, rather than terminating the run. - #[tokio::test] - async fn test_unparseable_tool_call_feeds_back_and_continues() -> Result<()> { - let temp_dir = TempDir::new().unwrap(); - let data_dir = temp_dir.path().to_path_buf(); - let session_manager = Arc::new(SessionManager::new(data_dir.clone())); - let agent = Agent::with_config(AgentConfig::new( - session_manager.clone(), - Arc::new(PermissionManager::new(data_dir)), - None, - GooseMode::default(), - true, - GoosePlatform::GooseCli, - )); - let provider = Arc::new(UnparseableToolProvider::new()); - - let session = session_manager - .create_session( - PathBuf::default(), - "unparseable-tool-test".to_string(), - SessionType::Hidden, - GooseMode::default(), - ) - .await?; - - agent - .update_provider( - provider.clone(), - ModelConfig::new("mock-model"), - &session.id, - ) - .await?; - - let session_config = SessionConfig { - id: session.id, - schedule_id: None, - max_turns: Some(5), - retry_config: None, - }; - - let reply_stream = agent - .reply( - Message::user().with_text("Hello"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; - tokio::pin!(reply_stream); - - let mut saw_tool_response_error = false; - let mut saw_recovery_text = false; - while let Some(event) = reply_stream.next().await { - if let Ok(AgentEvent::Message(message)) = event { - for content in &message.content { - match content { - MessageContent::ToolResponse(response) - if response.id == "call_bad" && response.tool_result.is_err() => - { - saw_tool_response_error = true; - } - MessageContent::Text(text) - if text.text.contains("Recovered after the bad tool call") => - { - saw_recovery_text = true; - } - _ => {} - } - } - } - } - - assert!( - saw_tool_response_error, - "expected an error tool response fed back to the model for the unparseable call" - ); - assert!( - saw_recovery_text, - "expected the loop to continue to a second provider turn instead of terminating" - ); - assert!( - provider.call_count.load(Ordering::SeqCst) >= 2, - "provider should have been called again after the bad tool call" - ); - Ok(()) - } - } - #[cfg(test)] mod tool_pair_summarization_tests { use super::*; @@ -970,7 +724,6 @@ mod tests { Arc::clone(&session_manager), Arc::new(PermissionManager::new(temp_dir.path().join("config"))), None, - GooseMode::Auto, true, GoosePlatform::GooseCli, )); @@ -1027,17 +780,9 @@ mod tests { id: session.id.clone(), schedule_id: None, max_turns: Some(1), - retry_config: None, }; - let reply_stream = agent - .reply( - user_message, - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; + let reply_stream = agent.reply(user_message, session_config, None).await?; tokio::pin!(reply_stream); // Drain the stream @@ -1162,7 +907,6 @@ mod tests { session_manager.clone(), PermissionManager::instance(), None, - GooseMode::default(), false, GoosePlatform::GooseCli, ); @@ -1357,7 +1101,6 @@ mod tests { session_manager.clone(), PermissionManager::instance(), None, - GooseMode::Auto, true, // disable session naming so it doesn't consume a provider call GoosePlatform::GooseCli, ); @@ -1391,14 +1134,12 @@ mod tests { id: session_id.clone(), schedule_id: None, max_turns: Some(2), - retry_config: None, }; let reply_stream = agent .reply( Message::user().with_text("Do something then say hello"), session_config, - goose::agents::state_machine::enabled(), None, ) .await?; @@ -1446,14 +1187,12 @@ mod tests { id: session_id.clone(), schedule_id: None, max_turns: Some(2), - retry_config: None, }; let reply_stream2 = agent .reply( Message::user().with_text("Tell me more"), session_config2, - goose::agents::state_machine::enabled(), Some(cancel_token), ) .await?; @@ -1614,7 +1353,6 @@ mod tests { session_manager.clone(), PermissionManager::instance(), None, - GooseMode::Auto, true, GoosePlatform::GooseCli, ); @@ -1639,14 +1377,12 @@ mod tests { id: session_id.clone(), schedule_id: None, max_turns: Some(2), - retry_config: None, }; let reply_stream = agent .reply( Message::user().with_text("Use the test tool"), session_config, - goose::agents::state_machine::enabled(), None, ) .await?; @@ -1816,7 +1552,6 @@ mod tests { session_manager.clone(), PermissionManager::instance(), None, - GooseMode::Auto, true, GoosePlatform::GooseCli, ); @@ -1841,14 +1576,12 @@ mod tests { id: session_id.clone(), schedule_id: None, max_turns: Some(2), - retry_config: None, }; let reply_stream = agent .reply( Message::user().with_text("Use the test tool"), session_config, - goose::agents::state_machine::enabled(), None, ) .await?; @@ -1870,362 +1603,6 @@ mod tests { assert_formatter_adds_reasoning_to_tool_calls(&messages, "combined-thinking-tool"); Ok(()) } - - /// Simulates the DeepSeek/Kimi multi-tool-call case: thinking arrives as a - /// separate stream chunk, then both tool calls arrive together in a second - /// chunk with no thinking. Before the fix, the second tool-call message - /// (asst(TC2)) received no reasoning_content because lines 210-213 in - /// format_messages_with_options cleared tool_call_turn_reasoning after the - /// first tool result. - struct MultiToolThinkingProvider { - call_count: AtomicUsize, - } - - impl MultiToolThinkingProvider { - fn new() -> Self { - Self { - call_count: AtomicUsize::new(0), - } - } - } - - impl goose::providers::base::ProviderDescriptor for MultiToolThinkingProvider { - fn metadata() -> ProviderMetadata { - ProviderMetadata { - name: "multi-tool-thinking-mock".to_string(), - display_name: "Multi Tool Thinking Mock".to_string(), - description: "Mock for multi-tool thinking preservation".to_string(), - default_model: "mock-model".to_string(), - known_models: vec![], - model_doc_link: "".to_string(), - config_keys: vec![], - setup_steps: vec![], - setup: None, - deprecated: None, - } - } - } - - impl ProviderDef for MultiToolThinkingProvider { - type Provider = Self; - - fn from_env( - _extensions: Vec, - _tls_config: Option, - ) -> futures::future::BoxFuture<'static, anyhow::Result> { - unimplemented!() - } - } - - #[async_trait] - impl Provider for MultiToolThinkingProvider { - async fn stream( - &self, - _model_config: &ModelConfig, - _system_prompt: &str, - _messages: &[Message], - _tools: &[Tool], - ) -> Result { - let call = self.call_count.fetch_add(1, Ordering::SeqCst); - let usage = ProviderUsage::new( - "mock-model".to_string(), - Usage::new(Some(10), Some(20), Some(30)), - ); - match call { - 0 => { - let thinking = Message::assistant() - .with_id("msg_multi") - .with_thinking("multi-tool reasoning", "sig_0"); - let text = Message::assistant() - .with_id("msg_multi") - .with_text("Calling both tools."); - let tc1 = CallToolRequestParams::new("tool_a") - .with_arguments(object!({"p": "1"})); - let tc2 = CallToolRequestParams::new("tool_b") - .with_arguments(object!({"p": "2"})); - let tool_msg = Message::assistant() - .with_id("msg_multi") - .with_tool_request("call_1", Ok(tc1)) - .with_tool_request("call_2", Ok(tc2)); - let stream = futures::stream::iter(vec![ - Ok((Some(thinking), None)), - Ok((Some(text), None)), - Ok((Some(tool_msg), Some(usage))), - ]); - Ok(Box::pin(stream)) - } - _ => { - let msg = Message::assistant().with_text("Done."); - Ok(Box::pin(futures::stream::once(async move { - Ok((Some(msg), Some(usage))) - }))) - } - } - } - - fn get_name(&self) -> &str { - "multi-tool-thinking-mock" - } - } - - #[tokio::test] - async fn test_multi_tool_response_preserves_reasoning_and_message_id_correlation( - ) -> Result<()> { - use goose_providers::formats::openai::{ - format_messages_with_options, OpenAiFormatOptions, - }; - use goose_providers::images::ImageFormat; - - let temp_dir = tempfile::tempdir()?; - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let config = AgentConfig::new( - session_manager.clone(), - PermissionManager::instance(), - None, - GooseMode::Auto, - true, - GoosePlatform::GooseCli, - ); - let agent = Agent::with_config(config); - let provider = Arc::new(MultiToolThinkingProvider::new()); - - let session = session_manager - .create_session( - PathBuf::default(), - "multi-tool-thinking-test".to_string(), - SessionType::Hidden, - GooseMode::default(), - ) - .await?; - - let session_id = session.id.clone(); - agent - .update_provider(provider, ModelConfig::new("mock-model"), &session_id) - .await?; - - let session_config = SessionConfig { - id: session_id.clone(), - schedule_id: None, - max_turns: Some(2), - retry_config: None, - }; - - let reply_stream = agent - .reply( - Message::user().with_text("Use both tools"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; - tokio::pin!(reply_stream); - let mut live_tool_message_id = None; - let mut usage_message_ids = Vec::new(); - while let Some(event) = reply_stream.next().await { - match event? { - AgentEvent::Message(message) - if message - .content - .iter() - .any(|content| matches!(content, MessageContent::ToolRequest(_))) => - { - live_tool_message_id = message.id; - } - AgentEvent::MessageUsage { message_id, .. } => { - usage_message_ids.push(message_id); - } - _ => {} - } - } - - let reloaded = session_manager.get_session(&session_id, true).await?; - let messages = reloaded - .conversation - .expect("should have conversation") - .messages() - .to_vec(); - - let live_tool_message_id = - live_tool_message_id.expect("live tool message must have a generated ID"); - let persisted_tool_message_ids: Vec<&str> = messages - .iter() - .filter(|message| { - message - .content - .iter() - .any(|content| matches!(content, MessageContent::ToolRequest(_))) - }) - .map(|message| { - message - .id - .as_deref() - .expect("persisted tool message must have an ID") - }) - .collect(); - - assert_eq!(persisted_tool_message_ids.len(), 2); - assert_ne!( - persisted_tool_message_ids[0], persisted_tool_message_ids[1], - "split tool messages must keep distinct message IDs" - ); - assert_eq!( - persisted_tool_message_ids - .iter() - .copied() - .filter(|message_id| *message_id == live_tool_message_id.as_str()) - .count(), - 1, - "exactly one persisted tool message must retain the live message ID" - ); - assert!( - usage_message_ids.iter().any(|message_id| { - message_id.as_deref() == Some(live_tool_message_id.as_str()) - }), - "tool-turn usage must reference the live message ID" - ); - - let spec = format_messages_with_options( - &messages, - &ImageFormat::OpenAi, - OpenAiFormatOptions { - preserve_thinking_context: true, - ..Default::default() - }, - ); - - // Both tool calls must end up in one merged assistant message with reasoning_content. - let assistant_msgs: Vec<_> = spec - .iter() - .filter(|m| m.get("role") == Some(&serde_json::json!("assistant"))) - .filter(|m| { - m.get("tool_calls") - .and_then(|tc| tc.as_array()) - .is_some_and(|a| !a.is_empty()) - }) - .collect(); - - assert_eq!( - assistant_msgs.len(), - 1, - "both tool calls must be merged into one assistant message" - ); - assert_eq!( - assistant_msgs[0]["reasoning_content"], "multi-tool reasoning", - "merged message must carry reasoning_content" - ); - let tool_calls = assistant_msgs[0]["tool_calls"].as_array().unwrap(); - assert_eq!(tool_calls.len(), 2, "both tool calls must be present"); - - Ok(()) - } - - #[tokio::test] - async fn test_signed_thinking_leads_text_and_tool_calls_for_anthropic() -> Result<()> { - use goose::conversation::{ - fix_conversation, merge_consecutive_messages_for_request, Conversation, - }; - use goose_providers::formats::anthropic::format_messages as anthropic_format; - - let temp_dir = tempfile::tempdir()?; - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let config = AgentConfig::new( - session_manager.clone(), - PermissionManager::instance(), - None, - GooseMode::Auto, - true, - GoosePlatform::GooseCli, - ); - let agent = Agent::with_config(config); - let provider = Arc::new(MultiToolThinkingProvider::new()); - - let session = session_manager - .create_session( - PathBuf::default(), - "anthropic-signed-thinking-test".to_string(), - SessionType::Hidden, - GooseMode::default(), - ) - .await?; - - let session_id = session.id.clone(); - agent - .update_provider(provider, ModelConfig::new("mock-model"), &session_id) - .await?; - - let session_config = SessionConfig { - id: session_id.clone(), - schedule_id: None, - max_turns: Some(2), - retry_config: None, - }; - - let reply_stream = agent - .reply( - Message::user().with_text("Use both tools"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; - tokio::pin!(reply_stream); - while let Some(event) = reply_stream.next().await { - event?; - } - - let reloaded = session_manager.get_session(&session_id, true).await?; - let messages = reloaded - .conversation - .expect("should have conversation") - .messages() - .to_vec(); - - let first_tool_row = messages - .iter() - .find(|message| { - message.content.iter().any( - |content| matches!(content, MessageContent::ToolRequest(r) if r.id == "call_1"), - ) - }) - .expect("the first tool call is persisted"); - assert_eq!(first_tool_row.id.as_deref(), Some("msg_multi")); - assert!( - matches!( - first_tool_row.content.as_slice(), - [ - MessageContent::Thinking(_), - MessageContent::Text(_), - MessageContent::ToolRequest(_) - ] - ), - "the first tool call must share the prefix's row: {:#?}", - first_tool_row.content - ); - - let (fixed, _) = fix_conversation(Conversation::new_unvalidated(messages)); - let spec = anthropic_format(&merge_consecutive_messages_for_request( - fixed.messages().to_vec(), - )); - let assistant_block_types: Vec> = spec - .iter() - .filter(|msg| msg["role"] == "assistant") - .map(|msg| { - msg["content"] - .as_array() - .unwrap() - .iter() - .filter_map(|block| block["type"].as_str()) - .collect() - }) - .collect(); - assert_eq!( - assistant_block_types, - vec![vec!["thinking", "text", "tool_use"], vec!["tool_use"]], - "{spec:#?}" - ); - - Ok(()) - } } #[cfg(test)] @@ -2321,7 +1698,6 @@ mod tests { session_manager, PermissionManager::instance(), None, - GooseMode::Auto, true, GoosePlatform::GooseCli, ); @@ -2365,16 +1741,10 @@ mod tests { id: session.id.clone(), schedule_id: None, max_turns: Some(10), - retry_config: None, }; let reply_stream = agent - .reply( - Message::user().with_text("Hello"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) + .reply(Message::user().with_text("Hello"), session_config, None) .await?; tokio::pin!(reply_stream); @@ -2449,16 +1819,10 @@ mod tests { id: session.id.clone(), schedule_id: None, max_turns: Some(10), - retry_config: None, }; let reply_stream = agent - .reply( - Message::user().with_text("Hello"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) + .reply(Message::user().with_text("Hello"), session_config, None) .await?; tokio::pin!(reply_stream); @@ -2478,54 +1842,6 @@ mod tests { Ok(()) } - #[tokio::test] - async fn test_goal_command_set_and_clear() -> Result<()> { - let temp_dir = TempDir::new()?; - let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); - let agent = create_agent_with_session_naming_disabled(session_manager.clone()); - - let session = session_manager - .create_session( - PathBuf::default(), - "goal-cmd-test".to_string(), - SessionType::Hidden, - GooseMode::default(), - ) - .await?; - - // No goal initially - let result = agent.execute_command("/goal", &session.id).await?.unwrap(); - assert!(result.as_concat_text().contains("No goal set")); - - // Set a goal - let result = agent - .execute_command("/goal make all tests pass", &session.id) - .await? - .unwrap(); - assert!(result.as_concat_text().contains("Goal set")); - assert_eq!( - GoalState::of(&session_manager.get_session(&session.id, false).await?).goal, - Some("make all tests pass".to_string()) - ); - - // Query it - let result = agent.execute_command("/goal", &session.id).await?.unwrap(); - assert!(result.as_concat_text().contains("make all tests pass")); - - // Clear it - let result = agent - .execute_command("/goal off", &session.id) - .await? - .unwrap(); - assert!(result.as_concat_text().contains("cleared")); - assert_eq!( - GoalState::of(&session_manager.get_session(&session.id, false).await?).goal, - None - ); - - Ok(()) - } - #[tokio::test] async fn test_setting_goal_via_reply_starts_a_turn() -> Result<()> { let temp_dir = TempDir::new()?; @@ -2553,14 +1869,12 @@ mod tests { id: session.id.clone(), schedule_id: None, max_turns: Some(10), - retry_config: None, }; let reply_stream = agent .reply( Message::user().with_text("/goal make all tests pass"), session_config, - goose::agents::state_machine::enabled(), None, ) .await?; @@ -2618,16 +1932,10 @@ mod tests { id: session.id.clone(), schedule_id: None, max_turns: Some(10), - retry_config: None, }; let reply_stream = agent - .reply( - Message::user().with_text("/goal"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) + .reply(Message::user().with_text("/goal"), session_config, None) .await?; tokio::pin!(reply_stream); @@ -2747,15 +2055,9 @@ mod tests { id: session_id.to_string(), schedule_id: None, max_turns: Some(1), - retry_config: None, }; let stream = agent - .reply( - Message::user().with_text(text), - session_config, - goose::agents::state_machine::enabled(), - None, - ) + .reply(Message::user().with_text(text), session_config, None) .await?; tokio::pin!(stream); while let Some(event) = stream.next().await { @@ -2772,7 +2074,6 @@ mod tests { session_manager.clone(), PermissionManager::instance(), None, - GooseMode::Auto, true, GoosePlatform::GooseCli, ); @@ -2861,7 +2162,6 @@ mod tests { session_manager.clone(), permission_manager, None, - GooseMode::default(), false, GoosePlatform::GooseDesktop, ))); @@ -3131,7 +2431,6 @@ mod tests { session_manager.clone(), permission_manager, None, - GooseMode::Auto, true, GoosePlatform::GooseCli, )); @@ -3163,9 +2462,7 @@ mod tests { id: session_id.clone(), schedule_id: None, max_turns: Some(3), - retry_config: None, }, - goose::agents::state_machine::enabled(), None, ) .await?; @@ -3303,22 +2600,6 @@ mod tests { manages_own_context: false, } } - - fn with_wrapped_empty_text(empty_count: usize) -> Self { - Self { - call_count: AtomicUsize::new(0), - empty_count, - wrap_empty_text: true, - manages_own_context: false, - } - } - - fn with_own_context() -> Self { - Self { - manages_own_context: true, - ..Self::new(usize::MAX) - } - } } impl FinalOutputRequestProvider { @@ -3445,16 +2726,10 @@ mod tests { id: session.id, schedule_id: None, max_turns: Some(50), - retry_config: None, }; let reply_stream = agent - .reply( - Message::user().with_text("Hi"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) + .reply(Message::user().with_text("Hi"), session_config, None) .await?; tokio::pin!(reply_stream); @@ -3493,80 +2768,6 @@ mod tests { message.role == rmcp::model::Role::Assistant && message.content.is_empty() } - /// A transient empty response should be retried and recover, ultimately - /// delivering the real text response instead of stopping silently. - #[tokio::test] - async fn test_empty_turn_retries_then_recovers() -> Result<()> { - let provider = Arc::new(EmptyThenTextProvider::new(2)); - let (messages, persisted) = run_reply(provider, "empty-retry-recover").await?; - - let text = concat_text(&messages); - assert!( - text.contains("All done."), - "expected recovery to deliver the real response, got: {text:?}" - ); - assert!( - !text.contains("empty response"), - "should not surface the empty-turn fallback when recovery succeeds: {text:?}" - ); - assert!( - !persisted.iter().any(is_empty_assistant), - "retried empty turns must not be persisted: {persisted:?}" - ); - Ok(()) - } - - #[tokio::test] - async fn test_wrapped_empty_text_retries_then_recovers() -> Result<()> { - let provider = Arc::new(EmptyThenTextProvider::with_wrapped_empty_text(1)); - let (messages, persisted) = run_reply(provider, "wrapped-empty-retry").await?; - - assert!(concat_text(&messages).contains("All done.")); - assert!(!persisted.iter().any(|message| { - message.role == rmcp::model::Role::Assistant - && matches!(message.content.as_slice(), [MessageContent::Text(text)] if text.text.is_empty()) - })); - Ok(()) - } - - /// A provider that only ever returns empty responses must not hang - /// silently — after the retry budget it surfaces a visible message. - #[tokio::test] - async fn test_persistent_empty_turn_surfaces_message() -> Result<()> { - let provider = Arc::new(EmptyThenTextProvider::new(usize::MAX)); - let (messages, persisted) = run_reply(provider, "empty-persistent").await?; - - let text = concat_text(&messages); - assert!( - text.contains("empty response"), - "expected a visible empty-response message, got: {text:?}" - ); - - let last = messages.last().expect("expected at least one message"); - assert!( - matches!(last.content.first(), Some(MessageContent::Text(_))), - "expected the final message to be visible text, got: {:?}", - last.content - ); - assert!( - !persisted.iter().any(is_empty_assistant), - "empty assistant turn must not be persisted alongside the fallback: {persisted:?}" - ); - - let emitted_fallback_id = last - .id - .as_deref() - .expect("empty-turn fallback should be emitted with ID"); - assert!(emitted_fallback_id.starts_with("msg_")); - - let stored_fallback = persisted - .iter() - .find(|message| message.as_concat_text().contains("empty response")) - .expect("empty-turn fallback should be stored"); - assert_eq!(stored_fallback.id.as_deref(), Some(emitted_fallback_id)); - Ok(()) - } - #[tokio::test] async fn test_assistant_only_response_is_persisted_without_empty_turn_retry() -> Result<()> { @@ -3634,16 +2835,10 @@ mod tests { id: session.id, schedule_id: None, max_turns: Some(50), - retry_config: None, }; let reply_stream = agent - .reply( - Message::user().with_text("Hi"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) + .reply(Message::user().with_text("Hi"), session_config, None) .await?; tokio::pin!(reply_stream); let mut emitted_steer_id = None; @@ -3687,210 +2882,6 @@ mod tests { Ok(()) } - #[tokio::test] - async fn legacy_structured_output_fails_before_provider_inference() -> Result<()> { - use goose::recipe::{Recipe, Response}; - - let _guard = env_lock::lock_env([("GOOSE_STATE_MACHINE", None::<&str>)]); - let agent = Agent::new(); - let session = agent - .config - .session_manager - .create_session( - PathBuf::default(), - "unsupported-structured-output".to_string(), - SessionType::Hidden, - GooseMode::default(), - ) - .await?; - let provider = Arc::new(EmptyThenTextProvider::with_own_context()); - agent - .update_provider( - provider.clone(), - ModelConfig::new("mock-model"), - &session.id, - ) - .await?; - agent - .config - .session_manager - .update(&session.id) - .recipe(Some( - Recipe::builder() - .title("Structured output") - .description("Structured output") - .prompt("Return structured output") - .response(Response { - json_schema: Some(serde_json::json!({ - "type": "object", - "properties": { "result": { "type": "string" } } - })), - }) - .build() - .expect("valid recipe"), - )) - .apply() - .await?; - - let reply_stream = agent - .reply( - Message::user().with_text("Hi"), - SessionConfig { - id: session.id, - schedule_id: None, - max_turns: Some(3), - retry_config: None, - }, - goose::agents::state_machine::enabled(), - None, - ) - .await?; - tokio::pin!(reply_stream); - - let mut messages = Vec::new(); - while let Some(event) = reply_stream.next().await { - if let AgentEvent::Message(message) = event? { - messages.push(message); - } - } - - let text = concat_text(&messages); - assert!( - text.contains("empty-then-text-mock") && text.contains("final_output"), - "expected the unsupported structured-output error, got: {text:?}" - ); - assert_eq!(provider.call_count.load(Ordering::SeqCst), 0); - - Ok(()) - } - - /// When a final-output tool is installed and the model stops without - /// calling it, the empty turn must yield the mandatory final-output nudge - /// — not the generic empty-response fallback — so structured-output - /// recipes are not abandoned without producing a result. - #[tokio::test] - async fn test_empty_turn_with_final_output_tool_nudges() -> Result<()> { - use goose::agents::final_output_tool::FINAL_OUTPUT_CONTINUATION_MESSAGE; - use goose::recipe::{Recipe, Response}; - - let agent = Agent::new(); - let session = agent - .config - .session_manager - .create_session( - PathBuf::default(), - "empty-final-output".to_string(), - SessionType::Hidden, - GooseMode::default(), - ) - .await?; - agent - .update_provider( - Arc::new(EmptyThenTextProvider::new(usize::MAX)), - ModelConfig::new("mock-model"), - &session.id, - ) - .await?; - agent - .config - .session_manager - .update(&session.id) - .recipe(Some( - Recipe::builder() - .title("Structured output") - .description("Structured output") - .prompt("Return structured output") - .response(Response { - json_schema: Some(serde_json::json!({ - "type": "object", - "properties": { "result": { "type": "string" } } - })), - }) - .build() - .expect("valid recipe"), - )) - .apply() - .await?; - - let session_config = SessionConfig { - id: session.id.clone(), - schedule_id: None, - max_turns: Some(3), - retry_config: None, - }; - - let reply_stream = agent - .reply( - Message::user().with_text("Hi"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; - tokio::pin!(reply_stream); - - let mut messages = Vec::new(); - let mut emitted_nudge_ids = Vec::new(); - while let Some(event) = reply_stream.next().await { - if let AgentEvent::Message(m) = event? { - if m.role == rmcp::model::Role::User - && m.as_concat_text() - .contains(FINAL_OUTPUT_CONTINUATION_MESSAGE) - { - emitted_nudge_ids.push( - m.id.clone() - .expect("Final-output nudge should be emitted with ID"), - ); - } - messages.push(m); - } - } - - let text = concat_text(&messages); - assert!( - text.contains(FINAL_OUTPUT_CONTINUATION_MESSAGE), - "expected the final-output nudge, got: {text:?}" - ); - assert!( - !text.contains("empty response"), - "empty-turn fallback must not pre-empt the final-output nudge: {text:?}" - ); - - assert!( - !emitted_nudge_ids.is_empty(), - "expected at least one emitted final-output nudge" - ); - assert!(emitted_nudge_ids.iter().all(|id| id.starts_with("msg_"))); - - let reloaded = agent - .config - .session_manager - .get_session(&session.id, true) - .await?; - let conversation = reloaded - .conversation - .expect("Session should have a conversation"); - let stored_nudge_ids = conversation - .messages() - .iter() - .filter(|message| { - message.role == rmcp::model::Role::User - && message - .as_concat_text() - .contains(FINAL_OUTPUT_CONTINUATION_MESSAGE) - }) - .map(|message| { - message - .id - .clone() - .expect("Stored final-output nudge should have ID") - }) - .collect::>(); - - assert_eq!(stored_nudge_ids, emitted_nudge_ids); - Ok(()) - } - #[tokio::test] async fn test_final_output_result_id_matches_persisted_message() -> Result<()> { use goose::recipe::{Recipe, Response}; @@ -3903,7 +2894,6 @@ mod tests { session_manager.clone(), Arc::new(PermissionManager::new(temp_dir.path().join("config"))), None, - GooseMode::Auto, true, GoosePlatform::GooseCli, )); @@ -3949,16 +2939,10 @@ mod tests { id: session.id, schedule_id: None, max_turns: Some(5), - retry_config: None, }; let reply_stream = agent - .reply( - Message::user().with_text("Hi"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) + .reply(Message::user().with_text("Hi"), session_config, None) .await?; tokio::pin!(reply_stream); @@ -4003,166 +2987,5 @@ mod tests { assert_eq!(provider.call_count.load(Ordering::SeqCst), 1); Ok(()) } - - /// A recipe with retry_config owns the turn: recipe retry logic runs - /// its success checks before the empty-turn fallback. When the check - /// already passes, an empty final turn is the successful end of the - /// recipe, not a generic empty-response error. - #[tokio::test] - async fn test_empty_turn_defers_to_recipe_retry() -> Result<()> { - use goose::agents::types::{RetryConfig, SuccessCheck}; - - let agent = Agent::new(); - let session = agent - .config - .session_manager - .create_session( - PathBuf::default(), - "empty-recipe-retry".to_string(), - SessionType::Hidden, - GooseMode::default(), - ) - .await?; - agent - .update_provider( - Arc::new(EmptyThenTextProvider::new(usize::MAX)), - ModelConfig::new("mock-model"), - &session.id, - ) - .await?; - - let session_config = SessionConfig { - id: session.id, - schedule_id: None, - max_turns: Some(3), - retry_config: Some(RetryConfig { - max_retries: 2, - checks: vec![SuccessCheck::Shell { - command: "true".to_string(), - }], - on_failure: None, - timeout_seconds: Some(30), - on_failure_timeout_seconds: None, - }), - }; - - let reply_stream = agent - .reply( - Message::user().with_text("Hi"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; - tokio::pin!(reply_stream); - - let mut messages = Vec::new(); - while let Some(event) = reply_stream.next().await { - if let AgentEvent::Message(m) = event? { - messages.push(m); - } - } - - let text = concat_text(&messages); - assert!( - !text.contains("empty response"), - "recipe retry (passing check) must own the empty turn, not the fallback: {text:?}" - ); - Ok(()) - } - - /// When a recipe exhausts its retries on empty turns, the max-attempts - /// failure message must be surfaced and persisted — not swallowed into a - /// silent stop. - #[tokio::test] - async fn test_recipe_max_retries_surfaces_failure() -> Result<()> { - use goose::agents::types::{RetryConfig, SuccessCheck}; - - let agent = Agent::new(); - let session = agent - .config - .session_manager - .create_session( - PathBuf::default(), - "recipe-max-retries".to_string(), - SessionType::Hidden, - GooseMode::default(), - ) - .await?; - let session_id = session.id.clone(); - agent - .update_provider( - Arc::new(EmptyThenTextProvider::new(usize::MAX)), - ModelConfig::new("mock-model"), - &session.id, - ) - .await?; - - let session_config = SessionConfig { - id: session.id, - schedule_id: None, - max_turns: Some(5), - retry_config: Some(RetryConfig { - max_retries: 1, - checks: vec![SuccessCheck::Shell { - command: "false".to_string(), - }], - on_failure: None, - timeout_seconds: Some(30), - on_failure_timeout_seconds: None, - }), - }; - - let reply_stream = agent - .reply( - Message::user().with_text("Hi"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; - tokio::pin!(reply_stream); - - let mut messages = Vec::new(); - while let Some(event) = reply_stream.next().await { - if let AgentEvent::Message(m) = event? { - messages.push(m); - } - } - - let text = concat_text(&messages); - assert!( - text.contains("Maximum retry attempts"), - "exhausted recipe retries must surface the failure message: {text:?}" - ); - let emitted_failure = messages - .iter() - .find(|message| message.as_concat_text().contains("Maximum retry attempts")) - .expect("max-retry failure message should be emitted"); - let emitted_failure_id = emitted_failure - .id - .as_deref() - .expect("max-retry failure message should be emitted with ID"); - assert!(emitted_failure_id.starts_with("msg_")); - - let persisted = agent - .config - .session_manager - .get_session(&session_id, true) - .await? - .conversation - .map(|c| c.messages().to_vec()) - .unwrap_or_default(); - assert!( - concat_text(&persisted).contains("Maximum retry attempts"), - "the max-retry failure message must be persisted: {persisted:?}" - ); - let stored_failure = persisted - .iter() - .find(|message| message.as_concat_text().contains("Maximum retry attempts")) - .expect("max-retry failure message should be stored"); - assert_eq!(stored_failure.id.as_deref(), Some(emitted_failure_id)); - Ok(()) - } } } diff --git a/crates/goose/tests/compaction.rs b/crates/goose/tests/compaction.rs index 82dcec1f1..ef957f0c4 100644 --- a/crates/goose/tests/compaction.rs +++ b/crates/goose/tests/compaction.rs @@ -32,13 +32,6 @@ impl MockCompactionProvider { } } - fn context_owning() -> Self { - Self { - has_compacted: Arc::new(AtomicBool::new(false)), - manages_own_context: true, - } - } - /// Calculate input tokens based on system prompt and messages /// Simulates realistic token counts for different scenarios fn calculate_input_tokens(&self, system_prompt: &str, messages: &[Message]) -> i32 { @@ -253,247 +246,6 @@ async fn setup_test_session( Ok(session) } -#[tokio::test] -async fn context_owning_provider_rejects_clear_and_compact_without_changing_session() -> Result<()> -{ - let temp_dir = TempDir::new()?; - let agent = Agent::new(); - let messages = vec![ - Message::user().with_text("Remember this"), - Message::assistant().with_text("I will"), - ]; - let session = setup_test_session( - &agent, - &temp_dir, - "context-owning-provider", - messages.clone(), - ) - .await?; - let before = agent - .config - .session_manager - .get_session(&session.id, true) - .await?; - let conversation_before = before.conversation.unwrap(); - let usage_before = before.usage; - let provider = Arc::new(MockCompactionProvider::context_owning()); - agent - .update_provider(provider, ModelConfig::new("mock-model"), &session.id) - .await?; - - for command in ["clear", "compact"] { - let error = agent - .execute_command(&format!("/{command}"), &session.id) - .await - .unwrap_err(); - assert_eq!( - error.to_string(), - format!( - "/{command} is not available for provider 'mock-compaction' because it manages its own conversation context" - ) - ); - } - - let unchanged = agent - .config - .session_manager - .get_session(&session.id, true) - .await?; - assert_eq!(unchanged.conversation.unwrap(), conversation_before); - assert_eq!(unchanged.usage, usage_before); - - Ok(()) -} - -/// Helper: Assert conversation has been compacted with proper message visibility -fn assert_conversation_compacted(conversation: &Conversation) { - let messages = conversation.messages(); - assert!(!messages.is_empty(), "Conversation should not be empty"); - - // Find the summary message (contains "mock summary") - let summary_index = messages - .iter() - .position(|msg| { - msg.content.iter().any(|content| { - if let MessageContent::Text(text) = content { - text.text.contains("mock summary") - } else { - false - } - }) - }) - .expect("Conversation should contain the summary message"); - - let summary_msg = &messages[summary_index]; - - // Assert summary message visibility - assert!( - summary_msg.is_agent_visible(), - "Summary message should be agent visible" - ); - assert!( - !summary_msg.is_user_visible(), - "Summary message should NOT be user visible" - ); - - // Check messages BEFORE the summary (the compacted original messages) - // These should be made agent-invisible - for (idx, msg) in messages.iter().enumerate() { - if idx < summary_index { - // Old messages before summary: agent can't see them - assert!( - !msg.is_agent_visible(), - "Message before summary at index {} should be agent-invisible", - idx - ); - } - } - - // Check for continuation message after summary - // (Should exist and be agent-only) - if summary_index + 1 < messages.len() { - let continuation_msg = &messages[summary_index + 1]; - // Continuation message should contain instructions about not mentioning summary - let has_continuation_text = continuation_msg.content.iter().any(|content| { - if let MessageContent::Text(text) = content { - text.text.contains("previous message contains a summary") - || text.text.contains("summarization occurred") - } else { - false - } - }); - - if has_continuation_text { - assert!( - continuation_msg.is_agent_visible(), - "Continuation message should be agent visible" - ); - assert!( - !continuation_msg.is_user_visible(), - "Continuation message should NOT be user visible" - ); - } - } - - // The projected replay of the preserved user message is agent-only. Any - // ordinary messages appended after it should remain visible to both sides. - let continuation_end = summary_index + 2; - for (idx, msg) in messages.iter().enumerate() { - if idx >= continuation_end { - assert!( - msg.is_agent_visible(), - "Message after compaction at index {} should be agent visible", - idx - ); - if msg.is_turn_context() { - assert!( - !msg.is_user_visible(), - "Carried turn-context event should be user-invisible" - ); - } else if idx == continuation_end && matches!(msg.role, rmcp::model::Role::User) { - assert!( - !msg.is_user_visible(), - "Projected preserved user message should be user-invisible" - ); - } else { - assert!( - msg.is_user_visible(), - "Ordinary message after compaction at index {} should be user visible", - idx - ); - } - } - } -} - -#[tokio::test] -async fn test_manual_compaction_updates_token_counts_and_conversation() -> Result<()> { - let temp_dir = TempDir::new()?; - let agent = Agent::new(); - - // Setup session with initial messages - // Each message ~100 tokens, so 4 messages = ~400 tokens in conversation - let messages = vec![ - Message::user().with_text("Hello, can you help me with something?"), - Message::assistant().with_text("Of course! What do you need help with?"), - Message::user().with_text("I need to understand how compaction works."), - Message::assistant() - .with_text("Compaction is a process that summarizes conversation history."), - ]; - - let session = setup_test_session(&agent, &temp_dir, "manual-compact-test", messages).await?; - - // Setup mock provider - let provider = Arc::new(MockCompactionProvider::new()); - agent - .update_provider(provider, ModelConfig::new("mock-model"), &session.id) - .await?; - - // Execute manual compaction - let result = agent.execute_command("/compact", &session.id).await?; - assert!(result.is_some(), "Compaction should return a result"); - - // Verify token counts - let updated_session = agent - .config - .session_manager - .get_session(&session.id, true) - .await?; - - // Expected token calculation for compaction: - // During compaction, the 4 messages are embedded in the system prompt template - // - Input: system prompt with embedded conversation + "Please summarize" message - // - Output: summary (200 tokens) - // - // From mock provider calculation: - // - System prompt (with 4 embedded messages): varies based on template + content - // - Single "summarize" message: 100 tokens - // - Total input observed: ~6100 tokens - // - // After compaction the baseline is the estimated retained conversation - // (summary + continuation), not the provider-reported output count - let input_after = updated_session - .usage - .input_tokens - .expect("Input tokens should be set after compaction"); - assert!( - input_after > 0 && input_after < 200, - "Input tokens should be the estimated retained context (smaller than the mock's claimed 200 output tokens). Got: {}", - input_after - ); - assert_eq!( - updated_session.usage.output_tokens, None, - "Output tokens should be None after compaction (no new assistant output)" - ); - assert_eq!( - updated_session.usage.total_tokens, - Some(input_after), - "Total should equal input after compaction" - ); - - // Accumulated tokens increased by the compaction cost - // Initial: 1000 - // Compaction input: ~6700 (system 6000 + compaction prompt + 4 messages; - // the mock derives input tokens from the rendered prompt length, so the - // band must absorb compaction.md wording changes) - // Compaction output: 200 - let accumulated = updated_session.accumulated_usage.total_tokens.unwrap(); - assert!( - (7300..=8600).contains(&accumulated), - "Accumulated should be ~7900 (1000 initial + ~6700 input + 200 output). Got: {}", - accumulated - ); - - // Verify conversation has been compacted - let compacted_conversation = updated_session - .conversation - .expect("Session should have conversation"); - - assert_conversation_compacted(&compacted_conversation); - - Ok(()) -} - #[tokio::test] async fn test_auto_compaction_during_reply() -> Result<()> { let temp_dir = TempDir::new()?; @@ -534,17 +286,9 @@ async fn test_auto_compaction_during_reply() -> Result<()> { id: session.id.clone(), schedule_id: None, max_turns: None, - retry_config: None, }; - let reply_stream = agent - .reply( - user_message, - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; + let reply_stream = agent.reply(user_message, session_config, None).await?; tokio::pin!(reply_stream); // Track compaction and context size changes @@ -660,178 +404,3 @@ async fn test_auto_compaction_during_reply() -> Result<()> { Ok(()) } - -#[tokio::test] -async fn test_context_limit_recovery_compaction() -> Result<()> { - let temp_dir = TempDir::new()?; - let agent = Agent::new(); - - // Setup session with messages that will push context over the limit - // Each message = 100 tokens, but we'll add a large one - let messages = vec![ - Message::user().with_text("Hello"), - Message::assistant().with_text("Hi there"), - Message::user().with_text("Can you process this long_tool_call result?"), - Message::assistant().with_text("Processing..."), - ]; - // Token calculation: - // - 3 regular messages: 300 tokens - // - 1 message with "long_tool_call": 100 + 15000 = 15100 tokens - // - Total conversation: ~15400 tokens - // - With system prompt (6000): 21400 tokens - - let session = setup_test_session(&agent, &temp_dir, "context-limit-test", messages).await?; - - // Setup mock provider with context limit of 20000 tokens - // Initial context (6000 system + 15400 messages = 21400) exceeds this limit - let provider = Arc::new(MockCompactionProvider::new()); - agent - .update_provider(provider, ModelConfig::new("mock-model"), &session.id) - .await?; - - // Try to send a message - should trigger context limit, then recover via compaction - let session_config = SessionConfig { - id: session.id.clone(), - schedule_id: None, - max_turns: None, - retry_config: None, - }; - - let reply_stream = agent - .reply( - Message::user().with_text("Tell me more"), - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; - tokio::pin!(reply_stream); - - // Track compaction and context size changes - let mut compaction_occurred = false; - let mut got_response = false; - let mut input_tokens_after_compaction: Option = None; - - while let Some(event_result) = reply_stream.next().await { - match event_result { - Ok(AgentEvent::HistoryReplaced(_)) => { - compaction_occurred = true; - - // Capture the input tokens immediately after compaction - let session_after_compact = agent - .config - .session_manager - .get_session(&session.id, true) - .await?; - input_tokens_after_compaction = session_after_compact.usage.input_tokens; - } - Ok(AgentEvent::Message(msg)) => { - // Check if we got a real response (not just a notification) - if msg - .content - .iter() - .any(|c| matches!(c, MessageContent::Text(_))) - { - got_response = true; - } - } - Ok(_) => {} - Err(e) => return Err(e), - } - } - - // Verify recovery occurred - assert!( - compaction_occurred, - "Compaction should have occurred due to context limit (>20000 tokens)" - ); - assert!( - got_response, - "Should have received a response after recovery" - ); - - // Verify token counts - let updated_session = agent - .config - .session_manager - .get_session(&session.id, true) - .await?; - - // Expected token flow: - // 1. Initial attempt: >20000 tokens -> Context limit exceeded - // 2. Compaction triggered: - // - Input: system prompt + messages (including long_tool_call with 15k tokens) - // - Output: 200 tokens (summary, as claimed by the mock) - // - New context size: estimated tokens of the retained conversation - // 3. Retry with compacted context: - // - Input: system prompt + summary + new message - // - Output: 100 tokens (response) - - // Verify that current input context is dramatically reduced after compaction - let tokens_after = - input_tokens_after_compaction.expect("Should have captured tokens after compaction"); - - // Before: system (6000) + long_tool_call messages (~15,400) = 21,400 (exceeded limit!) - assert!( - tokens_after > 0 && tokens_after < 200, - "Input tokens after compaction should be the estimated retained context (under the mock's claimed 200). Got: {}", - tokens_after - ); - - // The compacted context is now well under the 20k limit - assert!( - tokens_after < 20000, - "Compacted context should be under 20k limit. Got: {}", - tokens_after - ); - - // Check the final token state after recovery - // Note: The session state reflects the RETRY call (after compaction), - // which only sees agent-visible messages (summary + continuation + user message) - let final_input = updated_session.usage.input_tokens.unwrap(); - let final_output = updated_session.usage.output_tokens; - let final_total = updated_session.usage.total_tokens.unwrap(); - - // After compaction, the retry only sees agent-visible messages: - // Input: system (6000) + summary (~100) + continuation (~100) + user message (~100) = ~6300 - // Output: 200 (mock detects "summarized" in continuation as compaction) - // Total: ~6500 - assert!( - (6000..=6600).contains(&final_input), - "Final input should reflect retry with agent-visible messages (~6300). Got: {}", - final_input - ); - - assert_eq!( - final_output, - Some(200), - "Final output should be 200 (mock detects continuation as compaction). Got: {:?}", - final_output - ); - - assert_eq!( - final_total, - final_input + final_output.unwrap(), - "Final total should equal input + output" - ); - - // Accumulated tokens should include all operations: - // - Initial: 1000 - // - Compaction: ~6400 input (mock uses system_prompt.len()/4) + 200 output = ~6600 - // - Reply: ~6500 input + 200 output = ~6700 - // Total: 1000 + 6600 + 6700 = ~14300 - let accumulated = updated_session.accumulated_usage.total_tokens.unwrap(); - assert!( - (13000..=16000).contains(&accumulated), - "Accumulated should be ~14300 (initial + compaction + reply). Got: {}", - accumulated - ); - - // Verify that the conversation was compacted - let updated_conversation = updated_session - .conversation - .expect("Session should have conversation"); - assert_conversation_compacted(&updated_conversation); - - Ok(()) -} diff --git a/crates/goose/tests/mcp_integration_test.rs b/crates/goose/tests/mcp_integration_test.rs index 8289746ba..a007b5650 100644 --- a/crates/goose/tests/mcp_integration_test.rs +++ b/crates/goose/tests/mcp_integration_test.rs @@ -133,7 +133,7 @@ impl Fixture { config.clone(), Some(session.working_dir.clone()), None, - Some(&session.id), + &session.id, ) .await .unwrap(); @@ -504,7 +504,10 @@ async fn extension_lifecycle_across_real_transports(stdio_version: ProtocolVersi ); // Removal is invisible to a held lease and visible to a fresh one. - fx.manager.remove_extension("todo").await.unwrap(); + fx.manager + .remove_extension(&session.id, "todo") + .await + .unwrap(); assert!(tool_names(&lease.tools().await).contains(&"todo__todo_write".to_string())); assert!(!tool_names( &fx.resolve( @@ -918,7 +921,7 @@ async fn test_replayed_session( #[allow(clippy::redundant_closure_call)] let result = (async || -> Result<(), Box> { extension_manager - .add_extension(extension_config, None, None, None) + .add_extension(extension_config, None, None, "test-session-id") .await?; let mut results = Vec::new(); for tool_call in tool_calls { diff --git a/crates/goose/tests/providers.rs b/crates/goose/tests/providers.rs index 602ba032a..4406457e1 100644 --- a/crates/goose/tests/providers.rs +++ b/crates/goose/tests/providers.rs @@ -260,7 +260,6 @@ impl ProviderFixture { session_manager.clone(), permission_manager, None, - mode, true, GoosePlatform::GooseCli, )); @@ -269,7 +268,7 @@ impl ProviderFixture { std::env::current_dir()?, "provider_test".to_string(), SessionType::User, - GooseMode::default(), + mode, ) .await?; let session_id = session.id; @@ -583,18 +582,9 @@ impl ProviderFixture { id: self.session_id.clone(), schedule_id: None, max_turns: Some(5), - retry_config: None, }; - let mut stream = self - .agent - .reply( - message, - session_config, - goose::agents::state_machine::enabled(), - None, - ) - .await?; + let mut stream = self.agent.reply(message, session_config, None).await?; let mut saw_action_required = false; while let Some(event) = stream.next().await { diff --git a/ui/desktop/src/acp/__tests__/liveVoice.test.ts b/ui/desktop/src/acp/__tests__/liveVoice.test.ts index 8446a0ba7..7db71d2fb 100644 --- a/ui/desktop/src/acp/__tests__/liveVoice.test.ts +++ b/ui/desktop/src/acp/__tests__/liveVoice.test.ts @@ -7,7 +7,6 @@ vi.mock('../acpConnection', () => ({ getAcpClient: vi.fn() })); describe('ACP Live voice', () => { beforeEach(() => { vi.clearAllMocks(); - vi.mocked(window.electron.getSetting).mockResolvedValue(false); }); it('uses the generated availability client for the displayed session', async () => { @@ -27,7 +26,6 @@ describe('ACP Live voice', () => { }); expect(sessionLiveVoiceAvailability).toHaveBeenCalledWith({ sessionId: 'main-session', - _meta: { goose: { unrolledAgentLoop: true } }, }); }); @@ -46,29 +44,7 @@ describe('ACP Live voice', () => { status: 'unavailable', message: 'Live voice is disabled', }); - expect(sessionLiveVoiceAvailability).toHaveBeenCalledWith({ - _meta: { goose: { unrolledAgentLoop: true } }, - }); - }); - - it('passes the legacy loop selection to availability', async () => { - vi.mocked(window.electron.getSetting).mockResolvedValue(true); - const sessionLiveVoiceAvailability = vi.fn().mockResolvedValue({ - status: 'unavailable', - message: 'Live voice is unavailable while Use Legacy Agent Loop is enabled', - }); - vi.mocked(getAcpClient).mockResolvedValue({ - goose: { - sessionLiveVoiceAvailability_unstable: sessionLiveVoiceAvailability, - }, - } as unknown as Awaited>); - - await acpGetLiveVoiceAvailability('main-session'); - - expect(sessionLiveVoiceAvailability).toHaveBeenCalledWith({ - sessionId: 'main-session', - _meta: { goose: { unrolledAgentLoop: false } }, - }); + expect(sessionLiveVoiceAvailability).toHaveBeenCalledWith({}); }); it('uses generated start and stop clients with the interaction ID', async () => { @@ -92,7 +68,6 @@ describe('ACP Live voice', () => { expect(start).toHaveBeenCalledWith({ sessionId: 'main-session', offerSdp: 'offer', - _meta: { goose: { unrolledAgentLoop: true } }, }); expect(stop).toHaveBeenCalledWith({ sessionId: 'main-session', diff --git a/ui/desktop/src/acp/liveVoice.ts b/ui/desktop/src/acp/liveVoice.ts index 98780ef5f..7489745be 100644 --- a/ui/desktop/src/acp/liveVoice.ts +++ b/ui/desktop/src/acp/liveVoice.ts @@ -8,11 +8,7 @@ export async function acpGetLiveVoiceAvailability( sessionId?: string ): Promise { const { goose } = await getAcpClient(); - const useLegacyAgentLoop = await window.electron.getSetting('useLegacyAgentLoop'); - return goose.sessionLiveVoiceAvailability_unstable({ - ...(sessionId ? { sessionId } : {}), - _meta: { goose: { unrolledAgentLoop: !useLegacyAgentLoop } }, - }); + return goose.sessionLiveVoiceAvailability_unstable(sessionId ? { sessionId } : {}); } export async function acpStartLiveVoice( @@ -20,11 +16,9 @@ export async function acpStartLiveVoice( offerSdp: string ): Promise { const { goose } = await getAcpClient(); - const useLegacyAgentLoop = await window.electron.getSetting('useLegacyAgentLoop'); return goose.sessionLiveVoiceStart_unstable({ sessionId, offerSdp, - _meta: { goose: { unrolledAgentLoop: !useLegacyAgentLoop } }, }); } diff --git a/ui/desktop/src/acp/prompt.ts b/ui/desktop/src/acp/prompt.ts index 89e97e2a3..f3cd4105b 100644 --- a/ui/desktop/src/acp/prompt.ts +++ b/ui/desktop/src/acp/prompt.ts @@ -1,5 +1,8 @@ import { methods, type ContentBlock, type PromptResponse } from '@agentclientprotocol/sdk'; -import type { SteerSessionRequest_unstable, SteerSessionResponse_unstable } from '@aaif/goose-acp-client'; +import type { + SteerSessionRequest_unstable, + SteerSessionResponse_unstable, +} from '@aaif/goose-acp-client'; import type { Message } from '../types/message'; import { getAcpClient } from './acpConnection'; @@ -8,11 +11,9 @@ export async function acpPromptSession( message: Message ): Promise { const client = await getAcpClient(); - const useLegacyAgentLoop = await window.electron.getSetting('useLegacyAgentLoop'); return client.connection.agent.request(methods.agent.session.prompt, { sessionId, prompt: messageToAcpPromptContent(message), - _meta: { goose: { unrolledAgentLoop: !useLegacyAgentLoop } }, }); } diff --git a/ui/desktop/src/components/settings/AgentLoopSettings.tsx b/ui/desktop/src/components/settings/AgentLoopSettings.tsx index 09383f868..cb4314259 100644 --- a/ui/desktop/src/components/settings/AgentLoopSettings.tsx +++ b/ui/desktop/src/components/settings/AgentLoopSettings.tsx @@ -1,8 +1,7 @@ import { type ReactNode, useEffect, useState } from 'react'; import { useConfig } from '../ConfigContext'; import { Input } from '../ui/input'; -import { Switch } from '../ui/switch'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card'; +import { Card, CardContent, CardHeader, CardTitle } from '../ui/card'; import { defineMessages, useIntl } from '../../i18n'; const i18n = defineMessages({ @@ -10,10 +9,6 @@ const i18n = defineMessages({ id: 'settings.agentLoop.title', defaultMessage: 'Agent Loop', }, - description: { - id: 'settings.agentLoop.description', - defaultMessage: 'Use the operation-based agent loop. Turn this off to use the legacy loop.', - }, operationsHeading: { id: 'settings.agentLoop.operations.heading', defaultMessage: 'Configurable operations', @@ -204,7 +199,6 @@ function NumberInput({ export default function AgentLoopSettings() { const intl = useIntl(); const { read, remove, upsert } = useConfig(); - const [enabled, setEnabled] = useState(true); const [slashCommandsEnabled, setSlashCommandsEnabled] = useState(true); const [toolPairCompactionEnabled, setToolPairCompactionEnabled] = useState(false); const [numbers, setNumbers] = useState(defaultNumberSettings); @@ -213,7 +207,6 @@ export default function AgentLoopSettings() { let active = true; Promise.all([ - window.electron.getSetting('useLegacyAgentLoop'), read('GOOSE_MAX_TURNS', false), read('GOOSE_AUTO_COMPACT_THRESHOLD', false), read('GOOSE_SLASH_COMMANDS_ENABLED', false), @@ -224,7 +217,6 @@ export default function AgentLoopSettings() { read('GOOSE_STOP_HOOK_BLOCK_CAP', false), ]).then( ([ - useLegacyAgentLoop, maxTurns, compactionThreshold, slashCommands, @@ -236,7 +228,6 @@ export default function AgentLoopSettings() { ]) => { if (!active) return; - setEnabled(!useLegacyAgentLoop); setSlashCommandsEnabled(typeof slashCommands === 'boolean' ? slashCommands : true); setToolPairCompactionEnabled( typeof toolPairCompaction === 'boolean' ? toolPairCompaction : false @@ -281,11 +272,6 @@ export default function AgentLoopSettings() { await upsert(configKey, serialize(value), false); }; - const handleAgentLoopToggle = async (checked: boolean) => { - setEnabled(checked); - await window.electron.setSetting('useLegacyAgentLoop', !checked); - }; - const handleToolPairCompactionToggle = async (checked: boolean) => { setToolPairCompactionEnabled(checked); await upsert('GOOSE_TOOL_PAIR_SUMMARIZATION', checked, false); @@ -308,131 +294,121 @@ export default function AgentLoopSettings() {
-
-
- {intl.formatMessage(i18n.title)} - - {intl.formatMessage(i18n.description)} - -
- -
+ {intl.formatMessage(i18n.title)}
- {enabled && ( - -

- {intl.formatMessage(i18n.operationsHeading)} -

+ +

+ {intl.formatMessage(i18n.operationsHeading)} +

- + + + setNumber('maxTurns', value)} + onBlur={() => saveNumber('maxTurns', 'GOOSE_MAX_TURNS', 1, 10000)} /> + - + + setNumber('compactionThreshold', value)} + onBlur={() => + saveNumber( + 'compactionThreshold', + 'GOOSE_AUTO_COMPACT_THRESHOLD', + 1, + 99, + (value) => value / 100, + false + ) + } + /> + + + +
setNumber('maxTurns', value)} - onBlur={() => saveNumber('maxTurns', 'GOOSE_MAX_TURNS', 1, 10000)} + max={100000} + placeholder={intl.formatMessage(i18n.autoPlaceholder)} + disabled={!toolPairCompactionEnabled} + onChange={(value) => setNumber('toolCallCutoff', value)} + onBlur={saveToolCallCutoff} /> - +
+
- + +
setNumber('compactionThreshold', value)} + max={3600} + onChange={(value) => setNumber('retryTimeout', value)} onBlur={() => - saveNumber( - 'compactionThreshold', - 'GOOSE_AUTO_COMPACT_THRESHOLD', - 1, - 99, - (value) => value / 100, - false - ) + saveNumber('retryTimeout', 'GOOSE_RECIPE_RETRY_TIMEOUT_SECONDS', 1, 3600) } /> - - - -
- setNumber('toolCallCutoff', value)} - onBlur={saveToolCallCutoff} - /> -
-
- - -
- setNumber('retryTimeout', value)} - onBlur={() => - saveNumber('retryTimeout', 'GOOSE_RECIPE_RETRY_TIMEOUT_SECONDS', 1, 3600) - } - /> - setNumber('failureTimeout', value)} - onBlur={() => - saveNumber('failureTimeout', 'GOOSE_RECIPE_ON_FAILURE_TIMEOUT_SECONDS', 1, 3600) - } - /> -
-
- - setNumber('stopHookBlockCap', value)} - onBlur={() => saveNumber('stopHookBlockCap', 'GOOSE_STOP_HOOK_BLOCK_CAP', 1, 100)} + max={3600} + onChange={(value) => setNumber('failureTimeout', value)} + onBlur={() => + saveNumber('failureTimeout', 'GOOSE_RECIPE_ON_FAILURE_TIMEOUT_SECONDS', 1, 3600) + } /> - - - )} +
+
+ + + setNumber('stopHookBlockCap', value)} + onBlur={() => saveNumber('stopHookBlockCap', 'GOOSE_STOP_HOOK_BLOCK_CAP', 1, 100)} + /> + +
); diff --git a/ui/desktop/src/i18n/messages/de.json b/ui/desktop/src/i18n/messages/de.json index c6e432937..88b495bc8 100644 --- a/ui/desktop/src/i18n/messages/de.json +++ b/ui/desktop/src/i18n/messages/de.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "Besuchen Sie" }, - "settings.agentLoop.description": { - "defaultMessage": "Verwende die operationsbasierte Agentenschleife. Deaktiviere sie, um die Legacy-Schleife zu verwenden." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Automatisch" }, diff --git a/ui/desktop/src/i18n/messages/en.json b/ui/desktop/src/i18n/messages/en.json index 4de26516d..1421e948f 100644 --- a/ui/desktop/src/i18n/messages/en.json +++ b/ui/desktop/src/i18n/messages/en.json @@ -3977,9 +3977,6 @@ "sessions.toast.updated": { "defaultMessage": "Session description updated successfully" }, - "settings.agentLoop.description": { - "defaultMessage": "Use the operation-based agent loop. Turn this off to use the legacy loop." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Auto" }, diff --git a/ui/desktop/src/i18n/messages/es.json b/ui/desktop/src/i18n/messages/es.json index ecb4513b6..ec6f7b712 100644 --- a/ui/desktop/src/i18n/messages/es.json +++ b/ui/desktop/src/i18n/messages/es.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "Visita" }, - "settings.agentLoop.description": { - "defaultMessage": "Usa el bucle del agente basado en operaciones. Desactívalo para usar el bucle heredado." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Automático" }, diff --git a/ui/desktop/src/i18n/messages/fr.json b/ui/desktop/src/i18n/messages/fr.json index a45c69877..42982f08d 100644 --- a/ui/desktop/src/i18n/messages/fr.json +++ b/ui/desktop/src/i18n/messages/fr.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "Visitez" }, - "settings.agentLoop.description": { - "defaultMessage": "Utilise la boucle d’agent basée sur les opérations. Désactivez-la pour utiliser la boucle héritée." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Automatique" }, diff --git a/ui/desktop/src/i18n/messages/hi.json b/ui/desktop/src/i18n/messages/hi.json index 23e5d08e9..5b5d39e82 100644 --- a/ui/desktop/src/i18n/messages/hi.json +++ b/ui/desktop/src/i18n/messages/hi.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "जाएं" }, - "settings.agentLoop.description": { - "defaultMessage": "ऑपरेशन-आधारित एजेंट लूप का उपयोग करें। लेगेसी लूप का उपयोग करने के लिए इसे बंद करें।" - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "स्वचालित" }, diff --git a/ui/desktop/src/i18n/messages/id.json b/ui/desktop/src/i18n/messages/id.json index 9134f27e0..785c99e34 100644 --- a/ui/desktop/src/i18n/messages/id.json +++ b/ui/desktop/src/i18n/messages/id.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "Kunjungi" }, - "settings.agentLoop.description": { - "defaultMessage": "Gunakan loop agen berbasis operasi. Matikan untuk menggunakan loop lama." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Otomatis" }, diff --git a/ui/desktop/src/i18n/messages/it.json b/ui/desktop/src/i18n/messages/it.json index 7cf5b46bc..ed038adf2 100644 --- a/ui/desktop/src/i18n/messages/it.json +++ b/ui/desktop/src/i18n/messages/it.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "Visita" }, - "settings.agentLoop.description": { - "defaultMessage": "Usa il ciclo agente basato sulle operazioni. Disattivalo per usare il ciclo legacy." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Automatico" }, diff --git a/ui/desktop/src/i18n/messages/ja.json b/ui/desktop/src/i18n/messages/ja.json index 76008ec86..1751483f9 100644 --- a/ui/desktop/src/i18n/messages/ja.json +++ b/ui/desktop/src/i18n/messages/ja.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "次のURLにアクセスし、" }, - "settings.agentLoop.description": { - "defaultMessage": "オペレーションベースのエージェントループを使用します。オフにすると従来のループを使用します。" - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "自動" }, diff --git a/ui/desktop/src/i18n/messages/ko.json b/ui/desktop/src/i18n/messages/ko.json index ca36cd098..2805e8044 100644 --- a/ui/desktop/src/i18n/messages/ko.json +++ b/ui/desktop/src/i18n/messages/ko.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "방문하여" }, - "settings.agentLoop.description": { - "defaultMessage": "작업 기반 에이전트 루프를 사용합니다. 기존 루프를 사용하려면 끄세요." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "자동" }, diff --git a/ui/desktop/src/i18n/messages/ms.json b/ui/desktop/src/i18n/messages/ms.json index d9f8d810c..404305aa7 100644 --- a/ui/desktop/src/i18n/messages/ms.json +++ b/ui/desktop/src/i18n/messages/ms.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "Lawati" }, - "settings.agentLoop.description": { - "defaultMessage": "Gunakan gelung ejen berasaskan operasi. Matikan untuk menggunakan gelung legasi." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Automatik" }, diff --git a/ui/desktop/src/i18n/messages/pt.json b/ui/desktop/src/i18n/messages/pt.json index 3f796cfae..adc437e03 100644 --- a/ui/desktop/src/i18n/messages/pt.json +++ b/ui/desktop/src/i18n/messages/pt.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "Acesse" }, - "settings.agentLoop.description": { - "defaultMessage": "Use o loop do agente baseado em operações. Desative-o para usar o loop legado." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Automático" }, diff --git a/ui/desktop/src/i18n/messages/ru.json b/ui/desktop/src/i18n/messages/ru.json index c36becf06..7e8bffd3c 100644 --- a/ui/desktop/src/i18n/messages/ru.json +++ b/ui/desktop/src/i18n/messages/ru.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "Перейдите на" }, - "settings.agentLoop.description": { - "defaultMessage": "Использовать цикл агента на основе операций. Отключите, чтобы использовать прежний цикл." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Автоматически" }, diff --git a/ui/desktop/src/i18n/messages/tr.json b/ui/desktop/src/i18n/messages/tr.json index 40926a10d..22b527fed 100644 --- a/ui/desktop/src/i18n/messages/tr.json +++ b/ui/desktop/src/i18n/messages/tr.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "Ziyaret edin" }, - "settings.agentLoop.description": { - "defaultMessage": "İşlem tabanlı ajan döngüsünü kullanır. Eski döngüyü kullanmak için kapatın." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Otomatik" }, diff --git a/ui/desktop/src/i18n/messages/vi.json b/ui/desktop/src/i18n/messages/vi.json index 4c63a4a99..7973ceb69 100644 --- a/ui/desktop/src/i18n/messages/vi.json +++ b/ui/desktop/src/i18n/messages/vi.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "Truy cập" }, - "settings.agentLoop.description": { - "defaultMessage": "Sử dụng vòng lặp tác nhân dựa trên thao tác. Tắt tùy chọn này để dùng vòng lặp cũ." - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "Tự động" }, diff --git a/ui/desktop/src/i18n/messages/zh-CN.json b/ui/desktop/src/i18n/messages/zh-CN.json index 5d7371966..6be247171 100644 --- a/ui/desktop/src/i18n/messages/zh-CN.json +++ b/ui/desktop/src/i18n/messages/zh-CN.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "访问" }, - "settings.agentLoop.description": { - "defaultMessage": "使用基于操作的代理循环。关闭后将使用旧版循环。" - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "自动" }, diff --git a/ui/desktop/src/i18n/messages/zh-TW.json b/ui/desktop/src/i18n/messages/zh-TW.json index 1d89e6e17..5fa1b200b 100644 --- a/ui/desktop/src/i18n/messages/zh-TW.json +++ b/ui/desktop/src/i18n/messages/zh-TW.json @@ -4676,9 +4676,6 @@ "providerConfigurationModal.deviceCodeVisit": { "defaultMessage": "前往" }, - "settings.agentLoop.description": { - "defaultMessage": "使用以操作為基礎的代理程式迴圈。關閉後將使用舊版迴圈。" - }, "settings.agentLoop.operations.auto.placeholder": { "defaultMessage": "自動" }, diff --git a/ui/desktop/src/main.ts b/ui/desktop/src/main.ts index 45a4a7a0a..e471df645 100644 --- a/ui/desktop/src/main.ts +++ b/ui/desktop/src/main.ts @@ -1930,7 +1930,6 @@ const validSettingKeys: Set = new Set([ 'seenAnnouncementIds', 'disableAutoDownload', 'recentModels', - 'useLegacyAgentLoop', ]); ipcMain.handle('set-setting', (_event, key: SettingKey, value: unknown) => { diff --git a/ui/desktop/src/utils/settings.ts b/ui/desktop/src/utils/settings.ts index 9c02f3fe9..f693cd97c 100644 --- a/ui/desktop/src/utils/settings.ts +++ b/ui/desktop/src/utils/settings.ts @@ -55,7 +55,6 @@ export interface Settings { showPricing: boolean; seenAnnouncementIds: string[]; recentModels: RecentModel[]; - useLegacyAgentLoop: boolean; } export type SettingKey = keyof Settings; @@ -97,7 +96,6 @@ export const defaultSettings: Settings = { showPricing: true, seenAnnouncementIds: [], recentModels: [], - useLegacyAgentLoop: false, }; export function getKeyboardShortcuts(settings: Settings): KeyboardShortcuts {