diff --git a/codex-rs/core/src/context/world_state/environment.rs b/codex-rs/core/src/context/world_state/environment.rs index 188ec7723f..3a6c570925 100644 --- a/codex-rs/core/src/context/world_state/environment.rs +++ b/codex-rs/core/src/context/world_state/environment.rs @@ -18,6 +18,7 @@ use codex_protocol::models::ContentItem; use codex_protocol::models::ContentItemKind; use codex_protocol::models::input_text; use codex_protocol::protocol::NetworkAccess; +use codex_utils_output_truncation::ErrorContextBudget; use codex_utils_path_uri::PathUri; use serde::Deserialize; use serde::Serialize; @@ -594,26 +595,20 @@ fn environment_states( network_access: None, }); } - // Bound the additional model context even when many selected environments fail. - const MAX_ERROR_BYTES: usize = 256; - const MAX_TOTAL_ERROR_BYTES: usize = 512; - let mut remaining_error_bytes = MAX_TOTAL_ERROR_BYTES; + let mut error_budget = ErrorContextBudget::default(); for environment in &snapshot.environments { if let TurnEnvironmentState::Failed { selection, error, .. } = environment { - let detail = error - [..error.floor_char_boundary(remaining_error_bytes.min(MAX_ERROR_BYTES))] - .to_string(); - remaining_error_bytes -= detail.len(); + let detail = error_budget.take(error); environments.insert( selection.environment_id.clone(), EnvironmentState { cwd: selection.cwd.clone(), status: EnvironmentStatus::Failed, shell: None, - error: (!detail.is_empty()).then_some(detail), + error: (!detail.is_empty()).then(|| detail.to_owned()), is_primary: false, filesystem: None, network_access: None, diff --git a/codex-rs/core/src/context/world_state/environment_tests.rs b/codex-rs/core/src/context/world_state/environment_tests.rs index 598a141438..9ca5e1fffa 100644 --- a/codex-rs/core/src/context/world_state/environment_tests.rs +++ b/codex-rs/core/src/context/world_state/environment_tests.rs @@ -467,9 +467,12 @@ fn failure_context_is_escaped_incremental_and_cleared_on_recovery() -> Result<() fn failure_context_limits_total_detail_bytes_at_utf8_boundaries() { use codex_protocol::protocol::EnvironmentConfigState; use codex_protocol::protocol::TurnEnvironmentSelection; + let long_error = "界".repeat(300); let snapshot = TurnEnvironmentSnapshot { - environments: (0..4) - .map(|index| TurnEnvironmentState::Failed { + environments: [long_error.as_str(), &long_error, &long_error, "abc", "d"] + .into_iter() + .enumerate() + .map(|(index, error)| TurnEnvironmentState::Failed { required_skills: Vec::new(), selection: TurnEnvironmentSelection { selected_capability_roots: Default::default(), @@ -478,7 +481,7 @@ fn failure_context_limits_total_detail_bytes_at_utf8_boundaries() { workspace_roots: Vec::new(), config: EnvironmentConfigState::FromThread, }, - error: "界".repeat(300), + error: error.to_owned(), }) .collect(), }; @@ -494,6 +497,7 @@ fn failure_context_limits_total_detail_bytes_at_utf8_boundaries() { Some(truncated.as_str()), Some(truncated.as_str()), None, + Some("ab"), None ] ); diff --git a/codex-rs/core/src/tools/handlers/wait_for_environment.rs b/codex-rs/core/src/tools/handlers/wait_for_environment.rs index 449413a3c5..2df554352e 100644 --- a/codex-rs/core/src/tools/handlers/wait_for_environment.rs +++ b/codex-rs/core/src/tools/handlers/wait_for_environment.rs @@ -3,6 +3,7 @@ use codex_tools::JsonToolOutput; use codex_tools::ResponsesApiTool; use codex_tools::ToolName; use codex_tools::ToolSpec; +use codex_utils_output_truncation::ErrorContextBudget; use serde::Deserialize; use serde_json::json; use std::collections::BTreeMap; @@ -170,10 +171,8 @@ impl ToolExecutor for WaitForEnvironmentHandler { impl CoreToolRuntime for WaitForEnvironmentHandler {} -// Keep failure output small while preserving a UTF-8 boundary. fn environment_failure(environment_id: &str, error: &str) -> FunctionCallError { - const MAX_ERROR_BYTES: usize = 256; - let reason = &error[..error.floor_char_boundary(MAX_ERROR_BYTES)]; + let reason = ErrorContextBudget::default().take(error); FunctionCallError::RespondToModel(format!( "Environment `{environment_id}` failed to start: {reason}" )) diff --git a/codex-rs/utils/output-truncation/src/lib.rs b/codex-rs/utils/output-truncation/src/lib.rs index e676a9d3c7..fb0f68c23a 100644 --- a/codex-rs/utils/output-truncation/src/lib.rs +++ b/codex-rs/utils/output-truncation/src/lib.rs @@ -1,4 +1,4 @@ -//! Shared byte/token truncation for tool and exec output. +//! Shared byte/token truncation for model-visible error details, tool output, and exec output. use std::borrow::Cow; @@ -13,10 +13,38 @@ pub use codex_utils_string::approx_bytes_for_tokens; pub use codex_utils_string::approx_token_count; pub use codex_utils_string::approx_tokens_from_byte_count; use codex_utils_string::plan_token_truncation; +use codex_utils_string::take_bytes_at_char_boundary; use codex_utils_string::truncate_middle_chars; pub use codex_protocol::protocol::TruncationPolicy; +/// Bounds error details in a single context fragment or tool result. +/// Limits apply to the raw UTF-8 text before escaping or adding markup. +pub struct ErrorContextBudget { + remaining_bytes: usize, +} + +impl ErrorContextBudget { + const MAX_DETAIL_BYTES: usize = 256; + const MAX_TOTAL_BYTES: usize = 512; + + /// Charge only the returned prefix so later errors can use any leftover bytes. + pub fn take<'a>(&mut self, error: &'a str) -> &'a str { + let prefix = + take_bytes_at_char_boundary(error, self.remaining_bytes.min(Self::MAX_DETAIL_BYTES)); + self.remaining_bytes -= prefix.len(); + prefix + } +} + +impl Default for ErrorContextBudget { + fn default() -> Self { + Self { + remaining_bytes: Self::MAX_TOTAL_BYTES, + } + } +} + /// Adds the existing 20% allowance for serialization and headers. /// Saved history budgets already include this allowance. pub fn with_serialization_allowance(policy: TruncationPolicy) -> TruncationPolicy {