mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:50:52 +00:00
Support structured dynamic tool results in Code Mode (#63766)
## Why Dynamic tool clients could return JSON as text in `contentItems`, so Code Mode scripts had to parse that text to access fields in the result. ## What changed App server dynamic tool requests advertise `supportedResultFormat: "structuredContent"`. Clients can reply with `structuredContent` and a `success` flag, report a failure with `errorMessage` and `success: false`, or continue using `contentItems`. Code Mode exposes structured replies as MCP-style tool results, with the original JSON under `structuredContent` and failure status in `isError`. Completed tool items include a text representation of the reply. Matching post-tool-use hooks can receive the structured result for successful calls. ## Testing Add protocol tests for the wire formats and rejection of ambiguous replies, plus an app server integration test that exercises structured results, content items, and errors through Code Mode. GitOrigin-RevId: d63152633b43bd5bd236f6e0dcb41ee7e98e7947
This commit is contained in:
@@ -1,22 +1,31 @@
|
||||
use crate::function_tool::FunctionCallError;
|
||||
use crate::hook_environment_executor::with_tool_environment_hooks;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::tools::context::FunctionToolOutput;
|
||||
use crate::tools::context::ToolInvocation;
|
||||
use crate::tools::context::ToolOutput;
|
||||
use crate::tools::context::ToolPayload;
|
||||
use crate::tools::context::boxed_tool_output;
|
||||
use crate::tools::handlers::parse_arguments;
|
||||
use crate::tools::registry::CoreToolRuntime;
|
||||
use crate::tools::registry::PostToolUsePayload;
|
||||
use crate::tools::registry::ToolExecutor;
|
||||
use crate::tools::registry::ToolExposure;
|
||||
use crate::tools::registry::function_hook_tool_name;
|
||||
use crate::tools::registry::function_post_tool_use_payload;
|
||||
use codex_async_utils::OrCancelExt;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem;
|
||||
use codex_protocol::dynamic_tools::DynamicToolCallResult;
|
||||
use codex_protocol::dynamic_tools::DynamicToolFunctionSpec;
|
||||
use codex_protocol::dynamic_tools::DynamicToolNamespaceSpec;
|
||||
use codex_protocol::dynamic_tools::DynamicToolResponse;
|
||||
use codex_protocol::items::DynamicToolCallItem;
|
||||
use codex_protocol::items::DynamicToolCallStatus;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_tools::ResponsesApiNamespace;
|
||||
use codex_tools::ResponsesApiNamespaceTool;
|
||||
use codex_tools::ToolName;
|
||||
@@ -143,7 +152,7 @@ impl DynamicToolHandler {
|
||||
};
|
||||
|
||||
let args: Value = parse_arguments(&arguments)?;
|
||||
let response = request_dynamic_tool(
|
||||
let output = request_dynamic_tool(
|
||||
&session,
|
||||
turn.as_ref(),
|
||||
call_id.into(),
|
||||
@@ -158,22 +167,149 @@ impl DynamicToolHandler {
|
||||
)
|
||||
})?;
|
||||
|
||||
let DynamicToolResponse {
|
||||
content_items,
|
||||
success,
|
||||
} = response;
|
||||
let body = content_items
|
||||
.into_iter()
|
||||
.map(FunctionCallOutputContentItem::from)
|
||||
.collect::<Vec<_>>();
|
||||
Ok(boxed_tool_output(FunctionToolOutput::from_content(
|
||||
body,
|
||||
Some(success),
|
||||
)))
|
||||
Ok(boxed_tool_output(output))
|
||||
}
|
||||
}
|
||||
|
||||
enum DynamicToolOutput {
|
||||
ContentItems(FunctionToolOutput),
|
||||
/// The MCP-shaped value shared by optional observers and moved into Code Mode.
|
||||
StructuredContent(Value),
|
||||
}
|
||||
|
||||
impl DynamicToolOutput {
|
||||
fn from_response(
|
||||
response: DynamicToolCallResult,
|
||||
) -> (Self, Vec<DynamicToolCallOutputContentItem>) {
|
||||
match response {
|
||||
DynamicToolCallResult::ContentItems(response) => (
|
||||
Self::ContentItems(FunctionToolOutput::from_content(
|
||||
response
|
||||
.content_items
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(Into::into)
|
||||
.collect(),
|
||||
Some(response.success),
|
||||
)),
|
||||
response.content_items,
|
||||
),
|
||||
DynamicToolCallResult::StructuredContent {
|
||||
structured_content,
|
||||
success,
|
||||
} => {
|
||||
let text = structured_content.to_string();
|
||||
Self::native_result(Some(structured_content), text, success)
|
||||
}
|
||||
DynamicToolCallResult::Error { error_message } => {
|
||||
Self::native_result(
|
||||
/*structured_content*/ None,
|
||||
error_message,
|
||||
/*success*/ false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Native replies always have exactly one local text block, including errors.
|
||||
fn native_text(result: &Value) -> String {
|
||||
result["content"][0]["text"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn native_result(
|
||||
structured_content: Option<Value>,
|
||||
text: String,
|
||||
success: bool,
|
||||
) -> (Self, Vec<DynamicToolCallOutputContentItem>) {
|
||||
let mut result = serde_json::json!({
|
||||
"content": [{"type": "text", "text": text}],
|
||||
"isError": !success,
|
||||
});
|
||||
if let Some(value) = structured_content {
|
||||
result["structuredContent"] = value;
|
||||
}
|
||||
(
|
||||
Self::StructuredContent(result),
|
||||
vec![DynamicToolCallOutputContentItem::InputText { text }],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolOutput for DynamicToolOutput {
|
||||
fn log_output(&self) -> String {
|
||||
match self {
|
||||
Self::ContentItems(output) => output.log_output(),
|
||||
Self::StructuredContent(value) => Self::native_text(value),
|
||||
}
|
||||
}
|
||||
|
||||
fn success_for_logging(&self) -> bool {
|
||||
match self {
|
||||
Self::ContentItems(output) => output.success_for_logging(),
|
||||
Self::StructuredContent(value) => value["isError"] == false,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
|
||||
match self {
|
||||
Self::ContentItems(output) => output.to_response_item(call_id, payload),
|
||||
Self::StructuredContent(value) => ResponseInputItem::FunctionCallOutput {
|
||||
call_id: call_id.to_owned(),
|
||||
output: FunctionCallOutputPayload {
|
||||
body: FunctionCallOutputBody::Text(Self::native_text(value)),
|
||||
success: Some(self.success_for_logging()),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option<Value> {
|
||||
match self {
|
||||
Self::ContentItems(_) => None,
|
||||
Self::StructuredContent(value) => Some(value.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, payload: &ToolPayload) -> CodeModeToolResult {
|
||||
match self {
|
||||
Self::ContentItems(output) => output.code_mode_result(payload),
|
||||
Self::StructuredContent(value) => CodeModeToolResult::McpCallToolResult(value.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn into_code_mode_result(self: Box<Self>, payload: &ToolPayload) -> CodeModeToolResult {
|
||||
match *self {
|
||||
Self::ContentItems(output) => output.code_mode_result(payload),
|
||||
Self::StructuredContent(value) => CodeModeToolResult::McpCallToolResult(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CoreToolRuntime for DynamicToolHandler {
|
||||
fn post_tool_use_payload(
|
||||
&self,
|
||||
invocation: &ToolInvocation,
|
||||
result: &dyn ToolOutput,
|
||||
) -> Option<PostToolUsePayload> {
|
||||
if !result.success_for_logging() {
|
||||
return None;
|
||||
}
|
||||
let tool_name = function_hook_tool_name(invocation);
|
||||
let hooks = with_tool_environment_hooks(
|
||||
&invocation.session,
|
||||
&invocation.turn,
|
||||
&invocation.step_context.environments,
|
||||
&invocation.environments.hook_ids(),
|
||||
);
|
||||
if !hooks.has_post_tool_use_match(tool_name.name(), tool_name.matcher_aliases()) {
|
||||
return None;
|
||||
}
|
||||
function_post_tool_use_payload(invocation, result, tool_name)
|
||||
}
|
||||
|
||||
fn finishes_on_cancellation(&self) -> bool {
|
||||
true
|
||||
}
|
||||
@@ -194,7 +330,7 @@ async fn request_dynamic_tool(
|
||||
tool_name: ToolName,
|
||||
arguments: Value,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> Option<DynamicToolResponse> {
|
||||
) -> Option<DynamicToolOutput> {
|
||||
if cancellation_token.is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
@@ -242,39 +378,49 @@ async fn request_dynamic_tool(
|
||||
.ok()
|
||||
.and_then(Result::ok);
|
||||
|
||||
let item = match &response {
|
||||
Some(response) => DynamicToolCallItem {
|
||||
id: call_id,
|
||||
namespace,
|
||||
tool,
|
||||
arguments,
|
||||
status: if response.success {
|
||||
DynamicToolCallStatus::Completed
|
||||
} else {
|
||||
DynamicToolCallStatus::Failed
|
||||
let (output, item) = match response {
|
||||
Some(response) => {
|
||||
let success = response.success();
|
||||
let (output, content_items) = DynamicToolOutput::from_response(response);
|
||||
let item = DynamicToolCallItem {
|
||||
id: call_id,
|
||||
namespace,
|
||||
tool,
|
||||
arguments,
|
||||
status: if success {
|
||||
DynamicToolCallStatus::Completed
|
||||
} else {
|
||||
DynamicToolCallStatus::Failed
|
||||
},
|
||||
content_items: Some(content_items),
|
||||
success: Some(success),
|
||||
error: None,
|
||||
duration: Some(started_at.elapsed()),
|
||||
};
|
||||
(Some(output), item)
|
||||
}
|
||||
None => (
|
||||
None,
|
||||
DynamicToolCallItem {
|
||||
id: call_id,
|
||||
namespace,
|
||||
tool,
|
||||
arguments,
|
||||
status: DynamicToolCallStatus::Failed,
|
||||
content_items: Some(Vec::new()),
|
||||
success: Some(false),
|
||||
error: Some(
|
||||
"dynamic tool call was cancelled before receiving a response".to_string(),
|
||||
),
|
||||
duration: Some(started_at.elapsed()),
|
||||
},
|
||||
content_items: Some(response.content_items.clone()),
|
||||
success: Some(response.success),
|
||||
error: None,
|
||||
duration: Some(started_at.elapsed()),
|
||||
},
|
||||
None => DynamicToolCallItem {
|
||||
id: call_id,
|
||||
namespace,
|
||||
tool,
|
||||
arguments,
|
||||
status: DynamicToolCallStatus::Failed,
|
||||
content_items: Some(Vec::new()),
|
||||
success: Some(false),
|
||||
error: Some("dynamic tool call was cancelled before receiving a response".to_string()),
|
||||
duration: Some(started_at.elapsed()),
|
||||
},
|
||||
),
|
||||
};
|
||||
session
|
||||
.emit_turn_item_completed(turn_context, TurnItem::DynamicToolCall(item))
|
||||
.await;
|
||||
|
||||
response
|
||||
output
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -47,16 +47,17 @@ async fn response_cancel_race_completes_once() {
|
||||
}
|
||||
});
|
||||
next_item(&receiver).await;
|
||||
let response = DynamicToolResponse {
|
||||
content_items: Vec::new(),
|
||||
success: true,
|
||||
};
|
||||
let response =
|
||||
DynamicToolCallResult::ContentItems(codex_protocol::dynamic_tools::DynamicToolResponse {
|
||||
content_items: Vec::new(),
|
||||
success: true,
|
||||
});
|
||||
session
|
||||
.notify_dynamic_tool_response("call-1", response.clone())
|
||||
.notify_dynamic_tool_response("call-1", response)
|
||||
.await;
|
||||
cancellation.cancel();
|
||||
let result = lifecycle.await.expect("lifecycle joined");
|
||||
assert!(result.is_none() || result == Some(response));
|
||||
assert!(result.as_ref().is_none_or(ToolOutput::success_for_logging));
|
||||
let item = next_item(&receiver).await;
|
||||
assert_eq!(
|
||||
(item.status, item.success, item.error),
|
||||
@@ -74,3 +75,57 @@ async fn response_cancel_race_completes_once() {
|
||||
assert!(!matches!(event.msg, EventMsg::ItemCompleted(_)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_reply_has_the_same_code_mode_and_hook_payload() {
|
||||
let fields = json!({"threads": [{"id":"abc"}]});
|
||||
let (output, items) =
|
||||
DynamicToolOutput::from_response(DynamicToolCallResult::StructuredContent {
|
||||
structured_content: fields.clone(),
|
||||
success: true,
|
||||
});
|
||||
let payload = ToolPayload::Function {
|
||||
arguments: "{}".to_string(),
|
||||
};
|
||||
let result = codex_protocol::mcp::CallToolResult {
|
||||
content: vec![json!({"type": "text", "text": fields.to_string()})],
|
||||
structured_content: Some(fields.clone()),
|
||||
is_error: Some(false),
|
||||
meta: None,
|
||||
}
|
||||
.code_mode_result(&payload);
|
||||
assert_eq!(output.code_mode_result(&payload), result);
|
||||
assert_eq!(
|
||||
output.post_tool_use_response("call-1", &payload),
|
||||
Some(result.clone().into_json())
|
||||
);
|
||||
assert_eq!(Box::new(output).into_code_mode_result(&payload), result);
|
||||
assert_eq!(
|
||||
items,
|
||||
vec![DynamicToolCallOutputContentItem::InputText {
|
||||
text: fields.to_string()
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_reply_moves_the_original_payload_into_code_mode() {
|
||||
let text = "large tool reply".repeat(1024);
|
||||
let original = text.as_ptr();
|
||||
let (output, _) = DynamicToolOutput::from_response(DynamicToolCallResult::StructuredContent {
|
||||
structured_content: Value::String(text),
|
||||
success: true,
|
||||
});
|
||||
let output: Box<dyn ToolOutput> = Box::new(output);
|
||||
let CodeModeToolResult::McpCallToolResult(result) =
|
||||
output.into_code_mode_result(&ToolPayload::Function {
|
||||
arguments: "{}".to_owned(),
|
||||
})
|
||||
else {
|
||||
panic!("native reply lost its MCP result tag");
|
||||
};
|
||||
assert_eq!(
|
||||
result["structuredContent"].as_str().unwrap().as_ptr(),
|
||||
original
|
||||
);
|
||||
}
|
||||
|
||||
@@ -148,34 +148,7 @@ pub(crate) trait CoreToolRuntime: ToolExecutor<ToolInvocation> {
|
||||
invocation: &ToolInvocation,
|
||||
result: &dyn ToolOutput,
|
||||
) -> Option<PostToolUsePayload> {
|
||||
let ToolPayload::Function { arguments } = &invocation.payload else {
|
||||
return None;
|
||||
};
|
||||
|
||||
Some(PostToolUsePayload {
|
||||
tool_cwd: result.post_tool_use_cwd(),
|
||||
tool_name: function_hook_tool_name(invocation),
|
||||
tool_use_id: result.post_tool_use_id(&invocation.call_id),
|
||||
tool_input: result
|
||||
.post_tool_use_input(&invocation.payload)
|
||||
.unwrap_or_else(|| function_hook_tool_input(arguments)),
|
||||
tool_response: result
|
||||
.post_tool_use_response(&invocation.call_id, &invocation.payload)
|
||||
.or_else(|| {
|
||||
// Most function tools can expose their model-facing output
|
||||
// as the hook response. Outputs with a more stable hook
|
||||
// contract should override post_tool_use_response above.
|
||||
let ResponseInputItem::FunctionCallOutput {
|
||||
output: FunctionCallOutputPayload { body, .. },
|
||||
..
|
||||
} = result.to_response_item(&invocation.call_id, &invocation.payload)
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
|
||||
serde_json::to_value(body).ok()
|
||||
})?,
|
||||
})
|
||||
function_post_tool_use_payload(invocation, result, function_hook_tool_name(invocation))
|
||||
}
|
||||
|
||||
fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option<PreToolUsePayload> {
|
||||
@@ -363,7 +336,7 @@ impl AnyToolResult {
|
||||
let Self {
|
||||
payload, result, ..
|
||||
} = self;
|
||||
result.code_mode_result(&payload)
|
||||
result.into_code_mode_result(&payload)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,6 +370,10 @@ impl ToolOutput for PostToolUseFeedbackOutput {
|
||||
self.original.code_mode_result(payload)
|
||||
}
|
||||
|
||||
fn into_code_mode_result(self: Box<Self>, payload: &ToolPayload) -> CodeModeToolResult {
|
||||
self.original.into_code_mode_result(payload)
|
||||
}
|
||||
|
||||
fn tool_result_metadata(&self) -> ToolResultMetadata {
|
||||
self.original.tool_result_metadata()
|
||||
}
|
||||
@@ -1273,7 +1250,42 @@ pub(crate) async fn apply_pre_tool_use(
|
||||
}
|
||||
}
|
||||
|
||||
fn function_hook_tool_name(invocation: &ToolInvocation) -> HookToolName {
|
||||
pub(super) fn function_post_tool_use_payload(
|
||||
invocation: &ToolInvocation,
|
||||
result: &dyn ToolOutput,
|
||||
tool_name: HookToolName,
|
||||
) -> Option<PostToolUsePayload> {
|
||||
let ToolPayload::Function { arguments } = &invocation.payload else {
|
||||
return None;
|
||||
};
|
||||
|
||||
Some(PostToolUsePayload {
|
||||
tool_cwd: result.post_tool_use_cwd(),
|
||||
tool_name,
|
||||
tool_use_id: result.post_tool_use_id(&invocation.call_id),
|
||||
tool_input: result
|
||||
.post_tool_use_input(&invocation.payload)
|
||||
.unwrap_or_else(|| function_hook_tool_input(arguments)),
|
||||
tool_response: result
|
||||
.post_tool_use_response(&invocation.call_id, &invocation.payload)
|
||||
.or_else(|| {
|
||||
// Most function tools can expose their model-facing output
|
||||
// as the hook response. Outputs with a more stable hook
|
||||
// contract should override post_tool_use_response above.
|
||||
let ResponseInputItem::FunctionCallOutput {
|
||||
output: FunctionCallOutputPayload { body, .. },
|
||||
..
|
||||
} = result.to_response_item(&invocation.call_id, &invocation.payload)
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
|
||||
serde_json::to_value(body).ok()
|
||||
})?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn function_hook_tool_name(invocation: &ToolInvocation) -> HookToolName {
|
||||
if invocation.tool_name.name == "spawn_agent"
|
||||
&& (invocation.tool_name.is_default_namespace()
|
||||
|| invocation.tool_name.namespace.as_deref() == Some(MULTI_AGENT_V1_NAMESPACE))
|
||||
|
||||
Reference in New Issue
Block a user