diff --git a/.github/workflows/patched-test.yml b/.github/workflows/patched-test.yml index 4cd3d1432e37..c0c2fe63077a 100644 --- a/.github/workflows/patched-test.yml +++ b/.github/workflows/patched-test.yml @@ -90,7 +90,19 @@ jobs: "providers::formats::gcpvertexai::tests::claude_adaptive_thinking_requests_summarized_display" \ "agents::reply_parts::tests::toolshim_provider_stream_coalesces_streamed_thinking" \ "agents::reply_parts::tests::thinking_deltas_before_transient_error_retries_and_succeeds" \ - "agents::reply_parts::tests::signed_thinking_close_before_transient_error_does_not_retry" + "agents::reply_parts::tests::signed_thinking_close_before_transient_error_does_not_retry" \ + "acp::turn_error::tests::provider_errors_map_to_their_kind" \ + "acp::turn_error::tests::loop_errors_map_to_their_kind" \ + "acp::turn_error::tests::turn_failed_data_carries_reason_kind_and_message" \ + "acp::turn_error::tests::turn_error_message_under_the_cap_is_kept_whole" \ + "acp::turn_error::tests::turn_error_message_over_the_cap_is_cut_on_a_char_boundary" \ + "acp::server::tests::test_authentication_message_maps_to_auth_required" \ + "acp::server::tests::test_other_error_messages_map_to_internal_error" + + run_exact_tests --release -p goose --features "$F" --test acp_server_test -- \ + "test_prompt_reports_context_error_when_compaction_limit_is_exhausted" \ + "test_prompt_fails_and_streams_the_error" \ + "test_manual_compaction_refusal_fails_without_replacing_context" run_exact_tests --release -p goose-provider-types --lib -- \ "formats::anthropic::tests::native_claude_thinking_carries_display_and_block_binding" \ diff --git a/crates/goose/src/acp/mod.rs b/crates/goose/src/acp/mod.rs index e1ae866ada5d..2ad28e8bcf8e 100644 --- a/crates/goose/src/acp/mod.rs +++ b/crates/goose/src/acp/mod.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: turn_error module for session/prompt error.data.kind. mod common; mod handoff; #[cfg(feature = "acp-http")] @@ -9,6 +10,7 @@ pub mod server_factory; pub(crate) mod tool_call_notifier; #[cfg(feature = "acp-http")] pub mod transport; +mod turn_error; pub use common::{map_permission_response, PermissionDecision}; pub use goose_sdk_types::{custom_notifications, custom_requests}; diff --git a/crates/goose/src/acp/server.rs b/crates/goose/src/acp/server.rs index 43fae0278709..fc549abdba97 100644 --- a/crates/goose/src/acp/server.rs +++ b/crates/goose/src/acp/server.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: session/prompt turn_failed errors carry data.kind and data.message. use crate::acp::custom_notifications::*; use crate::acp::custom_requests::*; pub(super) use crate::acp::response_builder::{ @@ -1618,7 +1619,7 @@ fn prompt_error_from_message_content( MessageContent::Error(error) if error.kind == crate::conversation::message::MessageErrorKind::Authentication => { - Some(agent_client_protocol::Error::auth_required().data(turn_failed_data())) + Some(agent_client_protocol::Error::auth_required().data(turn_failed_data(error))) } MessageContent::SystemNotification(notification) if notification.notification_type == SystemNotificationType::CreditsExhausted => @@ -1640,14 +1641,14 @@ fn prompt_error_from_message_content( } MessageContent::Error(error) => Some( agent_client_protocol::Error::new(-32603, error.message.clone()) - .data(turn_failed_data()), + .data(turn_failed_data(error)), ), _ => None, } } -fn turn_failed_data() -> serde_json::Value { - serde_json::json!({ "reason": crate::acp::TURN_FAILED_REASON }) +fn turn_failed_data(error: &crate::conversation::message::ErrorContent) -> serde_json::Value { + crate::acp::turn_error::turn_failed_data(error) } fn credits_exhausted_prompt_error( @@ -3441,7 +3442,9 @@ print(\"hello, world\") error.code, agent_client_protocol::schema::v1::ErrorCode::AuthRequired ); - assert_eq!(error.data.unwrap()["reason"], "turn_failed"); + let data = error.data.unwrap(); + assert_eq!(data["reason"], "turn_failed"); + assert_eq!(data["kind"], "authentication"); } #[test] @@ -3459,7 +3462,7 @@ print(\"hello, world\") serde_json::json!({ "code": -32603, "message": message, - "data": { "reason": "turn_failed" } + "data": { "reason": "turn_failed", "kind": "network", "message": message } }) ); } diff --git a/crates/goose/src/acp/turn_error.rs b/crates/goose/src/acp/turn_error.rs new file mode 100644 index 000000000000..ddcaaa33285d --- /dev/null +++ b/crates/goose/src/acp/turn_error.rs @@ -0,0 +1,198 @@ +// Modified by Jonathan Mohrbacher, 2026: session/prompt turn errors carry a kind and a bounded message in error.data. +//! Why a turn failed, for clients that only see the `session/prompt` error. +//! +//! Upstream fails the prompt with `data: {reason: "turn_failed"}` and the full +//! error text as the RPC message. Clients that branch on the cause (stall-watch's +//! circuit breaker, honk's turn log) also need a stable kind, so the data +//! becomes `{reason, kind, message}`. The kind is recovered from the persisted +//! error message, which is all the server has once the turn has ended. + +use crate::agents::state_machine::{is_compaction_failure_message, is_retry_failure_message}; +use crate::conversation::message::{ErrorContent, MessageErrorKind}; +use goose_agent::max_turns::MAX_TURNS_MESSAGE; +use goose_providers::errors::ProviderError; +use serde::Serialize; + +pub(crate) const TURN_ERROR_MESSAGE_MAX_BYTES: usize = 2048; + +const TRUNCATION_MARKER: &str = "…"; +const REFUSAL_PREFIX: &str = "The provider refused this request."; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum TurnErrorKind { + Authentication, + Compaction, + ContextLength, + CreditsExhausted, + MaxTurns, + Network, + Provider, + Refusal, + ResourceExhausted, + RetryExhausted, +} + +pub(crate) fn turn_error_kind(error: &ErrorContent) -> TurnErrorKind { + match error.kind { + MessageErrorKind::Authentication => TurnErrorKind::Authentication, + MessageErrorKind::ContextLengthExceeded => TurnErrorKind::ContextLength, + MessageErrorKind::CreditsExhausted => TurnErrorKind::CreditsExhausted, + MessageErrorKind::ResourceExhausted if error.message == MAX_TURNS_MESSAGE => { + TurnErrorKind::MaxTurns + } + MessageErrorKind::ResourceExhausted => TurnErrorKind::ResourceExhausted, + MessageErrorKind::Other => kind_from_message(&error.message), + } +} + +fn kind_from_message(message: &str) -> TurnErrorKind { + if is_compaction_failure_message(message) { + TurnErrorKind::Compaction + } else if is_retry_failure_message(message) { + TurnErrorKind::RetryExhausted + } else if message.starts_with(&ProviderError::NetworkError(String::new()).to_string()) { + TurnErrorKind::Network + } else if message.starts_with(REFUSAL_PREFIX) { + TurnErrorKind::Refusal + } else { + TurnErrorKind::Provider + } +} + +pub(crate) fn turn_failed_data(error: &ErrorContent) -> serde_json::Value { + serde_json::json!({ + "reason": crate::acp::TURN_FAILED_REASON, + "kind": turn_error_kind(error), + "message": truncate_message(&error.message), + }) +} + +fn truncate_message(message: &str) -> String { + if message.len() <= TURN_ERROR_MESSAGE_MAX_BYTES { + return message.to_string(); + } + let budget = TURN_ERROR_MESSAGE_MAX_BYTES - TRUNCATION_MARKER.len(); + let mut kept = String::with_capacity(TURN_ERROR_MESSAGE_MAX_BYTES); + for c in message.chars() { + if kept.len() + c.len_utf8() > budget { + break; + } + kept.push(c); + } + kept.push_str(TRUNCATION_MARKER); + kept +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::conversation::message::Message; + + fn kind_of(message: Message) -> TurnErrorKind { + turn_error_kind(message.error().expect("message carries an error")) + } + + fn provider_error_kind(err: ProviderError) -> TurnErrorKind { + kind_of(Message::from_provider_error(&err)) + } + + #[test] + fn provider_errors_map_to_their_kind() { + assert_eq!( + provider_error_kind(ProviderError::NetworkError("connection reset".into())), + TurnErrorKind::Network + ); + assert_eq!( + provider_error_kind(ProviderError::Refusal { + details: "no".into(), + category: Some("cyber".into()), + }), + TurnErrorKind::Refusal + ); + assert_eq!( + provider_error_kind(ProviderError::ContextLengthExceeded("too long".into())), + TurnErrorKind::ContextLength + ); + assert_eq!( + provider_error_kind(ProviderError::Authentication("expired".into())), + TurnErrorKind::Authentication + ); + assert_eq!( + provider_error_kind(ProviderError::ServerError("HTTP 503".into())), + TurnErrorKind::Provider + ); + assert_eq!( + provider_error_kind(ProviderError::RateLimitExceeded { + details: "slow down".into(), + retry_delay: None, + }), + TurnErrorKind::Provider + ); + } + + #[test] + fn loop_errors_map_to_their_kind() { + let other = |text: &str| Message::assistant().with_error(MessageErrorKind::Other, text); + assert_eq!( + kind_of(other( + "Maximum retry attempts (2) exceeded. Unable to complete the task successfully." + )), + TurnErrorKind::RetryExhausted + ); + assert_eq!( + kind_of(other("Retry logic encountered an error: boom")), + TurnErrorKind::RetryExhausted + ); + assert_eq!( + kind_of(other( + "Ran into this error trying to compact: refused.\n\nPlease try again" + )), + TurnErrorKind::Compaction + ); + let exhausted = + |text: &str| Message::assistant().with_error(MessageErrorKind::ResourceExhausted, text); + assert_eq!( + kind_of(exhausted(MAX_TURNS_MESSAGE)), + TurnErrorKind::MaxTurns + ); + assert_eq!( + kind_of(exhausted("turn budget exhausted")), + TurnErrorKind::ResourceExhausted + ); + assert_eq!( + kind_of(Message::assistant().with_error(MessageErrorKind::CreditsExhausted, "top up")), + TurnErrorKind::CreditsExhausted + ); + } + + #[test] + fn turn_failed_data_carries_reason_kind_and_message() { + let message = Message::from_provider_error(&ProviderError::NetworkError("reset".into())); + let error = message.error().unwrap(); + assert_eq!( + turn_failed_data(error), + serde_json::json!({ + "reason": "turn_failed", + "kind": "network", + "message": error.message, + }) + ); + } + + #[test] + fn turn_error_message_under_the_cap_is_kept_whole() { + assert_eq!(truncate_message("connection reset"), "connection reset"); + } + + #[test] + fn turn_error_message_over_the_cap_is_cut_on_a_char_boundary() { + let message = truncate_message(&"é".repeat(TURN_ERROR_MESSAGE_MAX_BYTES)); + assert!(message.len() <= TURN_ERROR_MESSAGE_MAX_BYTES); + assert!(message.ends_with(TRUNCATION_MARKER)); + assert!(message + .trim_end_matches(TRUNCATION_MARKER) + .chars() + .all(|c| c == 'é')); + } +} diff --git a/crates/goose/src/agents/state_machine/mod.rs b/crates/goose/src/agents/state_machine/mod.rs index f568c1736790..8c9ad37963a5 100644 --- a/crates/goose/src/agents/state_machine/mod.rs +++ b/crates/goose/src/agents/state_machine/mod.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: export retry and compaction failure checks for turn errors. //! Runs an ordered, re-entrant pipeline over persisted conversation state. //! //! Callers persist incoming messages, construct `Step`s from their own operations, @@ -57,6 +58,7 @@ pub(crate) use tool_confirmation::{ pub(super) use goose_agent::skills::SkillOperation; pub(super) use inference_preparation::GooseInferenceRequestPreparer; pub(super) use ops_auto_effort::AutoEffortOperation; +pub(crate) use ops_compaction::is_compaction_failure_message; pub(super) use ops_compaction::CompactionOperation; pub(super) use ops_context_relevance::{ContextRelevanceOperation, UnavailableDecisions}; pub(super) use ops_doctor::DoctorOperation; @@ -68,6 +70,7 @@ pub(super) use ops_recipe::RecipeOperation; pub(super) use ops_remaining_tool_calls::RemainingToolCallsOperation; #[cfg(test)] pub(super) use ops_remaining_tool_calls::UNCLAIMED_TOOL_ERROR; +pub(crate) use ops_retry::is_retry_failure_message; pub(super) use ops_retry::RetryOperation; pub(super) use ops_skills::{GooseSkillSource, NO_SKILLS_HELP}; pub(super) use ops_status::StatusOperation; diff --git a/crates/goose/src/agents/state_machine/ops_compaction.rs b/crates/goose/src/agents/state_machine/ops_compaction.rs index 8bd1b85e3ef1..cb5074e14783 100644 --- a/crates/goose/src/agents/state_machine/ops_compaction.rs +++ b/crates/goose/src/agents/state_machine/ops_compaction.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: compaction failure messages are recognisable as turn errors. //! Compacts conversation history when it is too large for the configured context window. use std::sync::Arc; @@ -268,6 +269,12 @@ impl Operation for CompactionOperation { } } +const COMPACTION_FAILURE_PREFIX: &str = "Ran into this error trying to compact: "; + +pub(crate) fn is_compaction_failure_message(message: &str) -> bool { + message.starts_with(COMPACTION_FAILURE_PREFIX) +} + fn compaction_failure_message(e: &anyhow::Error) -> Message { let provider_error = e.downcast_ref::(); if let Some(err @ ProviderError::CreditsExhausted { .. }) = provider_error { @@ -276,7 +283,7 @@ fn compaction_failure_message(e: &anyhow::Error) -> Message { Message::assistant().with_error( provider_error.map_or(MessageErrorKind::Other, MessageErrorKind::from), format!( - "Ran into this error trying to compact: {e}.\n\n\ + "{COMPACTION_FAILURE_PREFIX}{e}.\n\n\ Please try again or create a new session" ), ) diff --git a/crates/goose/src/agents/state_machine/ops_retry.rs b/crates/goose/src/agents/state_machine/ops_retry.rs index b2ef6b569083..bd7c42d3059c 100644 --- a/crates/goose/src/agents/state_machine/ops_retry.rs +++ b/crates/goose/src/agents/state_machine/ops_retry.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: retry failure messages are recognisable as turn errors. //! Decides whether a completed response should finish, continue, or retry the turn. use anyhow::{anyhow, Result}; @@ -19,10 +20,17 @@ use crate::session::{GoalState, Session}; pub(super) const NUDGED: &str = "nudged"; pub(super) const ATTEMPTS: &str = "attempts"; +const RETRY_ERROR_PREFIX: &str = "Retry logic encountered an error: "; +const MAX_RETRIES_PREFIX: &str = "Maximum retry attempts ("; + +pub(crate) fn is_retry_failure_message(message: &str) -> bool { + message.starts_with(RETRY_ERROR_PREFIX) || message.starts_with(MAX_RETRIES_PREFIX) +} + fn retry_error(error: &str) -> Message { Message::assistant().with_error( MessageErrorKind::Other, - format!("Retry logic encountered an error: {error}"), + format!("{RETRY_ERROR_PREFIX}{error}"), ) } @@ -281,7 +289,7 @@ impl Operation for RetryOperation { let message = Message::assistant().with_error( MessageErrorKind::Other, format!( - "Maximum retry attempts ({}) exceeded. Unable to complete the task successfully.", + "{MAX_RETRIES_PREFIX}{}) exceeded. Unable to complete the task successfully.", retry_config.max_retries ), ); diff --git a/crates/goose/tests/acp_server_test.rs b/crates/goose/tests/acp_server_test.rs index 93b832ab307b..1f9d5b696c6a 100644 --- a/crates/goose/tests/acp_server_test.rs +++ b/crates/goose/tests/acp_server_test.rs @@ -1,4 +1,4 @@ -// Modified by Jonathan Mohrbacher, 2026: recipe settings.thinking_effort overrides the inherited delegate effort. +// Modified by Jonathan Mohrbacher, 2026: recipe settings.thinking_effort overrides the inherited delegate effort; turn_failed errors carry data.kind. #![recursion_limit = "256"] #[allow(dead_code)] #[path = "acp_common_tests/mod.rs"] @@ -1585,7 +1585,9 @@ fn test_prompt_reports_context_error_when_compaction_limit_is_exhausted() { .unwrap_err(); let error = prompt_acp_error(error); assert_eq!(error.code, ErrorCode::InternalError); - assert_eq!(error.data.unwrap()["reason"], "turn_failed"); + let data = error.data.unwrap(); + assert_eq!(data["reason"], "turn_failed"); + assert_eq!(data["kind"], "context_length"); }); } @@ -1598,6 +1600,7 @@ fn test_prompt_fails_and_streams_the_error() { prompt_and_stream("partial", vec![("partial", PARTIAL_THEN_STREAM_ERROR)]).await; let error = prompt_acp_error(result.unwrap_err()); assert_eq!(error.code, ErrorCode::InternalError); + assert_eq!(error.data.as_ref().unwrap()["kind"], "provider"); assert!( streamed.contains("partial answer") && streamed.contains("upstream exploded"), "streamed text: {streamed:?}" @@ -1654,7 +1657,9 @@ fn test_manual_compaction_refusal_fails_without_replacing_context() { assert!(!streamed.contains("Compaction complete"), "{streamed:?}"); let error = prompt_acp_error(result.unwrap_err()); assert_eq!(error.code, ErrorCode::InternalError); - assert_eq!(error.data.unwrap()["reason"], "turn_failed"); + let data = error.data.unwrap(); + assert_eq!(data["reason"], "turn_failed"); + assert_eq!(data["kind"], "compaction"); let after = manager .get_session(&session.session_id().0, true) .await