Files
codex/codex-rs/tools/src/tool_output.rs
T
ioanbudea-OAI 7d60863a4a Include direct MCP screenshots in synchronous Guardian reviews (#64811)
## Why

Synchronous Guardian reviews could receive screenshots from Code Mode calls,
but missed screenshots returned by direct calls to the same REPL connectors.

## What changed

Capture screenshots from accepted direct `node_repl` and `cua_repl` MCP
results when multimodal review evidence is enabled. Include them alongside
Code Mode evidence in call order, with separate retention budgets.

When the synchronous review prompt exceeds its fixed image budget, retry with
only the last image in prompt order and keep it if the prompt fits.

## Testing

Add coverage for screenshot delivery to synchronous permission reviews,
including text-only mode and image budget overflow. Verify that direct
screenshots preserve call order and do not consume the Code Mode retention
budget.

GitOrigin-RevId: e74ee6c5578225efb284c1ca38494377a1d0762e
2026-11-30 21:34:02 +00:00

338 lines
12 KiB
Rust

use codex_code_mode::CodeModeToolResult;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::models::AudioReference;
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ImageReference;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ToolResultMetadata;
use codex_utils_path_uri::PathUri;
use serde_json::Value as JsonValue;
use crate::ToolPayload;
/// Model-facing output contract returned by executable tool runtimes.
pub trait ToolOutput: Send {
/// Returns a deliberately lossy diagnostic representation, before telemetry size limits.
/// Implementations may summarize results or omit media and encrypted content. This is not
/// the authoritative tool result; an untruncated log does not imply a complete result.
/// The logger owns the additional configurable byte limit.
fn log_output(&self) -> String;
fn success_for_logging(&self) -> bool;
/// Whether the call was refused before its underlying operation started.
fn was_aborted(&self) -> bool {
false
}
/// Finalizes output using the same completed handler duration reported in tool-call logs.
/// Called before recording model-visible history; implementations must not measure time here.
fn set_handler_duration_ms(&mut self, _handler_duration_ms: u64) {}
/// Whether this output contains external context that should disable memory generation when
/// `memories.disable_on_external_context` is enabled.
fn contains_external_context(&self) -> bool {
false
}
/// Whether the complete model-visible result was already limited by its producer.
fn output_budget_applied(&self) -> bool {
false
}
/// Overrides history's fallback token limit after tool-specific truncation.
/// Include any serialization allowance; history uses this limit unchanged.
fn fallback_token_limit_override(&self) -> Option<usize> {
None
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem;
/// Borrows the underlying MCP result when it has not been replaced by another output.
fn mcp_result(&self) -> Option<&CallToolResult> {
None
}
/// Returns the tool call id exposed to `PostToolUse` hooks for this output.
fn post_tool_use_id(&self, call_id: &str) -> String {
call_id.to_string()
}
/// Returns the original local execution cwd for hook input, including delayed
/// results. Remote commands return `None` to retain the host hook cwd.
/// This does not change the local directory used to launch the hook process.
fn post_tool_use_cwd(&self) -> Option<PathUri> {
None
}
/// Returns the tool input exposed to `PostToolUse` hooks for this output.
fn post_tool_use_input(&self, _payload: &ToolPayload) -> Option<JsonValue> {
None
}
/// Returns the stable value exposed to `PostToolUse` hooks for this tool output.
///
/// Tool handlers decide whether a tool participates in `PostToolUse`, but
/// this method lets the output type own any conversion from model-facing
/// response content to hook-facing data. Returning `None` means the output
/// should not produce a post-use hook payload, not merely that the tool had
/// empty output.
fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option<JsonValue> {
None
}
/// Returns the script-visible value with its format for Code Mode's output helpers.
fn code_mode_result(&self, payload: &ToolPayload) -> CodeModeToolResult {
CodeModeToolResult::from(response_input_to_code_mode_result(
self.to_response_item("", payload),
))
}
/// Hands the final result to JavaScript, moving an already prepared value when possible.
fn into_code_mode_result(self: Box<Self>, payload: &ToolPayload) -> CodeModeToolResult {
self.code_mode_result(payload)
}
/// Returns the host-observed result fields for executed-tool passthrough.
fn tool_result_metadata(&self) -> ToolResultMetadata {
ToolResultMetadata::default()
}
}
impl<T> ToolOutput for Box<T>
where
T: ToolOutput + ?Sized,
{
fn log_output(&self) -> String {
(**self).log_output()
}
fn success_for_logging(&self) -> bool {
(**self).success_for_logging()
}
fn was_aborted(&self) -> bool {
(**self).was_aborted()
}
fn set_handler_duration_ms(&mut self, handler_duration_ms: u64) {
(**self).set_handler_duration_ms(handler_duration_ms);
}
fn contains_external_context(&self) -> bool {
(**self).contains_external_context()
}
fn output_budget_applied(&self) -> bool {
(**self).output_budget_applied()
}
fn fallback_token_limit_override(&self) -> Option<usize> {
(**self).fallback_token_limit_override()
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
(**self).to_response_item(call_id, payload)
}
fn post_tool_use_id(&self, call_id: &str) -> String {
(**self).post_tool_use_id(call_id)
}
fn post_tool_use_cwd(&self) -> Option<PathUri> {
(**self).post_tool_use_cwd()
}
fn post_tool_use_input(&self, payload: &ToolPayload) -> Option<JsonValue> {
(**self).post_tool_use_input(payload)
}
fn mcp_result(&self) -> Option<&CallToolResult> {
(**self).mcp_result()
}
fn post_tool_use_response(&self, call_id: &str, payload: &ToolPayload) -> Option<JsonValue> {
(**self).post_tool_use_response(call_id, payload)
}
fn code_mode_result(&self, payload: &ToolPayload) -> CodeModeToolResult {
(**self).code_mode_result(payload)
}
fn into_code_mode_result(self: Box<Self>, payload: &ToolPayload) -> CodeModeToolResult {
(*self).into_code_mode_result(payload)
}
fn tool_result_metadata(&self) -> ToolResultMetadata {
(**self).tool_result_metadata()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct JsonToolOutput {
value: JsonValue,
success: Option<bool>,
contains_external_context: bool,
}
impl JsonToolOutput {
pub fn new(value: JsonValue) -> Self {
Self {
value,
success: Some(true),
contains_external_context: false,
}
}
pub fn with_success(value: JsonValue, success: Option<bool>) -> Self {
Self {
value,
success,
contains_external_context: false,
}
}
pub fn with_external_context(mut self) -> Self {
self.contains_external_context = true;
self
}
}
impl ToolOutput for JsonToolOutput {
fn log_output(&self) -> String {
self.value.to_string()
}
fn success_for_logging(&self) -> bool {
self.success.unwrap_or(true)
}
fn contains_external_context(&self) -> bool {
self.contains_external_context
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
let output = FunctionCallOutputPayload {
body: FunctionCallOutputBody::Text(self.value.to_string()),
success: self.success,
};
if matches!(payload, ToolPayload::Custom { .. }) {
return ResponseInputItem::CustomToolCallOutput {
call_id: call_id.to_string(),
name: None,
output,
};
}
ResponseInputItem::FunctionCallOutput {
call_id: call_id.to_string(),
output,
}
}
fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option<JsonValue> {
Some(self.value.clone())
}
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
CodeModeToolResult::from(self.value.clone())
}
}
impl ToolOutput for codex_protocol::mcp::CallToolResult {
fn log_output(&self) -> String {
let output = self.as_function_call_output_payload();
// Do not fall back to serializing media or encrypted content into logs.
output.body.to_text().unwrap_or_default()
}
fn success_for_logging(&self) -> bool {
self.success()
}
fn to_response_item(&self, call_id: &str, _payload: &ToolPayload) -> ResponseInputItem {
ResponseInputItem::McpToolCallOutput {
call_id: call_id.to_string(),
output: self.clone(),
}
}
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
let mut result = match serde_json::to_value(self) {
Ok(value) => value,
Err(err) => {
return CodeModeToolResult::Json(JsonValue::String(format!(
"failed to serialize mcp result: {err}"
)));
}
};
// MCP result metadata is private to clients and must not reach Code Mode.
if let JsonValue::Object(fields) = &mut result {
fields.remove("_meta");
}
CodeModeToolResult::McpCallToolResult(result)
}
}
fn response_input_to_code_mode_result(response: ResponseInputItem) -> JsonValue {
match response {
ResponseInputItem::Message { content, .. } => content_items_to_code_mode_result(
&content
.into_iter()
.map(FunctionCallOutputContentItem::from)
.collect::<Vec<_>>(),
),
ResponseInputItem::FunctionCallOutput { output, .. }
| ResponseInputItem::CustomToolCallOutput { output, .. } => match output.body {
FunctionCallOutputBody::Text(text) => JsonValue::String(text),
FunctionCallOutputBody::ContentItems(items) => {
content_items_to_code_mode_result(&items)
}
},
ResponseInputItem::ToolSearchOutput { tools, .. } => JsonValue::Array(tools),
ResponseInputItem::McpToolCallOutput { output, .. } => serde_json::to_value(output)
.unwrap_or_else(|err| {
JsonValue::String(format!("failed to serialize mcp result: {err}"))
}),
}
}
fn content_items_to_code_mode_result(items: &[FunctionCallOutputContentItem]) -> JsonValue {
JsonValue::String(
items
.iter()
.filter_map(|item| match item {
FunctionCallOutputContentItem::InputText { text } if !text.trim().is_empty() => {
Some(text.clone())
}
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline { image_url },
..
} if !image_url.trim().is_empty() => Some(image_url.clone()),
FunctionCallOutputContentItem::InputImage {
image: ImageReference::File { file_id },
..
} if !file_id.trim().is_empty() => Some(file_id.clone()),
FunctionCallOutputContentItem::InputAudio {
audio: AudioReference::Inline { audio_url },
} if !audio_url.trim().is_empty() => Some(audio_url.clone()),
FunctionCallOutputContentItem::InputAudio {
audio: AudioReference::File { file_id },
} if !file_id.trim().is_empty() => Some(file_id.clone()),
FunctionCallOutputContentItem::InputText { .. }
| FunctionCallOutputContentItem::InputImage { .. }
| FunctionCallOutputContentItem::InputAudio { .. }
| FunctionCallOutputContentItem::EncryptedContent { .. } => None,
})
.collect::<Vec<_>>()
.join("\n"),
)
}
#[cfg(test)]
#[path = "tool_output_tests.rs"]
mod tests;