diff --git a/codex-rs/app-server-protocol/schema/json/DynamicToolCallParams.json b/codex-rs/app-server-protocol/schema/json/DynamicToolCallParams.json index 991733da66..5263f84d16 100644 --- a/codex-rs/app-server-protocol/schema/json/DynamicToolCallParams.json +++ b/codex-rs/app-server-protocol/schema/json/DynamicToolCallParams.json @@ -1,5 +1,13 @@ { "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "DynamicToolResultFormat": { + "enum": [ + "structuredContent" + ], + "type": "string" + } + }, "properties": { "arguments": true, "callId": { @@ -11,6 +19,17 @@ "null" ] }, + "supportedResultFormat": { + "anyOf": [ + { + "$ref": "#/definitions/DynamicToolResultFormat" + }, + { + "type": "null" + } + ], + "description": "Optional response format supported by the runtime serving this call." + }, "threadId": { "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/DynamicToolCallResponse.json b/codex-rs/app-server-protocol/schema/json/DynamicToolCallResponse.json index 47de6cb30e..7da54d7db3 100644 --- a/codex-rs/app-server-protocol/schema/json/DynamicToolCallResponse.json +++ b/codex-rs/app-server-protocol/schema/json/DynamicToolCallResponse.json @@ -1,6 +1,58 @@ { "$schema": "http://json-schema.org/draft-07/schema#", + "anyOf": [ + { + "$ref": "#/definitions/DynamicToolCallContentItems" + }, + { + "properties": { + "structuredContent": true, + "success": { + "type": "boolean" + } + }, + "required": [ + "structuredContent", + "success" + ], + "type": "object" + }, + { + "properties": { + "errorMessage": { + "type": "string" + }, + "success": { + "const": false, + "type": "boolean" + } + }, + "required": [ + "errorMessage", + "success" + ], + "type": "object" + } + ], "definitions": { + "DynamicToolCallContentItems": { + "properties": { + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": "array" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "contentItems", + "success" + ], + "type": "object" + }, "DynamicToolCallOutputContentItem": { "oneOf": [ { @@ -66,21 +118,26 @@ ] } }, - "properties": { - "contentItems": { - "items": { - "$ref": "#/definitions/DynamicToolCallOutputContentItem" - }, - "type": "array" + "description": "A dynamic tool reply carrying content items, structured JSON, or an error message.", + "oneOf": [ + { + "required": [ + "contentItems" + ], + "title": "ContentItemsDynamicToolCallResponse" }, - "success": { - "type": "boolean" + { + "required": [ + "structuredContent" + ], + "title": "StructuredContentDynamicToolCallResponse" + }, + { + "required": [ + "errorMessage" + ], + "title": "ErrorMessageDynamicToolCallResponse" } - }, - "required": [ - "contentItems", - "success" ], - "title": "DynamicToolCallResponse", - "type": "object" + "title": "DynamicToolCallResult" } \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/ServerRequest.json b/codex-rs/app-server-protocol/schema/json/ServerRequest.json index e96baf73ce..55836a050c 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ServerRequest.json @@ -484,6 +484,17 @@ "null" ] }, + "supportedResultFormat": { + "anyOf": [ + { + "$ref": "#/definitions/DynamicToolResultFormat" + }, + { + "type": "null" + } + ], + "description": "Optional response format supported by the runtime serving this call." + }, "threadId": { "type": "string" }, @@ -503,6 +514,12 @@ ], "type": "object" }, + "DynamicToolResultFormat": { + "enum": [ + "structuredContent" + ], + "type": "string" + }, "ExecCommandApprovalParams": { "properties": { "approvalId": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 43eaba786e..ff0df6e077 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -3096,6 +3096,24 @@ "title": "CommandExecutionRequestApprovalResponse", "type": "object" }, + "DynamicToolCallContentItems": { + "properties": { + "contentItems": { + "items": { + "$ref": "#/definitions/v2/DynamicToolCallOutputContentItem" + }, + "type": "array" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "contentItems", + "success" + ], + "type": "object" + }, "DynamicToolCallParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -3109,6 +3127,17 @@ "null" ] }, + "supportedResultFormat": { + "anyOf": [ + { + "$ref": "#/definitions/DynamicToolResultFormat" + }, + { + "type": "null" + } + ], + "description": "Optional response format supported by the runtime serving this call." + }, "threadId": { "type": "string" }, @@ -3131,23 +3160,68 @@ }, "DynamicToolCallResponse": { "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "contentItems": { - "items": { - "$ref": "#/definitions/v2/DynamicToolCallOutputContentItem" - }, - "type": "array" + "anyOf": [ + { + "$ref": "#/definitions/DynamicToolCallContentItems" }, - "success": { - "type": "boolean" + { + "properties": { + "structuredContent": true, + "success": { + "type": "boolean" + } + }, + "required": [ + "structuredContent", + "success" + ], + "type": "object" + }, + { + "properties": { + "errorMessage": { + "type": "string" + }, + "success": { + "const": false, + "type": "boolean" + } + }, + "required": [ + "errorMessage", + "success" + ], + "type": "object" } - }, - "required": [ - "contentItems", - "success" ], - "title": "DynamicToolCallResponse", - "type": "object" + "description": "A dynamic tool reply carrying content items, structured JSON, or an error message.", + "oneOf": [ + { + "required": [ + "contentItems" + ], + "title": "ContentItemsDynamicToolCallResponse" + }, + { + "required": [ + "structuredContent" + ], + "title": "StructuredContentDynamicToolCallResponse" + }, + { + "required": [ + "errorMessage" + ], + "title": "ErrorMessageDynamicToolCallResponse" + } + ], + "title": "DynamicToolCallResult" + }, + "DynamicToolResultFormat": { + "enum": [ + "structuredContent" + ], + "type": "string" }, "ExecCommandApprovalParams": { "$schema": "http://json-schema.org/draft-07/schema#", diff --git a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst index 619cca31d5..667c1d0d4c 100644 Binary files a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst and b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst differ diff --git a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst index 1b61a2c646..1faa3cb371 100644 Binary files a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst and b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst differ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolCallParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolCallParams.ts index 0823ac66cd..ccf9eb6bfa 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolCallParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolCallParams.ts @@ -2,5 +2,10 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { JsonValue } from "../serde_json/JsonValue"; +import type { DynamicToolResultFormat } from "./DynamicToolResultFormat"; -export type DynamicToolCallParams = { threadId: string, turnId: string, callId: string, namespace: string | null, tool: string, arguments: JsonValue, }; +export type DynamicToolCallParams = { +/** + * Optional response format supported by the runtime serving this call. + */ +supportedResultFormat?: DynamicToolResultFormat, threadId: string, turnId: string, callId: string, namespace: string | null, tool: string, arguments: JsonValue, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolCallResult.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolCallResult.ts new file mode 100644 index 0000000000..6e2615c6f5 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolCallResult.ts @@ -0,0 +1,10 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { JsonValue } from "../serde_json/JsonValue"; +import type { DynamicToolCallResponse } from "./DynamicToolCallResponse"; + +/** + * A dynamic tool reply carrying content items, structured JSON, or an error message. + */ +export type DynamicToolCallResult = DynamicToolCallResponse | { structuredContent: JsonValue, success: boolean, } | { errorMessage: string, success: false, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolResultFormat.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolResultFormat.ts new file mode 100644 index 0000000000..e3856843a0 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolResultFormat.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type DynamicToolResultFormat = "structuredContent"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index bef410abd2..b0096ee4b2 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -143,10 +143,12 @@ export type { DesktopOnboardingEntrypoint } from "./DesktopOnboardingEntrypoint" export type { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; export type { DynamicToolCallParams } from "./DynamicToolCallParams"; export type { DynamicToolCallResponse } from "./DynamicToolCallResponse"; +export type { DynamicToolCallResult } from "./DynamicToolCallResult"; export type { DynamicToolCallStatus } from "./DynamicToolCallStatus"; export type { DynamicToolFunctionSpec } from "./DynamicToolFunctionSpec"; export type { DynamicToolNamespaceSpec } from "./DynamicToolNamespaceSpec"; export type { DynamicToolNamespaceTool } from "./DynamicToolNamespaceTool"; +export type { DynamicToolResultFormat } from "./DynamicToolResultFormat"; export type { DynamicToolSpec } from "./DynamicToolSpec"; export type { EnvironmentConnectionNotification } from "./EnvironmentConnectionNotification"; export type { EnvironmentSkillsParams } from "./EnvironmentSkillsParams"; diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index 1f44e030fb..d9f3cd2bc9 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -1377,6 +1377,14 @@ where } else if file_stem == "ServerNotification" { strip_v1_server_notification_variants_from_json_schema(&mut schema_value); add_server_notification_emitted_at_to_json_schema(&mut schema_value)?; + } else if file_stem == "DynamicToolCallResponse" { + // The untagged variants validate values. Require exactly one result key + // by presence so even a malformed second key cannot slip through. + schema_value["oneOf"] = serde_json::json!([ + {"required": ["contentItems"]}, + {"required": ["structuredContent"]}, + {"required": ["errorMessage"]}, + ]); } if let Some(Value::Object(error_schema)) = schema_value.pointer_mut("/definitions/CodexErrorInfo") diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index be4214ef00..b21c69a74b 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -1972,7 +1972,7 @@ server_request_definitions! { /// Execute a dynamic tool call on the client. DynamicToolCall => "item/tool/call" { params: v2::DynamicToolCallParams, - response: v2::DynamicToolCallResponse, + response: v2::DynamicToolCallResult, }, ChatgptAuthTokensRefresh => "account/chatgptAuthTokens/refresh" { diff --git a/codex-rs/app-server-protocol/src/protocol/v2/item.rs b/codex-rs/app-server-protocol/src/protocol/v2/item.rs index 3b6509f21c..274d438012 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/item.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/item.rs @@ -1039,12 +1039,9 @@ impl From for ThreadItemPayload { tool: call.tool, arguments: call.arguments, status: call.status.into(), - content_items: call.content_items.map(|items| { - items - .into_iter() - .map(DynamicToolCallOutputContentItem::from) - .collect() - }), + content_items: call + .content_items + .map(|items| items.into_iter().map(Into::into).collect()), success: call.success, duration_ms: call .duration @@ -1794,10 +1791,21 @@ pub struct FileChangeRequestApprovalResponse { pub decision: FileChangeApprovalDecision, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum DynamicToolResultFormat { + StructuredContent, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct DynamicToolCallParams { + /// Optional response format supported by the runtime serving this call. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub supported_result_format: Option, pub thread_id: String, pub turn_id: String, pub call_id: String, @@ -1809,6 +1817,8 @@ pub struct DynamicToolCallParams { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] +// The RPC union occupies DynamicToolCallResponse in the bundled schema. +#[schemars(rename = "DynamicToolCallContentItems")] pub struct DynamicToolCallResponse { pub content_items: Vec, pub success: bool, @@ -1861,6 +1871,102 @@ impl From } } +/// A dynamic tool reply carrying content items, structured JSON, or an error message. +#[derive(Serialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(untagged)] +#[ts(export_to = "v2/")] +pub enum DynamicToolCallResult { + ContentItems(DynamicToolCallResponse), + StructuredContent { + #[serde(rename = "structuredContent")] + structured_content: JsonValue, + success: bool, + }, + Error { + #[serde(rename = "errorMessage")] + error_message: String, + #[schemars(schema_with = "dynamic_tool_error_success_schema")] + #[ts(type = "false")] + success: bool, + }, +} + +impl From for codex_protocol::dynamic_tools::DynamicToolCallResult { + fn from(result: DynamicToolCallResult) -> Self { + match result { + DynamicToolCallResult::ContentItems(response) => { + Self::ContentItems(codex_protocol::dynamic_tools::DynamicToolResponse { + content_items: response.content_items.into_iter().map(Into::into).collect(), + success: response.success, + }) + } + DynamicToolCallResult::StructuredContent { + structured_content, + success, + } => Self::StructuredContent { + structured_content, + success, + }, + DynamicToolCallResult::Error { error_message, .. } => Self::Error { error_message }, + } + } +} + +impl<'de> Deserialize<'de> for DynamicToolCallResult { + fn deserialize>(deserializer: D) -> Result { + // Ignore client extensions, but count each result field even when its value is null. + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Reply { + success: bool, + #[serde(default, with = "serde_with::rust::unwrap_or_skip")] + content_items: Option>, + #[serde(default, with = "serde_with::rust::unwrap_or_skip")] + structured_content: Option, + #[serde(default, with = "serde_with::rust::unwrap_or_skip")] + error_message: Option, + } + let Reply { + success, + content_items, + structured_content, + error_message, + } = Reply::deserialize(deserializer)?; + match (content_items, structured_content, error_message) { + (Some(content_items), None, None) => Ok(Self::ContentItems(DynamicToolCallResponse { + content_items, + success, + })), + (None, Some(structured_content), None) => Ok(Self::StructuredContent { + structured_content, + success, + }), + (None, None, Some(error_message)) if !success => Ok(Self::Error { + error_message, + success, + }), + (None, None, Some(_)) => Err(serde::de::Error::custom( + "a dynamic tool error requires success: false", + )), + _ => Err(serde::de::Error::custom( + "expected exactly one of contentItems, structuredContent or errorMessage", + )), + } + } +} + +#[cfg(test)] +fn dynamic_tool_error_success_schema( + _: &mut schemars::r#gen::SchemaGenerator, +) -> schemars::schema::Schema { + schemars::schema::SchemaObject { + instance_type: Some(schemars::schema::InstanceType::Boolean.into()), + const_value: Some(JsonValue::Bool(false)), + ..Default::default() + } + .into() +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] diff --git a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs index c0b8c686e7..1837c0cade 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -5136,6 +5136,71 @@ fn codex_error_info_serializes_active_turn_not_steerable_turn_kind_in_camel_case ); } +#[test] +fn dynamic_tool_native_wire_round_trip() { + let schema = serde_json::to_value(schemars::schema_for!(DynamicToolCallResult)).unwrap(); + for wire in [ + serde_json::json!({"success":true,"structuredContent":{"threads":[{"id":"🌿","text":"a\\n\\\"b"}]}}), + serde_json::json!({"success":true,"structuredContent":[]}), + serde_json::json!({"success":true,"structuredContent":{}}), + serde_json::json!({"success":true,"structuredContent":null}), + serde_json::json!({"success":false,"errorMessage":"History unavailable"}), + serde_json::json!({"success":true,"contentItems":[]}), + ] { + let mut extended = wire.clone(); + extended["_meta"] = json!({"client": "extension"}); + let response: DynamicToolCallResult = serde_json::from_value(extended).unwrap(); + assert_eq!(serde_json::to_value(response).unwrap(), wire); + let fields = wire.as_object().unwrap(); + assert!( + schema["anyOf"].as_array().unwrap().iter().any(|variant| { + let variant = match variant["$ref"].as_str() { + Some(reference) => schema + .pointer(reference.strip_prefix('#').unwrap()) + .unwrap(), + None => variant, + }; + let required = variant["required"].as_array().unwrap(); + required.len() == fields.len() + && required + .iter() + .all(|key| fields.contains_key(key.as_str().unwrap())) + }), + "schema must accept the fields in {wire}" + ); + } +} + +#[test] +fn dynamic_tool_wire_rejects_ambiguous_results_and_inconsistent_errors() { + for wire in [ + json!({"success":true,"contentItems":[],"structuredContent":null}), + json!({"success":true,"contentItems":[],"errorMessage":null}), + json!({"success":false,"contentItems":null,"structuredContent":{}}), + json!({"success":true,"_meta":{}}), + json!({"success":true,"structuredContent":{},"errorMessage":"error"}), + json!({"success":false,"contentItems":[],"errorMessage":"error"}), + json!({"success":true,"errorMessage":"error"}), + ] { + assert!( + serde_json::from_value::(wire.clone()).is_err(), + "unexpectedly accepted {wire}" + ); + } +} + +#[test] +fn dynamic_tool_call_advertises_native_result_format() { + let without_format = serde_json::json!({"threadId":"t","turnId":"u","callId":"c","namespace":null,"tool":"lookup","arguments":{}}); + let mut params: super::DynamicToolCallParams = + serde_json::from_value(without_format.clone()).unwrap(); + assert_eq!(serde_json::to_value(¶ms).unwrap(), without_format); + params.supported_result_format = Some(super::DynamicToolResultFormat::StructuredContent); + let mut expected = without_format; + expected["supportedResultFormat"] = serde_json::json!("structuredContent"); + assert_eq!(serde_json::to_value(params).unwrap(), expected); +} + #[test] fn dynamic_tool_response_serializes_content_items() { let value = serde_json::to_value(DynamicToolCallResponse { diff --git a/codex-rs/app-server-protocol/src/schema_fixtures_tests.rs b/codex-rs/app-server-protocol/src/schema_fixtures_tests.rs index 8186255ae7..c2b71c7460 100644 --- a/codex-rs/app-server-protocol/src/schema_fixtures_tests.rs +++ b/codex-rs/app-server-protocol/src/schema_fixtures_tests.rs @@ -92,6 +92,35 @@ fn experimental_precomputed_exports_match_generated() -> Result<()> { Ok(()) } +#[test] +fn bundled_dynamic_tool_response_resolves_content_items_branch() -> Result<()> { + for experimental_api in [false, true] { + let exports = decode_precomputed_exports(experimental_api)?; + let bundle = exports + .json_schema + .get("codex_app_server_protocol.schemas.json") + .context("read bundled schema")?; + let bundle: serde_json::Value = serde_json::from_str(bundle)?; + let content_items = &bundle["definitions"]["DynamicToolCallResponse"]["anyOf"][0]; + let content_items = if let Some(reference) = content_items["$ref"].as_str() { + bundle + .pointer( + reference + .strip_prefix('#') + .context("local schema reference")?, + ) + .context("resolve content-items schema")? + } else { + content_items + }; + assert_eq!( + content_items["required"], + serde_json::json!(["contentItems", "success"]) + ); + } + Ok(()) +} + #[test] #[ignore = "invoked by `just write-app-server-schema`"] fn write_schema_fixtures_from_env() -> Result<()> { diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 7e89a34485..079152a28d 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -1135,6 +1135,9 @@ pub(crate) async fn apply_bespoke_event_handling( }; let dynamic_tool_call_params = match &event.item { CoreTurnItem::DynamicToolCall(item) => Some(DynamicToolCallParams { + supported_result_format: Some( + codex_app_server_protocol::DynamicToolResultFormat::StructuredContent, + ), thread_id: conversation_id.to_string(), turn_id: event.turn_id.clone(), call_id: item.id.clone(), @@ -3500,6 +3503,9 @@ mod tests { assert_eq!( params, DynamicToolCallParams { + supported_result_format: Some( + codex_app_server_protocol::DynamicToolResultFormat::StructuredContent + ), thread_id: conversation_id.to_string(), turn_id: "turn-1".to_string(), call_id: "dynamic-1".to_string(), diff --git a/codex-rs/app-server/src/dynamic_tools.rs b/codex-rs/app-server/src/dynamic_tools.rs index 0069b6d3e4..6517a46702 100644 --- a/codex-rs/app-server/src/dynamic_tools.rs +++ b/codex-rs/app-server/src/dynamic_tools.rs @@ -1,8 +1,7 @@ use codex_app_server_protocol::DynamicToolCallOutputContentItem; -use codex_app_server_protocol::DynamicToolCallResponse; +use codex_app_server_protocol::DynamicToolCallResult; use codex_core::CodexThread; -use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem as CoreDynamicToolCallOutputContentItem; -use codex_protocol::dynamic_tools::DynamicToolResponse as CoreDynamicToolResponse; +use codex_protocol::dynamic_tools::DynamicToolCallResult as CoreDynamicToolCallResult; use codex_protocol::protocol::Op; use std::sync::Arc; use tokio::sync::oneshot; @@ -21,7 +20,7 @@ pub(crate) async fn on_call_response( conversation: Arc, ) { let response = receiver.await; - let (response, _error) = match response { + let response = match response { Ok(Ok(value)) => decode_response(value), Ok(Err(err)) if is_turn_transition_server_request_error(&err) => return, Ok(Err(err)) => { @@ -34,21 +33,10 @@ pub(crate) async fn on_call_response( } }; - let DynamicToolCallResponse { - content_items, - success, - } = response.clone(); - let core_response = CoreDynamicToolResponse { - content_items: content_items - .into_iter() - .map(CoreDynamicToolCallOutputContentItem::from) - .collect(), - success, - }; if let Err(err) = conversation - .submit(Op::DynamicToolResponse { + .submit(Op::DynamicToolResult { id: call_id.clone(), - response: core_response, + response, }) .await { @@ -56,9 +44,11 @@ pub(crate) async fn on_call_response( } } -fn decode_response(value: serde_json::Value) -> (DynamicToolCallResponse, Option) { - match serde_json::from_value::(value) { - Ok(response) +fn decode_response(value: serde_json::Value) -> CoreDynamicToolCallResult { + let structured = + value.get("structuredContent").is_some() || value.get("errorMessage").is_some(); + match serde_json::from_value::(value) { + Ok(DynamicToolCallResult::ContentItems(response)) if response.content_items.iter().any(|item| { matches!( item, @@ -73,7 +63,7 @@ fn decode_response(value: serde_json::Value) -> (DynamicToolCallResponse, Option ); fallback_response(REMOTE_IMAGE_URL_ERROR) } - Ok(response) + Ok(DynamicToolCallResult::ContentItems(response)) if response.content_items.iter().any(|item| { matches!( item, @@ -90,22 +80,29 @@ fn decode_response(value: serde_json::Value) -> (DynamicToolCallResponse, Option ); fallback_response(INVALID_AUDIO_URL_ERROR) } - Ok(response) => (response, None), + Ok(response) => response.into(), Err(err) => { - error!("failed to deserialize DynamicToolCallResponse: {err}"); - fallback_response("dynamic tool response was invalid") + error!("failed to deserialize DynamicToolCallResult: {err}"); + let message = "dynamic tool response was invalid"; + if structured { + CoreDynamicToolCallResult::Error { + error_message: message.to_owned(), + } + } else { + fallback_response(message) + } } } } -fn fallback_response(message: &str) -> (DynamicToolCallResponse, Option) { - ( - DynamicToolCallResponse { - content_items: vec![DynamicToolCallOutputContentItem::InputText { +fn fallback_response(message: &str) -> CoreDynamicToolCallResult { + // Advertising support does not mean the client selected structured results. + CoreDynamicToolCallResult::ContentItems(codex_protocol::dynamic_tools::DynamicToolResponse { + content_items: vec![ + codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem::InputText { text: message.to_string(), - }], - success: false, - }, - Some(message.to_string()), - ) + }, + ], + success: false, + }) } diff --git a/codex-rs/app-server/src/outgoing_message.rs b/codex-rs/app-server/src/outgoing_message.rs index d54fb0b13a..d4a82cf2be 100644 --- a/codex-rs/app-server/src/outgoing_message.rs +++ b/codex-rs/app-server/src/outgoing_message.rs @@ -1910,6 +1910,9 @@ mod tests { let (dynamic_tool_request_id, _dynamic_tool_waiter) = thread_outgoing .send_request(ServerRequestPayload::DynamicToolCall( DynamicToolCallParams { + supported_result_format: Some( + codex_app_server_protocol::DynamicToolResultFormat::StructuredContent, + ), thread_id: thread_id.to_string(), turn_id: "turn-1".to_string(), call_id: "call-0".to_string(), @@ -1974,6 +1977,9 @@ mod tests { let (_dynamic_tool_request_id, dynamic_tool_waiter) = thread_outgoing .send_request(ServerRequestPayload::DynamicToolCall( DynamicToolCallParams { + supported_result_format: Some( + codex_app_server_protocol::DynamicToolResultFormat::StructuredContent, + ), thread_id: thread_id.to_string(), turn_id: "turn-1".to_string(), call_id: "call-0".to_string(), diff --git a/codex-rs/app-server/src/request_processors/thread_replay_tests.rs b/codex-rs/app-server/src/request_processors/thread_replay_tests.rs index 3ac68db917..1b308b93ab 100644 --- a/codex-rs/app-server/src/request_processors/thread_replay_tests.rs +++ b/codex-rs/app-server/src/request_processors/thread_replay_tests.rs @@ -60,6 +60,9 @@ async fn stalled_replay_can_be_replaced_or_unsubscribed() -> Result<()> { .send_request_to_connections( Some(&[]), ServerRequestPayload::DynamicToolCall(DynamicToolCallParams { + supported_result_format: Some( + codex_app_server_protocol::DynamicToolResultFormat::StructuredContent, + ), thread_id: thread_id.to_string(), turn_id: "turn".into(), call_id: index.to_string(), diff --git a/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs b/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs index 2e95267df3..b7822da8f3 100644 --- a/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs +++ b/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs @@ -16,16 +16,19 @@ use codex_app_server_protocol::DynamicToolNamespaceTool; use codex_app_server_protocol::DynamicToolSpec; use codex_app_server_protocol::ItemCompletedNotification; use codex_app_server_protocol::ItemStartedNotification; +use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::ThreadItemPayload; +use codex_app_server_protocol::ThreadReadResponse; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::UserInput as V2UserInput; +use codex_features::Feature; use codex_protocol::models::DEFAULT_IMAGE_DETAIL; use codex_protocol::models::FunctionCallOutputBody; use codex_protocol::models::FunctionCallOutputContentItem; @@ -482,6 +485,9 @@ async fn dynamic_tool_call_round_trip_sends_text_content_items_to_model() -> Res }; let expected = DynamicToolCallParams { + supported_result_format: Some( + codex_app_server_protocol::DynamicToolResultFormat::StructuredContent, + ), thread_id: thread_id.clone(), turn_id: turn_id.clone(), call_id: call_id.to_string(), @@ -672,6 +678,9 @@ async fn start_function_dynamic_tool_call(call_id: &str) -> Result Result Result<()> { + let server = responses::start_mock_server().await; + let script = r#" +const keys = ["native", "content-items", "tool-error", "request-error", "malformed"]; +const results = await Promise.all(keys.map(key => tools.lookup({ key }))); +text(results[0]); +text(results[2]); +text(JSON.stringify(results)); +"#; + responses::mount_sse_once( + &server, + responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_custom_tool_call("cell", "exec", script), + responses::ev_completed("resp-1"), + ]), + ) + .await; + let follow_up = responses::mount_sse_once( + &server, + create_final_assistant_message_sse_response("Done")?, + ) + .await; + + let home = TempDir::new()?; + let config = MockResponsesConfig::new(&server.uri()).enable_feature(Feature::CodeModeOnly); + if dedup { + config.enable_feature(Feature::CodeModeMcpResultDedup) + } else { + config.disable_feature(Feature::CodeModeMcpResultDedup) + } + .write(home.path())?; + let mut app = TestAppServer::builder() + .with_codex_home(home.path()) + .build_initialized() + .await?; + let thread = app + .start_thread(ThreadStartParams { + dynamic_tools: Some(vec![DynamicToolSpec::Function(DynamicToolFunctionSpec { + name: "lookup".to_owned(), + description: "Look up a value.".to_owned(), + input_schema: json!({ + "type": "object", + "properties": {"key": {"type": "string"}}, + "required": ["key"], + "additionalProperties": false + }), + defer_loading: false, + })]), + ..Default::default() + }) + .await? + .thread; + let start_id = app + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![V2UserInput::Text { + text: "Run the lookups.".to_owned(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + let _: TurnStartResponse = app.read_response(start_id).await?; + + let structured = json!({"threads": [{"id":"🌿", "attributes":[{}, [], "\n\""]}]}); + let content_items_text = r#"{"threads":[]}"#; + let mut native_call_id = None; + for _ in 0..5 { + let ServerRequest::DynamicToolCall { request_id, params } = timeout( + DEFAULT_READ_TIMEOUT, + app.read_stream_until_request_message(), + ) + .await?? + else { + anyhow::bail!("expected a dynamic tool request"); + }; + let result = match params.arguments["key"].as_str() { + Some("native") => { + native_call_id = Some(params.call_id); + json!({"success":true, "structuredContent": structured}) + } + Some("content-items") => json!({ + "success":true, "contentItems":[{"type": "inputText", "text": content_items_text}], + "_meta": {"client":"extension"} + }), + Some("tool-error") => json!({"success":false, "errorMessage": "History unavailable"}), + Some("request-error") => { + app.send_error( + request_id, + JSONRPCErrorError { + code: -32000, + message: "Client disconnected".to_owned(), + data: None, + }, + ) + .await?; + continue; + } + Some("malformed") => { + json!({"success":true, "contentItems":[], "structuredContent": {}}) + } + key => anyhow::bail!("unexpected lookup key {key:?}"), + }; + app.send_response(request_id, result).await?; + } + + timeout( + DEFAULT_READ_TIMEOUT, + app.read_stream_until_notification_message("turn/completed"), + ) + .await??; + let body = follow_up.single_request().body_json(); + let output = body["input"] + .as_array() + .context("expected request input")? + .iter() + .find(|item| item["type"] == "custom_tool_call_output" && item["call_id"] == "cell") + .context("expected executed Code Mode cell")?; + let printed = output["output"] + .as_array() + .context("expected Code Mode output content")? + .iter() + .filter_map(|part| part["text"].as_str()) + .filter_map(|text| serde_json::from_str::(text).ok()) + .collect::>(); + let error = |message: &str| { + json!({ + "content": [{"type": "text", "text": message}], "isError": true, + }) + }; + let native = json!({ + "content": [{"type": "text", "text": structured.to_string()}], + "structuredContent": structured, "isError": false, + }); + let printed_native = if dedup { + json!({"structuredContent": structured, "isError": false}) + } else { + native.clone() + }; + assert_eq!( + printed, + vec![ + printed_native, + error("History unavailable"), + json!([ + native, + content_items_text, + error("History unavailable"), + "dynamic tool request failed", + error("dynamic tool response was invalid"), + ]), + ], + ); + + let read_id = app + .send_request( + "thread/read", + Some(json!({ + "threadId": thread.id, "includeTurns": true + })), + ) + .await?; + let saved: ThreadReadResponse = app.read_response(read_id).await?; + let native_call_id = native_call_id.context("expected native tool request")?; + let saved_output = saved + .thread + .turns + .into_iter() + .flat_map(|turn| turn.items) + .find_map(|item| { + if let ThreadItemPayload::DynamicToolCall { + id, + success, + content_items, + .. + } = item.payload + && id == native_call_id + { + return Some((success, content_items)); + } + None + }) + .context("expected saved dynamic tool call")?; + assert_eq!( + saved_output, + ( + Some(true), + Some(vec![DynamicToolCallOutputContentItem::InputText { + text: structured.to_string() + }]) + ) + ); + Ok(()) +} + /// Ensures dynamic tool call responses can include structured content items. #[tokio::test] async fn dynamic_tool_call_round_trip_handles_content_items() -> Result<()> { diff --git a/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs b/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs index f12de00674..23a80277f8 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs @@ -347,6 +347,9 @@ async fn thread_unsubscribe_during_turn_keeps_turn_running( assert_eq!( params, DynamicToolCallParams { + supported_result_format: Some( + codex_app_server_protocol::DynamicToolResultFormat::StructuredContent + ), thread_id: thread_id.clone(), turn_id: started.turn_id, call_id: call_id.to_string(), diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index e0f35239cf..d6f2d1211e 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -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, id: String, response: DynamicToolResponse) { +pub async fn dynamic_tool_response( + sess: &Arc, + 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 } diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 68edcecb74..265252d476 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -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() { diff --git a/codex-rs/core/src/state/turn.rs b/codex-rs/core/src/state/turn.rs index 031a99501c..d54ec6ef51 100644 --- a/codex-rs/core/src/state/turn.rs +++ b/codex-rs/core/src/state/turn.rs @@ -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, pending_user_input: HashMap, pending_elicitations: HashMap<(String, RequestId), oneshot::Sender>, - pending_dynamic_tools: HashMap>, + pending_dynamic_tools: HashMap>, 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, - ) -> Option> { + tx: oneshot::Sender, + ) -> Option> { self.pending_dynamic_tools.insert(key, tx) } pub(crate) fn remove_pending_dynamic_tool( &mut self, key: &str, - ) -> Option> { + ) -> Option> { self.pending_dynamic_tools.remove(key) } diff --git a/codex-rs/core/src/tools/handlers/dynamic.rs b/codex-rs/core/src/tools/handlers/dynamic.rs index 603cc0f035..8b115a3fea 100644 --- a/codex-rs/core/src/tools/handlers/dynamic.rs +++ b/codex-rs/core/src/tools/handlers/dynamic.rs @@ -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::>(); - 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) { + 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, + text: String, + success: bool, + ) -> (Self, Vec) { + 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 { + 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, 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 { + 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 { +) -> Option { 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)] diff --git a/codex-rs/core/src/tools/handlers/dynamic_tests.rs b/codex-rs/core/src/tools/handlers/dynamic_tests.rs index 2d926b321d..1802c4dfb8 100644 --- a/codex-rs/core/src/tools/handlers/dynamic_tests.rs +++ b/codex-rs/core/src/tools/handlers/dynamic_tests.rs @@ -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 = 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 + ); +} diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index 6b71d591d2..d23c5afd5b 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -148,34 +148,7 @@ pub(crate) trait CoreToolRuntime: ToolExecutor { invocation: &ToolInvocation, result: &dyn ToolOutput, ) -> Option { - 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 { @@ -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, 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 { + 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)) diff --git a/codex-rs/core/tests/suite/code_mode_dynamic_tools_tests.rs b/codex-rs/core/tests/suite/code_mode_dynamic_tools_tests.rs index cc7d9cbbee..955a1f019f 100644 --- a/codex-rs/core/tests/suite/code_mode_dynamic_tools_tests.rs +++ b/codex-rs/core/tests/suite/code_mode_dynamic_tools_tests.rs @@ -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::(&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(()) } diff --git a/codex-rs/hooks/src/registry.rs b/codex-rs/hooks/src/registry.rs index 278890f745..034a2a1121 100644 --- a/codex-rs/hooks/src/registry.rs +++ b/codex-rs/hooks/src/registry.rs @@ -263,6 +263,17 @@ impl Hooks { self.engine.max_permission_request_timeout() } + /// Check the same names used by PostToolUse before preparing a large tool response. + pub fn has_post_tool_use_match(&self, name: &str, aliases: &[String]) -> bool { + let inputs = crate::events::common::matcher_inputs(name, aliases); + !crate::engine::dispatcher::select_handlers_for_matcher_inputs( + &self.engine.handlers, + HookEventName::PostToolUse, + &inputs, + ) + .is_empty() + } + pub fn preview_post_tool_use( &self, request: &PostToolUseRequest, diff --git a/codex-rs/protocol/src/dynamic_tools.rs b/codex-rs/protocol/src/dynamic_tools.rs index bbe92b8fe0..3b968605a4 100644 --- a/codex-rs/protocol/src/dynamic_tools.rs +++ b/codex-rs/protocol/src/dynamic_tools.rs @@ -62,6 +62,32 @@ pub struct DynamicToolResponse { pub success: bool, } +/// The result delivered to a pending dynamic tool call in Core. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] +#[serde(untagged)] +pub enum DynamicToolCallResult { + ContentItems(DynamicToolResponse), + StructuredContent { + #[serde(rename = "structuredContent")] + structured_content: JsonValue, + success: bool, + }, + Error { + #[serde(rename = "errorMessage")] + error_message: String, + }, +} + +impl DynamicToolCallResult { + pub fn success(&self) -> bool { + match self { + Self::ContentItems(response) => response.success, + Self::StructuredContent { success, .. } => *success, + Self::Error { .. } => false, + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "camelCase")] #[ts(tag = "type")] diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 3a27179101..0a34d47456 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -31,6 +31,7 @@ use crate::config_types::ReasoningSummary as ReasoningSummaryConfig; use crate::config_types::WindowsSandboxLevel; use crate::dynamic_tools::DynamicToolCallOutputContentItem; use crate::dynamic_tools::DynamicToolCallRequest; +use crate::dynamic_tools::DynamicToolCallResult; use crate::dynamic_tools::DynamicToolResponse; use crate::dynamic_tools::DynamicToolSpec; use crate::error::Result as CodexResult; @@ -921,6 +922,12 @@ pub enum Op { /// Tool output payload. response: DynamicToolResponse, }, + /// Reply from a client that supports structured dynamic tool results. + #[debug("DynamicToolResult {{ id: {id:?}, success: {} }}", response.success())] + DynamicToolResult { + id: String, + response: DynamicToolCallResult, + }, /// Request MCP servers to reinitialize and refresh cached tool lists. RefreshMcpServers, @@ -1172,7 +1179,9 @@ impl Op { Self::ResolveElicitation { .. } => "resolve_elicitation", Self::UserInputAnswer { .. } => "user_input_answer", Self::RequestPermissionsResponse { .. } => "request_permissions_response", - Self::DynamicToolResponse { .. } => "dynamic_tool_response", + Self::DynamicToolResponse { .. } | Self::DynamicToolResult { .. } => { + "dynamic_tool_response" + } Self::RefreshMcpServers => "refresh_mcp_servers", Self::ReloadUserConfig => "reload_user_config", Self::Compact => "compact", diff --git a/codex-rs/tools/src/tool_output.rs b/codex-rs/tools/src/tool_output.rs index 6e1783c23c..fabcaf1d74 100644 --- a/codex-rs/tools/src/tool_output.rs +++ b/codex-rs/tools/src/tool_output.rs @@ -84,6 +84,11 @@ pub trait ToolOutput: Send { )) } + /// Hands the final result to JavaScript, moving an already prepared value when possible. + fn into_code_mode_result(self: Box, 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() @@ -146,6 +151,10 @@ where (**self).code_mode_result(payload) } + fn into_code_mode_result(self: Box, payload: &ToolPayload) -> CodeModeToolResult { + (*self).into_code_mode_result(payload) + } + fn tool_result_metadata(&self) -> ToolResultMetadata { (**self).tool_result_metadata() } diff --git a/codex-rs/tui/src/app/agents_overview_tests.rs b/codex-rs/tui/src/app/agents_overview_tests.rs index d4993fc70d..c9153f65f6 100644 --- a/codex-rs/tui/src/app/agents_overview_tests.rs +++ b/codex-rs/tui/src/app/agents_overview_tests.rs @@ -2523,6 +2523,7 @@ async fn root_switch_preserves_idle_root_with_running_subagent() -> Result<()> { AppServerEvent::ServerRequest(Box::new(ServerRequest::DynamicToolCall { request_id: RequestId::Integer(99), params: DynamicToolCallParams { + supported_result_format: None, thread_id: idle_child_id.to_string(), turn_id: "turn".into(), call_id: "call".into(), diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 99181a18a3..b8480221c9 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -6982,6 +6982,7 @@ async fn side_defers_subagent_approval_overlay_until_side_exits() -> Result<()> ServerRequest::DynamicToolCall { request_id: AppServerRequestId::Integer(99), params: codex_app_server_protocol::DynamicToolCallParams { + supported_result_format: None, thread_id: quiet_thread_id.to_string(), turn_id: "turn-quiet".to_string(), call_id: "call-quiet".to_string(), diff --git a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs index 23d2deb785..4a83ff7c0b 100644 --- a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs +++ b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs @@ -3889,6 +3889,7 @@ async fn embedded_server_dispatches_only_its_own_dynamic_tools() -> Result<()> { ServerRequest::DynamicToolCall { request_id: AppServerRequestId::Integer(id), params: codex_app_server_protocol::DynamicToolCallParams { + supported_result_format: None, thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), call_id: "call-1".to_string(), @@ -4032,6 +4033,7 @@ async fn check_dynamic_tool_requests( ServerRequest::DynamicToolCall { request_id: AppServerRequestId::Integer(100), params: codex_app_server_protocol::DynamicToolCallParams { + supported_result_format: None, thread_id: thread_id.clone(), turn_id: "turn-1".to_string(), call_id: "call-1".to_string(), @@ -4052,6 +4054,7 @@ async fn check_dynamic_tool_requests( ServerRequest::DynamicToolCall { request_id: AppServerRequestId::Integer(101), params: codex_app_server_protocol::DynamicToolCallParams { + supported_result_format: None, thread_id: thread_id.clone(), turn_id: "turn-1".to_string(), call_id: "call-2".to_string(), @@ -4111,6 +4114,7 @@ async fn check_dynamic_tool_requests( ServerRequest::DynamicToolCall { request_id: AppServerRequestId::Integer(102), params: codex_app_server_protocol::DynamicToolCallParams { + supported_result_format: None, thread_id: thread_id.clone(), turn_id: "turn-1".to_string(), call_id: "call-3".to_string(), @@ -4145,6 +4149,7 @@ async fn check_dynamic_tool_requests( ServerRequest::DynamicToolCall { request_id: AppServerRequestId::String(format!("rejected-{index}")), params: codex_app_server_protocol::DynamicToolCallParams { + supported_result_format: None, thread_id: thread_id.clone(), turn_id: "turn-1".to_string(), call_id: format!("rejected-{index}"), @@ -4224,6 +4229,7 @@ async fn check_dynamic_tool_requests( &app_server, AppServerRequestId::Integer(103), codex_app_server_protocol::DynamicToolCallParams { + supported_result_format: None, thread_id: creation_source.to_string(), turn_id: "turn-1".to_string(), call_id: "call-4".to_string(), @@ -4348,6 +4354,7 @@ async fn check_dynamic_tool_requests( &app_server, AppServerRequestId::Integer(104), codex_app_server_protocol::DynamicToolCallParams { + supported_result_format: None, thread_id: thread_id.clone(), turn_id: "turn-1".to_string(), call_id: "call-5".to_string(), @@ -4894,6 +4901,7 @@ async fn remote_legacy_history_start_negotiates_once_for_resume_and_fork() -> Re let response = crate::dynamic_tools::execute( app_server.request_handle(), codex_app_server_protocol::DynamicToolCallParams { + supported_result_format: None, thread_id: started.session.thread_id.to_string(), turn_id: "source-turn".to_string(), call_id: "legacy-wait".to_string(), diff --git a/codex-rs/tui/src/dynamic_tools_mcp.rs b/codex-rs/tui/src/dynamic_tools_mcp.rs index 3936fac702..29d4937c5a 100644 --- a/codex-rs/tui/src/dynamic_tools_mcp.rs +++ b/codex-rs/tui/src/dynamic_tools_mcp.rs @@ -299,6 +299,7 @@ impl ServerHandler for DynamicToolMcpHandler { .and_then(Value::as_str) .map_or_else(|| format!("mcp-call-{}", Uuid::new_v4()), str::to_string); let params = DynamicToolCallParams { + supported_result_format: None, thread_id: thread_id.to_string(), turn_id, call_id, diff --git a/codex-rs/tui/src/dynamic_tools_tests.rs b/codex-rs/tui/src/dynamic_tools_tests.rs index d150724fd7..531583fa70 100644 --- a/codex-rs/tui/src/dynamic_tools_tests.rs +++ b/codex-rs/tui/src/dynamic_tools_tests.rs @@ -130,6 +130,7 @@ async fn call_tool( execute( server.request_handle(), DynamicToolCallParams { + supported_result_format: None, thread_id: source.to_string(), turn_id: "persisted-turn".to_string(), call_id: "call-1".to_string(),