Files
codex/codex-rs/tools/src/tool_output.rs
T
Aismit 624fdeecee Run patch hooks for intercepted apply_patch commands (#65077)
## Why

Codex can intercept an `apply_patch` heredoc passed to `exec_command`
and apply the patch directly. That path ran shell hooks but bypassed
`apply_patch` hooks, so patch-specific rules could miss the same edit
when it was submitted through the shell tool.

## What changed

- Run `apply_patch` `PreToolUse` after shell hooks and before file
  verification. Hooks can block or rewrite the patch, and the final
  patch is checked against the selected environment's permissions.
- Report the executed patch through `apply_patch` `PostToolUse`. Link
  the patch hook events to the outer shell call with
  `parent_tool_use_id` and provide working-directory and filesystem
  metadata for hooks that inspect patch targets.
- Apply the same block and rewrite rules in recorded Guardian reviews.
  Mark those hook requests with `review_only` and review the resulting
  patch without executing it or publishing hook-provided context.

## Testing

Add coverage for hook blocks and rewrites, effective working directories,
environment permissions, and cancellation before and after a patch write.
Cover recorded reviews of rewritten patches and reviews stopped by a hook.

GitOrigin-RevId: 2115f26261a20d4a512669bc9e277a764b8f42f4
2026-12-01 20:18:13 +00:00

348 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
}
/// Identifies a committed operation performed by another tool during this call.
/// Its post-hook uses this name, and interruption preserves its execution outcome.
fn committed_tool_name(&self) -> Option<&str> {
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 effective execution cwd for hook input, including delayed
/// results. Hook dispatch retains the host fallback for remote tools' local hooks.
/// This does not change the 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 committed_tool_name(&self) -> Option<&str> {
(**self).committed_tool_name()
}
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;