mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +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:
@@ -51,7 +51,7 @@ use codex_protocol::request_user_input::RequestUserInputResponse;
|
||||
use codex_thread_store::PersistContext;
|
||||
|
||||
use crate::context_manager::is_instruction_turn_boundary;
|
||||
use codex_protocol::dynamic_tools::DynamicToolResponse;
|
||||
use codex_protocol::dynamic_tools::DynamicToolCallResult;
|
||||
use codex_protocol::mcp::RequestId as ProtocolRequestId;
|
||||
use codex_protocol::protocol::AgentStatus;
|
||||
use codex_rmcp_client::ElicitationAction;
|
||||
@@ -258,7 +258,11 @@ pub async fn request_permissions_response(
|
||||
.await;
|
||||
}
|
||||
|
||||
pub async fn dynamic_tool_response(sess: &Arc<Session>, id: String, response: DynamicToolResponse) {
|
||||
pub async fn dynamic_tool_response(
|
||||
sess: &Arc<Session>,
|
||||
id: String,
|
||||
response: DynamicToolCallResult,
|
||||
) {
|
||||
sess.notify_dynamic_tool_response(&id, response).await;
|
||||
}
|
||||
|
||||
@@ -929,6 +933,10 @@ pub(super) async fn submission_loop(
|
||||
false
|
||||
}
|
||||
Op::DynamicToolResponse { id, response } => {
|
||||
dynamic_tool_response(&sess, id, DynamicToolCallResult::ContentItems(response)).await;
|
||||
false
|
||||
}
|
||||
Op::DynamicToolResult { id, response } => {
|
||||
dynamic_tool_response(&sess, id, response).await;
|
||||
false
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ use codex_protocol::config_types::AutoCompactTokenLimitScope;
|
||||
use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE;
|
||||
use codex_protocol::config_types::ServiceTier;
|
||||
use codex_protocol::config_types::WebSearchMode;
|
||||
use codex_protocol::dynamic_tools::DynamicToolResponse;
|
||||
use codex_protocol::dynamic_tools::DynamicToolCallResult;
|
||||
use codex_protocol::dynamic_tools::DynamicToolSpec;
|
||||
use codex_protocol::items::EnteredReviewModeItem;
|
||||
use codex_protocol::items::ModelInvocationContext;
|
||||
@@ -3986,7 +3986,11 @@ impl Session {
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "active turn checks and turn state updates must remain atomic"
|
||||
)]
|
||||
pub async fn notify_dynamic_tool_response(&self, call_id: &str, response: DynamicToolResponse) {
|
||||
pub async fn notify_dynamic_tool_response(
|
||||
&self,
|
||||
call_id: &str,
|
||||
response: DynamicToolCallResult,
|
||||
) {
|
||||
let entry = {
|
||||
let mut active = self.active_turn.lock().await;
|
||||
match active.as_mut() {
|
||||
|
||||
@@ -12,7 +12,7 @@ use tokio_util::task::AbortOnDropHandle;
|
||||
use tokio_util::task::task_tracker::TaskTrackerToken;
|
||||
|
||||
use codex_diagnostics::GaugeGuard;
|
||||
use codex_protocol::dynamic_tools::DynamicToolResponse;
|
||||
use codex_protocol::dynamic_tools::DynamicToolCallResult;
|
||||
use codex_protocol::request_permissions::RequestPermissionProfile;
|
||||
use codex_protocol::request_permissions::RequestPermissionsResponse;
|
||||
use codex_rmcp_client::ElicitationResponse;
|
||||
@@ -114,7 +114,7 @@ pub(crate) struct TurnState {
|
||||
pending_request_permissions: HashMap<String, PendingRequestPermissions>,
|
||||
pending_user_input: HashMap<String, PendingUserInput>,
|
||||
pending_elicitations: HashMap<(String, RequestId), oneshot::Sender<ElicitationResponse>>,
|
||||
pending_dynamic_tools: HashMap<String, oneshot::Sender<DynamicToolResponse>>,
|
||||
pending_dynamic_tools: HashMap<String, oneshot::Sender<DynamicToolCallResult>>,
|
||||
pub(crate) pending_input: TurnInputQueue,
|
||||
mailbox_delivery_phase: MailboxDeliveryPhase,
|
||||
pub(crate) tool_calls: u64,
|
||||
@@ -297,15 +297,15 @@ impl TurnState {
|
||||
pub(crate) fn insert_pending_dynamic_tool(
|
||||
&mut self,
|
||||
key: String,
|
||||
tx: oneshot::Sender<DynamicToolResponse>,
|
||||
) -> Option<oneshot::Sender<DynamicToolResponse>> {
|
||||
tx: oneshot::Sender<DynamicToolCallResult>,
|
||||
) -> Option<oneshot::Sender<DynamicToolCallResult>> {
|
||||
self.pending_dynamic_tools.insert(key, tx)
|
||||
}
|
||||
|
||||
pub(crate) fn remove_pending_dynamic_tool(
|
||||
&mut self,
|
||||
key: &str,
|
||||
) -> Option<oneshot::Sender<DynamicToolResponse>> {
|
||||
) -> Option<oneshot::Sender<DynamicToolCallResult>> {
|
||||
self.pending_dynamic_tools.remove(key)
|
||||
}
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Dynamic tool calls remain independent while waiting for client responses.
|
||||
|
||||
use super::*;
|
||||
use codex_protocol::dynamic_tools::DynamicToolCallResult;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
@@ -48,6 +49,9 @@ async fn code_mode_dynamic_tool_calls_pending_together_resolve_in_reverse_order(
|
||||
const results = await Promise.all([
|
||||
tools.lookup({ key: "A" }),
|
||||
tools.lookup({ key: "B" }),
|
||||
tools.lookup({ key: "C" }).then(r => [r.isError, r.structuredContent.items, r.structuredContent.body.length]),
|
||||
tools.lookup({ key: "D" }),
|
||||
tools.lookup({ key: "E" }).then(r => r.structuredContent),
|
||||
]);
|
||||
text(JSON.stringify(results));
|
||||
"#,
|
||||
@@ -67,14 +71,14 @@ text(JSON.stringify(results));
|
||||
|
||||
test.codex
|
||||
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
|
||||
text: "Look up A and B concurrently.".to_string(),
|
||||
text: "Look up five values concurrently.".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}]))
|
||||
.await?;
|
||||
|
||||
// Neither response is submitted until both calls are waiting for the client.
|
||||
// No response is submitted until all calls are waiting for the client.
|
||||
let mut pending = Vec::new();
|
||||
for _ in 0..2 {
|
||||
for _ in 0..5 {
|
||||
pending.push(
|
||||
wait_for_event_match(&test.codex, |event| match event {
|
||||
EventMsg::DynamicToolCallRequest(request) => Some(request.clone()),
|
||||
@@ -87,15 +91,32 @@ text(JSON.stringify(results));
|
||||
|
||||
for request in pending.into_iter().rev() {
|
||||
let key = request.arguments["key"].as_str().unwrap();
|
||||
let response = match key {
|
||||
"C" => DynamicToolCallResult::StructuredContent {
|
||||
success: true,
|
||||
structured_content: serde_json::json!({
|
||||
"items": [{"id":"🌿","active":true,"value":null}],
|
||||
"body": "x".repeat(1_100_000),
|
||||
}),
|
||||
},
|
||||
"D" => DynamicToolCallResult::Error {
|
||||
error_message: "value-D".to_owned(),
|
||||
},
|
||||
"E" => DynamicToolCallResult::StructuredContent {
|
||||
success: true,
|
||||
structured_content: serde_json::json!([{}, [], "\n\\\""]),
|
||||
},
|
||||
_ => DynamicToolCallResult::ContentItems(DynamicToolResponse {
|
||||
success: key == "A",
|
||||
content_items: vec![DynamicToolCallOutputContentItem::InputText {
|
||||
text: format!(r#"{{"key":"{key}"}}"#),
|
||||
}],
|
||||
}),
|
||||
};
|
||||
test.codex
|
||||
.submit(Op::DynamicToolResponse {
|
||||
.submit(Op::DynamicToolResult {
|
||||
id: request.call_id,
|
||||
response: DynamicToolResponse {
|
||||
content_items: vec![DynamicToolCallOutputContentItem::InputText {
|
||||
text: format!("value-{key}"),
|
||||
}],
|
||||
success: true,
|
||||
},
|
||||
response,
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
@@ -109,7 +130,7 @@ text(JSON.stringify(results));
|
||||
.expect("the completed program should emit its results");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&output)?,
|
||||
serde_json::json!(["value-A", "value-B"])
|
||||
serde_json::json!([r#"{"key":"A"}"#, r#"{"key":"B"}"#, [false, [{"id":"🌿","active":true,"value":null}], 1_100_000], {"isError":true,"content":[{"type":"text","text":"value-D"}]}, [{}, [], "\n\\\""]])
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user