Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Add hook configuration to environment attachments (#56302)

andrewgu-oai7a5860da3507
diff --git a/codex-rs/config/src/hook_config.rs b/codex-rs/config/src/hook_config.rs
index 7fd1eef6cd..913ad56500 100644
--- a/codex-rs/config/src/hook_config.rs
+++ b/codex-rs/config/src/hook_config.rs
@@ -2,7 +2,9 @@ use std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;
-use codex_protocol::protocol::HookEventName;
+pub use codex_protocol::hooks::HookEventsToml;
+pub use codex_protocol::hooks::HookHandlerConfig;
+pub use codex_protocol::hooks::MatcherGroup;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
@@ -35,204 +37,6 @@ pub struct HookStateToml {
pub trusted_content_hash: Option<String>,
}
-#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
-pub struct HookEventsToml {
- #[serde(rename = "PreModelRequest", default)]
- pub pre_model_request: Vec<MatcherGroup>,
- #[serde(rename = "PostModelRequest", default)]
- pub post_model_request: Vec<MatcherGroup>,
- #[serde(rename = "PreToolUse", default)]
- pub pre_tool_use: Vec<MatcherGroup>,
- #[serde(rename = "PermissionRequest", default)]
- pub permission_request: Vec<MatcherGroup>,
- #[serde(rename = "PostToolUse", default)]
- pub post_tool_use: Vec<MatcherGroup>,
- #[serde(rename = "PreCompact", default)]
- pub pre_compact: Vec<MatcherGroup>,
- #[serde(rename = "PostCompact", default)]
- pub post_compact: Vec<MatcherGroup>,
- #[serde(rename = "SessionStart", default)]
- pub session_start: Vec<MatcherGroup>,
- #[serde(rename = "SessionEnd", default)]
- pub session_end: Vec<MatcherGroup>,
- #[serde(rename = "UserPromptSubmit", default)]
- pub user_prompt_submit: Vec<MatcherGroup>,
- #[serde(rename = "SubagentStart", default)]
- pub subagent_start: Vec<MatcherGroup>,
- #[serde(rename = "SubagentStop", default)]
- pub subagent_stop: Vec<MatcherGroup>,
- #[serde(rename = "Stop", default)]
- pub stop: Vec<MatcherGroup>,
- #[serde(rename = "Interrupt", default)]
- pub interrupt: Vec<MatcherGroup>,
-}
-
-impl HookEventsToml {
- pub fn is_empty(&self) -> bool {
- let Self {
- pre_model_request,
- post_model_request,
- pre_tool_use,
- permission_request,
- post_tool_use,
- pre_compact,
- post_compact,
- session_start,
- session_end,
- user_prompt_submit,
- subagent_start,
- subagent_stop,
- stop,
- interrupt,
- } = self;
- pre_model_request.is_empty()
- && post_model_request.is_empty()
- && pre_tool_use.is_empty()
- && permission_request.is_empty()
- && post_tool_use.is_empty()
- && pre_compact.is_empty()
- && post_compact.is_empty()
- && session_start.is_empty()
- && session_end.is_empty()
- && user_prompt_submit.is_empty()
- && subagent_start.is_empty()
- && subagent_stop.is_empty()
- && stop.is_empty()
- && interrupt.is_empty()
- }
-
- pub fn handler_count(&self) -> usize {
- let Self {
- pre_model_request,
- post_model_request,
- pre_tool_use,
- permission_request,
- post_tool_use,
- pre_compact,
- post_compact,
- session_start,
- session_end,
- user_prompt_submit,
- subagent_start,
- subagent_stop,
- stop,
- interrupt,
- } = self;
- [
- pre_model_request,
- post_model_request,
- pre_tool_use,
- permission_request,
- post_tool_use,
- pre_compact,
- post_compact,
- session_start,
- session_end,
- user_prompt_submit,
- subagent_start,
- subagent_stop,
- stop,
- interrupt,
- ]
- .into_iter()
- .flatten()
- .map(|group| group.hooks.len())
- .sum()
- }
-
- pub fn into_matcher_groups(mut self) -> [(HookEventName, Vec<MatcherGroup>); 14] {
- self.matcher_groups_mut()
- .map(|(event, groups)| (event, std::mem::take(groups)))
- }
-
- pub fn matcher_groups_mut(&mut self) -> [(HookEventName, &mut Vec<MatcherGroup>); 14] {
- use HookEventName as Event;
-
- [
- (Event::PreModelRequest, &mut self.pre_model_request),
- (Event::PostModelRequest, &mut self.post_model_request),
- (Event::PreToolUse, &mut self.pre_tool_use),
- (Event::PermissionRequest, &mut self.permission_request),
- (Event::PostToolUse, &mut self.post_tool_use),
- (Event::PreCompact, &mut self.pre_compact),
- (Event::PostCompact, &mut self.post_compact),
- (Event::SessionStart, &mut self.session_start),
- (Event::SessionEnd, &mut self.session_end),
- (Event::UserPromptSubmit, &mut self.user_prompt_submit),
- (Event::SubagentStart, &mut self.subagent_start),
- (Event::SubagentStop, &mut self.subagent_stop),
- (Event::Stop, &mut self.stop),
- (Event::Interrupt, &mut self.interrupt),
- ]
- }
-}
-
-#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
-pub struct MatcherGroup {
- #[serde(default)]
- pub matcher: Option<String>,
- #[serde(default)]
- pub hooks: Vec<HookHandlerConfig>,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
-#[serde(tag = "type")]
-pub enum HookHandlerConfig {
- #[serde(rename = "command")]
- Command {
- command: String,
- #[serde(default, rename = "commandWindows", alias = "command_windows")]
- command_windows: Option<String>,
- #[serde(default, rename = "timeout")]
- timeout_sec: Option<u64>,
- #[serde(default)]
- r#async: bool,
- #[serde(default, rename = "statusMessage")]
- status_message: Option<String>,
- /// Approximate token threshold for spilling this hook's `additionalContext` to disk.
- /// Unset uses 2,500 tokens; `0` disables spilling for this hook. The threshold is
- /// evaluated against the original context; a spilled preview also includes recovery
- /// metadata.
- #[serde(
- default,
- rename = "additionalContextLimit",
- skip_serializing_if = "Option::is_none"
- )]
- additional_context_limit: Option<usize>,
- },
- #[serde(rename = "mcp_tool")]
- McpTool {
- server: String,
- tool: String,
- #[serde(default, deserialize_with = "deserialize_mcp_tool_input")]
- input: serde_json::Map<String, serde_json::Value>,
- #[serde(default, rename = "timeout")]
- timeout_sec: Option<u64>,
- #[serde(default, rename = "statusMessage")]
- status_message: Option<String>,
- },
- #[serde(rename = "prompt")]
- Prompt {},
- #[serde(rename = "agent")]
- Agent {},
-}
-
-// Reject values such as null that cannot be represented in TOML for trust hashing.
-fn deserialize_mcp_tool_input<'de, D>(
- deserializer: D,
-) -> Result<serde_json::Map<String, serde_json::Value>, D::Error>
-where
- D: serde::Deserializer<'de>,
-{
- let input = serde_json::Map::deserialize(deserializer)?;
- toml::Value::try_from(&input).map_err(|error| {
- serde::de::Error::custom(format!(
- "MCP hook input must be representable as TOML: {error}"
- ))
- })?;
- Ok(input)
-}
-
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ManagedHooksRequirementsToml {
pub managed_dir: Option<PathBuf>,
diff --git a/codex-rs/core/src/agents_md_tests.rs b/codex-rs/core/src/agents_md_tests.rs
index a5b748dccd..aad04d540c 100644
--- a/codex-rs/core/src/agents_md_tests.rs
+++ b/codex-rs/core/src/agents_md_tests.rs
@@ -374,6 +374,7 @@ fn resolved_local_environments<const N: usize>(
cwd: PathUri::from_abs_path(&cwd),
workspace_roots: Vec::new(),
config: EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: Vec::new(),
windows_sandbox_level: WindowsSandboxLevel::Disabled,
diff --git a/codex-rs/core/src/environment_selection.rs b/codex-rs/core/src/environment_selection.rs
index 1d81033895..84abbe0ce1 100644
--- a/codex-rs/core/src/environment_selection.rs
+++ b/codex-rs/core/src/environment_selection.rs
@@ -1470,6 +1470,7 @@ mod tests {
pub(super) fn test_environment_config() -> EnvironmentConfig {
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: Vec::new(),
windows_sandbox_level: WindowsSandboxLevel::Disabled,
@@ -1651,6 +1652,7 @@ url = "ws://127.0.0.1:8765"
shell_path: std::path::PathBuf::from("/configured/zsh"),
};
let expected_config = EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: Vec::new(),
windows_sandbox_level: WindowsSandboxLevel::Disabled,
@@ -1928,6 +1930,7 @@ url = "ws://127.0.0.1:8765"
);
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
let expected_config = EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: Vec::new(),
windows_sandbox_level: legacy_level,
@@ -2025,6 +2028,7 @@ url = "ws://127.0.0.1:8765"
assert!(starting.single_local_environment().is_none());
let next_config = EnvironmentConfig {
+ environment_hooks: Default::default(),
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::Disabled),
..test_environment_config()
};
@@ -2196,6 +2200,7 @@ url = "ws://127.0.0.1:8765"
)
.expect("replacement environment");
let next_config = EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
..test_environment_config()
};
@@ -2359,6 +2364,7 @@ url = "ws://127.0.0.1:8765"
)
.expect("replacement environment");
let child_config = EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: Vec::new(),
windows_sandbox_level: WindowsSandboxLevel::Disabled,
@@ -2438,6 +2444,7 @@ url = "ws://127.0.0.1:8765"
parent.update_selections(std::slice::from_ref(&selection));
parent.snapshot().await;
let parent_owner_config = EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: selection.workspace_roots.clone(),
windows_sandbox_level: WindowsSandboxLevel::Disabled,
@@ -2483,6 +2490,7 @@ url = "ws://127.0.0.1:8765"
let child_environment = child_snapshot.primary().expect("child environment");
let cleared_parent_owner_config = EnvironmentConfig {
+ environment_hooks: Default::default(),
selected_capability_roots: Vec::new(),
..parent_owner_config.clone()
};
diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs
index 8726cd6990..039dc918fd 100644
--- a/codex-rs/core/src/mcp_tool_call_tests.rs
+++ b/codex-rs/core/src/mcp_tool_call_tests.rs
@@ -1361,6 +1361,7 @@ async fn mcp_sandbox_cwd_uses_matching_server_environment_uri() -> anyhow::Resul
cwd: secondary_cwd.clone(),
workspace_roots: Vec::new(),
config: EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: Vec::new(),
windows_sandbox_level: turn_context.windows_sandbox_level,
diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs
index 3431138b77..1477843968 100644
--- a/codex-rs/core/src/session/session.rs
+++ b/codex-rs/core/src/session/session.rs
@@ -182,6 +182,7 @@ impl SessionConfiguration {
pub(super) fn inferred_environment_config(&self) -> EnvironmentConfig {
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: self.allow_login_shell,
workspace_roots: Vec::new(),
permission_profile: self.permission_profile_state.snapshot(),
diff --git a/codex-rs/core/src/shell_snapshot_tests.rs b/codex-rs/core/src/shell_snapshot_tests.rs
index fc191bf590..84dcbaf86b 100644
--- a/codex-rs/core/src/shell_snapshot_tests.rs
+++ b/codex-rs/core/src/shell_snapshot_tests.rs
@@ -376,6 +376,7 @@ async fn inactive_profiles_keep_snapshots_but_active_brokers_require_sandbox() -
/*prefer_executor_snapshots*/ false,
);
let mut config = EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: Vec::new(),
windows_sandbox_level: WindowsSandboxLevel::Disabled,
diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs
index 98d4547f2f..a2afab3285 100644
--- a/codex-rs/core/src/thread_manager_tests.rs
+++ b/codex-rs/core/src/thread_manager_tests.rs
@@ -1388,6 +1388,7 @@ async fn spawn_internal_session_preserves_parent_lineage_without_forking_history
.expect("parent should have an environment");
reviewer_environment.config =
EnvironmentConfigState::Ready(codex_protocol::protocol::EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: reviewer_environment.workspace_roots.clone(),
permission_profile: config.permissions.permission_profile_state().snapshot(),
diff --git a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs
index 8dd60a07c8..8c5d7693a2 100644
--- a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs
+++ b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs
@@ -28,6 +28,7 @@ fn test_turn_environment(environment_id: &str) -> crate::session::turn_context::
cwd: PathUri::from_abs_path(&std::env::temp_dir().abs()),
workspace_roots: Vec::new(),
config: EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: Vec::new(),
windows_sandbox_level: WindowsSandboxLevel::Disabled,
diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs
index 35c70df79d..f0ba8205d4 100644
--- a/codex-rs/core/src/tools/runtimes/unified_exec.rs
+++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs
@@ -783,6 +783,7 @@ mod tests {
cwd,
workspace_roots: Vec::new(),
config: EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: Vec::new(),
windows_sandbox_level: WindowsSandboxLevel::Disabled,
diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs
index e42116a480..5b16177eb9 100644
--- a/codex-rs/core/tests/common/test_codex.rs
+++ b/codex-rs/core/tests/common/test_codex.rs
@@ -159,6 +159,7 @@ pub fn environment_config_for_selection(
None => PermissionProfileSnapshot::legacy(profile),
};
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: permissions.allow_login_shell,
workspace_roots: selection.workspace_roots.clone(),
permission_profile,
diff --git a/codex-rs/core/tests/suite/agent_execution.rs b/codex-rs/core/tests/suite/agent_execution.rs
index cf80fc38a0..2ab7c4ec53 100644
--- a/codex-rs/core/tests/suite/agent_execution.rs
+++ b/codex-rs/core/tests/suite/agent_execution.rs
@@ -470,6 +470,7 @@ async fn v2_residency_reload_preserves_inherited_environment_and_tools(
.await?;
owner_workspace_roots.push(owner_workspace_root);
child_environment.config = EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: test.config.permissions.allow_login_shell,
workspace_roots: owner_workspace_roots,
permission_profile: PermissionProfileSnapshot::legacy(child_permissions),
diff --git a/codex-rs/core/tests/suite/exec_policy.rs b/codex-rs/core/tests/suite/exec_policy.rs
index fb7ad89755..1f2e92dbf5 100644
--- a/codex-rs/core/tests/suite/exec_policy.rs
+++ b/codex-rs/core/tests/suite/exec_policy.rs
@@ -803,6 +803,7 @@ async fn environment_command_restrictions_override_saved_prefix_approvals() -> R
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::Disabled),
@@ -830,6 +831,7 @@ async fn environment_command_restrictions_override_saved_prefix_approvals() -> R
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::Disabled),
@@ -936,6 +938,7 @@ async fn environment_command_policy_changes_invalidate_session_approvals() -> Re
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(
diff --git a/codex-rs/core/tests/suite/executor_discovery_v2.rs b/codex-rs/core/tests/suite/executor_discovery_v2.rs
index 457677d42d..20d88fcaa3 100644
--- a/codex-rs/core/tests/suite/executor_discovery_v2.rs
+++ b/codex-rs/core/tests/suite/executor_discovery_v2.rs
@@ -625,6 +625,7 @@ async fn check_acquisition(enabled: bool, supported: bool) -> Result<()> {
selection.workspace_roots = vec![cwd.clone()];
selection.config =
codex_protocol::protocol::EnvironmentConfigState::Ready(codex_core::EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: codex_protocol::models::PermissionProfileSnapshot::legacy(
diff --git a/codex-rs/core/tests/suite/guardian_review.rs b/codex-rs/core/tests/suite/guardian_review.rs
index ec0ac13dc6..2f2b45e6f6 100644
--- a/codex-rs/core/tests/suite/guardian_review.rs
+++ b/codex-rs/core/tests/suite/guardian_review.rs
@@ -1740,6 +1740,7 @@ async fn guardian_session_is_reused_for_consecutive_tool_reviews_without_prewarm
.await;
let mut parent_environments = local_selections(test.config.cwd.clone());
let parent_environment_config = EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: test.config.permissions.allow_login_shell,
workspace_roots: parent_environments.environments[0].workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(
diff --git a/codex-rs/core/tests/suite/hooks_executor.rs b/codex-rs/core/tests/suite/hooks_executor.rs
index f033f7c64c..eec51c7399 100644
--- a/codex-rs/core/tests/suite/hooks_executor.rs
+++ b/codex-rs/core/tests/suite/hooks_executor.rs
@@ -939,6 +939,7 @@ impl ExecutorHookFixture {
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(
diff --git a/codex-rs/core/tests/suite/mcp_startup_refresh_http_proxy.rs b/codex-rs/core/tests/suite/mcp_startup_refresh_http_proxy.rs
index 4590ed9b20..82c2aa4286 100644
--- a/codex-rs/core/tests/suite/mcp_startup_refresh_http_proxy.rs
+++ b/codex-rs/core/tests/suite/mcp_startup_refresh_http_proxy.rs
@@ -367,6 +367,7 @@ async fn skill_mcp_dependency_oauth_uses_configured_http_client() -> Result<()>
turn_permission_fields(PermissionProfile::Disabled, fixture.config.cwd.as_path());
let mut environments = local_selections(fixture.config.cwd.clone());
environments.environments[0].config = EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: fixture.config.permissions.allow_login_shell,
workspace_roots: environments.environments[0].workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::Disabled),
diff --git a/codex-rs/core/tests/suite/mcp_tool_exposure.rs b/codex-rs/core/tests/suite/mcp_tool_exposure.rs
index 8e557c4eaa..237aa194ae 100644
--- a/codex-rs/core/tests/suite/mcp_tool_exposure.rs
+++ b/codex-rs/core/tests/suite/mcp_tool_exposure.rs
@@ -535,6 +535,7 @@ async fn root_reconciliation_reuses_pending_apps_startup() -> Result<()> {
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(
diff --git a/codex-rs/core/tests/suite/network_approval.rs b/codex-rs/core/tests/suite/network_approval.rs
index 62b5b1bfb7..dc2328ce36 100644
--- a/codex-rs/core/tests/suite/network_approval.rs
+++ b/codex-rs/core/tests/suite/network_approval.rs
@@ -1802,6 +1802,7 @@ async fn unattributed_network_request_uses_active_turn_environment_fallback(
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: test.config.permissions.allow_login_shell,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(
@@ -2779,6 +2780,7 @@ async fn owner_network_policy_follows_the_selected_remote_command() -> Result<()
PermissionProfile::from_runtime_permissions(&filesystem, network);
}
let owner_config = EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: test.config.permissions.allow_login_shell,
workspace_roots: remote.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(permission_profile),
@@ -2796,6 +2798,7 @@ async fn owner_network_policy_follows_the_selected_remote_command() -> Result<()
};
let mut primary = local(test.cwd.path().abs());
primary.config = EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
workspace_roots: primary.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::Disabled),
network_policy: None,
@@ -3001,6 +3004,7 @@ async fn escalated_owner_network_terminal_requires_stdin_approval(
let mut proxy = NetworkProxyConfig::default();
proxy.set_allowed_domains(vec!["owner-only.invalid".to_string()]);
remote.config = EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: test.config.permissions.allow_login_shell,
workspace_roots: remote.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(
diff --git a/codex-rs/core/tests/suite/remote_env.rs b/codex-rs/core/tests/suite/remote_env.rs
index c98ae447cf..8ca62669be 100644
--- a/codex-rs/core/tests/suite/remote_env.rs
+++ b/codex-rs/core/tests/suite/remote_env.rs
@@ -619,6 +619,7 @@ async fn environment_permissions_follow_configuration_ownership() -> Result<()>
test.config.cwd.clone(),
vec![TurnEnvironmentRequest {
config: EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: test.config.permissions.allow_login_shell,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: owner_permission_profile,
@@ -1664,6 +1665,7 @@ async fn shared_executor_keeps_ready_capability_roots_scoped_to_each_attachment(
for config in [
EnvironmentConfigState::Pending,
EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: permission_profile.clone(),
@@ -1706,6 +1708,7 @@ async fn shared_executor_keeps_ready_capability_roots_scoped_to_each_attachment(
.start_thread(StartThreadOptions {
environments: Some(vec![TurnEnvironmentRequest {
config: EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: permission_profile.clone(),
@@ -1732,6 +1735,7 @@ async fn shared_executor_keeps_ready_capability_roots_scoped_to_each_attachment(
test.config.cwd.clone(),
vec![TurnEnvironmentRequest {
config: EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: permission_profile.clone(),
@@ -1793,6 +1797,7 @@ async fn shared_executor_keeps_ready_capability_roots_scoped_to_each_attachment(
test.config.cwd.clone(),
vec![TurnEnvironmentRequest {
config: EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: permission_profile.clone(),
@@ -1853,6 +1858,7 @@ async fn owner_network_policy_rejects_unsupported_environment_authority() -> Res
.first()
.context("thread should select its executor environment")?;
let owner_config = EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: test.config.permissions.allow_login_shell,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::Disabled),
@@ -1954,6 +1960,7 @@ async fn pending_attachment_installs_configuration_before_waiting_turn_resumes()
},
};
let owner_config = |id: &str, allow_login_shell: bool| EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell,
workspace_roots: vec![selection.cwd.clone(), owner_workspace_root.clone()],
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::read_only()),
@@ -2396,6 +2403,7 @@ async fn future_pending_environment_can_finish_without_retargeting_the_active_tu
..active.clone()
};
let owner_config = |selection: &TurnEnvironmentSelection, id: &str| EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: test.config.permissions.allow_login_shell,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::read_only()),
@@ -3099,6 +3107,7 @@ async fn deferred_executor_spawn_agent_inherits_ready_step_environments(
cwd: PathUri::from_abs_path(&test.config.cwd),
workspace_roots: vec![PathUri::from_abs_path(&test.config.cwd)],
config: EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: test.config.permissions.allow_login_shell,
workspace_roots: vec![PathUri::from_abs_path(&test.config.cwd)],
permission_profile: PermissionProfileSnapshot::active_with_profile_workspace_roots(
diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs
index 006c2415e8..adb7852665 100644
--- a/codex-rs/core/tests/suite/rmcp_client.rs
+++ b/codex-rs/core/tests/suite/rmcp_client.rs
@@ -867,6 +867,7 @@ async fn environment_mcp_policy_filters_runtime_config_and_model_tools(
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(
@@ -984,6 +985,7 @@ async fn future_environment_mcp_policy_applies_on_the_next_turn() -> anyhow::Res
wait_for_mcp_server(&fixture.codex, "environment_policy").await?;
let selection = fixture.codex.environment_selections().await.remove(0);
let mut config = EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: fixture.config.permissions.allow_login_shell,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(
@@ -2617,6 +2619,7 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta(
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: fixture.config.permissions.allow_login_shell,
workspace_roots: workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(
diff --git a/codex-rs/core/tests/suite/shell_snapshot.rs b/codex-rs/core/tests/suite/shell_snapshot.rs
index 4be1c96bec..5c77711920 100644
--- a/codex-rs/core/tests/suite/shell_snapshot.rs
+++ b/codex-rs/core/tests/suite/shell_snapshot.rs
@@ -766,6 +766,7 @@ async fn shell_snapshot_v2_guardian_uses_its_resolved_permissions_and_tools(
.await;
let mut requests = local_requests(test.config.cwd.clone());
requests.environment_requests[0].config = EnvironmentConfigState::Ready(EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: requests.environment_requests[0].workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::Disabled),
diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs
index acdb81445f..a6ffe30f3f 100644
--- a/codex-rs/core/tests/suite/unified_exec.rs
+++ b/codex-rs/core/tests/suite/unified_exec.rs
@@ -555,6 +555,7 @@ async fn exec_command_uses_installed_environment_shell_policy_with_explicit_over
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: true,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::Disabled),
diff --git a/codex-rs/core/tests/suite/workspace_roots.rs b/codex-rs/core/tests/suite/workspace_roots.rs
index fbe86a8fc4..73742f35d5 100644
--- a/codex-rs/core/tests/suite/workspace_roots.rs
+++ b/codex-rs/core/tests/suite/workspace_roots.rs
@@ -271,6 +271,7 @@ async fn workspace_roots_allow_file_and_command_writes_in_secondary_root(
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: test.config.permissions.allow_login_shell,
workspace_roots: vec![selection.cwd.clone(), secondary_root.clone()],
permission_profile: PermissionProfileSnapshot::legacy(
diff --git a/codex-rs/ext/extension-api/tests/registry.rs b/codex-rs/ext/extension-api/tests/registry.rs
index 8b35456b87..a93603f121 100644
--- a/codex-rs/ext/extension-api/tests/registry.rs
+++ b/codex-rs/ext/extension-api/tests/registry.rs
@@ -38,6 +38,7 @@ use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
+use codex_protocol::protocol::TurnEnvironmentRequest;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::protocol::WarningEvent;
use codex_utils_path_uri::PathUri;
@@ -74,20 +75,24 @@ fn mcp_contribution_context_identifies_the_running_thread() {
fn mcp_context_preserves_selected_executor_order_and_unavailability() {
let config = ();
let environments = vec![
- TurnEnvironmentSelection {
- environment_id: "starting-primary".to_owned(),
- cwd: PathUri::parse("file:///workspace").expect("workspace URI"),
- workspace_roots: Vec::new(),
- selected_capability_roots: Default::default(),
- config: EnvironmentConfigState::Pending,
- },
- TurnEnvironmentSelection {
- environment_id: "ready-secondary".to_owned(),
- cwd: PathUri::parse("file:///other").expect("workspace URI"),
- workspace_roots: Vec::new(),
- selected_capability_roots: Default::default(),
- config: EnvironmentConfigState::FromThread,
- },
+ TurnEnvironmentSelection::new(
+ TurnEnvironmentRequest {
+ environment_id: "starting-primary".to_owned(),
+ cwd: PathUri::parse("file:///workspace").expect("workspace URI"),
+ workspace_roots: Vec::new(),
+ config: EnvironmentConfigState::Pending,
+ },
+ &[],
+ ),
+ TurnEnvironmentSelection::new(
+ TurnEnvironmentRequest {
+ environment_id: "ready-secondary".to_owned(),
+ cwd: PathUri::parse("file:///other").expect("workspace URI"),
+ workspace_roots: Vec::new(),
+ config: EnvironmentConfigState::FromThread,
+ },
+ &[],
+ ),
];
let context = McpServerContributionContext::global(&config);
assert_eq!(context.selected_environments(), None);
diff --git a/codex-rs/ext/mcp/tests/plugin_mcp.rs b/codex-rs/ext/mcp/tests/plugin_mcp.rs
index d9b5a99def..0f6167099d 100644
--- a/codex-rs/ext/mcp/tests/plugin_mcp.rs
+++ b/codex-rs/ext/mcp/tests/plugin_mcp.rs
@@ -824,6 +824,7 @@ async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
.environment_ready(
&selection,
EnvironmentConfig {
+ environment_hooks: Default::default(),
allow_login_shell: false,
workspace_roots: selection.workspace_roots.clone(),
permission_profile: PermissionProfileSnapshot::legacy(
diff --git a/codex-rs/protocol/src/environment.rs b/codex-rs/protocol/src/environment.rs
index 1ffc540912..c9f1a960a1 100644
--- a/codex-rs/protocol/src/environment.rs
+++ b/codex-rs/protocol/src/environment.rs
@@ -190,6 +190,8 @@ pub fn has_full_access<'a>(
/// Resolved configuration for a thread/environment attachment.
#[derive(Clone, PartialEq)]
pub struct EnvironmentConfig {
+ /// Hooks from this environment's effective managed requirements.
+ pub environment_hooks: crate::hooks::HookEventsToml,
/// Whether shell tools may start login shells in this environment.
pub allow_login_shell: bool,
/// Effective workspace roots resolved for this environment attachment.
@@ -218,6 +220,7 @@ impl std::fmt::Debug for EnvironmentConfig {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("EnvironmentConfig")
+ .field("environment_hooks", &self.environment_hooks.handler_count())
.field("allow_login_shell", &self.allow_login_shell)
.field("workspace_roots", &self.workspace_roots)
.field("permission_profile", &self.permission_profile)
diff --git a/codex-rs/protocol/src/hooks.rs b/codex-rs/protocol/src/hooks.rs
new file mode 100644
index 0000000000..20bd7910d1
--- /dev/null
+++ b/codex-rs/protocol/src/hooks.rs
@@ -0,0 +1,213 @@
+//! Shared hook handler configuration for local and owner-managed environment sources.
+
+use crate::protocol::HookEventName;
+use schemars::JsonSchema;
+use serde::Deserialize;
+use serde::Serialize;
+
+#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
+pub struct HookEventsToml {
+ #[serde(rename = "PreModelRequest", default)]
+ pub pre_model_request: Vec<MatcherGroup>,
+ #[serde(rename = "PostModelRequest", default)]
+ pub post_model_request: Vec<MatcherGroup>,
+ #[serde(rename = "PreToolUse", default)]
+ pub pre_tool_use: Vec<MatcherGroup>,
+ #[serde(rename = "PermissionRequest", default)]
+ pub permission_request: Vec<MatcherGroup>,
+ #[serde(rename = "PostToolUse", default)]
+ pub post_tool_use: Vec<MatcherGroup>,
+ #[serde(rename = "PreCompact", default)]
+ pub pre_compact: Vec<MatcherGroup>,
+ #[serde(rename = "PostCompact", default)]
+ pub post_compact: Vec<MatcherGroup>,
+ #[serde(rename = "SessionStart", default)]
+ pub session_start: Vec<MatcherGroup>,
+ #[serde(rename = "SessionEnd", default)]
+ pub session_end: Vec<MatcherGroup>,
+ #[serde(rename = "UserPromptSubmit", default)]
+ pub user_prompt_submit: Vec<MatcherGroup>,
+ #[serde(rename = "SubagentStart", default)]
+ pub subagent_start: Vec<MatcherGroup>,
+ #[serde(rename = "SubagentStop", default)]
+ pub subagent_stop: Vec<MatcherGroup>,
+ #[serde(rename = "Stop", default)]
+ pub stop: Vec<MatcherGroup>,
+ #[serde(rename = "Interrupt", default)]
+ pub interrupt: Vec<MatcherGroup>,
+}
+
+impl HookEventsToml {
+ pub fn is_empty(&self) -> bool {
+ let Self {
+ pre_model_request,
+ post_model_request,
+ pre_tool_use,
+ permission_request,
+ post_tool_use,
+ pre_compact,
+ post_compact,
+ session_start,
+ session_end,
+ user_prompt_submit,
+ subagent_start,
+ subagent_stop,
+ stop,
+ interrupt,
+ } = self;
+ pre_model_request.is_empty()
+ && post_model_request.is_empty()
+ && pre_tool_use.is_empty()
+ && permission_request.is_empty()
+ && post_tool_use.is_empty()
+ && pre_compact.is_empty()
+ && post_compact.is_empty()
+ && session_start.is_empty()
+ && session_end.is_empty()
+ && user_prompt_submit.is_empty()
+ && subagent_start.is_empty()
+ && subagent_stop.is_empty()
+ && stop.is_empty()
+ && interrupt.is_empty()
+ }
+
+ pub fn handler_count(&self) -> usize {
+ let Self {
+ pre_model_request,
+ post_model_request,
+ pre_tool_use,
+ permission_request,
+ post_tool_use,
+ pre_compact,
+ post_compact,
+ session_start,
+ session_end,
+ user_prompt_submit,
+ subagent_start,
+ subagent_stop,
+ stop,
+ interrupt,
+ } = self;
+ [
+ pre_model_request,
+ post_model_request,
+ pre_tool_use,
+ permission_request,
+ post_tool_use,
+ pre_compact,
+ post_compact,
+ session_start,
+ session_end,
+ user_prompt_submit,
+ subagent_start,
+ subagent_stop,
+ stop,
+ interrupt,
+ ]
+ .into_iter()
+ .flatten()
+ .map(|group| group.hooks.len())
+ .sum()
+ }
+
+ pub fn into_matcher_groups(mut self) -> [(HookEventName, Vec<MatcherGroup>); 14] {
+ self.matcher_groups_mut()
+ .map(|(event, groups)| (event, std::mem::take(groups)))
+ }
+
+ pub fn matcher_groups_mut(&mut self) -> [(HookEventName, &mut Vec<MatcherGroup>); 14] {
+ use HookEventName as Event;
+
+ [
+ (Event::PreModelRequest, &mut self.pre_model_request),
+ (Event::PostModelRequest, &mut self.post_model_request),
+ (Event::PreToolUse, &mut self.pre_tool_use),
+ (Event::PermissionRequest, &mut self.permission_request),
+ (Event::PostToolUse, &mut self.post_tool_use),
+ (Event::PreCompact, &mut self.pre_compact),
+ (Event::PostCompact, &mut self.post_compact),
+ (Event::SessionStart, &mut self.session_start),
+ (Event::SessionEnd, &mut self.session_end),
+ (Event::UserPromptSubmit, &mut self.user_prompt_submit),
+ (Event::SubagentStart, &mut self.subagent_start),
+ (Event::SubagentStop, &mut self.subagent_stop),
+ (Event::Stop, &mut self.stop),
+ (Event::Interrupt, &mut self.interrupt),
+ ]
+ }
+}
+
+#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
+pub struct MatcherGroup {
+ #[serde(default)]
+ pub matcher: Option<String>,
+ #[serde(default)]
+ pub hooks: Vec<HookHandlerConfig>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
+#[serde(tag = "type")]
+pub enum HookHandlerConfig {
+ #[serde(rename = "command")]
+ Command {
+ command: String,
+ #[serde(default, rename = "commandWindows", alias = "command_windows")]
+ command_windows: Option<String>,
+ #[serde(default, rename = "timeout")]
+ timeout_sec: Option<u64>,
+ #[serde(default)]
+ r#async: bool,
+ #[serde(default, rename = "statusMessage")]
+ status_message: Option<String>,
+ /// Approximate token threshold for spilling this hook's `additionalContext` to disk.
+ /// Unset uses 2,500 tokens; `0` disables spilling for this hook. The threshold is
+ /// evaluated against the original context; a spilled preview also includes recovery
+ /// metadata.
+ #[serde(
+ default,
+ rename = "additionalContextLimit",
+ skip_serializing_if = "Option::is_none"
+ )]
+ additional_context_limit: Option<usize>,
+ },
+ #[serde(rename = "mcp_tool")]
+ McpTool {
+ server: String,
+ tool: String,
+ #[serde(default, deserialize_with = "deserialize_mcp_tool_input")]
+ input: serde_json::Map<String, serde_json::Value>,
+ #[serde(default, rename = "timeout")]
+ timeout_sec: Option<u64>,
+ #[serde(default, rename = "statusMessage")]
+ status_message: Option<String>,
+ },
+ #[serde(rename = "prompt")]
+ Prompt {},
+ #[serde(rename = "agent")]
+ Agent {},
+}
+
+// Reject values such as null that cannot be represented in TOML for trust hashing.
+fn deserialize_mcp_tool_input<'de, D>(
+ deserializer: D,
+) -> Result<serde_json::Map<String, serde_json::Value>, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ let input = serde_json::Map::deserialize(deserializer)?;
+ fn representable(value: &serde_json::Value) -> bool {
+ match value {
+ serde_json::Value::Null => false,
+ serde_json::Value::Number(n) => !n.is_u64() || n.as_i64().is_some(),
+ serde_json::Value::Array(items) => items.iter().all(representable),
+ serde_json::Value::Object(items) => items.values().all(representable),
+ serde_json::Value::Bool(_) | serde_json::Value::String(_) => true,
+ }
+ }
+ if !input.values().all(representable) {
+ return Err(serde::de::Error::custom(
+ "MCP hook input must be representable as TOML",
+ ));
+ }
+ Ok(input)
+}
diff --git a/codex-rs/protocol/src/lib.rs b/codex-rs/protocol/src/lib.rs
index 17e22cc5af..6e6559f9df 100644
--- a/codex-rs/protocol/src/lib.rs
+++ b/codex-rs/protocol/src/lib.rs
@@ -28,6 +28,7 @@ pub mod dynamic_tools;
mod environment;
pub mod error;
pub mod exec_output;
+pub mod hooks;
pub mod items;
mod legacy_events;
pub mod local_media;