Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion .github/workflows/patched-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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" \
Expand Down
2 changes: 2 additions & 0 deletions crates/goose/src/acp/mod.rs
Original file line number Diff line number Diff line change
@@ -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")]
Expand All @@ -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};
Expand Down
15 changes: 9 additions & 6 deletions crates/goose/src/acp/server.rs
Original file line number Diff line number Diff line change
@@ -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::{
Expand Down Expand Up @@ -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 =>
Expand All @@ -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(
Expand Down Expand Up @@ -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]
Expand All @@ -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 }
})
);
}
Expand Down
198 changes: 198 additions & 0 deletions crates/goose/src/acp/turn_error.rs
Original file line number Diff line number Diff line change
@@ -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 == 'é'));
}
}
3 changes: 3 additions & 0 deletions crates/goose/src/agents/state_machine/mod.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down
9 changes: 8 additions & 1 deletion crates/goose/src/agents/state_machine/ops_compaction.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -268,6 +269,12 @@ impl Operation<Session, GooseEffect> 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::<ProviderError>();
if let Some(err @ ProviderError::CreditsExhausted { .. }) = provider_error {
Expand All @@ -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"
),
)
Expand Down
12 changes: 10 additions & 2 deletions crates/goose/src/agents/state_machine/ops_retry.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand All @@ -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}"),
)
}

Expand Down Expand Up @@ -281,7 +289,7 @@ impl Operation<Session, GooseEffect> 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
),
);
Expand Down
Loading
Loading