use std::collections::HashSet; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use ts_rs::TS; use super::InternalChatMessageMetadataPassthrough; use super::ResponseItem; /// Maximum distinct result sources retained for one tool invocation. const MAX_TOOL_RESULT_SOURCES: usize = 32; /// Maximum UTF-8 bytes for each source's `type` and `id` separately, not the source list. pub const MAX_TOOL_RESULT_SOURCE_FIELD_BYTES: usize = 128; const RESOURCE_ACCESS_METADATA_KEY: &str = "openai/resource_access"; const EXECUTED_TOOL_CALL_METADATA_FIELD_BYTES: usize = b"\"executed_tool_calls\":".len(); const INTERNAL_CHAT_MESSAGE_METADATA_PASSTHROUGH_FIELD_BYTES: usize = b"\"internal_chat_message_metadata_passthrough\":".len(); fn executed_tool_call_metadata_field_bytes( metadata: &InternalChatMessageMetadataPassthrough, ) -> usize { let fields = InternalChatMessageMetadataPassthrough { cell_id: metadata.cell_id.clone(), tool_calls_complete: metadata.tool_calls_complete, ..Default::default() }; let mut bytes = serde_json::to_vec(&fields).map_or(usize::MAX, |fields| fields.len().saturating_sub(2)); if metadata.executed_tool_calls.is_some() { bytes = bytes .saturating_add(usize::from(bytes > 0)) .saturating_add(EXECUTED_TOOL_CALL_METADATA_FIELD_BYTES); } if bytes == 0 { 0 } else if metadata.turn_id.is_some() || metadata.create_time.is_some() || metadata.content_item_kinds.is_some() || metadata.content_item_metadata.is_some() { bytes + 1 } else { bytes + INTERNAL_CHAT_MESSAGE_METADATA_PASSTHROUGH_FIELD_BYTES + 3 } } /// Returns the exact serialized wire size of an item's attempted-tool metadata. pub fn executed_tool_call_metadata_bytes(item: &ResponseItem) -> usize { let Some(metadata) = item.executed_tool_call_metadata() else { return 0; }; metadata .executed_tool_calls .as_ref() .map_or(0, |calls| { serde_json::to_vec(calls) .map(|calls| calls.len()) .unwrap_or(usize::MAX) }) .saturating_add(executed_tool_call_metadata_field_bytes(metadata)) } impl InternalChatMessageMetadataPassthrough { /// Compares call order, names and arguments, ignoring optional result metadata. pub fn has_same_tool_calls(&self, calls: &[ExecutedToolCall]) -> bool { self.executed_tool_calls.as_ref().is_some_and(|recorded| { recorded.len() == calls.len() && recorded.iter().zip(calls).all(|(recorded, call)| { recorded.name == call.name && recorded.arguments() == call.arguments() }) }) } /// Compares the complete ordered call inventory, independently of recorded arguments. pub fn has_same_tool_call_inventory(&self, calls: &[ExecutedToolCall]) -> bool { self.executed_tool_calls.as_ref().is_some_and(|recorded| { recorded.len() == calls.len() && recorded.iter().zip(calls).all(|(recorded, call)| { recorded.name == call.name && recorded.has_complete_inventory() && call.has_complete_inventory() }) }) } } /// Clears completion across a cell when recorded calls or tool names were lost. /// Argument truncation preserves inventory completeness; arguments and outputs are unchanged. pub fn normalize_executed_tool_call_completeness(items: &mut [ResponseItem]) { let mut damaged_cells = HashSet::new(); for item in items.iter_mut() { let Some(metadata) = item .internal_chat_message_metadata_passthrough_mut() .and_then(Option::as_mut) else { continue; }; if metadata .executed_tool_calls .iter() .flatten() .any(|call| !call.has_complete_inventory()) { metadata.tool_calls_complete = None; damaged_cells.extend(metadata.cell_id.clone()); } } clear_damaged_cell_completeness(items, &damaged_cells); } /// Bounds optional observations to the space left in the actual outgoing message. /// Ordinary output and unrelated item metadata are never changed. pub fn bound_executed_tool_calls_for_message( items: &mut [ResponseItem], max_metadata_bytes: usize, ) { let mut damaged_cells = HashSet::new(); let total_metadata_bytes = metadata_bytes(items); if total_metadata_bytes <= max_metadata_bytes { return; } let mut remaining_bytes = shed_generic_result_metadata(items, max_metadata_bytes, total_metadata_bytes); // Shed optional sources and recorded arguments before resource-access evidence. if metadata_bytes(items) > max_metadata_bytes { let overage_bytes = shed_result_sources(items, max_metadata_bytes); if overage_bytes > 0 { truncate_call_arguments_to_fit(items, max_metadata_bytes, overage_bytes); } remaining_bytes = metadata_bytes(items); } shed_remaining_result_metadata(items, max_metadata_bytes, remaining_bytes); // Recheck the serialized request rather than relying on the incremental size accounting. if metadata_bytes(items) <= max_metadata_bytes { return; } // Omission markers are optional too; keep the original call budget if they cannot fit. for item in items.iter_mut() { item.clear_tool_result_metadata(); } if metadata_bytes(items) <= max_metadata_bytes { return; } distribute_remaining_budget(items, max_metadata_bytes, &mut damaged_cells); clear_damaged_cell_completeness(items, &damaged_cells); } fn metadata_bytes(items: &[ResponseItem]) -> usize { items.iter().fold(0_usize, |bytes, item| { bytes.saturating_add(executed_tool_call_metadata_bytes(item)) }) } type ResultMetadataEntry<'a> = (usize, usize, usize, &'a mut ToolResultMetadata); fn result_metadata_by_size(items: &mut [ResponseItem]) -> Vec> { let mut result_metadata = Vec::new(); for (item_index, item) in items.iter_mut().enumerate() { if let Some(metadata) = item .internal_chat_message_metadata_passthrough_mut() .and_then(Option::as_mut) { for (call_index, call) in metadata .executed_tool_calls .iter_mut() .flatten() .enumerate() { if call.tool_result_metadata.is_some() { let bytes = serde_json::to_vec(&call.tool_result_metadata) .map_or(usize::MAX, |value| value.len()); result_metadata.push(( bytes, item_index, call_index, &mut call.tool_result_metadata, )); } } } } result_metadata.sort_by_key(|(bytes, order, call_index, _)| { (std::cmp::Reverse(*bytes), *order, *call_index) }); result_metadata } fn shed_generic_result_metadata( items: &mut [ResponseItem], max_metadata_bytes: usize, mut total_metadata_bytes: usize, ) -> usize { // Shed the largest values first so one large result does not discard unrelated small results. let mut result_metadata = result_metadata_by_size(items); for (bytes, _, _, metadata) in &mut result_metadata { if total_metadata_bytes <= max_metadata_bytes { break; } if metadata.retain_resource_access() { let retained_bytes = serde_json::to_vec(&**metadata).map_or(usize::MAX, |value| value.len()); total_metadata_bytes = total_metadata_bytes.saturating_sub(bytes.saturating_sub(retained_bytes)); *bytes = retained_bytes; } else { let retained_bytes = metadata.omit_if_smaller(*bytes, total_metadata_bytes - max_metadata_bytes); total_metadata_bytes = total_metadata_bytes.saturating_sub(*bytes - retained_bytes); *bytes = retained_bytes; } } // Tiny generic values and markers can be cheaper than replacing them with a // new marker. Remove their complete fields before sacrificing resource evidence. for (bytes, _, _, metadata) in &mut result_metadata { if total_metadata_bytes <= max_metadata_bytes { break; } if metadata.retain_resource_access() { continue; } **metadata = ToolResultMetadata::default(); total_metadata_bytes = total_metadata_bytes .saturating_sub(bytes.saturating_add(b",\"tool_result_metadata\":".len())); *bytes = 0; } total_metadata_bytes } fn shed_remaining_result_metadata( items: &mut [ResponseItem], max_metadata_bytes: usize, mut total_metadata_bytes: usize, ) { let mut result_metadata = result_metadata_by_size(items); // Resource evidence is optional too; it must not displace the call inventory. for (bytes, _, _, metadata) in &mut result_metadata { if total_metadata_bytes <= max_metadata_bytes { break; } // An omission marker can be larger than a small object, including an empty `_meta`. let retained_bytes = metadata.omit_if_smaller(*bytes, total_metadata_bytes - max_metadata_bytes); total_metadata_bytes = total_metadata_bytes.saturating_sub(*bytes - retained_bytes); *bytes = retained_bytes; } // Use the updated sizes: markers should be removed before smaller provider metadata. result_metadata.sort_by_key(|(bytes, order, call_index, metadata)| { ( !metadata.is_omitted_due_to_size_limit(), std::cmp::Reverse(*bytes), *order, *call_index, ) }); for (bytes, _, _, metadata) in result_metadata { if total_metadata_bytes <= max_metadata_bytes { break; } if metadata.is_none() { continue; } *metadata = ToolResultMetadata::default(); // The required name and arguments always precede this optional serialized field. total_metadata_bytes = total_metadata_bytes .saturating_sub(bytes.saturating_add(b",\"tool_result_metadata\":".len())); } } fn shed_result_sources(items: &mut [ResponseItem], max_metadata_bytes: usize) -> usize { // Source evidence is optional; dropping it must not discard calls or their completion proof. let mut overage_bytes = metadata_bytes(items).saturating_sub(max_metadata_bytes); for item in items.iter_mut() { if let Some(metadata) = item .internal_chat_message_metadata_passthrough_mut() .and_then(Option::as_mut) { for call in metadata.executed_tool_calls.iter_mut().flatten() { if overage_bytes == 0 { break; } if let Some(sources) = call.tool_result_sources.take() { let bytes = serde_json::to_vec(&sources).map_or(usize::MAX, |value| value.len()); overage_bytes = overage_bytes .saturating_sub(bytes.saturating_add(b",\"tool_result_sources\":".len())); } } } } overage_bytes } fn truncate_call_arguments_to_fit( items: &mut [ResponseItem], max_metadata_bytes: usize, mut overage_bytes: usize, ) { // A large outgoing message should not lose the other tool names in a // cell when replacing one call's arguments is enough to make it fit. for index in 0..items.len() { while overage_bytes > 0 { let Some(metadata) = items[index] .internal_chat_message_metadata_passthrough_mut() .and_then(Option::as_mut) else { break; }; let mut arguments_changed = false; for call in metadata.executed_tool_calls.iter_mut().flatten() { if call.truncation().is_some() { continue; } let original_bytes = serde_json::to_vec(&call.arguments).map_or(usize::MAX, |value| value.len()); let truncated = ExecutedToolCallArguments::Truncated { truncation: ExecutedToolCallTruncation { original_bytes, max_bytes: original_bytes.saturating_sub(overage_bytes), omitted_calls: None, original_name_bytes: None, }, }; let truncated_bytes = serde_json::to_vec(&truncated).map_or(usize::MAX, |value| value.len()); if truncated_bytes < original_bytes { call.arguments = truncated; arguments_changed = true; break; } } if !arguments_changed { break; } overage_bytes = metadata_bytes(items).saturating_sub(max_metadata_bytes); } } } fn distribute_remaining_budget( items: &mut [ResponseItem], max_metadata_bytes: usize, damaged_cells: &mut HashSet, ) { let mut remaining_items = items .iter() .filter(|item| executed_tool_call_metadata_bytes(item) > 0) .count(); let mut remaining_bytes = max_metadata_bytes; for item in items.iter_mut() { let item_bytes = executed_tool_call_metadata_bytes(item); if item_bytes == 0 { continue; } let item_budget = remaining_bytes / remaining_items; if item_bytes > item_budget { // Remember the cell before a too-small share removes its metadata entirely. let cell_id = item .executed_tool_call_metadata() .and_then(|metadata| metadata.cell_id.clone()); item.bound_executed_tool_calls_with_budget(item_budget); if item.executed_tool_call_metadata().is_none_or(|metadata| { metadata .executed_tool_calls .as_ref() .is_none_or(|calls| !calls.iter().all(ExecutedToolCall::has_complete_inventory)) }) { item.clear_tool_calls_complete(); damaged_cells.extend(cell_id); } } remaining_bytes = remaining_bytes.saturating_sub(executed_tool_call_metadata_bytes(item)); remaining_items -= 1; } } fn clear_damaged_cell_completeness(items: &mut [ResponseItem], damaged_cells: &HashSet) { for item in items { if item.executed_tool_call_metadata().is_some_and(|metadata| { metadata .cell_id .as_ref() .is_some_and(|cell_id| damaged_cells.contains(cell_id)) }) { item.clear_tool_calls_complete(); } } } /// Raw model arguments or trusted truncation metadata for an attempted tool call. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)] #[serde(untagged)] pub enum ExecutedToolCallArguments { Raw(serde_json::Value), #[serde(skip_deserializing)] Truncated { #[serde(rename = "_codex_executed_tool_call_truncated")] truncation: ExecutedToolCallTruncation, }, } /// A model-attempted Codex tool invocation captured at the shared runtime boundary. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)] pub struct ExecutedToolCall { pub name: String, #[ts(type = "unknown")] arguments: ExecutedToolCallArguments, /// Host-generated analytics only: ignore input JSON rather than accepting caller-supplied /// evidence, and keep this out of public schemas and generated clients. #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")] #[schemars(skip)] #[ts(skip)] tool_result_sources: Option>, /// Raw MCP result metadata is host-recorded only, never trusted from input JSON or exposed /// in public schemas. Its Debug implementation also prevents raw values reaching logs. #[serde( default, skip_deserializing, skip_serializing_if = "ToolResultMetadata::is_none" )] #[schemars(skip)] #[ts(skip)] tool_result_metadata: ToolResultMetadata, } /// MCP result metadata, optionally reduced to resource evidence, or a size-omission marker. #[derive(Clone, Default, Serialize, PartialEq, Eq)] #[serde(transparent)] pub struct ToolResultMetadata(Option); impl std::fmt::Debug for ToolResultMetadata { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("ToolResultMetadata([redacted])") } } impl ToolResultMetadata { /// Captures the complete result; retention and outgoing-request budgets apply later. pub fn new(metadata: &serde_json::Value) -> Self { Self(Some(metadata.clone())) } /// Leaves generic metadata unchanged when it has no resource-access field. fn retain_resource_access(&mut self) -> bool { let Some(serde_json::Value::Object(metadata)) = self.0.as_mut() else { return false; }; if !metadata.contains_key(RESOURCE_ACCESS_METADATA_KEY) { return false; } metadata.retain(|key, _| key == RESOURCE_ACCESS_METADATA_KEY); true } fn omitted_due_to_size_limit(overage_bytes: usize) -> Self { // MCP `_meta` is an object; this string is a harness omission status, not provider data. Self(Some(serde_json::Value::String(format!( "omitted_due_to_size_limit (overage_bytes={overage_bytes})" )))) } fn is_omitted_due_to_size_limit(&self) -> bool { let Some(serde_json::Value::String(value)) = self.0.as_ref() else { return false; }; value == "omitted_due_to_size_limit" || value .strip_prefix("omitted_due_to_size_limit (overage_bytes=") .and_then(|value| value.strip_suffix(')')) .is_some_and(|value| value.parse::().is_ok()) } fn omit_if_smaller(&mut self, original_bytes: usize, overage_bytes: usize) -> usize { if self.is_none() || self.is_omitted_due_to_size_limit() { return original_bytes; } let omitted = Self::omitted_due_to_size_limit(overage_bytes); let omitted_bytes = serde_json::to_vec(&omitted).map_or(usize::MAX, |value| value.len()); if omitted_bytes < original_bytes { *self = omitted; omitted_bytes } else { original_bytes } } /// Whether there is no captured result metadata. fn is_none(&self) -> bool { self.0.is_none() } /// Whether the captured snapshot contains metadata or an omission marker. pub fn is_some(&self) -> bool { self.0.is_some() } } /// A bounded capture update. Omitted updates still clear any previously recorded evidence. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ToolResultSources(Option>); impl ToolResultSources { /// Deduplicates a captured snapshot, discarding all sources if it exceeds a limit. /// Capture rules determine coverage; this is not a resource or permission inventory. pub fn new(sources: Vec) -> Self { let mut unique_sources = Vec::new(); for source in sources { if unique_sources.contains(&source) { continue; } if unique_sources.len() == MAX_TOOL_RESULT_SOURCES || source.r#type.len() > MAX_TOOL_RESULT_SOURCE_FIELD_BYTES || source.id.len() > MAX_TOOL_RESULT_SOURCE_FIELD_BYTES { return Self(None); } unique_sources.push(source); } Self(Some(unique_sources)) } /// Records a failed parse using the receiver's existing array-of-sources shape. /// `parse_failed` is a status marker, not a resource type; the required ID is empty. pub fn parse_failed() -> Self { Self(Some(vec![ToolResultSource { r#type: "parse_failed".to_string(), id: String::new(), }])) } } /// A captured source ID, or a `parse_failed` status marker with an empty ID. #[derive(Debug, Clone, Serialize, PartialEq, Eq)] pub struct ToolResultSource { #[serde(rename = "type")] pub r#type: String, pub id: String, } /// Trusted truncation details generated locally for an oversized attempted tool call. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)] pub struct ExecutedToolCallTruncation { original_bytes: usize, max_bytes: usize, #[serde(default, skip_serializing_if = "Option::is_none")] omitted_calls: Option, #[serde(default, skip_serializing_if = "Option::is_none")] original_name_bytes: Option, } impl ExecutedToolCall { /// Creates a recorded call without treating model-provided JSON as trusted metadata. pub fn new(name: String, arguments: serde_json::Value) -> Self { let arguments = if arguments .as_object() .is_some_and(|object| object.contains_key("_codex_executed_tool_call_truncated")) { serde_json::json!({ "_codex_executed_tool_call_raw": arguments }) } else { arguments }; Self { name, arguments: ExecutedToolCallArguments::Raw(arguments), tool_result_sources: None, tool_result_metadata: ToolResultMetadata::default(), } } /// Replaces oversized arguments with internally generated truncation metadata. pub fn truncated(name: String, original_bytes: usize, max_bytes: usize) -> Self { let mut call = Self::new(name, serde_json::Value::Null); call.set_truncation(original_bytes, max_bytes, /*omitted_calls*/ None); call } /// Returns the raw arguments or locally generated truncation payload. pub fn arguments(&self) -> &ExecutedToolCallArguments { &self.arguments } /// Whether this call has result metadata or an omission marker. pub fn has_tool_result_metadata(&self) -> bool { self.tool_result_metadata.is_some() } /// Replaces this invocation's capture outcome, including clearing omitted evidence. pub fn set_tool_result_sources(&mut self, sources: ToolResultSources) -> bool { self.tool_result_sources = sources.0; self.tool_result_sources.is_some() } /// Replaces the entire captured `_meta` snapshot. pub fn set_tool_result_metadata(&mut self, metadata: ToolResultMetadata) { self.tool_result_metadata = metadata; } fn truncation(&self) -> Option<&ExecutedToolCallTruncation> { match &self.arguments { ExecutedToolCallArguments::Raw(_) => None, ExecutedToolCallArguments::Truncated { truncation } => Some(truncation), } } /// Whether this entry retains its invocation and full tool name, regardless of arguments. pub fn has_complete_inventory(&self) -> bool { self.truncation().is_none_or(|truncation| { truncation.omitted_calls.unwrap_or_default() == 0 && truncation.original_name_bytes.is_none() }) } fn set_truncation( &mut self, original_bytes: usize, max_bytes: usize, omitted_calls: Option, ) { self.set_truncation_with_name( original_bytes, max_bytes, omitted_calls, /*original_name_bytes*/ None, ); } fn set_truncation_with_name( &mut self, original_bytes: usize, max_bytes: usize, omitted_calls: Option, original_name_bytes: Option, ) { self.arguments = ExecutedToolCallArguments::Truncated { truncation: ExecutedToolCallTruncation { original_bytes, max_bytes, omitted_calls, original_name_bytes, }, }; } } impl ResponseItem { fn ensure_tool_call_metadata(&mut self) -> Option<&mut InternalChatMessageMetadataPassthrough> { self.internal_chat_message_metadata_passthrough_mut() .map(Option::get_or_insert_default) } /// Associates host-recorded calls and completeness with their Code Mode cell. pub fn set_tool_call_cell_id(&mut self, cell_id: &str) { if let Some(metadata) = self.ensure_tool_call_metadata() { metadata.cell_id = Some(cell_id.to_string()); } } /// Attaches model-attempted tool invocations without replacing existing item metadata. pub fn append_executed_tool_calls(&mut self, calls: Vec) { if calls.is_empty() { return; } let Some(metadata) = self.ensure_tool_call_metadata() else { return; }; metadata .executed_tool_calls .get_or_insert_with(Vec::new) .extend(calls); } /// Marks a host-owned direct invocation or Code Mode cell's call inventory as complete. /// Always includes this output's call list, which can be an empty delta for a terminal wait. pub fn mark_tool_calls_complete(&mut self) { if let Some(metadata) = self.ensure_tool_call_metadata() { metadata.executed_tool_calls.get_or_insert_default(); metadata.tool_calls_complete = Some(true); } } /// Discards a completion claim when the host cannot retain the full call inventory. pub fn clear_tool_calls_complete(&mut self) { if let Some(metadata) = self .internal_chat_message_metadata_passthrough_mut() .and_then(Option::as_mut) { metadata.tool_calls_complete = None; } } /// Returns warehouse-only attempted-tool metadata for any supported item variant. pub fn executed_tool_call_metadata(&self) -> Option<&InternalChatMessageMetadataPassthrough> { self.internal_chat_message_metadata_passthrough() } /// Compares raw result metadata and its call bindings, ignoring other internal metadata. pub fn has_same_tool_result_metadata(&self, other: &Self) -> bool { fn result_metadata( item: &ResponseItem, ) -> impl Iterator { item.executed_tool_call_metadata() .and_then(|metadata| metadata.executed_tool_calls.as_ref()) .into_iter() .flatten() .enumerate() .filter(|(_, call)| call.tool_result_metadata.is_some()) .map(|(index, call)| { ( index, call.name.as_str(), call.arguments(), &call.tool_result_metadata, ) }) } result_metadata(self).eq(result_metadata(other)) } /// Whether an output carries raw result metadata or a harness omission marker. pub fn has_tool_result_metadata(&self) -> bool { self.executed_tool_call_metadata().is_some_and(|metadata| { metadata .executed_tool_calls .iter() .flatten() .any(|call| call.tool_result_metadata.is_some()) }) } /// Omits raw tool results without changing existing call, source or completion metadata. pub fn clear_tool_result_metadata(&mut self) { if let Some(metadata) = self .internal_chat_message_metadata_passthrough_mut() .and_then(Option::as_mut) { for call in metadata.executed_tool_calls.iter_mut().flatten() { call.tool_result_metadata = ToolResultMetadata::default(); } } } /// Marks larger raw results with the full request's overage, preserving existing markers. pub fn omit_tool_result_metadata(&mut self, overage_bytes: usize) { if let Some(metadata) = self .internal_chat_message_metadata_passthrough_mut() .and_then(Option::as_mut) { for call in metadata.executed_tool_calls.iter_mut().flatten() { let result = &mut call.tool_result_metadata; let bytes = serde_json::to_vec(result).map_or(usize::MAX, |value| value.len()); result.omit_if_smaller(bytes, overage_bytes); } } } /// Preserves complete resource evidence, marking other large results with request overage. pub fn retain_tool_resource_access_or_omit_metadata(&mut self, overage_bytes: usize) { if let Some(metadata) = self .internal_chat_message_metadata_passthrough_mut() .and_then(Option::as_mut) { for call in metadata.executed_tool_calls.iter_mut().flatten() { let result = &mut call.tool_result_metadata; if !result.retain_resource_access() { let bytes = serde_json::to_vec(result).map_or(usize::MAX, |value| value.len()); result.omit_if_smaller(bytes, overage_bytes); } } } } /// Reduces optional results to resource evidence before considering call-inventory loss. pub fn retain_tool_resource_access(&mut self) { if let Some(metadata) = self .internal_chat_message_metadata_passthrough_mut() .and_then(Option::as_mut) { for call in metadata.executed_tool_calls.iter_mut().flatten() { if !call.tool_result_metadata.retain_resource_access() { call.tool_result_metadata = ToolResultMetadata::default(); } } } } /// Replaces an over-budget output's calls with its own omission marker. fn bound_executed_tool_calls_with_budget(&mut self, max_metadata_bytes: usize) { let Some(metadata) = self.executed_tool_call_metadata() else { return; }; let max_call_bytes = max_metadata_bytes.saturating_sub(executed_tool_call_metadata_field_bytes(metadata)); let Some(calls) = self .internal_chat_message_metadata_passthrough_mut() .and_then(Option::as_mut) .and_then(|metadata| metadata.executed_tool_calls.as_mut()) .filter(|calls| !calls.is_empty()) else { self.clear_executed_tool_calls(); return; }; let represented_calls = calls.iter().fold(0_usize, |count, call| { count.saturating_add(1).saturating_add( call.truncation() .and_then(|truncation| truncation.omitted_calls) .unwrap_or_default(), ) }); calls.truncate(1); let call = &mut calls[0]; let original_bytes = call .truncation() .map(|truncation| truncation.original_bytes) .unwrap_or_else(|| { serde_json::to_vec(&call.arguments) .map(|bytes| bytes.len()) .unwrap_or(usize::MAX) }); let original_name_bytes = call .truncation() .and_then(|truncation| truncation.original_name_bytes); let omitted_calls = (represented_calls > 1).then_some(represented_calls - 1); call.set_truncation_with_name( original_bytes, max_call_bytes, omitted_calls, original_name_bytes, ); let serialized_bytes = |calls: &[ExecutedToolCall]| { serde_json::to_vec(calls) .map(|bytes| bytes.len()) .unwrap_or(usize::MAX) }; if serialized_bytes(calls) > max_call_bytes { let call = &mut calls[0]; call.set_truncation_with_name( original_bytes, max_call_bytes, omitted_calls, Some(original_name_bytes.unwrap_or(call.name.len())), ); // Removing UTF-8 name bytes saves at least that many serialized JSON bytes. let excess_bytes = serialized_bytes(calls).saturating_sub(max_call_bytes); let name = &mut calls[0].name; name.truncate(name.floor_char_boundary(name.len().saturating_sub(excess_bytes))); } if serialized_bytes(calls) > max_call_bytes { self.clear_executed_tool_calls(); } } /// Removes untrusted warehouse-only tool records without changing the turn ID. pub fn clear_executed_tool_calls(&mut self) { let Some(metadata) = self.internal_chat_message_metadata_passthrough_mut() else { return; }; let Some(passthrough) = metadata.as_mut() else { return; }; passthrough.cell_id = None; passthrough.executed_tool_calls = None; passthrough.tool_calls_complete = None; if *passthrough == InternalChatMessageMetadataPassthrough::default() { *metadata = None; } } } #[cfg(test)] #[path = "executed_tool_calls_tests.rs"] mod tests;