Expose TypeScript signatures in Code Mode's ALL_TOOLS (#64939)

## Why

Code Mode embeds TypeScript declarations in tool descriptions, so scripts
that want to inspect a tool's argument and return types have to extract
the declaration from the description.

## What changed

Enable `features.code_mode_all_tools_schema` to expose callable names,
descriptions, and TypeScript signatures as separate fields in `ALL_TOOLS`.
Update the `exec` guidance to match the selected format, including when
resuming a session. The flag is off by default.

Carry signatures over gRPC and stdio. Reject execution requests with
signatures when the host does not advertise support for them.

## Testing

Add coverage for both catalog formats, `exec` guidance on resume, and
signature preservation over gRPC and stdio.

GitOrigin-RevId: dedaeec4a2563c23d432c324187ef20f6a0e5ea3
This commit is contained in:
Alex Daley
2026-12-01 06:54:13 +00:00
committed by copyberry
parent 936ac6dbe6
commit a54018ff36
45 changed files with 703 additions and 37 deletions
+1
View File
@@ -2936,6 +2936,7 @@ version = "0.0.0"
dependencies = [
"codex-protocol",
"glob",
"insta",
"pretty_assertions",
"prost",
"protoc-bin-vendored",
@@ -85,6 +85,7 @@ fn tool_definition(definition: proto::ToolDefinition) -> Result<ToolDefinition,
}
},
input_schema: json_field(definition.input_schema_json, "input schema")?,
signature: definition.signature,
input_schema_max_bytes: None,
output_schema: json_field(definition.output_schema_json, "output schema")?,
})
@@ -38,6 +38,7 @@ fn rejects_missing_names_unknown_tool_kinds_and_invalid_json_schemas() {
tool_name: None,
description: String::new(),
kind: proto::ToolKind::Function as i32,
signature: None,
input_schema_json: None,
output_schema_json: None,
};
@@ -120,6 +120,7 @@ pub(super) fn tool(name: &str) -> proto::ToolDefinition {
}),
description: String::new(),
kind: proto::ToolKind::Function as i32,
signature: None,
input_schema_json: None,
output_schema_json: None,
}
@@ -132,6 +132,7 @@ impl GrpcHostState {
events
.try_send(Ok(proto::SessionEvent {
event: Some(proto::session_event::Event::Opened(proto::SessionOpened {
supports_tool_catalog_signature: true,
session_id: id.to_string(),
supports_catalog_revision: true,
output_truncation: match session.runtime.output_truncation() {
@@ -92,6 +92,7 @@ async fn assert_shared_capacity(
tool_name: ToolName::plain("block"),
description: String::new(),
kind: CodeModeToolKind::Function,
signature: None,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
+44
View File
@@ -135,6 +135,7 @@ fn tool(name: &str) -> ToolDefinition {
description: String::new(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}
@@ -1651,3 +1652,46 @@ async fn unix_socket_endpoints_execute_code_mode_cells() -> Result<()> {
server.abort();
Ok(())
}
#[tokio::test]
async fn grpc_preserves_structured_all_tools_metadata() -> Result<()> {
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
let session = provider
.create_session()
.await
.map_err(anyhow::Error::msg)?;
let mut request = request("text(ALL_TOOLS);");
let mut echo = tool("echo");
echo.description = "Echo tool guidance".to_string();
echo.signature = Some("echo(args: { value: string }): Promise<string>;".to_string());
request.enabled_tools = vec![echo, tool("legacy")];
let actual = execute(&session, request, Arc::new(RecordingDelegate::default())).await?;
let RuntimeResponse::Result {
content_items,
error_text: None,
..
} = actual
else {
panic!("catalog execution failed: {actual:?}");
};
let [FunctionCallOutputContentItem::InputText { text }] = content_items.as_slice() else {
panic!("unexpected catalog output: {content_items:?}");
};
assert_eq!(
serde_json::from_str::<serde_json::Value>(text)?,
json!([
{
"name": "echo",
"description": "Echo tool guidance",
"signature": "echo(args: { value: string }): Promise<string>;"
},
{
"name": "legacy",
"description": ""
}
])
);
session.shutdown().await.map_err(anyhow::Error::msg)?;
Ok(())
}
+1
View File
@@ -77,6 +77,7 @@ async fn assert_partial_results(provider: &dyn CodeModeSessionProvider) {
description: String::new(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}],
+17 -5
View File
@@ -240,6 +240,7 @@ async fn interrupt_yields_observations_without_stopping_the_cell() {
description: String::new(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}];
@@ -428,7 +429,9 @@ async fn remote_session_persists_values_forwards_delegates_and_controls_cells()
let mut callback_request = execute_request(
r#"
const result = await tools.echo({ value: String(load("key")) });
const echo = ALL_TOOLS.find(tool => tool.name === "echo");
text(echo);
const result = await tools[echo.name]({ value: String(load("key")) });
notify("notice");
text(result.value);
"#,
@@ -437,9 +440,10 @@ text(result.value);
callback_request.enabled_tools = vec![ToolDefinition {
name: "echo".to_string(),
tool_name: ToolName::plain("echo"),
description: String::new(),
description: "Echo tool guidance".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: Some("echo(args: { value: string }): Promise<unknown>;".to_string()),
input_schema_max_bytes: None,
output_schema: None,
}];
@@ -449,9 +453,14 @@ text(result.value);
RuntimeResponse::Result {
code_mode_host_duration: actual.code_mode_host_duration(),
cell_id: cell_id("g2:2"),
content_items: vec![FunctionCallOutputContentItem::InputText {
text: "output".to_string(),
}],
content_items: vec![
FunctionCallOutputContentItem::InputText {
text: r#"{"name":"echo","description":"Echo tool guidance","signature":"echo(args: { value: string }): Promise<unknown>;"}"#.to_string(),
},
FunctionCallOutputContentItem::InputText {
text: "output".to_string(),
},
],
result_buffered_for: Duration::ZERO,
error_text: None,
}
@@ -645,6 +654,7 @@ return;
description: String::new(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
})
@@ -783,6 +793,7 @@ async fn oversized_delegate_payloads_fail_only_the_tool_call() {
description: String::new(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
};
@@ -990,6 +1001,7 @@ async fn child_process_loss_cleans_up_and_rebuilds_the_shared_host() {
description: String::new(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}];
+1
View File
@@ -32,5 +32,6 @@ tonic-prost-build = { version = "=0.14.3", default-features = false, features =
ignored = ["prost", "tonic-prost"]
[dev-dependencies]
insta = { workspace = true }
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
@@ -0,0 +1,8 @@
//! Selects how Code Mode presents tool metadata in ALL_TOOLS and its prompt.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ToolCatalogFormat {
#[default]
Legacy,
Structured,
}
+79 -23
View File
@@ -21,12 +21,13 @@ Tool availability can change between calls."#;
pub const TOOL_SEARCH_GUIDANCE: &str = r#"Use `await tools.tool_search({query: "...", limit: 8})` for BM25-ranked discovery of deferred tools (up to `limit` matches; 8 by default). It returns `{tools: [{name, description}]}` with callable names and full TypeScript declarations. Print results with `text()` and inspect unfamiliar declarations before calling `tools[result.name](arguments)` in a later execution."#;
const LEGACY_IMAGE_HELPER_DESCRIPTION: &str = r#"`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."#;
const UNIFIED_IMAGE_HELPER_DESCRIPTION: &str = r#"`image(imageUrlOrItem: string | { image_url: string } | ImageContent)`: 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])`."#;
const EXEC_DESCRIPTION_TEMPLATE: &str = r#"Run JavaScript code to orchestrate/compose tool calls
const EXEC_DESCRIPTION_INTRO: &str = r#"Run JavaScript code to orchestrate/compose tool calls
- Evaluates the provided JavaScript code in a fresh V8 isolate as an async module.
- All nested tools are available on the global `tools` object, for example `await tools.exec_command(...)`. Tool names are exposed as normalized JavaScript identifiers, for example `await tools.mcp__ologs__get_profile(...)`.
- Nested tool methods take either a string or an object as their input argument.
- Nested tools return either an object or a string, based on the description.
- Runs raw JavaScript -- no Node, no file system, no network access, no console.
- All nested tools are available on the global `tools` object, for example `await tools.exec_command(...)`. Tool names are exposed as normalized JavaScript identifiers, for example `await tools.mcp__ologs__get_profile(...)`."#;
const LEGACY_NESTED_TOOL_TYPES: &str = r#"- Nested tool methods take either a string or an object as their input argument.
- Nested tools return either an object or a string, based on the description."#;
const SIGNATURE_NESTED_TOOL_TYPES: &str = "- Nested tools take a string or an object. Each tool’s signature shows its argument and return types.";
const EXEC_DESCRIPTION_BODY_TEMPLATE: &str = r#"- 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 {{ default_exec_yield_time_ms }} ms.
@@ -42,9 +43,11 @@ const EXEC_HELPERS_TEMPLATE: &str = r#"- Global helpers:
- `load(key: string)`: returns the stored value for a string key, or `undefined` if it is missing.
- `notify(value: string | number | boolean | undefined | null)`: immediately injects an extra `custom_tool_call_output` for the current `exec` call. Values are stringified like `text(...)`.
- `setTimeout(callback: () => void, delayMs?: number)`: schedules a callback to run later and returns a timeout id. Pending timeouts do not keep `exec` alive by themselves; await an explicit promise if you need to wait for one.
- `clearTimeout(timeoutId?: number)`: cancels a timeout created by `setTimeout`.
- `ALL_TOOLS`: metadata for the enabled nested tools as `{ name, description }` entries.
- `yield_control()`: yields the accumulated output to the model immediately while the script keeps running."#;
- `clearTimeout(timeoutId?: number)`: cancels a timeout created by `setTimeout`."#;
const LEGACY_ALL_TOOLS: &str =
"- `ALL_TOOLS`: metadata for the enabled nested tools as `{ name, description }` entries.";
const SIGNATURE_ALL_TOOLS: &str = "- `ALL_TOOLS`: metadata for the enabled nested tools as `{ name, description, signature }` entries.";
const EXEC_YIELD_CONTROL_GUIDANCE: &str = "- `yield_control()`: yields the accumulated output to the model immediately while the script keeps running.";
const WAIT_DESCRIPTION_TEMPLATE: &str = r#"- Use `wait` only after `exec` returns `Script running with cell ID ...`.
- `cell_id` identifies the running `exec` cell to resume.
- `yield_time_ms` controls how long to wait for more output before yielding again. Defaults to 10000 ms.
@@ -146,6 +149,9 @@ pub struct ToolDefinition {
pub tool_name: ToolName,
pub description: String,
pub kind: CodeModeToolKind,
/// When present, ALL_TOOLS exposes this TypeScript signature separately from the description.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signature: Option<String>,
pub input_schema: Option<JsonValue>,
/// Internal budget used while rendering the input declaration, before sending it to the host.
#[serde(skip)]
@@ -171,7 +177,7 @@ pub struct ExecDefinition {
#[derive(Debug, Default)]
pub struct ExecDefinitions {
pub entries: Vec<ExecDefinition>,
/// Newline-separated signatures of the global helpers inserted by the renderer.
/// Newline-separated helper signatures and catalog format markers used to refresh exec.
pub helper_signatures: String,
}
@@ -302,6 +308,7 @@ pub fn build_exec_tool_description_and_definitions(
image_detail_visibility: ImageDetailVisibility,
deferred_tool_discovery: DeferredToolDiscovery,
incremental_exec_enabled: bool,
catalog_format: crate::ToolCatalogFormat,
messages: Option<&CodeModeToolMessages>,
) -> (String, ExecDefinitions) {
let mut sections = Vec::new();
@@ -309,6 +316,10 @@ pub fn build_exec_tool_description_and_definitions(
ImageDetailVisibility::Visible => LEGACY_IMAGE_HELPER_DESCRIPTION,
ImageDetailVisibility::Hidden => UNIFIED_IMAGE_HELPER_DESCRIPTION,
};
let (nested_tool_types, all_tools) = match catalog_format {
crate::ToolCatalogFormat::Legacy => (LEGACY_NESTED_TOOL_TYPES, LEGACY_ALL_TOOLS),
crate::ToolCatalogFormat::Structured => (SIGNATURE_NESTED_TOOL_TYPES, SIGNATURE_ALL_TOOLS),
};
const IMAGE_HELPER_PLACEHOLDER: &str = "{{ image_helper }}";
let yield_time = default_exec_yield_time_ms.to_string();
let render = |template: &str| {
@@ -325,14 +336,21 @@ pub fn build_exec_tool_description_and_definitions(
if !description.is_empty() {
sections.push(description);
}
if catalog_format == crate::ToolCatalogFormat::Structured {
sections.push(all_tools.to_string());
}
if incremental_exec_enabled && template.contains(IMAGE_HELPER_PLACEHOLDER) {
definitions.helper_signatures = helper_signature(image_helper)
.unwrap_or_default()
.to_owned();
}
} else {
sections.push(render(EXEC_DESCRIPTION_TEMPLATE));
let body = render(EXEC_DESCRIPTION_BODY_TEMPLATE);
sections.push(format!(
"{EXEC_DESCRIPTION_INTRO}\n{nested_tool_types}\n{body}"
));
let helpers = render(EXEC_HELPERS_TEMPLATE);
let helpers = format!("{helpers}\n{all_tools}\n{EXEC_YIELD_CONTROL_GUIDANCE}");
if incremental_exec_enabled {
definitions.helper_signatures = helpers
.lines()
@@ -342,6 +360,16 @@ pub fn build_exec_tool_description_and_definitions(
}
sections.push(helpers);
}
// The helper name is ALL_TOOLS in both formats. Only tag the new shape so
// existing legacy snapshots keep their original refresh key on resume.
if incremental_exec_enabled && catalog_format == crate::ToolCatalogFormat::Structured {
if !definitions.helper_signatures.is_empty() {
definitions.helper_signatures.push('\n');
}
definitions
.helper_signatures
.push_str("ALL_TOOLS:signature");
}
let default_guidance = match deferred_tool_discovery {
// In Code Mode Only, the enabled search tool's description is rendered below.
DeferredToolDiscovery::RankedSearch if !code_mode_only => {
@@ -485,11 +513,14 @@ pub fn enabled_tool_metadata(definition: &ToolDefinition) -> EnabledToolMetadata
global_name: normalize_code_mode_identifier(&definition.name),
description: definition.description.clone(),
kind: definition.kind,
signature: definition.signature.clone(),
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct EnabledToolMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub signature: Option<String>,
pub tool_name: ToolName,
pub global_name: String,
pub description: String,
@@ -503,14 +534,22 @@ pub fn render_code_mode_sample(
input_type: String,
output_type: String,
) -> String {
let declaration = format!(
"declare const tools: {{ {} }};",
render_code_mode_tool_declaration(tool_name, input_name, &input_type, &output_type)
);
format!("{description}\n\nexec tool declaration:\n```ts\n{declaration}\n```")
let signature = render_method_signature(tool_name, input_name, &input_type, &output_type);
render_description_with_signature(description, &signature)
}
fn render_code_mode_sample_for_definition(definition: &ToolDefinition) -> String {
let signature = render_code_mode_signature(definition);
render_description_with_signature(&definition.description, &signature)
}
fn render_description_with_signature(description: &str, signature: &str) -> String {
format!(
"{description}\n\nexec tool declaration:\n```ts\ndeclare const tools: {{ {signature} }};\n```"
)
}
pub fn render_code_mode_signature(definition: &ToolDefinition) -> String {
let input_name = match definition.kind {
CodeModeToolKind::Function => "args",
CodeModeToolKind::Freeform => "input",
@@ -542,16 +581,10 @@ fn render_code_mode_sample_for_definition(definition: &ToolDefinition) -> String
.map(render_json_schema_to_typescript)
.unwrap_or_else(|| "unknown".to_string())
};
render_code_mode_sample(
&definition.description,
&definition.name,
input_name,
input_type,
output_type,
)
render_method_signature(&definition.name, input_name, &input_type, &output_type)
}
fn render_code_mode_tool_declaration(
fn render_method_signature(
tool_name: &str,
input_name: &str,
input_type: &str,
@@ -700,6 +733,7 @@ mod tests {
"required": ["city"],
"additionalProperties": false
})),
signature: None,
input_schema_max_bytes: None,
output_schema: Some(json!({
"type": "object",
@@ -741,6 +775,7 @@ mod tests {
},
"required": ["weather"]
})),
signature: None,
input_schema_max_bytes: None,
output_schema: Some(json!({
"type": "object",
@@ -778,6 +813,7 @@ mod tests {
"properties": {},
"additionalProperties": false
})),
signature: None,
input_schema_max_bytes: None,
output_schema: Some(mcp_call_tool_result_schema(json!({
"type": "object",
@@ -818,6 +854,7 @@ mod tests {
description: "bar".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}],
@@ -828,6 +865,7 @@ mod tests {
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
/*messages*/ None,
);
assert!(definitions.entries.is_empty());
@@ -849,6 +887,7 @@ bar"
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
/*messages*/ None,
);
assert!(description.contains("`audio(audioUrlOrItem:"));
@@ -877,6 +916,7 @@ bar"
"required": ["city"],
"additionalProperties": false
})),
signature: None,
input_schema_max_bytes: None,
output_schema: Some(mcp_call_tool_result_schema(json!({
"type": "object",
@@ -895,6 +935,7 @@ bar"
"properties": {},
"additionalProperties": false
})),
signature: None,
input_schema_max_bytes: None,
output_schema: Some(mcp_call_tool_result_schema(json!({
"type": "object",
@@ -912,6 +953,7 @@ bar"
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ true,
crate::ToolCatalogFormat::Legacy,
/*messages*/ None,
);
assert_eq!(description.matches("## mcp__sample").count(), 1);
@@ -963,6 +1005,7 @@ bar"
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ true,
crate::ToolCatalogFormat::Legacy,
/*messages*/ None,
);
assert_eq!(description.matches("## mcp__sample").count(), 2);
@@ -996,6 +1039,7 @@ bar"
"properties": {},
"additionalProperties": false
})),
signature: None,
input_schema_max_bytes: None,
output_schema: Some(mcp_call_tool_result_schema(json!({
"type": "object",
@@ -1010,6 +1054,7 @@ bar"
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
/*messages*/ None,
);
@@ -1029,6 +1074,7 @@ bar"
"properties": {},
"additionalProperties": false
})),
signature: None,
input_schema_max_bytes: None,
output_schema: Some(json!({
"type": "object",
@@ -1064,6 +1110,7 @@ bar"
"properties": {},
"additionalProperties": false
})),
signature: None,
input_schema_max_bytes: None,
output_schema: Some(json!({
"type": "object",
@@ -1098,6 +1145,7 @@ bar"
description: "First tool".to_string(),
kind: first_tool.kind,
input_schema: first_tool.input_schema,
signature: None,
input_schema_max_bytes: None,
output_schema: first_tool.output_schema,
},
@@ -1107,6 +1155,7 @@ bar"
description: "Second tool".to_string(),
kind: second_tool.kind,
input_schema: second_tool.input_schema,
signature: None,
input_schema_max_bytes: None,
output_schema: second_tool.output_schema,
},
@@ -1118,6 +1167,7 @@ bar"
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
/*messages*/ None,
);
@@ -1142,6 +1192,7 @@ bar"
"properties": {},
"additionalProperties": false
})),
signature: None,
input_schema_max_bytes: None,
output_schema: Some(mcp_call_tool_result_schema(json!({
"type": "object",
@@ -1159,6 +1210,7 @@ bar"
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
/*messages*/ None,
);
@@ -1175,6 +1227,7 @@ bar"
description: "Deferred tool".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}];
@@ -1184,6 +1237,7 @@ bar"
description: super::TOOL_SEARCH_GUIDANCE.to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
};
@@ -1205,6 +1259,7 @@ bar"
ImageDetailVisibility::Visible,
discovery,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
/*messages*/ None,
);
assert!(description.contains("Some deferred nested tools may be omitted"));
@@ -1223,6 +1278,7 @@ bar"
ImageDetailVisibility::Visible,
discovery,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
/*messages*/ None,
);
assert_eq!(description, empty_catalog_description);
@@ -38,6 +38,7 @@ fn exec_override_renders_only_known_literal_placeholders() {
image_detail_visibility,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ true,
crate::ToolCatalogFormat::Legacy,
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 ".into()),
@@ -70,6 +71,7 @@ fn exec_override_preserves_empty_and_whitespace_only_text() {
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(description_override.into()),
@@ -102,6 +104,7 @@ fn exec_override_preserves_runtime_sections() {
description: "First tool".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}];
@@ -111,6 +114,7 @@ fn exec_override_preserves_runtime_sections() {
description: "Deferred tool".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: Some(json!({
"type": "object",
@@ -161,6 +165,7 @@ fn exec_override_preserves_runtime_sections() {
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some("".into()),
@@ -185,6 +190,7 @@ fn ranked_search_guidance_honors_overrides() {
description: "Deferred tool".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}];
@@ -210,6 +216,7 @@ fn ranked_search_guidance_honors_overrides() {
ImageDetailVisibility::Visible,
DeferredToolDiscovery::RankedSearch,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some("".into()),
@@ -233,6 +240,7 @@ fn mcp_types_stay_stable_when_a_deferred_tool_changes_its_output_schema() {
description: "Deferred tool".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
};
@@ -246,6 +254,7 @@ fn mcp_types_stay_stable_when_a_deferred_tool_changes_its_output_schema() {
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
Some(&CodeModeToolMessages {
mcp_typescript_preamble: preamble.map(Into::into),
..Default::default()
@@ -278,6 +287,7 @@ fn nested_guidance_survives_catalog_changes_and_respects_overrides() {
description: "Echo a value.".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}];
@@ -291,6 +301,7 @@ fn nested_guidance_survives_catalog_changes_and_respects_overrides() {
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Legacy,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some("".into()),
@@ -316,3 +327,103 @@ fn nested_guidance_survives_catalog_changes_and_respects_overrides() {
}
assert!(DEFERRED_NESTED_TOOLS_GUIDANCE.contains("Tool availability can change between calls"));
}
#[test]
fn exec_catalog_guidance_matches_the_selected_format() {
let catalog_guidance = |format| {
let (description, _) = build_exec_tool_description_and_definitions(
&[],
&[],
&BTreeMap::new(),
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ false,
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
format,
/*messages*/ None,
);
description
.lines()
.filter(|line| {
line.starts_with("- Nested tool")
|| line.starts_with("- `ALL_TOOLS`")
|| line.starts_with("To find one,")
})
.collect::<Vec<_>>()
.join("\n")
};
insta::assert_snapshot!(catalog_guidance(crate::ToolCatalogFormat::Legacy), @r"
- Nested tool methods take either a string or an object as their input argument.
- Nested tools return either an object or a string, based on the description.
- `ALL_TOOLS`: metadata for the enabled nested tools as `{ name, description }` entries.
To find one, filter `ALL_TOOLS` by `name` and `description`.
");
insta::assert_snapshot!(catalog_guidance(crate::ToolCatalogFormat::Structured), @r"
- Nested tools take a string or an object. Each tool’s signature shows its argument and return types.
- `ALL_TOOLS`: metadata for the enabled nested tools as `{ name, description, signature }` entries.
To find one, filter `ALL_TOOLS` by `name` and `description`.
");
}
#[test]
fn structured_catalog_guidance_accompanies_custom_exec_descriptions() {
let (description, _) = build_exec_tool_description_and_definitions(
&[],
&[],
&BTreeMap::new(),
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ false,
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
crate::ToolCatalogFormat::Structured,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some("Custom execution guidance.".into()),
..Default::default()
}),
..Default::default()
}),
);
assert!(description.starts_with("Custom execution guidance.\n\n"));
assert!(description.contains("{ name, description, signature }"));
assert!(description.ends_with(DEFERRED_NESTED_TOOLS_GUIDANCE));
}
#[test]
fn catalog_format_refreshes_custom_exec_descriptions() {
let image_signature = super::helper_signature(LEGACY_IMAGE_HELPER_DESCRIPTION).unwrap();
for (template, original) in [
("Run JavaScript.", ""),
("Run JavaScript. {{ image_helper }}", image_signature),
] {
let messages = CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(template.into()),
..Default::default()
}),
..Default::default()
};
let render = |format| {
build_exec_tool_description_and_definitions(
&[],
&[],
&BTreeMap::new(),
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ true,
format,
Some(&messages),
)
};
let (_, legacy) = render(crate::ToolCatalogFormat::Legacy);
let (description, structured) = render(crate::ToolCatalogFormat::Structured);
assert_eq!(legacy.helper_signatures, original);
assert_ne!(structured.helper_signatures, legacy.helper_signatures);
assert!(!description.contains("ALL_TOOLS:signature"));
}
}
@@ -97,6 +97,8 @@ message SessionOpened {
optional OutputTruncation output_truncation = 2;
// Clients may send ExecuteRequest.catalog_revision when advertised.
bool supports_catalog_revision = 3;
// Whether the host exposes a separate signature on ALL_TOOLS entries.
bool supports_tool_catalog_signature = 4;
}
message CloseSessionRequest {
@@ -299,6 +301,8 @@ message ToolDefinition {
ToolKind kind = 4;
optional bytes input_schema_json = 5;
optional bytes output_schema_json = 6;
reserved 7;
optional string signature = 8;
}
message ToolName {
+3
View File
@@ -1,3 +1,4 @@
mod catalog;
mod description;
pub mod grpc;
pub mod host;
@@ -8,6 +9,7 @@ mod runtime;
mod session;
mod shared_catalog;
pub use catalog::ToolCatalogFormat;
pub use description::CODE_MODE_PRAGMA_PREFIX;
pub use description::CodeModeToolKind;
pub use description::DeferredToolDiscovery;
@@ -26,6 +28,7 @@ pub use description::is_code_mode_nested_tool;
pub use description::normalize_code_mode_identifier;
pub use description::parse_exec_source;
pub use description::render_code_mode_sample;
pub use description::render_code_mode_signature;
pub use json_schema_types::DEFAULT_INPUT_SCHEMA_MAX_BYTES;
pub use json_schema_types::render_json_schema_to_typescript;
pub use process_metrics::CodeModeProcessMetrics;
@@ -114,6 +114,7 @@ clearTimeout(earlyTimer); setTimeout(() => {}, 60000);
stored_values: HashMap::new(),
stored_value_writes: HashMap::new(),
enabled_tools: Arc::from([Arc::new(EnabledToolMetadata {
signature: None,
global_name: "echo".into(),
description: String::new(),
tool_name,
@@ -166,6 +166,9 @@ fn build_all_tools_value<'s>(
let description_key = v8::String::new(scope, "description")
.ok_or_else(|| "failed to allocate ALL_TOOLS description key".to_string())?;
let signature_key = v8::String::new(scope, "signature")
.ok_or_else(|| "failed to allocate ALL_TOOLS signature key".to_string())?;
for tool in enabled_tools {
let item = v8::Object::new(scope);
let name = v8::String::new(scope, &tool.global_name)
@@ -181,6 +184,15 @@ fn build_all_tools_value<'s>(
{
return Err("failed to set ALL_TOOLS description".to_string());
}
if let Some(signature) = &tool.signature {
let signature = v8::String::new(scope, signature)
.ok_or_else(|| "failed to allocate ALL_TOOLS signature".to_string())?;
if item.create_data_property(scope, signature_key.into(), signature.into())
!= Some(true)
{
return Err("failed to set ALL_TOOLS signature".to_string());
}
}
items.push(item.into());
}
@@ -114,6 +114,7 @@ impl InProcessCodeModeSession {
global_name: normalize_code_mode_identifier(&tool.name),
tool_name: tool.tool_name,
description: tool.description,
signature: tool.signature,
kind: tool.kind,
})
.collect();
@@ -174,6 +174,7 @@ fn blocking_tool() -> ToolDefinition {
description: String::new(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}
@@ -543,6 +543,7 @@ fn echo_tool() -> ToolDefinition {
description: String::new(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}
@@ -62,6 +62,7 @@ fn definition(binding: &str, tool_name: ToolName) -> ToolDefinition {
tool_name,
description: String::new(),
kind: CodeModeToolKind::Function,
signature: None,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
@@ -149,6 +150,7 @@ async fn preloads_follow_the_session_and_the_current_cells_tool_binding() {
tool_name: ToolName::plain(name),
description: String::new(),
kind: CodeModeToolKind::Function,
signature: None,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
@@ -75,6 +75,7 @@ fn session(client: GrpcClient) -> Arc<SessionInner> {
let client = Arc::new(client);
Arc::new(SessionInner {
catalog: None,
supports_tool_catalog_signature: true,
id: "session".to_string(),
output_truncation: CodeModeOutputTruncation::Client,
route: None,
@@ -59,6 +59,7 @@ fn tool_definition(definition: ToolDefinition) -> Result<grpc::ToolDefinition, S
namespace: definition.tool_name.namespace,
}),
description: definition.description,
signature: definition.signature,
kind: match definition.kind {
CodeModeToolKind::Function => grpc::ToolKind::Function as i32,
CodeModeToolKind::Freeform => grpc::ToolKind::Freeform as i32,
@@ -28,6 +28,7 @@ fn execute_request_preserves_tool_schemas_namespaces_and_limits() {
description: "search the workspace".to_string(),
kind: CodeModeToolKind::Freeform,
input_schema: Some(json!({"type": "object"})),
signature: Some("search(input: string): Promise<string>;".to_string()),
input_schema_max_bytes: None,
output_schema: Some(json!({"type": "string"})),
}],
@@ -52,6 +53,7 @@ fn execute_request_preserves_tool_schemas_namespaces_and_limits() {
}),
description: "search the workspace".to_string(),
kind: grpc::ToolKind::Freeform as i32,
signature: Some("search(input: string): Promise<string>;".to_string()),
input_schema_json: Some(br#"{"type":"object"}"#.to_vec()),
output_schema_json: Some(br#"{"type":"string"}"#.to_vec()),
}],
@@ -291,6 +291,7 @@ impl GrpcCodeModeSessionProvider {
let inner = Arc::new(SessionInner {
catalog: opened.supports_catalog_revision.then(Default::default),
supports_tool_catalog_signature: opened.supports_tool_catalog_signature,
id: opened.session_id,
output_truncation,
route,
@@ -434,6 +435,7 @@ impl Drop for GrpcCodeModeSession {
pub(super) struct SessionInner {
catalog: Option<Arc<tokio::sync::Mutex<crate::tool_catalog::Catalog>>>,
supports_tool_catalog_signature: bool,
pub(super) id: String,
output_truncation: CodeModeOutputTruncation,
// Affinity belongs to the session: parents and children may share a transport
@@ -78,6 +78,14 @@ impl SessionInner {
preempt: Option<CancellationToken>,
) -> Result<StartedCell, String> {
self.require_open()?;
if !self.supports_tool_catalog_signature
&& request
.enabled_tools
.iter()
.any(|tool| tool.signature.is_some())
{
return Err("code-mode host does not support structured ALL_TOOLS metadata; upgrade the host or disable code_mode_all_tools_schema".to_string());
}
let execution_id = Uuid::new_v4().to_string();
let execute_span = tracing::info_span!(
"code_mode.grpc.execute",
@@ -24,6 +24,7 @@ fn request(execution_id: &str) -> grpc::ExecuteRequest {
}),
description: String::new(),
kind: grpc::ToolKind::Function as i32,
signature: None,
input_schema_json: None,
output_schema_json: None,
}],
@@ -13,6 +13,7 @@ fn references_require_an_acknowledged_matching_admission() {
tool_name: ToolName::plain("echo"),
description: String::new(),
kind: CodeModeToolKind::Function,
signature: None,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
+6
View File
@@ -919,6 +919,9 @@
"code_mode": {
"$ref": "#/definitions/FeatureToml_for_CodeModeConfigToml"
},
"code_mode_all_tools_schema": {
"type": "boolean"
},
"code_mode_buffered_exec": {
"type": "boolean"
},
@@ -8327,6 +8330,9 @@
"code_mode": {
"$ref": "#/definitions/FeatureToml_for_CodeModeConfigToml"
},
"code_mode_all_tools_schema": {
"type": "boolean"
},
"code_mode_buffered_exec": {
"type": "boolean"
},
@@ -5,6 +5,7 @@ use crate::context::world_state::test_support::render_section_cases;
use crate::context_manager::updates::merge_world_state_updates;
use crate::session::extension_metrics::from_session_telemetry;
use codex_code_mode::ExecDefinition;
use codex_code_mode::ToolCatalogFormat;
use codex_models_manager::model_info::model_info_from_slug;
use codex_otel::MetricsClient;
use codex_otel::MetricsConfig;
@@ -771,6 +772,72 @@ fn namespace_replaced_by_builtin_keeps_the_replacement_available() {
);
}
#[test]
fn resumed_exec_refreshes_only_when_the_catalog_format_changes() {
let build = |format| {
let (description, definitions) =
codex_code_mode::build_exec_tool_description_and_definitions(
&[],
&[],
&BTreeMap::new(),
codex_code_mode::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
codex_code_mode::ImageDetailVisibility::Visible,
codex_code_mode::DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ true,
format,
/*messages*/ None,
);
let declaration = exec_declaration(&description, "grammar");
let state = TopLevelToolsState::new(
/*messages*/ Default::default(),
vec![declaration.clone()],
/*metrics*/ None,
)
.unwrap()
.with_incremental_exec_tools(Some(Arc::new(definitions)));
(state, declaration)
};
let formats = [ToolCatalogFormat::Legacy, ToolCatalogFormat::Structured];
for before in formats {
let (original, _) = build(before);
let snapshot = original
.render_diff(PreviousSectionState::Absent)
.0
.unwrap();
let restored: TopLevelToolsSnapshot =
serde_json::from_value(serde_json::to_value(snapshot).unwrap()).unwrap();
for after in formats {
let (resumed, declaration) = build(after);
let (next, updates) = resumed.render_diff(PreviousSectionState::Known(&restored));
let expected = if before == after {
Vec::new()
} else {
vec![
ContextualUserFragment::into(IncrementalToolsUpdate(
ResolvedIncrementalToolMessages::default()
.tool_update_hint
.as_cow(),
)),
item(vec![declaration]),
]
};
assert_eq!(
merge_world_state_updates(updates),
expected,
"{before:?} -> {after:?}"
);
assert!(
resumed
.render_diff(PreviousSectionState::Known(&next.unwrap()))
.1
.is_empty()
);
}
}
}
#[test]
fn hidden_exec_is_not_reintroduced_and_returning_exec_restores_full_catalog() {
let original = exec_declaration("Shared MCP Types:", "grammar");
@@ -23,14 +23,20 @@ type CodeModeNestedTool = (Arc<ToolSpec>, Option<Arc<dyn CoreToolRuntime>>);
pub struct CodeModeExecuteHandler {
spec: ToolSpec,
catalog_format: codex_code_mode::ToolCatalogFormat,
nested_tool_specs: Vec<CodeModeNestedTool>,
}
impl CodeModeExecuteHandler {
pub(crate) fn new(spec: ToolSpec, nested_tool_specs: Vec<CodeModeNestedTool>) -> Self {
pub(crate) fn new(
spec: ToolSpec,
nested_tool_specs: Vec<CodeModeNestedTool>,
catalog_format: codex_code_mode::ToolCatalogFormat,
) -> Self {
Self {
spec,
nested_tool_specs,
catalog_format,
}
}
@@ -60,6 +66,7 @@ impl CodeModeExecuteHandler {
cached_runtime.as_deref(),
|| Cow::Borrowed(spec.as_ref()),
code_mode_input_schema_max_bytes,
self.catalog_format,
);
match definitions {
Cow::Borrowed(definitions) => enabled_tools.extend_from_slice(definitions),
@@ -10,10 +10,11 @@ pub(crate) fn prepare_code_mode_tool_definitions<'a>(
runtime: Option<&'a dyn CoreToolRuntime>,
spec: impl FnOnce() -> Cow<'a, ToolSpec>,
code_mode_input_schema_max_bytes: Option<usize>,
catalog_format: codex_code_mode::ToolCatalogFormat,
) -> Cow<'a, [ToolDefinition]> {
if let Some(definitions) = runtime
.and_then(|runtime| runtime.cached_code_mode_definitions(code_mode_input_schema_max_bytes))
{
if let Some(definitions) = runtime.and_then(|runtime| {
runtime.cached_code_mode_definitions(code_mode_input_schema_max_bytes, catalog_format)
}) {
return Cow::Borrowed(definitions);
}
@@ -21,6 +22,7 @@ pub(crate) fn prepare_code_mode_tool_definitions<'a>(
let mut definitions = codex_tools::collect_code_mode_tool_definitions(
std::iter::once(spec.as_ref()),
code_mode_input_schema_max_bytes,
catalog_format,
);
for definition in &mut definitions {
definition.input_schema = None;
+30 -4
View File
@@ -104,6 +104,7 @@ impl McpHandlerDefinition {
pub struct McpHandler {
pub(crate) definition: Arc<McpHandlerDefinition>,
code_mode_tool_definitions: OnceLock<(Option<usize>, Vec<codex_code_mode::ToolDefinition>)>,
signature_tool_definitions: OnceLock<(Option<usize>, Vec<codex_code_mode::ToolDefinition>)>,
}
#[cfg(test)]
@@ -139,6 +140,7 @@ impl McpHandler {
Self {
definition,
code_mode_tool_definitions: OnceLock::new(),
signature_tool_definitions: OnceLock::new(),
}
}
@@ -378,11 +380,17 @@ impl CoreToolRuntime for McpHandler {
fn cached_code_mode_definitions(
&self,
code_mode_input_schema_max_bytes: Option<usize>,
format: codex_code_mode::ToolCatalogFormat,
) -> Option<&[codex_code_mode::ToolDefinition]> {
let (cached_budget, definitions) = self.code_mode_tool_definitions.get_or_init(|| {
let cache = match format {
codex_code_mode::ToolCatalogFormat::Legacy => &self.code_mode_tool_definitions,
codex_code_mode::ToolCatalogFormat::Structured => &self.signature_tool_definitions,
};
let (cached_budget, definitions) = cache.get_or_init(|| {
let mut definitions = codex_tools::collect_code_mode_tool_definitions(
std::iter::once(self.definition.spec.as_ref()),
code_mode_input_schema_max_bytes,
format,
);
for definition in &mut definitions {
definition.input_schema = None;
@@ -1012,17 +1020,35 @@ mod tests {
));
let first = handler
.cached_code_mode_definitions(/*code_mode_input_schema_max_bytes*/ None)
.cached_code_mode_definitions(
/*code_mode_input_schema_max_bytes*/ None,
codex_code_mode::ToolCatalogFormat::Legacy,
)
.expect("MCP definitions should be cached");
assert_eq!(first.len(), 1);
assert!(first[0].input_schema.is_none());
assert!(first[0].output_schema.is_none());
let with_signature = handler
.cached_code_mode_definitions(None, codex_code_mode::ToolCatalogFormat::Structured)
.unwrap();
assert!(with_signature[0].signature.is_some());
assert!(first[0].signature.is_none());
let second = handler
.cached_code_mode_definitions(/*code_mode_input_schema_max_bytes*/ None)
.cached_code_mode_definitions(
/*code_mode_input_schema_max_bytes*/ None,
codex_code_mode::ToolCatalogFormat::Legacy,
)
.expect("MCP definitions should be cached");
assert!(std::ptr::eq(first, second));
assert!(handler.cached_code_mode_definitions(Some(32_000)).is_none());
assert!(
handler
.cached_code_mode_definitions(
Some(32_000),
codex_code_mode::ToolCatalogFormat::Legacy
)
.is_none()
);
}
#[test]
@@ -322,6 +322,7 @@ impl ToolSearchHandler {
tool.cached_runtime().map(Arc::as_ref),
|| Cow::Owned(Arc::unwrap_or_clone(tool.spec())),
code_mode_input_schema_max_bytes,
codex_code_mode::ToolCatalogFormat::Legacy,
);
let Some(definition) = definitions.iter().find(|definition| {
definition.tool_name.clone().with_default_namespace() == candidate_name
+1
View File
@@ -91,6 +91,7 @@ pub(crate) trait CoreToolRuntime: ToolExecutor<ToolInvocation> {
fn cached_code_mode_definitions(
&self,
_code_mode_input_schema_max_bytes: Option<usize>,
_catalog_format: codex_code_mode::ToolCatalogFormat,
) -> Option<&[codex_code_mode::ToolDefinition]> {
None
}
+7
View File
@@ -1027,6 +1027,11 @@ fn register_code_mode_executors(
&& features.enabled(Feature::IncrementalTools)
&& features.enabled(Feature::IncrementalExecTools)
&& tool_mode == ToolMode::CodeModeOnly;
let catalog_format = if features.enabled(Feature::CodeModeAllToolsSchema) {
codex_code_mode::ToolCatalogFormat::Structured
} else {
codex_code_mode::ToolCatalogFormat::Legacy
};
let (exec_description, exec_definitions) =
codex_code_mode::build_exec_tool_description_and_definitions(
&enabled_tools,
@@ -1037,12 +1042,14 @@ fn register_code_mode_executors(
image_detail_visibility,
deferred_tool_discovery,
incremental_exec_enabled,
catalog_format,
model_messages.code_mode(),
);
let exec_definitions = incremental_exec_enabled.then(|| Arc::new(exec_definitions));
let execute_handler = CodeModeExecuteHandler::new(
create_code_mode_tool(exec_description),
code_mode_nested_tool_specs,
catalog_format,
);
registry.prepend_trusted(Arc::new(CodeModeWaitHandler::new(
+1
View File
@@ -130,6 +130,7 @@ async fn stdio_callbacks_preserve_context_across_overlapping_yielded_cells() {
tool_name: ToolName::plain("gate"),
description: String::new(),
kind: CodeModeToolKind::Function,
signature: None,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
+2
View File
@@ -185,6 +185,8 @@ mod catalog_apps_instructions;
#[path = "scenarios_managed_human_approval_tests.rs"]
mod managed_human_approval;
#[path = "scenarios_code_mode_all_tools_tests.rs"]
mod code_mode_all_tools;
#[path = "scenarios_context_management_tools.rs"]
mod context_management_tools;
@@ -0,0 +1,149 @@
//! Checks opt-in signatures and the legacy catalog through Code Mode.
use super::super::code_mode::custom_tool_output_last_non_empty_text;
use super::super::rmcp_client::remote_aware_environment_id;
use super::super::rmcp_client::remote_aware_stdio_server_bin;
use super::*;
use anyhow::Context;
use pretty_assertions::assert_eq;
#[test_case::test_case(true; "structured")]
#[test_case::test_case(false; "legacy")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn code_mode_all_tools_schema(structured: bool) -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_wine_exec!(Ok(()), "requires a Windows test_stdio_server binary");
let server = start_mock_server().await;
let command = remote_aware_stdio_server_bin()?;
let environment_id = remote_aware_environment_id();
let test = test_codex()
.with_model("gpt-5.5")
.with_config(move |config| {
configure_scenario_catalog(config);
if structured {
config
.features
.enable(Feature::CodeModeAllToolsSchema)
.expect("enable structured tool catalog");
}
config
.features
.enable(Feature::CodeModeOnly)
.expect("enable Code Mode Only");
config
.mcp_servers
.set(HashMap::from([(
"catalog".to_string(),
serde_json::from_value(json!({
"command": command,
"environment_id": environment_id,
"cwd": config.cwd,
"env": {"MCP_TEST_SERVER_INSTRUCTIONS": "Catalog tools."},
"enabled_tools": ["echo"],
"default_tools_approval_mode": "approve"
}))
.expect("MCP config"),
)]))
.expect("set MCP servers");
})
.with_model_info_override("gpt-5.5", |model| {
model.tool_mode = Some(ToolMode::CodeModeOnly);
model.model_messages.as_mut().expect("model messages").tools = Some(
serde_json::from_value(json!({
"indirect_description_prefixes": {
"mcp_servers": {"catalog": "Use for catalog checks."}
}
}))
.expect("tool messages"),
);
})
.build_with_auto_env(&server)
.await?;
wait_for_mcp_server(&test.codex, "catalog").await?;
let mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_custom_tool_call(
"catalog",
"exec",
r#"
const names = ["view_image", "apply_patch", "mcp__catalog__echo"];
const entries = names.map(name => ALL_TOOLS.find(tool => tool.name === name));
text(JSON.stringify(entries, null, 2));
const echo = entries[2];
text({echo: (await tools[echo.name]({message: "catalog works"})).structuredContent.echo});
"#,
),
ev_completed("catalog-response"),
]),
sse(vec![
ev_assistant_message("done", "Catalog inspected and echo called."),
ev_completed("done-response"),
]),
],
)
.await;
test.submit_turn("Inspect the image, patch, and echo tools, then call echo.")
.await?;
let requests = mock.requests();
assert_eq!(requests.len(), 2);
let output =
custom_tool_output_last_non_empty_text(&requests[1], "catalog").expect("catalog result");
let result: serde_json::Value = serde_json::from_str(&output)
.with_context(|| format!("catalog execution output: {output}"))?;
assert_eq!(
result,
json!({
"echo": "ECHOING: catalog works",
})
);
let output = requests[1].custom_tool_call_output("catalog");
let entries = output["output"]
.as_array()
.context("catalog output items")?
.iter()
.filter_map(|item| item["text"].as_str())
.find_map(|text| serde_json::from_str::<Vec<serde_json::Value>>(text).ok())
.context("catalog entries")?;
let names = ["view_image", "apply_patch", "mcp__catalog__echo"];
assert_eq!(entries.len(), names.len());
for (entry, name) in entries.iter().zip(names) {
assert_eq!(entry["name"], name);
let description = entry["description"].as_str().context("tool description")?;
assert_eq!(description.contains("exec tool declaration:"), !structured);
let entry = entry.as_object().context("catalog entry")?;
assert_eq!(entry.len(), if structured { 3 } else { 2 });
if structured {
let signature = entry["signature"].as_str().context("tool signature")?;
assert!(signature.starts_with(&format!("{name}(")));
assert!(signature.ends_with(">;"));
}
}
let echo_description = entries[2]["description"]
.as_str()
.context("echo description")?;
assert!(echo_description.contains("Use for catalog checks."));
assert!(echo_description.contains("Catalog tools."));
if structured {
assert_eq!(
entries[1]["signature"],
"apply_patch(input: string): Promise<unknown>;"
);
}
let body = requests[0].body_json();
let exec = body["tools"]
.as_array()
.expect("request tools array")
.iter()
.find(|tool| tool["name"] == "exec")
.expect("exec tool definition")["description"]
.as_str()
.expect("exec tool description");
assert_eq!(
exec.contains("{ name, description, signature }"),
structured
);
assert_eq!(exec.contains("{ name, description }"), !structured);
Ok(())
}
@@ -436,6 +436,89 @@ async fn changed_sections_and_entries_append_without_repeating_the_catalog(
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_resume_tracks_all_tools_catalog_format() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let mock = responses::mount_sse_sequence(
&server,
[
"initial",
"still-legacy",
"enabled",
"still-enabled",
"rollback",
]
.map(responses::sse_completed)
.to_vec(),
)
.await;
let builder = |structured: bool| {
test_codex()
.with_config(move |config| {
super::configure_scenario_catalog(config);
for feature in [Feature::IncrementalTools, Feature::IncrementalExecTools] {
config
.features
.enable(feature)
.expect("enable catalog updates");
}
config
.features
.set_enabled(Feature::CodeModeAllToolsSchema, structured)
.expect("set ALL_TOOLS format");
})
.with_model_info_override("catalog-initial", |model| {
model.use_responses_lite = true;
model.tool_mode = Some(ToolMode::CodeModeOnly);
model.model_messages = None;
})
.with_model("catalog-initial")
};
let mut thread = builder(/*structured*/ false)
.build_with_auto_env(&server)
.await?;
thread.submit_text_turn("Publish exec.").await?;
for structured in [false, true, true, false] {
thread = builder(structured)
.restart_with_auto_env(&server, &thread)
.await?;
thread
.submit_text_turn("Resume with the current catalog.")
.await?;
}
let requests = mock.requests();
assert_eq!(requests.len(), 5);
let legacy = "{ name, description }";
let structured = "{ name, description, signature }";
let expected = [
(1, legacy),
(1, legacy),
(2, structured),
(2, structured),
(3, legacy),
];
for (request, (count, shape)) in requests.iter().zip(expected) {
let input = request.input();
let declarations = input
.iter()
.filter(|item| item["type"] == "additional_tools")
.filter_map(|item| responses::namespace_child_tool(item, "functions", "exec"))
.collect::<Vec<_>>();
assert_eq!(declarations.len(), count);
let description = declarations.last().expect("exec declaration")["description"]
.as_str()
.expect("exec description");
assert!(
description.contains(shape),
"expected ALL_TOOLS shape {shape}"
);
}
Ok(())
}
#[test_case::test_case(None, true; "bundled_helpers")]
#[test_case::test_case(Some("Run JavaScript."), false; "helper_free_override")]
#[test_case::test_case(Some("Run JavaScript. {{ image_helper }}"), true; "image_helper_override")]
@@ -206,6 +206,7 @@ fn imagegen_code_mode_declaration_describes_generated_image_result() {
let definitions = codex_tools::collect_code_mode_tool_definitions(
[&spec],
/*code_mode_input_schema_max_bytes*/ None,
Default::default(),
);
let [definition] = definitions.as_slice() else {
panic!("imagegen should produce one code-mode declaration");
+8
View File
@@ -176,6 +176,8 @@ pub enum Feature {
CodeModeInterrupt,
/// Removed compatibility flag for Code Mode tool description ordering.
CodeModeToolDescriptionFirst,
/// Expose a separate TypeScript signature for each tool in ALL_TOOLS.
CodeModeAllToolsSchema,
/// Restrict model-visible tools to code mode entrypoints (`exec`, `wait`).
CodeModeOnly,
/// Keep eligible MCP/app and dynamic tools deferred in exec, only in Code Mode Only.
@@ -1485,6 +1487,12 @@ pub const FEATURES: &[FeatureSpec] = &[
stage: Stage::Removed,
default_enabled: false,
},
FeatureSpec {
id: Feature::CodeModeAllToolsSchema,
key: "code_mode_all_tools_schema",
stage: Stage::UnderDevelopment,
default_enabled: false,
},
FeatureSpec {
id: Feature::InstantInterrupt,
key: "instant_interrupt",
+18 -1
View File
@@ -43,6 +43,7 @@ pub fn augment_tool_spec_for_code_mode(
description: tool.description.clone(),
kind: CodeModeToolKind::Function,
input_schema: serde_json::to_value(&tool.parameters).ok(),
signature: None,
input_schema_max_bytes: Some(effective_input_schema_max_bytes(
tool.parameters.mcp_input_schema_max_bytes,
code_mode_input_schema_max_bytes,
@@ -64,6 +65,7 @@ pub fn augment_tool_spec_for_code_mode(
description: tool.description.clone(),
kind: CodeModeToolKind::Freeform,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
};
@@ -90,6 +92,7 @@ pub fn tool_spec_to_code_mode_tool_definition(spec: &ToolSpec) -> Option<CodeMod
pub fn collect_code_mode_tool_definitions<'a>(
specs: impl IntoIterator<Item = &'a ToolSpec>,
code_mode_input_schema_max_bytes: Option<usize>,
catalog_format: codex_code_mode::ToolCatalogFormat,
) -> Vec<CodeModeToolDefinition> {
let mut tool_definitions = specs
.into_iter()
@@ -108,7 +111,16 @@ pub fn collect_code_mode_tool_definitions<'a>(
definitions
})
.filter(|definition| codex_code_mode::is_code_mode_nested_tool(&definition.name))
.map(codex_code_mode::augment_tool_definition)
.map(|mut definition| match catalog_format {
codex_code_mode::ToolCatalogFormat::Legacy => {
codex_code_mode::augment_tool_definition(definition)
}
codex_code_mode::ToolCatalogFormat::Structured => {
definition.signature =
Some(codex_code_mode::render_code_mode_signature(&definition));
definition
}
})
.collect::<Vec<_>>();
tool_definitions.sort_by(|left, right| left.name.cmp(&right.name));
tool_definitions.dedup_by(|left, right| left.name == right.name);
@@ -171,6 +183,7 @@ fn code_mode_tool_definitions_for_spec(
description: tool.description.clone(),
kind: CodeModeToolKind::Function,
input_schema: serde_json::to_value(&tool.parameters).ok(),
signature: None,
input_schema_max_bytes: Some(effective_input_schema_max_bytes(
tool.parameters.mcp_input_schema_max_bytes,
code_mode_input_schema_max_bytes,
@@ -186,6 +199,7 @@ fn code_mode_tool_definitions_for_spec(
description: tool.description.clone(),
kind: CodeModeToolKind::Freeform,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}]
@@ -202,6 +216,7 @@ fn code_mode_tool_definitions_for_spec(
description: tool.description.clone(),
kind: CodeModeToolKind::Function,
input_schema: serde_json::to_value(&tool.parameters).ok(),
signature: None,
input_schema_max_bytes: Some(effective_input_schema_max_bytes(
tool.parameters.mcp_input_schema_max_bytes,
code_mode_input_schema_max_bytes,
@@ -217,6 +232,7 @@ fn code_mode_tool_definitions_for_spec(
description: tool.description.clone(),
kind: CodeModeToolKind::Freeform,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
}
@@ -231,6 +247,7 @@ fn code_mode_tool_definitions_for_spec(
description: codex_code_mode::TOOL_SEARCH_GUIDANCE.to_string(),
kind: CodeModeToolKind::Function,
input_schema: serde_json::to_value(parameters).ok(),
signature: None,
input_schema_max_bytes: Some(effective_input_schema_max_bytes(
parameters.mcp_input_schema_max_bytes,
code_mode_input_schema_max_bytes,
+4
View File
@@ -58,10 +58,12 @@ fn code_mode_materializes_mcp_output_schemas() {
super::collect_code_mode_tool_definitions(
[&ToolSpec::Function(parsed)],
/*code_mode_input_schema_max_bytes*/ None,
codex_code_mode::ToolCatalogFormat::Legacy,
),
super::collect_code_mode_tool_definitions(
[&ToolSpec::Function(eager)],
/*code_mode_input_schema_max_bytes*/ None,
codex_code_mode::ToolCatalogFormat::Legacy,
),
);
}
@@ -194,6 +196,7 @@ declare const tools: { apply_patch(input: string): Promise<unknown>; };
.to_string(),
kind: codex_code_mode::CodeModeToolKind::Freeform,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
})
@@ -231,6 +234,7 @@ declare const tools: { editor__apply_patch(input: string): Promise<unknown>; };
.to_string(),
kind: codex_code_mode::CodeModeToolKind::Freeform,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
})
@@ -20,6 +20,7 @@ fn plain_tools_join_an_existing_functions_group_only_with_a_prefix() {
description: "Tool guidance.".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
});
@@ -41,6 +42,7 @@ fn plain_tools_join_an_existing_functions_group_only_with_a_prefix() {
codex_code_mode::ImageDetailVisibility::Visible,
codex_code_mode::DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
codex_code_mode::ToolCatalogFormat::Legacy,
/*messages*/ None,
)
.0
@@ -182,6 +184,7 @@ fn flat_tool_descriptions_use_trimmed_namespace_prefixes() {
description: "Inspect.".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
};
@@ -216,6 +219,7 @@ fn matching_prefixes_cover_each_namespace_once() {
description: "Search.".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
signature: None,
input_schema_max_bytes: None,
output_schema: None,
});