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 4d62d91051..a7f1b41754 100644 --- a/codex-rs/app-server/tests/suite/v2/hooks_list.rs +++ b/codex-rs/app-server/tests/suite/v2/hooks_list.rs @@ -970,15 +970,24 @@ async fn hooks_list_shows_discovered_plugin_mcp_tool_hook() -> Result<()> { Ok(()) } -#[test_case::test_case("browser", "node_repl"; "node_repl")] -#[test_case::test_case("unified-computer-use", "cua_repl"; "cua_repl")] +#[test_case::test_case("browser", "node_repl", "turn_ended", HookEventName::Stop, None; "node_repl")] +#[test_case::test_case("unified-computer-use", "cua_repl", "turn_ended", HookEventName::Stop, None; "cua_repl")] +#[test_case::test_case("codex-dream-memory", "codex_apps", "codex_dream_memory.get_mec", HookEventName::SessionStart, Some("^(startup|compact)$"); "memory_without_apps_connection")] #[tokio::test] async fn hooks_list_hides_builtin_cleanup_and_preserves_other_plugin_hooks( plugin_name: &str, server: &str, + tool: &str, + event_name: HookEventName, + matcher: Option<&str>, ) -> Result<()> { let codex_home = TempDir::new()?; let cwd = TempDir::new()?; + let (event_key, event_wire) = match event_name { + HookEventName::Stop => ("stop", "Stop"), + HookEventName::SessionStart => ("session_start", "SessionStart"), + _ => unreachable!("test event"), + }; let plugin_id = format!("{plugin_name}@openai-bundled"); let plugin_root = codex_home .path() @@ -993,8 +1002,8 @@ async fn hooks_list_hides_builtin_cleanup_and_preserves_other_plugin_hooks( std::fs::write( plugin_root.join("hooks/hooks.json"), serde_json::to_vec(&serde_json::json!({ - "hooks": { "Stop": [{ "hooks": [ - { "type": "mcp_tool", "server": server, "tool": "turn_ended" }, + "hooks": { (event_wire): [{ "matcher": matcher, "hooks": [ + { "type": "mcp_tool", "server": server, "tool": tool }, { "type": "command", "command": ordinary_command, "timeout": 5 }, ] }] }, }))?, @@ -1009,7 +1018,7 @@ hooks = true [plugins."{plugin_id}"] enabled = true -[hooks.state."{plugin_id}:hooks/hooks.json:stop:0:1"] +[hooks.state."{plugin_id}:hooks/hooks.json:{event_key}:0:1"] enabled = false "# ), @@ -1036,13 +1045,13 @@ enabled = false vec![HooksListEntry { cwd: cwd.path().to_path_buf(), hooks: vec![HookMetadata { - key: format!("{plugin_id}:hooks/hooks.json:stop:0:1"), - event_name: HookEventName::Stop, + key: format!("{plugin_id}:hooks/hooks.json:{event_key}:0:1"), + event_name, handler: HookHandlerMetadata::Command { command: ordinary_command.to_string(), r#async: false, }, - matcher: None, + matcher: matcher.map(str::to_string), timeout_sec: 5, status_message: None, additional_context_limit: None, diff --git a/codex-rs/core/tests/suite/scenarios.rs b/codex-rs/core/tests/suite/scenarios.rs index e9ea6837e5..ff87eb5acc 100644 --- a/codex-rs/core/tests/suite/scenarios.rs +++ b/codex-rs/core/tests/suite/scenarios.rs @@ -1,5 +1,8 @@ //! Multi-turn Astra scenarios snapshot the model-visible request history of shipped features. +#[path = "scenarios_bundled_app_hooks.rs"] +mod bundled_app_hooks; + #[path = "scenarios_turn_input_agent_message.rs"] mod turn_input_agent_message; diff --git a/codex-rs/core/tests/suite/scenarios_bundled_app_hooks.rs b/codex-rs/core/tests/suite/scenarios_bundled_app_hooks.rs new file mode 100644 index 0000000000..2c3d1229b5 --- /dev/null +++ b/codex-rs/core/tests/suite/scenarios_bundled_app_hooks.rs @@ -0,0 +1,130 @@ +#![cfg(test)] +//! The bundled Memory hook injects context at startup and after compaction without saved trust. + +use super::*; +use core_test_support::apps_test_server::AppsTestServer; +use core_test_support::apps_test_server::recorded_apps_tool_calls; +use pretty_assertions::assert_eq; +use std::sync::Mutex; +use wiremock::Mock; +use wiremock::Request; +use wiremock::ResponseTemplate; +use wiremock::matchers::body_partial_json; +use wiremock::matchers::method; +use wiremock::matchers::path; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn bundled_memory_hook_injects_context() -> Result<()> { + skip_if_no_network!(Ok(())); + let connector_id = "connector_openai_codex_dream_memory"; + let server = start_mock_server().await; + let apps = AppsTestServer::mount_with_tools(&server, Arc::new(Mutex::new(vec![json!({ + "name": "codex_dream_memory.get_mec", + "description": "Read memory context.", + "inputSchema": { "type": "object", "properties": {} }, + "annotations": { "readOnlyHint": true }, + "_meta": { + "connector_id": connector_id, + "connector_name": "Memory", + "ui": { "visibility": ["app"] }, + "_codex_apps": { + "resource_uri": format!("connector://{connector_id}/tools/codex_dream_memory.get_mec"), + "contains_mcp_source": true, + "connector_id": connector_id, + }, + }, + })]))).await?; + Mock::given(method("POST")) + .and(path("/api/codex/ps/mcp")) + .and(body_partial_json(json!({ "method": "tools/call" }))) + .respond_with(|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.", + }, + }).to_string() }] }, + })) + }) + .with_priority(/*p*/ 1) + .mount(&server).await; + let home = Arc::new(TempDir::new()?); + let root = home + .path() + .join("plugins/cache/openai-bundled/codex-dream-memory/local"); + fs::create_dir_all(root.join(".codex-plugin"))?; + fs::write( + root.join(".codex-plugin/plugin.json"), + serde_json::to_vec(&json!({ + "name": "codex-dream-memory", + "hooks": { "hooks": { "SessionStart": [{ + "matcher": "^(startup|compact)$", + "hooks": [{ "type": "mcp_tool", "server": "codex_apps", "tool": "codex_dream_memory.get_mec" }], + }] } }, + }))?, + )?; + fs::write( + root.join(".app.json"), + serde_json::to_vec(&json!({ + "apps": { "memory": { "id": "connector_openai_codex_dream_memory" } }, + }))?, + )?; + let plugin_config = "[features]\napps = true\nplugins = true\nhooks = true\n[plugins.\"codex-dream-memory@openai-bundled\"]\nenabled = true\n[apps.connector_openai_codex_dream_memory]\n"; + fs::write(home.path().join("config.toml"), plugin_config)?; + let mut builder = test_codex() + .with_home(home) + .with_model("gpt-5.5") + .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; + for feature in [Feature::Apps, Feature::Plugins, Feature::CodexHooks] { + config.features.enable(feature).unwrap(); + } + config + .features + .disable(Feature::ExecutorCapabilityDiscovery) + .unwrap(); + // Exercise local compaction using the ordinary mock Responses endpoint. + config.model_provider.name = "OpenAI (test)".into(); + }); + let test = builder.build_with_auto_env(&server).await?; + assert!(!test.config.bypass_hook_trust); + let responses = mount_sse_sequence( + &server, + (0..3) + .map(|index| { + sse(vec![ + ev_assistant_message(&format!("message-{index}"), "Done."), + ev_completed(&format!("response-{index}")), + ]) + }) + .collect(), + ) + .await; + test.submit_text_turn("Remember my preferences.").await?; + assert_eq!(recorded_apps_tool_calls(&server).await.len(), 1); + test.codex.submit(Op::Compact).await?; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + test.submit_text_turn("Continue after compaction.").await?; + let calls = recorded_apps_tool_calls(&server).await; + assert_eq!(calls.len(), 2); + for call in calls { + assert_eq!(call["params"]["arguments"], json!({})); + assert_eq!(call["params"]["name"], "codex_dream_memory.get_mec"); + } + 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(), + &ContextSnapshotOptions::default().rewrite_known_segments(), + ) + ); + Ok(()) +} 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 new file mode 100644 index 0000000000..2de408e3ba --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__bundled_app_hooks__bundled_memory_hook_context.snap @@ -0,0 +1,69 @@ +--- +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(),)" +--- +Scenario: A bundled App-only hook injects memory at startup and after compaction without saved trust. + +## Window 1 +-- request 1 (turn) -- +00:message/developer: + +01:message/developer[3]: + [01] + [02] + [03] + Deferred tool namespaces: + - multi_agent_v1: Tools for spawning and managing sub-agents. + +02:message/user: + +03:message/developer: + The user prefers concise answers. +04:message/user: + Remember my preferences. + +## Window 2 (after request 1: settings changed (parallel_tool_calls, tools)) +-- request 2 (compaction) -- +00:message/developer: + +01:message/developer[3]: + [01] + [02] + [03] + Deferred tool namespaces: + - multi_agent_v1: Tools for spawning and managing sub-agents. + +02:message/user: + +03:message/developer: + The user prefers concise answers. +04:message/user: + Remember my preferences. +05:message/assistant: + Done. +06:message/user: + + +## Window 3 (after request 2: input diverged at item 03, settings changed (parallel_tool_calls, tools)) +-- request 3 (turn) -- +00:message/developer: + +01:message/developer[3]: + [01] + [02] + [03] + Deferred tool namespaces: + - multi_agent_v1: Tools for spawning and managing sub-agents. + +02:message/user: + +03:message/user: + Remember my preferences. +04:message/user: + + Done. +05:message/developer: + The user prefers concise answers. +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 5d4c495d65..055ad8f05b 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -17,6 +17,7 @@ use codex_config::RequirementSource; use codex_config::TomlValue; 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::protocol::HookEventName; use codex_utils_absolute_path::AbsolutePathBuf; @@ -648,6 +649,14 @@ fn append_matcher_groups( } }; for (handler_index, handler) in group.hooks.iter().cloned().enumerate() { + let expected_app_connector_id = source.plugin_id.as_deref().and_then(|plugin_id| { + bundled_hook_app_connector_id( + plugin_id, + event_name, + group.matcher.as_deref(), + &handler, + ) + }); let normalized = match handler { HookHandlerConfig::Command { command, @@ -770,7 +779,7 @@ fn append_matcher_groups( NormalizedHandler { config, kind: ConfiguredHandlerKind::McpTool { - expected_app_connector_id: None, + expected_app_connector_id, server, tool, input, @@ -820,6 +829,7 @@ fn append_matcher_groups( /*app_connector_id*/ None, ) }); + let builtin = builtin || expected_app_connector_id.is_some(); let plugin_content_hash = match source.plugin_content_hash { Some(Ok(hash)) => Some(hash.as_str()), Some(Err(err)) if !builtin && !source.bypass_hook_trust => { diff --git a/codex-rs/hooks/src/engine/mod_tests.rs b/codex-rs/hooks/src/engine/mod_tests.rs index c3ad7a9e80..1b606f5753 100644 --- a/codex-rs/hooks/src/engine/mod_tests.rs +++ b/codex-rs/hooks/src/engine/mod_tests.rs @@ -1826,6 +1826,52 @@ fn bundled_cleanup_hooks_are_trusted_without_saved_hashes() { } } +#[test] +fn bundled_app_hook_trust_requires_exact_declaration() { + for (matcher, input, trusted) in [ + ("^(startup|compact)$", serde_json::json!({}), true), + (".*", serde_json::json!({}), false), + ( + "^(startup|compact)$", + serde_json::json!({"untrusted": true}), + false, + ), + ] { + let temp = tempdir().expect("plugin root"); + let mut source = bundled_cleanup_source( + "codex-dream-memory@openai-bundled", + "codex_apps", + "SessionStart", + ); + source.plugin_root = AbsolutePathBuf::try_from(temp.path()).unwrap(); + source.hooks = serde_json::from_value(serde_json::json!({ + "SessionStart": [{ "matcher": matcher, "hooks": [{ + "type": "mcp_tool", "server": "codex_apps", "tool": "codex_dream_memory.get_mec", "input": input, + }] }], + })).unwrap(); + let discovered = super::discovery::discover_handlers( + /*config_layer_stack*/ None, + vec![source], + Vec::new(), + /*bypass_hook_trust*/ false, + DiscoveryMode::Listing, + ); + let expected = if trusted { + HookTrustStatus::Trusted + } else { + HookTrustStatus::Untrusted + }; + assert_eq!( + ( + discovered.handlers.len(), + discovered.hook_entries[0].trust_status, + discovered.hook_entries[0].builtin + ), + (usize::from(trusted), expected, trusted) + ); + } +} + #[test] fn bundled_cleanup_trust_does_not_extend_to_other_handlers() { let temp = tempdir().expect("create plugin directory"); diff --git a/codex-rs/plugin/src/bundled_hooks.rs b/codex-rs/plugin/src/bundled_hooks.rs index 47a4eeef28..68cb0a215f 100644 --- a/codex-rs/plugin/src/bundled_hooks.rs +++ b/codex-rs/plugin/src/bundled_hooks.rs @@ -1,5 +1,5 @@ -//! Temporary cleanup-hook allowlist shared by local and executor plugin discovery. -//! This narrowly authorizes known MCP cleanup calls; it does not verify plugin signatures. +//! Temporary bundled-hook exceptions. App session hooks require connector and policy checks +//! at dispatch; cleanup hooks retain their existing trust rules. This does not verify signatures. use codex_config::HookHandlerConfig; use codex_protocol::protocol::HookEventName; @@ -111,6 +111,32 @@ const ALLOWLISTED_BUNDLED_HOOKS: &[BundledHook] = &[ }, ]; +/// Recognizes the bundled SessionStart declaration without starting Apps discovery. +/// The caller must check this connector's identity and approval policy at dispatch. +pub fn bundled_hook_app_connector_id( + plugin_id: &str, + event: HookEventName, + matcher: Option<&str>, + handler: &HookHandlerConfig, +) -> Option<&'static str> { + let HookHandlerConfig::McpTool { + server, + tool, + input, + .. + } = handler + else { + return None; + }; + (plugin_id == "codex-dream-memory@openai-bundled" + && event == HookEventName::SessionStart + && matcher == Some("^(startup|compact)$") + && server == "codex_apps" + && tool == "codex_dream_memory.get_mec" + && input.is_empty()) + .then_some("connector_openai_codex_dream_memory") +} + /// Matches a temporary unsigned cleanup exception. App targets additionally require the /// connector identity for this handler's server and tool from the caller's enabled tool /// catalog; callers without that catalog must pass `None`. diff --git a/codex-rs/plugin/src/lib.rs b/codex-rs/plugin/src/lib.rs index d623c76466..39750a73d4 100644 --- a/codex-rs/plugin/src/lib.rs +++ b/codex-rs/plugin/src/lib.rs @@ -10,6 +10,7 @@ pub mod manifest; use codex_core_plugin_common::plugin_id; mod provider; +pub use bundled_hooks::bundled_hook_app_connector_id; pub use bundled_hooks::is_allowlisted_bundled_cleanup_hook; use codex_config::HookEventsToml; use codex_utils_absolute_path::AbsolutePathBuf;