From 9ecd72ff13502c4b03865a06d37fec84e6f18a0d Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Tue, 26 May 2026 13:15:24 -0700 Subject: [PATCH] Fix hook env file lifecycle --- codex-rs/core/src/hook_env.rs | 154 ++++++++++++++++++++++-------- codex-rs/core/src/hook_runtime.rs | 3 + codex-rs/core/src/session/mod.rs | 4 + 3 files changed, 121 insertions(+), 40 deletions(-) diff --git a/codex-rs/core/src/hook_env.rs b/codex-rs/core/src/hook_env.rs index ade621f312..d33a608884 100644 --- a/codex-rs/core/src/hook_env.rs +++ b/codex-rs/core/src/hook_env.rs @@ -31,6 +31,23 @@ impl HookEnvFile { &self.path } + /// Clears any env updates from an earlier SessionStart boundary. + /// + /// Each SessionStart event gets a fresh file. Hooks that append updates rebuild the overlay + /// for the current boundary, while removed hooks leave no stale file behind. + pub(crate) fn reset(&self) { + match fs::remove_file(self.path.as_path()) { + Ok(()) => {} + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + Err(err) => { + warn!( + path = %self.path.display(), + "failed to reset hook env file: {err}" + ); + } + } + } + /// Applies persisted hook env updates to later local tool environments. /// /// The returned names are the variables touched by the file. Shell-like tools use that list @@ -97,15 +114,15 @@ fn parse_env_value(value: &str, env: &HashMap) -> String { .strip_prefix('"') .and_then(|value| value.strip_suffix('"')) { - return expand_env_vars(&unescape_double_quoted(value), env); + return expand_double_quoted_env_value(value, env); } expand_env_vars(value.trim_end(), env) } -/// Handles the small set of backslash escapes expected inside double-quoted env values. -fn unescape_double_quoted(value: &str) -> String { +/// Parses double-quoted values, expanding unescaped env vars while preserving escaped dollars. +fn expand_double_quoted_env_value(value: &str, env: &HashMap) -> String { let mut out = String::with_capacity(value.len()); - let mut chars = value.chars(); + let mut chars = value.chars().peekable(); while let Some(ch) = chars.next() { if ch == '\\' && let Some(next) = chars.next() @@ -119,6 +136,10 @@ fn unescape_double_quoted(value: &str) -> String { } continue; } + if ch == '$' { + push_expanded_env_var_or_literal(&mut chars, env, &mut out); + continue; + } out.push(ch); } out @@ -134,46 +155,55 @@ fn expand_env_vars(value: &str, env: &HashMap) -> String { continue; } - if chars.peek() == Some(&'{') { - chars.next(); - let mut name = String::new(); - while let Some(&next) = chars.peek() { - chars.next(); - if next == '}' { - break; - } - name.push(next); - } - if is_env_name(&name) { - out.push_str(env.get(&name).map_or("", String::as_str)); - } else { - out.push_str("${"); - out.push_str(&name); - out.push('}'); - } - continue; - } - - let mut name = String::new(); - while let Some(&next) = chars.peek() { - if !is_env_name_char(next) { - break; - } - chars.next(); - name.push(next); - } - if name.is_empty() { - out.push('$'); - } else if is_env_name(&name) { - out.push_str(env.get(&name).map_or("", String::as_str)); - } else { - out.push('$'); - out.push_str(&name); - } + push_expanded_env_var_or_literal(&mut chars, env, &mut out); } out } +/// Appends the expansion for a `$` already consumed from `chars`. +fn push_expanded_env_var_or_literal( + chars: &mut std::iter::Peekable>, + env: &HashMap, + out: &mut String, +) { + if chars.peek() == Some(&'{') { + chars.next(); + let mut name = String::new(); + while let Some(&next) = chars.peek() { + chars.next(); + if next == '}' { + break; + } + name.push(next); + } + if is_env_name(&name) { + out.push_str(env.get(&name).map_or("", String::as_str)); + } else { + out.push_str("${"); + out.push_str(&name); + out.push('}'); + } + return; + } + + let mut name = String::new(); + while let Some(&next) = chars.peek() { + if !is_env_name_char(next) { + break; + } + chars.next(); + name.push(next); + } + if name.is_empty() { + out.push('$'); + } else if is_env_name(&name) { + out.push_str(env.get(&name).map_or("", String::as_str)); + } else { + out.push('$'); + out.push_str(&name); + } +} + /// Returns whether a string is a valid shell environment variable name. fn is_env_name(name: &str) -> bool { let mut chars = name.chars(); @@ -256,4 +286,48 @@ export FROM_BRACES=${FROM_DECLARE}/braces vec!["FROM_DECLARE".to_string(), "FROM_BRACES".to_string()] ); } + + #[test] + fn env_file_preserves_escaped_dollars_in_double_quotes() { + let mut env = HashMap::from([ + ("HOME".to_string(), "/home/codex".to_string()), + ("PATH".to_string(), "/usr/bin".to_string()), + ]); + + apply_env_file_lines( + &mut env, + r#" +export TEMPLATE="\$HOME/bin" +export MIXED="\$HOME:$PATH" +"#, + ); + + assert_eq!( + env, + HashMap::from([ + ("HOME".to_string(), "/home/codex".to_string()), + ("MIXED".to_string(), "$HOME:/usr/bin".to_string()), + ("PATH".to_string(), "/usr/bin".to_string()), + ("TEMPLATE".to_string(), "$HOME/bin".to_string()), + ]) + ); + } + + #[test] + fn reset_removes_existing_env_file_and_ignores_missing_file() { + let dir = tempfile::tempdir().expect("create temp dir"); + let path = + AbsolutePathBuf::try_from(dir.path().join("env.sh")).expect("absolute env file path"); + let env_file = HookEnvFile { path }; + fs::write( + env_file.path().as_path(), + "export PATH=\"/old/bin:$PATH\"\n", + ) + .expect("write env file"); + + env_file.reset(); + + assert!(!env_file.path().as_path().exists()); + env_file.reset(); + } } diff --git a/codex-rs/core/src/hook_runtime.rs b/codex-rs/core/src/hook_runtime.rs index 6452e9d5ad..0e0af58b88 100644 --- a/codex-rs/core/src/hook_runtime.rs +++ b/codex-rs/core/src/hook_runtime.rs @@ -124,6 +124,9 @@ pub(crate) async fn run_pending_session_start_hooks( source: session_start_source, }, }; + if matches!(target, StartHookTarget::SessionStart { .. }) { + sess.reset_hook_env_file(); + } let request = codex_hooks::SessionStartRequest { session_id: sess.session_id().into(), #[allow(deprecated)] diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 00d4a9b5a4..71fbf895aa 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -3248,6 +3248,10 @@ impl Session { self.services.hook_env_file.apply_to_env(env) } + pub(crate) fn reset_hook_env_file(&self) { + self.services.hook_env_file.reset(); + } + pub(crate) fn user_shell(&self) -> Arc { Arc::clone(&self.services.user_shell) }