diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index 45c18485e2..556b116241 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -138,6 +138,7 @@ pub(crate) async fn run_codex_thread_interactive( code_mode_session_provider: parent_session.services.code_mode_service.session_provider(), extensions, conversation_history, + create_preparation: None, resume_preparation: None, history_initialization, disabled_plugin_ids: (isolation == codex_extension_api::SessionIsolation::Inherit) diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index b409d38079..adef57b204 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -199,6 +199,7 @@ use codex_thread_store::PersistContext; use codex_thread_store::ReadThreadParams; use codex_thread_store::ResumeThreadParams; use codex_thread_store::ThreadStore; +use codex_thread_store::ThreadStoreCreatePreparation; use codex_thread_store::ThreadStoreResumePreparation; use codex_utils_audio::prepare_response_items as prepare_audio_response_items; use codex_utils_git_discovery::GitRootDiscovery; @@ -554,6 +555,7 @@ pub(crate) struct SessionSpawnArgs { pub(crate) code_mode_session_provider: Arc, pub(crate) extensions: Arc>, pub(crate) conversation_history: InitialHistory, + pub(crate) create_preparation: Option, pub(crate) resume_preparation: Option, pub(crate) history_initialization: HistoryInitialization, pub(crate) disabled_plugin_ids: Option>, @@ -750,6 +752,7 @@ impl Session { code_mode_session_provider, extensions, conversation_history, + create_preparation, resume_preparation, history_initialization, disabled_plugin_ids, @@ -1176,6 +1179,7 @@ impl Session { analytics_events_client, image_store, thread_store, + create_preparation, resume_preparation, parent_rollout_thread_trace, attestation_provider, diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index a736daf0fb..a9bc63cda2 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -835,6 +835,7 @@ impl Session { analytics_events_client: Option, image_store: Arc, thread_store: Arc, + create_preparation: Option, resume_preparation: Option, parent_rollout_thread_trace: ThreadTraceContext, attestation_provider: Option>, @@ -1191,13 +1192,30 @@ impl Session { Arc::clone(&thread_store), params, items, + create_preparation, guard, ) .await? } else { - guard - .acquire(LiveThread::create(Arc::clone(&thread_store), params)) - .await? + match create_preparation { + Some(preparation) => { + guard + .acquire(LiveThread::create_with_preparation( + Arc::clone(&thread_store), + params, + preparation, + )) + .await? + } + None => { + guard + .acquire(LiveThread::create( + Arc::clone(&thread_store), + params, + )) + .await? + } + } } } InitialHistory::Resumed(resumed_history) => { diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 5c04756c5e..10f7c90566 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -7083,6 +7083,7 @@ async fn make_session_with_config_and_rx( codex_thread_store::LocalThreadStoreConfig::from_config(config.as_ref()), /*state_db*/ None, )), + /*create_preparation*/ None, /*resume_preparation*/ None, codex_rollout_trace::ThreadTraceContext::disabled(), /*attestation_provider*/ None, @@ -7233,6 +7234,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx( .expect("state db should initialize"), ), )), + /*create_preparation*/ None, /*resume_preparation*/ None, codex_rollout_trace::ThreadTraceContext::disabled(), /*attestation_provider*/ None, diff --git a/codex-rs/core/src/session/tests/guardian_tests.rs b/codex-rs/core/src/session/tests/guardian_tests.rs index 299ce944c8..7fd6e54fe6 100644 --- a/codex-rs/core/src/session/tests/guardian_tests.rs +++ b/codex-rs/core/src/session/tests/guardian_tests.rs @@ -1408,6 +1408,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() { code_mode_session_provider: Arc::new(codex_code_mode::DisabledCodeModeSessionProvider), extensions: codex_extension_api::empty_extension_registry(), conversation_history: InitialHistory::New, + create_preparation: None, resume_preparation: None, history_initialization: HistoryInitialization::New, disabled_plugin_ids: None, diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 9f6d69e155..f688002c4e 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -119,6 +119,7 @@ use codex_thread_store::StoredModelContext; use codex_thread_store::StoredThread; use codex_thread_store::ThreadMetadataPatch; use codex_thread_store::ThreadStore; +use codex_thread_store::ThreadStoreCreatePreparation; use codex_thread_store::ThreadStoreError; use codex_thread_store::ThreadStoreResumePreparation; use codex_thread_store::UpdateThreadMetadataParams; @@ -380,6 +381,8 @@ pub struct StartThreadOptions { pub thread_instructions_provider: Option>, pub allow_provider_model_fallback: bool, pub initial_history: InitialHistory, + /// Store-owned state prepared before creating this thread. + pub create_preparation: Option, /// Store-owned state prepared while loading the resumed history. pub resume_preparation: Option, /// Parent captured for `start_thread`, including a parent not in the live registry. @@ -467,6 +470,7 @@ impl StartThreadOptions { allow_provider_model_fallback: false, initial_history: InitialHistory::New, inherited_multi_agent_version: None, + create_preparation: None, resume_preparation: None, internal_parent: None, history_mode: None, @@ -2685,6 +2689,7 @@ impl ThreadManagerState { thread_instructions_provider, allow_provider_model_fallback, initial_history, + create_preparation, resume_preparation, internal_parent: _, history_mode, @@ -2713,6 +2718,17 @@ impl ThreadManagerState { "thread store resume preparation requires a persisted resumed thread".to_string(), )); } + if create_preparation.is_some() + && (config.ephemeral + || !matches!( + &initial_history, + InitialHistory::New | InitialHistory::Cleared | InitialHistory::Forked(_) + )) + { + return Err(CodexErr::InvalidRequest( + "thread store create preparation requires a persisted new thread".to_string(), + )); + } let inherited_environments = captured_environments.or(inherited_environments); let session_source = session_source.unwrap_or_else(|| self.session_source.clone()); if let Some(parent_id) = parent_thread_id @@ -3128,6 +3144,7 @@ impl ThreadManagerState { code_mode_session_provider: Arc::clone(&self.code_mode_session_provider), extensions, conversation_history: initial_history, + create_preparation, resume_preparation, history_initialization: startup_context.history_initialization, disabled_plugin_ids, diff --git a/codex-rs/core/tests/suite/fork_thread.rs b/codex-rs/core/tests/suite/fork_thread.rs index e13ef3f400..dcb55a7329 100644 --- a/codex-rs/core/tests/suite/fork_thread.rs +++ b/codex-rs/core/tests/suite/fork_thread.rs @@ -20,6 +20,7 @@ use codex_protocol::user_input::UserInput; use codex_thread_store::InMemoryThreadStore; use codex_thread_store::InheritedHistoryVisibility; use codex_thread_store::PreparedFork; +use codex_thread_store::ThreadStoreCreatePreparation; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_response_created; use core_test_support::responses::sse; @@ -66,6 +67,40 @@ async fn prepared_fork_passes_inherited_history_visibility_to_store() -> anyhow: Ok(()) } +/// A supplied creation preparation must select the prepared store path instead of silently +/// repeating ordinary thread creation. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn prepared_fork_uses_prepared_store_creation() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = MockServer::start().await; + let test = test_codex().build_with_auto_env(&server).await?; + let prepared = PreparedFork::with_source_revalidation( + test.session_configured.thread_id, + /*history_base*/ None, + Arc::new(Vec::new()), + ); + let mut options = test.start_thread_options().await; + options.create_preparation = Some(ThreadStoreCreatePreparation::new(())); + + let Err(error) = test + .thread_manager + .fork_prepared_thread(options, prepared, InheritedHistoryVisibility::Full) + .await + else { + anyhow::bail!("prepared fork unexpectedly used ordinary thread creation"); + }; + assert!( + matches!( + error.details(), + CodexErrorDetails::UnsupportedOperation(message) + if message == "create_thread_with_preparation is not supported yet" + ), + "unexpected prepared fork error: {error}" + ); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn ephemeral_fork_skips_stored_title_lookup() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/thread-store/src/lib.rs b/codex-rs/thread-store/src/lib.rs index f3e05ba294..a3ef305535 100644 --- a/codex-rs/thread-store/src/lib.rs +++ b/codex-rs/thread-store/src/lib.rs @@ -68,6 +68,7 @@ pub use store::PendingDaybreakPreference; pub use store::PersistContext; pub use store::ThreadSearchObserver; pub use store::ThreadStore; +pub use store::ThreadStoreCreatePreparation; pub use store::ThreadStoreFuture; pub use store::ThreadStoreResumePreparation; pub use thread_attachments::AddThreadAttachmentParams; diff --git a/codex-rs/thread-store/src/live_thread.rs b/codex-rs/thread-store/src/live_thread.rs index 53039cd8c9..557bb52dcc 100644 --- a/codex-rs/thread-store/src/live_thread.rs +++ b/codex-rs/thread-store/src/live_thread.rs @@ -26,6 +26,7 @@ use crate::StoredThread; use crate::StoredThreadHistory; use crate::ThreadMetadataPatch; use crate::ThreadStore; +use crate::ThreadStoreCreatePreparation; use crate::ThreadStoreError; use crate::ThreadStoreFuture; use crate::ThreadStoreResult; @@ -138,6 +139,22 @@ impl LiveThread { pub async fn create( thread_store: Arc, params: CreateThreadParams, + ) -> ThreadStoreResult { + Self::create_inner(thread_store, params, /*preparation*/ None).await + } + + pub async fn create_with_preparation( + thread_store: Arc, + params: CreateThreadParams, + preparation: ThreadStoreCreatePreparation, + ) -> ThreadStoreResult { + Self::create_inner(thread_store, params, Some(preparation)).await + } + + async fn create_inner( + thread_store: Arc, + params: CreateThreadParams, + preparation: Option, ) -> ThreadStoreResult { let thread_id = params.thread_id; let history_mode = params.history_mode; @@ -151,7 +168,14 @@ impl LiveThread { }; let metadata_sync = ThreadMetadataSync::for_create(¶ms, inherited_preview.as_deref()).await; - thread_store.create_thread(params).await?; + match preparation { + Some(preparation) => { + thread_store + .create_thread_with_preparation(params, preparation) + .await?; + } + None => thread_store.create_thread(params).await?, + } Ok(Self { thread_id, history_mode, @@ -169,6 +193,7 @@ impl LiveThread { thread_store: Arc, mut params: CreateThreadParams, inherited_model_context: &[RolloutItem], + create_preparation: Option, guard: &mut LiveThreadInitGuard, ) -> ThreadStoreResult { let persisted_prefix_item_count = inherited_model_context @@ -185,7 +210,18 @@ impl LiveThread { message: "inherited model context is too large".to_string(), })?, ); - let live_thread = guard.acquire(Self::create(thread_store, params)).await?; + let live_thread = match create_preparation { + Some(preparation) => { + guard + .acquire(Self::create_with_preparation( + thread_store, + params, + preparation, + )) + .await? + } + None => guard.acquire(Self::create(thread_store, params)).await?, + }; live_thread .persist_appended_items(inherited_model_context) .await?; diff --git a/codex-rs/thread-store/src/local/mod.rs b/codex-rs/thread-store/src/local/mod.rs index 987a91aad2..ff3823b916 100644 --- a/codex-rs/thread-store/src/local/mod.rs +++ b/codex-rs/thread-store/src/local/mod.rs @@ -1352,6 +1352,7 @@ mod tests { store, params, &[user_message_item("legacy-only event"), parent.clone()], + /*create_preparation*/ None, &mut guard, ) .await diff --git a/codex-rs/thread-store/src/store.rs b/codex-rs/thread-store/src/store.rs index d41bc56374..a465f929c5 100644 --- a/codex-rs/thread-store/src/store.rs +++ b/codex-rs/thread-store/src/store.rs @@ -111,6 +111,37 @@ impl fmt::Debug for ThreadStoreResumePreparation { } } +/// Data a [`ThreadStore`] has prepared before Core creates a thread. +/// +/// Core does not inspect this value. It gives the value back to the store when creating the +/// thread, allowing the store to reuse work started before Core startup. The value can only be +/// used once because it may own resources that cannot be copied. +pub struct ThreadStoreCreatePreparation { + state: Box, +} + +impl ThreadStoreCreatePreparation { + pub fn new(state: T) -> Self { + Self { + state: Box::new(state), + } + } + + pub fn downcast(self) -> Result { + match self.state.downcast::() { + Ok(state) => Ok(*state), + Err(state) => Err(Self { state }), + } + } +} + +impl fmt::Debug for ThreadStoreCreatePreparation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ThreadStoreCreatePreparation") + .finish_non_exhaustive() + } +} + /// Why thread persistence is being requested. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PersistContext { @@ -175,6 +206,22 @@ pub trait ThreadStore: Any + Send + Sync { /// Creates a new live thread. fn create_thread(&self, params: CreateThreadParams) -> ThreadStoreFuture<'_, ()>; + /// Creates a thread using implementation-owned state prepared before Core startup. + /// + /// Stores should only override this when they also produce the preparation. Creation and + /// failure cleanup guarantees are the same as [`Self::create_thread`]. + fn create_thread_with_preparation( + &self, + _params: CreateThreadParams, + _preparation: ThreadStoreCreatePreparation, + ) -> ThreadStoreFuture<'_, ()> { + Box::pin(async { + Err(ThreadStoreError::Unsupported { + operation: "create_thread_with_preparation", + }) + }) + } + /// Stages host-owned metadata for a thread ID reserved before Core starts the thread. /// /// The entry remains in memory until the first successful metadata update for that thread.