Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Support model-catalog overrides for Code Mode tool messages (#47118)

rhan-oai5aa4939be4ed
diff --git a/codex-rs/code-mode-protocol/src/description.rs b/codex-rs/code-mode-protocol/src/description.rs
index 860074e769..6d4951712d 100644
--- a/codex-rs/code-mode-protocol/src/description.rs
+++ b/codex-rs/code-mode-protocol/src/description.rs
@@ -1,4 +1,8 @@
+//! Composes Code Mode descriptions, retaining runtime-owned tool declarations.
+//! Exec templates substitute only the documented literal placeholders.
+
use codex_protocol::ToolName;
+use codex_protocol::openai_models::CodeModeToolMessages;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
@@ -20,14 +24,14 @@ const EXEC_DESCRIPTION_TEMPLATE: &str = r#"Run JavaScript code to orchestrate/co
- Runs raw JavaScript -- no Node, no file system, no network access, no console.
- Accepts raw JavaScript source text, not JSON, quoted strings, or markdown code fences.
- You may optionally start the tool input with a first-line pragma like `// @exec: {"yield_time_ms": 10000, "max_output_tokens": 1000}`.
-- `yield_time_ms` asks `exec` to yield early if the script is still running. Defaults to 10000 ms.
+- `yield_time_ms` asks `exec` to yield early if the script is still running. Defaults to {{ default_exec_yield_time_ms }} ms.
- `max_output_tokens` sets the token budget for direct `exec` results. Defaults to 10000 tokens.
- When the JS code is fully evaluated, the isolate's lifetime ends and unawaited promises are silently discarded.
- Global helpers:
- `exit()`: Immediately ends the current script successfully (like an early return from the top level).
- `text(value: string | number | boolean | undefined | null)`: Appends a text item. Non-string values are stringified with `JSON.stringify(...)` when possible.
-- `image(imageUrlOrItem: string | { image_url: string; detail?: "auto" | "low" | "high" | "original" | null } | ImageContent, detail?: "auto" | "low" | "high" | "original" | null)`: Appends an image item. `image_url` should be a base64-encoded `data:` URL. To forward an MCP tool image, pass an individual `ImageContent` block from `result.content`, for example `image(result.content[0])`. MCP image blocks may request detail with `_meta: { "codex/imageDetail": "original" }`. When provided, the second `detail` argument overrides any detail embedded in the first argument.
+- {{ image_helper }}
- `audio(audioUrlOrItem: string | { audio_url: string } | AudioContent)`: Appends an audio item. `audio_url` should be a base64-encoded `data:` URL. To forward an MCP tool audio block, pass an individual `AudioContent` block from `result.content`, for example `audio(result.content[0])`.
- `generatedImage(result: { image_url: string; output_hint?: string })`: Appends an image-generation result and its optional output hint. HTTP(S) URLs are not supported.
- `store(key: string, value: any)`: stores a serializable value under a string key for later `exec` calls in the same session.
@@ -265,20 +269,32 @@ pub fn build_exec_tool_description(
default_exec_yield_time_ms: u64,
code_mode_only: bool,
image_detail_visibility: ImageDetailVisibility,
+ messages: Option<&CodeModeToolMessages>,
) -> String {
let mut sections = Vec::new();
- sections.push(EXEC_DESCRIPTION_TEMPLATE.replace(
- "Defaults to 10000 ms.",
- &format!("Defaults to {default_exec_yield_time_ms} ms."),
- ));
- if image_detail_visibility == ImageDetailVisibility::Hidden {
- sections[0] = sections[0].replace(
- LEGACY_IMAGE_HELPER_DESCRIPTION,
- UNIFIED_IMAGE_HELPER_DESCRIPTION,
- );
+ let image_helper = match image_detail_visibility {
+ ImageDetailVisibility::Visible => LEGACY_IMAGE_HELPER_DESCRIPTION,
+ ImageDetailVisibility::Hidden => UNIFIED_IMAGE_HELPER_DESCRIPTION,
+ };
+ let description = messages
+ .and_then(|messages| messages.exec.as_ref())
+ .and_then(|exec| exec.description.as_deref())
+ .unwrap_or(EXEC_DESCRIPTION_TEMPLATE)
+ .replace(
+ "{{ default_exec_yield_time_ms }}",
+ &default_exec_yield_time_ms.to_string(),
+ )
+ .replace("{{ image_helper }}", image_helper);
+ if !description.is_empty() {
+ sections.push(description);
}
if !deferred_tools.is_empty() {
- sections.push(DEFERRED_NESTED_TOOLS_GUIDANCE.to_string());
+ let guidance = messages
+ .and_then(|messages| messages.deferred_nested_tools_guidance.as_deref())
+ .unwrap_or(DEFERRED_NESTED_TOOLS_GUIDANCE);
+ if !guidance.is_empty() {
+ sections.push(guidance.to_string());
+ }
}
if !code_mode_only {
return sections.join("\n\n");
@@ -289,9 +305,12 @@ pub fn build_exec_tool_description(
.chain(deferred_tools)
.any(|tool| mcp_structured_content_schema(tool.output_schema.as_ref()).is_some());
if has_mcp_tools {
- sections.push(format!(
- "Shared MCP Types:\n```ts\n{MCP_TYPESCRIPT_PREAMBLE}\n```"
- ));
+ let preamble = messages
+ .and_then(|messages| messages.mcp_typescript_preamble.as_deref())
+ .unwrap_or(MCP_TYPESCRIPT_PREAMBLE);
+ if !preamble.is_empty() {
+ sections.push(format!("Shared MCP Types:\n```ts\n{preamble}\n```"));
+ }
}
if !enabled_tools.is_empty() {
@@ -502,6 +521,10 @@ fn mcp_structured_content_schema(output_schema: Option<&JsonValue>) -> Option<&J
)
}
+#[cfg(test)]
+#[path = "description_override_tests.rs"]
+mod description_override_tests;
+
#[cfg(test)]
mod tests {
use super::CodeModeToolKind;
@@ -709,6 +732,7 @@ mod tests {
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
ImageDetailVisibility::Visible,
+ /*messages*/ None,
);
assert!(description.contains(
"### `foo`
@@ -726,6 +750,7 @@ bar"
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ false,
ImageDetailVisibility::Visible,
+ /*messages*/ None,
);
assert!(description.contains("`audio(audioUrlOrItem:"));
assert!(description.contains("`setTimeout(callback: () => void, delayMs?: number)`"));
@@ -781,6 +806,7 @@ bar"
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
ImageDetailVisibility::Visible,
+ /*messages*/ None,
);
assert_eq!(description.matches("## mcp__sample").count(), 1);
assert!(description.contains("## mcp__sample\nShared namespace guidance."));
@@ -823,6 +849,7 @@ bar"
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
ImageDetailVisibility::Visible,
+ /*messages*/ None,
);
assert!(!description.contains("## mcp__sample"));
@@ -924,6 +951,7 @@ bar"
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
ImageDetailVisibility::Visible,
+ /*messages*/ None,
);
assert_eq!(
@@ -961,6 +989,7 @@ bar"
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
ImageDetailVisibility::Visible,
+ /*messages*/ None,
);
assert!(description.contains("Some deferred nested tools may be omitted"));
@@ -984,6 +1013,7 @@ bar"
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ false,
ImageDetailVisibility::Visible,
+ /*messages*/ None,
);
assert!(description.contains("Some deferred nested tools may be omitted"));
diff --git a/codex-rs/code-mode-protocol/src/description_override_tests.rs b/codex-rs/code-mode-protocol/src/description_override_tests.rs
new file mode 100644
index 0000000000..fcd4a092bc
--- /dev/null
+++ b/codex-rs/code-mode-protocol/src/description_override_tests.rs
@@ -0,0 +1,159 @@
+//! Tests catalog exec template rendering and runtime description composition.
+
+use super::CodeModeToolKind;
+use super::DEFERRED_NESTED_TOOLS_GUIDANCE;
+use super::ImageDetailVisibility;
+use super::LEGACY_IMAGE_HELPER_DESCRIPTION;
+use super::MCP_TYPESCRIPT_PREAMBLE;
+use super::ToolDefinition;
+use super::UNIFIED_IMAGE_HELPER_DESCRIPTION;
+use super::build_exec_tool_description;
+use codex_protocol::ToolName;
+use codex_protocol::openai_models::CodeModeToolMessages;
+use codex_protocol::openai_models::ToolMessage;
+use pretty_assertions::assert_eq;
+use serde_json::json;
+use std::collections::BTreeMap;
+
+#[test]
+fn exec_override_renders_only_known_literal_placeholders() {
+ for (image_detail_visibility, image_helper) in [
+ (
+ ImageDetailVisibility::Visible,
+ LEGACY_IMAGE_HELPER_DESCRIPTION,
+ ),
+ (
+ ImageDetailVisibility::Hidden,
+ UNIFIED_IMAGE_HELPER_DESCRIPTION,
+ ),
+ ] {
+ let description = build_exec_tool_description(
+ &[],
+ &[],
+ &BTreeMap::new(),
+ /*default_exec_yield_time_ms*/ 4567,
+ /*code_mode_only*/ false,
+ image_detail_visibility,
+ Some(&CodeModeToolMessages {
+ exec: Some(ToolMessage {
+ description: Some(" \nDefaults to 10000 ms. {{ default_exec_yield_time_ms }} ms.\n{{ image_helper }}\n{{ unknown }} {{default_exec_yield_time_ms}}\t ".to_string()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ );
+
+ assert_eq!(
+ description,
+ format!(
+ " \nDefaults to 10000 ms. 4567 ms.\n{image_helper}\n{{{{ unknown }}}} {{{{default_exec_yield_time_ms}}}}\t "
+ ),
+ );
+ }
+}
+
+#[test]
+fn exec_override_preserves_empty_and_whitespace_only_text() {
+ for description_override in ["", " \n\t "] {
+ assert_eq!(
+ build_exec_tool_description(
+ &[],
+ &[],
+ &BTreeMap::new(),
+ crate::DEFAULT_EXEC_YIELD_TIME_MS,
+ /*code_mode_only*/ true,
+ ImageDetailVisibility::Visible,
+ Some(&CodeModeToolMessages {
+ exec: Some(ToolMessage {
+ description: Some(description_override.to_string()),
+ ..Default::default()
+ }),
+ deferred_nested_tools_guidance: Some(
+ "No deferred tools; omit this.".to_string()
+ ),
+ mcp_typescript_preamble: Some("No MCP tools; omit this.".to_string()),
+ ..Default::default()
+ }),
+ ),
+ description_override,
+ );
+ }
+}
+
+#[test]
+fn exec_override_preserves_runtime_sections() {
+ let enabled_tools = [ToolDefinition {
+ name: "alpha".to_string(),
+ tool_name: ToolName::plain("alpha"),
+ description: "First tool".to_string(),
+ kind: CodeModeToolKind::Function,
+ input_schema: None,
+ output_schema: None,
+ }];
+ let deferred_tools = [ToolDefinition {
+ name: "mcp__sample__beta".to_string(),
+ tool_name: ToolName::namespaced("mcp__sample__", "beta"),
+ description: "Deferred tool".to_string(),
+ kind: CodeModeToolKind::Function,
+ input_schema: None,
+ output_schema: Some(json!({
+ "type": "object",
+ "properties": {
+ "content": { "type": "array", "items": { "type": "object" } },
+ "isError": { "type": "boolean" },
+ "_meta": { "type": "object" }
+ }
+ })),
+ }];
+ let declaration = "### `alpha`\nFirst tool\n\nexec tool declaration:\n```ts\ndeclare const tools: { alpha(args: unknown): Promise<unknown>; };\n```";
+ for (code_mode_only, guidance, preamble, expected) in [
+ (true, Some(""), Some(""), declaration.to_string()),
+ (
+ true,
+ None,
+ Some(""),
+ format!("{DEFERRED_NESTED_TOOLS_GUIDANCE}\n\n{declaration}"),
+ ),
+ (
+ true,
+ Some(""),
+ None,
+ format!("Shared MCP Types:\n```ts\n{MCP_TYPESCRIPT_PREAMBLE}\n```\n\n{declaration}"),
+ ),
+ (
+ true,
+ Some(" {{ image_helper }}\n"),
+ Some(" {{ default_exec_yield_time_ms }}\n"),
+ format!(
+ " {{{{ image_helper }}}}\n\n\nShared MCP Types:\n```ts\n {{{{ default_exec_yield_time_ms }}}}\n\n```\n\n{declaration}"
+ ),
+ ),
+ (
+ false,
+ Some("Catalog discovery."),
+ Some("No types outside Code Mode Only."),
+ "Catalog discovery.".to_string(),
+ ),
+ ] {
+ assert_eq!(
+ build_exec_tool_description(
+ &enabled_tools,
+ &deferred_tools,
+ &BTreeMap::new(),
+ crate::DEFAULT_EXEC_YIELD_TIME_MS,
+ code_mode_only,
+ ImageDetailVisibility::Visible,
+ Some(&CodeModeToolMessages {
+ exec: Some(ToolMessage {
+ description: Some(String::new()),
+ ..Default::default()
+ }),
+ deferred_nested_tools_guidance: guidance.map(str::to_string),
+ mcp_typescript_preamble: preamble.map(str::to_string),
+ ..Default::default()
+ }),
+ ),
+ expected,
+ );
+ }
+}
diff --git a/codex-rs/core/src/tools/catalog_parameters.rs b/codex-rs/core/src/tools/catalog_parameters.rs
new file mode 100644
index 0000000000..9c36c70abe
--- /dev/null
+++ b/codex-rs/core/src/tools/catalog_parameters.rs
@@ -0,0 +1,14 @@
+//! Parses catalog parameter overrides using the harness's supported JSON Schema subset.
+//! Rejected schemas leave fallback and transport-specific requirements to the tool owner.
+
+use codex_tools::JsonSchema;
+use serde_json::Value;
+
+pub(super) fn parse(parameters: &str) -> Result<JsonSchema, &'static str> {
+ let parameters: Value =
+ serde_json::from_str(parameters).map_err(|_| "schema is not valid JSON")?;
+ if !parameters.is_object() || parameters["type"] != "object" {
+ return Err("schema must declare an object type");
+ }
+ serde_json::from_value(parameters).map_err(|_| "schema uses unsupported JSON Schema structures")
+}
diff --git a/codex-rs/core/src/tools/code_mode/execute_spec.rs b/codex-rs/core/src/tools/code_mode/execute_spec.rs
index 3b44117b91..c320e182c5 100644
--- a/codex-rs/core/src/tools/code_mode/execute_spec.rs
+++ b/codex-rs/core/src/tools/code_mode/execute_spec.rs
@@ -1,5 +1,6 @@
use codex_code_mode::ImageDetailVisibility;
use codex_code_mode::ToolDefinition as CodeModeToolDefinition;
+use codex_protocol::openai_models::CodeModeToolMessages;
use codex_tools::FreeformTool;
use codex_tools::FreeformToolFormat;
use codex_tools::ToolSpec;
@@ -12,6 +13,7 @@ pub(crate) fn create_code_mode_tool(
default_exec_yield_time_ms: u64,
code_mode_only: bool,
image_detail_visibility: ImageDetailVisibility,
+ messages: Option<&CodeModeToolMessages>,
) -> ToolSpec {
const CODE_MODE_FREEFORM_GRAMMAR: &str = r#"
start: pragma_source | plain_source
@@ -32,6 +34,7 @@ SOURCE: /[\s\S]+/
default_exec_yield_time_ms,
code_mode_only,
image_detail_visibility,
+ messages,
),
defer_loading: None,
format: FreeformToolFormat {
@@ -67,6 +70,7 @@ mod tests {
codex_code_mode::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
ImageDetailVisibility::Visible,
+ /*messages*/ None,
),
ToolSpec::Freeform(FreeformTool {
name: codex_code_mode::PUBLIC_TOOL_NAME.to_string(),
@@ -77,6 +81,7 @@ mod tests {
codex_code_mode::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
ImageDetailVisibility::Visible,
+ /*messages*/ None,
),
defer_loading: None,
format: FreeformToolFormat {
diff --git a/codex-rs/core/src/tools/code_mode/wait_handler.rs b/codex-rs/core/src/tools/code_mode/wait_handler.rs
index 5b4bf374d6..617e412a57 100644
--- a/codex-rs/core/src/tools/code_mode/wait_handler.rs
+++ b/codex-rs/core/src/tools/code_mode/wait_handler.rs
@@ -20,7 +20,9 @@ use super::telemetry::CodeModeToolCallGuard;
use super::telemetry::trace_id;
use super::wait_spec::create_wait_tool;
-pub struct CodeModeWaitHandler;
+pub struct CodeModeWaitHandler {
+ spec: ToolSpec,
+}
#[derive(Debug, Deserialize)]
struct ExecWaitArgs {
@@ -52,7 +54,7 @@ impl ToolExecutor<ToolInvocation> for CodeModeWaitHandler {
}
fn spec(&self) -> ToolSpec {
- create_wait_tool()
+ self.spec.clone()
}
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutorFuture<'a>
@@ -64,6 +66,15 @@ impl ToolExecutor<ToolInvocation> for CodeModeWaitHandler {
}
impl CodeModeWaitHandler {
+ pub(crate) fn new(
+ description_override: Option<&str>,
+ parameters_override: Option<&str>,
+ ) -> Self {
+ Self {
+ spec: create_wait_tool(description_override, parameters_override),
+ }
+ }
+
// Default to interrupted if this future is dropped; telemetry::CodeModeToolCallGuard::finish
// overwrites this handler's captured span on explicit success or failure, including early errors.
#[tracing::instrument(
diff --git a/codex-rs/core/src/tools/code_mode/wait_spec.rs b/codex-rs/core/src/tools/code_mode/wait_spec.rs
index 72bb09084c..01b713e515 100644
--- a/codex-rs/core/src/tools/code_mode/wait_spec.rs
+++ b/codex-rs/core/src/tools/code_mode/wait_spec.rs
@@ -3,7 +3,10 @@ use codex_tools::ResponsesApiTool;
use codex_tools::ToolSpec;
use std::collections::BTreeMap;
-pub(crate) fn create_wait_tool() -> ToolSpec {
+pub(crate) fn create_wait_tool(
+ description_override: Option<&str>,
+ parameters_override: Option<&str>,
+) -> ToolSpec {
let properties = BTreeMap::from([
(
"cell_id".to_string(),
@@ -31,17 +34,35 @@ pub(crate) fn create_wait_tool() -> ToolSpec {
ToolSpec::Function(ResponsesApiTool {
name: codex_code_mode::WAIT_TOOL_NAME.to_string(),
- description: format!(
- "Waits on a yielded `{}` cell and returns new output or completion.\n{}",
- codex_code_mode::PUBLIC_TOOL_NAME,
- codex_code_mode::build_wait_tool_description().trim()
- ),
+ description: description_override.map(str::to_owned).unwrap_or_else(|| {
+ format!(
+ "Waits on a yielded `{}` cell and returns new output or completion.\n{}",
+ codex_code_mode::PUBLIC_TOOL_NAME,
+ codex_code_mode::build_wait_tool_description().trim()
+ )
+ }),
strict: false,
- parameters: JsonSchema::object(
- properties,
- Some(vec!["cell_id".to_string()]),
- Some(false.into()),
- ),
+ parameters: parameters_override
+ .and_then(
+ |parameters| match crate::tools::catalog_parameters::parse(parameters) {
+ Ok(parameters) => Some(parameters),
+ Err(reason) => {
+ tracing::warn!(
+ tool = codex_code_mode::WAIT_TOOL_NAME,
+ reason,
+ "Invalid catalog tool parameters; using bundled parameters"
+ );
+ None
+ }
+ },
+ )
+ .unwrap_or_else(|| {
+ JsonSchema::object(
+ properties,
+ Some(vec!["cell_id".to_string()]),
+ Some(false.into()),
+ )
+ }),
output_schema: None,
defer_loading: None,
})
@@ -55,7 +76,7 @@ mod tests {
#[test]
fn create_wait_tool_matches_expected_spec() {
assert_eq!(
- create_wait_tool(),
+ create_wait_tool(/*description_override*/ None, /*parameters_override*/ None),
ToolSpec::Function(ResponsesApiTool {
name: codex_code_mode::WAIT_TOOL_NAME.to_string(),
description: format!(
diff --git a/codex-rs/core/src/tools/mod.rs b/codex-rs/core/src/tools/mod.rs
index 262efcce71..464996b061 100644
--- a/codex-rs/core/src/tools/mod.rs
+++ b/codex-rs/core/src/tools/mod.rs
@@ -1,5 +1,6 @@
mod approvals;
pub(crate) mod call_trace;
+mod catalog_parameters;
pub(crate) mod code_mode;
pub(crate) mod context;
mod control_tool_analytics;
diff --git a/codex-rs/core/src/tools/multi_agent_tool.rs b/codex-rs/core/src/tools/multi_agent_tool.rs
index 8ea4a69eed..098e433646 100644
--- a/codex-rs/core/src/tools/multi_agent_tool.rs
+++ b/codex-rs/core/src/tools/multi_agent_tool.rs
@@ -13,7 +13,6 @@ use codex_tools::ToolName;
use codex_tools::ToolSearchInfo;
use codex_tools::ToolSpec;
use futures::future::BoxFuture;
-use serde_json::Value;
use std::sync::Arc;
pub(crate) const MULTI_AGENT_V2_NAMESPACE_DESCRIPTION: &str =
@@ -26,13 +25,7 @@ pub(super) fn multi_agent_v2_handler(
parameters_override: Option<&str>,
) -> Arc<dyn CoreToolRuntime> {
let parameters_override = parameters_override.map(|parameters| -> Result<JsonSchema, &str> {
- let parameters: Value =
- serde_json::from_str(parameters).map_err(|_| "schema is not valid JSON")?;
- if !parameters.is_object() || parameters["type"] != "object" {
- return Err("schema must declare an object type");
- }
- let mut parameters: JsonSchema = serde_json::from_value(parameters)
- .map_err(|_| "schema uses unsupported JSON Schema structures")?;
+ let mut parameters = super::catalog_parameters::parse(parameters)?;
if let ToolSpec::Function(tool) = handler.spec()
&& let Some(properties) = tool.parameters.properties
{
diff --git a/codex-rs/core/src/tools/registry_tests.rs b/codex-rs/core/src/tools/registry_tests.rs
index f1992670d4..895d8d4b99 100644
--- a/codex-rs/core/src/tools/registry_tests.rs
+++ b/codex-rs/core/src/tools/registry_tests.rs
@@ -563,7 +563,9 @@ async fn code_mode_wait_does_not_expose_default_hook_payloads() {
let (session, turn) = crate::session::tests::make_session_and_context().await;
let output = crate::tools::context::FunctionToolOutput::from_text("ok".to_string(), Some(true));
- let wait = crate::tools::handlers::CodeModeWaitHandler;
+ let wait = crate::tools::handlers::CodeModeWaitHandler::new(
+ /*description_override*/ None, /*parameters_override*/ None,
+ );
let wait_invocation = test_invocation(
Arc::new(session),
Arc::new(turn),
diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs
index f5c88e3b92..335ce59526 100644
--- a/codex-rs/core/src/tools/spec_plan.rs
+++ b/codex-rs/core/src/tools/spec_plan.rs
@@ -869,6 +869,7 @@ fn register_code_mode_executors(
);
enabled_tools
.sort_by(|left, right| compare_code_mode_tools(left, right, &namespace_descriptions));
+ let model_messages = ResolvedModelMessages::from_model(model_info);
let execute_handler = CodeModeExecuteHandler::new(
create_code_mode_tool(
&enabled_tools,
@@ -881,11 +882,15 @@ fn register_code_mode_executors(
} else {
codex_code_mode::ImageDetailVisibility::Visible
},
+ model_messages.code_mode(),
),
code_mode_nested_tool_specs,
);
- registry.prepend_trusted(Arc::new(CodeModeWaitHandler));
+ registry.prepend_trusted(Arc::new(CodeModeWaitHandler::new(
+ model_messages.code_mode_wait_description_override(),
+ model_messages.code_mode_wait_parameters_override(),
+ )));
registry.prepend_trusted(Arc::new(execute_handler));
code_mode_tool_names
diff --git a/codex-rs/core/src/tools/tool_dispatch_trace_tests.rs b/codex-rs/core/src/tools/tool_dispatch_trace_tests.rs
index 5c841f56a9..1317810361 100644
--- a/codex-rs/core/src/tools/tool_dispatch_trace_tests.rs
+++ b/codex-rs/core/src/tools/tool_dispatch_trace_tests.rs
@@ -287,7 +287,9 @@ async fn missing_code_mode_wait_traces_only_the_wait_tool_call() -> anyhow::Resu
);
attach_test_trace(&mut session, &turn, temp.path())?;
- let registry = ToolRegistry::with_handler_for_test(Arc::new(CodeModeWaitHandler));
+ let registry = ToolRegistry::with_handler_for_test(Arc::new(CodeModeWaitHandler::new(
+ /*description_override*/ None, /*parameters_override*/ None,
+ )));
let session = Arc::new(session);
let turn = Arc::new(turn);
diff --git a/codex-rs/core/tests/suite/code_mode_model_messages.rs b/codex-rs/core/tests/suite/code_mode_model_messages.rs
new file mode 100644
index 0000000000..4a5cc517ca
--- /dev/null
+++ b/codex-rs/core/tests/suite/code_mode_model_messages.rs
@@ -0,0 +1,73 @@
+//! Wait descriptions and parameter schemas resolve independently without changing other tools.
+
+use anyhow::Result;
+use codex_protocol::openai_models::ToolMessages;
+use codex_protocol::openai_models::ToolMode;
+use core_test_support::responses::mount_sse_sequence;
+use core_test_support::responses::sse_completed;
+use core_test_support::responses::start_mock_server;
+use core_test_support::skip_if_no_network;
+use core_test_support::test_codex::test_codex;
+use pretty_assertions::assert_eq;
+use serde_json::Value;
+use serde_json::json;
+use test_case::test_case;
+
+const PARAMETERS: &str = r#"{"type":"object","properties":{"cell_id":{"type":"string","description":"Catalog cell identifier."}},"required":["cell_id"],"additionalProperties":false}"#;
+
+#[test_case(ToolMode::CodeMode, json!({"description":" Catalog wait. {{ literal }}\n"}), false; "description_only")]
+#[test_case(ToolMode::CodeMode, json!({"parameters":PARAMETERS}), true; "parameters_only")]
+#[test_case(ToolMode::CodeModeOnly, json!({"description":"Catalog wait.","parameters":PARAMETERS}), true; "both_in_code_mode_only")]
+#[test_case(ToolMode::CodeModeOnly, json!({"description":"","parameters":""}), false; "empty_description_and_invalid_schema")]
+#[test_case(ToolMode::CodeMode, json!({"description":"Catalog wait.","parameters":"{"}), false; "invalid_parameters_preserve_description")]
+#[test_case(ToolMode::CodeMode, json!({"description":null,"parameters":null}), false; "null_fields_fall_back")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn code_mode_wait_overrides_are_independent(
+ tool_mode: ToolMode,
+ overrides: Value,
+ valid_parameters: bool,
+) -> Result<()> {
+ skip_if_no_network!(Ok(()));
+ let server = start_mock_server().await;
+ let mock = mount_sse_sequence(
+ &server,
+ vec![sse_completed("bundled"), sse_completed("catalog")],
+ )
+ .await;
+ for messages in [
+ None,
+ Some(serde_json::from_value::<ToolMessages>(
+ json!({"code_mode": {"wait": overrides}}),
+ )?),
+ ] {
+ let test = test_codex()
+ .with_model_info_override("gpt-5.5", move |model| {
+ model.tool_mode = Some(tool_mode);
+ model.use_responses_lite = false;
+ model.model_messages.as_mut().expect("model messages").tools = messages;
+ })
+ .with_config(|config| {
+ config.code_mode.disable_in_process_fallback = true;
+ })
+ .build_with_auto_env(&server)
+ .await?;
+ test.submit_turn("Inspect the available tools.").await?;
+ }
+ let requests = mock.requests();
+ assert_eq!(requests.len(), 2);
+ let mut expected = requests[0].body_json()["tools"].clone();
+ let wait = expected
+ .as_array_mut()
+ .expect("tools")
+ .iter_mut()
+ .find(|tool| tool["name"] == "wait")
+ .expect("wait");
+ if let Some(description) = overrides["description"].as_str() {
+ wait["description"] = json!(description);
+ }
+ if valid_parameters {
+ wait["parameters"] = serde_json::from_str(PARAMETERS)?;
+ }
+ assert_eq!(requests[1].body_json()["tools"], expected);
+ Ok(())
+}
diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs
index aca4328e9c..f2697f9b0e 100644
--- a/codex-rs/core/tests/suite/mod.rs
+++ b/codex-rs/core/tests/suite/mod.rs
@@ -53,6 +53,7 @@ mod client_websockets;
mod cloud_config;
mod code_mode;
mod code_mode_elicitation;
+mod code_mode_model_messages;
mod codex_apps_protocol;
mod codex_delegate;
mod collaboration_instructions;
diff --git a/codex-rs/core/tests/suite/scenarios.rs b/codex-rs/core/tests/suite/scenarios.rs
index 06d5b4f74e..49f7b6cc96 100644
--- a/codex-rs/core/tests/suite/scenarios.rs
+++ b/codex-rs/core/tests/suite/scenarios.rs
@@ -32,6 +32,9 @@ use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_protocol::items::AgentMessageDelivery;
use codex_protocol::items::TurnItem;
use codex_protocol::models::ImageReference;
+use codex_protocol::openai_models::CodeModeToolMessages;
+use codex_protocol::openai_models::ToolMessage;
+use codex_protocol::openai_models::ToolMode;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::user_input::UserInput;
@@ -62,6 +65,7 @@ use core_test_support::test_codex::test_codex;
use core_test_support::wait_for_event;
use core_test_support::wait_for_event_match;
use core_test_support::wait_for_mcp_server;
+use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use tokio::sync::oneshot;
@@ -775,6 +779,100 @@ async fn astra_reads_code_mode_call_timing() -> Result<()> {
Ok(())
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn code_mode_catalog_messages() -> Result<()> {
+ skip_if_no_network!(Ok(()));
+ let server = start_mock_server().await;
+ let apps =
+ core_test_support::apps_test_server::AppsTestServer::mount_searchable(&server).await?;
+ let test = test_codex()
+ .with_model("gpt-6-astra")
+ .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
+ .with_config(move |config| {
+ configure_scenario_catalog(config);
+ config.chatgpt_base_url = apps.chatgpt_base_url;
+ config.features.enable(Feature::Apps).expect("enable apps");
+ config.workspace_roots = vec![config.cwd.clone()];
+ config.code_mode.disable_in_process_fallback = true;
+ config.code_mode.default_exec_yield_time_ms = 1234;
+ config.features.enable(Feature::CodeModeHost).expect("enable the code-mode host");
+ let model = config.model_catalog.as_mut().expect("scenario model catalog")
+ .models.iter_mut().find(|model| model.slug == "gpt-6-astra")
+ .expect("Astra model");
+ model.tool_mode = Some(ToolMode::CodeModeOnly);
+ model.use_responses_lite = false;
+ model.supports_search_tool = true;
+ model.model_messages.as_mut().expect("model messages").tools
+ .get_or_insert_with(Default::default).code_mode = Some(CodeModeToolMessages {
+ exec: Some(ToolMessage {
+ description: Some("Catalog exec instructions. Default yield: {{ default_exec_yield_time_ms }} ms.\n{{ image_helper }}".to_string()),
+ ..Default::default()
+ }),
+ wait: Some(ToolMessage {
+ description: Some("Catalog wait instructions: resume the yielded cell.".to_string()),
+ parameters: Some(json!({
+ "type": "object",
+ "properties": {
+ "cell_id": {"type": "string", "description": "Catalog cell identifier returned by exec."},
+ "yield_time_ms": {"type": "number", "description": "Catalog wait duration in milliseconds."},
+ "max_tokens": {"type": "number", "description": "Catalog output token limit."},
+ "terminate": {"type": "boolean", "description": "Catalog switch to terminate the cell."}
+ },
+ "required": ["cell_id"],
+ "additionalProperties": false
+ }).to_string()),
+ }),
+ deferred_nested_tools_guidance: Some("Catalog discovery: find nested tools by name and description in ALL_TOOLS.".to_string()),
+ mcp_typescript_preamble: Some("type CallToolResult<T = unknown> = { content: unknown[]; structuredContent?: T; isError?: boolean };".to_string()),
+ });
+ })
+ .build_with_auto_env(&server)
+ .await?;
+ let mock = mount_sse_sequence(
+ &server,
+ vec![
+ sse(vec![
+ ev_response_created("exec-response"),
+ ev_custom_tool_call(
+ "exec-call",
+ "exec",
+ "text('started'); yield_control(); text('finished');",
+ ),
+ ev_completed("exec-response"),
+ ]),
+ sse(vec![
+ ev_response_created("wait-response"),
+ ev_function_call_with_namespace(
+ "wait-call",
+ "functions",
+ "wait",
+ r#"{"cell_id":"1"}"#,
+ ),
+ ev_completed("wait-response"),
+ ]),
+ sse(vec![
+ ev_assistant_message("final", "The cell started, yielded, and finished."),
+ ev_completed("final-response"),
+ ]),
+ ],
+ )
+ .await;
+ test.submit_turn("Start a code cell, yield its initial output, then wait for its completion.")
+ .await?;
+ let requests = mock.requests();
+ assert!(requests[0].body_contains_text("Catalog discovery: find nested tools"));
+ assert!(requests[0].body_contains_text("type CallToolResult<T = unknown>"));
+ insta::assert_snapshot!(
+ "code_mode_catalog_messages",
+ context_snapshot::format_request_history_snapshot(
+ "Catalog Code Mode instructions and wait parameter descriptions accompany a yielded cell through completion.",
+ &requests,
+ &ContextSnapshotOptions::default().include_request_settings(),
+ )
+ );
+ Ok(())
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn astra_refreshes_plugin_tools_and_skills_in_an_existing_thread() -> Result<()> {
skip_if_no_network!(Ok(()));
diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__code_mode_catalog_messages.snap b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__code_mode_catalog_messages.snap
new file mode 100644
index 0000000000..bce83c9768
--- /dev/null
+++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__code_mode_catalog_messages.snap
@@ -0,0 +1,116 @@
+---
+source: core/tests/suite/scenarios.rs
+expression: "context_snapshot::format_request_history_snapshot(\"Catalog Code Mode instructions and wait parameter descriptions accompany a yielded cell through completion.\",\n&requests, &ContextSnapshotOptions::default().include_request_settings(),)"
+---
+Scenario: Catalog Code Mode instructions and wait parameter descriptions accompany a yielded cell through completion.
+
+## Window 1
+Settings:
+ include: ["reasoning.encrypted_content"]
+ instructions: You are Codex, an agent based on GPT-6. You and the user share one workspace, and your job is to collabo...them until their intended goal is completely handled. [hash=efa50f074efa5803]
+
+ # When to ask the user for permission
+
+ Use your best judgement given task context for when you really need user permission, like a competent co...ork without ending the turn to clarify with the user. [hash=ca7367e658b51388]
+
+ User authorization and preferences persist across turns. Do not request permission again when the user h... any guidelines provided in skills or external files. [hash=911f91c92c72882c]
+
+ <OMITTED 155 LINES; ~4895 TOKENS; hash=fd5ef18a80f62502>
+
+ - Skill naming: If a plugin contributes skills, those skill entries are prefixed with plugin_name: in the Skills list.
+ - MCP naming: Plugin-provided MCP tools keep standard MCP identifiers such as mcp__server__tool; use tool provenance to tell which plugin they come from.
+ - Trigger rules: If the user explicitly names a plugin, prefer capabilities associated with that plugin for that turn.
+ - Relationship to capabilities: Plugins are not invoked directly. Use their underlying skills, MCP tools, and app tools to help solve the task.
+ - Relevance: Determine what a plugin can help with from explicit user mention or from the plugin-associa..., MCP tools, and apps exposed elsewhere in this turn. [hash=620459a4e7b590f0]
+ - Missing/blocked: If the user requests a plugin that does not have relevant callable capabilities for t..., say so briefly and continue with the best fallback. [hash=746b0469a8f6cb3e]
+
+ model: "gpt-6-astra"
+ parallel_tool_calls: true
+ prompt_cache_key: "<PROMPT_CACHE_KEY 1>"
+ reasoning: {"effort":"low"}
+ store: false
+ stream: true
+ text: {"verbosity":"low"}
+ tool_choice: "auto"
+ tools (7; hash=7721dd8962991c5e):
+ - custom/exec: Catalog exec instructions. Default yield: 1234 ms. `image(imageUrlOrItem: string | { image_url: s...; hash=a49b91fd82908e18
+ - function/wait: Catalog wait instructions: resume the yielded cell.; args=[cell_id, max_tokens, terminate, yield_time_ms]; hash=67bc0f04da3505b3
+ - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
+ - function/request_user_input_async: Ask the user one or more questions during ongoing work. Use this tool only to request missing inf...; args=[questions]; hash=d6d74f33db330162
+ - namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
+ - function/sleep
+ - namespace/collaboration: Tools for spawning and managing sub-agents.; hash=b25b153d1e4097db
+ - function/followup_task
+ - function/interrupt_agent
+ - function/list_agents
+ - function/send_message
+ - function/spawn_agent
+ - function/wait_agent
+ - web_search; hash=e214d4db1bc49e89
+-- request 1 (turn) --
+00:message/developer[2]:
+ [01] <permissions instructions>
+ Filesystem sandboxing defines which files can be read or written. `sandbox_mode` is `danger-full-access`...ll commands are permitted. Network access is enabled. [hash=c134061cebb94a1b]
+ Approval policy is currently never. Do not provide the `sandbox_permissions` for any reason, commands will be rejected.
+ </permissions instructions>
+ [02] <collaboration_mode># Collaboration Mode: Default
+
+ You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
+
+ Your active mode changes only when new developer instructions with a different `<collaboration_mode>...<...by themselves. Known mode names are Default and Plan. [hash=e75f6b12fc52d812]
+
+ ## request_user_input availability
+
+ Use the `request_user_input` tool only when it is listed in the available tools for this turn.
+
+ In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions.
+
+ Use the `request_user_input` tool only for optional questions where the answer would materially improve the quality of the work.
+
+ If `request_user_input` returns no answers, continue with best judgment instead of asking again or treating the turn as blocked.
+
+ Never use the `request_user_input` tool for permission requests or permission-related escalations.
+
+ If explicit user input is required for another reason before progress can safely continue, do not use th... as a textual assistant message.</collaboration_mode> [hash=8213052bde4a62b2]
+01:message/developer:
+ <multi_agent_role>You are `/root`, the primary agent in a team of agents collaborating to fulfill the user's goals.
+
+ At the start of your turn, you are the active agent.
+ You can spawn sub-agents to handle subtasks, and those sub-agents can spawn their own sub-agents.
+ All agents in the team, including the agents that you can assign tasks to, are equally intelligent and capable, and have access to the same set of tools.
+
+ You can use `spawn_agent` to create a new agent, `followup_task` to give an existing agent a new task an...message to a running agent without triggering a turn. [hash=7d40ff8b58977202]
+ `send_message` calls may be read by a human, so ensure they are legible. Always put proper spaces between words and/or numbers.
+ <OMITTED 17 LINES; ~246 TOKENS; hash=780031e2df907944>
+ - All agents use the same current working directory.
+ - As a result, edits made by one agent are immediately visible to all other agents.
+
+ When calling `wait_agent`, prefer longer waits (minutes) to avoid busy polling.
+
+ There are 4 available concurrency slots, meaning that up to 4 agents can be active at once, including you.
+
+ Full-history forks (`fork_turns` omitted or `"all"`) inherit the parent model and reasoning effort and d...ne"` or a positive integer string.</multi_agent_role> [hash=c7f52e90688299ce]
+02:message/developer:
+ <multi_agent_mode>Any earlier instruction enabling proactive multi-agent delegation no longer applies. D...elegation, or parallel agent work.</multi_agent_mode> [hash=2b6e037067b4390c]
+03:message/user:
+ <environment_context>
+ <cwd><CWD></cwd>
+ <shell><HOST_SHELL></shell>
+ <current_date><CURRENT_DATE></current_date>
+ <timezone><HOST_TIMEZONE></timezone>
+ <filesystem><workspace_roots><root><CWD></root></workspace_roots><permission_profile type="disabled"><...e="unrestricted" /></permission_profile></filesystem> [hash=d40b2f45cb028888]
+ </environment_context>
+04:message/user:
+ Start a code cell, yield its initial output, then wait for its completion.
+-- request 2 (turn) --
+05:custom_tool_call/exec:text('started'); yield_control(); text('finished');
+06:custom_tool_call_output:Script running with cell ID 1
+ Wall time <DURATION> seconds
+ Output:
+ | started
+-- request 3 (turn) --
+07:function_call/functions.wait:{"cell_id":"1"}
+08:function_call_output:Script completed
+ Wall time <DURATION> seconds
+ Output:
+ | finished
diff --git a/codex-rs/core/tests/suite/step_settings.rs b/codex-rs/core/tests/suite/step_settings.rs
index bc419aa968..28f0d4a9a5 100644
--- a/codex-rs/core/tests/suite/step_settings.rs
+++ b/codex-rs/core/tests/suite/step_settings.rs
@@ -35,6 +35,7 @@ use codex_protocol::models::PermissionProfile;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ApplyPatchToolType;
use codex_protocol::openai_models::ApprovalMessages;
+use codex_protocol::openai_models::CodeModeToolMessages;
use codex_protocol::openai_models::CollaborationModeMessages;
use codex_protocol::openai_models::ConfigShellToolType;
use codex_protocol::openai_models::ConfirmationPolicies;
@@ -2254,6 +2255,16 @@ async fn tool_messages_follow_mid_turn_model_changes() -> Result<()> {
"additionalProperties": false,
})
};
+ let wait_parameters = |model: &str| {
+ json!({
+ "type": "object",
+ "properties": {
+ "cell_id": {"type": "string", "description": format!("Cell on {model}.")},
+ },
+ "required": ["cell_id"],
+ "additionalProperties": false,
+ })
+ };
let server = start_mock_server().await;
let response_mock = mount_sse_sequence(
&server,
@@ -2270,12 +2281,16 @@ async fn tool_messages_follow_mid_turn_model_changes() -> Result<()> {
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
config.multi_agent_v2.expose_spawn_agent_model_overrides = false;
+ config.multi_agent_v2.non_code_mode_only = true;
+ config.code_mode.disable_in_process_fallback = true;
for model in &mut config
.model_catalog
.as_mut()
.expect("controlled model catalog")
.models
{
+ model.tool_mode = Some(ToolMode::CodeMode);
+ model.use_responses_lite = false;
model
.experimental_supported_tools
.push("send_user_message_async".to_string());
@@ -2302,6 +2317,17 @@ async fn tool_messages_follow_mid_turn_model_changes() -> Result<()> {
interrupt_agent: tool_message("interrupt_agent"),
list_agents: tool_message("list_agents"),
}),
+ code_mode: Some(CodeModeToolMessages {
+ exec: Some(ToolMessage {
+ description: Some(format!("Exec description for {}.", model.slug)),
+ ..Default::default()
+ }),
+ wait: Some(ToolMessage {
+ description: Some(format!("Wait description for {}.", model.slug)),
+ parameters: Some(wait_parameters(&model.slug).to_string()),
+ }),
+ ..Default::default()
+ }),
});
}
})
@@ -2331,12 +2357,10 @@ async fn tool_messages_follow_mid_turn_model_changes() -> Result<()> {
.iter()
.map(|request| {
let body = request.body_json();
- let tool = body["tools"]
- .as_array()
- .expect("request tools")
- .iter()
- .find(|tool| tool["name"] == "request_user_input_async")
- .expect("async message tool");
+ let tool = |name: &str| {
+ body["tools"].as_array().expect("request tools")
+ .iter().find(|tool| tool["name"] == name).expect(name)
+ };
let multi_agent_messages = MULTI_AGENT_TOOLS.map(|name| {
let tool = namespace_child_tool(&body, "collaboration", name).expect(name);
(name.to_string(), json!({
@@ -2346,8 +2370,11 @@ async fn tool_messages_follow_mid_turn_model_changes() -> Result<()> {
}).into_iter().collect::<serde_json::Map<String, Value>>();
json!({
"model": body["model"],
- "async_description": tool["description"],
+ "async_description": tool("request_user_input_async")["description"],
"multi_agent_messages": multi_agent_messages,
+ "exec_description": tool("exec")["description"],
+ "wait_description": tool("wait")["description"],
+ "wait_parameters": tool("wait")["parameters"],
})
})
.collect::<Vec<_>>(),
@@ -2362,6 +2389,9 @@ async fn tool_messages_follow_mid_turn_model_changes() -> Result<()> {
})))
.into_iter()
.collect::<serde_json::Map<String, Value>>(),
+ "exec_description": format!("Exec description for {model}."),
+ "wait_description": format!("Wait description for {model}."),
+ "wait_parameters": wait_parameters(model),
}))
.to_vec(),
);
diff --git a/codex-rs/models-manager/src/model_info_tests.rs b/codex-rs/models-manager/src/model_info_tests.rs
index 7cb82c7ab9..1d712bce77 100644
--- a/codex-rs/models-manager/src/model_info_tests.rs
+++ b/codex-rs/models-manager/src/model_info_tests.rs
@@ -95,6 +95,7 @@ fn base_instruction_override_is_literal_and_preserves_catalog_messages() {
}),
..Default::default()
}),
+ ..Default::default()
}),
instructions_template: Some("template".to_string()),
instructions_variables: Some(ModelInstructionsVariables {
@@ -168,6 +169,7 @@ fn personality_none_strips_catalog_instruction_sources_through_the_next_h1() {
}),
..Default::default()
}),
+ ..Default::default()
}),
approvals: Some(ApprovalMessages {
on_request: Some("user approvals".to_string()),
diff --git a/codex-rs/prompts/src/model_messages.rs b/codex-rs/prompts/src/model_messages.rs
index e774d1264d..ac6ec4042c 100644
--- a/codex-rs/prompts/src/model_messages.rs
+++ b/codex-rs/prompts/src/model_messages.rs
@@ -3,6 +3,7 @@
//! Prompt composition and runtime settings remain with consumers; each accessor
//! selects and resolves only the requested message family.
+use codex_protocol::openai_models::CodeModeToolMessages;
use codex_protocol::openai_models::ConfirmationPolicies;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelMessages;
@@ -180,6 +181,21 @@ impl<'a> ResolvedModelMessages<'a> {
tool.as_ref()
}
+ /// Selects Code Mode messages; bundled text and runtime composition belong to the tool owner.
+ pub fn code_mode(&self) -> Option<&'a CodeModeToolMessages> {
+ self.catalog_messages?.tools.as_ref()?.code_mode.as_ref()
+ }
+
+ /// Selects wait's complete description.
+ pub fn code_mode_wait_description_override(&self) -> Option<&'a str> {
+ self.code_mode()?.wait.as_ref()?.description.as_deref()
+ }
+
+ /// Selects wait's parameter schema. Exec uses a harness-owned freeform grammar.
+ pub fn code_mode_wait_parameters_override(&self) -> Option<&'a str> {
+ self.code_mode()?.wait.as_ref()?.parameters.as_deref()
+ }
+
/// Resolves persistent-mode instructions without deciding whether the mode is active.
pub fn persistent_instructions(&self) -> &'a str {
self.catalog_messages
diff --git a/codex-rs/protocol/src/openai_models.rs b/codex-rs/protocol/src/openai_models.rs
index 41b2a60dd5..b917fb2fc4 100644
--- a/codex-rs/protocol/src/openai_models.rs
+++ b/codex-rs/protocol/src/openai_models.rs
@@ -582,6 +582,8 @@ pub struct ToolMessages {
pub send_user_message_async: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub multi_agent: Option<MultiAgentToolMessages>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub code_mode: Option<CodeModeToolMessages>,
}
/// Model-owned messages for a built-in tool.
@@ -591,7 +593,7 @@ pub struct ToolMessage {
/// text without disabling the tool. Tool-owned runtime guidance is retained.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
- /// Complete JSON Schema encoded as a string. Consumed by Multi-Agent V2 tools only.
+ /// Complete JSON Schema encoded as a string. Consumed by Multi-Agent V2 tools and Code Mode wait.
/// Uses the harness's supported schema subset; unrecognized keywords are ignored.
/// Missing, null, invalid or unsupported structures, or a root without `type: "object"`
/// retains the harness parameters. Schema semantics must remain API-compatible.
@@ -620,6 +622,28 @@ pub struct MultiAgentToolMessages {
pub list_agents: Option<ToolMessage>,
}
+/// Model-owned instructions for Code Mode's exec and wait tools.
+#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
+pub struct CodeModeToolMessages {
+ /// Instructional template supporting `{{ default_exec_yield_time_ms }}` and `{{ image_helper }}`.
+ /// Runtime tool declarations are appended. Unknown placeholders remain literal.
+ /// Exec accepts raw JavaScript; `parameters` is not consumed and its grammar is unchanged.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub exec: Option<ToolMessage>,
+ /// Complete description and JSON parameter schema, selected independently.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub wait: Option<ToolMessage>,
+ /// Literal guidance appended when deferred nested tools exist.
+ /// Missing or null uses bundled text; an empty string omits the section.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub deferred_nested_tools_guidance: Option<String>,
+ /// Literal shared TypeScript definitions, emitted when Code Mode Only exposes MCP results.
+ /// Missing or null uses bundled definitions; an empty string omits the section.
+ /// Custom definitions must remain compatible with the generated tool declarations.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub mcp_typescript_preamble: Option<String>,
+}
+
/// Model-owned defaults for the context-window token-budget feature.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ModelTokenBudgetConfig {
@@ -1416,6 +1440,7 @@ mod tests {
}),
..Default::default()
}),
+ ..Default::default()
}),
instructions_template: None,
instructions_variables: None,