diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index 3a38e7ede6..2b71027351 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -26,6 +26,7 @@ use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::CommandExecutionApprovalDecision; use codex_app_server_protocol::CommandExecutionRequestApprovalResponse; +use codex_app_server_protocol::CyberAccessProgram; use codex_app_server_protocol::DeprecationNoticeNotification; use codex_app_server_protocol::FileChangeApprovalDecision; use codex_app_server_protocol::FileChangeRequestApprovalResponse; @@ -3945,6 +3946,15 @@ async fn thread_goal_set_edits_objective_without_resetting_usage() -> Result<()> #[tokio::test] async fn thread_goal_keeps_original_root_until_external_objective_edit() -> Result<()> { + check_thread_goal_continuation_program(/*enrolled*/ true).await +} + +#[tokio::test] +async fn thread_goal_continuation_respects_daybreak_opt_out() -> Result<()> { + check_thread_goal_continuation_program(/*enrolled*/ false).await +} + +async fn check_thread_goal_continuation_program(enrolled: bool) -> Result<()> { let (release_original_turn, original_turn_gate) = oneshot::channel(); let (release_edited_turn, edited_turn_gate) = oneshot::channel(); let (server, _response_completions) = start_streaming_sse_server(vec![ @@ -3982,19 +3992,52 @@ async fn thread_goal_keeps_original_root_until_external_objective_edit() -> Resu /*total_tokens*/ 100, ), ])), + ungated_goal_response(responses::sse(vec![ + responses::ev_response_created("replacement-goal-continuation"), + responses::ev_completed_with_tokens( + "replacement-goal-continuation", + /*total_tokens*/ 100, + ), + ])), ]) .await; let codex_home = TempDir::new()?; - mock_responses_config(server.uri()) - .enable_feature(Feature::Goals) - .enable_feature(Feature::UntrustedAsToolOutput) - .write(codex_home.path())?; + std::fs::write( + codex_home.path().join("config.toml"), + format!( + r#" +model = "gpt-5.4" +approval_policy = "never" +openai_base_url = "{}/v1" +cli_auth_credentials_store = "file" + +[features] +goals = true +untrusted_as_tool_output = true +daybreak_program_propagation = true +enable_request_compression = false +"#, + server.uri() + ), + )?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-test-token").plan_type("pro"), + AuthCredentialsStoreMode::File, + )?; let mut mcp = TestAppServer::builder() .with_codex_home(codex_home.path()) .without_managed_config() .build_initialized() .await?; - let thread = mcp.start_thread(ThreadStartParams::default()).await?.thread; + let thread = mcp + .start_thread(ThreadStartParams { + daybreak_program_propagation_enrolled: Some(enrolled), + ..Default::default() + }) + .await? + .thread; + assert_eq!(thread.daybreak_program_propagation_enrolled, Some(enrolled)); let start_id = mcp .send_turn_start_request(TurnStartParams { @@ -4003,6 +4046,7 @@ async fn thread_goal_keeps_original_root_until_external_objective_edit() -> Resu text: "create the original goal".to_string(), text_elements: Vec::new(), }], + cyber_access_program: Some(CyberAccessProgram::DaybreakBlue), ..Default::default() }) .await?; @@ -4101,8 +4145,58 @@ async fn thread_goal_keeps_original_root_until_external_objective_edit() -> Resu .await??; } + let clear_id = mcp + .send_raw_request("thread/goal/clear", Some(json!({"threadId": thread.id}))) + .await?; + let clear: ThreadGoalClearResponse = + timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(clear_id)).await??; + assert!(clear.cleared); + + let replacement_id = mcp + .send_raw_request( + "thread/goal/set", + Some(json!({ + "threadId": thread.id, + "objective": "a different goal", + "tokenBudget": 100, + })), + ) + .await?; + let replacement: ThreadGoalSetResponse = + timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(replacement_id)).await??; + assert_eq!(replacement.goal.objective, "a different goal"); + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + let requests = server.requests().await; - assert_eq!(requests.len(), 8); + assert_eq!(requests.len(), 9); + // Explicit requests retain their program regardless of enrollment; automatic goal turns + // propagate it only for enrolled threads, including after an objective edit. + let programs = requests + .iter() + .map(|request| { + let body: serde_json::Value = serde_json::from_slice(request)?; + Ok(body["access_programs"]["cyber"].as_str().map(str::to_owned)) + }) + .collect::>>()?; + let continuation_program = enrolled.then_some("daybreak_blue"); + assert_eq!( + programs.iter().map(Option::as_deref).collect::>(), + [ + Some("daybreak_blue"), + Some("daybreak_blue"), + Some("daybreak_blue"), + None, + continuation_program, + continuation_program, + continuation_program, + continuation_program, + None, + ] + ); let reopened_original_request = serde_json::from_slice::(&requests[2])?; assert_eq!( reopened_original_request["client_metadata"]["turn_id"].as_str(), @@ -4132,7 +4226,9 @@ async fn thread_goal_keeps_original_root_until_external_objective_edit() -> Resu .contains(objective) ); let mut wire_item = objective.as_object().expect("goal context item").clone(); - wire_item.remove("id"); // Generated for each run. + // The snapshot covers the tool output. These fields carry per-run identifiers and timing. + wire_item.remove("id"); + wire_item.remove("internal_chat_message_metadata_passthrough"); wire_item.sort_keys(); insta::assert_snapshot!( "model_written_goal_as_untrusted_tool_output", diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 06a19d1e73..01171366df 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -4,6 +4,7 @@ use crate::agent::api::AgentControl; use crate::config::ConstraintResult; use crate::context::ContextualUserFragment; use crate::context::GuardianReviewEvidence; +use crate::cyber_access_program::ContinuationCyberAccessProgram; use crate::elicitation::ElicitationRegistration; use crate::session::SessionIo; use crate::session::SessionSettingsUpdate; @@ -946,6 +947,19 @@ impl CodexThread { task.turn_context.turn_metadata_state.root_turn_id() } + /// Returns the explicit program captured for continuations of the named active turn. + pub async fn active_turn_continuation_program( + &self, + expected_turn_id: &str, + ) -> Option> { + let active = self.session.active_turn.lock().await; + let task = active.as_ref()?.task.as_ref()?; + if task.turn_context.sub_id != expected_turn_id { + return None; + } + task.turn_context.extension_data.get() + } + pub async fn set_app_server_client_info( &self, app_server_client_name: Option, diff --git a/codex-rs/core/src/cyber_access_program.rs b/codex-rs/core/src/cyber_access_program.rs index df5e035eff..37f2b18506 100644 --- a/codex-rs/core/src/cyber_access_program.rs +++ b/codex-rs/core/src/cyber_access_program.rs @@ -8,6 +8,8 @@ use codex_protocol::error::Result; use codex_protocol::turn_input::CyberAccessProgram; use std::sync::Arc; +pub use crate::session::turn_context::ContinuationCyberAccessProgram; + /// Host requirement for every model request issued by this thread. /// /// Install in thread extension data before startup and reapply on cold resume. diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index f54d7035c0..d93b1d7de0 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -1,3 +1,7 @@ +mod continuation_cyber_access_program; + +pub use continuation_cyber_access_program::ContinuationCyberAccessProgram; + use super::step_settings::ResolvedStepSettings; use super::token_budget::has_explicit_settings; use super::token_budget::resolve_token_budget; @@ -1520,6 +1524,9 @@ impl Session { turn_context.prompt_cache_ttl = options.prompt_cache_ttl; turn_context.cyber_access_program = cyber_access_program::for_provider(&turn_context.config, options.cyber_access_program); + if let Some(program) = ContinuationCyberAccessProgram::capture(self, &turn_context) { + turn_context.extension_data.insert(program); + } if let Some(admission) = options.helper_admission { admission.capture_intent(self, &mut turn_context).await; } diff --git a/codex-rs/core/src/session/turn_context/continuation_cyber_access_program.rs b/codex-rs/core/src/session/turn_context/continuation_cyber_access_program.rs new file mode 100644 index 0000000000..abf60557eb --- /dev/null +++ b/codex-rs/core/src/session/turn_context/continuation_cyber_access_program.rs @@ -0,0 +1,61 @@ +//! Carry explicit Cyber selection within live work owned by the same account and model. + +use super::TurnContext; +use crate::CodexThread; +use crate::agent::helper_daybreak::Enrollment; +use crate::cyber_access_program; +use crate::session::session::Session; +use codex_features::Feature; +use codex_login::AuthOwner; +use codex_model_provider::request_auth_owner; +use codex_protocol::turn_input::CyberAccessProgram; + +/// An explicit program captured for a live continuation on the same account and model. +pub struct ContinuationCyberAccessProgram { + program: CyberAccessProgram, + owner: AuthOwner, + model: String, + provider_id: String, +} + +impl ContinuationCyberAccessProgram { + pub(super) fn capture(session: &Session, turn: &TurnContext) -> Option { + session.services.thread_extension_data.get::()?; + let program = turn.cyber_access_program?; + if !turn + .config + .features + .enabled(Feature::DaybreakProgramPropagation) + { + return None; + } + Some(Self { + program, + owner: request_auth_owner(turn.provider.as_ref())?, + model: turn + .initial_settings + .selected_collaboration_mode() + .model() + .to_string(), + provider_id: turn.config.model_provider_id.clone(), + }) + } + + /// Reuse the selection only while the current turn configuration still matches its source. + pub async fn for_thread(&self, thread: &CodexThread) -> Option { + if !thread.daybreak_program_propagation_enrolled() { + return None; + } + let state = thread.session.state.lock().await; + let current = &state.session_configuration; + let config = ¤t.original_config_do_not_use; + if !config.features.enabled(Feature::DaybreakProgramPropagation) + || config.model_provider_id != self.provider_id + || current.step_settings.collaboration_mode.model() != self.model + || request_auth_owner(current.provider.as_ref()).as_ref() != Some(&self.owner) + { + return None; + } + cyber_access_program::for_provider(config, Some(self.program)) + } +} diff --git a/codex-rs/ext/goal/src/api.rs b/codex-rs/ext/goal/src/api.rs index a2bd783dc8..2dabd31bf0 100644 --- a/codex-rs/ext/goal/src/api.rs +++ b/codex-rs/ext/goal/src/api.rs @@ -280,7 +280,7 @@ impl GoalService { }; if let Some(runtime) = runtime.as_ref() { - runtime.clear_pending_turn_start_options().await; + runtime.reset_goal_continuation(Some(&goal.goal_id)).await; } if objective.is_some() { @@ -330,7 +330,9 @@ impl GoalService { })?; let cleared = cleared_goal.is_some(); if cleared && let Some(runtime) = runtime.as_ref() { - runtime.clear_pending_turn_start_options().await; + runtime + .reset_goal_continuation(/*remaining_goal_id*/ None) + .await; } drop(goal_state_permit); drop(runtime); diff --git a/codex-rs/ext/goal/src/runtime.rs b/codex-rs/ext/goal/src/runtime.rs index fa0eaea5e9..ce96d9f6fa 100644 --- a/codex-rs/ext/goal/src/runtime.rs +++ b/codex-rs/ext/goal/src/runtime.rs @@ -6,6 +6,7 @@ use std::sync::atomic::Ordering; use codex_core::StartIfIdleSubmission; use codex_core::ThreadManager; use codex_core::TurnStartOptions; +use codex_core::cyber_access_program::ContinuationCyberAccessProgram; use codex_protocol::ThreadId; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::ThreadGoal; @@ -62,6 +63,12 @@ pub(crate) struct AccountedGoalProgress { pub(crate) goal_id: String, } +/// The live goal keeps this choice across changes to its continuation's turn lineage. +pub(crate) struct ToolCreatedGoalProgram { + pub(crate) goal_id: String, + pub(crate) program: Arc, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct PreviousGoalSnapshot { pub goal_id: String, @@ -141,14 +148,21 @@ impl GoalRuntimeHandle { self.inner.root_accounting_state.clone() } - pub(crate) async fn clear_pending_turn_start_options(&self) { + pub(crate) async fn reset_goal_continuation(&self, remaining_goal_id: Option<&str>) { let Some(thread_manager) = self.inner.thread_manager.upgrade() else { return; }; let Ok(thread) = thread_manager.get_thread(self.inner.thread_id).await else { return; }; - thread.thread_extension_data().remove::(); + let thread_store = thread.thread_extension_data(); + thread_store.remove::(); + if thread_store + .get::() + .is_some_and(|captured| Some(captured.goal_id.as_str()) != remaining_goal_id) + { + thread_store.remove::(); + } } pub(crate) async fn goal_state_permit(&self) -> Result, String> { @@ -478,16 +492,21 @@ impl GoalRuntimeHandle { self.inner.accounting_state.clear_active_goal(); return Ok(()); } - let start_options = thread - .thread_extension_data() - .get::() - .map(|options| options.as_ref().clone()) - .unwrap_or_default(); + let thread_store = thread.thread_extension_data(); + let captured_program = thread_store + .get::() + .filter(|captured| captured.goal_id == goal.goal_id); let request = continuation_request( &protocol_goal_from_state(goal), thread.config().await.update_plan_enabled, ); - + let mut start_options = thread_store + .get::() + .map(|options| options.as_ref().clone()) + .unwrap_or_default(); + if let Some(captured) = captured_program { + start_options.cyber_access_program = captured.program.for_thread(&thread).await; + } match thread .start_turn_if_idle(request.on_start(TurnStartOptions { turn_trigger: Some("goal".to_string()), diff --git a/codex-rs/ext/goal/src/tool.rs b/codex-rs/ext/goal/src/tool.rs index 3955bfaefb..24d3ff2a96 100644 --- a/codex-rs/ext/goal/src/tool.rs +++ b/codex-rs/ext/goal/src/tool.rs @@ -23,6 +23,7 @@ use crate::analytics::GoalEventAttribution; use crate::events::GoalEventEmitter; use crate::metrics::GoalMetrics; use crate::runtime::GoalRuntimeHandle; +use crate::runtime::ToolCreatedGoalProgram; use crate::spec::CREATE_GOAL_TOOL_NAME; use crate::spec::GET_GOAL_TOOL_NAME; use crate::spec::UPDATE_GOAL_TOOL_NAME; @@ -47,7 +48,10 @@ pub(crate) struct GoalToolExecutor { #[derive(Clone)] enum GoalToolKind { Get, - Create(Weak), + Create { + thread_manager: Weak, + runtime: GoalRuntimeHandle, + }, Update, } @@ -110,7 +114,10 @@ impl GoalToolExecutor { max_goal_token_budget: Option, ) -> Self { Self { - kind: GoalToolKind::Create(thread_manager), + kind: GoalToolKind::Create { + thread_manager, + runtime: runtime.clone(), + }, execution_allowed: true, thread_id: runtime.thread_id(), state_db, @@ -148,7 +155,7 @@ impl<'call> ToolExecutor> for GoalToolExecutor { fn tool_name(&self) -> ToolName { ToolName::plain(match self.kind { GoalToolKind::Get => GET_GOAL_TOOL_NAME, - GoalToolKind::Create(_) => CREATE_GOAL_TOOL_NAME, + GoalToolKind::Create { .. } => CREATE_GOAL_TOOL_NAME, GoalToolKind::Update => UPDATE_GOAL_TOOL_NAME, }) } @@ -160,7 +167,7 @@ impl<'call> ToolExecutor> for GoalToolExecutor { fn spec(&self) -> ToolSpec { match self.kind { GoalToolKind::Get => create_get_goal_tool(), - GoalToolKind::Create(_) => create_create_goal_tool(), + GoalToolKind::Create { .. } => create_create_goal_tool(), GoalToolKind::Update => create_update_goal_tool(), } } @@ -180,8 +187,12 @@ impl<'call> ToolExecutor> for GoalToolExecutor { } match &self.kind { GoalToolKind::Get => self.handle_get(invocation).await, - GoalToolKind::Create(thread_manager) => { - self.handle_create(invocation, thread_manager).await + GoalToolKind::Create { + thread_manager, + runtime, + } => { + self.handle_create(invocation, thread_manager, runtime) + .await } GoalToolKind::Update => self.handle_update(invocation).await, } @@ -211,6 +222,7 @@ impl GoalToolExecutor { &self, invocation: ToolCall<'_>, thread_manager: &Weak, + runtime: &GoalRuntimeHandle, ) -> Result, FunctionCallError> { let mut request: CreateGoalRequest = parse_arguments(invocation.function_arguments()?)?; request.objective = request.objective.trim().to_string(); @@ -220,6 +232,11 @@ impl GoalToolExecutor { validate_goal_budget(request.token_budget, self.max_goal_token_budget) .map_err(FunctionCallError::RespondToModel)?; + // Keep the captured program in sync with goal creation and external goal mutations. + let _goal_state_permit = runtime + .goal_state_permit() + .await + .map_err(FunctionCallError::RespondToModel)?; let goal = self .state_db .thread_goals() @@ -244,6 +261,18 @@ impl GoalToolExecutor { if let Some(manager) = thread_manager.upgrade() && let Ok(thread) = manager.get_thread(self.thread_id).await { + let thread_store = thread.thread_extension_data(); + if let Some(program) = thread + .active_turn_continuation_program(&invocation.turn_id) + .await + { + thread_store.insert(ToolCreatedGoalProgram { + goal_id: goal.goal_id.clone(), + program, + }); + } else { + thread_store.remove::(); + } thread .inject_untrusted_context_for_turn( &invocation.turn_id,