From 5fcc380bd99b9f5e095a2b65231198f368334fef Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 30 Oct 2025 07:22:42 -0700 Subject: [PATCH 1/6] Pass initial history as an optional to codex delegate (#5950) This will give us more freedom on controlling the delegation. i.e we can fork our history and run `compact`. --- codex-rs/core/src/codex_delegate.rs | 5 ++++- codex-rs/core/src/tasks/review.rs | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index b123a8a3ff..c0fa0bf780 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -36,6 +36,7 @@ pub(crate) async fn run_codex_conversation_interactive( parent_session: Arc, parent_ctx: Arc, cancel_token: CancellationToken, + initial_history: Option, ) -> Result { let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); let (tx_ops, rx_ops) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); @@ -43,7 +44,7 @@ pub(crate) async fn run_codex_conversation_interactive( let CodexSpawnOk { codex, .. } = Codex::spawn( config, auth_manager, - InitialHistory::New, + initial_history.unwrap_or(InitialHistory::New), SessionSource::SubAgent(SubAgentSource::Review), ) .await?; @@ -93,6 +94,7 @@ pub(crate) async fn run_codex_conversation_one_shot( parent_session: Arc, parent_ctx: Arc, cancel_token: CancellationToken, + initial_history: Option, ) -> Result { // Use a child token so we can stop the delegate after completion without // requiring the caller to cancel the parent token. @@ -103,6 +105,7 @@ pub(crate) async fn run_codex_conversation_one_shot( parent_session, parent_ctx, child_cancel.clone(), + initial_history, ) .await?; diff --git a/codex-rs/core/src/tasks/review.rs b/codex-rs/core/src/tasks/review.rs index 286eefa6f5..57258f4cd9 100644 --- a/codex-rs/core/src/tasks/review.rs +++ b/codex-rs/core/src/tasks/review.rs @@ -90,6 +90,7 @@ async fn start_review_conversation( session.clone_session(), ctx.clone(), cancellation_token, + None, ) .await) .ok() From f4f9695978c22c2e24497b83d60118e44bfe97d4 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 30 Oct 2025 14:24:24 +0000 Subject: [PATCH 2/6] feat: compaction prompt configurable (#5959) ``` codex -c compact_prompt="Summarize in bullet points" ``` --- codex-rs/app-server-protocol/src/protocol.rs | 5 + .../app-server/src/codex_message_processor.rs | 2 + codex-rs/core/src/codex.rs | 19 ++- codex-rs/core/src/codex/compact.rs | 5 +- codex-rs/core/src/config/mod.rs | 116 +++++++++++++++--- codex-rs/core/src/config/profile.rs | 1 + codex-rs/core/tests/suite/compact.rs | 59 +++++++++ codex-rs/docs/codex_mcp_interface.md | 1 + codex-rs/exec/src/lib.rs | 1 + codex-rs/mcp-server/src/codex_tool_config.rs | 10 ++ codex-rs/tui/src/lib.rs | 1 + 11 files changed, 198 insertions(+), 22 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index 28e7ec50d6..05c9d91fb2 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -321,6 +321,10 @@ pub struct NewConversationParams { #[serde(skip_serializing_if = "Option::is_none")] pub base_instructions: Option, + /// Prompt used during conversation compaction. + #[serde(skip_serializing_if = "Option::is_none")] + pub compact_prompt: Option, + /// Whether to include the apply patch tool in the conversation. #[serde(skip_serializing_if = "Option::is_none")] pub include_apply_patch_tool: Option, @@ -1125,6 +1129,7 @@ mod tests { sandbox: None, config: None, base_instructions: None, + compact_prompt: None, include_apply_patch_tool: None, }, }; diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index f28d9c6af0..14418fb048 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -1760,6 +1760,7 @@ async fn derive_config_from_params( sandbox: sandbox_mode, config: cli_overrides, base_instructions, + compact_prompt, include_apply_patch_tool, } = params; let overrides = ConfigOverrides { @@ -1772,6 +1773,7 @@ async fn derive_config_from_params( model_provider, codex_linux_sandbox_exe, base_instructions, + compact_prompt, include_apply_patch_tool, include_view_image_tool: None, show_raw_agent_reasoning: None, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index f1cbefe2b6..e7fde7b99a 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -173,6 +173,7 @@ impl Codex { model_reasoning_summary: config.model_reasoning_summary, user_instructions, base_instructions: config.base_instructions.clone(), + compact_prompt: config.compact_prompt.clone(), approval_policy: config.approval_policy, sandbox_policy: config.sandbox_policy.clone(), cwd: config.cwd.clone(), @@ -265,6 +266,7 @@ pub(crate) struct TurnContext { /// instead of `std::env::current_dir()`. pub(crate) cwd: PathBuf, pub(crate) base_instructions: Option, + pub(crate) compact_prompt: Option, pub(crate) user_instructions: Option, pub(crate) approval_policy: AskForApproval, pub(crate) sandbox_policy: SandboxPolicy, @@ -281,6 +283,12 @@ impl TurnContext { .map(PathBuf::from) .map_or_else(|| self.cwd.clone(), |p| self.cwd.join(p)) } + + pub(crate) fn compact_prompt(&self) -> &str { + self.compact_prompt + .as_deref() + .unwrap_or(compact::SUMMARIZATION_PROMPT) + } } #[allow(dead_code)] @@ -301,6 +309,9 @@ pub(crate) struct SessionConfiguration { /// Base instructions override. base_instructions: Option, + /// Compact prompt override. + compact_prompt: Option, + /// When to escalate for approval for execution approval_policy: AskForApproval, /// How to sandbox commands executed in the system @@ -407,6 +418,7 @@ impl Session { client, cwd: session_configuration.cwd.clone(), base_instructions: session_configuration.base_instructions.clone(), + compact_prompt: session_configuration.compact_prompt.clone(), user_instructions: session_configuration.user_instructions.clone(), approval_policy: session_configuration.approval_policy, sandbox_policy: session_configuration.sandbox_policy.clone(), @@ -1313,7 +1325,7 @@ mod handlers { use crate::codex::Session; use crate::codex::SessionSettingsUpdate; use crate::codex::TurnContext; - use crate::codex::compact; + use crate::codex::spawn_review_thread; use crate::config::Config; use crate::mcp::auth::compute_auth_statuses; @@ -1540,7 +1552,7 @@ mod handlers { // Attempt to inject input into current task if let Err(items) = sess .inject_input(vec![UserInput::Text { - text: compact::SUMMARIZATION_PROMPT.to_string(), + text: turn_context.compact_prompt().to_string(), }]) .await { @@ -1664,6 +1676,7 @@ async fn spawn_review_thread( tools_config, user_instructions: None, base_instructions: Some(base_instructions.clone()), + compact_prompt: parent_turn_context.compact_prompt.clone(), approval_policy: parent_turn_context.approval_policy, sandbox_policy: parent_turn_context.sandbox_policy.clone(), shell_environment_policy: parent_turn_context.shell_environment_policy.clone(), @@ -2500,6 +2513,7 @@ mod tests { model_reasoning_summary: config.model_reasoning_summary, user_instructions: config.user_instructions.clone(), base_instructions: config.base_instructions.clone(), + compact_prompt: config.compact_prompt.clone(), approval_policy: config.approval_policy, sandbox_policy: config.sandbox_policy.clone(), cwd: config.cwd.clone(), @@ -2574,6 +2588,7 @@ mod tests { model_reasoning_summary: config.model_reasoning_summary, user_instructions: config.user_instructions.clone(), base_instructions: config.base_instructions.clone(), + compact_prompt: config.compact_prompt.clone(), approval_policy: config.approval_policy, sandbox_policy: config.sandbox_policy.clone(), cwd: config.cwd.clone(), diff --git a/codex-rs/core/src/codex/compact.rs b/codex-rs/core/src/codex/compact.rs index 6b07e2458c..eba9ebe286 100644 --- a/codex-rs/core/src/codex/compact.rs +++ b/codex-rs/core/src/codex/compact.rs @@ -39,9 +39,8 @@ pub(crate) async fn run_inline_auto_compact_task( sess: Arc, turn_context: Arc, ) { - let input = vec![UserInput::Text { - text: SUMMARIZATION_PROMPT.to_string(), - }]; + let prompt = turn_context.compact_prompt().to_string(); + let input = vec![UserInput::Text { text: prompt }]; run_compact_task_inner(sess, turn_context, input).await; } diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 3759a3adc0..b6bc9baf57 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -128,6 +128,9 @@ pub struct Config { /// Base instructions override. pub base_instructions: Option, + /// Compact prompt override. + pub compact_prompt: Option, + /// Optional external notifier command. When set, Codex will spawn this /// program after each completed *turn* (i.e. when the agent finishes /// processing a user submission). The value must be the full command @@ -540,6 +543,8 @@ pub struct ConfigToml { /// System instructions. pub instructions: Option, + /// Compact prompt used for history compaction. + pub compact_prompt: Option, /// When set, restricts ChatGPT login to a specific workspace identifier. #[serde(default)] @@ -644,6 +649,7 @@ pub struct ConfigToml { /// Legacy, now use features pub experimental_instructions_file: Option, + pub experimental_compact_prompt_file: Option, pub experimental_use_exec_command_tool: Option, pub experimental_use_unified_exec_tool: Option, pub experimental_use_rmcp_client: Option, @@ -824,6 +830,7 @@ pub struct ConfigOverrides { pub config_profile: Option, pub codex_linux_sandbox_exe: Option, pub base_instructions: Option, + pub compact_prompt: Option, pub include_apply_patch_tool: Option, pub include_view_image_tool: Option, pub show_raw_agent_reasoning: Option, @@ -854,6 +861,7 @@ impl Config { config_profile: config_profile_key, codex_linux_sandbox_exe, base_instructions, + compact_prompt, include_apply_patch_tool: include_apply_patch_tool_override, include_view_image_tool: include_view_image_tool_override, show_raw_agent_reasoning, @@ -1030,6 +1038,15 @@ impl Config { .and_then(|info| info.auto_compact_token_limit) }); + let compact_prompt = compact_prompt.or(cfg.compact_prompt).and_then(|value| { + let trimmed = value.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } + }); + // Load base instructions override from a file if specified. If the // path is relative, resolve it against the effective cwd so the // behaviour matches other path-like config values. @@ -1037,10 +1054,24 @@ impl Config { .experimental_instructions_file .as_ref() .or(cfg.experimental_instructions_file.as_ref()); - let file_base_instructions = - Self::get_base_instructions(experimental_instructions_path, &resolved_cwd)?; + let file_base_instructions = Self::load_override_from_file( + experimental_instructions_path, + &resolved_cwd, + "experimental instructions file", + )?; let base_instructions = base_instructions.or(file_base_instructions); + let experimental_compact_prompt_path = config_profile + .experimental_compact_prompt_file + .as_ref() + .or(cfg.experimental_compact_prompt_file.as_ref()); + let file_compact_prompt = Self::load_override_from_file( + experimental_compact_prompt_path, + &resolved_cwd, + "experimental compact prompt file", + )?; + let compact_prompt = compact_prompt.or(file_compact_prompt); + // Default review model when not set in config; allow CLI override to take precedence. let review_model = override_review_model .or(cfg.review_model) @@ -1064,6 +1095,7 @@ impl Config { notify: cfg.notify, user_instructions, base_instructions, + compact_prompt, // The config.toml omits "_mode" because it's a config file. However, "_mode" // is important in code to differentiate the mode from the store implementation. cli_auth_credentials_store_mode: cfg.cli_auth_credentials_store.unwrap_or_default(), @@ -1160,18 +1192,15 @@ impl Config { None } - fn get_base_instructions( + fn load_override_from_file( path: Option<&PathBuf>, cwd: &Path, + description: &str, ) -> std::io::Result> { - let p = match path.as_ref() { - None => return Ok(None), - Some(p) => p, + let Some(p) = path else { + return Ok(None); }; - // Resolve relative paths against the provided cwd to make CLI - // overrides consistent regardless of where the process was launched - // from. let full_path = if p.is_relative() { cwd.join(p) } else { @@ -1181,10 +1210,7 @@ impl Config { let contents = std::fs::read_to_string(&full_path).map_err(|e| { std::io::Error::new( e.kind(), - format!( - "failed to read experimental instructions file {}: {e}", - full_path.display() - ), + format!("failed to read {description} {}: {e}", full_path.display()), ) })?; @@ -1192,10 +1218,7 @@ impl Config { if s.is_empty() { Err(std::io::Error::new( std::io::ErrorKind::InvalidData, - format!( - "experimental instructions file is empty: {}", - full_path.display() - ), + format!("{description} is empty: {}", full_path.display()), )) } else { Ok(Some(s)) @@ -2653,6 +2676,61 @@ model = "gpt-5-codex" } } + #[test] + fn cli_override_sets_compact_prompt() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let overrides = ConfigOverrides { + compact_prompt: Some("Use the compact override".to_string()), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + ConfigToml::default(), + overrides, + codex_home.path().to_path_buf(), + )?; + + assert_eq!( + config.compact_prompt.as_deref(), + Some("Use the compact override") + ); + + Ok(()) + } + + #[test] + fn loads_compact_prompt_from_file() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let workspace = codex_home.path().join("workspace"); + std::fs::create_dir_all(&workspace)?; + + let prompt_path = workspace.join("compact_prompt.txt"); + std::fs::write(&prompt_path, " summarize differently ")?; + + let cfg = ConfigToml { + experimental_compact_prompt_file: Some(PathBuf::from("compact_prompt.txt")), + ..Default::default() + }; + + let overrides = ConfigOverrides { + cwd: Some(workspace), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + cfg, + overrides, + codex_home.path().to_path_buf(), + )?; + + assert_eq!( + config.compact_prompt.as_deref(), + Some("summarize differently") + ); + + Ok(()) + } + fn create_test_fixture() -> std::io::Result { let toml = r#" model = "o3" @@ -2808,6 +2886,7 @@ model_verbosity = "high" model_verbosity: None, chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), base_instructions: None, + compact_prompt: None, forced_chatgpt_workspace_id: None, forced_login_method: None, include_apply_patch_tool: false, @@ -2879,6 +2958,7 @@ model_verbosity = "high" model_verbosity: None, chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), base_instructions: None, + compact_prompt: None, forced_chatgpt_workspace_id: None, forced_login_method: None, include_apply_patch_tool: false, @@ -2965,6 +3045,7 @@ model_verbosity = "high" model_verbosity: None, chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), base_instructions: None, + compact_prompt: None, forced_chatgpt_workspace_id: None, forced_login_method: None, include_apply_patch_tool: false, @@ -3037,6 +3118,7 @@ model_verbosity = "high" model_verbosity: Some(Verbosity::High), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), base_instructions: None, + compact_prompt: None, forced_chatgpt_workspace_id: None, forced_login_method: None, include_apply_patch_tool: false, diff --git a/codex-rs/core/src/config/profile.rs b/codex-rs/core/src/config/profile.rs index 7b7cafedbc..7a863f1381 100644 --- a/codex-rs/core/src/config/profile.rs +++ b/codex-rs/core/src/config/profile.rs @@ -22,6 +22,7 @@ pub struct ConfigProfile { pub model_verbosity: Option, pub chatgpt_base_url: Option, pub experimental_instructions_file: Option, + pub experimental_compact_prompt_file: Option, pub include_apply_patch_tool: Option, pub include_view_image_tool: Option, pub experimental_use_unified_exec_tool: Option, diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index 17d72abe7e..0dea8a02cb 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -261,6 +261,65 @@ async fn summarize_context_three_requests_and_instructions() { ); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn manual_compact_uses_custom_prompt() { + skip_if_no_network!(); + + let server = start_mock_server().await; + let sse_stream = sse(vec![ev_completed("r1")]); + mount_sse_once(&server, sse_stream).await; + + let custom_prompt = "Use this compact prompt instead"; + + let model_provider = ModelProviderInfo { + base_url: Some(format!("{}/v1", server.uri())), + ..built_in_model_providers()["openai"].clone() + }; + let home = TempDir::new().unwrap(); + let mut config = load_default_config_for_test(&home); + config.model_provider = model_provider; + config.compact_prompt = Some(custom_prompt.to_string()); + + let conversation_manager = ConversationManager::with_auth(CodexAuth::from_api_key("dummy")); + let codex = conversation_manager + .new_conversation(config) + .await + .expect("create conversation") + .conversation; + + codex.submit(Op::Compact).await.expect("trigger compact"); + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; + + let requests = server.received_requests().await.expect("collect requests"); + let body = requests + .iter() + .find_map(|req| req.body_json::().ok()) + .expect("summary request body"); + + let input = body + .get("input") + .and_then(|v| v.as_array()) + .expect("input array"); + let mut found_custom_prompt = false; + let mut found_default_prompt = false; + + for item in input { + if item["type"].as_str() != Some("message") { + continue; + } + let text = item["content"][0]["text"].as_str().unwrap_or_default(); + if text == custom_prompt { + found_custom_prompt = true; + } + if text == SUMMARIZATION_PROMPT { + found_default_prompt = true; + } + } + + assert!(found_custom_prompt, "custom prompt should be injected"); + assert!(!found_default_prompt, "default prompt should be replaced"); +} + // Windows CI only: bump to 4 workers to prevent SSE/event starvation and test timeouts. #[cfg_attr(windows, tokio::test(flavor = "multi_thread", worker_threads = 4))] #[cfg_attr(not(windows), tokio::test(flavor = "multi_thread", worker_threads = 2))] diff --git a/codex-rs/docs/codex_mcp_interface.md b/codex-rs/docs/codex_mcp_interface.md index aaaa0f4cad..5945db8505 100644 --- a/codex-rs/docs/codex_mcp_interface.md +++ b/codex-rs/docs/codex_mcp_interface.md @@ -61,6 +61,7 @@ Request `newConversation` params (subset): - `sandbox`: `read-only` | `workspace-write` | `danger-full-access` - `config`: map of additional config overrides - `baseInstructions`: optional instruction override +- `compactPrompt`: optional replacement for the default compaction prompt - `includePlanTool` / `includeApplyPatchTool`: booleans Response: `{ conversationId, model, reasoningEffort?, rolloutPath }` diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index af45a7d20a..4ab0b0302b 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -174,6 +174,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any model_provider, codex_linux_sandbox_exe, base_instructions: None, + compact_prompt: None, include_apply_patch_tool: None, include_view_image_tool: None, show_raw_agent_reasoning: oss.then_some(true), diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index 24a5eec4b8..471d65603a 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -49,6 +49,10 @@ pub struct CodexToolCallParam { /// The set of instructions to use instead of the default ones. #[serde(default, skip_serializing_if = "Option::is_none")] pub base_instructions: Option, + + /// Prompt used when compacting the conversation. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compact_prompt: Option, } /// Custom enum mirroring [`AskForApproval`], but has an extra dependency on @@ -141,6 +145,7 @@ impl CodexToolCallParam { sandbox, config: cli_overrides, base_instructions, + compact_prompt, } = self; // Build the `ConfigOverrides` recognized by codex-core. @@ -154,6 +159,7 @@ impl CodexToolCallParam { model_provider: None, codex_linux_sandbox_exe, base_instructions, + compact_prompt, include_apply_patch_tool: None, include_view_image_tool: None, show_raw_agent_reasoning: None, @@ -288,6 +294,10 @@ mod tests { "description": "The set of instructions to use instead of the default ones.", "type": "string" }, + "compact-prompt": { + "description": "Prompt used when compacting the conversation.", + "type": "string" + }, }, "required": [ "prompt" diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 028bf68e87..0629dd8c07 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -144,6 +144,7 @@ pub async fn run_main( config_profile: cli.config_profile.clone(), codex_linux_sandbox_exe, base_instructions: None, + compact_prompt: None, include_apply_patch_tool: None, include_view_image_tool: None, show_raw_agent_reasoning: cli.oss.then_some(true), From 209af686115189eca795a25d0309692a06cdf9f3 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 30 Oct 2025 17:40:38 +0000 Subject: [PATCH 3/6] nit: log rmcp_client (#5978) --- codex-rs/cli/src/mcp_cmd.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 65c459a31c..b8ad63ef23 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -347,9 +347,7 @@ async fn run_login(config_overrides: &CliConfigOverrides, login_args: LoginArgs) .context("failed to load configuration")?; if !config.features.enabled(Feature::RmcpClient) { - bail!( - "OAuth login is only supported when experimental_use_rmcp_client is true in config.toml." - ); + bail!("OAuth login is only supported when [feature].rmcp_client is true in config.toml."); } let LoginArgs { name, scopes } = login_args; From 4a55646a02a0336c46c3fb4cd78aea35b966b513 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Thu, 30 Oct 2025 10:40:48 -0700 Subject: [PATCH 4/6] chore: testing on freeform apply_patch (#5952) ## Summary Duplicates the tests in `apply_patch_cli.rs`, but tests the freeform apply_patch tool as opposed to the function call path. The good news is that all the tests pass with zero logical tests, with the exception of the heredoc, which doesn't really make sense in the freeform tool context anyway. @jif-oai since you wrote the original tests in #5557, I'd love your opinion on the right way to DRY these test cases between the two. Happy to set up a more sophisticated harness, but didn't want to go down the rabbit hole until we agreed on the right pattern ## Testing - [x] These are tests --- codex-rs/core/tests/common/test_codex.rs | 24 + .../core/tests/suite/apply_patch_freeform.rs | 1001 +++++++++++++++++ codex-rs/core/tests/suite/mod.rs | 2 + 3 files changed, 1027 insertions(+) create mode 100644 codex-rs/core/tests/suite/apply_patch_freeform.rs diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 6d1fda5aa0..0f9fdaae8f 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -240,6 +240,30 @@ impl TestCodexHarness { .expect("output string") .to_string() } + + pub async fn custom_tool_call_output(&self, call_id: &str) -> String { + let bodies = self.request_bodies().await; + custom_tool_call_output(&bodies, call_id) + .get("output") + .and_then(Value::as_str) + .expect("output string") + .to_string() + } +} + +fn custom_tool_call_output<'a>(bodies: &'a [Value], call_id: &str) -> &'a Value { + for body in bodies { + if let Some(items) = body.get("input").and_then(Value::as_array) { + for item in items { + if item.get("type").and_then(Value::as_str) == Some("custom_tool_call_output") + && item.get("call_id").and_then(Value::as_str) == Some(call_id) + { + return item; + } + } + } + } + panic!("custom_tool_call_output {call_id} not found"); } fn function_call_output<'a>(bodies: &'a [Value], call_id: &str) -> &'a Value { diff --git a/codex-rs/core/tests/suite/apply_patch_freeform.rs b/codex-rs/core/tests/suite/apply_patch_freeform.rs new file mode 100644 index 0000000000..72c405eb1b --- /dev/null +++ b/codex-rs/core/tests/suite/apply_patch_freeform.rs @@ -0,0 +1,1001 @@ +#![allow(clippy::expect_used)] + +use anyhow::Result; +use core_test_support::responses::ev_apply_patch_custom_tool_call; +use pretty_assertions::assert_eq; +use std::fs; + +use codex_core::config::Config; +use codex_core::features::Feature; +use codex_core::model_family::find_family_for_model; +use codex_core::protocol::AskForApproval; +use codex_core::protocol::EventMsg; +use codex_core::protocol::Op; +use codex_core::protocol::SandboxPolicy; +use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::user_input::UserInput; +use core_test_support::assert_regex_match; +use core_test_support::responses::ev_assistant_message; +use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_response_created; +use core_test_support::responses::mount_sse_sequence; +use core_test_support::responses::sse; +use core_test_support::skip_if_no_network; +use core_test_support::test_codex::TestCodexHarness; +use core_test_support::wait_for_event; + +async fn apply_patch_harness() -> Result { + apply_patch_harness_with(|_| {}).await +} + +async fn apply_patch_harness_with( + configure: impl FnOnce(&mut Config) + Send + 'static, +) -> Result { + TestCodexHarness::with_config(|config| { + config.include_apply_patch_tool = true; + configure(config); + }) + .await +} + +async fn mount_apply_patch( + harness: &TestCodexHarness, + call_id: &str, + patch: &str, + assistant_msg: &str, +) { + mount_sse_sequence( + harness.server(), + freeform_apply_patch_responses(call_id, patch, assistant_msg), + ) + .await; +} + +fn freeform_apply_patch_responses(call_id: &str, patch: &str, assistant_msg: &str) -> Vec { + vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_apply_patch_custom_tool_call(call_id, patch), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_assistant_message("msg-1", assistant_msg), + ev_completed("resp-2"), + ]), + ] +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_multiple_operations_integration() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness_with(|config| { + config.model = "gpt-5".to_string(); + config.model_family = find_family_for_model("gpt-5").expect("gpt-5 is valid"); + }) + .await?; + + // Seed workspace state + let modify_path = harness.path("modify.txt"); + let delete_path = harness.path("delete.txt"); + fs::write(&modify_path, "line1\nline2\n")?; + fs::write(&delete_path, "obsolete\n")?; + + let patch = "*** Begin Patch\n*** Add File: nested/new.txt\n+created\n*** Delete File: delete.txt\n*** Update File: modify.txt\n@@\n-line2\n+changed\n*** End Patch"; + + let call_id = "apply-multi-ops"; + mount_apply_patch(&harness, call_id, patch, "done").await; + + harness.submit("please apply multi-ops patch").await?; + + let out = harness.custom_tool_call_output(call_id).await; + + let expected = r"(?s)^Exit code: 0 +Wall time: [0-9]+(?:\.[0-9]+)? seconds +Output: +Success. Updated the following files: +A nested/new.txt +M modify.txt +D delete.txt +?$"; + assert_regex_match(expected, &out); + + assert_eq!( + fs::read_to_string(harness.path("nested/new.txt"))?, + "created\n" + ); + assert_eq!(fs::read_to_string(&modify_path)?, "line1\nchanged\n"); + assert!(!delete_path.exists()); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_multiple_chunks() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let target = harness.path("multi.txt"); + fs::write(&target, "line1\nline2\nline3\nline4\n")?; + + let patch = "*** Begin Patch\n*** Update File: multi.txt\n@@\n-line2\n+changed2\n@@\n-line4\n+changed4\n*** End Patch"; + let call_id = "apply-multi-chunks"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("apply multi-chunk patch").await?; + + assert_eq!( + fs::read_to_string(&target)?, + "line1\nchanged2\nline3\nchanged4\n" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_moves_file_to_new_directory() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let original = harness.path("old/name.txt"); + let new_path = harness.path("renamed/dir/name.txt"); + fs::create_dir_all(original.parent().expect("parent"))?; + fs::write(&original, "old content\n")?; + + let patch = "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/dir/name.txt\n@@\n-old content\n+new content\n*** End Patch"; + let call_id = "apply-move"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("apply move patch").await?; + + assert!(!original.exists()); + assert_eq!(fs::read_to_string(&new_path)?, "new content\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_updates_file_appends_trailing_newline() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let target = harness.path("no_newline.txt"); + fs::write(&target, "no newline at end")?; + + let patch = "*** Begin Patch\n*** Update File: no_newline.txt\n@@\n-no newline at end\n+first line\n+second line\n*** End Patch"; + let call_id = "apply-append-nl"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("apply newline patch").await?; + + let contents = fs::read_to_string(&target)?; + assert!(contents.ends_with('\n')); + assert_eq!(contents, "first line\nsecond line\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_insert_only_hunk_modifies_file() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let target = harness.path("insert_only.txt"); + fs::write(&target, "alpha\nomega\n")?; + + let patch = "*** Begin Patch\n*** Update File: insert_only.txt\n@@\n alpha\n+beta\n omega\n*** End Patch"; + let call_id = "apply-insert-only"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("insert lines via apply_patch").await?; + + assert_eq!(fs::read_to_string(&target)?, "alpha\nbeta\nomega\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_move_overwrites_existing_destination() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let original = harness.path("old/name.txt"); + let destination = harness.path("renamed/dir/name.txt"); + fs::create_dir_all(original.parent().expect("parent"))?; + fs::create_dir_all(destination.parent().expect("parent"))?; + fs::write(&original, "from\n")?; + fs::write(&destination, "existing\n")?; + + let patch = "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/dir/name.txt\n@@\n-from\n+new\n*** End Patch"; + let call_id = "apply-move-overwrite"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("apply move overwrite patch").await?; + + assert!(!original.exists()); + assert_eq!(fs::read_to_string(&destination)?, "new\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_move_without_content_change_has_no_turn_diff() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + let test = harness.test(); + let codex = test.codex.clone(); + let cwd = test.cwd.clone(); + + let original = harness.path("old/name.txt"); + let destination = harness.path("renamed/name.txt"); + fs::create_dir_all(original.parent().expect("parent should exist"))?; + fs::write(&original, "same\n")?; + + let patch = "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/name.txt\n@@\n same\n*** End Patch"; + let call_id = "apply-move-no-change"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + let model = test.session_configured.model.clone(); + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "rename without content change".into(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model, + effort: None, + summary: ReasoningSummary::Auto, + }) + .await?; + + let mut saw_turn_diff = false; + wait_for_event(&codex, |event| match event { + EventMsg::TurnDiff(_) => { + saw_turn_diff = true; + false + } + EventMsg::TaskComplete(_) => true, + _ => false, + }) + .await; + + assert!(!saw_turn_diff, "pure rename should not emit a turn diff"); + assert!(!original.exists()); + assert_eq!(fs::read_to_string(&destination)?, "same\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_add_overwrites_existing_file() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let path = harness.path("duplicate.txt"); + fs::write(&path, "old content\n")?; + + let patch = "*** Begin Patch\n*** Add File: duplicate.txt\n+new content\n*** End Patch"; + let call_id = "apply-add-overwrite"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("apply add overwrite patch").await?; + + assert_eq!(fs::read_to_string(&path)?, "new content\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_rejects_invalid_hunk_header() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let patch = "*** Begin Patch\n*** Frobnicate File: foo\n*** End Patch"; + let call_id = "apply-invalid-header"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("apply invalid header patch").await?; + + let out = harness.custom_tool_call_output(call_id).await; + + assert!( + out.contains("apply_patch verification failed"), + "expected verification failure message" + ); + assert!( + out.contains("is not a valid hunk header"), + "expected parse diagnostics in output: {out:?}" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_reports_missing_context() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let target = harness.path("modify.txt"); + fs::write(&target, "line1\nline2\n")?; + + let patch = + "*** Begin Patch\n*** Update File: modify.txt\n@@\n-missing\n+changed\n*** End Patch"; + let call_id = "apply-missing-context"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("apply missing context patch").await?; + + let out = harness.custom_tool_call_output(call_id).await; + + assert!( + out.contains("apply_patch verification failed"), + "expected verification failure message" + ); + assert!(out.contains("Failed to find expected lines in")); + assert_eq!(fs::read_to_string(&target)?, "line1\nline2\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_reports_missing_target_file() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let patch = "*** Begin Patch\n*** Update File: missing.txt\n@@\n-nope\n+better\n*** End Patch"; + let call_id = "apply-missing-file"; + mount_apply_patch(&harness, call_id, patch, "fail").await; + + harness.submit("attempt to update a missing file").await?; + + let out = harness.custom_tool_call_output(call_id).await; + assert!( + out.contains("apply_patch verification failed"), + "expected verification failure message" + ); + assert!( + out.contains("Failed to read file to update"), + "expected missing file diagnostics: {out}" + ); + assert!( + out.contains("missing.txt"), + "expected missing file path in diagnostics: {out}" + ); + assert!(!harness.path("missing.txt").exists()); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_delete_missing_file_reports_error() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let patch = "*** Begin Patch\n*** Delete File: missing.txt\n*** End Patch"; + let call_id = "apply-delete-missing"; + mount_apply_patch(&harness, call_id, patch, "fail").await; + + harness.submit("attempt to delete missing file").await?; + + let out = harness.custom_tool_call_output(call_id).await; + + assert!( + out.contains("apply_patch verification failed"), + "expected verification failure message: {out}" + ); + assert!( + out.contains("Failed to read"), + "missing delete diagnostics should mention read failure: {out}" + ); + assert!( + out.contains("missing.txt"), + "missing delete diagnostics should surface target path: {out}" + ); + assert!(!harness.path("missing.txt").exists()); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_rejects_empty_patch() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let patch = "*** Begin Patch\n*** End Patch"; + let call_id = "apply-empty"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("apply empty patch").await?; + + let out = harness.custom_tool_call_output(call_id).await; + assert!( + out.contains("patch rejected: empty patch"), + "expected rejection for empty patch: {out}" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_delete_directory_reports_verification_error() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + fs::create_dir(harness.path("dir"))?; + + let patch = "*** Begin Patch\n*** Delete File: dir\n*** End Patch"; + let call_id = "apply-delete-dir"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("delete a directory via apply_patch").await?; + + let out = harness.custom_tool_call_output(call_id).await; + assert!(out.contains("apply_patch verification failed")); + assert!(out.contains("Failed to read")); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_rejects_path_traversal_outside_workspace() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let escape_path = harness + .test() + .cwd + .path() + .parent() + .expect("cwd should have parent") + .join("escape.txt"); + let _ = fs::remove_file(&escape_path); + + let patch = "*** Begin Patch\n*** Add File: ../escape.txt\n+outside\n*** End Patch"; + let call_id = "apply-path-traversal"; + mount_apply_patch(&harness, call_id, patch, "fail").await; + + let sandbox_policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![], + network_access: false, + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + }; + harness + .submit_with_policy( + "attempt to escape workspace via apply_patch", + sandbox_policy, + ) + .await?; + + let out = harness.custom_tool_call_output(call_id).await; + assert!( + out.contains( + "patch rejected: writing outside of the project; rejected by user approval settings" + ), + "expected rejection message for path traversal: {out}" + ); + assert!( + !escape_path.exists(), + "path traversal should be rejected; tool output: {out}" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_rejects_move_path_traversal_outside_workspace() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let escape_path = harness + .test() + .cwd + .path() + .parent() + .expect("cwd should have parent") + .join("escape-move.txt"); + let _ = fs::remove_file(&escape_path); + + let source = harness.path("stay.txt"); + fs::write(&source, "from\n")?; + + let patch = "*** Begin Patch\n*** Update File: stay.txt\n*** Move to: ../escape-move.txt\n@@\n-from\n+to\n*** End Patch"; + let call_id = "apply-move-traversal"; + mount_apply_patch(&harness, call_id, patch, "fail").await; + + let sandbox_policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![], + network_access: false, + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + }; + harness + .submit_with_policy("attempt move traversal via apply_patch", sandbox_policy) + .await?; + + let out = harness.custom_tool_call_output(call_id).await; + assert!( + out.contains( + "patch rejected: writing outside of the project; rejected by user approval settings" + ), + "expected rejection message for path traversal: {out}" + ); + assert!( + !escape_path.exists(), + "move path traversal should be rejected; tool output: {out}" + ); + assert_eq!(fs::read_to_string(&source)?, "from\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_verification_failure_has_no_side_effects() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness_with(|config| { + config.features.enable(Feature::ApplyPatchFreeform); + }) + .await?; + + // Compose a patch that would create a file, then fail verification on an update. + let call_id = "apply-partial-no-side-effects"; + let patch = "*** Begin Patch\n*** Add File: created.txt\n+hello\n*** Update File: missing.txt\n@@\n-old\n+new\n*** End Patch"; + + mount_apply_patch(&harness, call_id, patch, "failed").await; + + harness.submit("attempt partial apply patch").await?; + + let created = harness.path("created.txt"); + assert!( + !created.exists(), + "verification failure should prevent any filesystem changes" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_shell_failure_propagates_error_and_skips_diff() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness_with(|config| { + config.model = "gpt-5".to_string(); + config.model_family = find_family_for_model("gpt-5").expect("gpt-5 is valid"); + }) + .await?; + let test = harness.test(); + let codex = test.codex.clone(); + let cwd = test.cwd.clone(); + + let target = cwd.path().join("invalid.txt"); + fs::write(&target, "ok\n")?; + + let patch = + "*** Begin Patch\n*** Update File: invalid.txt\n@@\n-nope\n+changed\n*** End Patch\n"; + let call_id = "shell-apply-failure"; + let bodies = vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_apply_patch_custom_tool_call(call_id, patch), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "fail"), + ev_completed("resp-2"), + ]), + ]; + mount_sse_sequence(harness.server(), bodies).await; + + let model = test.session_configured.model.clone(); + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "apply patch via shell".into(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model, + effort: None, + summary: ReasoningSummary::Auto, + }) + .await?; + + let mut saw_turn_diff = false; + wait_for_event(&codex, |event| match event { + EventMsg::TurnDiff(_) => { + saw_turn_diff = true; + false + } + EventMsg::TaskComplete(_) => true, + _ => false, + }) + .await; + + assert!( + !saw_turn_diff, + "turn diff should not be emitted when shell apply_patch fails verification" + ); + + let out = harness.custom_tool_call_output(call_id).await; + assert!( + out.contains("apply_patch verification failed"), + "expected verification failure message" + ); + assert!( + out.contains("Failed to find expected lines in"), + "expected failure diagnostics: {out}" + ); + assert!( + out.contains("invalid.txt"), + "expected file path in output: {out}" + ); + assert_eq!(fs::read_to_string(&target)?, "ok\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_function_accepts_lenient_heredoc_wrapped_patch() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let file_name = "lenient.txt"; + let patch_inner = + format!("*** Begin Patch\n*** Add File: {file_name}\n+lenient\n*** End Patch\n"); + let wrapped = format!("<<'EOF'\n{patch_inner}EOF\n"); + let call_id = "apply-lenient"; + mount_apply_patch(&harness, call_id, &wrapped, "ok").await; + + harness.submit("apply lenient heredoc patch").await?; + + let new_file = harness.path(file_name); + assert_eq!(fs::read_to_string(new_file)?, "lenient\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_end_of_file_anchor() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let target = harness.path("tail.txt"); + fs::write(&target, "alpha\nlast\n")?; + + let patch = "*** Begin Patch\n*** Update File: tail.txt\n@@\n-last\n+end\n*** End of File\n*** End Patch"; + let call_id = "apply-eof"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("apply EOF-anchored patch").await?; + assert_eq!(fs::read_to_string(&target)?, "alpha\nend\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_cli_missing_second_chunk_context_rejected() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let target = harness.path("two_chunks.txt"); + fs::write(&target, "a\nb\nc\nd\n")?; + + // First chunk has @@, second chunk intentionally omits @@ to trigger parse error. + let patch = + "*** Begin Patch\n*** Update File: two_chunks.txt\n@@\n-b\n+B\n\n-d\n+D\n*** End Patch"; + let call_id = "apply-missing-ctx-2nd"; + mount_apply_patch(&harness, call_id, patch, "fail").await; + + harness.submit("apply missing context second chunk").await?; + + let out = harness.custom_tool_call_output(call_id).await; + assert!(out.contains("apply_patch verification failed")); + assert!( + out.contains("Failed to find expected lines in"), + "expected hunk context diagnostics: {out}" + ); + // Original file unchanged on failure + assert_eq!(fs::read_to_string(&target)?, "a\nb\nc\nd\n"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_emits_turn_diff_event_with_unified_diff() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + let test = harness.test(); + let codex = test.codex.clone(); + let cwd = test.cwd.clone(); + + let call_id = "apply-diff-event"; + let file = "udiff.txt"; + let patch = format!("*** Begin Patch\n*** Add File: {file}\n+hello\n*** End Patch\n"); + let first = sse(vec![ + ev_response_created("resp-1"), + ev_apply_patch_custom_tool_call(call_id, &patch), + ev_completed("resp-1"), + ]); + let second = sse(vec![ + ev_assistant_message("msg-1", "ok"), + ev_completed("resp-2"), + ]); + mount_sse_sequence(harness.server(), vec![first, second]).await; + + let model = test.session_configured.model.clone(); + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "emit diff".into(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model, + effort: None, + summary: ReasoningSummary::Auto, + }) + .await?; + + let mut saw_turn_diff = None; + wait_for_event(&codex, |event| match event { + EventMsg::TurnDiff(ev) => { + saw_turn_diff = Some(ev.unified_diff.clone()); + false + } + EventMsg::TaskComplete(_) => true, + _ => false, + }) + .await; + + let diff = saw_turn_diff.expect("expected TurnDiff event"); + // Basic markers of a unified diff with file addition + assert!(diff.contains("diff --git"), "diff header missing: {diff:?}"); + assert!(diff.contains("--- /dev/null") || diff.contains("--- a/")); + assert!(diff.contains("+++ b/")); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_turn_diff_for_rename_with_content_change() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + let test = harness.test(); + let codex = test.codex.clone(); + let cwd = test.cwd.clone(); + + // Seed original file + let old = cwd.path().join("old.txt"); + fs::write(&old, "old\n")?; + + // Patch: update + move + let call_id = "apply-rename-change"; + let patch = "*** Begin Patch\n*** Update File: old.txt\n*** Move to: new.txt\n@@\n-old\n+new\n*** End Patch"; + let first = sse(vec![ + ev_response_created("resp-1"), + ev_apply_patch_custom_tool_call(call_id, patch), + ev_completed("resp-1"), + ]); + let second = sse(vec![ + ev_assistant_message("msg-1", "ok"), + ev_completed("resp-2"), + ]); + mount_sse_sequence(harness.server(), vec![first, second]).await; + + let model = test.session_configured.model.clone(); + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "rename with change".into(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model, + effort: None, + summary: ReasoningSummary::Auto, + }) + .await?; + + let mut last_diff: Option = None; + wait_for_event(&codex, |event| match event { + EventMsg::TurnDiff(ev) => { + last_diff = Some(ev.unified_diff.clone()); + false + } + EventMsg::TaskComplete(_) => true, + _ => false, + }) + .await; + + let diff = last_diff.expect("expected TurnDiff event after rename"); + // Basic checks: shows old -> new, and the content delta + assert!(diff.contains("old.txt"), "diff missing old path: {diff:?}"); + assert!(diff.contains("new.txt"), "diff missing new path: {diff:?}"); + assert!(diff.contains("--- a/"), "missing old header"); + assert!(diff.contains("+++ b/"), "missing new header"); + assert!(diff.contains("-old\n"), "missing removal line"); + assert!(diff.contains("+new\n"), "missing addition line"); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_aggregates_diff_across_multiple_tool_calls() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + let test = harness.test(); + let codex = test.codex.clone(); + let cwd = test.cwd.clone(); + + let call1 = "agg-1"; + let call2 = "agg-2"; + let patch1 = "*** Begin Patch\n*** Add File: agg/a.txt\n+v1\n*** End Patch"; + let patch2 = "*** Begin Patch\n*** Update File: agg/a.txt\n@@\n-v1\n+v2\n*** Add File: agg/b.txt\n+B\n*** End Patch"; + + let s1 = sse(vec![ + ev_response_created("resp-1"), + ev_apply_patch_custom_tool_call(call1, patch1), + ev_completed("resp-1"), + ]); + let s2 = sse(vec![ + ev_response_created("resp-2"), + ev_apply_patch_custom_tool_call(call2, patch2), + ev_completed("resp-2"), + ]); + let s3 = sse(vec![ + ev_assistant_message("msg-1", "ok"), + ev_completed("resp-3"), + ]); + mount_sse_sequence(harness.server(), vec![s1, s2, s3]).await; + + let model = test.session_configured.model.clone(); + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "aggregate diffs".into(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model, + effort: None, + summary: ReasoningSummary::Auto, + }) + .await?; + + let mut last_diff: Option = None; + wait_for_event(&codex, |event| match event { + EventMsg::TurnDiff(ev) => { + last_diff = Some(ev.unified_diff.clone()); + false + } + EventMsg::TaskComplete(_) => true, + _ => false, + }) + .await; + + let diff = last_diff.expect("expected TurnDiff after two patches"); + assert!(diff.contains("agg/a.txt"), "diff missing a.txt"); + assert!(diff.contains("agg/b.txt"), "diff missing b.txt"); + // Final content reflects v2 for a.txt + assert!(diff.contains("+v2\n") || diff.contains("v2\n")); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_aggregates_diff_preserves_success_after_failure() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + let test = harness.test(); + let codex = test.codex.clone(); + let cwd = test.cwd.clone(); + + let call_success = "agg-success"; + let call_failure = "agg-failure"; + let patch_success = "*** Begin Patch\n*** Add File: partial/success.txt\n+ok\n*** End Patch"; + let patch_failure = + "*** Begin Patch\n*** Update File: partial/success.txt\n@@\n-missing\n+new\n*** End Patch"; + + let responses = vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_apply_patch_custom_tool_call(call_success, patch_success), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_apply_patch_custom_tool_call(call_failure, patch_failure), + ev_completed("resp-2"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "failed"), + ev_completed("resp-3"), + ]), + ]; + mount_sse_sequence(harness.server(), responses).await; + + let model = test.session_configured.model.clone(); + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "apply patch twice with failure".into(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model, + effort: None, + summary: ReasoningSummary::Auto, + }) + .await?; + + let mut last_diff: Option = None; + wait_for_event(&codex, |event| match event { + EventMsg::TurnDiff(ev) => { + last_diff = Some(ev.unified_diff.clone()); + false + } + EventMsg::TaskComplete(_) => true, + _ => false, + }) + .await; + + let diff = last_diff.expect("expected TurnDiff after failed patch"); + assert!( + diff.contains("partial/success.txt"), + "diff should still include the successful addition: {diff}" + ); + assert!( + diff.contains("+ok"), + "diff should include contents from successful patch: {diff}" + ); + + let failure_out = harness.custom_tool_call_output(call_failure).await; + assert!( + failure_out.contains("apply_patch verification failed"), + "expected verification failure output: {failure_out}" + ); + assert!( + failure_out.contains("Failed to find expected lines in"), + "expected missing context diagnostics: {failure_out}" + ); + + assert_eq!( + fs::read_to_string(cwd.path().join("partial/success.txt"))?, + "ok\n" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_change_context_disambiguates_target() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + + let target = harness.path("multi_ctx.txt"); + fs::write(&target, "fn a\nx=10\ny=2\nfn b\nx=10\ny=20\n")?; + + let patch = + "*** Begin Patch\n*** Update File: multi_ctx.txt\n@@ fn b\n-x=10\n+x=11\n*** End Patch"; + let call_id = "apply-ctx"; + mount_apply_patch(&harness, call_id, patch, "ok").await; + + harness.submit("apply with change_context").await?; + + let contents = fs::read_to_string(&target)?; + assert_eq!(contents, "fn a\nx=10\ny=2\nfn b\nx=11\ny=20\n"); + Ok(()) +} diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index 5eca79b5d9..915e8a6548 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -5,6 +5,8 @@ mod abort_tasks; #[cfg(not(target_os = "windows"))] mod apply_patch_cli; #[cfg(not(target_os = "windows"))] +mod apply_patch_freeform; +#[cfg(not(target_os = "windows"))] mod approvals; mod cli_stream; mod client; From 9572cfc78286ddab7df23d15e5f407fdd61dcd36 Mon Sep 17 00:00:00 2001 From: Anton Panasenko Date: Thu, 30 Oct 2025 11:18:31 -0700 Subject: [PATCH 5/6] [codex] add developer instructions (#5897) we are using developer instructions for code reviews, we need to pass them in cli as well. --- codex-rs/app-server-protocol/src/protocol.rs | 5 ++ .../app-server/src/codex_message_processor.rs | 2 + .../app-server/tests/suite/send_message.rs | 27 ++++++- codex-rs/core/src/codex.rs | 15 +++- codex-rs/core/src/config/mod.rs | 16 +++++ codex-rs/core/src/user_instructions.rs | 28 ++++++++ codex-rs/core/tests/suite/client.rs | 70 +++++++++++++++++++ codex-rs/exec/src/lib.rs | 1 + codex-rs/mcp-server/src/codex_tool_config.rs | 10 +++ codex-rs/mcp-server/tests/suite/codex_tool.rs | 21 +++++- codex-rs/tui/src/lib.rs | 1 + 11 files changed, 192 insertions(+), 4 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index 05c9d91fb2..45562657a7 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -321,6 +321,10 @@ pub struct NewConversationParams { #[serde(skip_serializing_if = "Option::is_none")] pub base_instructions: Option, + /// Developer instructions that will be sent as a `developer` role message. + #[serde(skip_serializing_if = "Option::is_none")] + pub developer_instructions: Option, + /// Prompt used during conversation compaction. #[serde(skip_serializing_if = "Option::is_none")] pub compact_prompt: Option, @@ -1129,6 +1133,7 @@ mod tests { sandbox: None, config: None, base_instructions: None, + developer_instructions: None, compact_prompt: None, include_apply_patch_tool: None, }, diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 14418fb048..193b47ea5a 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -1760,6 +1760,7 @@ async fn derive_config_from_params( sandbox: sandbox_mode, config: cli_overrides, base_instructions, + developer_instructions, compact_prompt, include_apply_patch_tool, } = params; @@ -1773,6 +1774,7 @@ async fn derive_config_from_params( model_provider, codex_linux_sandbox_exe, base_instructions, + developer_instructions, compact_prompt, include_apply_patch_tool, include_view_image_tool: None, diff --git a/codex-rs/app-server/tests/suite/send_message.rs b/codex-rs/app-server/tests/suite/send_message.rs index 32c408dce6..8793caafcc 100644 --- a/codex-rs/app-server/tests/suite/send_message.rs +++ b/codex-rs/app-server/tests/suite/send_message.rs @@ -44,7 +44,9 @@ async fn test_send_message_success() -> Result<()> { // Start a conversation using the new wire API. let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams::default()) + .send_new_conversation_request(NewConversationParams { + ..Default::default() + }) .await?; let new_conv_resp: JSONRPCResponse = timeout( DEFAULT_READ_TIMEOUT, @@ -143,7 +145,10 @@ async fn test_send_message_raw_notifications_opt_in() -> Result<()> { timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams::default()) + .send_new_conversation_request(NewConversationParams { + developer_instructions: Some("Use the test harness tools.".to_string()), + ..Default::default() + }) .await?; let new_conv_resp: JSONRPCResponse = timeout( DEFAULT_READ_TIMEOUT, @@ -177,6 +182,9 @@ async fn test_send_message_raw_notifications_opt_in() -> Result<()> { }) .await?; + let developer = read_raw_response_item(&mut mcp, conversation_id).await; + assert_developer_message(&developer, "Use the test harness tools."); + let instructions = read_raw_response_item(&mut mcp, conversation_id).await; assert_instructions_message(&instructions); @@ -316,6 +324,21 @@ fn assert_instructions_message(item: &ResponseItem) { } } +fn assert_developer_message(item: &ResponseItem, expected_text: &str) { + match item { + ResponseItem::Message { role, content, .. } => { + assert_eq!(role, "developer"); + let texts = content_texts(content); + assert_eq!( + texts, + vec![expected_text], + "expected developer instructions message, got {texts:?}" + ); + } + other => panic!("expected developer instructions message, got {other:?}"), + } +} + fn assert_environment_message(item: &ResponseItem) { match item { ResponseItem::Message { role, content, .. } => { diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index e7fde7b99a..f7a5d92bf5 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -112,6 +112,7 @@ use crate::tools::spec::ToolsConfig; use crate::tools::spec::ToolsConfigParams; use crate::turn_diff_tracker::TurnDiffTracker; use crate::unified_exec::UnifiedExecSessionManager; +use crate::user_instructions::DeveloperInstructions; use crate::user_instructions::UserInstructions; use crate::user_notification::UserNotification; use crate::util::backoff; @@ -171,6 +172,7 @@ impl Codex { model: config.model.clone(), model_reasoning_effort: config.model_reasoning_effort, model_reasoning_summary: config.model_reasoning_summary, + developer_instructions: config.developer_instructions.clone(), user_instructions, base_instructions: config.base_instructions.clone(), compact_prompt: config.compact_prompt.clone(), @@ -265,6 +267,7 @@ pub(crate) struct TurnContext { /// the model as well as sandbox policies are resolved against this path /// instead of `std::env::current_dir()`. pub(crate) cwd: PathBuf, + pub(crate) developer_instructions: Option, pub(crate) base_instructions: Option, pub(crate) compact_prompt: Option, pub(crate) user_instructions: Option, @@ -303,6 +306,9 @@ pub(crate) struct SessionConfiguration { model_reasoning_effort: Option, model_reasoning_summary: ReasoningSummaryConfig, + /// Developer instructions that supplement the base instructions. + developer_instructions: Option, + /// Model instructions that are appended to the base instructions. user_instructions: Option, @@ -417,6 +423,7 @@ impl Session { sub_id, client, cwd: session_configuration.cwd.clone(), + developer_instructions: session_configuration.developer_instructions.clone(), base_instructions: session_configuration.base_instructions.clone(), compact_prompt: session_configuration.compact_prompt.clone(), user_instructions: session_configuration.user_instructions.clone(), @@ -991,7 +998,10 @@ impl Session { } pub(crate) fn build_initial_context(&self, turn_context: &TurnContext) -> Vec { - let mut items = Vec::::with_capacity(2); + let mut items = Vec::::with_capacity(3); + if let Some(developer_instructions) = turn_context.developer_instructions.as_deref() { + items.push(DeveloperInstructions::new(developer_instructions.to_string()).into()); + } if let Some(user_instructions) = turn_context.user_instructions.as_deref() { items.push(UserInstructions::new(user_instructions.to_string()).into()); } @@ -1674,6 +1684,7 @@ async fn spawn_review_thread( sub_id: sub_id.to_string(), client, tools_config, + developer_instructions: None, user_instructions: None, base_instructions: Some(base_instructions.clone()), compact_prompt: parent_turn_context.compact_prompt.clone(), @@ -2511,6 +2522,7 @@ mod tests { model: config.model.clone(), model_reasoning_effort: config.model_reasoning_effort, model_reasoning_summary: config.model_reasoning_summary, + developer_instructions: config.developer_instructions.clone(), user_instructions: config.user_instructions.clone(), base_instructions: config.base_instructions.clone(), compact_prompt: config.compact_prompt.clone(), @@ -2586,6 +2598,7 @@ mod tests { model: config.model.clone(), model_reasoning_effort: config.model_reasoning_effort, model_reasoning_summary: config.model_reasoning_summary, + developer_instructions: config.developer_instructions.clone(), user_instructions: config.user_instructions.clone(), base_instructions: config.base_instructions.clone(), compact_prompt: config.compact_prompt.clone(), diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index b6bc9baf57..17fddcf3d3 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -128,6 +128,9 @@ pub struct Config { /// Base instructions override. pub base_instructions: Option, + /// Developer instructions override injected as a separate message. + pub developer_instructions: Option, + /// Compact prompt override. pub compact_prompt: Option, @@ -543,6 +546,11 @@ pub struct ConfigToml { /// System instructions. pub instructions: Option, + + /// Developer instructions inserted as a `developer` role message. + #[serde(default)] + pub developer_instructions: Option, + /// Compact prompt used for history compaction. pub compact_prompt: Option, @@ -830,6 +838,7 @@ pub struct ConfigOverrides { pub config_profile: Option, pub codex_linux_sandbox_exe: Option, pub base_instructions: Option, + pub developer_instructions: Option, pub compact_prompt: Option, pub include_apply_patch_tool: Option, pub include_view_image_tool: Option, @@ -861,6 +870,7 @@ impl Config { config_profile: config_profile_key, codex_linux_sandbox_exe, base_instructions, + developer_instructions, compact_prompt, include_apply_patch_tool: include_apply_patch_tool_override, include_view_image_tool: include_view_image_tool_override, @@ -1060,6 +1070,7 @@ impl Config { "experimental instructions file", )?; let base_instructions = base_instructions.or(file_base_instructions); + let developer_instructions = developer_instructions.or(cfg.developer_instructions); let experimental_compact_prompt_path = config_profile .experimental_compact_prompt_file @@ -1095,6 +1106,7 @@ impl Config { notify: cfg.notify, user_instructions, base_instructions, + developer_instructions, compact_prompt, // The config.toml omits "_mode" because it's a config file. However, "_mode" // is important in code to differentiate the mode from the store implementation. @@ -2886,6 +2898,7 @@ model_verbosity = "high" model_verbosity: None, chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), base_instructions: None, + developer_instructions: None, compact_prompt: None, forced_chatgpt_workspace_id: None, forced_login_method: None, @@ -2958,6 +2971,7 @@ model_verbosity = "high" model_verbosity: None, chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), base_instructions: None, + developer_instructions: None, compact_prompt: None, forced_chatgpt_workspace_id: None, forced_login_method: None, @@ -3045,6 +3059,7 @@ model_verbosity = "high" model_verbosity: None, chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), base_instructions: None, + developer_instructions: None, compact_prompt: None, forced_chatgpt_workspace_id: None, forced_login_method: None, @@ -3118,6 +3133,7 @@ model_verbosity = "high" model_verbosity: Some(Verbosity::High), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), base_instructions: None, + developer_instructions: None, compact_prompt: None, forced_chatgpt_workspace_id: None, forced_login_method: None, diff --git a/codex-rs/core/src/user_instructions.rs b/codex-rs/core/src/user_instructions.rs index 76054edcb3..f479846168 100644 --- a/codex-rs/core/src/user_instructions.rs +++ b/codex-rs/core/src/user_instructions.rs @@ -40,3 +40,31 @@ impl From for ResponseItem { } } } + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename = "developer_instructions", rename_all = "snake_case")] +pub(crate) struct DeveloperInstructions { + text: String, +} + +impl DeveloperInstructions { + pub fn new>(text: T) -> Self { + Self { text: text.into() } + } + + pub fn into_text(self) -> String { + self.text + } +} + +impl From for ResponseItem { + fn from(di: DeveloperInstructions) -> Self { + ResponseItem::Message { + id: None, + role: "developer".to_string(), + content: vec![ContentItem::InputText { + text: di.into_text(), + }], + } + } +} diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index c1354a6257..07bee704f4 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -58,6 +58,18 @@ fn assert_message_role(request_body: &serde_json::Value, role: &str) { assert_eq!(request_body["role"].as_str().unwrap(), role); } +#[expect(clippy::expect_used)] +fn assert_message_equals(request_body: &serde_json::Value, text: &str) { + let content = request_body["content"][0]["text"] + .as_str() + .expect("invalid message content"); + + assert_eq!( + content, text, + "expected message content '{content}' to equal '{text}'" + ); +} + #[expect(clippy::expect_used)] fn assert_message_starts_with(request_body: &serde_json::Value, text: &str) { let content = request_body["content"][0]["text"] @@ -608,6 +620,64 @@ async fn includes_user_instructions_message_in_request() { assert_message_ends_with(&request_body["input"][1], ""); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn includes_developer_instructions_message_in_request() { + skip_if_no_network!(); + let server = MockServer::start().await; + + let resp_mock = + responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) + .await; + + let model_provider = ModelProviderInfo { + base_url: Some(format!("{}/v1", server.uri())), + ..built_in_model_providers()["openai"].clone() + }; + + let codex_home = TempDir::new().unwrap(); + let mut config = load_default_config_for_test(&codex_home); + config.model_provider = model_provider; + config.user_instructions = Some("be nice".to_string()); + config.developer_instructions = Some("be useful".to_string()); + + let conversation_manager = + ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); + let codex = conversation_manager + .new_conversation(config) + .await + .expect("create new conversation") + .conversation; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "hello".into(), + }], + }) + .await + .unwrap(); + + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; + + let request = resp_mock.single_request(); + let request_body = request.body_json(); + + assert!( + !request_body["instructions"] + .as_str() + .unwrap() + .contains("be nice") + ); + assert_message_role(&request_body["input"][0], "developer"); + assert_message_equals(&request_body["input"][0], "be useful"); + assert_message_role(&request_body["input"][1], "user"); + assert_message_starts_with(&request_body["input"][1], ""); + assert_message_ends_with(&request_body["input"][1], ""); + assert_message_role(&request_body["input"][2], "user"); + assert_message_starts_with(&request_body["input"][2], ""); + assert_message_ends_with(&request_body["input"][2], ""); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn azure_responses_request_includes_store_and_reasoning_ids() { skip_if_no_network!(); diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 4ab0b0302b..a086990dff 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -174,6 +174,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any model_provider, codex_linux_sandbox_exe, base_instructions: None, + developer_instructions: None, compact_prompt: None, include_apply_patch_tool: None, include_view_image_tool: None, diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index 471d65603a..fd671ea12c 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -50,6 +50,10 @@ pub struct CodexToolCallParam { #[serde(default, skip_serializing_if = "Option::is_none")] pub base_instructions: Option, + /// Developer instructions that should be injected as a developer role message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub developer_instructions: Option, + /// Prompt used when compacting the conversation. #[serde(default, skip_serializing_if = "Option::is_none")] pub compact_prompt: Option, @@ -145,6 +149,7 @@ impl CodexToolCallParam { sandbox, config: cli_overrides, base_instructions, + developer_instructions, compact_prompt, } = self; @@ -159,6 +164,7 @@ impl CodexToolCallParam { model_provider: None, codex_linux_sandbox_exe, base_instructions, + developer_instructions, compact_prompt, include_apply_patch_tool: None, include_view_image_tool: None, @@ -294,6 +300,10 @@ mod tests { "description": "The set of instructions to use instead of the default ones.", "type": "string" }, + "developer-instructions": { + "description": "Developer instructions that should be injected as a developer role message.", + "type": "string" + }, "compact-prompt": { "description": "Prompt used when compacting the conversation.", "type": "string" diff --git a/codex-rs/mcp-server/tests/suite/codex_tool.rs b/codex-rs/mcp-server/tests/suite/codex_tool.rs index 4ab83ca24e..ae0c23f1d8 100644 --- a/codex-rs/mcp-server/tests/suite/codex_tool.rs +++ b/codex-rs/mcp-server/tests/suite/codex_tool.rs @@ -341,6 +341,7 @@ async fn codex_tool_passes_base_instructions() -> anyhow::Result<()> { .send_codex_tool_call(CodexToolCallParam { prompt: "How are you?".to_string(), base_instructions: Some("You are a helpful assistant.".to_string()), + developer_instructions: Some("Foreshadow upcoming tool calls.".to_string()), ..Default::default() }) .await?; @@ -367,10 +368,28 @@ async fn codex_tool_passes_base_instructions() -> anyhow::Result<()> { ); let requests = server.received_requests().await.unwrap(); - let request = requests[0].body_json::().unwrap(); + let request = requests[0].body_json::()?; let instructions = request["messages"][0]["content"].as_str().unwrap(); assert!(instructions.starts_with("You are a helpful assistant.")); + let developer_msg = request["messages"] + .as_array() + .and_then(|messages| { + messages + .iter() + .find(|msg| msg.get("role").and_then(|role| role.as_str()) == Some("developer")) + }) + .unwrap(); + let developer_content = developer_msg + .get("content") + .and_then(|value| value.as_str()) + .unwrap(); + assert!( + !developer_content.contains('<'), + "expected developer instructions without XML tags, got `{developer_content}`" + ); + assert_eq!(developer_content, "Foreshadow upcoming tool calls."); + Ok(()) } diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 0629dd8c07..487b687a57 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -144,6 +144,7 @@ pub async fn run_main( config_profile: cli.config_profile.clone(), codex_linux_sandbox_exe, base_instructions: None, + developer_instructions: None, compact_prompt: None, include_apply_patch_tool: None, include_view_image_tool: None, From 89c00611c2011bbc0d0ac6c64f8397b8ed2183db Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Thu, 30 Oct 2025 11:18:53 -0700 Subject: [PATCH 6/6] [app-server] remove serde(skip_serializing_if = "Option::is_none") annotations (#5939) We had this annotation everywhere in app-server APIs which made it so that fields get serialized as `field?: T`, meaning if the field as `None` we would omit the field in the payload. Removing this annotation changes it so that we return `field: T | null` instead, which makes codex app-server's API more aligned with the convention of public OpenAI APIs like Responses. Separately, remove the `#[ts(optional_fields = nullable)]` annotations that were recently added which made all the TS types become `field?: T | null` which is not great since clients need to handle undefined and null. I think generally it'll be best to have optional types be either: - `field: T | null` (preferred, aligned with public OpenAI APIs) - `field?: T` where we have to, such as types generated from the MCP schema: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-06-18/schema.ts (see changes to `mcp-types/`) I updated @etraut-openai's unit test to check that all generated TS types are one or the other, not both (so will error if we have a type that has `field?: T | null`). I don't think there's currently a good use case for that - but we can always revisit. --- codex-rs/app-server-protocol/src/export.rs | 134 ++++++++++++------ .../app-server-protocol/src/jsonrpc_lite.rs | 6 +- codex-rs/app-server-protocol/src/protocol.rs | 109 ++------------ codex-rs/app-server/src/outgoing_message.rs | 1 + codex-rs/mcp-types/generate_mcp_types.py | 24 +++- codex-rs/mcp-types/src/lib.rs | 122 ++++++++++++++++ codex-rs/protocol/src/approvals.rs | 2 - codex-rs/protocol/src/custom_prompts.rs | 1 - codex-rs/protocol/src/models.rs | 32 ++--- codex-rs/protocol/src/parse_command.rs | 3 - codex-rs/protocol/src/plan_tool.rs | 1 - codex-rs/protocol/src/protocol.rs | 22 --- codex-rs/utils/git/src/lib.rs | 1 - 13 files changed, 265 insertions(+), 193 deletions(-) diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index 2fff3a4277..c8facffdb5 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -545,7 +545,7 @@ mod tests { use uuid::Uuid; #[test] - fn generated_ts_omits_undefined_unions_for_optionals() -> Result<()> { + fn generated_ts_has_no_optional_nullable_fields() -> Result<()> { let output_dir = std::env::temp_dir().join(format!("codex_ts_types_{}", Uuid::now_v7())); fs::create_dir(&output_dir)?; @@ -562,7 +562,7 @@ mod tests { generate_ts(&output_dir, None)?; let mut undefined_offenders = Vec::new(); - let mut missing_optional_marker = BTreeSet::new(); + let mut optional_nullable_offenders = BTreeSet::new(); let mut stack = vec![output_dir]; while let Some(dir) = stack.pop() { for entry in fs::read_dir(&dir)? { @@ -591,27 +591,80 @@ mod tests { let mut search_start = 0; while let Some(idx) = contents[search_start..].find("| null") { let abs_idx = search_start + idx; - let Some(colon_idx) = contents[..abs_idx].rfind(':') else { + // Find the property-colon for this field by scanning forward + // from the start of the segment and ignoring nested braces, + // brackets, and parens. This avoids colons inside nested + // type literals like `{ [k in string]?: string }`. + + let line_start_idx = + contents[..abs_idx].rfind('\n').map(|i| i + 1).unwrap_or(0); + + let mut segment_start_idx = line_start_idx; + if let Some(rel_idx) = contents[line_start_idx..abs_idx].rfind(',') { + segment_start_idx = segment_start_idx.max(line_start_idx + rel_idx + 1); + } + if let Some(rel_idx) = contents[line_start_idx..abs_idx].rfind('{') { + segment_start_idx = segment_start_idx.max(line_start_idx + rel_idx + 1); + } + if let Some(rel_idx) = contents[line_start_idx..abs_idx].rfind('}') { + segment_start_idx = segment_start_idx.max(line_start_idx + rel_idx + 1); + } + + // Scan forward for the colon that separates the field name from its type. + let mut level_brace = 0_i32; + let mut level_brack = 0_i32; + let mut level_paren = 0_i32; + let mut in_single = false; + let mut in_double = false; + let mut escape = false; + let mut prop_colon_idx = None; + for (i, ch) in contents[segment_start_idx..abs_idx].char_indices() { + let idx_abs = segment_start_idx + i; + if escape { + escape = false; + continue; + } + match ch { + '\\' => { + // Only treat as escape when inside a string. + if in_single || in_double { + escape = true; + } + } + '\'' => { + if !in_double { + in_single = !in_single; + } + } + '"' => { + if !in_single { + in_double = !in_double; + } + } + '{' if !in_single && !in_double => level_brace += 1, + '}' if !in_single && !in_double => level_brace -= 1, + '[' if !in_single && !in_double => level_brack += 1, + ']' if !in_single && !in_double => level_brack -= 1, + '(' if !in_single && !in_double => level_paren += 1, + ')' if !in_single && !in_double => level_paren -= 1, + ':' if !in_single + && !in_double + && level_brace == 0 + && level_brack == 0 + && level_paren == 0 => + { + prop_colon_idx = Some(idx_abs); + break; + } + _ => {} + } + } + + let Some(colon_idx) = prop_colon_idx else { search_start = abs_idx + 5; continue; }; - let line_start_idx = contents[..colon_idx] - .rfind('\n') - .map(|i| i + 1) - .unwrap_or(0); - - let mut segment_start_idx = line_start_idx; - if let Some(rel_idx) = contents[line_start_idx..colon_idx].rfind(',') { - segment_start_idx = segment_start_idx.max(line_start_idx + rel_idx + 1); - } - if let Some(rel_idx) = contents[line_start_idx..colon_idx].rfind('{') { - segment_start_idx = segment_start_idx.max(line_start_idx + rel_idx + 1); - } - if let Some(rel_idx) = contents[line_start_idx..colon_idx].rfind('}') { - segment_start_idx = segment_start_idx.max(line_start_idx + rel_idx + 1); - } - let mut field_prefix = contents[segment_start_idx..colon_idx].trim(); if field_prefix.is_empty() { search_start = abs_idx + 5; @@ -640,25 +693,26 @@ mod tests { continue; } + // If the last non-whitespace before ':' is '?', then this is an + // optional field with a nullable type (i.e., "?: T | null"), + // which we explicitly disallow. if field_prefix.chars().rev().find(|c| !c.is_whitespace()) == Some('?') { - search_start = abs_idx + 5; - continue; + let line_number = + contents[..abs_idx].chars().filter(|c| *c == '\n').count() + 1; + let offending_line_end = contents[line_start_idx..] + .find('\n') + .map(|i| line_start_idx + i) + .unwrap_or(contents.len()); + let offending_snippet = + contents[line_start_idx..offending_line_end].trim(); + + optional_nullable_offenders.insert(format!( + "{}:{}: {offending_snippet}", + path.display(), + line_number + )); } - let line_number = - contents[..abs_idx].chars().filter(|c| *c == '\n').count() + 1; - let offending_line_end = contents[line_start_idx..] - .find('\n') - .map(|i| line_start_idx + i) - .unwrap_or(contents.len()); - let offending_snippet = contents[line_start_idx..offending_line_end].trim(); - - missing_optional_marker.insert(format!( - "{}:{}: {offending_snippet}", - path.display(), - line_number - )); - search_start = abs_idx + 5; } } @@ -670,12 +724,12 @@ mod tests { "Generated TypeScript still includes unions with `undefined` in {undefined_offenders:?}" ); - // If this test fails, it means that a struct field that is `Option` in Rust - // is being generated as `T | null` in TypeScript, without the optional marker - // (`?`). To fix this, add #[ts(optional_fields = nullable)] to the struct definition. + // If this assertion fails, it means a field was generated as + // "?: T | null" — i.e., both optional (undefined) and nullable (null). + // We only want either "?: T" or ": T | null". assert!( - missing_optional_marker.is_empty(), - "Generated TypeScript has nullable fields without an optional marker: {missing_optional_marker:?}" + optional_nullable_offenders.is_empty(), + "Generated TypeScript has optional fields with nullable types (disallowed '?: T | null'), add #[ts(optional)] to fix:\n{optional_nullable_offenders:?}" ); Ok(()) diff --git a/codex-rs/app-server-protocol/src/jsonrpc_lite.rs b/codex-rs/app-server-protocol/src/jsonrpc_lite.rs index 88554176d9..65ffa2a005 100644 --- a/codex-rs/app-server-protocol/src/jsonrpc_lite.rs +++ b/codex-rs/app-server-protocol/src/jsonrpc_lite.rs @@ -30,20 +30,20 @@ pub enum JSONRPCMessage { /// A request that expects a response. #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct JSONRPCRequest { pub id: RequestId, pub method: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub params: Option, } /// A notification which does not expect a response. #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct JSONRPCNotification { pub method: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub params: Option, } @@ -62,10 +62,10 @@ pub struct JSONRPCError { } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct JSONRPCErrorError { pub code: i64, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub data: Option, pub message: String, } diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index 45562657a7..163edcfc18 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -248,7 +248,6 @@ pub enum Account { #[serde(rename = "chatgpt", rename_all = "camelCase")] #[ts(rename = "chatgpt", rename_all = "camelCase")] ChatGpt { - #[ts(optional = nullable)] email: Option, plan_type: PlanType, }, @@ -267,11 +266,9 @@ pub struct InitializeParams { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ClientInfo { pub name: String, - #[serde(skip_serializing_if = "Option::is_none")] pub title: Option, pub version: String, } @@ -283,42 +280,33 @@ pub struct InitializeResponse { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct NewConversationParams { /// Optional override for the model name (e.g. "o3", "o4-mini"). - #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, /// Override the model provider to use for this session. - #[serde(skip_serializing_if = "Option::is_none")] pub model_provider: Option, /// Configuration profile from config.toml to specify default options. - #[serde(skip_serializing_if = "Option::is_none")] pub profile: Option, /// Working directory for the session. If relative, it is resolved against /// the server process's current working directory. - #[serde(skip_serializing_if = "Option::is_none")] pub cwd: Option, /// Approval policy for shell commands generated by the model: /// `untrusted`, `on-failure`, `on-request`, `never`. - #[serde(skip_serializing_if = "Option::is_none")] pub approval_policy: Option, /// Sandbox mode: `read-only`, `workspace-write`, or `danger-full-access`. - #[serde(skip_serializing_if = "Option::is_none")] pub sandbox: Option, /// Individual config settings that will override what is in /// CODEX_HOME/config.toml. - #[serde(skip_serializing_if = "Option::is_none")] pub config: Option>, /// The set of instructions to use instead of the default ones. - #[serde(skip_serializing_if = "Option::is_none")] pub base_instructions: Option, /// Developer instructions that will be sent as a `developer` role message. @@ -330,29 +318,24 @@ pub struct NewConversationParams { pub compact_prompt: Option, /// Whether to include the apply patch tool in the conversation. - #[serde(skip_serializing_if = "Option::is_none")] pub include_apply_patch_tool: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct NewConversationResponse { pub conversation_id: ConversationId, pub model: String, /// Note this could be ignored by the model. - #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_effort: Option, pub rollout_path: PathBuf, } #[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ResumeConversationResponse { pub conversation_id: ConversationId, pub model: String, - #[serde(skip_serializing_if = "Option::is_none")] pub initial_messages: Option>, pub rollout_path: PathBuf, } @@ -381,57 +364,46 @@ pub struct GetConversationSummaryResponse { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ListConversationsParams { /// Optional page size; defaults to a reasonable server-side value. - #[serde(skip_serializing_if = "Option::is_none")] pub page_size: Option, /// Opaque pagination cursor returned by a previous call. - #[serde(skip_serializing_if = "Option::is_none")] pub cursor: Option, /// Optional model provider filter (matches against session metadata). /// - None => filter by the server's default model provider /// - Some([]) => no filtering, include all providers /// - Some([...]) => only include sessions with one of the specified providers - #[serde(skip_serializing_if = "Option::is_none")] pub model_providers: Option>, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ConversationSummary { pub conversation_id: ConversationId, pub path: PathBuf, pub preview: String, /// RFC3339 timestamp string for the session start, if available. - #[serde(skip_serializing_if = "Option::is_none")] pub timestamp: Option, /// Model provider recorded for the session (resolved when absent in metadata). pub model_provider: String, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ListConversationsResponse { pub items: Vec, /// Opaque cursor to pass to the next call to continue after the last item. /// if None, there are no more items to return. - #[serde(skip_serializing_if = "Option::is_none")] pub next_cursor: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ListModelsParams { /// Optional page size; defaults to a reasonable server-side value. - #[serde(skip_serializing_if = "Option::is_none")] pub page_size: Option, /// Opaque pagination cursor returned by a previous call. - #[serde(skip_serializing_if = "Option::is_none")] pub cursor: Option, } @@ -456,24 +428,19 @@ pub struct ReasoningEffortOption { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ListModelsResponse { pub items: Vec, /// Opaque cursor to pass to the next call to continue after the last item. /// if None, there are no more items to return. - #[serde(skip_serializing_if = "Option::is_none")] pub next_cursor: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct UploadFeedbackParams { pub classification: String, - #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub conversation_id: Option, pub include_logs: bool, } @@ -501,7 +468,6 @@ pub enum LoginAccountParams { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct LoginAccountResponse { /// Only set if the login method is ChatGPT. @@ -518,20 +484,15 @@ pub struct LoginAccountResponse { pub struct LogoutAccountResponse {} #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ResumeConversationParams { /// Absolute path to the rollout JSONL file, when explicitly resuming a known rollout. - #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, /// If the rollout path is not known, it can be discovered via the conversation id at the cost of extra latency. - #[serde(skip_serializing_if = "Option::is_none")] pub conversation_id: Option, /// if the rollout path or conversation id is not known, it can be resumed from given history - #[serde(skip_serializing_if = "Option::is_none")] pub history: Option>, /// Optional overrides to apply when spawning the resumed session. - #[serde(skip_serializing_if = "Option::is_none")] pub overrides: Option, } @@ -610,19 +571,15 @@ pub struct LogoutChatGptParams {} pub struct LogoutChatGptResponse {} #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct GetAuthStatusParams { /// If true, include the current auth token (if available) in the response. - #[serde(skip_serializing_if = "Option::is_none")] pub include_token: Option, /// If true, attempt to refresh the token before returning status. - #[serde(skip_serializing_if = "Option::is_none")] pub refresh_token: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ExecOneOffCommandParams { /// Command argv to execute. @@ -631,10 +588,8 @@ pub struct ExecOneOffCommandParams { /// If not specified, a sensible default is used server-side. pub timeout_ms: Option, /// Optional working directory for the process. Defaults to server config cwd. - #[serde(skip_serializing_if = "Option::is_none")] pub cwd: Option, /// Optional explicit sandbox policy overriding the server default. - #[serde(skip_serializing_if = "Option::is_none")] pub sandbox_policy: Option, } @@ -654,17 +609,13 @@ pub struct GetAccountRateLimitsResponse { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] -#[ts(optional_fields = nullable)] pub struct GetAuthStatusResponse { - #[serde(skip_serializing_if = "Option::is_none")] pub auth_method: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub auth_token: Option, // Indicates that auth method must be valid to use the server. // This can be false if using a custom provider that is configured // with requires_openai_auth == false. - #[serde(skip_serializing_if = "Option::is_none")] pub requires_openai_auth: Option, } @@ -675,7 +626,6 @@ pub struct GetUserAgentResponse { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct UserInfoResponse { /// Note: `alleged_user_email` is not currently verified. We read it from @@ -692,15 +642,12 @@ pub struct GetUserSavedConfigResponse { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct SetDefaultModelParams { /// If set to None, this means `model` should be cleared in config.toml. - #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, /// If set to None, this means `model_reasoning_effort` should be cleared /// in config.toml. - #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_effort: Option, } @@ -712,46 +659,32 @@ pub struct SetDefaultModelResponse {} /// client-configurable settings that can be specified in the NewConversation /// and SendUserTurn requests. #[derive(Deserialize, Debug, Clone, PartialEq, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct UserSavedConfig { /// Approvals - #[serde(skip_serializing_if = "Option::is_none")] pub approval_policy: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub sandbox_mode: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub sandbox_settings: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub forced_chatgpt_workspace_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub forced_login_method: Option, /// Model-specific configuration - #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub model_reasoning_effort: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub model_reasoning_summary: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub model_verbosity: Option, /// Tools - #[serde(skip_serializing_if = "Option::is_none")] pub tools: Option, /// Profiles - #[serde(skip_serializing_if = "Option::is_none")] pub profile: Option, - #[serde(default)] pub profiles: HashMap, } /// MCP representation of a [`codex_core::config_profile::ConfigProfile`]. #[derive(Deserialize, Debug, Clone, PartialEq, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct Profile { pub model: Option, @@ -764,29 +697,23 @@ pub struct Profile { pub model_verbosity: Option, pub chatgpt_base_url: Option, } + /// MCP representation of a [`codex_core::config::ToolsToml`]. #[derive(Deserialize, Debug, Clone, PartialEq, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct Tools { - #[serde(skip_serializing_if = "Option::is_none")] pub web_search: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub view_image: Option, } /// MCP representation of a [`codex_core::config::types::SandboxWorkspaceWrite`]. #[derive(Deserialize, Debug, Clone, PartialEq, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct SandboxSettings { #[serde(default)] pub writable_roots: Vec, - #[serde(skip_serializing_if = "Option::is_none")] pub network_access: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub exclude_tmpdir_env_var: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub exclude_slash_tmp: Option, } @@ -798,7 +725,6 @@ pub struct SendUserMessageParams { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct SendUserTurnParams { pub conversation_id: ConversationId, @@ -807,7 +733,6 @@ pub struct SendUserTurnParams { pub approval_policy: AskForApproval, pub sandbox_policy: SandboxPolicy, pub model: String, - #[serde(skip_serializing_if = "Option::is_none")] pub effort: Option, pub summary: ReasoningSummary, } @@ -942,7 +867,6 @@ server_request_definitions! { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ApplyPatchApprovalParams { pub conversation_id: ConversationId, @@ -951,16 +875,13 @@ pub struct ApplyPatchApprovalParams { pub call_id: String, pub file_changes: HashMap, /// Optional explanatory reason (e.g. request for extra write access). - #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option, /// When set, the agent is asking the user to allow writes under this root /// for the remainder of the session (unclear if this is honored today). - #[serde(skip_serializing_if = "Option::is_none")] pub grant_root: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct ExecCommandApprovalParams { pub conversation_id: ConversationId, @@ -969,9 +890,7 @@ pub struct ExecCommandApprovalParams { pub call_id: String, pub command: Vec, pub cwd: PathBuf, - #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub risk: Option, pub parsed_cmd: Vec, } @@ -987,26 +906,22 @@ pub struct ApplyPatchApprovalResponse { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] #[ts(rename_all = "camelCase")] pub struct FuzzyFileSearchParams { pub query: String, pub roots: Vec, // if provided, will cancel any previous request that used the same value - #[serde(skip_serializing_if = "Option::is_none")] pub cancellation_token: Option, } /// Superset of [`codex_file_search::FileMatch`] #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct FuzzyFileSearchResult { pub root: String, pub path: String, pub file_name: String, pub score: u32, - #[serde(skip_serializing_if = "Option::is_none")] pub indices: Option>, } @@ -1016,18 +931,15 @@ pub struct FuzzyFileSearchResponse { } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct LoginChatGptCompleteNotification { #[schemars(with = "String")] pub login_id: Uuid, pub success: bool, - #[serde(skip_serializing_if = "Option::is_none")] pub error: Option, } #[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct SessionConfiguredNotification { /// Name left as session_id instead of conversation_id for backwards compatibility. @@ -1037,7 +949,6 @@ pub struct SessionConfiguredNotification { pub model: String, /// The effort the model is putting into reasoning about the user's request. - #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_effort: Option, /// Identifier of the history log file (inode on Unix, 0 otherwise). @@ -1049,18 +960,15 @@ pub struct SessionConfiguredNotification { /// Optional initial messages (as events) for resumed sessions. /// When present, UIs can use these to seed the history. - #[serde(skip_serializing_if = "Option::is_none")] pub initial_messages: Option>, pub rollout_path: PathBuf, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] #[serde(rename_all = "camelCase")] pub struct AuthStatusChangeNotification { /// Current authentication method; omitted if signed out. - #[serde(skip_serializing_if = "Option::is_none")] pub auth_method: Option, } @@ -1144,7 +1052,14 @@ mod tests { "id": 42, "params": { "model": "gpt-5-codex", - "approvalPolicy": "on-request" + "modelProvider": null, + "profile": null, + "cwd": null, + "approvalPolicy": "on-request", + "sandbox": null, + "config": null, + "baseInstructions": null, + "includeApplyPatchTool": null } }), serde_json::to_value(&request)?, @@ -1217,6 +1132,7 @@ mod tests { "command": ["echo", "hello"], "cwd": "/tmp", "reason": "because tests", + "risk": null, "parsedCmd": [ { "type": "unknown", @@ -1361,7 +1277,10 @@ mod tests { json!({ "method": "model/list", "id": 6, - "params": {} + "params": { + "pageSize": null, + "cursor": null + } }), serde_json::to_value(&request)?, ); diff --git a/codex-rs/app-server/src/outgoing_message.rs b/codex-rs/app-server/src/outgoing_message.rs index feaa19e37a..3f4497fb23 100644 --- a/codex-rs/app-server/src/outgoing_message.rs +++ b/codex-rs/app-server/src/outgoing_message.rs @@ -166,6 +166,7 @@ mod tests { "params": { "loginId": Uuid::nil(), "success": true, + "error": null, }, }), serde_json::to_value(jsonrpc_notification) diff --git a/codex-rs/mcp-types/generate_mcp_types.py b/codex-rs/mcp-types/generate_mcp_types.py index 1906033537..7535b4c760 100755 --- a/codex-rs/mcp-types/generate_mcp_types.py +++ b/codex-rs/mcp-types/generate_mcp_types.py @@ -332,6 +332,7 @@ class StructField: name: str type_name: str serde: str | None = None + ts: str | None = None comment: str | None = None def append(self, out: list[str], supports_const: bool) -> None: @@ -339,6 +340,8 @@ class StructField: out.append(f" // {self.comment}\n") if self.serde: out.append(f" {self.serde}\n") + if self.ts: + out.append(f" {self.ts}\n") if self.viz == "const": if supports_const: out.append(f" const {self.name}: {self.type_name};\n") @@ -378,9 +381,9 @@ def define_struct( prop_type = f"Option<{prop_type}>" rs_prop = rust_prop_name(prop_name, is_optional) if prop_type.startswith("&'static str"): - fields.append(StructField("const", rs_prop.name, prop_type, rs_prop.serde)) + fields.append(StructField("const", rs_prop.name, prop_type, rs_prop.serde, rs_prop.ts)) else: - fields.append(StructField("pub", rs_prop.name, prop_type, rs_prop.serde)) + fields.append(StructField("pub", rs_prop.name, prop_type, rs_prop.serde, rs_prop.ts)) # Special-case: add Codex-specific user_agent to Implementation if name == "Implementation": @@ -390,6 +393,7 @@ def define_struct( "user_agent", "Option", '#[serde(default, skip_serializing_if = "Option::is_none")]', + '#[ts(optional)]', "This is an extra field that the Codex MCP server sends as part of InitializeResult.", ) ) @@ -474,7 +478,6 @@ def define_string_enum( out.append(f" {capitalize(value)},\n") out.append("}\n\n") - return out def define_untagged_enum(name: str, type_list: list[str], out: list[str]) -> None: @@ -590,7 +593,7 @@ def get_serde_annotation_for_anyof_type(type_name: str) -> str | None: def map_type( - typedef: dict[str, any], + typedef: dict[str, Any], prop_name: str | None = None, struct_name: str | None = None, ) -> str: @@ -665,7 +668,8 @@ class RustProp: name: str # serde annotation, if necessary serde: str | None = None - + # ts annotation, if necessary + ts: str | None = None def rust_prop_name(name: str, is_optional: bool) -> RustProp: """Convert a JSON property name to a Rust property name.""" @@ -684,6 +688,7 @@ def rust_prop_name(name: str, is_optional: bool) -> RustProp: prop_name = name serde_annotations = [] + ts_str = None if is_rename: serde_annotations.append(f'rename = "{name}"') if is_optional: @@ -691,13 +696,18 @@ def rust_prop_name(name: str, is_optional: bool) -> RustProp: serde_annotations.append('skip_serializing_if = "Option::is_none"') if serde_annotations: + # Also mark optional fields for ts-rs generation. serde_str = f"#[serde({', '.join(serde_annotations)})]" else: serde_str = None - return RustProp(prop_name, serde_str) + + if is_optional and serde_str: + ts_str = "#[ts(optional)]" + + return RustProp(prop_name, serde_str, ts_str) -def to_snake_case(name: str) -> str: +def to_snake_case(name: str) -> str | None: """Convert a camelCase or PascalCase name to snake_case.""" snake_case = name[0].lower() + "".join("_" + c.lower() if c.isupper() else c for c in name[1:]) if snake_case != name: diff --git a/codex-rs/mcp-types/src/lib.rs b/codex-rs/mcp-types/src/lib.rs index 98dab7252b..e390322fc8 100644 --- a/codex-rs/mcp-types/src/lib.rs +++ b/codex-rs/mcp-types/src/lib.rs @@ -37,14 +37,17 @@ fn default_jsonrpc() -> String { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct Annotations { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub audience: Option>, #[serde( rename = "lastModified", default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub last_modified: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub priority: Option, } @@ -52,6 +55,7 @@ pub struct Annotations { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct AudioContent { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub annotations: Option, pub data: String, #[serde(rename = "mimeType")] @@ -64,6 +68,7 @@ pub struct AudioContent { pub struct BaseMetadata { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, } @@ -71,6 +76,7 @@ pub struct BaseMetadata { pub struct BlobResourceContents { pub blob: String, #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub mime_type: Option, pub uri: String, } @@ -78,10 +84,13 @@ pub struct BlobResourceContents { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct BooleanSchema { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub default: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, pub r#type: String, // &'static str = "boolean" } @@ -98,6 +107,7 @@ impl ModelContextProtocolRequest for CallToolRequest { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct CallToolRequestParams { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub arguments: Option, pub name: String, } @@ -107,12 +117,14 @@ pub struct CallToolRequestParams { pub struct CallToolResult { pub content: Vec, #[serde(rename = "isError", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub is_error: Option, #[serde( rename = "structuredContent", default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub structured_content: Option, } @@ -135,6 +147,7 @@ impl ModelContextProtocolNotification for CancelledNotification { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct CancelledNotificationParams { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub reason: Option, #[serde(rename = "requestId")] pub request_id: RequestId, @@ -144,12 +157,16 @@ pub struct CancelledNotificationParams { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ClientCapabilities { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub elicitation: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub experimental: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub roots: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub sampling: Option, } @@ -161,6 +178,7 @@ pub struct ClientCapabilitiesRoots { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub list_changed: Option, } @@ -228,6 +246,7 @@ impl ModelContextProtocolRequest for CompleteRequest { pub struct CompleteRequestParams { pub argument: CompleteRequestParamsArgument, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub context: Option, pub r#ref: CompleteRequestParamsRef, } @@ -236,6 +255,7 @@ pub struct CompleteRequestParams { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct CompleteRequestParamsContext { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub arguments: Option, } @@ -262,8 +282,10 @@ pub struct CompleteResult { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct CompleteResultCompletion { #[serde(rename = "hasMore", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub has_more: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub total: Option, pub values: Vec, } @@ -302,31 +324,37 @@ pub struct CreateMessageRequestParams { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub include_context: Option, #[serde(rename = "maxTokens")] pub max_tokens: i64, pub messages: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub metadata: Option, #[serde( rename = "modelPreferences", default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub model_preferences: Option, #[serde( rename = "stopSequences", default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub stop_sequences: Option>, #[serde( rename = "systemPrompt", default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub system_prompt: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub temperature: Option, } @@ -341,6 +369,7 @@ pub struct CreateMessageResult { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub stop_reason: Option, } @@ -385,6 +414,7 @@ pub struct ElicitRequestParams { pub struct ElicitRequestParamsRequestedSchema { pub properties: serde_json::Value, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub required: Option>, pub r#type: String, // &'static str = "object" } @@ -394,6 +424,7 @@ pub struct ElicitRequestParamsRequestedSchema { pub struct ElicitResult { pub action: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub content: Option, } @@ -412,6 +443,7 @@ impl From for serde_json::Value { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct EmbeddedResource { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub annotations: Option, pub resource: EmbeddedResourceResource, pub r#type: String, // &'static str = "resource" @@ -429,11 +461,14 @@ pub type EmptyResult = Result; #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct EnumSchema { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, pub r#enum: Vec, #[serde(rename = "enumNames", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub enum_names: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, pub r#type: String, // &'static str = "string" } @@ -450,6 +485,7 @@ impl ModelContextProtocolRequest for GetPromptRequest { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct GetPromptRequestParams { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub arguments: Option, pub name: String, } @@ -458,6 +494,7 @@ pub struct GetPromptRequestParams { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct GetPromptResult { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, pub messages: Vec, } @@ -474,6 +511,7 @@ impl From for serde_json::Value { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ImageContent { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub annotations: Option, pub data: String, #[serde(rename = "mimeType")] @@ -486,10 +524,12 @@ pub struct ImageContent { pub struct Implementation { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, pub version: String, // This is an extra field that the Codex MCP server sends as part of InitializeResult. #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub user_agent: Option, } @@ -516,6 +556,7 @@ pub struct InitializeRequestParams { pub struct InitializeResult { pub capabilities: ServerCapabilities, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub instructions: Option, #[serde(rename = "protocolVersion")] pub protocol_version: String, @@ -552,6 +593,7 @@ pub struct JSONRPCError { pub struct JSONRPCErrorError { pub code: i64, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub data: Option, pub message: String, } @@ -573,6 +615,7 @@ pub struct JSONRPCNotification { pub jsonrpc: String, pub method: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub params: Option, } @@ -584,6 +627,7 @@ pub struct JSONRPCRequest { pub jsonrpc: String, pub method: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub params: Option, } @@ -608,6 +652,7 @@ impl ModelContextProtocolRequest for ListPromptsRequest { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ListPromptsRequestParams { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub cursor: Option, } @@ -619,6 +664,7 @@ pub struct ListPromptsResult { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub next_cursor: Option, pub prompts: Vec, } @@ -643,6 +689,7 @@ impl ModelContextProtocolRequest for ListResourceTemplatesRequest { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ListResourceTemplatesRequestParams { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub cursor: Option, } @@ -654,6 +701,7 @@ pub struct ListResourceTemplatesResult { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub next_cursor: Option, #[serde(rename = "resourceTemplates")] pub resource_templates: Vec, @@ -679,6 +727,7 @@ impl ModelContextProtocolRequest for ListResourcesRequest { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ListResourcesRequestParams { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub cursor: Option, } @@ -690,6 +739,7 @@ pub struct ListResourcesResult { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub next_cursor: Option, pub resources: Vec, } @@ -739,6 +789,7 @@ impl ModelContextProtocolRequest for ListToolsRequest { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ListToolsRequestParams { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub cursor: Option, } @@ -750,6 +801,7 @@ pub struct ListToolsResult { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub next_cursor: Option, pub tools: Vec, } @@ -799,6 +851,7 @@ pub struct LoggingMessageNotificationParams { pub data: serde_json::Value, pub level: LoggingLevel, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub logger: Option, } @@ -809,6 +862,7 @@ pub struct LoggingMessageNotificationParams { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ModelHint { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub name: Option, } @@ -830,20 +884,24 @@ pub struct ModelPreferences { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub cost_priority: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub hints: Option>, #[serde( rename = "intelligencePriority", default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub intelligence_priority: Option, #[serde( rename = "speedPriority", default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub speed_priority: Option, } @@ -851,18 +909,23 @@ pub struct ModelPreferences { pub struct Notification { pub method: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub params: Option, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct NumberSchema { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub maximum: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub minimum: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, pub r#type: String, } @@ -871,12 +934,14 @@ pub struct NumberSchema { pub struct PaginatedRequest { pub method: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub params: Option, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct PaginatedRequestParams { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub cursor: Option, } @@ -887,6 +952,7 @@ pub struct PaginatedResult { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub next_cursor: Option, } @@ -929,11 +995,13 @@ impl ModelContextProtocolNotification for ProgressNotification { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ProgressNotificationParams { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub message: Option, pub progress: f64, #[serde(rename = "progressToken")] pub progress_token: ProgressToken, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub total: Option, } @@ -948,11 +1016,14 @@ pub enum ProgressToken { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct Prompt { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub arguments: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, } @@ -960,11 +1031,14 @@ pub struct Prompt { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct PromptArgument { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub required: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, } @@ -991,6 +1065,7 @@ pub struct PromptMessage { pub struct PromptReference { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, pub r#type: String, // &'static str = "ref/prompt" } @@ -1034,6 +1109,7 @@ impl From for serde_json::Value { pub struct Request { pub method: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub params: Option, } @@ -1048,15 +1124,20 @@ pub enum RequestId { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub annotations: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub mime_type: Option, pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub size: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, pub uri: String, } @@ -1065,6 +1146,7 @@ pub struct Resource { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ResourceContents { #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub mime_type: Option, pub uri: String, } @@ -1075,15 +1157,20 @@ pub struct ResourceContents { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ResourceLink { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub annotations: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub mime_type: Option, pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub size: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, pub r#type: String, // &'static str = "resource_link" pub uri: String, @@ -1101,13 +1188,17 @@ impl ModelContextProtocolNotification for ResourceListChangedNotification { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ResourceTemplate { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub annotations: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub mime_type: Option, pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, #[serde(rename = "uriTemplate")] pub uri_template: String, @@ -1148,6 +1239,7 @@ pub enum Role { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct Root { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub name: Option, pub uri: String, } @@ -1179,16 +1271,22 @@ pub enum SamplingMessageContent { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ServerCapabilities { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub completions: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub experimental: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub logging: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub prompts: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub resources: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub tools: Option, } @@ -1200,6 +1298,7 @@ pub struct ServerCapabilitiesTools { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub list_changed: Option, } @@ -1211,8 +1310,10 @@ pub struct ServerCapabilitiesResources { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub list_changed: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub subscribe: Option, } @@ -1224,6 +1325,7 @@ pub struct ServerCapabilitiesPrompts { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub list_changed: Option, } @@ -1298,14 +1400,19 @@ pub struct SetLevelRequestParams { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct StringSchema { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub format: Option, #[serde(rename = "maxLength", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub max_length: Option, #[serde(rename = "minLength", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub min_length: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, pub r#type: String, // &'static str = "string" } @@ -1328,6 +1435,7 @@ pub struct SubscribeRequestParams { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct TextContent { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub annotations: Option, pub text: String, pub r#type: String, // &'static str = "text" @@ -1336,6 +1444,7 @@ pub struct TextContent { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct TextResourceContents { #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub mime_type: Option, pub text: String, pub uri: String, @@ -1345,8 +1454,10 @@ pub struct TextResourceContents { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct Tool { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub annotations: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub description: Option, #[serde(rename = "inputSchema")] pub input_schema: ToolInputSchema, @@ -1356,8 +1467,10 @@ pub struct Tool { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub output_schema: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, } @@ -1366,8 +1479,10 @@ pub struct Tool { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ToolOutputSchema { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub properties: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub required: Option>, pub r#type: String, // &'static str = "object" } @@ -1376,8 +1491,10 @@ pub struct ToolOutputSchema { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct ToolInputSchema { #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub properties: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub required: Option>, pub r#type: String, // &'static str = "object" } @@ -1397,26 +1514,31 @@ pub struct ToolAnnotations { default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub destructive_hint: Option, #[serde( rename = "idempotentHint", default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub idempotent_hint: Option, #[serde( rename = "openWorldHint", default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub open_world_hint: Option, #[serde( rename = "readOnlyHint", default, skip_serializing_if = "Option::is_none" )] + #[ts(optional)] pub read_only_hint: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] pub title: Option, } diff --git a/codex-rs/protocol/src/approvals.rs b/codex-rs/protocol/src/approvals.rs index 77a1b50fec..d608dba639 100644 --- a/codex-rs/protocol/src/approvals.rs +++ b/codex-rs/protocol/src/approvals.rs @@ -61,7 +61,6 @@ impl SandboxRiskCategory { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct ExecApprovalRequestEvent { /// Identifier for the associated exec call, if available. pub call_id: String, @@ -79,7 +78,6 @@ pub struct ExecApprovalRequestEvent { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct ApplyPatchApprovalRequestEvent { /// Responses API call id for the associated patch apply call, if available. pub call_id: String, diff --git a/codex-rs/protocol/src/custom_prompts.rs b/codex-rs/protocol/src/custom_prompts.rs index 790e0df821..7472d1b4c5 100644 --- a/codex-rs/protocol/src/custom_prompts.rs +++ b/codex-rs/protocol/src/custom_prompts.rs @@ -11,7 +11,6 @@ use ts_rs::TS; pub const PROMPTS_CMD_PREFIX: &str = "prompts"; #[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct CustomPrompt { pub name: String, pub path: PathBuf, diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index f7b31c4d6b..a824ee91e4 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -48,36 +48,35 @@ pub enum ContentItem { #[serde(tag = "type", rename_all = "snake_case")] pub enum ResponseItem { Message { - #[serde(skip_serializing)] - #[ts(optional = nullable)] + #[serde(default, skip_serializing)] + #[ts(skip)] id: Option, role: String, content: Vec, }, Reasoning { #[serde(default, skip_serializing)] + #[ts(skip)] id: String, summary: Vec, #[serde(default, skip_serializing_if = "should_serialize_reasoning_content")] - #[ts(optional = nullable)] + #[ts(optional)] content: Option>, - #[ts(optional = nullable)] encrypted_content: Option, }, LocalShellCall { /// Set when using the chat completions API. - #[serde(skip_serializing)] - #[ts(optional = nullable)] + #[serde(default, skip_serializing)] + #[ts(skip)] id: Option, /// Set when using the Responses API. - #[ts(optional = nullable)] call_id: Option, status: LocalShellStatus, action: LocalShellAction, }, FunctionCall { - #[serde(skip_serializing)] - #[ts(optional = nullable)] + #[serde(default, skip_serializing)] + #[ts(skip)] id: Option, name: String, // The Responses API returns the function call arguments as a *string* that contains @@ -97,11 +96,11 @@ pub enum ResponseItem { output: FunctionCallOutputPayload, }, CustomToolCall { - #[serde(skip_serializing)] - #[ts(optional = nullable)] + #[serde(default, skip_serializing)] + #[ts(skip)] id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional = nullable)] + #[ts(optional)] status: Option, call_id: String, @@ -121,11 +120,11 @@ pub enum ResponseItem { // "action": {"type":"search","query":"weather: San Francisco, CA"} // } WebSearchCall { - #[serde(skip_serializing)] - #[ts(optional = nullable)] + #[serde(default, skip_serializing)] + #[ts(skip)] id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional = nullable)] + #[ts(optional)] status: Option, action: WebSearchAction, }, @@ -203,7 +202,6 @@ pub enum LocalShellAction { } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct LocalShellExecAction { pub command: Vec, pub timeout_ms: Option, @@ -296,7 +294,6 @@ impl From> for ResponseInputItem { /// If the `name` of a `ResponseItem::FunctionCall` is either `container.exec` /// or shell`, the `arguments` field should deserialize to this struct. #[derive(Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct ShellToolCallParams { pub command: Vec, pub workdir: Option, @@ -329,7 +326,6 @@ pub enum FunctionCallOutputContentItem { /// `content_items` with the structured form that the Responses/Chat /// Completions APIs understand. #[derive(Debug, Default, Clone, PartialEq, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct FunctionCallOutputPayload { pub content: String, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/codex-rs/protocol/src/parse_command.rs b/codex-rs/protocol/src/parse_command.rs index b74713b452..77926f11b6 100644 --- a/codex-rs/protocol/src/parse_command.rs +++ b/codex-rs/protocol/src/parse_command.rs @@ -18,14 +18,11 @@ pub enum ParsedCommand { }, ListFiles { cmd: String, - #[ts(optional = nullable)] path: Option, }, Search { cmd: String, - #[ts(optional = nullable)] query: Option, - #[ts(optional = nullable)] path: Option, }, Unknown { diff --git a/codex-rs/protocol/src/plan_tool.rs b/codex-rs/protocol/src/plan_tool.rs index a95fe32efd..a9038eb03b 100644 --- a/codex-rs/protocol/src/plan_tool.rs +++ b/codex-rs/protocol/src/plan_tool.rs @@ -21,7 +21,6 @@ pub struct PlanItemArg { #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, TS)] #[serde(deny_unknown_fields)] -#[ts(optional_fields = nullable)] pub struct UpdatePlanArgs { #[serde(default)] pub explanation: Option, diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index b16baab9b0..dcb0299e49 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -661,7 +661,6 @@ impl HasLegacyEvent for EventMsg { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct ExitedReviewModeEvent { pub review_output: Option, } @@ -674,13 +673,11 @@ pub struct ErrorEvent { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct TaskCompleteEvent { pub last_agent_message: Option, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct TaskStartedEvent { pub model_context_window: Option, } @@ -700,11 +697,9 @@ pub struct TokenUsage { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct TokenUsageInfo { pub total_token_usage: TokenUsage, pub last_token_usage: TokenUsage, - #[ts(optional = nullable)] #[ts(type = "number | null")] pub model_context_window: Option, } @@ -765,30 +760,25 @@ impl TokenUsageInfo { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct TokenCountEvent { pub info: Option, pub rate_limits: Option, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct RateLimitSnapshot { pub primary: Option, pub secondary: Option, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct RateLimitWindow { /// Percentage (0-100) of the window that has been consumed. pub used_percent: f64, /// Rolling window duration, in minutes. - #[ts(optional = nullable)] #[ts(type = "number | null")] pub window_minutes: Option, /// Unix timestamp (seconds since epoch) when the window resets. - #[ts(optional = nullable)] #[ts(type = "number | null")] pub resets_at: Option, } @@ -902,7 +892,6 @@ pub struct AgentMessageEvent { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct UserMessageEvent { pub message: String, #[serde(skip_serializing_if = "Option::is_none")] @@ -938,7 +927,6 @@ pub struct AgentReasoningDeltaEvent { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS, PartialEq)] -#[ts(optional_fields = nullable)] pub struct McpInvocation { /// Name of the MCP server as defined in the config. pub server: String, @@ -1067,7 +1055,6 @@ pub enum SubAgentSource { } #[derive(Serialize, Deserialize, Clone, Debug, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct SessionMeta { pub id: ConversationId, pub timestamp: String, @@ -1096,7 +1083,6 @@ impl Default for SessionMeta { } #[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct SessionMetaLine { #[serde(flatten)] pub meta: SessionMeta, @@ -1132,7 +1118,6 @@ impl From for ResponseItem { } #[derive(Serialize, Deserialize, Clone, Debug, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct TurnContextItem { pub cwd: PathBuf, pub approval_policy: AskForApproval, @@ -1151,7 +1136,6 @@ pub struct RolloutLine { } #[derive(Serialize, Deserialize, Clone, Debug, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct GitInfo { /// Current commit hash (SHA) #[serde(skip_serializing_if = "Option::is_none")] @@ -1285,7 +1269,6 @@ pub struct BackgroundEventEvent { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct DeprecationNoticeEvent { /// Concise summary of what is deprecated. pub summary: String, @@ -1295,14 +1278,12 @@ pub struct DeprecationNoticeEvent { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct UndoStartedEvent { #[serde(skip_serializing_if = "Option::is_none")] pub message: Option, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct UndoCompletedEvent { pub success: bool, #[serde(skip_serializing_if = "Option::is_none")] @@ -1347,7 +1328,6 @@ pub struct TurnDiffEvent { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct GetHistoryEntryResponseEvent { pub offset: usize, pub log_id: u64, @@ -1397,7 +1377,6 @@ pub struct ListCustomPromptsResponseEvent { } #[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct SessionConfiguredEvent { /// Name left as session_id instead of conversation_id for backwards compatibility. pub session_id: ConversationId, @@ -1458,7 +1437,6 @@ pub enum FileChange { }, Update { unified_diff: String, - #[ts(optional = nullable)] move_path: Option, }, } diff --git a/codex-rs/utils/git/src/lib.rs b/codex-rs/utils/git/src/lib.rs index 57ab05b38b..cf2887aa8f 100644 --- a/codex-rs/utils/git/src/lib.rs +++ b/codex-rs/utils/git/src/lib.rs @@ -28,7 +28,6 @@ type CommitID = String; /// Details of a ghost commit created from a repository state. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, TS)] -#[ts(optional_fields = nullable)] pub struct GhostCommit { id: CommitID, parent: Option,