diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 7f2ecbcd18..36302b30bc 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -11203,6 +11203,15 @@ }, { "properties": { + "additionalContextLimit": { + "description": "Approximate token threshold for spilling plaintext `additionalContext` to disk. Defaults to 2,500. For MCP hooks, `0` and values above 10,000 trigger a warning and use 10,000. Command hooks can disable spilling with `0` or set a higher threshold. The MCP ceiling mirrors the current default tool-output budget and may change in the future. Encrypted hook output has a separate byte limit.", + "format": "uint", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, "input": { "additionalProperties": true, "type": "object" @@ -14571,7 +14580,7 @@ ], "properties": { "additionalContextLimit": { - "description": "Configured `additionalContext` spill threshold. `null` uses 2,500 tokens; `0` disables spilling.", + "description": "Configured `additionalContext` spill threshold. `null` uses 2,500 approximate tokens. Only command hooks support `0` (no spill) or values above 10,000.", "format": "uint", "minimum": 0.0, "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index d4b18554ac..14803b0ccf 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -6883,6 +6883,15 @@ }, { "properties": { + "additionalContextLimit": { + "description": "Approximate token threshold for spilling plaintext `additionalContext` to disk. Defaults to 2,500. For MCP hooks, `0` and values above 10,000 trigger a warning and use 10,000. Command hooks can disable spilling with `0` or set a higher threshold. The MCP ceiling mirrors the current default tool-output budget and may change in the future. Encrypted hook output has a separate byte limit.", + "format": "uint", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, "input": { "additionalProperties": true, "type": "object" @@ -10362,7 +10371,7 @@ ], "properties": { "additionalContextLimit": { - "description": "Configured `additionalContext` spill threshold. `null` uses 2,500 tokens; `0` disables spilling.", + "description": "Configured `additionalContext` spill threshold. `null` uses 2,500 approximate tokens. Only command hooks support `0` (no spill) or values above 10,000.", "format": "uint", "minimum": 0.0, "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json index 09ca61d93f..2ba7f89502 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json @@ -747,6 +747,15 @@ }, { "properties": { + "additionalContextLimit": { + "description": "Approximate token threshold for spilling plaintext `additionalContext` to disk. Defaults to 2,500. For MCP hooks, `0` and values above 10,000 trigger a warning and use 10,000. Command hooks can disable spilling with `0` or set a higher threshold. The MCP ceiling mirrors the current default tool-output budget and may change in the future. Encrypted hook output has a separate byte limit.", + "format": "uint", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, "input": { "additionalProperties": true, "type": "object" diff --git a/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json index 286201cec5..cfc9ac2501 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json @@ -118,7 +118,7 @@ ], "properties": { "additionalContextLimit": { - "description": "Configured `additionalContext` spill threshold. `null` uses 2,500 tokens; `0` disables spilling.", + "description": "Configured `additionalContext` spill threshold. `null` uses 2,500 approximate tokens. Only command hooks support `0` (no spill) or values above 10,000.", "format": "uint", "minimum": 0.0, "type": [ diff --git a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst index 82fa859880..3fcd24a14e 100644 Binary files a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst and b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-experimental.json.zst differ diff --git a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst index e707f011e8..33410f5c05 100644 Binary files a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst and b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst differ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ConfiguredHookHandler.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ConfiguredHookHandler.ts index f70d35ccef..8c42d23ee7 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ConfiguredHookHandler.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ConfiguredHookHandler.ts @@ -11,4 +11,13 @@ export type ConfiguredHookHandler = { "type": "command", command: string, comman * evaluated against the original context; a spilled preview also includes recovery * metadata. */ -additionalContextLimit: number | null, } | { "type": "mcp_tool", server: string, tool: string, input: { [key in string]?: JsonValue }, timeoutSec: bigint | null, statusMessage: string | null, onFailure: ConfiguredHookFailurePolicy | null, } | { "type": "prompt", } | { "type": "agent", }; +additionalContextLimit: number | null, } | { "type": "mcp_tool", server: string, tool: string, input: { [key in string]?: JsonValue }, timeoutSec: bigint | null, statusMessage: string | null, onFailure: ConfiguredHookFailurePolicy | null, +/** + * Approximate token threshold for spilling plaintext `additionalContext` to disk. + * Defaults to 2,500. For MCP hooks, `0` and values above 10,000 + * trigger a warning and use 10,000. Command hooks can disable spilling + * with `0` or set a higher threshold. The MCP ceiling mirrors the + * current default tool-output budget and may change in the future. + * Encrypted hook output has a separate byte limit. + */ +additionalContextLimit: number | null, } | { "type": "prompt", } | { "type": "agent", }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/HookMetadata.ts b/codex-rs/app-server-protocol/schema/typescript/v2/HookMetadata.ts index b6477f2ccc..809be7acab 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/HookMetadata.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/HookMetadata.ts @@ -9,7 +9,7 @@ import type { HookTrustStatus } from "./HookTrustStatus"; export type HookMetadata = { key: string, eventName: HookEventName, matcher: string | null, timeoutSec: bigint, statusMessage: string | null, /** * Configured `additionalContext` spill threshold. - * `null` uses 2,500 tokens; `0` disables spilling. + * `null` uses 2,500 approximate tokens. Only command hooks support `0` (no spill) or values above 10,000. */ additionalContextLimit: number | null, sourcePath: AbsolutePathBuf, source: HookSource, pluginId: string | null, /** diff --git a/codex-rs/app-server-protocol/src/protocol/v2/config.rs b/codex-rs/app-server-protocol/src/protocol/v2/config.rs index 1d40b7451c..7889c33f97 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/config.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/config.rs @@ -790,6 +790,15 @@ pub enum ConfiguredHookHandler { #[serde(rename = "onFailure")] #[ts(rename = "onFailure")] on_failure: Option, + /// Approximate token threshold for spilling plaintext `additionalContext` to disk. + /// Defaults to 2,500. For MCP hooks, `0` and values above 10,000 + /// trigger a warning and use 10,000. Command hooks can disable spilling + /// with `0` or set a higher threshold. The MCP ceiling mirrors the + /// current default tool-output budget and may change in the future. + /// Encrypted hook output has a separate byte limit. + #[serde(rename = "additionalContextLimit")] + #[ts(rename = "additionalContextLimit")] + additional_context_limit: Option, }, #[serde(rename = "prompt")] #[ts(rename = "prompt")] diff --git a/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs b/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs index 05c1665af6..b742bea46c 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs @@ -595,7 +595,7 @@ pub struct HookMetadata { pub timeout_sec: u64, pub status_message: Option, /// Configured `additionalContext` spill threshold. - /// `null` uses 2,500 tokens; `0` disables spilling. + /// `null` uses 2,500 approximate tokens. Only command hooks support `0` (no spill) or values above 10,000. pub additional_context_limit: Option, pub source_path: AbsolutePathBuf, pub source: HookSource, diff --git a/codex-rs/app-server/src/request_processors/config_processor.rs b/codex-rs/app-server/src/request_processors/config_processor.rs index d0104942dc..0a1645cb39 100644 --- a/codex-rs/app-server/src/request_processors/config_processor.rs +++ b/codex-rs/app-server/src/request_processors/config_processor.rs @@ -884,6 +884,7 @@ fn map_hook_handler_to_api(handler: CoreHookHandlerConfig) -> ConfiguredHookHand timeout_sec, status_message, on_failure, + additional_context_limit, } => ConfiguredHookHandler::McpTool { server, tool, @@ -891,6 +892,7 @@ fn map_hook_handler_to_api(handler: CoreHookHandlerConfig) -> ConfiguredHookHand timeout_sec, status_message, on_failure: on_failure.map(map_hook_failure_policy_to_api), + additional_context_limit, }, CoreHookHandlerConfig::Prompt {} => ConfiguredHookHandler::Prompt {}, CoreHookHandlerConfig::Agent {} => ConfiguredHookHandler::Agent {}, diff --git a/codex-rs/app-server/tests/suite/v2/config_rpc.rs b/codex-rs/app-server/tests/suite/v2/config_rpc.rs index 30da8cce18..953618adab 100644 --- a/codex-rs/app-server/tests/suite/v2/config_rpc.rs +++ b/codex-rs/app-server/tests/suite/v2/config_rpc.rs @@ -277,6 +277,7 @@ tool = "scan" input = { path = "${tool_input.file_path}", metadata = { enabled = true, retries = 2 } } timeout = 30 statusMessage = "Scanning file" +additionalContextLimit = 8000 onFailure = "continue" "#, )?; @@ -322,6 +323,7 @@ onFailure = "continue" timeout_sec: Some(30), status_message: Some("Scanning file".to_string()), on_failure: Some(codex_app_server_protocol::ConfiguredHookFailurePolicy::Continue), + additional_context_limit: Some(8_000), }, ] ); diff --git a/codex-rs/app-server/tests/suite/v2/hooks_list.rs b/codex-rs/app-server/tests/suite/v2/hooks_list.rs index 1246a36448..3c8acd423e 100644 --- a/codex-rs/app-server/tests/suite/v2/hooks_list.rs +++ b/codex-rs/app-server/tests/suite/v2/hooks_list.rs @@ -908,6 +908,7 @@ async fn hooks_list_shows_discovered_plugin_mcp_tool_hook() -> Result<()> { "tool": "inspect", "input": {"path": "${tool_input.path}"}, "timeout": 9, + "additionalContextLimit": 4096, "statusMessage": "checking security policy" } ] @@ -952,7 +953,7 @@ async fn hooks_list_shows_discovered_plugin_mcp_tool_hook() -> Result<()> { matcher: Some("Bash".to_string()), timeout_sec: 9, status_message: Some("checking security policy".to_string()), - additional_context_limit: None, + additional_context_limit: Some(4_096), source_path, source: HookSource::Plugin, plugin_id: Some("demo@test".to_string()), diff --git a/codex-rs/config/src/hooks_tests.rs b/codex-rs/config/src/hooks_tests.rs index 8154f50130..4ab80ee19c 100644 --- a/codex-rs/config/src/hooks_tests.rs +++ b/codex-rs/config/src/hooks_tests.rs @@ -97,6 +97,7 @@ fn hooks_file_deserializes_mcp_tool_handler_with_json_inputs() { timeout_sec: Some(30), status_message: Some("Scanning file".to_string()), on_failure: None, + additional_context_limit: None, }] ); } diff --git a/codex-rs/core-plugins/src/executor_hooks_tests.rs b/codex-rs/core-plugins/src/executor_hooks_tests.rs index fcffe68ac4..200650c666 100644 --- a/codex-rs/core-plugins/src/executor_hooks_tests.rs +++ b/codex-rs/core-plugins/src/executor_hooks_tests.rs @@ -101,6 +101,7 @@ fn expected_source(index: usize) -> ExecutorPluginHookSource { timeout_sec: None, status_message: None, on_failure: None, + additional_context_limit: None, }], }], ..Default::default() @@ -249,6 +250,7 @@ fn preserves_allowlisted_executor_plugin_hook_options() { timeout_sec: Some(30), status_message: Some("Cleaning up Computer Use".to_string()), on_failure: None, + additional_context_limit: None, }; expected.hooks.interrupt = expected.hooks.stop.clone(); diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index b1b67ed406..084399c834 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -2684,6 +2684,13 @@ }, { "properties": { + "additionalContextLimit": { + "description": "Approximate token threshold for spilling plaintext `additionalContext` to disk. Defaults to 2,500. For MCP hooks, `0` and values above 10,000 trigger a warning and use 10,000. Command hooks can disable spilling with `0` or set a higher threshold. The MCP ceiling mirrors the current default tool-output budget and may change in the future. Encrypted hook output has a separate byte limit.", + "format": "uint", + "maximum": 10000.0, + "minimum": 1.0, + "type": "integer" + }, "input": { "additionalProperties": true, "default": {}, diff --git a/codex-rs/core/tests/suite/scenarios_bundled_app_hooks.rs b/codex-rs/core/tests/suite/scenarios_bundled_app_hooks.rs index 2c3d1229b5..4277bdcb1c 100644 --- a/codex-rs/core/tests/suite/scenarios_bundled_app_hooks.rs +++ b/codex-rs/core/tests/suite/scenarios_bundled_app_hooks.rs @@ -34,22 +34,25 @@ async fn bundled_memory_hook_injects_context() -> Result<()> { }, }, })]))).await?; + let memory = ["The user prefers short, direct answers."; 1_000].join(" "); + let hook_output = memory.clone(); Mock::given(method("POST")) .and(path("/api/codex/ps/mcp")) .and(body_partial_json(json!({ "method": "tools/call" }))) - .respond_with(|request: &Request| { + .respond_with(move |request: &Request| { let request: serde_json::Value = serde_json::from_slice(&request.body).unwrap(); ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ "jsonrpc": "2.0", "id": request["id"], "result": { "content": [{ "type": "text", "text": json!({ "hookSpecificOutput": { - "hookEventName": "SessionStart", "additionalContext": "The user prefers concise answers.", + "hookEventName": "SessionStart", "additionalContext": hook_output, }, }).to_string() }] }, })) }) .with_priority(/*p*/ 1) - .mount(&server).await; + .mount(&server) + .await; let home = Arc::new(TempDir::new()?); let root = home .path() @@ -61,7 +64,12 @@ async fn bundled_memory_hook_injects_context() -> Result<()> { "name": "codex-dream-memory", "hooks": { "hooks": { "SessionStart": [{ "matcher": "^(startup|compact)$", - "hooks": [{ "type": "mcp_tool", "server": "codex_apps", "tool": "codex_dream_memory.get_mec" }], + "hooks": [{ + "type": "mcp_tool", + "server": "codex_apps", + "tool": "codex_dream_memory.get_mec", + "additionalContextLimit": 10_000, + }], }] } }, }))?, )?; @@ -118,11 +126,15 @@ async fn bundled_memory_hook_injects_context() -> Result<()> { assert_eq!(call["params"]["arguments"], json!({})); assert_eq!(call["params"]["name"], "codex_dream_memory.get_mec"); } + let requests = responses.requests(); + for request in [&requests[0], &requests[2]] { + assert!(request.message_input_texts("developer").contains(&memory)); + } insta::assert_snapshot!( "bundled_memory_hook_context", context_snapshot::format_request_history_snapshot( "A bundled App-only hook injects memory at startup and after compaction without saved trust.", - &responses.requests(), + &requests, &ContextSnapshotOptions::default().rewrite_known_segments(), ) ); diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__bundled_app_hooks__bundled_memory_hook_context.snap b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__bundled_app_hooks__bundled_memory_hook_context.snap index 2de408e3ba..4eadd6d0d5 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__bundled_app_hooks__bundled_memory_hook_context.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__bundled_app_hooks__bundled_memory_hook_context.snap @@ -1,7 +1,7 @@ --- source: core/tests/suite/scenarios_bundled_app_hooks.rs -assertion_line: 151 -expression: "context_snapshot::format_request_history_snapshot(\"A bundled App-only hook injects memory at startup and after compaction without saved trust.\",\n&responses.requests(),\n&ContextSnapshotOptions::default().rewrite_known_segments(),)" +assertion_line: 132 +expression: "context_snapshot::format_request_history_snapshot(\"A bundled App-only hook injects memory at startup and after compaction without saved trust.\",\n&requests, &ContextSnapshotOptions::default().rewrite_known_segments(),)" --- Scenario: A bundled App-only hook injects memory at startup and after compaction without saved trust. @@ -19,7 +19,7 @@ Scenario: A bundled App-only hook injects memory at startup and after compaction 02:message/user: 03:message/developer: - The user prefers concise answers. + The user prefers short, direct answers. The user prefers short, direct answers. The user prefers short, ...rect answers. The user prefers short, direct answers. [hash=3a4c8f7df967100f] 04:message/user: Remember my preferences. @@ -37,7 +37,7 @@ Scenario: A bundled App-only hook injects memory at startup and after compaction 02:message/user: 03:message/developer: - The user prefers concise answers. + The user prefers short, direct answers. The user prefers short, direct answers. The user prefers short, ...rect answers. The user prefers short, direct answers. [hash=3a4c8f7df967100f] 04:message/user: Remember my preferences. 05:message/assistant: @@ -64,6 +64,6 @@ Scenario: A bundled App-only hook injects memory at startup and after compaction Done. 05:message/developer: - The user prefers concise answers. + The user prefers short, direct answers. The user prefers short, direct answers. The user prefers short, ...rect answers. The user prefers short, direct answers. [hash=3a4c8f7df967100f] 06:message/user: Continue after compaction. diff --git a/codex-rs/hooks/src/engine/discovery.rs b/codex-rs/hooks/src/engine/discovery.rs index 4095adde5d..b87814d756 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -19,7 +19,9 @@ use codex_config::version_for_toml; use codex_plugin::PluginHookSource; use codex_plugin::bundled_hook_app_connector_id; use codex_plugin::is_allowlisted_bundled_cleanup_hook; +use codex_protocol::hooks::MAX_MCP_HOOK_CONTEXT_TOKENS; use codex_protocol::protocol::HookEventName; +use codex_protocol::protocol::HookHandlerType; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; @@ -715,26 +717,13 @@ fn append_matcher_groups( source.path.display() )); } - let additional_context_limit = if matches!( + let additional_context_limit = normalize_additional_context_limit( event_name, - codex_protocol::protocol::HookEventName::PreToolUse - | codex_protocol::protocol::HookEventName::PostToolUse - | codex_protocol::protocol::HookEventName::SessionStart - | codex_protocol::protocol::HookEventName::UserPromptSubmit - | codex_protocol::protocol::HookEventName::SubagentStart - ) { - additional_context_limit - } else { - if additional_context_limit.is_some() { - warnings.push(format!( - "ignoring additionalContextLimit for {event_name:?} hook in {}: this event cannot emit additionalContext", - source.path.display() - )); - } - None - }; - let normalized_additional_context_limit = additional_context_limit - .filter(|limit| *limit != DEFAULT_HOOK_OUTPUT_TOKEN_LIMIT); + HookHandlerType::Command, + additional_context_limit, + source.path.as_path(), + warnings, + ); let config = HookHandlerConfig::Command { command: command.clone(), command_windows: None, @@ -742,7 +731,8 @@ fn append_matcher_groups( r#async, status_message: status_message.clone(), on_failure, - additional_context_limit: normalized_additional_context_limit, + additional_context_limit: additional_context_limit + .filter(|limit| *limit != DEFAULT_HOOK_OUTPUT_TOKEN_LIMIT), }; let command = source.env.iter().fold(command, |command, (key, value)| { command.replace(&format!("${{{key}}}"), value) @@ -766,6 +756,7 @@ fn append_matcher_groups( timeout_sec, status_message, on_failure, + additional_context_limit, } => { if event_name == HookEventName::SessionEnd { source.record_load_failure( @@ -794,6 +785,13 @@ fn append_matcher_groups( source.path.as_path(), warnings, ); + let additional_context_limit = normalize_additional_context_limit( + event_name, + HookHandlerType::McpTool, + additional_context_limit, + source.path.as_path(), + warnings, + ); let config = HookHandlerConfig::McpTool { server: server.clone(), tool: tool.clone(), @@ -801,6 +799,8 @@ fn append_matcher_groups( timeout_sec: Some(timeout_sec), status_message: status_message.clone(), on_failure, + additional_context_limit: additional_context_limit + .filter(|limit| *limit != DEFAULT_HOOK_OUTPUT_TOKEN_LIMIT), }; NormalizedHandler { config, @@ -812,7 +812,7 @@ fn append_matcher_groups( }, timeout_sec, status_message, - additional_context_limit: None, + additional_context_limit, } } HookHandlerConfig::Prompt {} => { @@ -981,6 +981,40 @@ fn append_matcher_groups( } } +fn normalize_additional_context_limit( + event_name: HookEventName, + handler_type: HookHandlerType, + limit: Option, + path: &Path, + warnings: &mut Vec, +) -> Option { + let limit = limit?; + if !matches!( + event_name, + HookEventName::PreToolUse + | HookEventName::PostToolUse + | HookEventName::SessionStart + | HookEventName::UserPromptSubmit + | HookEventName::SubagentStart + ) { + warnings.push(format!( + "ignoring additionalContextLimit for {event_name:?} hook in {}: this event cannot emit additionalContext", + path.display() + )); + return None; + } + if handler_type == HookHandlerType::McpTool + && !(1..=MAX_MCP_HOOK_CONTEXT_TOKENS).contains(&limit) + { + warnings.push(format!( + "clamping additionalContextLimit from {limit} to {MAX_MCP_HOOK_CONTEXT_TOKENS} for MCP hook in {}", + path.display() + )); + return Some(MAX_MCP_HOOK_CONTEXT_TOKENS); + } + Some(limit) +} + /// Normalizes hook timeouts. SessionEnd and Interrupt default to one second and are capped at three /// seconds; all other hooks keep the standard ten-minute default. fn normalize_command_hook( @@ -1279,6 +1313,7 @@ mod tests { timeout_sec: Some(30), status_message: Some("Scanning file".to_string()), on_failure: None, + additional_context_limit: None, }], }], ); @@ -1321,6 +1356,7 @@ mod tests { timeout_sec: None, status_message: None, on_failure: None, + additional_context_limit: None, }], }], ); @@ -1362,6 +1398,7 @@ mod tests { timeout_sec: None, status_message: None, on_failure: None, + additional_context_limit: None, }, HookHandlerConfig::McpTool { server: "security".to_string(), @@ -1370,6 +1407,7 @@ mod tests { timeout_sec: Some(600), status_message: None, on_failure: None, + additional_context_limit: None, }, ], }], @@ -1521,6 +1559,53 @@ mod tests { } } + #[test] + fn mcp_context_limits_are_bounded_and_hashed_by_effective_value() { + let source_path = source_path(); + let hook_states = std::collections::HashMap::new(); + let mut handlers = Vec::new(); + let mut entries = Vec::new(); + let mut warnings = Vec::new(); + let mut display_order = 0; + for limit in [None, Some(2_500), Some(0), Some(10_000), Some(10_001)] { + let hook = serde_json::from_value(serde_json::json!({ + "type": "mcp_tool", "server": "scanner", "tool": "check", + "additionalContextLimit": limit, + })) + .expect("MCP hook"); + append_matcher_groups( + &mut handlers, + &mut entries, + &mut warnings, + &mut display_order, + &mut hook_handler_source(&source_path, &hook_states), + HookEventName::SessionStart, + vec![MatcherGroup { + matcher: None, + hooks: vec![hook], + }], + ); + } + assert_eq!( + entries + .iter() + .map(|entry| entry.additional_context_limit) + .collect::>(), + [None, Some(2_500), Some(10_000), Some(10_000), Some(10_000)] + ); + assert_eq!( + handlers[2].additional_context_limit, + AdditionalContextLimit::from_config(Some(10_000)) + ); + assert_eq!(entries[0].current_hash, entries[1].current_hash); + assert_ne!(entries[0].current_hash, entries[2].current_hash); + assert_eq!(entries[2].current_hash, entries[3].current_hash); + assert_eq!(entries[3].current_hash, entries[4].current_hash); + assert_eq!(warnings.len(), 2); + assert!(warnings[0].contains("clamping additionalContextLimit from 0 to 10000")); + assert!(warnings[1].contains("clamping additionalContextLimit from 10001 to 10000")); + } + #[test] fn unsupported_event_warns_and_ignores_additional_context_limit() { let source_path = source_path(); diff --git a/codex-rs/hooks/src/engine/mod.rs b/codex-rs/hooks/src/engine/mod.rs index c52c31c832..47cba9f35d 100644 --- a/codex-rs/hooks/src/engine/mod.rs +++ b/codex-rs/hooks/src/engine/mod.rs @@ -393,6 +393,8 @@ impl ClaudeHooksEngine { timeout_sec, status_message, on_failure, + // Executor-scoped cleanup events cannot emit additionalContext. + additional_context_limit: _, } = handler else { unreachable!("allowlisted executor handler must be an MCP tool"); diff --git a/codex-rs/hooks/src/engine/mod_tests.rs b/codex-rs/hooks/src/engine/mod_tests.rs index d10def8466..c0396029c8 100644 --- a/codex-rs/hooks/src/engine/mod_tests.rs +++ b/codex-rs/hooks/src/engine/mod_tests.rs @@ -416,6 +416,7 @@ fn required_managed_mcp_hooks_reject_empty_targets() { timeout_sec: None, status_message: None, on_failure: None, + additional_context_limit: None, }], }], ..Default::default() @@ -457,6 +458,7 @@ fn required_managed_session_end_mcp_hooks_reject_startup() { timeout_sec: None, status_message: None, on_failure: None, + additional_context_limit: None, }], }], ..Default::default() @@ -1898,6 +1900,7 @@ fn bundled_cleanup_trust_does_not_extend_to_other_handlers() { timeout_sec: None, status_message: None, on_failure: None, + additional_context_limit: None, }, HookHandlerConfig::McpTool { server: "other_server".to_string(), @@ -1906,6 +1909,7 @@ fn bundled_cleanup_trust_does_not_extend_to_other_handlers() { timeout_sec: None, status_message: None, on_failure: None, + additional_context_limit: None, }, HookHandlerConfig::Command { command: "echo cleanup".to_string(), @@ -1992,6 +1996,7 @@ fn local_hosted_app_cleanup_hooks_require_saved_trust() { timeout_sec: None, status_message: None, on_failure: None, + additional_context_limit: None, }; let discovered = super::discovery::discover_handlers( /*config_layer_stack*/ None, @@ -2442,6 +2447,7 @@ fn executor_stop_hook_fixture() -> ( timeout_sec: None, status_message: None, on_failure: None, + additional_context_limit: None, }], }], ..Default::default() diff --git a/codex-rs/protocol/src/hooks.rs b/codex-rs/protocol/src/hooks.rs index 4a5e33487a..dd6b2bee7c 100644 --- a/codex-rs/protocol/src/hooks.rs +++ b/codex-rs/protocol/src/hooks.rs @@ -145,6 +145,8 @@ pub struct MatcherGroup { pub hooks: Vec, } +pub const MAX_MCP_HOOK_CONTEXT_TOKENS: usize = 10_000; + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(tag = "type")] pub enum HookHandlerConfig { @@ -188,6 +190,19 @@ pub enum HookHandlerConfig { /// Defaults to continue; block applies the event's blocking behavior on failure. #[serde(default, rename = "onFailure", skip_serializing_if = "Option::is_none")] on_failure: Option, + /// Approximate token threshold for spilling plaintext `additionalContext` to disk. + /// Defaults to 2,500. For MCP hooks, `0` and values above 10,000 + /// trigger a warning and use 10,000. Command hooks can disable spilling + /// with `0` or set a higher threshold. The MCP ceiling mirrors the + /// current default tool-output budget and may change in the future. + /// Encrypted hook output has a separate byte limit. + #[serde( + default, + rename = "additionalContextLimit", + skip_serializing_if = "Option::is_none" + )] + #[schemars(range(min = 1, max = "MAX_MCP_HOOK_CONTEXT_TOKENS"))] + additional_context_limit: Option, }, #[serde(rename = "prompt")] Prompt {}, diff --git a/sdk/python/src/openai_codex/generated/v2_all.py b/sdk/python/src/openai_codex/generated/v2_all.py index 3e0c5a8232..01b9be778e 100644 --- a/sdk/python/src/openai_codex/generated/v2_all.py +++ b/sdk/python/src/openai_codex/generated/v2_all.py @@ -1070,6 +1070,14 @@ class McpToolConfiguredHookHandler(BaseModel): model_config = ConfigDict( populate_by_name=True, ) + additional_context_limit: Annotated[ + int | None, + Field( + alias="additionalContextLimit", + description="Approximate token threshold for spilling plaintext `additionalContext` to disk. Defaults to 2,500. For MCP hooks, `0` and values above 10,000 trigger a warning and use 10,000. Command hooks can disable spilling with `0` or set a higher threshold. The MCP ceiling mirrors the current default tool-output budget and may change in the future. Encrypted hook output has a separate byte limit.", + ge=0, + ), + ] = None input: dict[str, Any] on_failure: Annotated[ConfiguredHookFailurePolicy | None, Field(alias="onFailure")] = None server: str @@ -9379,7 +9387,7 @@ class HookMetadata1(BaseModel): int | None, Field( alias="additionalContextLimit", - description="Configured `additionalContext` spill threshold. `null` uses 2,500 tokens; `0` disables spilling.", + description="Configured `additionalContext` spill threshold. `null` uses 2,500 approximate tokens. Only command hooks support `0` (no spill) or values above 10,000.", ge=0, ), ] = None @@ -9416,7 +9424,7 @@ class HookMetadata2(BaseModel): int | None, Field( alias="additionalContextLimit", - description="Configured `additionalContext` spill threshold. `null` uses 2,500 tokens; `0` disables spilling.", + description="Configured `additionalContext` spill threshold. `null` uses 2,500 approximate tokens. Only command hooks support `0` (no spill) or values above 10,000.", ge=0, ), ] = None @@ -9453,7 +9461,7 @@ class PromptHookMetadata(BaseModel): int | None, Field( alias="additionalContextLimit", - description="Configured `additionalContext` spill threshold. `null` uses 2,500 tokens; `0` disables spilling.", + description="Configured `additionalContext` spill threshold. `null` uses 2,500 approximate tokens. Only command hooks support `0` (no spill) or values above 10,000.", ge=0, ), ] = None @@ -9488,7 +9496,7 @@ class AgentHookMetadata(BaseModel): int | None, Field( alias="additionalContextLimit", - description="Configured `additionalContext` spill threshold. `null` uses 2,500 tokens; `0` disables spilling.", + description="Configured `additionalContext` spill threshold. `null` uses 2,500 approximate tokens. Only command hooks support `0` (no spill) or values above 10,000.", ge=0, ), ] = None