mirror of
https://github.com/openai/codex.git
synced 2026-11-15 21:50:46 +00:00
Add SessionStart hook environment overlays
This commit is contained in:
@@ -61,24 +61,6 @@ struct ContextInjectingHookOutcome {
|
||||
outcome: HookRuntimeOutcome,
|
||||
}
|
||||
|
||||
impl From<SessionStartOutcome> for ContextInjectingHookOutcome {
|
||||
fn from(value: SessionStartOutcome) -> Self {
|
||||
let SessionStartOutcome {
|
||||
hook_events,
|
||||
should_stop,
|
||||
stop_reason: _,
|
||||
additional_contexts,
|
||||
} = value;
|
||||
Self {
|
||||
hook_events,
|
||||
outcome: HookRuntimeOutcome {
|
||||
should_stop,
|
||||
additional_contexts,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<UserPromptSubmitOutcome> for ContextInjectingHookOutcome {
|
||||
fn from(value: UserPromptSubmitOutcome) -> Self {
|
||||
let UserPromptSubmitOutcome {
|
||||
@@ -135,16 +117,22 @@ pub(crate) async fn run_pending_session_start_hooks(
|
||||
};
|
||||
let hooks = sess.hooks();
|
||||
let preview_runs = hooks.preview_session_start(&request);
|
||||
if run_context_injecting_hook(
|
||||
sess,
|
||||
turn_context,
|
||||
preview_runs,
|
||||
hooks.run_session_start(request, Some(turn_context.sub_id.clone())),
|
||||
)
|
||||
.await
|
||||
.record_additional_contexts(sess, turn_context)
|
||||
.await
|
||||
{
|
||||
emit_hook_started_events(sess, turn_context, preview_runs).await;
|
||||
let SessionStartOutcome {
|
||||
hook_events,
|
||||
should_stop,
|
||||
stop_reason: _,
|
||||
additional_contexts,
|
||||
session_start_env,
|
||||
} = hooks
|
||||
.run_session_start(request, Some(turn_context.sub_id.clone()))
|
||||
.await;
|
||||
emit_hook_completed_events(sess, turn_context, hook_events).await;
|
||||
if let Some(env) = session_start_env {
|
||||
sess.replace_session_start_env(env);
|
||||
}
|
||||
record_additional_contexts(sess, turn_context, additional_contexts).await;
|
||||
if should_stop {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -569,18 +557,6 @@ where
|
||||
outcome.outcome
|
||||
}
|
||||
|
||||
impl HookRuntimeOutcome {
|
||||
async fn record_additional_contexts(
|
||||
self,
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &Arc<TurnContext>,
|
||||
) -> bool {
|
||||
record_additional_contexts(sess, turn_context, self.additional_contexts).await;
|
||||
|
||||
self.should_stop
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn record_additional_contexts(
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &Arc<TurnContext>,
|
||||
|
||||
@@ -80,6 +80,7 @@ pub(crate) mod mentions {
|
||||
mod sandbox_tags;
|
||||
pub mod sandboxing;
|
||||
mod session_prefix;
|
||||
mod session_start_env;
|
||||
mod session_startup_prewarm;
|
||||
mod shell_detect;
|
||||
pub mod skills;
|
||||
|
||||
@@ -3222,6 +3222,23 @@ impl Session {
|
||||
Arc::clone(&self.services.user_shell)
|
||||
}
|
||||
|
||||
pub(crate) fn replace_session_start_env(&self, env: HashMap<String, String>) {
|
||||
self.services.session_start_env.replace(env);
|
||||
}
|
||||
|
||||
pub(crate) fn apply_session_start_env(&self, env: &mut HashMap<String, String>) {
|
||||
self.services.session_start_env.apply(env);
|
||||
}
|
||||
|
||||
pub(crate) fn extend_session_start_env_snapshot_overrides(
|
||||
&self,
|
||||
overrides: &mut HashMap<String, String>,
|
||||
) {
|
||||
self.services
|
||||
.session_start_env
|
||||
.extend_snapshot_overrides(overrides);
|
||||
}
|
||||
|
||||
pub(crate) async fn current_rollout_path(&self) -> anyhow::Result<Option<PathBuf>> {
|
||||
let Some(live_thread) = self.live_thread() else {
|
||||
return Ok(None);
|
||||
|
||||
@@ -998,6 +998,7 @@ impl Session {
|
||||
hooks: arc_swap::ArcSwap::from_pointee(hooks),
|
||||
rollout_thread_trace,
|
||||
user_shell: Arc::new(default_shell),
|
||||
session_start_env: Default::default(),
|
||||
shell_snapshot_tx,
|
||||
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
|
||||
exec_policy,
|
||||
|
||||
@@ -4640,6 +4640,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
})),
|
||||
rollout_thread_trace: codex_rollout_trace::ThreadTraceContext::disabled(),
|
||||
user_shell: Arc::new(default_user_shell()),
|
||||
session_start_env: Default::default(),
|
||||
shell_snapshot_tx: watch::channel(None).0,
|
||||
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
|
||||
exec_policy,
|
||||
@@ -6483,6 +6484,7 @@ where
|
||||
})),
|
||||
rollout_thread_trace: codex_rollout_trace::ThreadTraceContext::disabled(),
|
||||
user_shell: Arc::new(default_user_shell()),
|
||||
session_start_env: Default::default(),
|
||||
shell_snapshot_tx: watch::channel(None).0,
|
||||
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
|
||||
exec_policy,
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use crate::exec_env::CODEX_THREAD_ID_ENV_VAR;
|
||||
|
||||
/// Session-owned environment changes emitted by `SessionStart` hooks.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SessionStartEnvOverlay {
|
||||
values: RwLock<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
impl SessionStartEnvOverlay {
|
||||
pub(crate) fn replace(&self, values: HashMap<String, String>) {
|
||||
*self.values.write().unwrap_or_else(PoisonError::into_inner) = values;
|
||||
}
|
||||
|
||||
pub(crate) fn apply(&self, env: &mut HashMap<String, String>) {
|
||||
for (key, value) in self
|
||||
.values
|
||||
.read()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.iter()
|
||||
{
|
||||
if is_runtime_owned(key) {
|
||||
continue;
|
||||
}
|
||||
insert_env_var(env, key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn extend_snapshot_overrides(&self, overrides: &mut HashMap<String, String>) {
|
||||
for (key, value) in self
|
||||
.values
|
||||
.read()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.iter()
|
||||
{
|
||||
if is_runtime_owned(key) {
|
||||
continue;
|
||||
}
|
||||
insert_env_var(overrides, key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_runtime_owned(key: &str) -> bool {
|
||||
env_key_eq(key, CODEX_THREAD_ID_ENV_VAR)
|
||||
}
|
||||
|
||||
fn insert_env_var(env: &mut HashMap<String, String>, key: String, value: String) {
|
||||
remove_env_var(env, &key);
|
||||
env.insert(key, value);
|
||||
}
|
||||
|
||||
fn remove_env_var(env: &mut HashMap<String, String>, key: &str) {
|
||||
if let Some(existing) = env
|
||||
.keys()
|
||||
.find(|candidate| env_key_eq(candidate, key))
|
||||
.cloned()
|
||||
{
|
||||
env.remove(&existing);
|
||||
}
|
||||
}
|
||||
|
||||
fn env_key_eq(candidate: &str, key: &str) -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
candidate.eq_ignore_ascii_case(key)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
candidate == key
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn applies_hook_env_with_runtime_precedence() {
|
||||
let overlay = SessionStartEnvOverlay::default();
|
||||
overlay.replace(HashMap::from([
|
||||
("CODEX_THREAD_ID".to_string(), "hook-thread".to_string()),
|
||||
("PATH".to_string(), "/hook/bin".to_string()),
|
||||
("SET_BY_POLICY".to_string(), "hook".to_string()),
|
||||
]));
|
||||
let mut env = HashMap::from([
|
||||
("CODEX_THREAD_ID".to_string(), "runtime-thread".to_string()),
|
||||
("PATH".to_string(), "/usr/bin".to_string()),
|
||||
("SET_BY_POLICY".to_string(), "policy".to_string()),
|
||||
]);
|
||||
|
||||
overlay.apply(&mut env);
|
||||
|
||||
assert_eq!(
|
||||
env,
|
||||
HashMap::from([
|
||||
("CODEX_THREAD_ID".to_string(), "runtime-thread".to_string()),
|
||||
("PATH".to_string(), "/hook/bin".to_string()),
|
||||
("SET_BY_POLICY".to_string(), "hook".to_string()),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_overrides_include_hook_env() {
|
||||
let overlay = SessionStartEnvOverlay::default();
|
||||
overlay.replace(HashMap::from([(
|
||||
"PLUGIN_HOME".to_string(),
|
||||
"/plugin".to_string(),
|
||||
)]));
|
||||
let mut overrides = HashMap::new();
|
||||
|
||||
overlay.extend_snapshot_overrides(&mut overrides);
|
||||
|
||||
assert_eq!(
|
||||
overrides,
|
||||
HashMap::from([("PLUGIN_HOME".to_string(), "/plugin".to_string())])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ pub(crate) struct SessionServices {
|
||||
pub(crate) hooks: ArcSwap<Hooks>,
|
||||
pub(crate) rollout_thread_trace: ThreadTraceContext,
|
||||
pub(crate) user_shell: Arc<crate::shell::Shell>,
|
||||
pub(crate) session_start_env: crate::session_start_env::SessionStartEnvOverlay,
|
||||
pub(crate) shell_snapshot_tx: watch::Sender<Option<Arc<crate::shell_snapshot::ShellSnapshot>>>,
|
||||
pub(crate) show_raw_agent_reasoning: bool,
|
||||
pub(crate) exec_policy: Arc<ExecPolicyManager>,
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::exec::ExecCapturePolicy;
|
||||
use crate::exec::StdoutStream;
|
||||
use crate::exec::execute_exec_request;
|
||||
use crate::exec_env::create_env;
|
||||
use crate::hook_runtime::run_pending_session_start_hooks;
|
||||
use crate::sandboxing::ExecRequest;
|
||||
use crate::session::TurnInput;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
@@ -119,6 +120,11 @@ pub(crate) async fn execute_user_shell_command(
|
||||
});
|
||||
session.send_event(turn_context.as_ref(), event).await;
|
||||
}
|
||||
if mode == UserShellCommandMode::StandaloneTurn
|
||||
&& run_pending_session_start_hooks(&session, &turn_context).await
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Execute the user's script under their default shell when known; this
|
||||
// allows commands that use shell features (pipes, &&, redirects, etc.).
|
||||
@@ -130,6 +136,7 @@ pub(crate) async fn execute_user_shell_command(
|
||||
&turn_context.shell_environment_policy,
|
||||
Some(session.conversation_id),
|
||||
);
|
||||
session.apply_session_start_env(&mut exec_env_map);
|
||||
if exec_env_map.contains_key(PROXY_ACTIVE_ENV_KEY) {
|
||||
for key in PROXY_ENV_KEYS {
|
||||
exec_env_map.remove(*key);
|
||||
@@ -144,12 +151,14 @@ pub(crate) async fn execute_user_shell_command(
|
||||
exec_env_map.remove(PROXY_GIT_SSH_COMMAND_ENV_KEY);
|
||||
}
|
||||
}
|
||||
let mut snapshot_overrides = turn_context.shell_environment_policy.r#set.clone();
|
||||
session.extend_session_start_env_snapshot_overrides(&mut snapshot_overrides);
|
||||
let exec_command = maybe_wrap_shell_lc_with_snapshot(
|
||||
&display_command,
|
||||
session_shell.as_ref(),
|
||||
#[allow(deprecated)]
|
||||
&turn_context.cwd,
|
||||
&turn_context.shell_environment_policy.r#set,
|
||||
&snapshot_overrides,
|
||||
&exec_env_map,
|
||||
);
|
||||
|
||||
|
||||
@@ -94,13 +94,15 @@ impl ShellCommandHandler {
|
||||
let command = Self::base_command(shell.as_ref(), ¶ms.command, use_login_shell);
|
||||
#[allow(deprecated)]
|
||||
let cwd = turn_context.resolve_path(params.workdir.clone());
|
||||
let mut env = create_env(&turn_context.shell_environment_policy, Some(thread_id));
|
||||
session.apply_session_start_env(&mut env);
|
||||
|
||||
Ok(ExecParams {
|
||||
command,
|
||||
cwd,
|
||||
expiration: params.timeout_ms.into(),
|
||||
capture_policy: ExecCapturePolicy::ShellTool,
|
||||
env: create_env(&turn_context.shell_environment_policy, Some(thread_id)),
|
||||
env,
|
||||
network: turn_context.network.clone(),
|
||||
sandbox_permissions: params.sandbox_permissions.unwrap_or_default(),
|
||||
windows_sandbox_level: turn_context.windows_sandbox_level,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -77,6 +78,10 @@ fn assert_safe(shell: &Shell, command: &str) {
|
||||
#[tokio::test]
|
||||
async fn shell_command_handler_to_exec_params_uses_session_shell_and_turn_context() {
|
||||
let (session, turn_context) = make_session_and_context().await;
|
||||
session.replace_session_start_env(HashMap::from([(
|
||||
"CODEX_SESSION_START_ENV_TEST".to_string(),
|
||||
"from hook".to_string(),
|
||||
)]));
|
||||
|
||||
let command = "echo hello".to_string();
|
||||
let workdir = Some("subdir".to_string());
|
||||
@@ -90,10 +95,14 @@ async fn shell_command_handler_to_exec_params_uses_session_shell_and_turn_contex
|
||||
.derive_exec_args(&command, /*use_login_shell*/ true);
|
||||
#[allow(deprecated)]
|
||||
let expected_cwd = turn_context.resolve_path(workdir.clone());
|
||||
let expected_env = create_env(
|
||||
let mut expected_env = create_env(
|
||||
&turn_context.shell_environment_policy,
|
||||
Some(session.conversation_id),
|
||||
);
|
||||
expected_env.insert(
|
||||
"CODEX_SESSION_START_ENV_TEST".to_string(),
|
||||
"from hook".to_string(),
|
||||
);
|
||||
|
||||
let params = ShellCommandToolCallParams {
|
||||
command,
|
||||
|
||||
@@ -259,6 +259,9 @@ impl ToolRuntime<ShellRequest, ExecToolCallOutput> for ShellRuntime {
|
||||
}
|
||||
(env, explicit_env_overrides)
|
||||
};
|
||||
let mut explicit_env_overrides = explicit_env_overrides;
|
||||
ctx.session
|
||||
.extend_session_start_env_snapshot_overrides(&mut explicit_env_overrides);
|
||||
let command = maybe_wrap_shell_lc_with_snapshot(
|
||||
&req.command,
|
||||
session_shell.as_ref(),
|
||||
|
||||
@@ -292,6 +292,11 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
|
||||
explicit_env_overrides
|
||||
};
|
||||
let environment_is_remote = req.environment.is_remote();
|
||||
let mut explicit_env_overrides = explicit_env_overrides;
|
||||
if !environment_is_remote {
|
||||
ctx.session
|
||||
.extend_session_start_env_snapshot_overrides(&mut explicit_env_overrides);
|
||||
}
|
||||
let command = if environment_is_remote {
|
||||
base_command.to_vec()
|
||||
} else {
|
||||
|
||||
@@ -1004,6 +1004,9 @@ impl UnifiedExecProcessManager {
|
||||
CODEX_THREAD_ID_ENV_VAR.to_string(),
|
||||
context.session.conversation_id.to_string(),
|
||||
);
|
||||
if !request.environment.is_remote() {
|
||||
context.session.apply_session_start_env(&mut env);
|
||||
}
|
||||
let env = apply_unified_exec_env(env);
|
||||
let exec_server_env_config = ExecServerEnvConfig {
|
||||
policy: exec_env_policy_from_shell_policy(&context.turn.shell_environment_policy),
|
||||
|
||||
@@ -12,6 +12,7 @@ use codex_protocol::protocol::TurnAbortReason;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use core_test_support::PathBufExt;
|
||||
use core_test_support::assert_regex_match;
|
||||
use core_test_support::hooks::trust_discovered_hooks;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
@@ -28,11 +29,42 @@ use core_test_support::wait_for_event_match;
|
||||
use core_test_support::wait_for_event_with_timeout;
|
||||
use pretty_assertions::assert_eq;
|
||||
use regex_lite::escape;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::TempDir;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
fn write_session_start_hook_with_env(home: &Path) -> anyhow::Result<()> {
|
||||
let script_path = home.join("session_start_env_hook.py");
|
||||
let script = r#"import json
|
||||
|
||||
print(json.dumps({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "SessionStart",
|
||||
"env": {
|
||||
"CODEX_SESSION_START_ENV_TEST": "from-hook"
|
||||
}
|
||||
}
|
||||
}))
|
||||
"#;
|
||||
let hooks = serde_json::json!({
|
||||
"hooks": {
|
||||
"SessionStart": [{
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": format!("python3 {}", script_path.display()),
|
||||
}]
|
||||
}]
|
||||
}
|
||||
});
|
||||
|
||||
fs::write(&script_path, script).context("write session start env hook script")?;
|
||||
fs::write(home.join("hooks.json"), hooks.to_string()).context("write hooks.json")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn user_shell_cmd_ls_and_cat_in_temp_dir() {
|
||||
// Create a temporary working directory with a known file.
|
||||
@@ -98,6 +130,38 @@ async fn user_shell_cmd_ls_and_cat_in_temp_dir() {
|
||||
assert_eq!(stdout, contents);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn user_shell_command_applies_pending_session_start_env() -> anyhow::Result<()> {
|
||||
let server = responses::start_mock_server().await;
|
||||
let mut builder = test_codex()
|
||||
.with_pre_build_hook(|home| {
|
||||
if let Err(error) = write_session_start_hook_with_env(home) {
|
||||
panic!("failed to write session start env hook fixture: {error}");
|
||||
}
|
||||
})
|
||||
.with_config(trust_discovered_hooks);
|
||||
let test = builder.build(&server).await?;
|
||||
|
||||
#[cfg(windows)]
|
||||
let command = r#"[System.Console]::Write($env:CODEX_SESSION_START_ENV_TEST)"#.to_string();
|
||||
#[cfg(not(windows))]
|
||||
let command = r#"printf '%s' "$CODEX_SESSION_START_ENV_TEST""#.to_string();
|
||||
|
||||
test.codex
|
||||
.submit(Op::RunUserShellCommand { command })
|
||||
.await?;
|
||||
|
||||
let end_event = wait_for_event_match(&test.codex, |event| match event {
|
||||
EventMsg::ExecCommandEnd(event) => Some(event.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(end_event.exit_code, 0);
|
||||
assert_eq!(end_event.stdout, "from-hook");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn user_shell_cmd_can_be_interrupted() {
|
||||
// Set up isolated config and conversation.
|
||||
|
||||
@@ -9,6 +9,14 @@
|
||||
"default": null,
|
||||
"type": "string"
|
||||
},
|
||||
"env": {
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
},
|
||||
"default": {},
|
||||
"description": "Environment changes applied to subsequent local shell commands.\n\nMultiple matching `SessionStart` handlers merge in configured order. Later handlers win for duplicate keys.",
|
||||
"type": "object"
|
||||
},
|
||||
"hookEventName": {
|
||||
"const": "SessionStart",
|
||||
"type": "string"
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct UniversalOutput {
|
||||
pub continue_processing: bool,
|
||||
@@ -10,6 +12,8 @@ pub(crate) struct UniversalOutput {
|
||||
pub(crate) struct SessionStartOutput {
|
||||
pub universal: UniversalOutput,
|
||||
pub additional_context: Option<String>,
|
||||
pub env: HashMap<String, String>,
|
||||
pub invalid_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -92,10 +96,16 @@ use crate::schema::UserPromptSubmitCommandOutputWire;
|
||||
|
||||
pub(crate) fn parse_session_start(stdout: &str) -> Option<SessionStartOutput> {
|
||||
let wire: SessionStartCommandOutputWire = parse_json(stdout)?;
|
||||
let (additional_context, env) = wire
|
||||
.hook_specific_output
|
||||
.map(|output| (output.additional_context, output.env))
|
||||
.unwrap_or_default();
|
||||
let invalid_reason = invalid_session_start_env_reason(&env);
|
||||
Some(session_start_output(
|
||||
wire.universal,
|
||||
wire.hook_specific_output
|
||||
.and_then(|output| output.additional_context),
|
||||
additional_context,
|
||||
env,
|
||||
invalid_reason,
|
||||
))
|
||||
}
|
||||
|
||||
@@ -105,19 +115,44 @@ pub(crate) fn parse_subagent_start(stdout: &str) -> Option<SessionStartOutput> {
|
||||
wire.universal,
|
||||
wire.hook_specific_output
|
||||
.and_then(|output| output.additional_context),
|
||||
HashMap::new(),
|
||||
None,
|
||||
))
|
||||
}
|
||||
|
||||
fn session_start_output(
|
||||
universal: HookUniversalOutputWire,
|
||||
additional_context: Option<String>,
|
||||
env: HashMap<String, String>,
|
||||
invalid_reason: Option<String>,
|
||||
) -> SessionStartOutput {
|
||||
SessionStartOutput {
|
||||
universal: UniversalOutput::from(universal),
|
||||
additional_context,
|
||||
env,
|
||||
invalid_reason,
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_session_start_env_reason(env: &HashMap<String, String>) -> Option<String> {
|
||||
for (key, value) in env {
|
||||
if key.is_empty() || key.contains('=') || key.contains('\0') {
|
||||
return Some("SessionStart hook returned an invalid env variable name".to_string());
|
||||
}
|
||||
if key.eq_ignore_ascii_case("CODEX_THREAD_ID") {
|
||||
return Some(
|
||||
"SessionStart hook cannot set reserved env variable `CODEX_THREAD_ID`".to_string(),
|
||||
);
|
||||
}
|
||||
if value.contains('\0') {
|
||||
return Some(format!(
|
||||
"SessionStart hook returned an env value containing NUL for `{key}`"
|
||||
));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn parse_pre_tool_use(stdout: &str) -> Option<PreToolUseOutput> {
|
||||
let PreToolUseCommandOutputWire {
|
||||
universal: universal_wire,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
@@ -82,6 +83,7 @@ pub struct SessionStartOutcome {
|
||||
pub should_stop: bool,
|
||||
pub stop_reason: Option<String>,
|
||||
pub additional_contexts: Vec<String>,
|
||||
pub session_start_env: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -89,6 +91,7 @@ struct SessionStartHandlerData {
|
||||
should_stop: bool,
|
||||
stop_reason: Option<String>,
|
||||
additional_contexts_for_model: Vec<String>,
|
||||
session_start_env: HashMap<String, String>,
|
||||
}
|
||||
|
||||
pub(crate) fn preview(
|
||||
@@ -111,17 +114,16 @@ pub(crate) async fn run(
|
||||
request: SessionStartRequest,
|
||||
turn_id: Option<String>,
|
||||
) -> SessionStartOutcome {
|
||||
let matched = dispatcher::select_handlers(
|
||||
handlers,
|
||||
request.target.event_name(),
|
||||
Some(request.target.matcher_input()),
|
||||
);
|
||||
let event_name = request.target.event_name();
|
||||
let matched =
|
||||
dispatcher::select_handlers(handlers, event_name, Some(request.target.matcher_input()));
|
||||
if matched.is_empty() {
|
||||
return SessionStartOutcome {
|
||||
hook_events: Vec::new(),
|
||||
should_stop: false,
|
||||
stop_reason: None,
|
||||
additional_contexts: Vec::new(),
|
||||
session_start_env: session_start_env_for_event(event_name),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -143,6 +145,7 @@ pub(crate) async fn run(
|
||||
turn_id,
|
||||
format!("failed to serialize session start hook input: {error}"),
|
||||
),
|
||||
event_name,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -173,6 +176,7 @@ pub(crate) async fn run(
|
||||
Some(subagent_turn_id),
|
||||
format!("failed to serialize subagent start hook input: {error}"),
|
||||
),
|
||||
event_name,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -199,12 +203,16 @@ pub(crate) async fn run(
|
||||
.iter()
|
||||
.map(|result| result.data.additional_contexts_for_model.as_slice()),
|
||||
);
|
||||
let session_start_env = (event_name == HookEventName::SessionStart).then(|| {
|
||||
merge_session_start_env(results.iter().map(|result| &result.data.session_start_env))
|
||||
});
|
||||
|
||||
SessionStartOutcome {
|
||||
hook_events: results.into_iter().map(|result| result.completed).collect(),
|
||||
should_stop,
|
||||
stop_reason,
|
||||
additional_contexts,
|
||||
session_start_env,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,6 +232,7 @@ fn parse_completed(
|
||||
let mut should_stop = false;
|
||||
let mut stop_reason = None;
|
||||
let mut additional_contexts_for_model = Vec::new();
|
||||
let mut session_start_env = HashMap::new();
|
||||
|
||||
match run_result.error.as_deref() {
|
||||
Some(error) => {
|
||||
@@ -254,25 +263,34 @@ fn parse_completed(
|
||||
text: system_message,
|
||||
});
|
||||
}
|
||||
if let Some(additional_context) = parsed.additional_context {
|
||||
common::append_additional_context(
|
||||
&mut entries,
|
||||
&mut additional_contexts_for_model,
|
||||
additional_context,
|
||||
);
|
||||
}
|
||||
let _ = parsed.universal.suppress_output;
|
||||
if handler.event_name == HookEventName::SessionStart
|
||||
&& !parsed.universal.continue_processing
|
||||
{
|
||||
status = HookRunStatus::Stopped;
|
||||
should_stop = true;
|
||||
stop_reason = parsed.universal.stop_reason.clone();
|
||||
if let Some(stop_reason_text) = parsed.universal.stop_reason {
|
||||
entries.push(HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Stop,
|
||||
text: stop_reason_text,
|
||||
});
|
||||
if let Some(invalid_reason) = parsed.invalid_reason {
|
||||
status = HookRunStatus::Failed;
|
||||
entries.push(HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Error,
|
||||
text: invalid_reason,
|
||||
});
|
||||
} else {
|
||||
session_start_env = parsed.env;
|
||||
if let Some(additional_context) = parsed.additional_context {
|
||||
common::append_additional_context(
|
||||
&mut entries,
|
||||
&mut additional_contexts_for_model,
|
||||
additional_context,
|
||||
);
|
||||
}
|
||||
let _ = parsed.universal.suppress_output;
|
||||
if handler.event_name == HookEventName::SessionStart
|
||||
&& !parsed.universal.continue_processing
|
||||
{
|
||||
status = HookRunStatus::Stopped;
|
||||
should_stop = true;
|
||||
stop_reason = parsed.universal.stop_reason.clone();
|
||||
if let Some(stop_reason_text) = parsed.universal.stop_reason {
|
||||
entries.push(HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Stop,
|
||||
text: stop_reason_text,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if output_parser::looks_like_json(&run_result.stdout) {
|
||||
@@ -329,22 +347,58 @@ fn parse_completed(
|
||||
should_stop,
|
||||
stop_reason,
|
||||
additional_contexts_for_model,
|
||||
session_start_env,
|
||||
},
|
||||
completion_order: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn serialization_failure_outcome(hook_events: Vec<HookCompletedEvent>) -> SessionStartOutcome {
|
||||
fn serialization_failure_outcome(
|
||||
hook_events: Vec<HookCompletedEvent>,
|
||||
event_name: HookEventName,
|
||||
) -> SessionStartOutcome {
|
||||
SessionStartOutcome {
|
||||
hook_events,
|
||||
should_stop: false,
|
||||
stop_reason: None,
|
||||
additional_contexts: Vec::new(),
|
||||
session_start_env: session_start_env_for_event(event_name),
|
||||
}
|
||||
}
|
||||
|
||||
fn session_start_env_for_event(event_name: HookEventName) -> Option<HashMap<String, String>> {
|
||||
(event_name == HookEventName::SessionStart).then(HashMap::new)
|
||||
}
|
||||
|
||||
fn merge_session_start_env<'a>(
|
||||
envs: impl IntoIterator<Item = &'a HashMap<String, String>>,
|
||||
) -> HashMap<String, String> {
|
||||
let mut merged = HashMap::new();
|
||||
for env in envs {
|
||||
for (key, value) in env {
|
||||
insert_session_start_env(&mut merged, key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
fn insert_session_start_env(env: &mut HashMap<String, String>, key: String, value: String) {
|
||||
#[cfg(windows)]
|
||||
if let Some(existing) = env
|
||||
.keys()
|
||||
.find(|candidate| candidate.eq_ignore_ascii_case(&key))
|
||||
.cloned()
|
||||
{
|
||||
env.remove(&existing);
|
||||
}
|
||||
|
||||
env.insert(key, value);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::HookOutputEntry;
|
||||
use codex_protocol::protocol::HookOutputEntryKind;
|
||||
@@ -354,6 +408,7 @@ mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::SessionStartHandlerData;
|
||||
use super::merge_session_start_env;
|
||||
use super::parse_completed;
|
||||
use crate::engine::ConfiguredHandler;
|
||||
use crate::engine::command_runner::CommandRunResult;
|
||||
@@ -372,6 +427,7 @@ mod tests {
|
||||
should_stop: false,
|
||||
stop_reason: None,
|
||||
additional_contexts_for_model: vec!["hello from hook".to_string()],
|
||||
session_start_env: HashMap::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(parsed.completed.run.status, HookRunStatus::Completed);
|
||||
@@ -402,6 +458,7 @@ mod tests {
|
||||
should_stop: true,
|
||||
stop_reason: Some("pause".to_string()),
|
||||
additional_contexts_for_model: vec!["do not inject".to_string()],
|
||||
session_start_env: HashMap::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(parsed.completed.run.status, HookRunStatus::Stopped);
|
||||
@@ -438,6 +495,7 @@ mod tests {
|
||||
should_stop: false,
|
||||
stop_reason: None,
|
||||
additional_contexts_for_model: Vec::new(),
|
||||
session_start_env: HashMap::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(parsed.completed.run.status, HookRunStatus::Failed);
|
||||
@@ -464,6 +522,7 @@ mod tests {
|
||||
should_stop: false,
|
||||
stop_reason: None,
|
||||
additional_contexts_for_model: vec!["hello from subagent hook".to_string()],
|
||||
session_start_env: HashMap::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(parsed.completed.turn_id.as_deref(), Some("turn-1"));
|
||||
@@ -495,6 +554,7 @@ mod tests {
|
||||
should_stop: false,
|
||||
stop_reason: None,
|
||||
additional_contexts_for_model: vec!["child context".to_string()],
|
||||
session_start_env: HashMap::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(parsed.completed.turn_id.as_deref(), Some("turn-1"));
|
||||
@@ -508,6 +568,69 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_start_env_is_parsed() {
|
||||
let parsed = parse_completed(
|
||||
&handler(),
|
||||
run_result(
|
||||
Some(0),
|
||||
r#"{"hookSpecificOutput":{"hookEventName":"SessionStart","env":{"PATH":"/plugin/bin","PLUGIN_HOME":"/plugin"}}}"#,
|
||||
"",
|
||||
),
|
||||
/*turn_id*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
parsed.data.session_start_env,
|
||||
HashMap::from([
|
||||
("PATH".to_string(), "/plugin/bin".to_string()),
|
||||
("PLUGIN_HOME".to_string(), "/plugin".to_string()),
|
||||
])
|
||||
);
|
||||
assert_eq!(parsed.completed.run.status, HookRunStatus::Completed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_session_start_env_wins() {
|
||||
let first = HashMap::from([
|
||||
("FIRST".to_string(), "1".to_string()),
|
||||
("PATH".to_string(), "/first".to_string()),
|
||||
]);
|
||||
let second = HashMap::from([("PATH".to_string(), "/second".to_string())]);
|
||||
|
||||
assert_eq!(
|
||||
merge_session_start_env([&first, &second]),
|
||||
HashMap::from([
|
||||
("FIRST".to_string(), "1".to_string()),
|
||||
("PATH".to_string(), "/second".to_string()),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_session_start_env_is_rejected() {
|
||||
let parsed = parse_completed(
|
||||
&handler(),
|
||||
run_result(
|
||||
Some(0),
|
||||
r#"{"hookSpecificOutput":{"hookEventName":"SessionStart","env":{"CODEX_THREAD_ID":"hook-thread"}}}"#,
|
||||
"",
|
||||
),
|
||||
/*turn_id*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(parsed.data.session_start_env, HashMap::new());
|
||||
assert_eq!(parsed.completed.run.status, HookRunStatus::Failed);
|
||||
assert_eq!(
|
||||
parsed.completed.run.entries,
|
||||
vec![HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Error,
|
||||
text: "SessionStart hook cannot set reserved env variable `CODEX_THREAD_ID`"
|
||||
.to_string(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
fn handler() -> ConfiguredHandler {
|
||||
handler_for(HookEventName::SessionStart)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -395,6 +396,12 @@ pub(crate) struct SessionStartHookSpecificOutputWire {
|
||||
pub hook_event_name: HookEventNameWire,
|
||||
#[serde(default)]
|
||||
pub additional_context: Option<String>,
|
||||
/// Environment changes applied to subsequent local shell commands.
|
||||
///
|
||||
/// Multiple matching `SessionStart` handlers merge in configured order.
|
||||
/// Later handlers win for duplicate keys.
|
||||
#[serde(default)]
|
||||
pub env: HashMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
|
||||
Reference in New Issue
Block a user