diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index f78f27ffa3..2367cb5c2a 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2433,7 +2433,6 @@ dependencies = [ "bm25", "chrono", "clap", - "codex-agent-graph-store", "codex-analytics", "codex-api", "codex-app-server-protocol", diff --git a/codex-rs/analytics/src/events.rs b/codex-rs/analytics/src/events.rs index 2232c88d39..2bcd43f380 100644 --- a/codex-rs/analytics/src/events.rs +++ b/codex-rs/analytics/src/events.rs @@ -880,6 +880,8 @@ fn analytics_hook_event_name(event_name: HookEventName) -> &'static str { HookEventName::PreToolUse => "PreToolUse", HookEventName::PermissionRequest => "PermissionRequest", HookEventName::PostToolUse => "PostToolUse", + HookEventName::PreCompact => "PreCompact", + HookEventName::PostCompact => "PostCompact", HookEventName::SessionStart => "SessionStart", HookEventName::UserPromptSubmit => "UserPromptSubmit", HookEventName::Stop => "Stop", diff --git a/codex-rs/app-server-client/src/lib.rs b/codex-rs/app-server-client/src/lib.rs index 6e10cef255..ebafe351af 100644 --- a/codex-rs/app-server-client/src/lib.rs +++ b/codex-rs/app-server-client/src/lib.rs @@ -29,6 +29,7 @@ pub use codex_app_server::in_process::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY; pub use codex_app_server::in_process::InProcessServerEvent; use codex_app_server::in_process::InProcessStartArgs; use codex_app_server::in_process::LogDbLayer; +pub use codex_app_server::in_process::StateDbHandle; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ClientNotification; use codex_app_server_protocol::ClientRequest; @@ -46,7 +47,6 @@ use codex_config::LoaderOverrides; use codex_config::NoopThreadConfigLoader; use codex_config::RemoteThreadConfigLoader; use codex_config::ThreadConfigLoader; -pub use codex_core::StateDbHandle; use codex_core::config::Config; pub use codex_exec_server::EnvironmentManager; pub use codex_exec_server::EnvironmentManagerArgs; @@ -951,7 +951,7 @@ mod tests { use codex_app_server_protocol::ToolRequestUserInputParams; use codex_app_server_protocol::ToolRequestUserInputQuestion; use codex_core::config::ConfigBuilder; - use codex_core::init_state_db_from_config; + use codex_core::init_state_db; use futures::SinkExt; use futures::StreamExt; use pretty_assertions::assert_eq; @@ -1017,7 +1017,7 @@ mod tests { ) -> TestClient { let codex_home = TempDir::new().expect("temp dir"); let config = Arc::new(build_test_config_for_codex_home(codex_home.path()).await); - let state_db = init_state_db_from_config(config.as_ref()) + let state_db = init_state_db(config.as_ref()) .await .expect("state db should initialize for in-process test"); let client = InProcessAppServerClient::start(InProcessClientStartArgs { diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 883ab8e68a..5dc3c09a44 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1736,6 +1736,8 @@ "preToolUse", "permissionRequest", "postToolUse", + "preCompact", + "postCompact", "sessionStart", "userPromptSubmit", "stop" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 24b8ea9cc0..06ccdb48b2 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -9824,6 +9824,8 @@ "preToolUse", "permissionRequest", "postToolUse", + "preCompact", + "postCompact", "sessionStart", "userPromptSubmit", "stop" @@ -10664,12 +10666,24 @@ }, "type": "array" }, + "PostCompact": { + "items": { + "$ref": "#/definitions/v2/ConfiguredHookMatcherGroup" + }, + "type": "array" + }, "PostToolUse": { "items": { "$ref": "#/definitions/v2/ConfiguredHookMatcherGroup" }, "type": "array" }, + "PreCompact": { + "items": { + "$ref": "#/definitions/v2/ConfiguredHookMatcherGroup" + }, + "type": "array" + }, "PreToolUse": { "items": { "$ref": "#/definitions/v2/ConfiguredHookMatcherGroup" @@ -10709,7 +10723,9 @@ }, "required": [ "PermissionRequest", + "PostCompact", "PostToolUse", + "PreCompact", "PreToolUse", "SessionStart", "Stop", diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 76d81c729e..852cc2489d 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -6391,6 +6391,8 @@ "preToolUse", "permissionRequest", "postToolUse", + "preCompact", + "postCompact", "sessionStart", "userPromptSubmit", "stop" @@ -7275,12 +7277,24 @@ }, "type": "array" }, + "PostCompact": { + "items": { + "$ref": "#/definitions/ConfiguredHookMatcherGroup" + }, + "type": "array" + }, "PostToolUse": { "items": { "$ref": "#/definitions/ConfiguredHookMatcherGroup" }, "type": "array" }, + "PreCompact": { + "items": { + "$ref": "#/definitions/ConfiguredHookMatcherGroup" + }, + "type": "array" + }, "PreToolUse": { "items": { "$ref": "#/definitions/ConfiguredHookMatcherGroup" @@ -7320,7 +7334,9 @@ }, "required": [ "PermissionRequest", + "PostCompact", "PostToolUse", + "PreCompact", "PreToolUse", "SessionStart", "Stop", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json index 545d8dc9b4..14a8d572d6 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json @@ -213,12 +213,24 @@ }, "type": "array" }, + "PostCompact": { + "items": { + "$ref": "#/definitions/ConfiguredHookMatcherGroup" + }, + "type": "array" + }, "PostToolUse": { "items": { "$ref": "#/definitions/ConfiguredHookMatcherGroup" }, "type": "array" }, + "PreCompact": { + "items": { + "$ref": "#/definitions/ConfiguredHookMatcherGroup" + }, + "type": "array" + }, "PreToolUse": { "items": { "$ref": "#/definitions/ConfiguredHookMatcherGroup" @@ -258,7 +270,9 @@ }, "required": [ "PermissionRequest", + "PostCompact", "PostToolUse", + "PreCompact", "PreToolUse", "SessionStart", "Stop", diff --git a/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json index d55c059a73..f63e6a5cfe 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json @@ -10,6 +10,8 @@ "preToolUse", "permissionRequest", "postToolUse", + "preCompact", + "postCompact", "sessionStart", "userPromptSubmit", "stop" diff --git a/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json index 03d2998ca5..f8eeecfe4d 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json @@ -10,6 +10,8 @@ "preToolUse", "permissionRequest", "postToolUse", + "preCompact", + "postCompact", "sessionStart", "userPromptSubmit", "stop" diff --git a/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json index ae9cd9e63c..f2a7c80cf0 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json @@ -25,6 +25,8 @@ "preToolUse", "permissionRequest", "postToolUse", + "preCompact", + "postCompact", "sessionStart", "userPromptSubmit", "stop" diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts b/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts index 28657d2282..91c2def709 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type HookEventName = "preToolUse" | "permissionRequest" | "postToolUse" | "sessionStart" | "userPromptSubmit" | "stop"; +export type HookEventName = "preToolUse" | "permissionRequest" | "postToolUse" | "preCompact" | "postCompact" | "sessionStart" | "userPromptSubmit" | "stop"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ManagedHooksRequirements.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ManagedHooksRequirements.ts index 3386d16ec3..cde0e4a503 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ManagedHooksRequirements.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ManagedHooksRequirements.ts @@ -3,4 +3,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ConfiguredHookMatcherGroup } from "./ConfiguredHookMatcherGroup"; -export type ManagedHooksRequirements = { managedDir: string | null, windowsManagedDir: string | null, PreToolUse: Array, PermissionRequest: Array, PostToolUse: Array, SessionStart: Array, UserPromptSubmit: Array, Stop: Array, }; +export type ManagedHooksRequirements = { managedDir: string | null, windowsManagedDir: string | null, PreToolUse: Array, PermissionRequest: Array, PostToolUse: Array, PreCompact: Array, PostCompact: Array, SessionStart: Array, UserPromptSubmit: Array, Stop: Array, }; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 682556b976..d687a79ec9 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -77,6 +77,7 @@ macro_rules! experimental_type_entry { #[derive(Debug, Clone, PartialEq, Eq)] pub enum ClientRequestSerializationScope { Global(&'static str), + GlobalSharedRead(&'static str), Thread { thread_id: String }, ThreadPath { path: PathBuf }, CommandExecProcess { process_id: String }, @@ -93,6 +94,9 @@ macro_rules! serialization_scope_expr { ($actual_params:ident, global($key:literal)) => { Some(ClientRequestSerializationScope::Global($key)) }; + ($actual_params:ident, global_shared_read($key:literal)) => { + Some(ClientRequestSerializationScope::GlobalSharedRead($key)) + }; ($actual_params:ident, thread_id($params:ident . $field:ident)) => { Some(ClientRequestSerializationScope::Thread { thread_id: $actual_params.$field.clone(), @@ -585,7 +589,7 @@ client_request_definitions! { }, SkillsList => "skills/list" { params: v2::SkillsListParams, - serialization: global("config"), + serialization: global_shared_read("config"), response: v2::SkillsListResponse, }, HooksList => "hooks/list" { @@ -610,7 +614,7 @@ client_request_definitions! { }, PluginList => "plugin/list" { params: v2::PluginListParams, - serialization: global("config"), + serialization: global_shared_read("config"), response: v2::PluginListResponse, }, PluginRead => "plugin/read" { @@ -947,7 +951,7 @@ client_request_definitions! { ConfigRead => "config/read" { params: v2::ConfigReadParams, - serialization: global("config"), + serialization: global_shared_read("config"), response: v2::ConfigReadResponse, }, ExternalAgentConfigDetect => "externalAgentConfig/detect" { @@ -1655,6 +1659,31 @@ mod tests { Some(ClientRequestSerializationScope::Global("config")) ); + let skills_list = ClientRequest::SkillsList { + request_id: request_id(), + params: v2::SkillsListParams { + cwds: Vec::new(), + force_reload: false, + per_cwd_extra_user_roots: None, + }, + }; + assert_eq!( + skills_list.serialization_scope(), + Some(ClientRequestSerializationScope::GlobalSharedRead("config")) + ); + + let plugin_list = ClientRequest::PluginList { + request_id: request_id(), + params: v2::PluginListParams { + cwds: None, + marketplace_kinds: None, + }, + }; + assert_eq!( + plugin_list.serialization_scope(), + Some(ClientRequestSerializationScope::GlobalSharedRead("config")) + ); + let plugin_uninstall = ClientRequest::PluginUninstall { request_id: request_id(), params: v2::PluginUninstallParams { @@ -1705,7 +1734,7 @@ mod tests { }; assert_eq!( config_read.serialization_scope(), - Some(ClientRequestSerializationScope::Global("config")) + Some(ClientRequestSerializationScope::GlobalSharedRead("config")) ); let account_read = ClientRequest::GetAccount { diff --git a/codex-rs/app-server-protocol/src/protocol/v2/config.rs b/codex-rs/app-server-protocol/src/protocol/v2/config.rs index da4f493d77..8bc50bb1f2 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/config.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/config.rs @@ -380,6 +380,12 @@ pub struct ManagedHooksRequirements { #[serde(rename = "PostToolUse")] #[ts(rename = "PostToolUse")] pub post_tool_use: Vec, + #[serde(rename = "PreCompact")] + #[ts(rename = "PreCompact")] + pub pre_compact: Vec, + #[serde(rename = "PostCompact")] + #[ts(rename = "PostCompact")] + pub post_compact: Vec, #[serde(rename = "SessionStart")] #[ts(rename = "SessionStart")] pub session_start: Vec, diff --git a/codex-rs/app-server-protocol/src/protocol/v2/hook.rs b/codex-rs/app-server-protocol/src/protocol/v2/hook.rs index e0f74b5ded..4a07bd495b 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/hook.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/hook.rs @@ -17,7 +17,7 @@ use ts_rs::TS; v2_enum_from_core!( pub enum HookEventName from CoreHookEventName { - PreToolUse, PermissionRequest, PostToolUse, SessionStart, UserPromptSubmit, Stop + PreToolUse, PermissionRequest, PostToolUse, PreCompact, PostCompact, SessionStart, UserPromptSubmit, Stop } ); diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index ec06898d9b..64215566ee 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -49,6 +49,7 @@ use codex_app_server_protocol::RawResponseItemCompletedNotification; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequestPayload; +use codex_app_server_protocol::SkillsChangedNotification; use codex_app_server_protocol::ThreadGoalUpdatedNotification; use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadRealtimeClosedNotification; @@ -193,6 +194,13 @@ pub(crate) async fn apply_bespoke_event_handling( ) .await; } + EventMsg::SkillsUpdateAvailable => { + outgoing + .send_server_notification(ServerNotification::SkillsChanged( + SkillsChangedNotification {}, + )) + .await; + } EventMsg::McpStartupUpdate(update) => { let (status, error) = match update.status { codex_protocol::protocol::McpStartupStatus::Starting => { @@ -2586,8 +2594,7 @@ mod tests { config.model_provider.clone(), config.codex_home.to_path_buf(), Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await, + ), ); let codex_core::NewThread { thread_id: conversation_id, @@ -3165,8 +3172,7 @@ mod tests { config.model_provider.clone(), config.codex_home.to_path_buf(), Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await, + ), ); let codex_core::NewThread { thread_id: conversation_id, diff --git a/codex-rs/app-server/src/in_process.rs b/codex-rs/app-server/src/in_process.rs index 35b92548b8..dda4a3bf4a 100644 --- a/codex-rs/app-server/src/in_process.rs +++ b/codex-rs/app-server/src/in_process.rs @@ -82,13 +82,12 @@ use codex_config::CloudRequirementsLoader; use codex_config::LoaderOverrides; use codex_config::ThreadConfigLoader; use codex_core::config::Config; -use codex_core::init_state_db_from_config; use codex_core::resolve_installation_id; use codex_exec_server::EnvironmentManager; use codex_feedback::CodexFeedback; use codex_login::AuthManager; use codex_protocol::protocol::SessionSource; -use codex_rollout::state_db::StateDbHandle; +pub use codex_rollout::StateDbHandle; pub use codex_state::log_db::LogDbLayer; use tokio::sync::mpsc; use tokio::sync::oneshot; @@ -129,7 +128,7 @@ pub struct InProcessStartArgs { pub feedback: CodexFeedback, /// SQLite tracing layer used to flush recently emitted logs before feedback upload. pub log_db: Option, - /// Optional state DB handle to use for the in-process runtime. + /// Process-wide SQLite state handle shared with embedded app-server consumers. pub state_db: Option, /// Environment manager used by core execution and filesystem operations. pub environment_manager: Arc, @@ -368,10 +367,6 @@ pub async fn start(args: InProcessStartArgs) -> IoResult async fn start_uninitialized(args: InProcessStartArgs) -> IoResult { let channel_capacity = args.channel_capacity.max(1); - let state_db = match args.state_db.clone() { - Some(state_db) => Some(state_db), - None => init_state_db_from_config(args.config.as_ref()).await, - }; let installation_id = resolve_installation_id(&args.config.codex_home).await?; let (client_tx, mut client_rx) = mpsc::channel::(channel_capacity); let (event_tx, event_rx) = mpsc::channel::(channel_capacity); @@ -421,12 +416,6 @@ async fn start_uninitialized(args: InProcessStartArgs) -> IoResult(channel_capacity); let mut processor_handle = tokio::spawn(async move { - let Some(state_db) = state_db else { - warn!( - "in-process app-server state db initialization failed; shutting down processor task" - ); - return; - }; let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs { outgoing: Arc::clone(&processor_outgoing), analytics_events_client, @@ -436,7 +425,7 @@ async fn start_uninitialized(args: InProcessStartArgs) -> IoResult InProcessClientHandle { let codex_home = TempDir::new().expect("temp dir"); let config = Arc::new(build_test_config(codex_home.path()).await); - let state_db = init_state_db_from_config(config.as_ref()) + let state_db = codex_rollout::state_db::try_init(config.as_ref()) .await .expect("state db should initialize for in-process test"); let args = InProcessStartArgs { @@ -833,7 +822,7 @@ mod tests { } #[tokio::test] - async fn in_process_allows_device_key_requests_to_reach_device_key_api() { + async fn in_process_allows_device_key_requests_to_reach_device_key_processor() { let client = start_test_client(SessionSource::Cli).await; const MALFORMED_KEY_ID_MESSAGE: &str = concat!( "invalid device key payload: keyId must be dk_hse_, dk_tpm_, or dk_osn_ ", diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 2efdfef52e..08aab99f65 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -51,11 +51,11 @@ use codex_config::TextRange as CoreTextRange; use codex_core::ExecPolicyError; use codex_core::check_execpolicy_for_warnings; use codex_core::config::find_codex_home; -use codex_core::init_state_db_from_config; use codex_exec_server::EnvironmentManager; use codex_exec_server::ExecServerRuntimePaths; use codex_feedback::CodexFeedback; use codex_protocol::protocol::SessionSource; +use codex_rollout::state_db as rollout_state_db; use codex_state::log_db; use tokio::sync::mpsc; use tokio::sync::oneshot; @@ -93,7 +93,6 @@ mod outgoing_message; mod request_processors; mod request_serialization; mod server_request_error; -mod skills_watcher; mod thread_state; mod thread_status; mod transport; @@ -490,9 +489,9 @@ pub async fn run_main_with_transport_options( } }; - let state_db = init_state_db_from_config(&config) - .await - .ok_or_else(|| std::io::Error::other("failed to initialize sqlite state db"))?; + let state_db_result = rollout_state_db::try_init(&config).await; + let state_db_init_error = state_db_result.as_ref().err().map(ToString::to_string); + let state_db = state_db_result.ok(); if should_run_personality_migration { let effective_toml = config.config_layer_stack.effective_config(); @@ -601,12 +600,10 @@ pub async fn run_main_with_transport_options( let feedback_layer = feedback.logger_layer(); let feedback_metadata_layer = feedback.metadata_layer(); - let log_db = log_db::start(state_db.clone()); - let log_db_layer = Some( - log_db - .clone() - .with_filter(Targets::new().with_default(Level::TRACE)), - ); + let log_db = state_db.clone().map(log_db::start); + let log_db_layer = log_db + .clone() + .map(|layer| layer.with_filter(Targets::new().with_default(Level::TRACE))); let otel_logger_layer = otel.as_ref().and_then(|o| o.logger_layer()); let otel_tracing_layer = otel.as_ref().and_then(|o| o.tracing_layer()); let _ = tracing_subscriber::registry() @@ -624,6 +621,10 @@ pub async fn run_main_with_transport_options( } } let installation_id = resolve_installation_id(&config.codex_home).await?; + if let Some(err) = &state_db_init_error { + error!("failed to initialize sqlite state db: {err}"); + } + let transport_shutdown_token = CancellationToken::new(); let mut transport_accept_handles = Vec::>::new(); @@ -668,17 +669,25 @@ pub async fn run_main_with_transport_options( let auth_manager = AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await; - let remote_control_enabled = config.features.enabled(Feature::RemoteControl); + let remote_control_config_enabled = config.features.enabled(Feature::RemoteControl); + let remote_control_enabled = remote_control_config_enabled && state_db.is_some(); + if remote_control_config_enabled && state_db.is_none() { + error!("remote control disabled because sqlite state db is unavailable"); + } if transport_accept_handles.is_empty() && !remote_control_enabled { return Err(std::io::Error::new( ErrorKind::InvalidInput, - "no transport configured; use --listen or enable remote control", + if remote_control_config_enabled && state_db.is_none() { + "no transport configured; remote control disabled because sqlite state db is unavailable" + } else { + "no transport configured; use --listen or enable remote control" + }, )); } let (remote_control_accept_handle, remote_control_handle) = start_remote_control( config.chatgpt_base_url.clone(), - Some(state_db.clone()), + state_db.clone(), auth_manager.clone(), transport_event_tx.clone(), transport_shutdown_token.clone(), @@ -762,7 +771,7 @@ pub async fn run_main_with_transport_options( config_manager, environment_manager, feedback: feedback.clone(), - log_db: Some(log_db), + log_db, state_db: state_db.clone(), config_warnings, session_source, diff --git a/codex-rs/app-server/src/mcp_refresh.rs b/codex-rs/app-server/src/mcp_refresh.rs index b1471d88fc..8e1ccd3c0a 100644 --- a/codex-rs/app-server/src/mcp_refresh.rs +++ b/codex-rs/app-server/src/mcp_refresh.rs @@ -108,9 +108,8 @@ mod tests { use codex_config::ThreadConfigLoadErrorCode; use codex_config::ThreadConfigLoader; use codex_config::ThreadConfigSource; - use codex_core::agent_graph_store_from_state_db; use codex_core::config::ConfigOverrides; - use codex_core::init_state_db_from_config; + use codex_core::init_state_db; use codex_core::thread_store_from_config; use codex_exec_server::EnvironmentManager; use codex_login::AuthManager; @@ -175,20 +174,18 @@ mod tests { .await?; let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("dummy")); - let state_db = init_state_db_from_config(&good_config) + let state_db = init_state_db(&good_config) .await .expect("refresh tests require state db"); - let thread_store = thread_store_from_config(&good_config, state_db.clone()); - let agent_graph_store = agent_graph_store_from_state_db(state_db.clone()); + let thread_store = thread_store_from_config(&good_config, Some(state_db.clone())); let thread_manager = Arc::new(ThreadManager::new( &good_config, auth_manager, SessionSource::Exec, Arc::new(EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, thread_store, - agent_graph_store, + Some(state_db.clone()), "11111111-1111-4111-8111-111111111111".to_string(), )); thread_manager.start_thread(good_config).await?; diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index b1d28f20cc..2e7414a178 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -35,7 +35,6 @@ use crate::request_processors::WindowsSandboxRequestProcessor; use crate::request_serialization::QueuedInitializedRequest; use crate::request_serialization::RequestSerializationQueueKey; use crate::request_serialization::RequestSerializationQueues; -use crate::skills_watcher::SkillsWatcher; use crate::thread_state::ThreadStateManager; use crate::transport::AppServerTransport; use crate::transport::ConnectionOrigin; @@ -62,7 +61,6 @@ use codex_app_server_protocol::experimental_required_message; use codex_arg0::Arg0DispatchPaths; use codex_chatgpt::workspace_settings; use codex_core::ThreadManager; -use codex_core::agent_graph_store_from_state_db; use codex_core::config::Config; use codex_core::thread_store_from_config; use codex_exec_server::EnvironmentManager; @@ -256,7 +254,7 @@ pub(crate) struct MessageProcessorArgs { pub(crate) environment_manager: Arc, pub(crate) feedback: CodexFeedback, pub(crate) log_db: Option, - pub(crate) state_db: StateDbHandle, + pub(crate) state_db: Option, pub(crate) config_warnings: Vec, pub(crate) session_source: SessionSource, pub(crate) auth_manager: Arc, @@ -295,22 +293,19 @@ impl MessageProcessor { // affect per-thread behavior, but they must not move newly started, // resumed, or forked threads to a different persistence backend/root. let thread_store = thread_store_from_config(config.as_ref(), state_db.clone()); - let agent_graph_store = agent_graph_store_from_state_db(state_db.clone()); let thread_manager = Arc::new(ThreadManager::new( config.as_ref(), auth_manager.clone(), session_source, environment_manager, Some(analytics_events_client.clone()), - state_db.clone(), Arc::clone(&thread_store), - agent_graph_store.clone(), + state_db.clone(), installation_id, )); thread_manager .plugins_manager() .set_analytics_events_client(analytics_events_client.clone()); - let skills_watcher = SkillsWatcher::new(thread_manager.skills_manager(), outgoing.clone()); let pending_thread_unloads = Arc::new(Mutex::new(HashSet::new())); let thread_state_manager = ThreadStateManager::new(); @@ -352,7 +347,7 @@ impl MessageProcessor { Arc::clone(&config), feedback, log_db, - Some(state_db.clone()), + state_db.clone(), ); let git_processor = GitRequestProcessor::new(); let initialize_processor = InitializeRequestProcessor::new( @@ -402,8 +397,7 @@ impl MessageProcessor { thread_watch_manager.clone(), Arc::clone(&thread_list_state_permit), thread_goal_processor.clone(), - Some(state_db.clone()), - Arc::clone(&skills_watcher), + state_db.clone(), ); let turn_processor = TurnRequestProcessor::new( auth_manager.clone(), @@ -417,7 +411,6 @@ impl MessageProcessor { thread_state_manager, thread_watch_manager, thread_list_state_permit, - Arc::clone(&skills_watcher), ); if matches!(plugin_startup_tasks, crate::PluginStartupTasks::Start) { // Keep plugin startup warmups aligned at app-server startup. @@ -804,9 +797,9 @@ impl MessageProcessor { ); if let Some(scope) = serialization_scope { - let key = RequestSerializationQueueKey::from_scope(connection_id, scope); + let (key, access) = RequestSerializationQueueKey::from_scope(connection_id, scope); self.request_serialization_queues - .enqueue(key, request) + .enqueue(key, access, request) .await; } else { tokio::spawn(async move { diff --git a/codex-rs/app-server/src/message_processor_tracing_tests.rs b/codex-rs/app-server/src/message_processor_tracing_tests.rs index 27e2c2f473..0d4ef8279b 100644 --- a/codex-rs/app-server/src/message_processor_tracing_tests.rs +++ b/codex-rs/app-server/src/message_processor_tracing_tests.rs @@ -32,7 +32,6 @@ use codex_config::CloudRequirementsLoader; use codex_config::LoaderOverrides; use codex_core::config::Config; use codex_core::config::ConfigBuilder; -use codex_core::init_state_db_from_config; use codex_exec_server::EnvironmentManager; use codex_feedback::CodexFeedback; use codex_login::AuthManager; @@ -282,9 +281,6 @@ async fn build_test_processor( outgoing_tx, analytics_events_client.clone(), )); - let state_db = init_state_db_from_config(config.as_ref()) - .await - .expect("tracing test processor requires state db"); let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs { outgoing, analytics_events_client, @@ -294,7 +290,7 @@ async fn build_test_processor( environment_manager: Arc::new(EnvironmentManager::default_for_tests()), feedback: CodexFeedback::new(), log_db: None, - state_db, + state_db: None, config_warnings: Vec::new(), session_source: SessionSource::VSCode, auth_manager, diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index 84e16f726d..52b15b0521 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -11,7 +11,6 @@ use crate::outgoing_message::ConnectionRequestId; use crate::outgoing_message::OutgoingMessageSender; use crate::outgoing_message::RequestContext; use crate::outgoing_message::ThreadScopedOutgoingMessageSender; -use crate::skills_watcher::SkillsWatcher; use crate::thread_status::ThreadWatchManager; use crate::thread_status::resolve_thread_status; use chrono::DateTime; diff --git a/codex-rs/app-server/src/request_processors/catalog_processor.rs b/codex-rs/app-server/src/request_processors/catalog_processor.rs index f93f9cc08c..b26748d551 100644 --- a/codex-rs/app-server/src/request_processors/catalog_processor.rs +++ b/codex-rs/app-server/src/request_processors/catalog_processor.rs @@ -1,4 +1,5 @@ use super::*; +use futures::StreamExt; #[derive(Clone)] pub(crate) struct CatalogRequestProcessor { @@ -9,6 +10,8 @@ pub(crate) struct CatalogRequestProcessor { pub(super) workspace_settings_cache: Arc, } +const SKILLS_LIST_CWD_CONCURRENCY: usize = 5; + fn skills_to_info( skills: &[codex_core::skills::SkillMetadata], disabled_paths: &HashSet, @@ -430,56 +433,76 @@ impl CatalogRequestProcessor { .environment_manager() .default_environment() .map(|environment| environment.get_filesystem()); - let mut data = Vec::new(); - for cwd in cwds { - let (cwd_abs, config_layer_stack) = match self.resolve_cwd_config(&cwd).await { - Ok(resolved) => resolved, - Err(message) => { - let error_path = cwd.clone(); - data.push(codex_app_server_protocol::SkillsListEntry { - cwd, - skills: Vec::new(), - errors: vec![codex_app_server_protocol::SkillErrorInfo { - path: error_path, - message, - }], - }); - continue; + let mut data = futures::stream::iter(cwds.into_iter().enumerate()) + .map(|(index, cwd)| { + let config = &config; + let extra_roots_by_cwd = &extra_roots_by_cwd; + let fs = fs.clone(); + let plugins_manager = &plugins_manager; + let skills_manager = &skills_manager; + async move { + let (cwd_abs, config_layer_stack) = match self.resolve_cwd_config(&cwd).await { + Ok(resolved) => resolved, + Err(message) => { + let error_path = cwd.clone(); + return ( + index, + codex_app_server_protocol::SkillsListEntry { + cwd, + skills: Vec::new(), + errors: vec![codex_app_server_protocol::SkillErrorInfo { + path: error_path, + message, + }], + }, + ); + } + }; + let extra_roots = extra_roots_by_cwd + .get(&cwd) + .map_or(&[][..], std::vec::Vec::as_slice); + let effective_skill_roots = if workspace_codex_plugins_enabled { + let plugins_input = config.plugins_config_input(); + plugins_manager + .effective_skill_roots_for_layer_stack( + &config_layer_stack, + &plugins_input, + ) + .await + } else { + Vec::new() + }; + let skills_input = codex_core::skills::SkillsLoadInput::new( + cwd_abs.clone(), + effective_skill_roots, + config_layer_stack, + config.bundled_skills_enabled(), + ); + let outcome = skills_manager + .skills_for_cwd_with_extra_user_roots( + &skills_input, + force_reload, + extra_roots, + fs, + ) + .await; + let errors = errors_to_info(&outcome.errors); + let skills = skills_to_info(&outcome.skills, &outcome.disabled_paths); + ( + index, + codex_app_server_protocol::SkillsListEntry { + cwd, + skills, + errors, + }, + ) } - }; - let extra_roots = extra_roots_by_cwd - .get(&cwd) - .map_or(&[][..], std::vec::Vec::as_slice); - let effective_skill_roots = if workspace_codex_plugins_enabled { - let plugins_input = config.plugins_config_input(); - plugins_manager - .effective_skill_roots_for_layer_stack(&config_layer_stack, &plugins_input) - .await - } else { - Vec::new() - }; - let skills_input = codex_core::skills::SkillsLoadInput::new( - cwd_abs.clone(), - effective_skill_roots, - config_layer_stack, - config.bundled_skills_enabled(), - ); - let outcome = skills_manager - .skills_for_cwd_with_extra_user_roots( - &skills_input, - force_reload, - extra_roots, - fs.clone(), - ) - .await; - let errors = errors_to_info(&outcome.errors); - let skills = skills_to_info(&outcome.skills, &outcome.disabled_paths); - data.push(codex_app_server_protocol::SkillsListEntry { - cwd, - skills, - errors, - }); - } + }) + .buffer_unordered(SKILLS_LIST_CWD_CONCURRENCY) + .collect::>() + .await; + data.sort_unstable_by_key(|(index, _)| *index); + let data = data.into_iter().map(|(_, entry)| entry).collect(); Ok(SkillsListResponse { data }) } diff --git a/codex-rs/app-server/src/request_processors/config_processor.rs b/codex-rs/app-server/src/request_processors/config_processor.rs index f084867719..840542419a 100644 --- a/codex-rs/app-server/src/request_processors/config_processor.rs +++ b/codex-rs/app-server/src/request_processors/config_processor.rs @@ -462,6 +462,8 @@ fn map_hooks_requirements_to_api(hooks: ManagedHooksRequirementsToml) -> Managed pre_tool_use, permission_request, post_tool_use, + pre_compact, + post_compact, session_start, user_prompt_submit, stop, @@ -473,6 +475,8 @@ fn map_hooks_requirements_to_api(hooks: ManagedHooksRequirementsToml) -> Managed pre_tool_use: map_hook_matcher_groups_to_api(pre_tool_use), permission_request: map_hook_matcher_groups_to_api(permission_request), post_tool_use: map_hook_matcher_groups_to_api(post_tool_use), + pre_compact: map_hook_matcher_groups_to_api(pre_compact), + post_compact: map_hook_matcher_groups_to_api(post_compact), session_start: map_hook_matcher_groups_to_api(session_start), user_prompt_submit: map_hook_matcher_groups_to_api(user_prompt_submit), stop: map_hook_matcher_groups_to_api(stop), diff --git a/codex-rs/app-server/src/request_processors/device_key_processor.rs b/codex-rs/app-server/src/request_processors/device_key_processor.rs index e1da459a2e..ea0a96c2af 100644 --- a/codex-rs/app-server/src/request_processors/device_key_processor.rs +++ b/codex-rs/app-server/src/request_processors/device_key_processor.rs @@ -33,8 +33,8 @@ use codex_device_key::RemoteControlClientConnectionAudience; use codex_device_key::RemoteControlClientConnectionSignPayload; use codex_device_key::RemoteControlClientEnrollmentAudience; use codex_device_key::RemoteControlClientEnrollmentSignPayload; -use codex_rollout::state_db::StateDbHandle; use codex_state::DeviceKeyBindingRecord; +use codex_state::StateRuntime; #[derive(Clone)] pub(crate) struct DeviceKeyRequestProcessor { @@ -43,7 +43,10 @@ pub(crate) struct DeviceKeyRequestProcessor { } impl DeviceKeyRequestProcessor { - pub(crate) fn new(outgoing: Arc, state_db: StateDbHandle) -> Self { + pub(crate) fn new( + outgoing: Arc, + state_db: Option>, + ) -> Self { Self { outgoing, store: DeviceKeyStore::new(Arc::new(StateDeviceKeyBindingStore::new(state_db))), @@ -167,18 +170,25 @@ async fn sign_device_key( } struct StateDeviceKeyBindingStore { - state_db: StateDbHandle, + state_db: Option>, } impl StateDeviceKeyBindingStore { - fn new(state_db: StateDbHandle) -> Self { + fn new(state_db: Option>) -> Self { Self { state_db } } + + async fn state_db(&self) -> Result, DeviceKeyError> { + self.state_db + .clone() + .ok_or_else(|| DeviceKeyError::Platform("sqlite state db unavailable".to_string())) + } } impl fmt::Debug for StateDeviceKeyBindingStore { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("StateDeviceKeyBindingStore") + .field("has_state_db", &self.state_db.is_some()) .finish_non_exhaustive() } } @@ -186,7 +196,7 @@ impl fmt::Debug for StateDeviceKeyBindingStore { #[async_trait] impl DeviceKeyBindingStore for StateDeviceKeyBindingStore { async fn get_binding(&self, key_id: &str) -> Result, DeviceKeyError> { - let state_db = self.state_db.clone(); + let state_db = self.state_db().await?; state_db .get_device_key_binding(key_id) .await @@ -204,7 +214,7 @@ impl DeviceKeyBindingStore for StateDeviceKeyBindingStore { key_id: &str, binding: &DeviceKeyBinding, ) -> Result<(), DeviceKeyError> { - let state_db = self.state_db.clone(); + let state_db = self.state_db().await?; state_db .upsert_device_key_binding(&DeviceKeyBindingRecord { key_id: key_id.to_string(), diff --git a/codex-rs/app-server/src/request_processors/thread_goal_processor.rs b/codex-rs/app-server/src/request_processors/thread_goal_processor.rs index ff192e34b2..0e12e44ce5 100644 --- a/codex-rs/app-server/src/request_processors/thread_goal_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_goal_processor.rs @@ -7,7 +7,7 @@ pub(crate) struct ThreadGoalRequestProcessor { outgoing: Arc, config: Arc, thread_state_manager: ThreadStateManager, - state_db: StateDbHandle, + state_db: Option, } impl ThreadGoalRequestProcessor { @@ -16,7 +16,7 @@ impl ThreadGoalRequestProcessor { outgoing: Arc, config: Arc, thread_state_manager: ThreadStateManager, - state_db: StateDbHandle, + state_db: Option, ) -> Self { Self { thread_manager, @@ -72,6 +72,23 @@ impl ThreadGoalRequestProcessor { } } + pub(crate) async fn pending_resume_goal_state( + &self, + thread: &CodexThread, + ) -> (bool, Option) { + let emit_thread_goal_update = self.config.features.enabled(Feature::Goals); + let thread_goal_state_db = if emit_thread_goal_update { + if let Some(state_db) = thread.state_db() { + Some(state_db) + } else { + self.state_db.clone() + } + } else { + None + }; + (emit_thread_goal_update, thread_goal_state_db) + } + async fn thread_goal_set_inner( &self, request_id: ConnectionRequestId, @@ -93,7 +110,7 @@ impl ThreadGoalRequestProcessor { None => find_thread_path_by_id_str( &self.config.codex_home, &thread_id.to_string(), - Some(self.state_db.as_ref()), + self.state_db.as_deref(), ) .await .map_err(|err| { @@ -258,7 +275,7 @@ impl ThreadGoalRequestProcessor { None => find_thread_path_by_id_str( &self.config.codex_home, &thread_id.to_string(), - Some(self.state_db.as_ref()), + self.state_db.as_deref(), ) .await .map_err(|err| { @@ -322,7 +339,7 @@ impl ThreadGoalRequestProcessor { find_thread_path_by_id_str( &self.config.codex_home, &thread_id.to_string(), - Some(self.state_db.as_ref()), + self.state_db.as_deref(), ) .await .map_err(|err| { @@ -331,7 +348,9 @@ impl ThreadGoalRequestProcessor { .ok_or_else(|| invalid_request(format!("thread not found: {thread_id}")))?; } - Ok(self.state_db.clone()) + self.state_db + .clone() + .ok_or_else(|| internal_error("sqlite state db unavailable for thread goals")) } async fn emit_thread_goal_snapshot(&self, thread_id: ThreadId) { diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs index 45031490b0..ef44a2b178 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -12,7 +12,6 @@ pub(super) struct ListenerTaskContext { pub(super) thread_list_state_permit: Arc, pub(super) fallback_model_provider: String, pub(super) codex_home: PathBuf, - pub(super) skills_watcher: Arc, } struct UnloadingState { @@ -227,22 +226,12 @@ pub(super) async fn ensure_listener_task_running( "thread {conversation_id} is closing; retry after the thread is closed" ))); }; - let config = conversation.config().await; - let environments = conversation.environment_selections().await; - let watch_registration = listener_task_context - .skills_watcher - .register_thread_config( - config.as_ref(), - listener_task_context.thread_manager.as_ref(), - &environments, - ) - .await; let (mut listener_command_rx, listener_generation) = { let mut thread_state = thread_state.lock().await; if thread_state.listener_matches(&conversation) { return Ok(()); } - thread_state.set_listener(cancel_tx, &conversation, watch_registration) + thread_state.set_listener(cancel_tx, &conversation) }; let ListenerTaskContext { outgoing, @@ -253,7 +242,6 @@ pub(super) async fn ensure_listener_task_running( thread_list_state_permit, fallback_model_provider, codex_home, - .. } = listener_task_context; let outgoing_for_task = Arc::clone(&outgoing); tokio::spawn(async move { diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs index d498e17c53..deeb2e9d62 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -316,7 +316,6 @@ pub(crate) struct ThreadRequestProcessor { pub(super) thread_goal_processor: ThreadGoalRequestProcessor, pub(super) state_db: Option, pub(super) background_tasks: TaskTracker, - pub(super) skills_watcher: Arc, } impl ThreadRequestProcessor { @@ -335,7 +334,6 @@ impl ThreadRequestProcessor { thread_list_state_permit: Arc, thread_goal_processor: ThreadGoalRequestProcessor, state_db: Option, - skills_watcher: Arc, ) -> Self { Self { auth_manager, @@ -352,7 +350,6 @@ impl ThreadRequestProcessor { thread_goal_processor, state_db, background_tasks: TaskTracker::new(), - skills_watcher, } } @@ -745,7 +742,6 @@ impl ThreadRequestProcessor { thread_list_state_permit: self.thread_list_state_permit.clone(), fallback_model_provider: self.config.model_provider_id.clone(), codex_home: self.config.codex_home.to_path_buf(), - skills_watcher: Arc::clone(&self.skills_watcher), } } @@ -843,7 +839,6 @@ impl ThreadRequestProcessor { thread_list_state_permit: self.thread_list_state_permit.clone(), fallback_model_provider: self.config.model_provider_id.clone(), codex_home: self.config.codex_home.to_path_buf(), - skills_watcher: Arc::clone(&self.skills_watcher), }; let request_trace = request_context.request_trace(); let config_manager = self.config_manager.clone(); @@ -1044,6 +1039,7 @@ impl ThreadRequestProcessor { .collect() }; let core_dynamic_tool_count = core_dynamic_tools.len(); + let NewThread { thread_id, thread, @@ -2675,10 +2671,10 @@ impl ThreadRequestProcessor { ))); }; - let emit_thread_goal_update = self.config.features.enabled(Feature::Goals); - let thread_goal_state_db = emit_thread_goal_update - .then(|| self.state_db.clone()) - .flatten(); + let (emit_thread_goal_update, thread_goal_state_db) = self + .thread_goal_processor + .pending_resume_goal_state(existing_thread.as_ref()) + .await; let command = crate::thread_state::ThreadListenerCommand::SendThreadResumeResponse( Box::new(crate::thread_state::PendingThreadResumeRequest { diff --git a/codex-rs/app-server/src/request_processors/turn_processor.rs b/codex-rs/app-server/src/request_processors/turn_processor.rs index d1dae4ef46..bdc5847b0d 100644 --- a/codex-rs/app-server/src/request_processors/turn_processor.rs +++ b/codex-rs/app-server/src/request_processors/turn_processor.rs @@ -13,7 +13,6 @@ pub(crate) struct TurnRequestProcessor { thread_state_manager: ThreadStateManager, thread_watch_manager: ThreadWatchManager, thread_list_state_permit: Arc, - skills_watcher: Arc, } impl TurnRequestProcessor { @@ -30,7 +29,6 @@ impl TurnRequestProcessor { thread_state_manager: ThreadStateManager, thread_watch_manager: ThreadWatchManager, thread_list_state_permit: Arc, - skills_watcher: Arc, ) -> Self { Self { auth_manager, @@ -44,7 +42,6 @@ impl TurnRequestProcessor { thread_state_manager, thread_watch_manager, thread_list_state_permit, - skills_watcher, } } @@ -1090,7 +1087,6 @@ impl TurnRequestProcessor { thread_list_state_permit: self.thread_list_state_permit.clone(), fallback_model_provider: self.config.model_provider_id.clone(), codex_home: self.config.codex_home.to_path_buf(), - skills_watcher: Arc::clone(&self.skills_watcher), } } diff --git a/codex-rs/app-server/src/request_serialization.rs b/codex-rs/app-server/src/request_serialization.rs index 0eb509e098..0dd167b74d 100644 --- a/codex-rs/app-server/src/request_serialization.rs +++ b/codex-rs/app-server/src/request_serialization.rs @@ -6,6 +6,7 @@ use std::pin::Pin; use std::sync::Arc; use codex_app_server_protocol::ClientRequestSerializationScope; +use futures::future::join_all; use tokio::sync::Mutex; use tracing::Instrument; @@ -43,35 +44,61 @@ pub(crate) enum RequestSerializationQueueKey { }, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum RequestSerializationAccess { + Exclusive, + SharedRead, +} + impl RequestSerializationQueueKey { pub(crate) fn from_scope( connection_id: ConnectionId, scope: ClientRequestSerializationScope, - ) -> Self { + ) -> (Self, RequestSerializationAccess) { match scope { - ClientRequestSerializationScope::Global(name) => Self::Global(name), - ClientRequestSerializationScope::Thread { thread_id } => Self::Thread { thread_id }, - ClientRequestSerializationScope::ThreadPath { path } => Self::ThreadPath { path }, - ClientRequestSerializationScope::CommandExecProcess { process_id } => { + ClientRequestSerializationScope::Global(name) => { + (Self::Global(name), RequestSerializationAccess::Exclusive) + } + ClientRequestSerializationScope::GlobalSharedRead(name) => { + (Self::Global(name), RequestSerializationAccess::SharedRead) + } + ClientRequestSerializationScope::Thread { thread_id } => ( + Self::Thread { thread_id }, + RequestSerializationAccess::Exclusive, + ), + ClientRequestSerializationScope::ThreadPath { path } => ( + Self::ThreadPath { path }, + RequestSerializationAccess::Exclusive, + ), + ClientRequestSerializationScope::CommandExecProcess { process_id } => ( Self::CommandExecProcess { connection_id, process_id, - } - } - ClientRequestSerializationScope::Process { process_handle } => Self::Process { - connection_id, - process_handle, - }, - ClientRequestSerializationScope::FuzzyFileSearchSession { session_id } => { - Self::FuzzyFileSearchSession { session_id } - } - ClientRequestSerializationScope::FsWatch { watch_id } => Self::FsWatch { - connection_id, - watch_id, - }, - ClientRequestSerializationScope::McpOauth { server_name } => { - Self::McpOauth { server_name } - } + }, + RequestSerializationAccess::Exclusive, + ), + ClientRequestSerializationScope::Process { process_handle } => ( + Self::Process { + connection_id, + process_handle, + }, + RequestSerializationAccess::Exclusive, + ), + ClientRequestSerializationScope::FuzzyFileSearchSession { session_id } => ( + Self::FuzzyFileSearchSession { session_id }, + RequestSerializationAccess::Exclusive, + ), + ClientRequestSerializationScope::FsWatch { watch_id } => ( + Self::FsWatch { + connection_id, + watch_id, + }, + RequestSerializationAccess::Exclusive, + ), + ClientRequestSerializationScope::McpOauth { server_name } => ( + Self::McpOauth { server_name }, + RequestSerializationAccess::Exclusive, + ), } } } @@ -98,17 +125,24 @@ impl QueuedInitializedRequest { } } +struct QueuedSerializedRequest { + access: RequestSerializationAccess, + request: QueuedInitializedRequest, +} + #[derive(Clone, Default)] pub(crate) struct RequestSerializationQueues { - inner: Arc>>>, + inner: Arc>>>, } impl RequestSerializationQueues { pub(crate) async fn enqueue( &self, key: RequestSerializationQueueKey, + access: RequestSerializationAccess, request: QueuedInitializedRequest, ) { + let request = QueuedSerializedRequest { access, request }; let should_spawn = { let mut queues = self.inner.lock().await; match queues.get_mut(&key) { @@ -134,13 +168,27 @@ impl RequestSerializationQueues { async fn drain(self, key: RequestSerializationQueueKey) { loop { - let request = { + let requests = { let mut queues = self.inner.lock().await; let Some(queue) = queues.get_mut(&key) else { return; }; match queue.pop_front() { - Some(request) => request, + Some(request) => { + let access = request.access; + let mut requests = vec![request]; + if access == RequestSerializationAccess::SharedRead { + while queue.front().is_some_and(|request| { + request.access == RequestSerializationAccess::SharedRead + }) { + let Some(request) = queue.pop_front() else { + break; + }; + requests.push(request); + } + } + requests + } None => { queues.remove(&key); return; @@ -148,7 +196,7 @@ impl RequestSerializationQueues { } }; - request.run().await; + join_all(requests.into_iter().map(|request| request.request.run())).await; } } } @@ -158,6 +206,7 @@ mod tests { use super::*; use pretty_assertions::assert_eq; use std::sync::Arc; + use tokio::sync::broadcast; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::time::Duration; @@ -195,6 +244,7 @@ mod tests { queues .enqueue( key.clone(), + RequestSerializationAccess::Exclusive, QueuedInitializedRequest::new(Arc::clone(&gate), async move { tx.send(value).expect("receiver should be open"); }), @@ -230,6 +280,7 @@ mod tests { queues .enqueue( RequestSerializationQueueKey::Global("blocked"), + RequestSerializationAccess::Exclusive, QueuedInitializedRequest::new(gate(), async move { let _ = blocked_rx.await; }), @@ -238,6 +289,7 @@ mod tests { queues .enqueue( RequestSerializationQueueKey::Global("other"), + RequestSerializationAccess::Exclusive, QueuedInitializedRequest::new(gate(), async move { ran_tx.send(()).expect("receiver should be open"); }), @@ -268,6 +320,7 @@ mod tests { queues .enqueue( key.clone(), + RequestSerializationAccess::Exclusive, QueuedInitializedRequest::new(Arc::clone(&live_gate), async move { tx.send(FIRST_REQUEST_VALUE) .expect("receiver should be open"); @@ -281,6 +334,7 @@ mod tests { queues .enqueue( key.clone(), + RequestSerializationAccess::Exclusive, QueuedInitializedRequest::new(closed_gate, async move { tx.send(SECOND_REQUEST_VALUE) .expect("receiver should be open"); @@ -293,6 +347,7 @@ mod tests { queues .enqueue( key, + RequestSerializationAccess::Exclusive, QueuedInitializedRequest::new(live_gate, async move { tx.send(THIRD_REQUEST_VALUE) .expect("receiver should be open"); @@ -336,6 +391,7 @@ mod tests { queues .enqueue( key.clone(), + RequestSerializationAccess::Exclusive, QueuedInitializedRequest::new(Arc::clone(&live_gate), async move { tx.send(FIRST_REQUEST_VALUE) .expect("receiver should be open"); @@ -349,6 +405,7 @@ mod tests { queues .enqueue( key, + RequestSerializationAccess::Exclusive, QueuedInitializedRequest::new(live_gate.clone(), async move { tx.send(SECOND_REQUEST_VALUE) .expect("receiver should be open"); @@ -385,4 +442,241 @@ mod tests { None ); } + + #[tokio::test] + async fn same_key_shared_reads_run_concurrently() { + let queues = RequestSerializationQueues::default(); + let key = RequestSerializationQueueKey::Global("test"); + let (blocker_started_tx, blocker_started_rx) = oneshot::channel::<()>(); + let (blocker_release_tx, blocker_release_rx) = oneshot::channel::<()>(); + let (started_tx, mut started_rx) = mpsc::unbounded_channel(); + let (release_tx, _) = broadcast::channel::<()>(/*capacity*/ 1); + + queues + .enqueue( + key.clone(), + RequestSerializationAccess::Exclusive, + QueuedInitializedRequest::new(gate(), async move { + blocker_started_tx + .send(()) + .expect("receiver should be open"); + let _ = blocker_release_rx.await; + }), + ) + .await; + timeout(queue_drain_timeout(), blocker_started_rx) + .await + .expect("blocker should start") + .expect("sender should be open"); + + for value in [FIRST_REQUEST_VALUE, SECOND_REQUEST_VALUE] { + let started_tx = started_tx.clone(); + let mut release_rx = release_tx.subscribe(); + queues + .enqueue( + key.clone(), + RequestSerializationAccess::SharedRead, + QueuedInitializedRequest::new(gate(), async move { + started_tx.send(value).expect("receiver should be open"); + let _ = release_rx.recv().await; + }), + ) + .await; + } + drop(started_tx); + blocker_release_tx + .send(()) + .expect("blocker should still be waiting"); + + let mut started = Vec::new(); + for _ in 0..2 { + started.push( + timeout(queue_drain_timeout(), started_rx.recv()) + .await + .expect("timed out waiting for shared read") + .expect("sender should be open"), + ); + } + assert_eq!(started, vec![FIRST_REQUEST_VALUE, SECOND_REQUEST_VALUE]); + + release_tx + .send(()) + .expect("shared reads should still be waiting"); + } + + #[tokio::test] + async fn exclusive_write_waits_for_running_shared_reads() { + let queues = RequestSerializationQueues::default(); + let key = RequestSerializationQueueKey::Global("test"); + let (blocker_started_tx, blocker_started_rx) = oneshot::channel::<()>(); + let (blocker_release_tx, blocker_release_rx) = oneshot::channel::<()>(); + let (read_started_tx, mut read_started_rx) = mpsc::unbounded_channel(); + let (read_release_tx, _) = broadcast::channel::<()>(/*capacity*/ 1); + let (write_started_tx, write_started_rx) = oneshot::channel::<()>(); + + queues + .enqueue( + key.clone(), + RequestSerializationAccess::Exclusive, + QueuedInitializedRequest::new(gate(), async move { + blocker_started_tx + .send(()) + .expect("receiver should be open"); + let _ = blocker_release_rx.await; + }), + ) + .await; + timeout(queue_drain_timeout(), blocker_started_rx) + .await + .expect("blocker should start") + .expect("sender should be open"); + + for value in [FIRST_REQUEST_VALUE, SECOND_REQUEST_VALUE] { + let read_started_tx = read_started_tx.clone(); + let mut read_release_rx = read_release_tx.subscribe(); + queues + .enqueue( + key.clone(), + RequestSerializationAccess::SharedRead, + QueuedInitializedRequest::new(gate(), async move { + read_started_tx + .send(value) + .expect("receiver should be open"); + let _ = read_release_rx.recv().await; + }), + ) + .await; + } + queues + .enqueue( + key.clone(), + RequestSerializationAccess::Exclusive, + QueuedInitializedRequest::new(gate(), async move { + write_started_tx.send(()).expect("receiver should be open"); + }), + ) + .await; + drop(read_started_tx); + blocker_release_tx + .send(()) + .expect("blocker should still be waiting"); + + for _ in 0..2 { + timeout(queue_drain_timeout(), read_started_rx.recv()) + .await + .expect("timed out waiting for shared read") + .expect("sender should be open"); + } + let mut write_started_rx = Box::pin(write_started_rx); + timeout(shutdown_wait_timeout(), &mut write_started_rx) + .await + .expect_err("write should wait for running shared reads"); + + read_release_tx + .send(()) + .expect("shared reads should still be waiting"); + timeout(queue_drain_timeout(), &mut write_started_rx) + .await + .expect("write should start after shared reads finish") + .expect("sender should be open"); + } + + #[tokio::test] + async fn later_shared_reads_do_not_jump_ahead_of_queued_write() { + let queues = RequestSerializationQueues::default(); + let key = RequestSerializationQueueKey::Global("test"); + let (blocker_started_tx, blocker_started_rx) = oneshot::channel::<()>(); + let (blocker_release_tx, blocker_release_rx) = oneshot::channel::<()>(); + let (first_read_started_tx, first_read_started_rx) = oneshot::channel::<()>(); + let (first_read_release_tx, first_read_release_rx) = oneshot::channel::<()>(); + let (write_started_tx, write_started_rx) = oneshot::channel::<()>(); + let (write_release_tx, write_release_rx) = oneshot::channel::<()>(); + let (later_read_started_tx, later_read_started_rx) = oneshot::channel::<()>(); + + queues + .enqueue( + key.clone(), + RequestSerializationAccess::Exclusive, + QueuedInitializedRequest::new(gate(), async move { + blocker_started_tx + .send(()) + .expect("receiver should be open"); + let _ = blocker_release_rx.await; + }), + ) + .await; + timeout(queue_drain_timeout(), blocker_started_rx) + .await + .expect("blocker should start") + .expect("sender should be open"); + + queues + .enqueue( + key.clone(), + RequestSerializationAccess::SharedRead, + QueuedInitializedRequest::new(gate(), async move { + first_read_started_tx + .send(()) + .expect("receiver should be open"); + let _ = first_read_release_rx.await; + }), + ) + .await; + queues + .enqueue( + key.clone(), + RequestSerializationAccess::Exclusive, + QueuedInitializedRequest::new(gate(), async move { + write_started_tx.send(()).expect("receiver should be open"); + let _ = write_release_rx.await; + }), + ) + .await; + queues + .enqueue( + key.clone(), + RequestSerializationAccess::SharedRead, + QueuedInitializedRequest::new(gate(), async move { + later_read_started_tx + .send(()) + .expect("receiver should be open"); + }), + ) + .await; + blocker_release_tx + .send(()) + .expect("blocker should still be waiting"); + + timeout(queue_drain_timeout(), first_read_started_rx) + .await + .expect("first read should start") + .expect("sender should be open"); + let mut write_started_rx = Box::pin(write_started_rx); + timeout(shutdown_wait_timeout(), &mut write_started_rx) + .await + .expect_err("write should wait for the first read"); + let mut later_read_started_rx = Box::pin(later_read_started_rx); + timeout(shutdown_wait_timeout(), &mut later_read_started_rx) + .await + .expect_err("later read should wait behind the queued write"); + + first_read_release_tx + .send(()) + .expect("first read should still be waiting"); + timeout(queue_drain_timeout(), &mut write_started_rx) + .await + .expect("write should start after the first read") + .expect("sender should be open"); + timeout(shutdown_wait_timeout(), &mut later_read_started_rx) + .await + .expect_err("later read should still wait while the write is running"); + + write_release_tx + .send(()) + .expect("write should still be waiting"); + timeout(queue_drain_timeout(), &mut later_read_started_rx) + .await + .expect("later read should start after the write") + .expect("sender should be open"); + } } diff --git a/codex-rs/app-server/src/skills_watcher.rs b/codex-rs/app-server/src/skills_watcher.rs deleted file mode 100644 index 33acf65335..0000000000 --- a/codex-rs/app-server/src/skills_watcher.rs +++ /dev/null @@ -1,112 +0,0 @@ -use std::sync::Arc; -use std::time::Duration; - -use crate::outgoing_message::OutgoingMessageSender; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::SkillsChangedNotification; -use codex_core::ThreadManager; -use codex_core::config::Config; -use codex_core::file_watcher::FileWatcher; -use codex_core::file_watcher::FileWatcherSubscriber; -use codex_core::file_watcher::Receiver; -use codex_core::file_watcher::ThrottledWatchReceiver; -use codex_core::file_watcher::WatchPath; -use codex_core::file_watcher::WatchRegistration; -use codex_core::skills::SkillsLoadInput; -use codex_core::skills::SkillsManager; -use codex_protocol::protocol::TurnEnvironmentSelection; -use tracing::warn; - -#[cfg(not(test))] -const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_secs(10); -#[cfg(test)] -const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_millis(50); - -pub(crate) struct SkillsWatcher { - subscriber: FileWatcherSubscriber, -} - -impl SkillsWatcher { - pub(crate) fn new( - skills_manager: Arc, - outgoing: Arc, - ) -> Arc { - let file_watcher = match FileWatcher::new() { - Ok(file_watcher) => Arc::new(file_watcher), - Err(err) => { - warn!("failed to initialize skills file watcher: {err}"); - Arc::new(FileWatcher::noop()) - } - }; - let (subscriber, rx) = file_watcher.add_subscriber(); - Self::spawn_event_loop(rx, skills_manager, outgoing); - Arc::new(Self { subscriber }) - } - - pub(crate) async fn register_thread_config( - &self, - config: &Config, - thread_manager: &ThreadManager, - environments: &[TurnEnvironmentSelection], - ) -> WatchRegistration { - let Some(environment_selection) = environments.first() else { - return WatchRegistration::default(); - }; - let Some(environment) = thread_manager - .environment_manager() - .get_environment(&environment_selection.environment_id) - else { - warn!( - "failed to register skills watcher for unknown environment `{}`", - environment_selection.environment_id - ); - return WatchRegistration::default(); - }; - if environment.is_remote() { - return WatchRegistration::default(); - } - - let plugins_input = config.plugins_config_input(); - let plugins_manager = thread_manager.plugins_manager(); - let plugin_outcome = plugins_manager.plugins_for_config(&plugins_input).await; - let skills_input = SkillsLoadInput::new( - config.cwd.clone(), - plugin_outcome.effective_plugin_skill_roots(), - config.config_layer_stack.clone(), - config.bundled_skills_enabled(), - ); - let roots = thread_manager - .skills_manager() - .skill_roots_for_config(&skills_input, Some(environment.get_filesystem())) - .await - .into_iter() - .map(|root| WatchPath { - path: root.path.into_path_buf(), - recursive: true, - }) - .collect(); - self.subscriber.register_paths(roots) - } - - fn spawn_event_loop( - rx: Receiver, - skills_manager: Arc, - outgoing: Arc, - ) { - let mut rx = ThrottledWatchReceiver::new(rx, WATCHER_THROTTLE_INTERVAL); - let Ok(handle) = tokio::runtime::Handle::try_current() else { - warn!("skills watcher listener skipped: no Tokio runtime available"); - return; - }; - handle.spawn(async move { - while rx.recv().await.is_some() { - skills_manager.clear_cache(); - outgoing - .send_server_notification(ServerNotification::SkillsChanged( - SkillsChangedNotification {}, - )) - .await; - } - }); - } -} diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index 9b26f6ad90..dddbcf483b 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -7,7 +7,6 @@ use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnError; use codex_core::CodexThread; use codex_core::ThreadConfigSnapshot; -use codex_core::file_watcher::WatchRegistration; use codex_protocol::ThreadId; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::RolloutItem; @@ -78,7 +77,6 @@ pub(crate) struct ThreadState { listener_command_tx: Option>, current_turn_history: ThreadHistoryBuilder, listener_thread: Option>, - watch_registration: WatchRegistration, } impl ThreadState { @@ -93,7 +91,6 @@ impl ThreadState { &mut self, cancel_tx: oneshot::Sender<()>, conversation: &Arc, - watch_registration: WatchRegistration, ) -> (mpsc::UnboundedReceiver, u64) { if let Some(previous) = self.cancel_tx.replace(cancel_tx) { let _ = previous.send(()); @@ -102,7 +99,6 @@ impl ThreadState { let (listener_command_tx, listener_command_rx) = mpsc::unbounded_channel(); self.listener_command_tx = Some(listener_command_tx); self.listener_thread = Some(Arc::downgrade(conversation)); - self.watch_registration = watch_registration; (listener_command_rx, self.listener_generation) } @@ -113,7 +109,6 @@ impl ThreadState { self.listener_command_tx = None; self.current_turn_history.reset(); self.listener_thread = None; - self.watch_registration = WatchRegistration::default(); } pub(crate) fn set_experimental_raw_events(&mut self, enabled: bool) { diff --git a/codex-rs/app-server/tests/suite/v2/remote_thread_store.rs b/codex-rs/app-server/tests/suite/v2/remote_thread_store.rs index 9363217864..b04eb12a45 100644 --- a/codex-rs/app-server/tests/suite/v2/remote_thread_store.rs +++ b/codex-rs/app-server/tests/suite/v2/remote_thread_store.rs @@ -42,7 +42,6 @@ use codex_core::config::ConfigBuilder; use codex_exec_server::EnvironmentManager; use codex_feedback::CodexFeedback; use codex_protocol::protocol::SessionSource; -use codex_state::StateRuntime; use codex_thread_store::InMemoryThreadStore; use pretty_assertions::assert_eq; use tempfile::TempDir; @@ -68,13 +67,6 @@ async fn thread_start_with_non_local_thread_store_does_not_create_local_persiste .loader_overrides(loader_overrides.clone()) .build() .await?; - let sqlite_home = TempDir::new()?; - let state_db = StateRuntime::init( - sqlite_home.path().to_path_buf(), - config.model_provider_id.clone(), - ) - .await - .expect("remote thread store regression test should initialize state db"); let thread_store = InMemoryThreadStore::for_id(store_id.clone()); let _in_memory_store = InMemoryThreadStoreId { store_id }; @@ -88,7 +80,7 @@ async fn thread_start_with_non_local_thread_store_does_not_create_local_persiste thread_config_loader: Arc::new(NoopThreadConfigLoader), feedback: CodexFeedback::new(), log_db: None, - state_db: Some(state_db), + state_db: None, environment_manager: Arc::new(EnvironmentManager::default_for_tests()), config_warnings: Vec::new(), session_source: SessionSource::Cli, diff --git a/codex-rs/app-server/tests/suite/v2/skills_list.rs b/codex-rs/app-server/tests/suite/v2/skills_list.rs index 88960ec850..cbfeb32870 100644 --- a/codex-rs/app-server/tests/suite/v2/skills_list.rs +++ b/codex-rs/app-server/tests/suite/v2/skills_list.rs @@ -533,6 +533,44 @@ async fn skills_list_accepts_relative_cwds() -> Result<()> { Ok(()) } +#[tokio::test] +async fn skills_list_preserves_requested_cwd_order() -> Result<()> { + let codex_home = TempDir::new()?; + let first_cwd = TempDir::new()?; + let second_cwd = TempDir::new()?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_skills_list_request(SkillsListParams { + cwds: vec![ + first_cwd.path().to_path_buf(), + second_cwd.path().to_path_buf(), + ], + force_reload: true, + per_cwd_extra_user_roots: None, + }) + .await?; + + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let SkillsListResponse { data } = to_response(response)?; + assert_eq!( + data.iter() + .map(|entry| entry.cwd.clone()) + .collect::>(), + vec![ + first_cwd.path().to_path_buf(), + second_cwd.path().to_path_buf(), + ] + ); + Ok(()) +} + #[tokio::test] async fn skills_list_ignores_per_cwd_extra_roots_for_unknown_cwd() -> Result<()> { let codex_home = TempDir::new()?; @@ -661,27 +699,6 @@ async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<( let mut mcp = McpProcess::new(codex_home.path()).await?; timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - let initial_skills_request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![codex_home.path().to_path_buf()], - force_reload: true, - per_cwd_extra_user_roots: None, - }) - .await?; - let initial_skills_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(initial_skills_request_id)), - ) - .await??; - let SkillsListResponse { data } = to_response(initial_skills_response)?; - assert_eq!(data.len(), 1); - assert!( - data[0] - .skills - .iter() - .any(|skill| { skill.name == "demo" && skill.description == "demo description" }) - ); - let thread_start_request_id = mcp .send_thread_start_request(ThreadStartParams { model: None, @@ -734,25 +751,5 @@ async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<( let notification: SkillsChangedNotification = serde_json::from_value(params)?; assert_eq!(notification, SkillsChangedNotification {}); - let updated_skills_request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![codex_home.path().to_path_buf()], - force_reload: false, - per_cwd_extra_user_roots: None, - }) - .await?; - let updated_skills_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(updated_skills_request_id)), - ) - .await??; - let SkillsListResponse { data } = to_response(updated_skills_response)?; - assert_eq!(data.len(), 1); - assert!( - data[0] - .skills - .iter() - .any(|skill| skill.name == "demo" && skill.description == "updated") - ); Ok(()) } diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index f3545629c1..6a1d08e560 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -1431,7 +1431,7 @@ async fn run_debug_prompt_input_command( }); } - let prompt_input = codex_core::build_prompt_input(config, input).await?; + let prompt_input = codex_core::build_prompt_input(config, input, /*state_db*/ None).await?; println!("{}", serde_json::to_string_pretty(&prompt_input)?); Ok(()) diff --git a/codex-rs/config/src/hook_config.rs b/codex-rs/config/src/hook_config.rs index 27cca781c7..630d18c569 100644 --- a/codex-rs/config/src/hook_config.rs +++ b/codex-rs/config/src/hook_config.rs @@ -37,6 +37,10 @@ pub struct HookEventsToml { pub permission_request: Vec, #[serde(rename = "PostToolUse", default)] pub post_tool_use: Vec, + #[serde(rename = "PreCompact", default)] + pub pre_compact: Vec, + #[serde(rename = "PostCompact", default)] + pub post_compact: Vec, #[serde(rename = "SessionStart", default)] pub session_start: Vec, #[serde(rename = "UserPromptSubmit", default)] @@ -51,6 +55,8 @@ impl HookEventsToml { pre_tool_use, permission_request, post_tool_use, + pre_compact, + post_compact, session_start, user_prompt_submit, stop, @@ -58,6 +64,8 @@ impl HookEventsToml { 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() && user_prompt_submit.is_empty() && stop.is_empty() @@ -68,6 +76,8 @@ impl HookEventsToml { pre_tool_use, permission_request, post_tool_use, + pre_compact, + post_compact, session_start, user_prompt_submit, stop, @@ -76,6 +86,8 @@ impl HookEventsToml { pre_tool_use, permission_request, post_tool_use, + pre_compact, + post_compact, session_start, user_prompt_submit, stop, @@ -86,11 +98,13 @@ impl HookEventsToml { .sum() } - pub fn into_matcher_groups(self) -> [(HookEventName, Vec); 6] { + pub fn into_matcher_groups(self) -> [(HookEventName, Vec); 8] { [ (HookEventName::PreToolUse, self.pre_tool_use), (HookEventName::PermissionRequest, self.permission_request), (HookEventName::PostToolUse, self.post_tool_use), + (HookEventName::PreCompact, self.pre_compact), + (HookEventName::PostCompact, self.post_compact), (HookEventName::SessionStart, self.session_start), (HookEventName::UserPromptSubmit, self.user_prompt_submit), (HookEventName::Stop, self.stop), diff --git a/codex-rs/core-api/src/lib.rs b/codex-rs/core-api/src/lib.rs index 9af459830a..f9bdc9b56b 100644 --- a/codex-rs/core-api/src/lib.rs +++ b/codex-rs/core-api/src/lib.rs @@ -31,7 +31,6 @@ pub use codex_core::StartThreadOptions; pub use codex_core::StateDbHandle; pub use codex_core::ThreadManager; pub use codex_core::ThreadShutdownReport; -pub use codex_core::agent_graph_store_from_state_db; pub use codex_core::config::Config; pub use codex_core::config::Constrained; pub use codex_core::config::GhostSnapshotConfig; @@ -41,7 +40,6 @@ pub use codex_core::config::TerminalResizeReflowConfig; pub use codex_core::config::ThreadStoreConfig; pub use codex_core::config::find_codex_home; pub use codex_core::init_state_db; -pub use codex_core::init_state_db_from_config; pub use codex_core::resolve_installation_id; pub use codex_core::skills::SkillsManager; pub use codex_core::thread_store_from_config; diff --git a/codex-rs/core-plugins/src/lib.rs b/codex-rs/core-plugins/src/lib.rs index 9ff6bc24c5..b724699039 100644 --- a/codex-rs/core-plugins/src/lib.rs +++ b/codex-rs/core-plugins/src/lib.rs @@ -26,6 +26,7 @@ pub const TOOL_SUGGEST_DISCOVERABLE_PLUGIN_ALLOWLIST: &[&str] = &[ "gmail@openai-curated", "google-calendar@openai-curated", "google-drive@openai-curated", + "openai-developers@openai-curated", "canva@openai-curated", "teams@openai-curated", "sharepoint@openai-curated", diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 49ed304623..44c6aacac5 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -26,7 +26,6 @@ bm25 = { workspace = true } chrono = { workspace = true, features = ["serde"] } clap = { workspace = true, features = ["derive"] } codex-analytics = { workspace = true } -codex-agent-graph-store = { workspace = true } codex-api = { workspace = true } codex-app-server-protocol = { workspace = true } codex-apply-patch = { workspace = true } diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index fe3e48a2df..6eab1d4c55 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1033,6 +1033,13 @@ }, "type": "array" }, + "PostCompact": { + "default": [], + "items": { + "$ref": "#/definitions/MatcherGroup" + }, + "type": "array" + }, "PostToolUse": { "default": [], "items": { @@ -1040,6 +1047,13 @@ }, "type": "array" }, + "PreCompact": { + "default": [], + "items": { + "$ref": "#/definitions/MatcherGroup" + }, + "type": "array" + }, "PreToolUse": { "default": [], "items": { diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 8c8114324c..f39c9a1826 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -31,6 +31,7 @@ use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_protocol::user_input::UserInput; +use codex_state::DirectionalThreadSpawnEdgeStatus; use codex_thread_store::ReadThreadParams; use serde::Serialize; use std::collections::HashMap; @@ -310,6 +311,7 @@ impl AgentControl { state.notify_thread_created(new_thread.thread_id); self.persist_thread_spawn_edge_for_source( + new_thread.thread.as_ref(), new_thread.thread_id, notification_source.as_ref(), ) @@ -459,14 +461,19 @@ impl AgentControl { )) .await?; let state = self.upgrade()?; - let agent_graph_store = state.agent_graph_store(); + let Ok(resumed_thread) = state.get_thread(resumed_thread_id).await else { + return Ok(resumed_thread_id); + }; + let Some(state_db_ctx) = resumed_thread.state_db() else { + return Ok(resumed_thread_id); + }; let mut resume_queue = VecDeque::from([(thread_id, root_depth)]); while let Some((parent_thread_id, parent_depth)) = resume_queue.pop_front() { - let child_ids = match agent_graph_store - .list_thread_spawn_children( + let child_ids = match state_db_ctx + .list_thread_spawn_children_with_status( parent_thread_id, - Some(codex_agent_graph_store::ThreadSpawnEdgeStatus::Open), + DirectionalThreadSpawnEdgeStatus::Open, ) .await { @@ -530,6 +537,7 @@ impl AgentControl { let _ = config.features.disable(Feature::Collab); } let state = self.upgrade()?; + let state_db_ctx = state.state_db(); let mut reservation = self.state.reserve_spawn_slot(config.agent_max_threads)?; let (session_source, agent_metadata) = match session_source { SessionSource::SubAgent(SubAgentSource::ThreadSpawn { @@ -539,11 +547,14 @@ impl AgentControl { agent_role: _, agent_nickname: _, }) => { - let state_db_ctx = state.state_db(); let (resumed_agent_nickname, resumed_agent_role) = - match state_db_ctx.get_thread(thread_id).await { - Ok(Some(metadata)) => (metadata.agent_nickname, metadata.agent_role), - Ok(None) | Err(_) => (None, None), + if let Some(state_db_ctx) = state_db_ctx.as_ref() { + match state_db_ctx.get_thread(thread_id).await { + Ok(Some(metadata)) => (metadata.agent_nickname, metadata.agent_role), + Ok(None) | Err(_) => (None, None), + } + } else { + (None, None) }; self.prepare_thread_spawn( &mut reservation, @@ -610,6 +621,7 @@ impl AgentControl { ); } self.persist_thread_spawn_edge_for_source( + resumed_thread.thread.as_ref(), resumed_thread.thread_id, Some(¬ification_source), ) @@ -722,13 +734,11 @@ impl AgentControl { /// agent and any live descendants reached from the in-memory tree. pub(crate) async fn close_agent(&self, agent_id: ThreadId) -> CodexResult { let state = self.upgrade()?; - if let Err(err) = state - .agent_graph_store() - .set_thread_spawn_edge_status( - agent_id, - codex_agent_graph_store::ThreadSpawnEdgeStatus::Closed, - ) - .await + if let Ok(thread) = state.get_thread(agent_id).await + && let Some(state_db_ctx) = thread.state_db() + && let Err(err) = state_db_ctx + .set_thread_spawn_edge_status(agent_id, DirectionalThreadSpawnEdgeStatus::Closed) + .await { warn!("failed to persist thread-spawn edge status for {agent_id}: {err}"); } @@ -1144,21 +1154,21 @@ impl AgentControl { async fn persist_thread_spawn_edge_for_source( &self, + thread: &crate::CodexThread, child_thread_id: ThreadId, session_source: Option<&SessionSource>, ) { let Some(parent_thread_id) = session_source.and_then(thread_spawn_parent_thread_id) else { return; }; - let Ok(state) = self.upgrade() else { + let Some(state_db_ctx) = thread.state_db() else { return; }; - if let Err(err) = state - .agent_graph_store() + if let Err(err) = state_db_ctx .upsert_thread_spawn_edge( parent_thread_id, child_thread_id, - codex_agent_graph_store::ThreadSpawnEdgeStatus::Open, + DirectionalThreadSpawnEdgeStatus::Open, ) .await { diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index a8de427814..b95aad4489 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -1,5 +1,6 @@ use super::*; use crate::CodexThread; +use crate::StateDbHandle; use crate::ThreadManager; use crate::agent::agent_status_from_event; use crate::config::AgentRoleConfig; @@ -7,6 +8,7 @@ use crate::config::Config; use crate::config::ConfigBuilder; use crate::context::ContextualUserFragment; use crate::context::SubagentNotification; +use crate::init_state_db; use assert_matches::assert_matches; use codex_features::Feature; use codex_login::CodexAuth; @@ -84,6 +86,7 @@ fn spawn_agent_call(call_id: &str) -> ResponseItem { struct AgentControlHarness { _home: TempDir, config: Config, + state_db: Option, manager: ThreadManager, control: AgentControl, } @@ -91,17 +94,19 @@ struct AgentControlHarness { impl AgentControlHarness { async fn new() -> Self { let (home, config) = test_config().await; - let manager = ThreadManager::with_models_provider_and_home_for_tests( + let state_db = init_state_db(&config).await; + let manager = ThreadManager::with_models_provider_home_and_state_for_tests( CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.to_path_buf(), std::sync::Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await; + state_db.clone(), + ); let control = manager.agent_control(); Self { _home: home, config, + state_db, manager, control, } @@ -950,8 +955,7 @@ async fn spawn_agent_respects_max_threads_limit() { config.model_provider.clone(), config.codex_home.to_path_buf(), std::sync::Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await; + ); let control = manager.agent_control(); let _ = manager @@ -1003,8 +1007,7 @@ async fn spawn_agent_releases_slot_after_shutdown() { config.model_provider.clone(), config.codex_home.to_path_buf(), std::sync::Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await; + ); let control = manager.agent_control(); let first_agent_id = control @@ -1047,8 +1050,7 @@ async fn spawn_agent_limit_shared_across_clones() { config.model_provider.clone(), config.codex_home.to_path_buf(), std::sync::Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await; + ); let control = manager.agent_control(); let cloned = control.clone(); @@ -1093,8 +1095,7 @@ async fn resume_agent_respects_max_threads_limit() { config.model_provider.clone(), config.codex_home.to_path_buf(), std::sync::Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await; + ); let control = manager.agent_control(); let resumable_id = control @@ -1150,8 +1151,7 @@ async fn resume_agent_releases_slot_after_resume_failure() { config.model_provider.clone(), config.codex_home.to_path_buf(), std::sync::Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await; + ); let control = manager.agent_control(); let _ = control @@ -1543,17 +1543,19 @@ async fn resume_thread_subagent_restores_stored_nickname_and_role() { .features .enable(Feature::Sqlite) .expect("test config should allow sqlite"); - let manager = ThreadManager::with_models_provider_and_home_for_tests( + let state_db = init_state_db(&config).await; + let manager = ThreadManager::with_models_provider_home_and_state_for_tests( CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.to_path_buf(), std::sync::Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await; + state_db.clone(), + ); let control = manager.agent_control(); let harness = AgentControlHarness { _home: home, config, + state_db, manager, control, }; @@ -1704,12 +1706,7 @@ async fn resume_agent_from_rollout_reads_archived_rollout_path() { .expect("child shutdown should succeed"); let store = LocalThreadStore::new( LocalThreadStoreConfig::from_config(&harness.config), - codex_state::StateRuntime::init( - harness.config.sqlite_home.clone(), - harness.config.model_provider_id.clone(), - ) - .await - .expect("state db should initialize"), + harness.state_db.clone(), ); store .archive_thread(ArchiveThreadParams { diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index eb51b9dcbf..a89d8fc973 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -83,6 +83,7 @@ pub(crate) async fn run_codex_thread_interactive( skills_manager: Arc::clone(&parent_session.services.skills_manager), plugins_manager: Arc::clone(&parent_session.services.plugins_manager), mcp_manager: Arc::clone(&parent_session.services.mcp_manager), + skills_watcher: Arc::clone(&parent_session.services.skills_watcher), conversation_history: initial_history.unwrap_or(InitialHistory::New), session_source: SessionSource::SubAgent(subagent_source.clone()), thread_source: Some(ThreadSource::Subagent), @@ -97,7 +98,6 @@ pub(crate) async fn run_codex_thread_interactive( parent_trace: None, environment_selections: parent_ctx.environments.clone(), analytics_events_client: Some(parent_session.services.analytics_events_client.clone()), - state_db: parent_session.services.state_db.clone(), thread_store: Arc::clone(&parent_session.services.thread_store), })) .or_cancel(&cancel_token) diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index b7b992e47c..24a976637b 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -1,5 +1,6 @@ use crate::agent::AgentStatus; use crate::config::ConstraintResult; +use crate::file_watcher::WatchRegistration; use crate::goals::ExternalGoalSet; use crate::goals::GoalRuntimeEvent; use crate::session::Codex; @@ -30,7 +31,6 @@ use codex_protocol::protocol::Submission; use codex_protocol::protocol::ThreadMemoryMode; use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TokenUsageInfo; -use codex_protocol::protocol::TurnEnvironmentSelection; use codex_protocol::protocol::W3cTraceContext; use codex_protocol::user_input::UserInput; use codex_thread_store::StoredThread; @@ -101,6 +101,7 @@ pub struct CodexThread { session_configured: SessionConfiguredEvent, rollout_path: Option, out_of_band_elicitation_count: Mutex, + _watch_registration: WatchRegistration, } /// Conduit for the bidirectional stream of messages that compose a thread @@ -111,6 +112,7 @@ impl CodexThread { session_configured: SessionConfiguredEvent, rollout_path: Option, session_source: SessionSource, + watch_registration: WatchRegistration, ) -> Self { Self { codex, @@ -118,6 +120,7 @@ impl CodexThread { session_configured, rollout_path, out_of_band_elicitation_count: Mutex::new(0), + _watch_registration: watch_registration, } } @@ -461,10 +464,6 @@ impl CodexThread { self.codex.session.get_config().await } - pub async fn environment_selections(&self) -> Vec { - self.codex.thread_environment_selections().await - } - pub async fn read_mcp_resource( &self, server: &str, diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index 38eb19f1ba..9d1c82eb65 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -4,6 +4,10 @@ use std::time::Instant; use crate::Prompt; use crate::client::ModelClientSession; use crate::client_common::ResponseEvent; +use crate::hook_runtime::PostCompactHookOutcome; +use crate::hook_runtime::PreCompactHookOutcome; +use crate::hook_runtime::run_post_compact_hooks; +use crate::hook_runtime::run_pre_compact_hooks; #[cfg(test)] use crate::session::PreviousTurnSettings; use crate::session::session::Session; @@ -110,7 +114,8 @@ pub(crate) async fn run_compact_task( CompactionReason::UserRequested, CompactionPhase::StandaloneTurn, ) - .await + .await?; + Ok(()) } async fn run_compact_task_inner( @@ -131,6 +136,17 @@ async fn run_compact_task_inner( phase, ) .await; + let pre_compact_outcome = run_pre_compact_hooks(&sess, &turn_context, trigger).await; + match pre_compact_outcome { + PreCompactHookOutcome::Continue => {} + PreCompactHookOutcome::Stopped { reason } => { + let error = reason.unwrap_or_else(|| "PreCompact hook stopped execution".to_string()); + attempt + .track(sess.as_ref(), CompactionStatus::Interrupted, Some(error)) + .await; + return Err(CodexErr::TurnAborted); + } + } let result = run_compact_task_inner_impl( Arc::clone(&sess), Arc::clone(&turn_context), @@ -138,14 +154,17 @@ async fn run_compact_task_inner( initial_context_injection, ) .await; - attempt - .track( - sess.as_ref(), - compaction_status_from_result(&result), - result.as_ref().err().map(ToString::to_string), - ) - .await; - result + let status = compaction_status_from_result(&result); + let error = result.as_ref().err().map(ToString::to_string); + if result.is_ok() { + let post_compact_outcome = run_post_compact_hooks(&sess, &turn_context, trigger).await; + if let PostCompactHookOutcome::Stopped = post_compact_outcome { + attempt.track(sess.as_ref(), status, error).await; + return Err(CodexErr::TurnAborted); + } + } + attempt.track(sess.as_ref(), status, error).await; + result.map(|_| ()) } async fn run_compact_task_inner_impl( @@ -153,7 +172,7 @@ async fn run_compact_task_inner_impl( turn_context: Arc, input: Vec, initial_context_injection: InitialContextInjection, -) -> CodexResult<()> { +) -> CodexResult { let compaction_item = TurnItem::ContextCompaction(ContextCompactionItem::new()); sess.emit_turn_item_started(&turn_context, &compaction_item) .await; @@ -272,7 +291,7 @@ async fn run_compact_task_inner_impl( message: "Heads up: Long threads and multiple compactions can cause the model to be less accurate. Start a new thread when possible to keep threads small and targeted.".to_string(), }); sess.send_event(&turn_context, warning).await; - Ok(()) + Ok(summary_suffix) } pub(crate) struct CompactionAnalyticsAttempt { diff --git a/codex-rs/core/src/compact_remote.rs b/codex-rs/core/src/compact_remote.rs index bc0516ce01..eb9e454677 100644 --- a/codex-rs/core/src/compact_remote.rs +++ b/codex-rs/core/src/compact_remote.rs @@ -11,6 +11,10 @@ use crate::context_manager::ContextManager; use crate::context_manager::TotalTokenUsageBreakdown; use crate::context_manager::estimate_response_item_model_visible_bytes; use crate::context_manager::is_codex_generated_item; +use crate::hook_runtime::PostCompactHookOutcome; +use crate::hook_runtime::PreCompactHookOutcome; +use crate::hook_runtime::run_post_compact_hooks; +use crate::hook_runtime::run_pre_compact_hooks; use crate::session::session::Session; use crate::session::turn::built_tools; use crate::session::turn_context::TurnContext; @@ -72,7 +76,8 @@ pub(crate) async fn run_remote_compact_task( CompactionReason::UserRequested, CompactionPhase::StandaloneTurn, ) - .await + .await?; + Ok(()) } async fn run_remote_compact_task_inner( @@ -92,15 +97,33 @@ async fn run_remote_compact_task_inner( phase, ) .await; + let pre_compact_outcome = run_pre_compact_hooks(sess, turn_context, trigger).await; + match pre_compact_outcome { + PreCompactHookOutcome::Continue => {} + PreCompactHookOutcome::Stopped { reason } => { + let error = reason.unwrap_or_else(|| "PreCompact hook stopped execution".to_string()); + attempt + .track( + sess.as_ref(), + codex_analytics::CompactionStatus::Interrupted, + Some(error), + ) + .await; + return Err(CodexErr::TurnAborted); + } + } let result = run_remote_compact_task_inner_impl(sess, turn_context, initial_context_injection).await; - attempt - .track( - sess.as_ref(), - compaction_status_from_result(&result), - result.as_ref().err().map(ToString::to_string), - ) - .await; + let status = compaction_status_from_result(&result); + let error = result.as_ref().err().map(ToString::to_string); + if result.is_ok() { + let post_compact_outcome = run_post_compact_hooks(sess, turn_context, trigger).await; + if let PostCompactHookOutcome::Stopped = post_compact_outcome { + attempt.track(sess.as_ref(), status, error).await; + return Err(CodexErr::TurnAborted); + } + } + attempt.track(sess.as_ref(), status, error.clone()).await; if let Err(err) = result { let event = EventMsg::Error( err.to_error_event(Some("Error running remote compact task".to_string())), diff --git a/codex-rs/core/src/goals.rs b/codex-rs/core/src/goals.rs index 8f15b1b24f..7de2737b32 100644 --- a/codex-rs/core/src/goals.rs +++ b/codex-rs/core/src/goals.rs @@ -30,6 +30,7 @@ use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::validate_thread_goal_objective; use codex_rollout::state_db::reconcile_rollout; +use codex_thread_store::LocalThreadStore; use codex_utils_template::Template; use futures::future::BoxFuture; use std::sync::Arc; @@ -1338,6 +1339,17 @@ impl Session { state_db } else if let Some(state_db) = self.goal_runtime.state_db.lock().await.clone() { state_db + } else if let Some(local_store) = self + .services + .thread_store + .as_any() + .downcast_ref::() + { + local_store.state_db().await.ok_or_else(|| { + anyhow::anyhow!( + "thread goals require a local persisted thread with a state database" + ) + })? } else { anyhow::bail!("thread goals require a local persisted thread with a state database"); }; diff --git a/codex-rs/core/src/hook_runtime.rs b/codex-rs/core/src/hook_runtime.rs index 01d5ce1534..2bea729339 100644 --- a/codex-rs/core/src/hook_runtime.rs +++ b/codex-rs/core/src/hook_runtime.rs @@ -2,6 +2,7 @@ use std::future::Future; use std::sync::Arc; use std::time::Duration; +use codex_analytics::CompactionTrigger; use codex_analytics::HookRunFact; use codex_analytics::build_track_events_context; use codex_hooks::PermissionRequestDecision; @@ -255,6 +256,68 @@ pub(crate) async fn run_post_tool_use_hooks( outcome } +pub(crate) async fn run_pre_compact_hooks( + sess: &Arc, + turn_context: &Arc, + trigger: CompactionTrigger, +) -> PreCompactHookOutcome { + let request = codex_hooks::PreCompactRequest { + session_id: sess.conversation_id, + turn_id: turn_context.sub_id.clone(), + cwd: turn_context.cwd.clone(), + transcript_path: sess.hook_transcript_path().await, + model: turn_context.model_info.slug.clone(), + trigger: compaction_trigger_label(trigger).to_string(), + }; + let preview_runs = sess.hooks().preview_pre_compact(&request); + emit_hook_started_events(sess, turn_context, preview_runs).await; + + let outcome = sess.hooks().run_pre_compact(request).await; + emit_hook_completed_events(sess, turn_context, outcome.hook_events).await; + if outcome.should_stop { + PreCompactHookOutcome::Stopped { + reason: outcome.stop_reason, + } + } else { + PreCompactHookOutcome::Continue + } +} + +pub(crate) enum PreCompactHookOutcome { + Continue, + Stopped { reason: Option }, +} + +pub(crate) enum PostCompactHookOutcome { + Continue, + Stopped, +} + +pub(crate) async fn run_post_compact_hooks( + sess: &Arc, + turn_context: &Arc, + trigger: CompactionTrigger, +) -> PostCompactHookOutcome { + let request = codex_hooks::PostCompactRequest { + session_id: sess.conversation_id, + turn_id: turn_context.sub_id.clone(), + cwd: turn_context.cwd.clone(), + transcript_path: sess.hook_transcript_path().await, + model: turn_context.model_info.slug.clone(), + trigger: compaction_trigger_label(trigger).to_string(), + }; + let preview_runs = sess.hooks().preview_post_compact(&request); + emit_hook_started_events(sess, turn_context, preview_runs).await; + + let outcome = sess.hooks().run_post_compact(request).await; + emit_hook_completed_events(sess, turn_context, outcome.hook_events).await; + if outcome.should_stop { + PostCompactHookOutcome::Stopped + } else { + PostCompactHookOutcome::Continue + } +} + pub(crate) async fn run_user_prompt_submit_hooks( sess: &Arc, turn_context: &Arc, @@ -469,6 +532,8 @@ fn hook_run_metric_tags(run: &HookRunSummary) -> [(&'static str, &'static str); HookEventName::PreToolUse => "PreToolUse", HookEventName::PermissionRequest => "PermissionRequest", HookEventName::PostToolUse => "PostToolUse", + HookEventName::PreCompact => "PreCompact", + HookEventName::PostCompact => "PostCompact", HookEventName::SessionStart => "SessionStart", HookEventName::UserPromptSubmit => "UserPromptSubmit", HookEventName::Stop => "Stop", @@ -511,6 +576,13 @@ fn hook_permission_mode(turn_context: &TurnContext) -> String { .to_string() } +fn compaction_trigger_label(value: CompactionTrigger) -> &'static str { + match value { + CompactionTrigger::Manual => "manual", + CompactionTrigger::Auto => "auto", + } +} + #[cfg(test)] mod tests { use codex_protocol::models::ContentItem; diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 398d44df5c..0cdf0e2d46 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -99,6 +99,7 @@ pub(crate) use skills::manager; pub(crate) use skills::maybe_emit_implicit_skill_invocation; pub(crate) use skills::resolve_skill_dependencies_for_turn; pub(crate) use skills::skills_load_input_from_config; +mod skills_watcher; mod stream_events_utils; pub mod test_support; mod unified_exec; @@ -116,9 +117,7 @@ pub use thread_manager::NewThread; pub use thread_manager::StartThreadOptions; pub use thread_manager::ThreadManager; pub use thread_manager::ThreadShutdownReport; -pub use thread_manager::agent_graph_store_from_state_db; pub use thread_manager::build_models_manager; -pub use thread_manager::init_state_db_from_config; pub use thread_manager::thread_store_from_config; pub use web_search::web_search_action_detail; pub use web_search::web_search_detail; diff --git a/codex-rs/core/src/personality_migration.rs b/codex-rs/core/src/personality_migration.rs index bb1cb43587..975aecd4af 100644 --- a/codex-rs/core/src/personality_migration.rs +++ b/codex-rs/core/src/personality_migration.rs @@ -25,7 +25,7 @@ pub enum PersonalityMigrationStatus { pub async fn maybe_migrate_personality( codex_home: &Path, config_toml: &ConfigToml, - state_db: StateDbHandle, + state_db: Option, ) -> io::Result { let marker_path = codex_home.join(PERSONALITY_MIGRATION_FILENAME); if tokio::fs::try_exists(&marker_path).await? { @@ -65,13 +65,16 @@ pub async fn maybe_migrate_personality( async fn has_recorded_sessions( codex_home: &Path, default_provider: &str, - state_db: StateDbHandle, + state_db: Option, ) -> io::Result { - let config = LocalThreadStoreConfig { - codex_home: codex_home.to_path_buf(), - default_model_provider_id: default_provider.to_string(), - }; - let store = LocalThreadStore::new(config, state_db); + let store = LocalThreadStore::new( + LocalThreadStoreConfig { + codex_home: codex_home.to_path_buf(), + sqlite_home: codex_home.to_path_buf(), + default_model_provider_id: default_provider.to_string(), + }, + state_db, + ); if has_threads(&store, /*archived*/ false).await? { return Ok(true); } diff --git a/codex-rs/core/src/personality_migration_tests.rs b/codex-rs/core/src/personality_migration_tests.rs index 3de22ba1d3..699e06fe67 100644 --- a/codex-rs/core/src/personality_migration_tests.rs +++ b/codex-rs/core/src/personality_migration_tests.rs @@ -8,10 +8,7 @@ use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::UserMessageEvent; use codex_rollout::ARCHIVED_SESSIONS_SUBDIR; -use codex_rollout::RolloutConfig; use codex_rollout::SESSIONS_SUBDIR; -use codex_rollout::state_db::StateDbHandle; -use codex_state::state_db_path; use pretty_assertions::assert_eq; use tempfile::TempDir; use tokio::io::AsyncWriteExt; @@ -23,26 +20,6 @@ async fn read_config_toml(codex_home: &Path) -> io::Result { toml::from_str(&contents).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) } -async fn state_db_for_test(codex_home: &Path) -> io::Result { - state_db_for_test_with_sqlite_home(codex_home, codex_home).await -} - -async fn state_db_for_test_with_sqlite_home( - codex_home: &Path, - sqlite_home: &Path, -) -> io::Result { - let config = RolloutConfig { - codex_home: codex_home.to_path_buf(), - sqlite_home: sqlite_home.to_path_buf(), - cwd: codex_home.to_path_buf(), - model_provider_id: "openai".to_string(), - generate_memories: false, - }; - codex_rollout::state_db::try_init(&config) - .await - .map_err(io::Error::other) -} - async fn write_session_with_user_event(codex_home: &Path) -> io::Result<()> { let thread_id = ThreadId::new(); let dir = codex_home @@ -111,8 +88,7 @@ async fn applies_when_sessions_exist_and_no_personality() -> io::Result<()> { write_session_with_user_event(temp.path()).await?; let config_toml = ConfigToml::default(); - let state_db = state_db_for_test(temp.path()).await?; - let status = maybe_migrate_personality(temp.path(), &config_toml, state_db).await?; + let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::Applied); assert!(temp.path().join(PERSONALITY_MIGRATION_FILENAME).exists()); @@ -128,8 +104,7 @@ async fn applies_when_only_archived_sessions_exist_and_no_personality() -> io::R write_archived_session_with_user_event(temp.path()).await?; let config_toml = ConfigToml::default(); - let state_db = state_db_for_test(temp.path()).await?; - let status = maybe_migrate_personality(temp.path(), &config_toml, state_db).await?; + let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::Applied); assert!(temp.path().join(PERSONALITY_MIGRATION_FILENAME).exists()); @@ -145,8 +120,7 @@ async fn skips_when_marker_exists() -> io::Result<()> { create_marker(&temp.path().join(PERSONALITY_MIGRATION_FILENAME)).await?; let config_toml = ConfigToml::default(); - let state_db = state_db_for_test(temp.path()).await?; - let status = maybe_migrate_personality(temp.path(), &config_toml, state_db).await?; + let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::SkippedMarker); assert!(!temp.path().join("config.toml").exists()); @@ -163,8 +137,7 @@ async fn skips_when_personality_explicit() -> io::Result<()> { .map_err(|err| io::Error::other(format!("failed to write config: {err}")))?; let config_toml = read_config_toml(temp.path()).await?; - let state_db = state_db_for_test(temp.path()).await?; - let status = maybe_migrate_personality(temp.path(), &config_toml, state_db).await?; + let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?; assert_eq!( status, @@ -181,37 +154,10 @@ async fn skips_when_personality_explicit() -> io::Result<()> { async fn skips_when_no_sessions() -> io::Result<()> { let temp = TempDir::new()?; let config_toml = ConfigToml::default(); - let state_db = state_db_for_test(temp.path()).await?; - let status = maybe_migrate_personality(temp.path(), &config_toml, state_db).await?; + let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::SkippedNoSessions); assert!(temp.path().join(PERSONALITY_MIGRATION_FILENAME).exists()); assert!(!temp.path().join("config.toml").exists()); Ok(()) } - -#[tokio::test] -async fn uses_configured_sqlite_home_when_checking_for_sessions() -> io::Result<()> { - let codex_home = TempDir::new()?; - let sqlite_home = TempDir::new()?; - write_session_with_user_event(codex_home.path()).await?; - - let config_toml = ConfigToml::default(); - let state_db = - state_db_for_test_with_sqlite_home(codex_home.path(), sqlite_home.path()).await?; - let status = maybe_migrate_personality(codex_home.path(), &config_toml, state_db).await?; - - assert_eq!(status, PersonalityMigrationStatus::Applied); - assert!( - codex_home - .path() - .join(PERSONALITY_MIGRATION_FILENAME) - .exists() - ); - - let persisted = read_config_toml(codex_home.path()).await?; - assert_eq!(persisted.personality, Some(Personality::Pragmatic)); - assert!(!state_db_path(codex_home.path()).exists()); - assert!(state_db_path(sqlite_home.path()).exists()); - Ok(()) -} diff --git a/codex-rs/core/src/plugins/discoverable_tests.rs b/codex-rs/core/src/plugins/discoverable_tests.rs index 276e822ae9..a481f45822 100644 --- a/codex-rs/core/src/plugins/discoverable_tests.rs +++ b/codex-rs/core/src/plugins/discoverable_tests.rs @@ -19,7 +19,7 @@ use tracing_test::internal::MockWriter; async fn list_tool_suggest_discoverable_plugins_returns_uninstalled_curated_plugins() { let codex_home = tempdir().expect("tempdir should succeed"); let curated_root = curated_plugins_repo_path(codex_home.path()); - write_openai_curated_marketplace(&curated_root, &["sample", "slack"]); + write_openai_curated_marketplace(&curated_root, &["sample", "slack", "openai-developers"]); write_plugins_feature_config(codex_home.path()); let config = load_plugins_config(codex_home.path()).await; @@ -29,16 +29,28 @@ async fn list_tool_suggest_discoverable_plugins_returns_uninstalled_curated_plug assert_eq!( discoverable_plugins, - vec![DiscoverablePluginInfo { - id: "slack@openai-curated".to_string(), - name: "slack".to_string(), - description: Some( - "Plugin that includes skills, MCP servers, and app connectors".to_string(), - ), - has_skills: true, - mcp_server_names: vec!["sample-docs".to_string()], - app_connector_ids: vec!["connector_calendar".to_string()], - }] + vec![ + DiscoverablePluginInfo { + id: "openai-developers@openai-curated".to_string(), + name: "openai-developers".to_string(), + description: Some( + "Plugin that includes skills, MCP servers, and app connectors".to_string(), + ), + has_skills: true, + mcp_server_names: vec!["sample-docs".to_string()], + app_connector_ids: vec!["connector_calendar".to_string()], + }, + DiscoverablePluginInfo { + id: "slack@openai-curated".to_string(), + name: "slack".to_string(), + description: Some( + "Plugin that includes skills, MCP servers, and app connectors".to_string(), + ), + has_skills: true, + mcp_server_names: vec!["sample-docs".to_string()], + app_connector_ids: vec!["connector_calendar".to_string()], + }, + ] ); } diff --git a/codex-rs/core/src/prompt_debug.rs b/codex-rs/core/src/prompt_debug.rs index 1b0c75230c..8717427afe 100644 --- a/codex-rs/core/src/prompt_debug.rs +++ b/codex-rs/core/src/prompt_debug.rs @@ -17,9 +17,8 @@ use crate::resolve_installation_id; use crate::session::session::Session; use crate::session::turn::build_prompt; use crate::session::turn::built_tools; +use crate::state_db_bridge::StateDbHandle; use crate::thread_manager::ThreadManager; -use crate::thread_manager::agent_graph_store_from_state_db; -use crate::thread_manager::init_state_db_from_config; use crate::thread_manager::thread_store_from_config; /// Build the model-visible `input` list for a single debug turn. @@ -27,6 +26,7 @@ use crate::thread_manager::thread_store_from_config; pub async fn build_prompt_input( mut config: Config, input: Vec, + state_db: Option, ) -> CodexResult> { config.ephemeral = true; @@ -38,11 +38,7 @@ pub async fn build_prompt_input( config.codex_linux_sandbox_exe.clone(), )?; - let state_db = init_state_db_from_config(&config) - .await - .ok_or_else(|| std::io::Error::other("prompt debug requires state db"))?; let thread_store = thread_store_from_config(&config, state_db.clone()); - let agent_graph_store = agent_graph_store_from_state_db(state_db.clone()); let installation_id = resolve_installation_id(&config.codex_home).await?; let thread_manager = ThreadManager::new( &config, @@ -50,9 +46,8 @@ pub async fn build_prompt_input( SessionSource::Exec, Arc::new(EnvironmentManager::new(EnvironmentManagerArgs::new(local_runtime_paths)).await), /*analytics_events_client*/ None, - state_db, thread_store, - agent_graph_store, + state_db.clone(), installation_id, ); let thread = thread_manager.start_thread(config).await?; diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 952b9a5711..0910a3f879 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -113,7 +113,6 @@ use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::TurnContextItem; use codex_protocol::protocol::TurnContextNetworkItem; -use codex_protocol::protocol::TurnEnvironmentSelection; use codex_protocol::protocol::W3cTraceContext; use codex_protocol::request_permissions::PermissionGrantScope; use codex_protocol::request_permissions::RequestPermissionProfile; @@ -133,6 +132,7 @@ use codex_terminal_detection::user_agent; use codex_thread_store::CreateThreadParams; use codex_thread_store::LiveThread; use codex_thread_store::LiveThreadInitGuard; +use codex_thread_store::LocalThreadStore; use codex_thread_store::ResumeThreadParams; use codex_thread_store::ThreadEventPersistenceMode; use codex_thread_store::ThreadPersistenceMetadata; @@ -282,6 +282,8 @@ use crate::rollout::map_session_init_error; use crate::session_startup_prewarm::SessionStartupPrewarmHandle; use crate::shell; use crate::shell_snapshot::ShellSnapshot; +use crate::skills_watcher::SkillsWatcher; +use crate::skills_watcher::SkillsWatcherEvent; use crate::state::ActiveTurn; use crate::state::MailboxDeliveryPhase; use crate::state::PendingRequestPermissions; @@ -351,6 +353,7 @@ use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TokenUsageInfo; use codex_protocol::protocol::WarningEvent; use codex_protocol::user_input::UserInput; +use codex_tools::ToolEnvironmentMode; use codex_tools::ToolsConfig; use codex_tools::ToolsConfigParams; use codex_utils_absolute_path::AbsolutePathBuf; @@ -389,6 +392,7 @@ pub(crate) struct CodexSpawnArgs { pub(crate) skills_manager: Arc, pub(crate) plugins_manager: Arc, pub(crate) mcp_manager: Arc, + pub(crate) skills_watcher: Arc, pub(crate) conversation_history: InitialHistory, pub(crate) session_source: SessionSource, pub(crate) thread_source: Option, @@ -407,7 +411,6 @@ pub(crate) struct CodexSpawnArgs { pub(crate) parent_trace: Option, pub(crate) environment_selections: ResolvedTurnEnvironments, pub(crate) analytics_events_client: Option, - pub(crate) state_db: Option, pub(crate) thread_store: Arc, } @@ -452,6 +455,7 @@ impl Codex { skills_manager, plugins_manager, mcp_manager, + skills_watcher, conversation_history, session_source, thread_source, @@ -466,7 +470,6 @@ impl Codex { parent_trace: _, environment_selections, analytics_events_client, - state_db, thread_store, } = args; let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); @@ -555,7 +558,15 @@ impl Codex { }; match thread_id { Some(thread_id) => { - let state_db_ctx = state_db.clone(); + let state_db_ctx = if config.ephemeral { + None + } else if let Some(local_store) = + thread_store.as_any().downcast_ref::() + { + local_store.state_db().await + } else { + None + }; state_db::get_dynamic_tools(state_db_ctx.as_deref(), thread_id, "codex_spawn") .await } @@ -639,10 +650,10 @@ impl Codex { skills_manager, plugins_manager, mcp_manager.clone(), + skills_watcher, agent_control, environment_manager, analytics_events_client, - state_db, thread_store, parent_rollout_thread_trace, ) @@ -773,11 +784,6 @@ impl Codex { state.session_configuration.thread_config_snapshot() } - pub(crate) async fn thread_environment_selections(&self) -> Vec { - let state = self.session.state.lock().await; - state.session_configuration.environments.clone() - } - pub(crate) fn state_db(&self) -> Option { self.session.state_db() } @@ -1002,6 +1008,29 @@ impl Session { self.out_of_band_elicitation_paused.send_replace(paused); } + fn start_skills_watcher_listener(self: &Arc) { + let mut rx = self.services.skills_watcher.subscribe(); + let weak_sess = Arc::downgrade(self); + tokio::spawn(async move { + loop { + match rx.recv().await { + Ok(SkillsWatcherEvent::SkillsChanged { .. }) => { + let Some(sess) = weak_sess.upgrade() else { + break; + }; + let event = Event { + id: sess.next_internal_sub_id(), + msg: EventMsg::SkillsUpdateAvailable, + }; + sess.send_event_raw(event).await; + } + Err(tokio::sync::broadcast::error::RecvError::Closed) => break, + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, + } + } + }); + } + pub(crate) fn get_tx_event(&self) -> Sender { self.tx_event.clone() } @@ -1286,7 +1315,7 @@ impl Session { self.services.user_shell.as_ref().clone(), self.services.shell_snapshot_tx.clone(), self.services.session_telemetry.clone(), - self.state_db(), + self.services.state_db.clone(), ); } diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 1110869ff5..e12f1fdee2 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -364,10 +364,10 @@ impl Session { skills_manager: Arc, plugins_manager: Arc, mcp_manager: Arc, + skills_watcher: Arc, agent_control: AgentControl, environment_manager: Arc, analytics_events_client: Option, - state_db: Option, thread_store: Arc, parent_rollout_thread_trace: ThreadTraceContext, ) -> anyhow::Result> { @@ -467,7 +467,22 @@ impl Session { otel.name = "session_init.thread_persistence", session_init.ephemeral = config.ephemeral, )); - let state_db_ctx = if config.ephemeral { None } else { state_db }; + let state_db_fut = async { + if config.ephemeral { + None + } else if let Some(local_store) = + thread_store.as_any().downcast_ref::() + { + local_store.state_db().await + } else { + None + } + } + .instrument(info_span!( + "session_init.state_db", + otel.name = "session_init.state_db", + session_init.ephemeral = config.ephemeral, + )); let auth_manager_clone = Arc::clone(&auth_manager); let config_for_mcp = Arc::clone(&config); @@ -491,8 +506,8 @@ impl Session { )); // Join all independent futures. - let (thread_persistence_result, (auth, mcp_servers, auth_statuses)) = - tokio::join!(thread_persistence_fut, auth_and_mcp_fut); + let (thread_persistence_result, state_db_ctx, (auth, mcp_servers, auth_statuses)) = + tokio::join!(thread_persistence_fut, state_db_fut, auth_and_mcp_fut); let mut live_thread_init = LiveThreadInitGuard::new(thread_persistence_result.map_err(|e| { @@ -830,6 +845,7 @@ impl Session { skills_manager, plugins_manager: Arc::clone(&plugins_manager), mcp_manager: Arc::clone(&mcp_manager), + skills_watcher, agent_control, network_proxy, network_approval: Arc::clone(&network_approval), @@ -916,6 +932,8 @@ impl Session { sess.send_event_raw(event).await; } + // Start the watcher after SessionConfigured so it cannot emit earlier events. + sess.start_skills_watcher_listener(); let mut required_mcp_servers: Vec = mcp_servers .iter() .filter(|(_, server)| server.enabled && server.required) diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 72ce91c7a9..b250cadfb0 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -915,7 +915,7 @@ async fn danger_full_access_turns_do_not_expose_managed_network_proxy() -> anyho &permission_profile_for_sandbox_policy(&SandboxPolicy::DangerFullAccess), )?; - let (session, _codex_home) = make_session_with_config(move |config| { + let session = make_session_with_config(move |config| { let cwd = config.cwd.clone(); config .permissions @@ -981,7 +981,7 @@ async fn danger_full_access_tool_attempts_do_not_enforce_managed_network() -> an &permission_profile_for_sandbox_policy(&SandboxPolicy::DangerFullAccess), )?; - let (session, _codex_home) = make_session_with_config(move |config| { + let session = make_session_with_config(move |config| { let cwd = config.cwd.clone(); config .permissions @@ -1056,7 +1056,7 @@ async fn workspace_write_turns_continue_to_expose_managed_network_proxy() -> any &permission_profile_for_sandbox_policy(&sandbox_policy), )?; - let (session, _codex_home) = make_session_with_config(move |config| { + let session = make_session_with_config(move |config| { let cwd = config.cwd.clone(); config .permissions @@ -1083,7 +1083,7 @@ async fn user_shell_commands_do_not_inherit_managed_network_proxy() -> anyhow::R &permission_profile_for_sandbox_policy(&sandbox_policy), )?; - let (session, rx, _codex_home) = make_session_with_config_and_rx(move |config| { + let (session, rx) = make_session_with_config_and_rx(move |config| { let cwd = config.cwd.clone(); config .permissions @@ -1213,7 +1213,7 @@ async fn reload_user_config_layer_updates_effective_apps_config() { #[tokio::test] async fn reload_user_config_layer_refreshes_hooks() -> anyhow::Result<()> { - let (session, _codex_home) = make_session_with_config(|config| { + let session = make_session_with_config(|config| { config .features .enable(Feature::CodexHooks) @@ -3052,13 +3052,15 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati fn turn_environments_for_tests( environment: &Arc, cwd: &codex_utils_absolute_path::AbsolutePathBuf, -) -> Vec { - vec![TurnEnvironment { - environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(), - environment: Arc::clone(environment), - cwd: cwd.clone(), - shell: None, - }] +) -> crate::environment_selection::ResolvedTurnEnvironments { + crate::environment_selection::ResolvedTurnEnvironments { + turn_environments: vec![TurnEnvironment { + environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(), + environment: Arc::clone(environment), + cwd: cwd.clone(), + shell: None, + }], + } } #[tokio::test] @@ -3594,18 +3596,13 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() { skills_manager, plugins_manager, mcp_manager, + Arc::new(SkillsWatcher::noop()), AgentControl::default(), Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - /*state_db*/ None, Arc::new(codex_thread_store::LocalThreadStore::new( codex_thread_store::LocalThreadStoreConfig::from_config(config.as_ref()), - codex_state::StateRuntime::init( - config.sqlite_home.clone(), - config.model_provider_id.clone(), - ) - .await - .expect("state db should initialize"), + /*state_db*/ None, )), codex_rollout_trace::ThreadTraceContext::disabled(), ) @@ -3710,6 +3707,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { .expect("create environment"), ); + let skills_watcher = Arc::new(SkillsWatcher::noop()); let services = SessionServices { mcp_connection_manager: Arc::new(RwLock::new(McpConnectionManager::new_uninitialized( &config.permissions.approval_policy, @@ -3745,6 +3743,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { skills_manager, plugins_manager, mcp_manager, + skills_watcher, agent_control, network_proxy: None, network_approval: Arc::clone(&network_approval), @@ -3752,12 +3751,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { live_thread: None, thread_store: Arc::new(codex_thread_store::LocalThreadStore::new( codex_thread_store::LocalThreadStoreConfig::from_config(config.as_ref()), - codex_state::StateRuntime::init( - config.sqlite_home.clone(), - config.model_provider_id.clone(), - ) - .await - .expect("state db should initialize"), + /*state_db*/ None, )), model_client: ModelClient::new( Some(auth_manager.clone()), @@ -3804,7 +3798,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { model_info, &models_manager, /*network*/ None, - crate::environment_selection::ResolvedTurnEnvironments { turn_environments }, + turn_environments, session_configuration.cwd.clone(), "turn_id".to_string(), skills_outcome, @@ -3838,18 +3832,14 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { async fn make_session_with_config( mutator: impl FnOnce(&mut Config), -) -> anyhow::Result<(Arc, tempfile::TempDir)> { - let (session, _rx_event, codex_home) = make_session_with_config_and_rx(mutator).await?; - Ok((session, codex_home)) +) -> anyhow::Result> { + let (session, _rx_event) = make_session_with_config_and_rx(mutator).await?; + Ok(session) } async fn make_session_with_config_and_rx( mutator: impl FnOnce(&mut Config), -) -> anyhow::Result<( - Arc, - async_channel::Receiver, - tempfile::TempDir, -)> { +) -> anyhow::Result<(Arc, async_channel::Receiver)> { let codex_home = tempfile::tempdir().expect("create temp dir"); let mut config = build_test_config(codex_home.path()).await; mutator(&mut config); @@ -3932,24 +3922,19 @@ async fn make_session_with_config_and_rx( skills_manager, plugins_manager, mcp_manager, + Arc::new(SkillsWatcher::noop()), AgentControl::default(), Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - /*state_db*/ None, Arc::new(codex_thread_store::LocalThreadStore::new( codex_thread_store::LocalThreadStoreConfig::from_config(config.as_ref()), - codex_state::StateRuntime::init( - config.sqlite_home.clone(), - config.model_provider_id.clone(), - ) - .await - .expect("state db should initialize"), + /*state_db*/ None, )), codex_rollout_trace::ThreadTraceContext::disabled(), ) .await?; - Ok((session, rx_event, codex_home)) + Ok((session, rx_event)) } async fn make_session_with_history_source_and_agent_control_and_rx( @@ -4039,18 +4024,20 @@ async fn make_session_with_history_source_and_agent_control_and_rx( skills_manager, plugins_manager, mcp_manager, + Arc::new(SkillsWatcher::noop()), agent_control, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - /*state_db*/ None, Arc::new(codex_thread_store::LocalThreadStore::new( codex_thread_store::LocalThreadStoreConfig::from_config(config.as_ref()), - codex_state::StateRuntime::init( - config.sqlite_home.clone(), - config.model_provider_id.clone(), - ) - .await - .expect("state db should initialize"), + Some( + codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.model_provider_id.clone(), + ) + .await + .expect("state db should initialize"), + ), )), codex_rollout_trace::ThreadTraceContext::disabled(), ) @@ -4779,7 +4766,7 @@ async fn default_turn_honors_empty_stored_thread_environments() { let turn_context = session.new_default_turn().await; - assert!(turn_context.environments.primary_environment().is_none()); + assert!(turn_context.environments.primary().is_none()); assert!(turn_context.environments.turn_environments.is_empty()); assert_eq!(turn_context.cwd, session_cwd); assert_eq!(turn_context.config.cwd, session_cwd); @@ -4841,7 +4828,7 @@ async fn empty_turn_environments_clear_primary_environment() { .await .expect("turn should start"); - assert!(turn_context.environments.primary_environment().is_none()); + assert!(turn_context.environments.primary().is_none()); assert!(turn_context.environments.turn_environments.is_empty()); assert_eq!(turn_context.cwd, session.get_config().await.cwd); assert_eq!(turn_context.config.cwd, session.get_config().await.cwd); @@ -5298,13 +5285,47 @@ async fn make_session_and_context_with_auth_and_config_and_rx( Arc, async_channel::Receiver, ) +where + F: FnOnce(&mut Config), +{ + let codex_home = tempfile::tempdir().expect("create temp dir"); + make_session_and_context_with_auth_config_home_and_rx( + auth, + dynamic_tools, + codex_home.path(), + configure_config, + ) + .await +} + +async fn make_session_and_context_with_auth_config_home_and_rx( + auth: CodexAuth, + dynamic_tools: Vec, + codex_home: &Path, + configure_config: F, +) -> ( + Arc, + Arc, + async_channel::Receiver, +) where F: FnOnce(&mut Config), { let (tx_event, rx_event) = async_channel::unbounded(); - let codex_home = tempfile::tempdir().expect("create temp dir").keep(); - let mut config = build_test_config(codex_home.as_path()).await; + let mut config = build_test_config(codex_home).await; configure_config(&mut config); + let state_db = if config.features.enabled(Feature::Goals) { + Some( + codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.model_provider_id.clone(), + ) + .await + .expect("goal tests should initialize sqlite state db"), + ) + } else { + None + }; let config = Arc::new(config); let thread_id = ThreadId::default(); let auth_manager = AuthManager::from_auth_for_testing(auth); @@ -5391,12 +5412,7 @@ where .expect("create environment"), ); - let state_db = codex_state::StateRuntime::init( - config.sqlite_home.clone(), - config.model_provider_id.clone(), - ) - .await - .expect("state db should initialize"); + let skills_watcher = Arc::new(SkillsWatcher::noop()); let services = SessionServices { mcp_connection_manager: Arc::new(RwLock::new(McpConnectionManager::new_uninitialized( &config.permissions.approval_policy, @@ -5432,10 +5448,11 @@ where skills_manager, plugins_manager, mcp_manager, + skills_watcher, agent_control, network_proxy: None, network_approval: Arc::clone(&network_approval), - state_db: Some(state_db.clone()), + state_db: state_db.clone(), live_thread: None, thread_store: Arc::new(codex_thread_store::LocalThreadStore::new( codex_thread_store::LocalThreadStoreConfig::from_config(config.as_ref()), @@ -5486,7 +5503,7 @@ where model_info, &models_manager, /*network*/ None, - crate::environment_selection::ResolvedTurnEnvironments { turn_environments }, + turn_environments, session_configuration.cwd.clone(), "turn_id".to_string(), skills_outcome, @@ -5537,10 +5554,13 @@ async fn make_goal_session_and_context_with_rx() -> ( Arc, Arc, async_channel::Receiver, + tempfile::TempDir, ) { - let (session, turn_context, rx) = make_session_and_context_with_auth_and_config_and_rx( + let codex_home = tempfile::tempdir().expect("create temp dir"); + let (session, turn_context, rx) = make_session_and_context_with_auth_config_home_and_rx( CodexAuth::from_api_key("Test API Key"), Vec::new(), + codex_home.path(), |config| { config .features @@ -5550,14 +5570,14 @@ async fn make_goal_session_and_context_with_rx() -> ( ) .await; upsert_goal_test_thread(session.as_ref()).await; - (session, turn_context, rx) + (session, turn_context, rx, codex_home) } async fn upsert_goal_test_thread(session: &Session) { let config = session.get_config().await; - let state_db = goal_test_state_db(session) - .await - .expect("goal test state db should initialize"); + let state_db = session + .state_db() + .expect("goal test session should have a state db"); let mut builder = codex_state::ThreadMetadataBuilder::new( session.conversation_id, config @@ -7422,7 +7442,7 @@ async fn abort_empty_active_turn_preserves_pending_input() { #[tokio::test] async fn interrupt_accounts_active_goal_before_pausing() -> anyhow::Result<()> { - let (sess, tc, _rx) = make_goal_session_and_context_with_rx().await; + let (sess, tc, _rx, _codex_home) = make_goal_session_and_context_with_rx().await; sess.set_thread_goal( tc.as_ref(), SetGoalRequest { @@ -7686,7 +7706,7 @@ async fn goal_test_state_db(sess: &Session) -> anyhow::Result anyhow::Result<()> { - let (sess, tc, rx) = make_goal_session_and_context_with_rx().await; + let (sess, tc, rx, _codex_home) = make_goal_session_and_context_with_rx().await; sess.set_thread_goal( tc.as_ref(), SetGoalRequest { @@ -7786,7 +7806,7 @@ async fn budget_limited_accounting_steers_active_turn_without_aborting() -> anyh #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn external_goal_mutation_accounts_active_turn_before_status_change() -> anyhow::Result<()> { - let (sess, tc, _rx) = make_goal_session_and_context_with_rx().await; + let (sess, tc, _rx, _codex_home) = make_goal_session_and_context_with_rx().await; sess.set_thread_goal( tc.as_ref(), SetGoalRequest { @@ -7853,7 +7873,7 @@ async fn external_goal_mutation_accounts_active_turn_before_status_change() -> a #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn external_active_goal_set_marks_current_turn_for_accounting() -> anyhow::Result<()> { - let (sess, tc, _rx) = make_goal_session_and_context_with_rx().await; + let (sess, tc, _rx, _codex_home) = make_goal_session_and_context_with_rx().await; sess.spawn_task( Arc::clone(&tc), Vec::new(), @@ -8520,7 +8540,7 @@ async fn sample_rollout( #[tokio::test] async fn create_goal_tool_rejects_existing_goal() { - let (session, turn_context, _rx) = make_goal_session_and_context_with_rx().await; + let (session, turn_context, _rx, _codex_home) = make_goal_session_and_context_with_rx().await; let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())); let handler = CreateGoalHandler; @@ -8582,7 +8602,7 @@ async fn create_goal_tool_rejects_existing_goal() { #[tokio::test] async fn update_goal_tool_rejects_pausing_goal() { - let (session, turn_context, _rx) = make_goal_session_and_context_with_rx().await; + let (session, turn_context, _rx, _codex_home) = make_goal_session_and_context_with_rx().await; let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())); let create_handler = CreateGoalHandler; let update_handler = UpdateGoalHandler; @@ -8643,7 +8663,7 @@ async fn update_goal_tool_rejects_pausing_goal() { #[tokio::test] async fn update_goal_tool_marks_goal_complete() { - let (session, turn_context, _rx) = make_goal_session_and_context_with_rx().await; + let (session, turn_context, _rx, _codex_home) = make_goal_session_and_context_with_rx().await; let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())); let create_handler = CreateGoalHandler; let update_handler = UpdateGoalHandler; diff --git a/codex-rs/core/src/session/tests/guardian_tests.rs b/codex-rs/core/src/session/tests/guardian_tests.rs index af7397dea0..857ec950c2 100644 --- a/codex-rs/core/src/session/tests/guardian_tests.rs +++ b/codex-rs/core/src/session/tests/guardian_tests.rs @@ -728,14 +728,10 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() { /*bundled_skills_enabled*/ true, )); let mcp_manager = Arc::new(McpManager::new(Arc::clone(&plugins_manager))); + let skills_watcher = Arc::new(SkillsWatcher::noop()); let thread_store = Arc::new(codex_thread_store::LocalThreadStore::new( codex_thread_store::LocalThreadStoreConfig::from_config(&config), - codex_state::StateRuntime::init( - config.sqlite_home.clone(), - config.model_provider_id.clone(), - ) - .await - .expect("state db should initialize"), + /*state_db*/ None, )); let CodexSpawnOk { codex, .. } = Codex::spawn(CodexSpawnArgs { @@ -747,6 +743,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() { skills_manager, plugins_manager, mcp_manager, + skills_watcher, conversation_history: InitialHistory::New, session_source: SessionSource::SubAgent(SubAgentSource::Other( GUARDIAN_REVIEWER_NAME.to_string(), @@ -765,7 +762,6 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() { turn_environments: Vec::new(), }, analytics_events_client: None, - state_db: None, thread_store, }) .await diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index 4579a4147a..effbf5372f 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -1511,6 +1511,7 @@ pub(super) fn realtime_text_for_event(msg: &EventMsg) -> Option { | EventMsg::StreamError(_) | EventMsg::TurnDiff(_) | EventMsg::RealtimeConversationListVoicesResponse(_) + | EventMsg::SkillsUpdateAvailable | EventMsg::PlanUpdate(_) | EventMsg::TurnAborted(_) | EventMsg::ShutdownComplete diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index 769953475e..d4fe30063f 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -11,7 +11,6 @@ use codex_protocol::protocol::TurnEnvironmentSelection; use codex_sandboxing::compatibility_sandbox_policy_for_permission_profile; use codex_sandboxing::policy_transforms::effective_file_system_sandbox_policy; use codex_sandboxing::policy_transforms::effective_network_sandbox_policy; -use codex_tools::ToolEnvironmentMode; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; diff --git a/codex-rs/core/src/skills_watcher.rs b/codex-rs/core/src/skills_watcher.rs new file mode 100644 index 0000000000..fb271ca876 --- /dev/null +++ b/codex-rs/core/src/skills_watcher.rs @@ -0,0 +1,125 @@ +//! Skills-specific watcher built on top of the generic [`FileWatcher`]. + +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use tokio::runtime::Handle; +use tokio::sync::broadcast; +use tracing::warn; + +use crate::SkillsManager; +use crate::config::Config; +use crate::file_watcher::FileWatcher; +use crate::file_watcher::FileWatcherSubscriber; +use crate::file_watcher::Receiver; +use crate::file_watcher::ThrottledWatchReceiver; +use crate::file_watcher::WatchPath; +use crate::file_watcher::WatchRegistration; +use crate::skills_load_input_from_config; +use codex_core_plugins::PluginsManager; + +#[cfg(not(test))] +const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_secs(10); +#[cfg(test)] +const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_millis(50); + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SkillsWatcherEvent { + SkillsChanged { paths: Vec }, +} + +pub(crate) struct SkillsWatcher { + subscriber: FileWatcherSubscriber, + tx: broadcast::Sender, +} + +impl SkillsWatcher { + pub(crate) fn new(file_watcher: &Arc) -> Self { + let (subscriber, rx) = file_watcher.add_subscriber(); + let (tx, _) = broadcast::channel(128); + let skills_watcher = Self { + subscriber, + tx: tx.clone(), + }; + Self::spawn_event_loop(rx, tx); + skills_watcher + } + + pub(crate) fn noop() -> Self { + Self::new(&Arc::new(FileWatcher::noop())) + } + + pub(crate) fn subscribe(&self) -> broadcast::Receiver { + self.tx.subscribe() + } + + pub(crate) async fn register_config( + &self, + config: &Config, + skills_manager: &SkillsManager, + plugins_manager: &PluginsManager, + fs: Option>, + ) -> WatchRegistration { + let plugins_input = config.plugins_config_input(); + let plugin_outcome = plugins_manager.plugins_for_config(&plugins_input).await; + let effective_skill_roots = plugin_outcome.effective_plugin_skill_roots(); + let skills_input = skills_load_input_from_config(config, effective_skill_roots); + let roots = skills_manager + .skill_roots_for_config(&skills_input, fs) + .await + .into_iter() + .map(|root| WatchPath { + path: root.path.into_path_buf(), + recursive: true, + }) + .collect(); + self.subscriber.register_paths(roots) + } + + fn spawn_event_loop(rx: Receiver, tx: broadcast::Sender) { + let mut rx = ThrottledWatchReceiver::new(rx, WATCHER_THROTTLE_INTERVAL); + if let Ok(handle) = Handle::try_current() { + handle.spawn(async move { + while let Some(event) = rx.recv().await { + let _ = tx.send(SkillsWatcherEvent::SkillsChanged { paths: event.paths }); + } + }); + } else { + warn!("skills watcher listener skipped: no Tokio runtime available"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use tokio::time::Duration; + use tokio::time::timeout; + + #[tokio::test] + async fn forwards_file_watcher_events() { + let file_watcher = Arc::new(FileWatcher::noop()); + let skills_watcher = SkillsWatcher::new(&file_watcher); + let mut rx = skills_watcher.subscribe(); + let _registration = skills_watcher + .subscriber + .register_path(PathBuf::from("/tmp/skill"), /*recursive*/ true); + + file_watcher + .send_paths_for_test(vec![PathBuf::from("/tmp/skill/SKILL.md")]) + .await; + + let event = timeout(Duration::from_secs(2), rx.recv()) + .await + .expect("skills watcher event") + .expect("broadcast recv"); + assert_eq!( + event, + SkillsWatcherEvent::SkillsChanged { + paths: vec![PathBuf::from("/tmp/skill/SKILL.md")], + } + ); + } +} diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index 64a1810740..9cd9e97fbb 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -9,6 +9,7 @@ use crate::exec_policy::ExecPolicyManager; use crate::guardian::GuardianRejection; use crate::guardian::GuardianRejectionCircuitBreaker; use crate::mcp::McpManager; +use crate::skills_watcher::SkillsWatcher; use crate::tools::code_mode::CodeModeService; use crate::tools::network_approval::NetworkApprovalService; use crate::tools::sandboxing::ApprovalStore; @@ -58,6 +59,7 @@ pub(crate) struct SessionServices { pub(crate) skills_manager: Arc, pub(crate) plugins_manager: Arc, pub(crate) mcp_manager: Arc, + pub(crate) skills_watcher: Arc, pub(crate) agent_control: AgentControl, pub(crate) network_proxy: Option, pub(crate) network_approval: Arc, diff --git a/codex-rs/core/src/stream_events_utils.rs b/codex-rs/core/src/stream_events_utils.rs index fc608aed93..29884da4ae 100644 --- a/codex-rs/core/src/stream_events_utils.rs +++ b/codex-rs/core/src/stream_events_utils.rs @@ -138,8 +138,11 @@ pub(crate) async fn record_completed_response_item( .await; } mark_thread_memory_mode_polluted_if_external_context(sess, turn_context, item).await; - let has_memory_citation = - record_stage1_output_usage_and_detect_memory_citation(sess.state_db(), item).await; + let has_memory_citation = record_stage1_output_usage_and_detect_memory_citation( + sess.services.state_db.as_ref(), + item, + ) + .await; if has_memory_citation { sess.record_memory_citation_for_turn(&turn_context.sub_id) .await; @@ -174,7 +177,7 @@ pub(crate) async fn mark_thread_memory_mode_polluted_if_external_context( } async fn record_stage1_output_usage_and_detect_memory_citation( - state_db_ctx: Option, + state_db_ctx: Option<&state_db::StateDbHandle>, item: &ResponseItem, ) -> bool { let Some(raw_text) = raw_assistant_output_text_from_item(item) else { diff --git a/codex-rs/core/src/test_support.rs b/codex-rs/core/src/test_support.rs index 74305fb518..48eec66c58 100644 --- a/codex-rs/core/src/test_support.rs +++ b/codex-rs/core/src/test_support.rs @@ -52,14 +52,14 @@ pub fn auth_manager_from_auth_with_home(auth: CodexAuth, codex_home: PathBuf) -> AuthManager::from_auth_for_testing_with_home(auth, codex_home) } -pub async fn thread_manager_with_models_provider( +pub fn thread_manager_with_models_provider( auth: CodexAuth, provider: ModelProviderInfo, ) -> ThreadManager { - ThreadManager::with_models_provider_for_tests(auth, provider).await + ThreadManager::with_models_provider_for_tests(auth, provider) } -pub async fn thread_manager_with_models_provider_and_home( +pub fn thread_manager_with_models_provider_and_home( auth: CodexAuth, provider: ModelProviderInfo, codex_home: PathBuf, @@ -71,7 +71,22 @@ pub async fn thread_manager_with_models_provider_and_home( codex_home, environment_manager, ) - .await +} + +pub fn thread_manager_with_models_provider_home_and_state( + auth: CodexAuth, + provider: ModelProviderInfo, + codex_home: PathBuf, + environment_manager: Arc, + state_db: Option, +) -> ThreadManager { + ThreadManager::with_models_provider_home_and_state_for_tests( + auth, + provider, + codex_home, + environment_manager, + state_db, + ) } pub async fn start_thread_with_user_shell_override( diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index b9ee319feb..feda91ce2f 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -5,8 +5,8 @@ use crate::config::Config; use crate::config::ThreadStoreConfig; use crate::environment_selection::default_thread_environment_selections; use crate::environment_selection::resolve_environment_selections; +use crate::file_watcher::FileWatcher; use crate::mcp::McpManager; -use crate::resolve_installation_id; use crate::rollout::RolloutRecorder; use crate::rollout::truncation; use crate::session::Codex; @@ -14,10 +14,10 @@ use crate::session::CodexSpawnArgs; use crate::session::CodexSpawnOk; use crate::session::INITIAL_SUBMIT_ID; use crate::shell_snapshot::ShellSnapshot; +use crate::skills_watcher::SkillsWatcher; +use crate::skills_watcher::SkillsWatcherEvent; use crate::tasks::InterruptedTurnHistoryMarker; use crate::tasks::interrupted_turn_history_marker; -use codex_agent_graph_store::AgentGraphStore; -use codex_agent_graph_store::LocalAgentGraphStore; use codex_analytics::AnalyticsEventsClient; use codex_app_server_protocol::ThreadHistoryBuilder; use codex_app_server_protocol::TurnStatus; @@ -50,8 +50,8 @@ use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::TurnAbortedEvent; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_protocol::protocol::W3cTraceContext; -use codex_rollout::state_db; use codex_rollout::state_db::StateDbHandle; +use codex_state::DirectionalThreadSpawnEdgeStatus; use codex_thread_store::InMemoryThreadStore; use codex_thread_store::LocalThreadStore; use codex_thread_store::LocalThreadStoreConfig; @@ -70,6 +70,8 @@ use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::time::Duration; +use tokio::runtime::Handle; +use tokio::runtime::RuntimeFlavor; use tokio::sync::RwLock; use tokio::sync::broadcast; use tracing::warn; @@ -103,6 +105,47 @@ impl Drop for TempCodexHomeGuard { } } +fn build_skills_watcher(skills_manager: Arc) -> Arc { + if should_use_test_thread_manager_behavior() + && let Ok(handle) = Handle::try_current() + && handle.runtime_flavor() == RuntimeFlavor::CurrentThread + { + // The real watcher spins background tasks that can starve the + // current-thread test runtime and cause event waits to time out. + warn!("using noop skills watcher under current-thread test runtime"); + return Arc::new(SkillsWatcher::noop()); + } + + let file_watcher = match FileWatcher::new() { + Ok(file_watcher) => Arc::new(file_watcher), + Err(err) => { + warn!("failed to initialize file watcher: {err}"); + Arc::new(FileWatcher::noop()) + } + }; + let skills_watcher = Arc::new(SkillsWatcher::new(&file_watcher)); + + let mut rx = skills_watcher.subscribe(); + let skills_manager = Arc::clone(&skills_manager); + if let Ok(handle) = Handle::try_current() { + handle.spawn(async move { + loop { + match rx.recv().await { + Ok(SkillsWatcherEvent::SkillsChanged { .. }) => { + skills_manager.clear_cache(); + } + Err(broadcast::error::RecvError::Closed) => break, + Err(broadcast::error::RecvError::Lagged(_)) => continue, + } + } + }); + } else { + warn!("skills watcher listener skipped: no Tokio runtime available"); + } + + skills_watcher +} + /// Represents a newly created Codex thread (formerly called a conversation), including the first event /// (which is [`EventMsg::SessionConfigured`]). pub struct NewThread { @@ -203,12 +246,12 @@ pub(crate) struct ThreadManagerState { skills_manager: Arc, plugins_manager: Arc, mcp_manager: Arc, + skills_watcher: Arc, thread_store: Arc, - state_db: StateDbHandle, - agent_graph_store: Arc, session_source: SessionSource, installation_id: String, analytics_events_client: Option, + state_db: Option, // Captures submitted ops for testing purpose when test mode is enabled. ops_log: Option, } @@ -224,11 +267,10 @@ pub fn build_models_manager( ) } -pub async fn init_state_db_from_config(config: &Config) -> Option { - state_db::init(config).await -} - -pub fn thread_store_from_config(config: &Config, state_db: StateDbHandle) -> Arc { +pub fn thread_store_from_config( + config: &Config, + state_db: Option, +) -> Arc { match &config.experimental_thread_store { ThreadStoreConfig::Local => Arc::new(LocalThreadStore::new( LocalThreadStoreConfig::from_config(config), @@ -239,27 +281,6 @@ pub fn thread_store_from_config(config: &Config, state_db: StateDbHandle) -> Arc } } -pub fn agent_graph_store_from_state_db(state_db: StateDbHandle) -> Arc { - Arc::new(LocalAgentGraphStore::new(state_db)) -} - -async fn state_db_from_roots_for_tests( - codex_home: PathBuf, - sqlite_home: PathBuf, - default_model_provider_id: String, -) -> StateDbHandle { - let config = codex_rollout::RolloutConfig { - codex_home: codex_home.clone(), - sqlite_home, - cwd: codex_home, - model_provider_id: default_model_provider_id, - generate_memories: false, - }; - state_db::try_init(&config) - .await - .unwrap_or_else(|err| panic!("test state db should initialize: {err}")) -} - impl ThreadManager { #[allow(clippy::too_many_arguments)] pub fn new( @@ -268,9 +289,8 @@ impl ThreadManager { session_source: SessionSource, environment_manager: Arc, analytics_events_client: Option, - state_db: StateDbHandle, thread_store: Arc, - agent_graph_store: Arc, + state_db: Option, installation_id: String, ) -> Self { let codex_home = config.codex_home.clone(); @@ -286,6 +306,7 @@ impl ThreadManager { config.bundled_skills_enabled(), restriction_product, )); + let skills_watcher = build_skills_watcher(Arc::clone(&skills_manager)); Self { state: Arc::new(ThreadManagerState { threads: Arc::new(RwLock::new(HashMap::new())), @@ -295,13 +316,13 @@ impl ThreadManager { skills_manager, plugins_manager, mcp_manager, + skills_watcher, thread_store, - state_db, - agent_graph_store, auth_manager, session_source, installation_id, analytics_events_client, + state_db, ops_log: should_use_test_thread_manager_behavior() .then(|| Arc::new(std::sync::Mutex::new(Vec::new()))), }), @@ -311,7 +332,7 @@ impl ThreadManager { /// Construct with a dummy AuthManager containing the provided CodexAuth. /// Used for integration tests: should not be used by ordinary business logic. - pub(crate) async fn with_models_provider_for_tests( + pub(crate) fn with_models_provider_for_tests( auth: CodexAuth, provider: ModelProviderInfo, ) -> Self { @@ -322,27 +343,11 @@ impl ThreadManager { )); std::fs::create_dir_all(&codex_home) .unwrap_or_else(|err| panic!("temp codex home dir create failed: {err}")); - let state_db = state_db_from_roots_for_tests( - codex_home.clone(), - codex_home.clone(), - OPENAI_PROVIDER_ID.to_string(), - ) - .await; - let skills_codex_home = match AbsolutePathBuf::from_absolute_path_checked(&codex_home) { - Ok(codex_home) => codex_home, - Err(err) => panic!("test codex_home should be absolute: {err}"), - }; - let installation_id = resolve_installation_id(&skills_codex_home) - .await - .unwrap_or_else(|err| panic!("resolve test installation id failed: {err}")); - let mut manager = Self::with_models_provider_and_home_and_state_db_for_tests( + let mut manager = Self::with_models_provider_and_home_for_tests( auth, provider, codex_home.clone(), Arc::new(EnvironmentManager::default_for_tests()), - state_db, - skills_codex_home, - installation_id, ); manager._test_codex_home_guard = Some(TempCodexHomeGuard { path: codex_home }); manager @@ -350,47 +355,35 @@ impl ThreadManager { /// Construct with a dummy AuthManager containing the provided CodexAuth and codex home. /// Used for integration tests: should not be used by ordinary business logic. - pub(crate) async fn with_models_provider_and_home_for_tests( + pub(crate) fn with_models_provider_and_home_for_tests( auth: CodexAuth, provider: ModelProviderInfo, codex_home: PathBuf, environment_manager: Arc, ) -> Self { - let state_db = state_db_from_roots_for_tests( - codex_home.clone(), - codex_home.clone(), - OPENAI_PROVIDER_ID.to_string(), - ) - .await; - let skills_codex_home = match AbsolutePathBuf::from_absolute_path_checked(&codex_home) { - Ok(codex_home) => codex_home, - Err(err) => panic!("test codex_home should be absolute: {err}"), - }; - let installation_id = resolve_installation_id(&skills_codex_home) - .await - .unwrap_or_else(|err| panic!("resolve test installation id failed: {err}")); - Self::with_models_provider_and_home_and_state_db_for_tests( + Self::with_models_provider_home_and_state_for_tests( auth, provider, codex_home, environment_manager, - state_db, - skills_codex_home, - installation_id, + /*state_db*/ None, ) } - fn with_models_provider_and_home_and_state_db_for_tests( + pub(crate) fn with_models_provider_home_and_state_for_tests( auth: CodexAuth, provider: ModelProviderInfo, codex_home: PathBuf, environment_manager: Arc, - state_db: StateDbHandle, - skills_codex_home: AbsolutePathBuf, - installation_id: String, + state_db: Option, ) -> Self { set_thread_manager_test_mode_for_tests(/*enabled*/ true); let auth_manager = AuthManager::from_auth_for_testing(auth); + let installation_id = uuid::Uuid::new_v4().to_string(); + let skills_codex_home = match AbsolutePathBuf::from_absolute_path_checked(&codex_home) { + Ok(codex_home) => codex_home, + Err(err) => panic!("test codex_home should be absolute: {err}"), + }; let (thread_created_tx, _) = broadcast::channel(THREAD_CREATED_CHANNEL_CAPACITY); let restriction_product = SessionSource::Exec.restriction_product(); let plugins_manager = Arc::new(PluginsManager::new_with_restriction_product( @@ -403,16 +396,17 @@ impl ThreadManager { /*bundled_skills_enabled*/ true, restriction_product, )); + let skills_watcher = build_skills_watcher(Arc::clone(&skills_manager)); // This test constructor has no Config input. Tests that need a non-local // process store should construct ThreadManager::new with an explicit store. let thread_store: Arc = Arc::new(LocalThreadStore::new( LocalThreadStoreConfig { codex_home: codex_home.clone(), + sqlite_home: codex_home.clone(), default_model_provider_id: OPENAI_PROVIDER_ID.to_string(), }, state_db.clone(), )); - let agent_graph_store = agent_graph_store_from_state_db(state_db.clone()); Self { state: Arc::new(ThreadManagerState { threads: Arc::new(RwLock::new(HashMap::new())), @@ -423,13 +417,13 @@ impl ThreadManager { skills_manager, plugins_manager, mcp_manager, + skills_watcher, thread_store, - state_db, - agent_graph_store, auth_manager, session_source: SessionSource::Exec, installation_id, analytics_events_client: None, + state_db, ops_log: should_use_test_thread_manager_behavior() .then(|| Arc::new(std::sync::Mutex::new(Vec::new()))), }), @@ -515,17 +509,22 @@ impl ThreadManager { subtree_thread_ids.push(thread_id); seen_thread_ids.insert(thread_id); - for descendant_id in self - .state - .agent_graph_store - .list_thread_spawn_descendants(thread_id, /*status_filter*/ None) - .await - .map_err(|err| { - CodexErr::Fatal(format!("failed to load thread-spawn descendants: {err}")) - })? - { - if seen_thread_ids.insert(descendant_id) { - subtree_thread_ids.push(descendant_id); + if let Some(state_db_ctx) = thread.state_db() { + for status in [ + DirectionalThreadSpawnEdgeStatus::Open, + DirectionalThreadSpawnEdgeStatus::Closed, + ] { + for descendant_id in state_db_ctx + .list_thread_spawn_descendants_with_status(thread_id, status) + .await + .map_err(|err| { + CodexErr::Fatal(format!("failed to load thread-spawn descendants: {err}")) + })? + { + if seen_thread_ids.insert(descendant_id) { + subtree_thread_ids.push(descendant_id); + } + } } } @@ -867,14 +866,10 @@ impl ThreadManager { } impl ThreadManagerState { - pub(crate) fn state_db(&self) -> StateDbHandle { + pub(crate) fn state_db(&self) -> Option { self.state_db.clone() } - pub(crate) fn agent_graph_store(&self) -> Arc { - self.agent_graph_store.clone() - } - pub(crate) async fn list_thread_ids(&self) -> Vec { self.threads .read() @@ -1148,6 +1143,19 @@ impl ThreadManagerState { } let environment_selections = resolve_environment_selections(self.environment_manager.as_ref(), &environments)?; + let watch_registration = match environment_selections.primary() { + Some(turn_environment) if !turn_environment.environment.is_remote() => { + self.skills_watcher + .register_config( + &config, + self.skills_manager.as_ref(), + self.plugins_manager.as_ref(), + Some(turn_environment.environment.get_filesystem()), + ) + .await + } + Some(_) | None => crate::file_watcher::WatchRegistration::default(), + }; let parent_rollout_thread_trace = self .parent_rollout_thread_trace_for_source(&session_source, &initial_history) .await; @@ -1163,6 +1171,7 @@ impl ThreadManagerState { skills_manager: Arc::clone(&self.skills_manager), plugins_manager: Arc::clone(&self.plugins_manager), mcp_manager: Arc::clone(&self.mcp_manager), + skills_watcher: Arc::clone(&self.skills_watcher), conversation_history: initial_history, session_source, thread_source, @@ -1177,12 +1186,11 @@ impl ThreadManagerState { parent_trace, environment_selections, analytics_events_client: self.analytics_events_client.clone(), - state_db: Some(self.state_db.clone()), thread_store: Arc::clone(&self.thread_store), }) .await?; let new_thread = self - .finalize_thread_spawn(codex, thread_id, tracked_session_source) + .finalize_thread_spawn(codex, thread_id, tracked_session_source, watch_registration) .await?; if is_resumed_thread && let Err(err) = new_thread.thread.apply_goal_resume_runtime_effects().await @@ -1197,6 +1205,7 @@ impl ThreadManagerState { codex: Codex, thread_id: ThreadId, session_source: SessionSource, + watch_registration: crate::file_watcher::WatchRegistration, ) -> CodexResult { let event = codex.next_event().await?; let session_configured = match event { @@ -1217,6 +1226,7 @@ impl ThreadManagerState { session_configured.clone(), session_configured.rollout_path.clone(), session_source, + watch_registration, )); e.insert(thread.clone()); return Ok(NewThread { diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs index 0f6afa05a6..17ac81a93b 100644 --- a/codex-rs/core/src/thread_manager_tests.rs +++ b/codex-rs/core/src/thread_manager_tests.rs @@ -1,5 +1,6 @@ use super::*; use crate::config::test_config; +use crate::init_state_db; use crate::installation_id::INSTALLATION_ID_FILENAME; use crate::rollout::RolloutRecorder; use crate::session::session::SessionSettingsUpdate; @@ -50,21 +51,6 @@ fn assistant_msg(text: &str) -> ResponseItem { } } -async fn state_backed_stores( - config: &Config, -) -> ( - StateDbHandle, - Arc, - Arc, -) { - let state_db = init_state_db_from_config(config) - .await - .expect("thread manager test requires state db"); - let thread_store = thread_store_from_config(config, state_db.clone()); - let agent_graph_store = agent_graph_store_from_state_db(state_db.clone()); - (state_db, thread_store, agent_graph_store) -} - fn contextual_user_interrupted_marker() -> ResponseItem { interrupted_turn_history_marker(InterruptedTurnHistoryMarker::ContextualUser) .expect("contextual-user interrupted marker should be enabled") @@ -280,8 +266,7 @@ async fn shutdown_all_threads_bounded_submits_shutdown_to_every_thread() { config.model_provider.clone(), config.codex_home.to_path_buf(), Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await; + ); let thread_1 = manager .start_thread(config.clone()) .await @@ -330,8 +315,7 @@ async fn start_thread_accepts_explicit_environment_when_default_environment_is_d config.model_provider.clone(), config.codex_home.to_path_buf(), environment_manager, - ) - .await; + ); let thread = manager .start_thread_with_options(StartThreadOptions { @@ -367,8 +351,7 @@ async fn start_thread_keeps_internal_threads_hidden_from_normal_lookups() { config.model_provider.clone(), config.codex_home.to_path_buf(), Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ) - .await; + ); let thread = manager .start_thread_with_options(StartThreadOptions { config, @@ -408,16 +391,14 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() { let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let (state_db, thread_store, agent_graph_store) = state_backed_stores(&config).await; let manager = ThreadManager::new( &config, auth_manager.clone(), SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, + thread_store_from_config(&config, /*state_db*/ None), + /*state_db*/ None, TEST_INSTALLATION_ID.to_string(), ); let selected_cwd = @@ -524,16 +505,16 @@ async fn explicit_installation_id_skips_codex_home_file() { let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); let installation_id = uuid::Uuid::new_v4().to_string(); - let (state_db, thread_store, agent_graph_store) = state_backed_stores(&config).await; + let state_db = init_state_db(&config).await; + let thread_store = thread_store_from_config(&config, state_db.clone()); let manager = ThreadManager::new( &config, auth_manager, SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, thread_store, - agent_graph_store, + state_db.clone(), installation_id.clone(), ); @@ -563,16 +544,14 @@ async fn resume_active_thread_from_rollout_returns_running_thread() { let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let (state_db, thread_store, agent_graph_store) = state_backed_stores(&config).await; let manager = ThreadManager::new( &config, auth_manager.clone(), SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, + thread_store_from_config(&config, /*state_db*/ None), + /*state_db*/ None, TEST_INSTALLATION_ID.to_string(), ); @@ -620,16 +599,14 @@ async fn resume_stopped_thread_from_rollout_spawns_new_thread() { let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let (state_db, thread_store, agent_graph_store) = state_backed_stores(&config).await; let manager = ThreadManager::new( &config, auth_manager.clone(), SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, + thread_store_from_config(&config, /*state_db*/ None), + /*state_db*/ None, TEST_INSTALLATION_ID.to_string(), ); @@ -682,16 +659,16 @@ async fn resume_stopped_thread_from_rollout_preserves_thread_source() { let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let (state_db, thread_store, agent_graph_store) = state_backed_stores(&config).await; + let state_db = init_state_db(&config).await; + let thread_store = thread_store_from_config(&config, state_db.clone()); let manager = ThreadManager::new( &config, auth_manager.clone(), SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, thread_store, - agent_graph_store, + state_db.clone(), TEST_INSTALLATION_ID.to_string(), ); @@ -768,16 +745,14 @@ async fn new_uses_active_provider_for_model_refresh() { let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let (state_db, thread_store, agent_graph_store) = state_backed_stores(&config).await; let manager = ThreadManager::new( &config, auth_manager, SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, + thread_store_from_config(&config, /*state_db*/ None), + /*state_db*/ None, TEST_INSTALLATION_ID.to_string(), ); @@ -983,16 +958,15 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let (state_db, thread_store, agent_graph_store) = state_backed_stores(&config).await; + let state_db = init_state_db(&config).await; let manager = ThreadManager::new( &config, auth_manager.clone(), SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, + thread_store_from_config(&config, state_db.clone()), + state_db.clone(), TEST_INSTALLATION_ID.to_string(), ); @@ -1090,16 +1064,15 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() { let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let (state_db, thread_store, agent_graph_store) = state_backed_stores(&config).await; + let state_db = init_state_db(&config).await; let manager = ThreadManager::new( &config, auth_manager.clone(), SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, + thread_store_from_config(&config, state_db.clone()), + state_db.clone(), TEST_INSTALLATION_ID.to_string(), ); @@ -1186,16 +1159,15 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_ let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let (state_db, thread_store, agent_graph_store) = state_backed_stores(&config).await; + let state_db = init_state_db(&config).await; let manager = ThreadManager::new( &config, auth_manager.clone(), SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, + thread_store_from_config(&config, state_db.clone()), + state_db.clone(), TEST_INSTALLATION_ID.to_string(), ); @@ -1328,16 +1300,15 @@ async fn resumed_thread_keeps_paused_goal_paused() -> anyhow::Result<()> { let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let (state_db, thread_store, agent_graph_store) = state_backed_stores(&config).await; + let state_db = init_state_db(&config).await; let manager = ThreadManager::new( &config, auth_manager.clone(), SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, + thread_store_from_config(&config, state_db.clone()), + state_db.clone(), TEST_INSTALLATION_ID.to_string(), ); @@ -1407,11 +1378,6 @@ async fn resumed_thread_keeps_paused_goal_paused() -> anyhow::Result<()> { .await .is_none() ); - let goal = state_db - .get_thread_goal(resumed.thread_id) - .await? - .expect("goal should still exist after resume"); - assert_eq!(codex_state::ThreadGoalStatus::Paused, goal.status); resumed.thread.shutdown_and_wait().await?; Ok(()) diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index b678f3ffe8..6f44673f13 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -6,7 +6,6 @@ use crate::function_tool::FunctionCallError; use crate::init_state_db; use crate::session::tests::make_session_and_context; use crate::session_prefix::format_subagent_notification_message; -use crate::thread_manager::agent_graph_store_from_state_db; use crate::thread_manager::thread_store_from_config; use crate::tools::context::ToolOutput; use crate::tools::handlers::multi_agents_v2::CloseAgentHandler as CloseAgentHandlerV2; @@ -91,12 +90,11 @@ fn parse_agent_id(id: &str) -> ThreadId { ThreadId::from_string(id).expect("agent id should be valid") } -async fn thread_manager() -> ThreadManager { +fn thread_manager() -> ThreadManager { ThreadManager::with_models_provider_for_tests( CodexAuth::from_api_key("dummy"), built_in_model_providers(/* openai_base_url */ /*openai_base_url*/ None)["openai"].clone(), ) - .await } async fn install_role_with_model_override(turn: &mut TurnContext) -> String { @@ -243,7 +241,7 @@ async fn spawn_agent_uses_explorer_role_and_preserves_approval_policy() { } let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let mut config = (*turn.config).clone(); let provider_info = @@ -298,7 +296,7 @@ async fn spawn_agent_uses_explorer_role_and_preserves_approval_policy() { async fn spawn_agent_fork_context_rejects_agent_type_override() { let (mut session, mut turn) = make_session_and_context().await; let role_name = install_role_with_model_override(&mut turn).await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -330,7 +328,7 @@ async fn spawn_agent_fork_context_rejects_agent_type_override() { #[tokio::test] async fn spawn_agent_fork_context_rejects_child_model_overrides() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -365,7 +363,7 @@ async fn spawn_agent_fork_context_rejects_child_model_overrides() { async fn multi_agent_v2_spawn_fork_turns_all_rejects_agent_type_override() { let (mut session, mut turn) = make_session_and_context().await; let role_name = install_role_with_model_override(&mut turn).await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -408,7 +406,7 @@ async fn multi_agent_v2_spawn_fork_turns_all_rejects_agent_type_override() { #[tokio::test] async fn multi_agent_v2_spawn_defaults_to_full_fork_and_rejects_child_model_overrides() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -449,7 +447,7 @@ async fn multi_agent_v2_spawn_defaults_to_full_fork_and_rejects_child_model_over async fn multi_agent_v2_spawn_partial_fork_turns_allows_agent_type_override() { let (mut session, mut turn) = make_session_and_context().await; let role_name = install_role_with_model_override(&mut turn).await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -505,7 +503,7 @@ async fn multi_agent_v2_spawn_partial_fork_turns_allows_agent_type_override() { #[tokio::test] async fn spawn_agent_returns_agent_id_without_task_name() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let output = SpawnAgentHandler @@ -532,7 +530,7 @@ async fn spawn_agent_returns_agent_id_without_task_name() { #[tokio::test] async fn multi_agent_v2_spawn_requires_task_name() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -566,7 +564,7 @@ async fn multi_agent_v2_spawn_requires_task_name() { #[tokio::test] async fn multi_agent_v2_spawn_rejects_legacy_items_field() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -626,7 +624,7 @@ async fn multi_agent_v2_spawn_returns_path_and_send_message_accepts_relative_pat } let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -723,7 +721,7 @@ async fn multi_agent_v2_spawn_returns_path_and_send_message_accepts_relative_pat #[tokio::test] async fn multi_agent_v2_spawn_rejects_legacy_fork_context() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -762,7 +760,7 @@ async fn multi_agent_v2_spawn_rejects_legacy_fork_context() { #[tokio::test] async fn multi_agent_v2_spawn_rejects_invalid_fork_turns_string() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -801,7 +799,7 @@ async fn multi_agent_v2_spawn_rejects_invalid_fork_turns_string() { #[tokio::test] async fn multi_agent_v2_spawn_rejects_zero_fork_turns() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -840,7 +838,7 @@ async fn multi_agent_v2_spawn_rejects_zero_fork_turns() { #[tokio::test] async fn multi_agent_v2_send_message_accepts_root_target_from_child() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -916,7 +914,7 @@ async fn multi_agent_v2_send_message_accepts_root_target_from_child() { #[tokio::test] async fn multi_agent_v2_followup_task_rejects_root_target_from_child() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -997,7 +995,7 @@ async fn multi_agent_v2_followup_task_rejects_root_target_from_child() { #[tokio::test] async fn multi_agent_v2_list_agents_returns_completed_status_and_last_task_message() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -1091,7 +1089,7 @@ async fn multi_agent_v2_list_agents_returns_completed_status_and_last_task_messa #[tokio::test] async fn multi_agent_v2_list_agents_filters_by_relative_path_prefix() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -1178,7 +1176,7 @@ async fn multi_agent_v2_list_agents_filters_by_relative_path_prefix() { #[tokio::test] async fn multi_agent_v2_list_agents_omits_closed_agents() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -1242,7 +1240,7 @@ async fn multi_agent_v2_list_agents_omits_closed_agents() { #[tokio::test] async fn multi_agent_v2_send_message_rejects_legacy_items_field() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -1298,7 +1296,7 @@ async fn multi_agent_v2_send_message_rejects_legacy_items_field() { #[tokio::test] async fn multi_agent_v2_send_message_rejects_interrupt_parameter() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -1371,7 +1369,7 @@ async fn multi_agent_v2_send_message_rejects_interrupt_parameter() { #[tokio::test] async fn multi_agent_v2_followup_task_completion_notifies_parent_on_every_turn() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -1506,7 +1504,7 @@ async fn multi_agent_v2_followup_task_completion_notifies_parent_on_every_turn() #[tokio::test] async fn multi_agent_v2_followup_task_rejects_legacy_items_field() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -1559,7 +1557,7 @@ async fn multi_agent_v2_followup_task_rejects_legacy_items_field() { #[tokio::test] async fn multi_agent_v2_interrupted_turn_does_not_notify_parent() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -1636,7 +1634,7 @@ async fn multi_agent_v2_interrupted_turn_does_not_notify_parent() { #[tokio::test] async fn multi_agent_v2_spawn_omits_agent_id_when_named() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -1675,7 +1673,7 @@ async fn multi_agent_v2_spawn_omits_agent_id_when_named() { #[tokio::test] async fn multi_agent_v2_spawn_surfaces_task_name_validation_errors() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -1718,7 +1716,7 @@ async fn spawn_agent_reapplies_runtime_sandbox_after_role_config() { } let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let expected_sandbox = turn.config.legacy_sandbox_policy(); let mut expected_file_system_sandbox_policy = @@ -1799,7 +1797,7 @@ async fn spawn_agent_reapplies_runtime_sandbox_after_role_config() { #[tokio::test] async fn spawn_agent_rejects_when_depth_limit_exceeded() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let max_depth = turn.config.agent_max_depth; @@ -1837,7 +1835,7 @@ async fn spawn_agent_allows_depth_up_to_configured_max_depth() { } let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let mut config = (*turn.config).clone(); @@ -1883,7 +1881,7 @@ async fn multi_agent_v2_spawn_agent_ignores_configured_max_depth() { } let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let mut config = (*turn.config).clone(); config.agent_max_depth = 1; config @@ -1991,7 +1989,7 @@ async fn send_input_rejects_invalid_id() { #[tokio::test] async fn send_input_reports_missing_agent() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let agent_id = ThreadId::new(); let invocation = invocation( @@ -2012,7 +2010,7 @@ async fn send_input_reports_missing_agent() { #[tokio::test] async fn send_input_interrupts_before_prompt() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let config = turn.config.as_ref().clone(); let thread = manager @@ -2054,7 +2052,7 @@ async fn send_input_interrupts_before_prompt() { #[tokio::test] async fn send_input_accepts_structured_items() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let config = turn.config.as_ref().clone(); let thread = manager @@ -2128,7 +2126,7 @@ async fn resume_agent_rejects_invalid_id() { #[tokio::test] async fn resume_agent_reports_missing_agent() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let agent_id = ThreadId::new(); let invocation = invocation( @@ -2149,7 +2147,7 @@ async fn resume_agent_reports_missing_agent() { #[tokio::test] async fn resume_agent_noops_for_active_agent() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let config = turn.config.as_ref().clone(); let thread = manager @@ -2188,7 +2186,7 @@ async fn resume_agent_noops_for_active_agent() { #[tokio::test] async fn resume_agent_restores_closed_agent_and_accepts_send_input() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let config = turn.config.as_ref().clone(); let thread = manager @@ -2267,7 +2265,7 @@ async fn resume_agent_restores_closed_agent_and_accepts_send_input() { #[tokio::test] async fn resume_agent_rejects_when_depth_limit_exceeded() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let max_depth = turn.config.agent_max_depth; @@ -2356,7 +2354,7 @@ async fn wait_agent_rejects_empty_targets() { #[tokio::test] async fn multi_agent_v2_wait_agent_accepts_timeout_only_argument() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -2495,7 +2493,7 @@ async fn multi_agent_v2_wait_agent_uses_configured_min_timeout() { #[tokio::test] async fn wait_agent_returns_not_found_for_missing_agents() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let id_a = ThreadId::new(); let id_b = ThreadId::new(); @@ -2531,7 +2529,7 @@ async fn wait_agent_returns_not_found_for_missing_agents() { #[tokio::test] async fn wait_agent_times_out_when_status_is_not_final() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let config = turn.config.as_ref().clone(); let thread = manager @@ -2574,7 +2572,7 @@ async fn wait_agent_times_out_when_status_is_not_final() { #[tokio::test] async fn wait_agent_clamps_short_timeouts_to_minimum() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let config = turn.config.as_ref().clone(); let thread = manager @@ -2612,7 +2610,7 @@ async fn wait_agent_clamps_short_timeouts_to_minimum() { #[tokio::test] async fn wait_agent_returns_final_status_without_timeout() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let config = turn.config.as_ref().clone(); let thread = manager @@ -2664,7 +2662,7 @@ async fn wait_agent_returns_final_status_without_timeout() { #[tokio::test] async fn multi_agent_v2_wait_agent_returns_summary_for_mailbox_activity() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -2755,7 +2753,7 @@ async fn multi_agent_v2_wait_agent_returns_summary_for_mailbox_activity() { #[tokio::test] async fn multi_agent_v2_wait_agent_returns_for_already_queued_mail() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -2833,7 +2831,7 @@ async fn multi_agent_v2_wait_agent_returns_for_already_queued_mail() { #[tokio::test] async fn multi_agent_v2_wait_agent_wakes_on_any_mailbox_notification() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -2921,7 +2919,7 @@ async fn multi_agent_v2_wait_agent_wakes_on_any_mailbox_notification() { #[tokio::test] async fn multi_agent_v2_wait_agent_does_not_return_completed_content() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -3007,7 +3005,7 @@ async fn multi_agent_v2_wait_agent_does_not_return_completed_content() { #[tokio::test] async fn multi_agent_v2_close_agent_accepts_task_name_target() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -3066,7 +3064,7 @@ async fn multi_agent_v2_close_agent_accepts_task_name_target() { #[tokio::test] async fn multi_agent_v2_close_agent_rejects_root_target_and_id() { let (mut session, mut turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); let root = manager .start_thread((*turn.config).clone()) .await @@ -3114,7 +3112,7 @@ async fn multi_agent_v2_close_agent_rejects_root_target_and_id() { #[tokio::test] async fn close_agent_submits_shutdown_and_returns_previous_status() { let (mut session, turn) = make_session_and_context().await; - let manager = thread_manager().await; + let manager = thread_manager(); session.services.agent_control = manager.agent_control(); let config = turn.config.as_ref().clone(); let thread = manager @@ -3159,18 +3157,15 @@ async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtr .features .enable(Feature::Sqlite) .expect("test config should allow sqlite"); - let state_db = init_state_db(&config) - .await - .expect("test config should initialize state db"); + let state_db = init_state_db(&config).await; let manager = ThreadManager::new( &config, AuthManager::from_auth_for_testing(CodexAuth::from_api_key("dummy")), SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db.clone(), thread_store_from_config(&config, state_db.clone()), - agent_graph_store_from_state_db(state_db.clone()), + state_db.clone(), "11111111-1111-4111-8111-111111111111".to_string(), ); diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index bdf18cf2fe..98e8e227aa 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -522,10 +522,6 @@ impl ToolRegistryBuilder { } } - pub fn push_spec(&mut self, spec: ToolSpec) { - self.push_spec_with_parallel_support(spec, /*supports_parallel_tool_calls*/ false); - } - pub fn push_spec_with_parallel_support( &mut self, spec: ToolSpec, @@ -535,6 +531,20 @@ impl ToolRegistryBuilder { .push(ConfiguredToolSpec::new(spec, supports_parallel_tool_calls)); } + pub(crate) fn push_spec( + &mut self, + spec: ToolSpec, + supports_parallel_tool_calls: bool, + code_mode_enabled: bool, + ) { + let spec = if code_mode_enabled { + codex_tools::augment_tool_spec_for_code_mode(spec) + } else { + spec + }; + self.push_spec_with_parallel_support(spec, supports_parallel_tool_calls); + } + pub fn register_handler(&mut self, handler: Arc) where H: ToolHandler + 'static, @@ -547,6 +557,10 @@ impl ToolRegistryBuilder { } } + pub(crate) fn specs(&self) -> &[ConfiguredToolSpec] { + &self.specs + } + pub fn build(self) -> (Vec, ToolRegistry) { let registry = ToolRegistry::new(self.handlers); (self.specs, registry) diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index b13345f333..d79fda73a3 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -1,18 +1,15 @@ use crate::shell::Shell; use crate::shell::ShellType; -use crate::tools::handlers::agent_jobs::ReportAgentJobResultHandler; -use crate::tools::handlers::agent_jobs::SpawnAgentsOnCsvHandler; use crate::tools::handlers::multi_agents_common::DEFAULT_WAIT_TIMEOUT_MS; use crate::tools::handlers::multi_agents_common::MAX_WAIT_TIMEOUT_MS; use crate::tools::handlers::multi_agents_common::MIN_WAIT_TIMEOUT_MS; use crate::tools::handlers::multi_agents_spec::WaitAgentTimeoutOptions; use crate::tools::registry::ToolRegistryBuilder; -use crate::tools::spec_plan::build_tool_registry_plan; -use crate::tools::spec_plan_types::ToolHandlerKind; +use crate::tools::spec_plan::build_tool_registry_builder; use crate::tools::spec_plan_types::ToolNamespace; -use crate::tools::spec_plan_types::ToolRegistryPlanDeferredTool; -use crate::tools::spec_plan_types::ToolRegistryPlanMcpTool; -use crate::tools::spec_plan_types::ToolRegistryPlanParams; +use crate::tools::spec_plan_types::ToolRegistryBuildDeferredTool; +use crate::tools::spec_plan_types::ToolRegistryBuildMcpTool; +use crate::tools::spec_plan_types::ToolRegistryBuildParams; use codex_mcp::ToolInfo; use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_tools::AdditionalProperties; @@ -22,7 +19,6 @@ use codex_tools::ResponsesApiTool; use codex_tools::ToolName; use codex_tools::ToolUserShellType; use codex_tools::ToolsConfig; -use codex_tools::augment_tool_spec_for_code_mode; use std::collections::HashMap; use std::collections::HashSet; use std::sync::Arc; @@ -38,7 +34,7 @@ pub(crate) fn tool_user_shell_type(user_shell: &Shell) -> ToolUserShellType { } struct McpToolPlanInputs<'a> { - mcp_tools: Vec>, + mcp_tools: Vec>, tool_namespaces: HashMap, } @@ -46,7 +42,7 @@ fn map_mcp_tools_for_plan(mcp_tools: &HashMap) -> McpToolPlanI McpToolPlanInputs { mcp_tools: mcp_tools .values() - .map(|tool| ToolRegistryPlanMcpTool { + .map(|tool| ToolRegistryBuildMcpTool { name: tool.canonical_tool_name(), tool: &tool.tool, }) @@ -74,51 +70,15 @@ pub(crate) fn build_specs_with_discoverable_tools( discoverable_tools: Option>, dynamic_tools: &[DynamicToolSpec], ) -> ToolRegistryBuilder { - use crate::tools::handlers::ApplyPatchHandler; - use crate::tools::handlers::CodeModeExecuteHandler; - use crate::tools::handlers::CodeModeWaitHandler; - use crate::tools::handlers::ContainerExecHandler; - use crate::tools::handlers::CreateGoalHandler; - use crate::tools::handlers::DynamicToolHandler; - use crate::tools::handlers::ExecCommandHandler; - use crate::tools::handlers::GetGoalHandler; - use crate::tools::handlers::ListMcpResourceTemplatesHandler; - use crate::tools::handlers::ListMcpResourcesHandler; - use crate::tools::handlers::LocalShellHandler; - use crate::tools::handlers::McpHandler; - use crate::tools::handlers::PlanHandler; - use crate::tools::handlers::ReadMcpResourceHandler; - use crate::tools::handlers::RequestPermissionsHandler; - use crate::tools::handlers::RequestPluginInstallHandler; - use crate::tools::handlers::RequestUserInputHandler; - use crate::tools::handlers::ShellCommandHandler; - use crate::tools::handlers::ShellHandler; - use crate::tools::handlers::TestSyncHandler; - use crate::tools::handlers::ToolSearchHandler; use crate::tools::handlers::UnavailableToolHandler; - use crate::tools::handlers::UpdateGoalHandler; - use crate::tools::handlers::ViewImageHandler; - use crate::tools::handlers::WriteStdinHandler; - use crate::tools::handlers::multi_agents::CloseAgentHandler; - use crate::tools::handlers::multi_agents::ResumeAgentHandler; - use crate::tools::handlers::multi_agents::SendInputHandler; - use crate::tools::handlers::multi_agents::SpawnAgentHandler; - use crate::tools::handlers::multi_agents::WaitAgentHandler; - use crate::tools::handlers::multi_agents_v2::CloseAgentHandler as CloseAgentHandlerV2; - use crate::tools::handlers::multi_agents_v2::FollowupTaskHandler as FollowupTaskHandlerV2; - use crate::tools::handlers::multi_agents_v2::ListAgentsHandler as ListAgentsHandlerV2; - use crate::tools::handlers::multi_agents_v2::SendMessageHandler as SendMessageHandlerV2; - use crate::tools::handlers::multi_agents_v2::SpawnAgentHandler as SpawnAgentHandlerV2; - use crate::tools::handlers::multi_agents_v2::WaitAgentHandler as WaitAgentHandlerV2; use crate::tools::handlers::unavailable_tool_message; use crate::tools::tool_search_entry::build_tool_search_entries_for_config; - let mut builder = ToolRegistryBuilder::new(); let mcp_tool_plan_inputs = mcp_tools.as_ref().map(map_mcp_tools_for_plan); let deferred_mcp_tool_sources = deferred_mcp_tools.as_ref().map(|tools| { tools .values() - .map(|tool| ToolRegistryPlanDeferredTool { + .map(|tool| ToolRegistryBuildDeferredTool { name: tool.canonical_tool_name(), server_name: tool.server_name.as_str(), connector_name: tool.connector_name.as_deref(), @@ -138,9 +98,19 @@ pub(crate) fn build_specs_with_discoverable_tools( }; let default_wait_timeout_ms = DEFAULT_WAIT_TIMEOUT_MS.clamp(min_wait_timeout_ms, MAX_WAIT_TIMEOUT_MS); - let plan = build_tool_registry_plan( + let deferred_dynamic_tools = dynamic_tools + .iter() + .filter(|tool| tool.defer_loading && (config.namespace_tools || tool.namespace.is_none())) + .cloned() + .collect::>(); + let tool_search_entries = build_tool_search_entries_for_config( config, - ToolRegistryPlanParams { + deferred_mcp_tools.as_ref(), + &deferred_dynamic_tools, + ); + let mut builder = build_tool_registry_builder( + config, + ToolRegistryBuildParams { mcp_tools: mcp_tool_plan_inputs .as_ref() .map(|inputs| inputs.mcp_tools.as_slice()), @@ -156,164 +126,15 @@ pub(crate) fn build_specs_with_discoverable_tools( min_timeout_ms: min_wait_timeout_ms, max_timeout_ms: MAX_WAIT_TIMEOUT_MS, }, + tool_search_entries: &tool_search_entries, }, ); - let deferred_dynamic_tools = dynamic_tools - .iter() - .filter(|tool| tool.defer_loading && (config.namespace_tools || tool.namespace.is_none())) - .cloned() - .collect::>(); - let mut existing_spec_names = plan - .specs + let mut existing_spec_names = builder + .specs() .iter() .map(|configured_tool| configured_tool.name().to_string()) .collect::>(); - for spec in plan.specs { - if spec.supports_parallel_tool_calls { - builder.push_spec_with_parallel_support( - spec.spec, /*supports_parallel_tool_calls*/ true, - ); - } else { - builder.push_spec(spec.spec); - } - } - - for handler in plan.handlers { - let name = handler.name; - match handler.kind { - ToolHandlerKind::ApplyPatch => { - builder.register_handler(Arc::new(ApplyPatchHandler)); - } - ToolHandlerKind::CloseAgentV1 => { - builder.register_handler(Arc::new(CloseAgentHandler)); - } - ToolHandlerKind::CloseAgentV2 => { - builder.register_handler(Arc::new(CloseAgentHandlerV2)); - } - ToolHandlerKind::CodeModeExecute => { - builder.register_handler(Arc::new(CodeModeExecuteHandler)); - } - ToolHandlerKind::CodeModeWait => { - builder.register_handler(Arc::new(CodeModeWaitHandler)); - } - ToolHandlerKind::ContainerExec => { - builder.register_handler(Arc::new(ContainerExecHandler)); - } - ToolHandlerKind::CreateGoal => { - builder.register_handler(Arc::new(CreateGoalHandler)); - } - ToolHandlerKind::DynamicTool => { - builder.register_handler(Arc::new(DynamicToolHandler::new(name))); - } - ToolHandlerKind::ExecCommand => { - builder.register_handler(Arc::new(ExecCommandHandler)); - } - ToolHandlerKind::FollowupTaskV2 => { - builder.register_handler(Arc::new(FollowupTaskHandlerV2)); - } - ToolHandlerKind::GetGoal => { - builder.register_handler(Arc::new(GetGoalHandler)); - } - ToolHandlerKind::ListAgentsV2 => { - builder.register_handler(Arc::new(ListAgentsHandlerV2)); - } - ToolHandlerKind::ListMcpResources => { - builder.register_handler(Arc::new(ListMcpResourcesHandler)); - } - ToolHandlerKind::ListMcpResourceTemplates => { - builder.register_handler(Arc::new(ListMcpResourceTemplatesHandler)); - } - ToolHandlerKind::LocalShell => { - builder.register_handler(Arc::new(LocalShellHandler)); - } - ToolHandlerKind::Mcp => { - builder.register_handler(Arc::new(McpHandler::new(name))); - } - ToolHandlerKind::Plan => { - builder.register_handler(Arc::new(PlanHandler)); - } - ToolHandlerKind::ReadMcpResource => { - builder.register_handler(Arc::new(ReadMcpResourceHandler)); - } - ToolHandlerKind::ReportAgentJobResult => { - builder.register_handler(Arc::new(ReportAgentJobResultHandler)); - } - ToolHandlerKind::RequestPermissions => { - builder.register_handler(Arc::new(RequestPermissionsHandler)); - } - ToolHandlerKind::RequestUserInput => { - builder.register_handler(Arc::new(RequestUserInputHandler { - available_modes: config.request_user_input_available_modes.clone(), - })); - } - ToolHandlerKind::ResumeAgentV1 => { - builder.register_handler(Arc::new(ResumeAgentHandler)); - } - ToolHandlerKind::SendInputV1 => { - builder.register_handler(Arc::new(SendInputHandler)); - } - ToolHandlerKind::SendMessageV2 => { - builder.register_handler(Arc::new(SendMessageHandlerV2)); - } - ToolHandlerKind::Shell => { - builder.register_handler(Arc::new(ShellHandler)); - } - ToolHandlerKind::ShellCommand => { - builder.register_handler(Arc::new(ShellCommandHandler::from( - config.shell_command_backend, - ))); - } - ToolHandlerKind::SpawnAgentsOnCsv => { - builder.register_handler(Arc::new(SpawnAgentsOnCsvHandler)); - } - ToolHandlerKind::SpawnAgentV1 => { - builder.register_handler(Arc::new(SpawnAgentHandler)); - } - ToolHandlerKind::SpawnAgentV2 => { - builder.register_handler(Arc::new(SpawnAgentHandlerV2)); - } - ToolHandlerKind::TestSync => { - builder.register_handler(Arc::new(TestSyncHandler)); - } - ToolHandlerKind::ToolSearch => { - let entries = build_tool_search_entries_for_config( - config, - deferred_mcp_tools.as_ref(), - &deferred_dynamic_tools, - ); - builder.register_handler(Arc::new(ToolSearchHandler::new(entries))); - } - ToolHandlerKind::RequestPluginInstall => { - builder.register_handler(Arc::new(RequestPluginInstallHandler)); - } - ToolHandlerKind::UpdateGoal => { - builder.register_handler(Arc::new(UpdateGoalHandler)); - } - ToolHandlerKind::ViewImage => { - builder.register_handler(Arc::new(ViewImageHandler)); - } - ToolHandlerKind::WaitAgentV1 => { - builder.register_handler(Arc::new(WaitAgentHandler)); - } - ToolHandlerKind::WaitAgentV2 => { - builder.register_handler(Arc::new(WaitAgentHandlerV2)); - } - ToolHandlerKind::WriteStdin => { - builder.register_handler(Arc::new(WriteStdinHandler)); - } - } - } - if let Some(deferred_mcp_tools) = deferred_mcp_tools.as_ref() { - for (_, tool) in deferred_mcp_tools.iter().filter(|(name, _)| { - !mcp_tools - .as_ref() - .is_some_and(|tools| tools.contains_key(*name)) - }) { - builder.register_handler(Arc::new(McpHandler::new(tool.canonical_tool_name()))); - } - } - for unavailable_tool in unavailable_called_tools { let tool_name = unavailable_tool.display(); if existing_spec_names.insert(tool_name.clone()) { @@ -332,12 +153,11 @@ pub(crate) fn build_specs_with_discoverable_tools( output_schema: None, defer_loading: None, }); - let spec = if config.code_mode_enabled { - augment_tool_spec_for_code_mode(spec) - } else { - spec - }; - builder.push_spec(spec); + builder.push_spec( + spec, + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); } builder.register_handler(Arc::new(UnavailableToolHandler::new(unavailable_tool))); } diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs index e323bce741..61850c4157 100644 --- a/codex-rs/core/src/tools/spec_plan.rs +++ b/codex-rs/core/src/tools/spec_plan.rs @@ -1,5 +1,31 @@ use crate::tools::code_mode::execute_spec::create_code_mode_tool; use crate::tools::code_mode::wait_spec::create_wait_tool; +use crate::tools::handlers::ApplyPatchHandler; +use crate::tools::handlers::CodeModeExecuteHandler; +use crate::tools::handlers::CodeModeWaitHandler; +use crate::tools::handlers::ContainerExecHandler; +use crate::tools::handlers::CreateGoalHandler; +use crate::tools::handlers::DynamicToolHandler; +use crate::tools::handlers::ExecCommandHandler; +use crate::tools::handlers::GetGoalHandler; +use crate::tools::handlers::ListMcpResourceTemplatesHandler; +use crate::tools::handlers::ListMcpResourcesHandler; +use crate::tools::handlers::LocalShellHandler; +use crate::tools::handlers::McpHandler; +use crate::tools::handlers::PlanHandler; +use crate::tools::handlers::ReadMcpResourceHandler; +use crate::tools::handlers::RequestPermissionsHandler; +use crate::tools::handlers::RequestPluginInstallHandler; +use crate::tools::handlers::RequestUserInputHandler; +use crate::tools::handlers::ShellCommandHandler; +use crate::tools::handlers::ShellHandler; +use crate::tools::handlers::TestSyncHandler; +use crate::tools::handlers::ToolSearchHandler; +use crate::tools::handlers::UpdateGoalHandler; +use crate::tools::handlers::ViewImageHandler; +use crate::tools::handlers::WriteStdinHandler; +use crate::tools::handlers::agent_jobs::ReportAgentJobResultHandler; +use crate::tools::handlers::agent_jobs::SpawnAgentsOnCsvHandler; use crate::tools::handlers::agent_jobs_spec::create_report_agent_job_result_tool; use crate::tools::handlers::agent_jobs_spec::create_spawn_agents_on_csv_tool; use crate::tools::handlers::apply_patch_spec::create_apply_patch_freeform_tool; @@ -10,6 +36,11 @@ use crate::tools::handlers::goal_spec::create_update_goal_tool; use crate::tools::handlers::mcp_resource_spec::create_list_mcp_resource_templates_tool; use crate::tools::handlers::mcp_resource_spec::create_list_mcp_resources_tool; use crate::tools::handlers::mcp_resource_spec::create_read_mcp_resource_tool; +use crate::tools::handlers::multi_agents::CloseAgentHandler; +use crate::tools::handlers::multi_agents::ResumeAgentHandler; +use crate::tools::handlers::multi_agents::SendInputHandler; +use crate::tools::handlers::multi_agents::SpawnAgentHandler; +use crate::tools::handlers::multi_agents::WaitAgentHandler; use crate::tools::handlers::multi_agents_spec::SpawnAgentToolOptions; use crate::tools::handlers::multi_agents_spec::create_close_agent_tool_v1; use crate::tools::handlers::multi_agents_spec::create_close_agent_tool_v2; @@ -22,9 +53,14 @@ use crate::tools::handlers::multi_agents_spec::create_spawn_agent_tool_v1; use crate::tools::handlers::multi_agents_spec::create_spawn_agent_tool_v2; use crate::tools::handlers::multi_agents_spec::create_wait_agent_tool_v1; use crate::tools::handlers::multi_agents_spec::create_wait_agent_tool_v2; +use crate::tools::handlers::multi_agents_v2::CloseAgentHandler as CloseAgentHandlerV2; +use crate::tools::handlers::multi_agents_v2::FollowupTaskHandler as FollowupTaskHandlerV2; +use crate::tools::handlers::multi_agents_v2::ListAgentsHandler as ListAgentsHandlerV2; +use crate::tools::handlers::multi_agents_v2::SendMessageHandler as SendMessageHandlerV2; +use crate::tools::handlers::multi_agents_v2::SpawnAgentHandler as SpawnAgentHandlerV2; +use crate::tools::handlers::multi_agents_v2::WaitAgentHandler as WaitAgentHandlerV2; use crate::tools::handlers::plan_spec::create_update_plan_tool; use crate::tools::handlers::request_plugin_install_spec::create_request_plugin_install_tool; -use crate::tools::handlers::request_user_input_spec::REQUEST_USER_INPUT_TOOL_NAME; use crate::tools::handlers::request_user_input_spec::create_request_user_input_tool; use crate::tools::handlers::request_user_input_spec::request_user_input_tool_description; use crate::tools::handlers::shell_spec::CommandToolOptions; @@ -43,17 +79,14 @@ use crate::tools::handlers::view_image_spec::create_view_image_tool; use crate::tools::hosted_spec::WebSearchToolOptions; use crate::tools::hosted_spec::create_image_generation_tool; use crate::tools::hosted_spec::create_web_search_tool; -use crate::tools::spec_plan_types::ToolHandlerKind; -use crate::tools::spec_plan_types::ToolRegistryPlan; -use crate::tools::spec_plan_types::ToolRegistryPlanParams; +use crate::tools::registry::ToolRegistryBuilder; +use crate::tools::spec_plan_types::ToolRegistryBuildParams; use crate::tools::spec_plan_types::agent_type_description; use codex_protocol::openai_models::ApplyPatchToolType; use codex_protocol::openai_models::ConfigShellToolType; -use codex_tools::REQUEST_PLUGIN_INSTALL_TOOL_NAME; use codex_tools::ResponsesApiNamespace; use codex_tools::ResponsesApiNamespaceTool; use codex_tools::TOOL_SEARCH_DEFAULT_LIMIT; -use codex_tools::TOOL_SEARCH_TOOL_NAME; use codex_tools::ToolEnvironmentMode; use codex_tools::ToolName; use codex_tools::ToolSearchSource; @@ -68,12 +101,13 @@ use codex_tools::default_namespace_description; use codex_tools::dynamic_tool_to_loadable_tool_spec; use codex_tools::mcp_tool_to_responses_api_tool; use std::collections::BTreeMap; +use std::sync::Arc; -pub fn build_tool_registry_plan( +pub fn build_tool_registry_builder( config: &ToolsConfig, - params: ToolRegistryPlanParams<'_>, -) -> ToolRegistryPlan { - let mut plan = ToolRegistryPlan::new(); + params: ToolRegistryBuildParams<'_>, +) -> ToolRegistryBuilder { + let mut builder = ToolRegistryBuilder::new(); let exec_permission_approvals_enabled = config.exec_permission_approvals_enabled; if config.code_mode_enabled { @@ -92,22 +126,22 @@ pub fn build_tool_registry_plan( }) .collect::>(); let nested_config = config.for_code_mode_nested_tools(); - let nested_plan = build_tool_registry_plan( + let nested_builder = build_tool_registry_builder( &nested_config, - ToolRegistryPlanParams { + ToolRegistryBuildParams { discoverable_tools: None, ..params }, ); let mut enabled_tools = collect_code_mode_exec_prompt_tool_definitions( - nested_plan - .specs + nested_builder + .specs() .iter() .map(|configured_tool| &configured_tool.spec), ); enabled_tools .sort_by(|left, right| compare_code_mode_tools(left, right, &namespace_descriptions)); - plan.push_spec( + builder.push_spec( create_code_mode_tool( &enabled_tools, &namespace_descriptions, @@ -120,19 +154,13 @@ pub fn build_tool_registry_plan( /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler( - codex_code_mode::PUBLIC_TOOL_NAME, - ToolHandlerKind::CodeModeExecute, - ); - plan.push_spec( + builder.register_handler(Arc::new(CodeModeExecuteHandler)); + builder.push_spec( create_wait_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler( - codex_code_mode::WAIT_TOOL_NAME, - ToolHandlerKind::CodeModeWait, - ); + builder.register_handler(Arc::new(CodeModeWaitHandler)); } if config.environment_mode.has_environment() { @@ -140,7 +168,7 @@ pub fn build_tool_registry_plan( matches!(config.environment_mode, ToolEnvironmentMode::Multiple); match &config.shell_type { ConfigShellToolType::Default => { - plan.push_spec( + builder.push_spec( create_shell_tool(ShellToolOptions { exec_permission_approvals_enabled, }), @@ -149,14 +177,14 @@ pub fn build_tool_registry_plan( ); } ConfigShellToolType::Local => { - plan.push_spec( + builder.push_spec( create_local_shell_tool(), /*supports_parallel_tool_calls*/ true, config.code_mode_enabled, ); } ConfigShellToolType::UnifiedExec => { - plan.push_spec( + builder.push_spec( create_exec_command_tool_with_environment_id( CommandToolOptions { allow_login_shell: config.allow_login_shell, @@ -167,17 +195,17 @@ pub fn build_tool_registry_plan( /*supports_parallel_tool_calls*/ true, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_write_stdin_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler("exec_command", ToolHandlerKind::ExecCommand); - plan.register_handler("write_stdin", ToolHandlerKind::WriteStdin); + builder.register_handler(Arc::new(ExecCommandHandler)); + builder.register_handler(Arc::new(WriteStdinHandler)); } ConfigShellToolType::Disabled => {} ConfigShellToolType::ShellCommand => { - plan.push_spec( + builder.push_spec( create_shell_command_tool(CommandToolOptions { allow_login_shell: config.allow_login_shell, exec_permission_approvals_enabled, @@ -192,82 +220,80 @@ pub fn build_tool_registry_plan( if config.environment_mode.has_environment() && config.shell_type != ConfigShellToolType::Disabled { - plan.register_handler("shell", ToolHandlerKind::Shell); - plan.register_handler("container.exec", ToolHandlerKind::ContainerExec); - plan.register_handler("local_shell", ToolHandlerKind::LocalShell); - plan.register_handler("shell_command", ToolHandlerKind::ShellCommand); + builder.register_handler(Arc::new(ShellHandler)); + builder.register_handler(Arc::new(ContainerExecHandler)); + builder.register_handler(Arc::new(LocalShellHandler)); + builder.register_handler(Arc::new(ShellCommandHandler::from( + config.shell_command_backend, + ))); } if params.mcp_tools.is_some() { - plan.push_spec( + builder.push_spec( create_list_mcp_resources_tool(), /*supports_parallel_tool_calls*/ true, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_list_mcp_resource_templates_tool(), /*supports_parallel_tool_calls*/ true, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_read_mcp_resource_tool(), /*supports_parallel_tool_calls*/ true, config.code_mode_enabled, ); - plan.register_handler("list_mcp_resources", ToolHandlerKind::ListMcpResources); - plan.register_handler( - "list_mcp_resource_templates", - ToolHandlerKind::ListMcpResourceTemplates, - ); - plan.register_handler("read_mcp_resource", ToolHandlerKind::ReadMcpResource); + builder.register_handler(Arc::new(ListMcpResourcesHandler)); + builder.register_handler(Arc::new(ListMcpResourceTemplatesHandler)); + builder.register_handler(Arc::new(ReadMcpResourceHandler)); } - plan.push_spec( + builder.push_spec( create_update_plan_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler("update_plan", ToolHandlerKind::Plan); + builder.register_handler(Arc::new(PlanHandler)); if config.goal_tools { - plan.push_spec( + builder.push_spec( create_get_goal_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler("get_goal", ToolHandlerKind::GetGoal); - plan.push_spec( + builder.register_handler(Arc::new(GetGoalHandler)); + builder.push_spec( create_create_goal_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler("create_goal", ToolHandlerKind::CreateGoal); - plan.push_spec( + builder.register_handler(Arc::new(CreateGoalHandler)); + builder.push_spec( create_update_goal_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler("update_goal", ToolHandlerKind::UpdateGoal); + builder.register_handler(Arc::new(UpdateGoalHandler)); } - plan.push_spec( + builder.push_spec( create_request_user_input_tool(request_user_input_tool_description( &config.request_user_input_available_modes, )), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler( - REQUEST_USER_INPUT_TOOL_NAME, - ToolHandlerKind::RequestUserInput, - ); + builder.register_handler(Arc::new(RequestUserInputHandler { + available_modes: config.request_user_input_available_modes.clone(), + })); if config.request_permissions_tool_enabled { - plan.push_spec( + builder.push_spec( create_request_permissions_tool(request_permissions_tool_description()), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler("request_permissions", ToolHandlerKind::RequestPermissions); + builder.register_handler(Arc::new(RequestPermissionsHandler)); } let deferred_dynamic_tools = params @@ -303,35 +329,28 @@ pub fn build_tool_registry_plan( }); } - plan.push_spec( + builder.push_spec( create_tool_search_tool(&search_source_infos, TOOL_SEARCH_DEFAULT_LIMIT), /*supports_parallel_tool_calls*/ true, config.code_mode_enabled, ); - plan.register_handler(TOOL_SEARCH_TOOL_NAME, ToolHandlerKind::ToolSearch); - - if let Some(deferred_mcp_tools) = deferred_mcp_tools_for_search { - for tool in deferred_mcp_tools { - plan.register_handler(tool.name.clone(), ToolHandlerKind::Mcp); - } - } + builder.register_handler(Arc::new(ToolSearchHandler::new( + params.tool_search_entries.to_vec(), + ))); } if config.tool_suggest && let Some(discoverable_tools) = params.discoverable_tools.filter(|tools| !tools.is_empty()) { - plan.push_spec( + builder.push_spec( create_request_plugin_install_tool(&collect_request_plugin_install_entries( discoverable_tools, )), /*supports_parallel_tool_calls*/ true, /*code_mode_enabled*/ false, ); - plan.register_handler( - REQUEST_PLUGIN_INSTALL_TOOL_NAME, - ToolHandlerKind::RequestPluginInstall, - ); + builder.register_handler(Arc::new(RequestPluginInstallHandler)); } if config.environment_mode.has_environment() @@ -339,21 +358,21 @@ pub fn build_tool_registry_plan( { match apply_patch_tool_type { ApplyPatchToolType::Freeform => { - plan.push_spec( + builder.push_spec( create_apply_patch_freeform_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); } ApplyPatchToolType::Function => { - plan.push_spec( + builder.push_spec( create_apply_patch_json_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); } } - plan.register_handler("apply_patch", ToolHandlerKind::ApplyPatch); + builder.register_handler(Arc::new(ApplyPatchHandler)); } if config @@ -361,12 +380,12 @@ pub fn build_tool_registry_plan( .iter() .any(|tool| tool == "test_sync_tool") { - plan.push_spec( + builder.push_spec( create_test_sync_tool(), /*supports_parallel_tool_calls*/ true, config.code_mode_enabled, ); - plan.register_handler("test_sync_tool", ToolHandlerKind::TestSync); + builder.register_handler(Arc::new(TestSyncHandler)); } if let Some(web_search_tool) = create_web_search_tool(WebSearchToolOptions { @@ -374,7 +393,7 @@ pub fn build_tool_registry_plan( web_search_config: config.web_search_config.as_ref(), web_search_tool_type: config.web_search_tool_type, }) { - plan.push_spec( + builder.push_spec( web_search_tool, /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, @@ -382,7 +401,7 @@ pub fn build_tool_registry_plan( } if config.image_gen_tool { - plan.push_spec( + builder.push_spec( create_image_generation_tool("png"), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, @@ -390,21 +409,21 @@ pub fn build_tool_registry_plan( } if config.environment_mode.has_environment() { - plan.push_spec( + builder.push_spec( create_view_image_tool(ViewImageToolOptions { can_request_original_image_detail: config.can_request_original_image_detail, }), /*supports_parallel_tool_calls*/ true, config.code_mode_enabled, ); - plan.register_handler("view_image", ToolHandlerKind::ViewImage); + builder.register_handler(Arc::new(ViewImageHandler)); } if config.collab_tools { if config.multi_agent_v2 { let agent_type_description = agent_type_description(config, params.default_agent_type_description); - plan.push_spec( + builder.push_spec( create_spawn_agent_tool_v2(SpawnAgentToolOptions { available_models: &config.available_models, agent_type_description, @@ -416,41 +435,41 @@ pub fn build_tool_registry_plan( /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_send_message_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_followup_task_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_wait_agent_tool_v2(params.wait_agent_timeouts), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_close_agent_tool_v2(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_list_agents_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler("spawn_agent", ToolHandlerKind::SpawnAgentV2); - plan.register_handler("send_message", ToolHandlerKind::SendMessageV2); - plan.register_handler("followup_task", ToolHandlerKind::FollowupTaskV2); - plan.register_handler("wait_agent", ToolHandlerKind::WaitAgentV2); - plan.register_handler("close_agent", ToolHandlerKind::CloseAgentV2); - plan.register_handler("list_agents", ToolHandlerKind::ListAgentsV2); + builder.register_handler(Arc::new(SpawnAgentHandlerV2)); + builder.register_handler(Arc::new(SendMessageHandlerV2)); + builder.register_handler(Arc::new(FollowupTaskHandlerV2)); + builder.register_handler(Arc::new(WaitAgentHandlerV2)); + builder.register_handler(Arc::new(CloseAgentHandlerV2)); + builder.register_handler(Arc::new(ListAgentsHandlerV2)); } else { let agent_type_description = agent_type_description(config, params.default_agent_type_description); - plan.push_spec( + builder.push_spec( create_spawn_agent_tool_v1(SpawnAgentToolOptions { available_models: &config.available_models, agent_type_description, @@ -462,51 +481,48 @@ pub fn build_tool_registry_plan( /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_send_input_tool_v1(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_resume_agent_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler("resume_agent", ToolHandlerKind::ResumeAgentV1); - plan.push_spec( + builder.register_handler(Arc::new(ResumeAgentHandler)); + builder.push_spec( create_wait_agent_tool_v1(params.wait_agent_timeouts), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.push_spec( + builder.push_spec( create_close_agent_tool_v1(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler("spawn_agent", ToolHandlerKind::SpawnAgentV1); - plan.register_handler("send_input", ToolHandlerKind::SendInputV1); - plan.register_handler("wait_agent", ToolHandlerKind::WaitAgentV1); - plan.register_handler("close_agent", ToolHandlerKind::CloseAgentV1); + builder.register_handler(Arc::new(SpawnAgentHandler)); + builder.register_handler(Arc::new(SendInputHandler)); + builder.register_handler(Arc::new(WaitAgentHandler)); + builder.register_handler(Arc::new(CloseAgentHandler)); } } if config.agent_jobs_tools { - plan.push_spec( + builder.push_spec( create_spawn_agents_on_csv_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler("spawn_agents_on_csv", ToolHandlerKind::SpawnAgentsOnCsv); + builder.register_handler(Arc::new(SpawnAgentsOnCsvHandler)); if config.agent_jobs_worker_tools { - plan.push_spec( + builder.push_spec( create_report_agent_job_result_tool(), /*supports_parallel_tool_calls*/ false, config.code_mode_enabled, ); - plan.register_handler( - "report_agent_job_result", - ToolHandlerKind::ReportAgentJobResult, - ); + builder.register_handler(Arc::new(ReportAgentJobResultHandler)); } } @@ -548,7 +564,7 @@ pub fn build_tool_registry_plan( match mcp_tool_to_responses_api_tool(&tool.name, tool.tool) { Ok(converted_tool) => { tools.push(ResponsesApiNamespaceTool::Function(converted_tool)); - plan.register_handler(tool.name, ToolHandlerKind::Mcp); + builder.register_handler(Arc::new(McpHandler::new(tool.name))); } Err(error) => { let tool_name = &tool.name; @@ -559,8 +575,8 @@ pub fn build_tool_registry_plan( } } - if !tools.is_empty() { - plan.push_spec( + if config.namespace_tools && !tools.is_empty() { + builder.push_spec( ToolSpec::Namespace(ResponsesApiNamespace { name: namespace, description, @@ -579,7 +595,7 @@ pub fn build_tool_registry_plan( Ok(loadable_tool) => { let handler_name = ToolName::new(tool.namespace.clone(), tool.name.clone()); dynamic_tool_specs.push(loadable_tool); - plan.register_handler(handler_name, ToolHandlerKind::DynamicTool); + builder.register_handler(Arc::new(DynamicToolHandler::new(handler_name))); } Err(error) => { tracing::error!( @@ -590,19 +606,28 @@ pub fn build_tool_registry_plan( } } for spec in coalesce_loadable_tool_specs(dynamic_tool_specs) { - plan.push_spec( - spec.into(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); + let spec = spec.into(); + if config.namespace_tools || !matches!(spec, ToolSpec::Namespace(_)) { + builder.push_spec( + spec, + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + } } - if !config.namespace_tools { - plan.specs - .retain(|configured_tool| !matches!(&configured_tool.spec, ToolSpec::Namespace(_))); + if let Some(deferred_mcp_tools) = params.deferred_mcp_tools { + for tool in deferred_mcp_tools { + let registered_directly = params + .mcp_tools + .is_some_and(|mcp_tools| mcp_tools.iter().any(|direct| direct.name == tool.name)); + if !registered_directly { + builder.register_handler(Arc::new(McpHandler::new(tool.name.clone()))); + } + } } - plan + builder } fn compare_code_mode_tools( diff --git a/codex-rs/core/src/tools/spec_plan_tests.rs b/codex-rs/core/src/tools/spec_plan_tests.rs index 1ad8388803..f41060906b 100644 --- a/codex-rs/core/src/tools/spec_plan_tests.rs +++ b/codex-rs/core/src/tools/spec_plan_tests.rs @@ -1,11 +1,12 @@ use super::*; use crate::tools::handlers::multi_agents_spec::WaitAgentTimeoutOptions; +use crate::tools::handlers::request_user_input_spec::REQUEST_USER_INPUT_TOOL_NAME; use crate::tools::handlers::shell_spec::CommandToolOptions; use crate::tools::handlers::shell_spec::create_exec_command_tool; -use crate::tools::spec_plan_types::ToolHandlerSpec; +use crate::tools::registry::ToolRegistry; use crate::tools::spec_plan_types::ToolNamespace; -use crate::tools::spec_plan_types::ToolRegistryPlanDeferredTool; -use crate::tools::spec_plan_types::ToolRegistryPlanMcpTool; +use crate::tools::spec_plan_types::ToolRegistryBuildDeferredTool; +use crate::tools::spec_plan_types::ToolRegistryBuildMcpTool; use codex_app_server_protocol::AppInfo; use codex_features::Feature; use codex_features::Features; @@ -29,10 +30,12 @@ use codex_tools::FreeformTool; use codex_tools::JsonSchema; use codex_tools::JsonSchemaPrimitiveType; use codex_tools::JsonSchemaType; +use codex_tools::REQUEST_PLUGIN_INSTALL_TOOL_NAME; use codex_tools::ResponsesApiNamespaceTool; use codex_tools::ResponsesApiTool; use codex_tools::ResponsesApiWebSearchFilters; use codex_tools::ResponsesApiWebSearchUserLocation; +use codex_tools::TOOL_SEARCH_TOOL_NAME; use codex_tools::ToolEnvironmentMode; use codex_tools::ToolName; use codex_tools::ToolsConfigParams; @@ -1244,7 +1247,7 @@ fn namespace_specs_are_hidden_when_namespace_tools_are_disabled() { }); tools_config.namespace_tools = false; - let (tools, handlers) = build_specs( + let (tools, registry) = build_specs( &tools_config, Some(HashMap::from([( ToolName::namespaced("mcp__sample__", "echo"), @@ -1255,10 +1258,7 @@ fn namespace_specs_are_hidden_when_namespace_tools_are_disabled() { ); assert_lacks_tool_name(&tools, "mcp__sample__"); - assert!(handlers.contains(&ToolHandlerSpec { - name: ToolName::namespaced("mcp__sample__", "echo"), - kind: ToolHandlerKind::Mcp, - })); + assert!(registry.has_handler(&ToolName::namespaced("mcp__sample__", "echo"))); } #[test] @@ -1412,7 +1412,7 @@ fn search_tool_description_lists_each_mcp_source_once() { windows_sandbox_level: WindowsSandboxLevel::Disabled, }); - let (tools, handlers) = build_specs( + let (tools, registry) = build_specs( &tools_config, Some(HashMap::from([ ( @@ -1477,14 +1477,11 @@ fn search_tool_description_lists_each_mcp_source_once() { assert!(description.contains("- rmcp: Remote memory tools.")); assert!(!description.contains("mcp__rmcp__echo")); - assert!(handlers.contains(&ToolHandlerSpec { - name: ToolName::namespaced("mcp__codex_apps__calendar", "_create_event"), - kind: ToolHandlerKind::Mcp, - })); - assert!(handlers.contains(&ToolHandlerSpec { - name: ToolName::namespaced("mcp__rmcp__", "echo"), - kind: ToolHandlerKind::Mcp, - })); + assert!(registry.has_handler(&ToolName::namespaced( + "mcp__codex_apps__calendar", + "_create_event", + ))); + assert!(registry.has_handler(&ToolName::namespaced("mcp__rmcp__", "echo"))); } #[test] @@ -1578,7 +1575,7 @@ fn search_tool_is_hidden_when_only_deferred_namespace_tools_are_available() { }); tools_config.namespace_tools = false; - let (tools, handlers) = build_specs( + let (tools, registry) = build_specs( &tools_config, /*mcp_tools*/ None, Some(vec![deferred_mcp_tool( @@ -1592,10 +1589,7 @@ fn search_tool_is_hidden_when_only_deferred_namespace_tools_are_available() { ); assert_lacks_tool_name(&tools, TOOL_SEARCH_TOOL_NAME); - assert!(!handlers.contains(&ToolHandlerSpec { - name: ToolName::plain(TOOL_SEARCH_TOOL_NAME), - kind: ToolHandlerKind::ToolSearch, - })); + assert!(!registry.has_handler(&ToolName::plain(TOOL_SEARCH_TOOL_NAME))); } #[test] @@ -1639,7 +1633,7 @@ fn search_tool_registers_for_deferred_dynamic_tools() { }, ]; - let (tools, handlers) = build_specs( + let (tools, registry) = build_specs( &tools_config, /*mcp_tools*/ None, /*deferred_mcp_tools*/ None, @@ -1670,18 +1664,9 @@ fn search_tool_registers_for_deferred_dynamic_tools() { let dynamic_tool = find_namespace_function_tool(&tools, "codex_app", tool_name); assert_eq!(dynamic_tool.defer_loading, Some(true)); } - assert!(handlers.contains(&ToolHandlerSpec { - name: ToolName::plain(TOOL_SEARCH_TOOL_NAME), - kind: ToolHandlerKind::ToolSearch, - })); - assert!(handlers.contains(&ToolHandlerSpec { - name: ToolName::namespaced("codex_app", "automation_update"), - kind: ToolHandlerKind::DynamicTool, - })); - assert!(handlers.contains(&ToolHandlerSpec { - name: ToolName::namespaced("codex_app", "automation_list"), - kind: ToolHandlerKind::DynamicTool, - })); + assert!(registry.has_handler(&ToolName::plain(TOOL_SEARCH_TOOL_NAME))); + assert!(registry.has_handler(&ToolName::namespaced("codex_app", "automation_update"))); + assert!(registry.has_handler(&ToolName::namespaced("codex_app", "automation_list"))); } #[test] @@ -1718,7 +1703,7 @@ fn search_tool_keeps_plain_deferred_dynamic_tools_when_namespace_tools_are_disab }, ]; - let (tools, handlers) = build_specs( + let (tools, registry) = build_specs( &tools_config, /*mcp_tools*/ None, /*deferred_mcp_tools*/ None, @@ -1727,10 +1712,7 @@ fn search_tool_keeps_plain_deferred_dynamic_tools_when_namespace_tools_are_disab assert_contains_tool_names(&tools, &[TOOL_SEARCH_TOOL_NAME, "plain_dynamic"]); assert_lacks_tool_name(&tools, "codex_app"); - assert!(handlers.contains(&ToolHandlerSpec { - name: ToolName::plain(TOOL_SEARCH_TOOL_NAME), - kind: ToolHandlerKind::ToolSearch, - })); + assert!(registry.has_handler(&ToolName::plain(TOOL_SEARCH_TOOL_NAME))); } #[test] @@ -1862,17 +1844,14 @@ fn request_plugin_install_description_lists_discoverable_tools() { })), ]; - let (tools, handlers) = build_specs_with_discoverable_tools( + let (tools, registry) = build_specs_with_discoverable_tools( &tools_config, /*mcp_tools*/ None, /*deferred_mcp_tools*/ None, Some(discoverable_tools), &[], ); - assert!(handlers.contains(&ToolHandlerSpec { - name: ToolName::plain(REQUEST_PLUGIN_INSTALL_TOOL_NAME), - kind: ToolHandlerKind::RequestPluginInstall, - })); + assert!(registry.has_handler(&ToolName::plain(REQUEST_PLUGIN_INSTALL_TOOL_NAME))); let request_plugin_install = find_tool(&tools, REQUEST_PLUGIN_INSTALL_TOOL_NAME); let ToolSpec::Function(ResponsesApiTool { @@ -2225,9 +2204,9 @@ fn search_capable_model_info() -> ModelInfo { fn build_specs<'a>( config: &ToolsConfig, mcp_tools: Option>, - deferred_mcp_tools: Option>>, + deferred_mcp_tools: Option>>, dynamic_tools: &[DynamicToolSpec], -) -> (Vec, Vec) { +) -> (Vec, ToolRegistry) { build_specs_with_discoverable_tools( config, mcp_tools, @@ -2240,10 +2219,10 @@ fn build_specs<'a>( fn build_specs_with_discoverable_tools<'a>( config: &ToolsConfig, mcp_tools: Option>, - deferred_mcp_tools: Option>>, + deferred_mcp_tools: Option>>, discoverable_tools: Option>, dynamic_tools: &[DynamicToolSpec], -) -> (Vec, Vec) { +) -> (Vec, ToolRegistry) { build_specs_with_optional_tool_namespaces( config, mcp_tools, @@ -2257,23 +2236,23 @@ fn build_specs_with_discoverable_tools<'a>( fn build_specs_with_optional_tool_namespaces<'a>( config: &ToolsConfig, mcp_tools: Option>, - deferred_mcp_tools: Option>>, + deferred_mcp_tools: Option>>, tool_namespaces: Option>, discoverable_tools: Option>, dynamic_tools: &[DynamicToolSpec], -) -> (Vec, Vec) { +) -> (Vec, ToolRegistry) { let mcp_tool_inputs = mcp_tools.as_ref().map(|mcp_tools| { mcp_tools .iter() - .map(|(name, tool)| ToolRegistryPlanMcpTool { + .map(|(name, tool)| ToolRegistryBuildMcpTool { name: name.clone(), tool, }) .collect::>() }); - let plan = build_tool_registry_plan( + let builder = build_tool_registry_builder( config, - ToolRegistryPlanParams { + ToolRegistryBuildParams { mcp_tools: mcp_tool_inputs.as_deref(), deferred_mcp_tools: deferred_mcp_tools.as_deref(), tool_namespaces: tool_namespaces.as_ref(), @@ -2281,9 +2260,10 @@ fn build_specs_with_optional_tool_namespaces<'a>( dynamic_tools, default_agent_type_description: DEFAULT_AGENT_TYPE_DESCRIPTION, wait_agent_timeouts: wait_agent_timeout_options(), + tool_search_entries: &[], }, ); - (plan.specs, plan.handlers) + builder.build() } fn mcp_tool(name: &str, description: &str, input_schema: serde_json::Value) -> rmcp::model::Tool { @@ -2397,8 +2377,8 @@ fn deferred_mcp_tool<'a>( server_name: &'a str, connector_name: Option<&'a str>, description: Option<&'a str>, -) -> ToolRegistryPlanDeferredTool<'a> { - ToolRegistryPlanDeferredTool { +) -> ToolRegistryBuildDeferredTool<'a> { + ToolRegistryBuildDeferredTool { name: ToolName::namespaced(tool_namespace, tool_name), server_name, connector_name, diff --git a/codex-rs/core/src/tools/spec_plan_types.rs b/codex-rs/core/src/tools/spec_plan_types.rs index 506c4bc719..a1cb654dd7 100644 --- a/codex-rs/core/src/tools/spec_plan_types.rs +++ b/codex-rs/core/src/tools/spec_plan_types.rs @@ -1,75 +1,20 @@ use crate::tools::handlers::multi_agents_spec::WaitAgentTimeoutOptions; use codex_protocol::dynamic_tools::DynamicToolSpec; -use codex_tools::ConfiguredToolSpec; use codex_tools::DiscoverableTool; use codex_tools::ToolName; -use codex_tools::ToolSpec; use codex_tools::ToolsConfig; -use codex_tools::augment_tool_spec_for_code_mode; use std::collections::HashMap; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ToolHandlerKind { - ApplyPatch, - CloseAgentV1, - CloseAgentV2, - CodeModeExecute, - CodeModeWait, - ContainerExec, - CreateGoal, - DynamicTool, - ExecCommand, - FollowupTaskV2, - GetGoal, - ListAgentsV2, - ListMcpResourceTemplates, - ListMcpResources, - LocalShell, - Mcp, - Plan, - ReadMcpResource, - ReportAgentJobResult, - RequestPluginInstall, - RequestPermissions, - RequestUserInput, - ResumeAgentV1, - SendInputV1, - SendMessageV2, - Shell, - ShellCommand, - SpawnAgentsOnCsv, - SpawnAgentV1, - SpawnAgentV2, - TestSync, - ToolSearch, - UpdateGoal, - ViewImage, - WaitAgentV1, - WaitAgentV2, - WriteStdin, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ToolHandlerSpec { - pub name: ToolName, - pub kind: ToolHandlerKind, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct ToolRegistryPlan { - pub specs: Vec, - pub handlers: Vec, -} - -#[derive(Debug, Clone, Copy)] -pub struct ToolRegistryPlanParams<'a> { - pub mcp_tools: Option<&'a [ToolRegistryPlanMcpTool<'a>]>, - pub deferred_mcp_tools: Option<&'a [ToolRegistryPlanDeferredTool<'a>]>, +#[derive(Clone, Copy)] +pub struct ToolRegistryBuildParams<'a> { + pub mcp_tools: Option<&'a [ToolRegistryBuildMcpTool<'a>]>, + pub deferred_mcp_tools: Option<&'a [ToolRegistryBuildDeferredTool<'a>]>, pub tool_namespaces: Option<&'a HashMap>, pub discoverable_tools: Option<&'a [DiscoverableTool]>, pub dynamic_tools: &'a [DynamicToolSpec], pub default_agent_type_description: &'a str, pub wait_agent_timeouts: WaitAgentTimeoutOptions, + pub tool_search_entries: &'a [crate::tools::tool_search_entry::ToolSearchEntry], } #[derive(Debug, Clone, PartialEq, Eq)] @@ -82,50 +27,19 @@ pub struct ToolNamespace { /// while registering its runtime handler with the canonical namespace/name /// identity. #[derive(Debug, Clone)] -pub struct ToolRegistryPlanMcpTool<'a> { +pub struct ToolRegistryBuildMcpTool<'a> { pub name: ToolName, pub tool: &'a rmcp::model::Tool, } #[derive(Debug, Clone)] -pub struct ToolRegistryPlanDeferredTool<'a> { +pub struct ToolRegistryBuildDeferredTool<'a> { pub name: ToolName, pub server_name: &'a str, pub connector_name: Option<&'a str>, pub description: Option<&'a str>, } -impl ToolRegistryPlan { - pub(crate) fn new() -> Self { - Self { - specs: Vec::new(), - handlers: Vec::new(), - } - } - - pub(crate) fn push_spec( - &mut self, - spec: ToolSpec, - supports_parallel_tool_calls: bool, - code_mode_enabled: bool, - ) { - let spec = if code_mode_enabled { - augment_tool_spec_for_code_mode(spec) - } else { - spec - }; - self.specs - .push(ConfiguredToolSpec::new(spec, supports_parallel_tool_calls)); - } - - pub(crate) fn register_handler(&mut self, name: impl Into, kind: ToolHandlerKind) { - self.handlers.push(ToolHandlerSpec { - name: name.into(), - kind, - }); - } -} - pub(crate) fn agent_type_description( config: &ToolsConfig, default_agent_type_description: &str, diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 1728f5bc5c..7082d26089 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -15,9 +15,7 @@ use anyhow::anyhow; use codex_config::CloudRequirementsLoader; use codex_core::CodexThread; use codex_core::ThreadManager; -use codex_core::agent_graph_store_from_state_db; use codex_core::config::Config; -use codex_core::init_state_db_from_config; use codex_core::resolve_installation_id; use codex_core::shell::Shell; use codex_core::shell::get_shell_by_model_provided_path; @@ -426,33 +424,19 @@ impl TestCodexBuilder { environment_manager: Arc, ) -> anyhow::Result { let auth = self.auth.clone(); - let thread_manager = if config.model_catalog.is_some() { - let state_db = init_state_db_from_config(&config) - .await - .expect("test codex requires state db"); - let thread_store = thread_store_from_config(&config, state_db.clone()); - let agent_graph_store = agent_graph_store_from_state_db(state_db.clone()); - let installation_id = resolve_installation_id(&config.codex_home).await?; - ThreadManager::new( - &config, - codex_core::test_support::auth_manager_from_auth(auth.clone()), - SessionSource::Exec, - Arc::clone(&environment_manager), - /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, - installation_id, - ) - } else { - codex_core::test_support::thread_manager_with_models_provider_and_home( - auth.clone(), - config.model_provider.clone(), - config.codex_home.to_path_buf(), - Arc::clone(&environment_manager), - ) - .await - }; + let state_db = codex_core::init_state_db(&config).await; + let thread_store = thread_store_from_config(&config, state_db.clone()); + let installation_id = resolve_installation_id(&config.codex_home).await?; + let thread_manager = ThreadManager::new( + &config, + codex_core::test_support::auth_manager_from_auth(auth.clone()), + SessionSource::Exec, + Arc::clone(&environment_manager), + /*analytics_events_client*/ None, + thread_store, + state_db.clone(), + installation_id, + ); let thread_manager = Arc::new(thread_manager); let user_shell_override = self.user_shell_override.clone(); diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 143681e2e1..432b57de9f 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -5,8 +5,6 @@ use codex_core::NewThread; use codex_core::Prompt; use codex_core::ResponseEvent; use codex_core::ThreadManager; -use codex_core::agent_graph_store_from_state_db; -use codex_core::init_state_db_from_config; use codex_core::resolve_installation_id; use codex_core::thread_store_from_config; use codex_features::Feature; @@ -1116,11 +1114,6 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() { Ok(None) => panic!("No CodexAuth found in codex_home"), Err(e) => panic!("Failed to load CodexAuth: {e}"), }; - let state_db = init_state_db_from_config(&config) - .await - .expect("client test requires state db"); - let thread_store = thread_store_from_config(&config, state_db.clone()); - let agent_graph_store = agent_graph_store_from_state_db(state_db.clone()); let installation_id = resolve_installation_id(&config.codex_home) .await .expect("resolve installation id"); @@ -1130,9 +1123,8 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() { SessionSource::Exec, Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, + thread_store_from_config(&config, /*state_db*/ None), + /*state_db*/ None, installation_id, ); let NewThread { thread: codex, .. } = thread_manager diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index 1d770649d0..b1620ee36b 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -13,6 +13,8 @@ use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelsResponse; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::HookEventName; +use codex_protocol::protocol::HookRunStatus; use codex_protocol::protocol::ItemCompletedEvent; use codex_protocol::protocol::ItemStartedEvent; use codex_protocol::protocol::Op; @@ -23,6 +25,7 @@ use codex_protocol::user_input::UserInput; use core_test_support::context_snapshot; use core_test_support::context_snapshot::ContextSnapshotOptions; use core_test_support::context_snapshot::ContextSnapshotRenderMode; +use core_test_support::hooks::trust_discovered_hooks; use core_test_support::responses::ev_local_shell_call; use core_test_support::responses::ev_reasoning_item; use core_test_support::responses::mount_models_once; @@ -47,7 +50,10 @@ use core_test_support::responses::sse_failed; use core_test_support::responses::sse_response; use core_test_support::responses::start_mock_server; use pretty_assertions::assert_eq; +use serde_json::Value; use serde_json::json; +use std::fs; +use std::path::Path; use wiremock::MockServer; // --- Test helpers ----------------------------------------------------------- @@ -119,6 +125,107 @@ fn json_fragment(text: &str) -> String { .to_string() } +fn read_hook_inputs(path: &Path) -> Vec { + let text = fs::read_to_string(path) + .unwrap_or_else(|err| panic!("failed to read hook input log {}: {err}", path.display())); + text.lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| { + serde_json::from_str(line) + .unwrap_or_else(|err| panic!("failed to parse hook input log line: {err}")) + }) + .collect() +} + +fn python_hook_command(script_path: &Path) -> String { + format!("python3 \"{}\"", script_path.display()) +} + +fn write_unsupported_blocking_pre_compact_hook(home: &Path) { + let script_path = home.join("pre_compact_block.py"); + let log_path = home.join("pre_compact_block_log.jsonl"); + let script = format!( + r#"import json +from pathlib import Path +import sys + +payload = json.load(sys.stdin) +with Path(r"{log_path}").open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload) + "\n") + +print(json.dumps({{"decision": "block", "reason": "blocked by policy"}})) +"#, + log_path = log_path.display(), + ); + let hooks = json!({ + "hooks": { + "PreCompact": [{ + "matcher": "manual", + "hooks": [{ + "type": "command", + "command": python_hook_command(&script_path), + "statusMessage": "checking compact policy", + }] + }] + } + }); + + fs::write(&script_path, script).expect("write pre compact hook script"); + fs::write(home.join("hooks.json"), hooks.to_string()).expect("write hooks.json"); +} + +fn write_matching_compact_hooks(home: &Path) { + let auto_script_path = home.join("pre_compact_auto.py"); + let auto_log_path = home.join("pre_compact_auto_log.jsonl"); + let manual_post_script_path = home.join("post_compact_manual.py"); + let manual_post_log_path = home.join("post_compact_manual_log.jsonl"); + let auto_script = format!( + r#"import json +from pathlib import Path +import sys + +payload = json.load(sys.stdin) +with Path(r"{auto_log_path}").open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload) + "\n") +"#, + auto_log_path = auto_log_path.display(), + ); + let manual_post_script = format!( + r#"import json +from pathlib import Path +import sys + +payload = json.load(sys.stdin) +with Path(r"{manual_post_log_path}").open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload) + "\n") +"#, + manual_post_log_path = manual_post_log_path.display(), + ); + let hooks = json!({ + "hooks": { + "PreCompact": [{ + "matcher": "auto", + "hooks": [{ + "type": "command", + "command": python_hook_command(&auto_script_path), + }] + }], + "PostCompact": [{ + "matcher": "manual", + "hooks": [{ + "type": "command", + "command": python_hook_command(&manual_post_script_path), + }] + }] + } + }); + + fs::write(&auto_script_path, auto_script).expect("write auto pre compact hook script"); + fs::write(&manual_post_script_path, manual_post_script) + .expect("write manual post compact hook script"); + fs::write(home.join("hooks.json"), hooks.to_string()).expect("write hooks.json"); +} + fn non_openai_model_provider(server: &MockServer) -> ModelProviderInfo { let mut provider = built_in_model_providers(/* openai_base_url */ /*openai_base_url*/ None)["openai"].clone(); @@ -437,6 +544,145 @@ async fn summarize_context_three_requests_and_instructions() { ); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn manual_pre_compact_block_decision_does_not_block_compaction() { + skip_if_no_network!(); + + let server = start_mock_server().await; + let first_turn = sse(vec![ + ev_assistant_message("m0", FIRST_REPLY), + ev_completed_with_tokens("r0", /*total_tokens*/ 80), + ]); + let compact_turn = sse(vec![ + ev_assistant_message("m1", SUMMARY_TEXT), + ev_completed_with_tokens("r1", /*total_tokens*/ 100), + ]); + let request_log = mount_sse_sequence(&server, vec![first_turn, compact_turn]).await; + + let model_provider = non_openai_model_provider(&server); + let mut builder = test_codex() + .with_pre_build_hook(write_unsupported_blocking_pre_compact_hook) + .with_config(move |config| { + config.model_provider = model_provider; + trust_discovered_hooks(config); + set_test_compact_prompt(config); + }); + let test = builder.build(&server).await.expect("create conversation"); + let codex = test.codex.clone(); + + codex + .submit(Op::UserInput { + environments: None, + items: vec![UserInput::Text { + text: "hello before blocked compact".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + responsesapi_client_metadata: None, + }) + .await + .expect("submit first user turn"); + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + codex.submit(Op::Compact).await.expect("trigger compact"); + + let completed = wait_for_event_match(&codex, |ev| match ev { + EventMsg::HookCompleted(completed) + if completed.run.event_name == HookEventName::PreCompact => + { + Some(completed.clone()) + } + _ => None, + }) + .await; + assert_eq!(completed.run.status, HookRunStatus::Failed); + wait_for_event(&codex, |ev| matches!(ev, EventMsg::Warning(_))).await; + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let requests = request_log.requests(); + assert_eq!( + requests.len(), + 2, + "unsupported PreCompact block output should not prevent the compact request" + ); + + let hook_inputs = read_hook_inputs(&test.codex_home_path().join("pre_compact_block_log.jsonl")); + assert_eq!(hook_inputs.len(), 1); + let input = &hook_inputs[0]; + assert_eq!(input["hook_event_name"], "PreCompact"); + assert_eq!(input["trigger"], "manual"); + assert!(input.get("reason").is_none()); + assert!(input.get("phase").is_none()); + assert!(input.get("implementation").is_none()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn compact_hooks_respect_matchers_and_post_runs_after_compaction() { + skip_if_no_network!(); + + let server = start_mock_server().await; + let first_turn = sse(vec![ + ev_assistant_message("m0", FIRST_REPLY), + ev_completed_with_tokens("r0", /*total_tokens*/ 80), + ]); + let compact_turn = sse(vec![ + ev_assistant_message("m1", SUMMARY_TEXT), + ev_completed_with_tokens("r1", /*total_tokens*/ 100), + ]); + let request_log = mount_sse_sequence(&server, vec![first_turn, compact_turn]).await; + + let model_provider = non_openai_model_provider(&server); + let mut builder = test_codex() + .with_pre_build_hook(write_matching_compact_hooks) + .with_config(move |config| { + config.model_provider = model_provider; + trust_discovered_hooks(config); + set_test_compact_prompt(config); + }); + let test = builder.build(&server).await.expect("create conversation"); + let codex = test.codex.clone(); + + codex + .submit(Op::UserInput { + environments: None, + items: vec![UserInput::Text { + text: "hello before matched compact".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + responsesapi_client_metadata: None, + }) + .await + .expect("submit first user turn"); + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + codex.submit(Op::Compact).await.expect("trigger compact"); + wait_for_event(&codex, |ev| matches!(ev, EventMsg::Warning(_))).await; + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + assert_eq!(request_log.requests().len(), 2); + assert!( + !test + .codex_home_path() + .join("pre_compact_auto_log.jsonl") + .exists(), + "auto matcher should not run for manual compaction" + ); + + let hook_inputs = + read_hook_inputs(&test.codex_home_path().join("post_compact_manual_log.jsonl")); + assert_eq!(hook_inputs.len(), 1); + let input = &hook_inputs[0]; + assert_eq!(input["hook_event_name"], "PostCompact"); + assert_eq!(input["trigger"], "manual"); + assert!(input.get("compact_summary").is_none()); + assert!(input.get("status").is_none()); + assert!(input.get("error").is_none()); + assert!(input.get("reason").is_none()); + assert!(input.get("phase").is_none()); + assert!(input.get("implementation").is_none()); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn manual_compact_uses_custom_prompt() { skip_if_no_network!(); diff --git a/codex-rs/core/tests/suite/live_reload.rs b/codex-rs/core/tests/suite/live_reload.rs new file mode 100644 index 0000000000..c422073e4f --- /dev/null +++ b/codex-rs/core/tests/suite/live_reload.rs @@ -0,0 +1,157 @@ +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use std::fs; +use std::path::Path; +use std::path::PathBuf; +use std::time::Duration; + +use anyhow::Result; +use codex_config::config_toml::ProjectConfig; +use codex_protocol::config_types::TrustLevel; +use codex_protocol::models::PermissionProfile; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::user_input::UserInput; +use core_test_support::responses; +use core_test_support::responses::ResponsesRequest; +use core_test_support::responses::mount_sse_sequence; +use core_test_support::responses::start_mock_server; +use core_test_support::test_codex::TestCodex; +use core_test_support::test_codex::test_codex; +use core_test_support::test_codex::turn_permission_fields; +use core_test_support::wait_for_event; +use tokio::time::timeout; + +fn enable_trusted_project(config: &mut codex_core::config::Config) { + config.active_project = ProjectConfig { + trust_level: Some(TrustLevel::Trusted), + }; +} + +fn write_skill(home: &Path, name: &str, description: &str, body: &str) -> PathBuf { + let skill_dir = home.join("skills").join(name); + fs::create_dir_all(&skill_dir).expect("create skill dir"); + let contents = format!("---\nname: {name}\ndescription: {description}\n---\n\n{body}\n"); + let path = skill_dir.join("SKILL.md"); + fs::write(&path, contents).expect("write skill"); + path +} + +fn contains_skill_body(request: &ResponsesRequest, skill_body: &str) -> bool { + request + .message_input_texts("user") + .iter() + .any(|text| text.contains(skill_body) && text.contains("")) +} + +async fn submit_skill_turn(test: &TestCodex, skill_path: PathBuf, prompt: &str) -> Result<()> { + let session_model = test.session_configured.model.clone(); + let (sandbox_policy, permission_profile) = + turn_permission_fields(PermissionProfile::Disabled, test.cwd_path()); + test.codex + .submit(Op::UserTurn { + environments: None, + items: vec![ + UserInput::Text { + text: prompt.to_string(), + text_elements: Vec::new(), + }, + UserInput::Skill { + name: "demo".to_string(), + path: skill_path, + }, + ], + final_output_json_schema: None, + cwd: test.cwd_path().to_path_buf(), + approval_policy: AskForApproval::Never, + approvals_reviewer: None, + sandbox_policy, + permission_profile, + model: session_model, + effort: None, + summary: None, + service_tier: None, + collaboration_mode: None, + personality: None, + }) + .await?; + + wait_for_event(test.codex.as_ref(), |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn live_skills_reload_refreshes_skill_cache_after_skill_change() -> Result<()> { + let server = start_mock_server().await; + let responses = mount_sse_sequence( + &server, + vec![ + responses::sse(vec![responses::ev_completed("resp-1")]), + responses::sse(vec![responses::ev_completed("resp-2")]), + ], + ) + .await; + + let skill_v1 = "skill body v1"; + let skill_v2 = "skill body v2"; + let mut builder = test_codex() + .with_pre_build_hook(move |home| { + write_skill(home, "demo", "demo skill", skill_v1); + }) + .with_config(|config| { + enable_trusted_project(config); + }); + let test = builder.build(&server).await?; + + let skill_path = dunce::canonicalize(test.codex_home_path().join("skills/demo/SKILL.md"))?; + + submit_skill_turn(&test, skill_path.clone(), "please use $demo").await?; + let first_request = responses + .requests() + .first() + .cloned() + .expect("first request captured"); + assert!( + contains_skill_body(&first_request, skill_v1), + "expected initial skill body in request" + ); + + write_skill(test.codex_home_path(), "demo", "demo skill", skill_v2); + + let saw_skills_update = timeout(Duration::from_secs(5), async { + loop { + match test.codex.next_event().await { + Ok(event) => { + if matches!(event.msg, EventMsg::SkillsUpdateAvailable) { + break; + } + } + Err(err) => panic!("event stream ended unexpectedly: {err}"), + } + } + }) + .await; + + if saw_skills_update.is_err() { + // Some environments do not reliably surface file watcher events for + // skill changes. Clear the cache explicitly so we can still validate + // that the updated skill body is injected on the next turn. + test.thread_manager.skills_manager().clear_cache(); + } + + submit_skill_turn(&test, skill_path.clone(), "please use $demo again").await?; + let last_request = responses + .last_request() + .expect("request captured after skill update"); + + assert!( + contains_skill_body(&last_request, skill_v2), + "expected updated skill body after reload" + ); + + Ok(()) +} diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index a914af3021..ad3280ebf0 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -57,6 +57,7 @@ mod image_rollout; mod items; mod json_result; mod live_cli; +mod live_reload; mod model_overrides; mod model_switching; mod model_visible_layout; diff --git a/codex-rs/core/tests/suite/personality_migration.rs b/codex-rs/core/tests/suite/personality_migration.rs index 25415cd7ee..0b89a9cfba 100644 --- a/codex-rs/core/tests/suite/personality_migration.rs +++ b/codex-rs/core/tests/suite/personality_migration.rs @@ -13,8 +13,6 @@ use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::UserMessageEvent; -use codex_rollout::RolloutConfig; -use codex_rollout::state_db::StateDbHandle; use pretty_assertions::assert_eq; use std::io; use std::path::Path; @@ -28,27 +26,6 @@ async fn read_config_toml(codex_home: &Path) -> io::Result { toml::from_str(&contents).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) } -async fn state_db_for_test(codex_home: &Path) -> io::Result { - let config = RolloutConfig { - codex_home: codex_home.to_path_buf(), - sqlite_home: codex_home.to_path_buf(), - cwd: codex_home.to_path_buf(), - model_provider_id: "openai".to_string(), - generate_memories: false, - }; - codex_rollout::state_db::try_init(&config) - .await - .map_err(io::Error::other) -} - -async fn run_migration( - codex_home: &Path, - config_toml: &ConfigToml, -) -> io::Result { - let state_db = state_db_for_test(codex_home).await?; - maybe_migrate_personality(codex_home, config_toml, state_db).await -} - async fn write_session_with_user_event(codex_home: &Path) -> io::Result<()> { let thread_id = ThreadId::new(); let dir = codex_home @@ -166,7 +143,8 @@ async fn migration_marker_exists_no_sessions_no_change() -> io::Result<()> { let marker_path = temp.path().join(PERSONALITY_MIGRATION_FILENAME); tokio::fs::write(&marker_path, "v1\n").await?; - let status = run_migration(temp.path(), &ConfigToml::default()).await?; + let status = + maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::SkippedMarker); assert_eq!( @@ -180,7 +158,8 @@ async fn migration_marker_exists_no_sessions_no_change() -> io::Result<()> { async fn no_marker_no_sessions_no_change() -> io::Result<()> { let temp = TempDir::new()?; - let status = run_migration(temp.path(), &ConfigToml::default()).await?; + let status = + maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::SkippedNoSessions); assert_eq!( @@ -199,7 +178,8 @@ async fn no_marker_sessions_sets_personality() -> io::Result<()> { let temp = TempDir::new()?; write_session_with_user_event(temp.path()).await?; - let status = run_migration(temp.path(), &ConfigToml::default()).await?; + let status = + maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::Applied); assert_eq!( @@ -219,7 +199,7 @@ async fn no_marker_sessions_preserves_existing_config_fields() -> io::Result<()> tokio::fs::write(temp.path().join("config.toml"), "model = \"gpt-5.4\"\n").await?; let config_toml = read_config_toml(temp.path()).await?; - let status = run_migration(temp.path(), &config_toml).await?; + let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::Applied); let persisted = read_config_toml(temp.path()).await?; @@ -233,7 +213,8 @@ async fn no_marker_meta_only_rollout_is_treated_as_no_sessions() -> io::Result<( let temp = TempDir::new()?; write_session_with_meta_only(temp.path()).await?; - let status = run_migration(temp.path(), &ConfigToml::default()).await?; + let status = + maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::SkippedNoSessions); assert_eq!( @@ -253,7 +234,7 @@ async fn no_marker_explicit_global_personality_skips_migration() -> io::Result<( write_session_with_user_event(temp.path()).await?; let config_toml = parse_config_toml("personality = \"friendly\"\n")?; - let status = run_migration(temp.path(), &config_toml).await?; + let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?; assert_eq!( status, @@ -283,7 +264,7 @@ personality = "friendly" "#, )?; - let status = run_migration(temp.path(), &config_toml).await?; + let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?; assert_eq!( status, @@ -306,7 +287,7 @@ async fn marker_short_circuits_invalid_profile_resolution() -> io::Result<()> { tokio::fs::write(temp.path().join(PERSONALITY_MIGRATION_FILENAME), "v1\n").await?; let config_toml = parse_config_toml("profile = \"missing\"\n")?; - let status = run_migration(temp.path(), &config_toml).await?; + let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::SkippedMarker); Ok(()) @@ -317,7 +298,7 @@ async fn invalid_selected_profile_returns_error_and_does_not_write_marker() -> i let temp = TempDir::new()?; let config_toml = parse_config_toml("profile = \"missing\"\n")?; - let err = run_migration(temp.path(), &config_toml) + let err = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None) .await .expect_err("missing profile should fail"); @@ -334,8 +315,10 @@ async fn applied_migration_is_idempotent_on_second_run() -> io::Result<()> { let temp = TempDir::new()?; write_session_with_user_event(temp.path()).await?; - let first_status = run_migration(temp.path(), &ConfigToml::default()).await?; - let second_status = run_migration(temp.path(), &ConfigToml::default()).await?; + let first_status = + maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?; + let second_status = + maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?; assert_eq!(first_status, PersonalityMigrationStatus::Applied); assert_eq!(second_status, PersonalityMigrationStatus::SkippedMarker); @@ -349,7 +332,8 @@ async fn no_marker_archived_sessions_sets_personality() -> io::Result<()> { let temp = TempDir::new()?; write_archived_session_with_user_event(temp.path()).await?; - let status = run_migration(temp.path(), &ConfigToml::default()).await?; + let status = + maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?; assert_eq!(status, PersonalityMigrationStatus::Applied); assert_eq!( diff --git a/codex-rs/core/tests/suite/prompt_debug_tests.rs b/codex-rs/core/tests/suite/prompt_debug_tests.rs index 4fee438261..dc506bc474 100644 --- a/codex-rs/core/tests/suite/prompt_debug_tests.rs +++ b/codex-rs/core/tests/suite/prompt_debug_tests.rs @@ -29,6 +29,7 @@ async fn build_prompt_input_includes_context_and_user_message() -> Result<()> { text: "hello from debug prompt".to_string(), text_elements: Vec::new(), }], + /*state_db*/ None, ) .await?; diff --git a/codex-rs/core/tests/suite/resume_warning.rs b/codex-rs/core/tests/suite/resume_warning.rs index 02e7626d87..cb545df351 100644 --- a/codex-rs/core/tests/suite/resume_warning.rs +++ b/codex-rs/core/tests/suite/resume_warning.rs @@ -95,8 +95,7 @@ async fn emits_warning_when_resumed_model_differs() { let thread_manager = codex_core::test_support::thread_manager_with_models_provider( CodexAuth::from_api_key("test"), config.model_provider.clone(), - ) - .await; + ); let auth_manager = codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("test")); diff --git a/codex-rs/core/tests/suite/unstable_features_warning.rs b/codex-rs/core/tests/suite/unstable_features_warning.rs index 7a4924cdda..66a7366589 100644 --- a/codex-rs/core/tests/suite/unstable_features_warning.rs +++ b/codex-rs/core/tests/suite/unstable_features_warning.rs @@ -34,8 +34,7 @@ async fn emits_warning_when_unstable_features_enabled_via_config() { let thread_manager = codex_core::test_support::thread_manager_with_models_provider( CodexAuth::from_api_key("test"), config.model_provider.clone(), - ) - .await; + ); let auth_manager = codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("test")); @@ -82,8 +81,7 @@ async fn suppresses_warning_when_configured() { let thread_manager = codex_core::test_support::thread_manager_with_models_provider( CodexAuth::from_api_key("test"), config.model_provider.clone(), - ) - .await; + ); let auth_manager = codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("test")); diff --git a/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json b/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json index 21d45382b0..c89f80a3b0 100644 --- a/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json @@ -7,6 +7,8 @@ "PreToolUse", "PermissionRequest", "PostToolUse", + "PreCompact", + "PostCompact", "SessionStart", "UserPromptSubmit", "Stop" diff --git a/codex-rs/hooks/schema/generated/post-compact.command.input.schema.json b/codex-rs/hooks/schema/generated/post-compact.command.input.schema.json new file mode 100644 index 0000000000..e80ed092b7 --- /dev/null +++ b/codex-rs/hooks/schema/generated/post-compact.command.input.schema.json @@ -0,0 +1,52 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "additionalProperties": false, + "definitions": { + "NullableString": { + "type": [ + "string", + "null" + ] + } + }, + "properties": { + "cwd": { + "type": "string" + }, + "hook_event_name": { + "const": "PostCompact", + "type": "string" + }, + "model": { + "type": "string" + }, + "session_id": { + "type": "string" + }, + "transcript_path": { + "$ref": "#/definitions/NullableString" + }, + "trigger": { + "enum": [ + "manual", + "auto" + ], + "type": "string" + }, + "turn_id": { + "description": "Codex extension: expose the active turn id to internal turn-scoped hooks.", + "type": "string" + } + }, + "required": [ + "cwd", + "hook_event_name", + "model", + "session_id", + "transcript_path", + "trigger", + "turn_id" + ], + "title": "post-compact.command.input", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/hooks/schema/generated/post-compact.command.output.schema.json b/codex-rs/hooks/schema/generated/post-compact.command.output.schema.json new file mode 100644 index 0000000000..0221ac29b4 --- /dev/null +++ b/codex-rs/hooks/schema/generated/post-compact.command.output.schema.json @@ -0,0 +1,24 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "additionalProperties": false, + "properties": { + "continue": { + "default": true, + "type": "boolean" + }, + "stopReason": { + "default": null, + "type": "string" + }, + "suppressOutput": { + "default": false, + "type": "boolean" + }, + "systemMessage": { + "default": null, + "type": "string" + } + }, + "title": "post-compact.command.output", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json b/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json index 43a2a4828e..2b64c0ad00 100644 --- a/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json @@ -13,6 +13,8 @@ "PreToolUse", "PermissionRequest", "PostToolUse", + "PreCompact", + "PostCompact", "SessionStart", "UserPromptSubmit", "Stop" diff --git a/codex-rs/hooks/schema/generated/pre-compact.command.input.schema.json b/codex-rs/hooks/schema/generated/pre-compact.command.input.schema.json new file mode 100644 index 0000000000..816fae23c8 --- /dev/null +++ b/codex-rs/hooks/schema/generated/pre-compact.command.input.schema.json @@ -0,0 +1,52 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "additionalProperties": false, + "definitions": { + "NullableString": { + "type": [ + "string", + "null" + ] + } + }, + "properties": { + "cwd": { + "type": "string" + }, + "hook_event_name": { + "const": "PreCompact", + "type": "string" + }, + "model": { + "type": "string" + }, + "session_id": { + "type": "string" + }, + "transcript_path": { + "$ref": "#/definitions/NullableString" + }, + "trigger": { + "enum": [ + "manual", + "auto" + ], + "type": "string" + }, + "turn_id": { + "description": "Codex extension: expose the active turn id to internal turn-scoped hooks.", + "type": "string" + } + }, + "required": [ + "cwd", + "hook_event_name", + "model", + "session_id", + "transcript_path", + "trigger", + "turn_id" + ], + "title": "pre-compact.command.input", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/hooks/schema/generated/pre-compact.command.output.schema.json b/codex-rs/hooks/schema/generated/pre-compact.command.output.schema.json new file mode 100644 index 0000000000..644cd1a8b4 --- /dev/null +++ b/codex-rs/hooks/schema/generated/pre-compact.command.output.schema.json @@ -0,0 +1,24 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "additionalProperties": false, + "properties": { + "continue": { + "default": true, + "type": "boolean" + }, + "stopReason": { + "default": null, + "type": "string" + }, + "suppressOutput": { + "default": false, + "type": "boolean" + }, + "systemMessage": { + "default": null, + "type": "string" + } + }, + "title": "pre-compact.command.output", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json b/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json index ba6bb3401b..3ab17b9f5c 100644 --- a/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json @@ -7,6 +7,8 @@ "PreToolUse", "PermissionRequest", "PostToolUse", + "PreCompact", + "PostCompact", "SessionStart", "UserPromptSubmit", "Stop" diff --git a/codex-rs/hooks/schema/generated/session-start.command.output.schema.json b/codex-rs/hooks/schema/generated/session-start.command.output.schema.json index 30d2b0f977..4d6ba033fe 100644 --- a/codex-rs/hooks/schema/generated/session-start.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/session-start.command.output.schema.json @@ -7,6 +7,8 @@ "PreToolUse", "PermissionRequest", "PostToolUse", + "PreCompact", + "PostCompact", "SessionStart", "UserPromptSubmit", "Stop" diff --git a/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json b/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json index 26353d97db..6baceb149f 100644 --- a/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json @@ -13,6 +13,8 @@ "PreToolUse", "PermissionRequest", "PostToolUse", + "PreCompact", + "PostCompact", "SessionStart", "UserPromptSubmit", "Stop" diff --git a/codex-rs/hooks/src/engine/discovery.rs b/codex-rs/hooks/src/engine/discovery.rs index f24da13bb4..ed4322fb58 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -511,6 +511,8 @@ fn hook_event_key_label(event_name: codex_protocol::protocol::HookEventName) -> codex_protocol::protocol::HookEventName::PreToolUse => "pre_tool_use", codex_protocol::protocol::HookEventName::PermissionRequest => "permission_request", codex_protocol::protocol::HookEventName::PostToolUse => "post_tool_use", + codex_protocol::protocol::HookEventName::PreCompact => "pre_compact", + codex_protocol::protocol::HookEventName::PostCompact => "post_compact", codex_protocol::protocol::HookEventName::SessionStart => "session_start", codex_protocol::protocol::HookEventName::UserPromptSubmit => "user_prompt_submit", codex_protocol::protocol::HookEventName::Stop => "stop", diff --git a/codex-rs/hooks/src/engine/dispatcher.rs b/codex-rs/hooks/src/engine/dispatcher.rs index c44b1fe69d..9c71bf49b5 100644 --- a/codex-rs/hooks/src/engine/dispatcher.rs +++ b/codex-rs/hooks/src/engine/dispatcher.rs @@ -46,7 +46,9 @@ pub(crate) fn select_handlers_for_matcher_inputs( HookEventName::PreToolUse | HookEventName::PermissionRequest | HookEventName::PostToolUse - | HookEventName::SessionStart => { + | HookEventName::SessionStart + | HookEventName::PreCompact + | HookEventName::PostCompact => { if matcher_inputs.is_empty() { matches_matcher(handler.matcher.as_deref(), /*input*/ None) } else { @@ -132,6 +134,8 @@ fn scope_for_event(event_name: HookEventName) -> HookScope { HookEventName::PreToolUse | HookEventName::PermissionRequest | HookEventName::PostToolUse + | HookEventName::PreCompact + | HookEventName::PostCompact | HookEventName::UserPromptSubmit | HookEventName::Stop => HookScope::Turn, } @@ -215,6 +219,29 @@ mod tests { assert_eq!(selected[1].display_order, 1); } + #[test] + fn compact_hooks_match_trigger() { + let handlers = vec![ + make_handler( + HookEventName::PreCompact, + Some("manual"), + "echo manual", + /*display_order*/ 0, + ), + make_handler( + HookEventName::PreCompact, + Some("auto"), + "echo auto", + /*display_order*/ 1, + ), + ]; + + let selected = select_handlers(&handlers, HookEventName::PreCompact, Some("manual")); + + assert_eq!(selected.len(), 1); + assert_eq!(selected[0].display_order, 0); + } + #[test] fn pre_tool_use_matches_tool_name() { let handlers = vec![ diff --git a/codex-rs/hooks/src/engine/mod.rs b/codex-rs/hooks/src/engine/mod.rs index 18262989e8..579f7594d4 100644 --- a/codex-rs/hooks/src/engine/mod.rs +++ b/codex-rs/hooks/src/engine/mod.rs @@ -6,6 +6,10 @@ pub(crate) mod schema_loader; use std::collections::HashMap; +use crate::events::compact::PostCompactRequest; +use crate::events::compact::PreCompactOutcome; +use crate::events::compact::PreCompactRequest; +use crate::events::compact::StatelessHookOutcome; use crate::events::permission_request::PermissionRequestOutcome; use crate::events::permission_request::PermissionRequestRequest; use crate::events::post_tool_use::PostToolUseOutcome; @@ -63,6 +67,8 @@ impl ConfiguredHandler { codex_protocol::protocol::HookEventName::PreToolUse => "pre-tool-use", codex_protocol::protocol::HookEventName::PermissionRequest => "permission-request", codex_protocol::protocol::HookEventName::PostToolUse => "post-tool-use", + codex_protocol::protocol::HookEventName::PreCompact => "pre-compact", + codex_protocol::protocol::HookEventName::PostCompact => "post-compact", codex_protocol::protocol::HookEventName::SessionStart => "session-start", codex_protocol::protocol::HookEventName::UserPromptSubmit => "user-prompt-submit", codex_protocol::protocol::HookEventName::Stop => "stop", @@ -198,6 +204,25 @@ impl ClaudeHooksEngine { outcome } + pub(crate) fn preview_pre_compact(&self, request: &PreCompactRequest) -> Vec { + crate::events::compact::preview_pre(&self.handlers, request) + } + + pub(crate) async fn run_pre_compact(&self, request: PreCompactRequest) -> PreCompactOutcome { + crate::events::compact::run_pre(&self.handlers, &self.shell, request).await + } + + pub(crate) fn preview_post_compact(&self, request: &PostCompactRequest) -> Vec { + crate::events::compact::preview_post(&self.handlers, request) + } + + pub(crate) async fn run_post_compact( + &self, + request: PostCompactRequest, + ) -> StatelessHookOutcome { + crate::events::compact::run_post(&self.handlers, &self.shell, request).await + } + pub(crate) fn preview_user_prompt_submit( &self, request: &UserPromptSubmitRequest, diff --git a/codex-rs/hooks/src/engine/output_parser.rs b/codex-rs/hooks/src/engine/output_parser.rs index 464c7f8608..3bccb10127 100644 --- a/codex-rs/hooks/src/engine/output_parser.rs +++ b/codex-rs/hooks/src/engine/output_parser.rs @@ -60,12 +60,26 @@ pub(crate) struct StopOutput { pub invalid_block_reason: Option, } +#[derive(Debug, Clone)] +pub(crate) struct PreCompactOutput { + pub universal: UniversalOutput, + pub invalid_reason: Option, +} + +#[derive(Debug, Clone)] +pub(crate) struct StatelessHookOutput { + pub universal: UniversalOutput, + pub invalid_reason: Option, +} + use crate::schema::BlockDecisionWire; use crate::schema::HookUniversalOutputWire; use crate::schema::PermissionRequestBehaviorWire; use crate::schema::PermissionRequestCommandOutputWire; use crate::schema::PermissionRequestDecisionWire; +use crate::schema::PostCompactCommandOutputWire; use crate::schema::PostToolUseCommandOutputWire; +use crate::schema::PreCompactCommandOutputWire; use crate::schema::PreToolUseCommandOutputWire; use crate::schema::PreToolUseDecisionWire; use crate::schema::PreToolUsePermissionDecisionWire; @@ -191,6 +205,24 @@ pub(crate) fn parse_post_tool_use(stdout: &str) -> Option { }) } +pub(crate) fn parse_pre_compact(stdout: &str) -> Option { + let wire: PreCompactCommandOutputWire = parse_json(stdout)?; + let universal = UniversalOutput::from(wire.universal); + Some(PreCompactOutput { + universal, + invalid_reason: None, + }) +} + +pub(crate) fn parse_post_compact(stdout: &str) -> Option { + let wire: PostCompactCommandOutputWire = parse_json(stdout)?; + let universal = UniversalOutput::from(wire.universal); + Some(StatelessHookOutput { + universal, + invalid_reason: None, + }) +} + pub(crate) fn parse_user_prompt_submit(stdout: &str) -> Option { let wire: UserPromptSubmitCommandOutputWire = parse_json(stdout)?; let should_block = matches!(wire.decision, Some(BlockDecisionWire::Block)); @@ -261,6 +293,11 @@ where serde_json::from_value(value).ok() } +pub(crate) fn looks_like_json(stdout: &str) -> bool { + let trimmed = stdout.trim_start(); + trimmed.starts_with('{') || trimmed.starts_with('[') +} + fn invalid_block_message(event_name: &str) -> String { format!("{event_name} hook returned decision:block without a non-empty reason") } diff --git a/codex-rs/hooks/src/engine/schema_loader.rs b/codex-rs/hooks/src/engine/schema_loader.rs index d8bdb141c2..704edea4ba 100644 --- a/codex-rs/hooks/src/engine/schema_loader.rs +++ b/codex-rs/hooks/src/engine/schema_loader.rs @@ -8,8 +8,12 @@ pub(crate) struct GeneratedHookSchemas { pub post_tool_use_command_output: Value, pub permission_request_command_input: Value, pub permission_request_command_output: Value, + pub post_compact_command_input: Value, + pub post_compact_command_output: Value, pub pre_tool_use_command_input: Value, pub pre_tool_use_command_output: Value, + pub pre_compact_command_input: Value, + pub pre_compact_command_output: Value, pub session_start_command_input: Value, pub session_start_command_output: Value, pub user_prompt_submit_command_input: Value, @@ -37,6 +41,14 @@ pub(crate) fn generated_hook_schemas() -> &'static GeneratedHookSchemas { "permission-request.command.output", include_str!("../../schema/generated/permission-request.command.output.schema.json"), ), + post_compact_command_input: parse_json_schema( + "post-compact.command.input", + include_str!("../../schema/generated/post-compact.command.input.schema.json"), + ), + post_compact_command_output: parse_json_schema( + "post-compact.command.output", + include_str!("../../schema/generated/post-compact.command.output.schema.json"), + ), pre_tool_use_command_input: parse_json_schema( "pre-tool-use.command.input", include_str!("../../schema/generated/pre-tool-use.command.input.schema.json"), @@ -45,6 +57,14 @@ pub(crate) fn generated_hook_schemas() -> &'static GeneratedHookSchemas { "pre-tool-use.command.output", include_str!("../../schema/generated/pre-tool-use.command.output.schema.json"), ), + pre_compact_command_input: parse_json_schema( + "pre-compact.command.input", + include_str!("../../schema/generated/pre-compact.command.input.schema.json"), + ), + pre_compact_command_output: parse_json_schema( + "pre-compact.command.output", + include_str!("../../schema/generated/pre-compact.command.output.schema.json"), + ), session_start_command_input: parse_json_schema( "session-start.command.input", include_str!("../../schema/generated/session-start.command.input.schema.json"), @@ -90,8 +110,12 @@ mod tests { assert_eq!(schemas.post_tool_use_command_output["type"], "object"); assert_eq!(schemas.permission_request_command_input["type"], "object"); assert_eq!(schemas.permission_request_command_output["type"], "object"); + assert_eq!(schemas.post_compact_command_input["type"], "object"); + assert_eq!(schemas.post_compact_command_output["type"], "object"); assert_eq!(schemas.pre_tool_use_command_input["type"], "object"); assert_eq!(schemas.pre_tool_use_command_output["type"], "object"); + assert_eq!(schemas.pre_compact_command_input["type"], "object"); + assert_eq!(schemas.pre_compact_command_output["type"], "object"); assert_eq!(schemas.session_start_command_input["type"], "object"); assert_eq!(schemas.session_start_command_output["type"], "object"); assert_eq!(schemas.user_prompt_submit_command_input["type"], "object"); diff --git a/codex-rs/hooks/src/events/common.rs b/codex-rs/hooks/src/events/common.rs index de3f3292ac..e79a139b79 100644 --- a/codex-rs/hooks/src/events/common.rs +++ b/codex-rs/hooks/src/events/common.rs @@ -103,7 +103,9 @@ pub(crate) fn matcher_pattern_for_event( HookEventName::PreToolUse | HookEventName::PermissionRequest | HookEventName::PostToolUse - | HookEventName::SessionStart => matcher, + | HookEventName::SessionStart + | HookEventName::PreCompact + | HookEventName::PostCompact => matcher, HookEventName::UserPromptSubmit | HookEventName::Stop => None, } } @@ -267,5 +269,13 @@ mod tests { matcher_pattern_for_event(HookEventName::SessionStart, Some("startup|resume")), Some("startup|resume") ); + assert_eq!( + matcher_pattern_for_event(HookEventName::PreCompact, Some("^auto$")), + Some("^auto$") + ); + assert_eq!( + matcher_pattern_for_event(HookEventName::PostCompact, Some("manual|auto")), + Some("manual|auto") + ); } } diff --git a/codex-rs/hooks/src/events/compact.rs b/codex-rs/hooks/src/events/compact.rs new file mode 100644 index 0000000000..67c13c34eb --- /dev/null +++ b/codex-rs/hooks/src/events/compact.rs @@ -0,0 +1,608 @@ +use std::path::PathBuf; + +use codex_protocol::ThreadId; +use codex_protocol::protocol::HookCompletedEvent; +use codex_protocol::protocol::HookEventName; +use codex_protocol::protocol::HookOutputEntry; +use codex_protocol::protocol::HookOutputEntryKind; +use codex_protocol::protocol::HookRunStatus; +use codex_protocol::protocol::HookRunSummary; +use codex_utils_absolute_path::AbsolutePathBuf; + +use super::common; +use crate::engine::CommandShell; +use crate::engine::ConfiguredHandler; +use crate::engine::command_runner::CommandRunResult; +use crate::engine::dispatcher; +use crate::engine::output_parser; +use crate::schema::PostCompactCommandInput; +use crate::schema::PreCompactCommandInput; + +#[derive(Debug, Clone)] +pub struct PreCompactRequest { + pub session_id: ThreadId, + pub turn_id: String, + pub cwd: AbsolutePathBuf, + pub transcript_path: Option, + pub model: String, + pub trigger: String, +} + +#[derive(Debug, Clone)] +pub struct PostCompactRequest { + pub session_id: ThreadId, + pub turn_id: String, + pub cwd: AbsolutePathBuf, + pub transcript_path: Option, + pub model: String, + pub trigger: String, +} + +#[derive(Debug)] +pub struct StatelessHookOutcome { + pub hook_events: Vec, + pub should_stop: bool, + pub stop_reason: Option, +} + +#[derive(Debug)] +pub struct PreCompactOutcome { + pub hook_events: Vec, + pub should_stop: bool, + pub stop_reason: Option, +} + +pub(crate) fn preview_pre( + handlers: &[ConfiguredHandler], + request: &PreCompactRequest, +) -> Vec { + dispatcher::select_handlers( + handlers, + HookEventName::PreCompact, + Some(request.trigger.as_str()), + ) + .into_iter() + .map(|handler| dispatcher::running_summary(&handler)) + .collect() +} + +pub(crate) async fn run_pre( + handlers: &[ConfiguredHandler], + shell: &CommandShell, + request: PreCompactRequest, +) -> PreCompactOutcome { + let matched = dispatcher::select_handlers( + handlers, + HookEventName::PreCompact, + Some(request.trigger.as_str()), + ); + if matched.is_empty() { + return PreCompactOutcome { + hook_events: Vec::new(), + should_stop: false, + stop_reason: None, + }; + } + + let input_json = match pre_command_input_json(&request) { + Ok(input_json) => input_json, + Err(error) => { + return PreCompactOutcome { + hook_events: common::serialization_failure_hook_events( + matched, + Some(request.turn_id), + format!("failed to serialize pre compact hook input: {error}"), + ), + should_stop: false, + stop_reason: None, + }; + } + }; + + let results = dispatcher::execute_handlers( + shell, + matched, + input_json, + request.cwd.as_path(), + Some(request.turn_id), + parse_pre_completed, + ) + .await; + let should_stop = results.iter().any(|result| result.data.should_stop); + let stop_reason = results + .iter() + .find_map(|result| result.data.stop_reason.clone()); + PreCompactOutcome { + hook_events: results.into_iter().map(|result| result.completed).collect(), + should_stop, + stop_reason, + } +} + +fn pre_command_input_json(request: &PreCompactRequest) -> Result { + serde_json::to_string(&PreCompactCommandInput { + session_id: request.session_id.to_string(), + turn_id: request.turn_id.clone(), + transcript_path: crate::schema::NullableString::from_path(request.transcript_path.clone()), + cwd: request.cwd.display().to_string(), + hook_event_name: "PreCompact".to_string(), + model: request.model.clone(), + trigger: request.trigger.clone(), + }) +} + +pub(crate) fn preview_post( + handlers: &[ConfiguredHandler], + request: &PostCompactRequest, +) -> Vec { + dispatcher::select_handlers( + handlers, + HookEventName::PostCompact, + Some(request.trigger.as_str()), + ) + .into_iter() + .map(|handler| dispatcher::running_summary(&handler)) + .collect() +} + +pub(crate) async fn run_post( + handlers: &[ConfiguredHandler], + shell: &CommandShell, + request: PostCompactRequest, +) -> StatelessHookOutcome { + let matched = dispatcher::select_handlers( + handlers, + HookEventName::PostCompact, + Some(request.trigger.as_str()), + ); + if matched.is_empty() { + return StatelessHookOutcome { + hook_events: Vec::new(), + should_stop: false, + stop_reason: None, + }; + } + + let input_json = match post_command_input_json(&request) { + Ok(input_json) => input_json, + Err(error) => { + return StatelessHookOutcome { + hook_events: common::serialization_failure_hook_events( + matched, + Some(request.turn_id), + format!("failed to serialize post compact hook input: {error}"), + ), + should_stop: false, + stop_reason: None, + }; + } + }; + + let results = dispatcher::execute_handlers( + shell, + matched, + input_json, + request.cwd.as_path(), + Some(request.turn_id), + parse_post_completed, + ) + .await; + let should_stop = results.iter().any(|result| result.data.should_stop); + let stop_reason = results + .iter() + .find_map(|result| result.data.stop_reason.clone()); + StatelessHookOutcome { + hook_events: results.into_iter().map(|result| result.completed).collect(), + should_stop, + stop_reason, + } +} + +fn post_command_input_json(request: &PostCompactRequest) -> Result { + serde_json::to_string(&PostCompactCommandInput { + session_id: request.session_id.to_string(), + turn_id: request.turn_id.clone(), + transcript_path: crate::schema::NullableString::from_path(request.transcript_path.clone()), + cwd: request.cwd.display().to_string(), + hook_event_name: "PostCompact".to_string(), + model: request.model.clone(), + trigger: request.trigger.clone(), + }) +} + +#[derive(Default)] +struct CompactHandlerData { + should_stop: bool, + stop_reason: Option, +} + +fn parse_pre_completed( + handler: &ConfiguredHandler, + run_result: CommandRunResult, + turn_id: Option, +) -> dispatcher::ParsedHandler { + let mut entries = Vec::new(); + let mut status = HookRunStatus::Completed; + let mut should_stop = false; + let mut stop_reason = None; + + match run_result.error.as_deref() { + Some(error) => { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: error.to_string(), + }); + } + None => match run_result.exit_code { + Some(0) => { + let trimmed_stdout = run_result.stdout.trim(); + if trimmed_stdout.is_empty() { + } else if let Some(parsed) = output_parser::parse_pre_compact(&run_result.stdout) { + if let Some(system_message) = parsed.universal.system_message { + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Warning, + text: system_message, + }); + } + let _ = parsed.universal.suppress_output; + if !parsed.universal.continue_processing { + status = HookRunStatus::Stopped; + should_stop = true; + stop_reason = parsed.universal.stop_reason.clone(); + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Stop, + text: parsed + .universal + .stop_reason + .unwrap_or_else(|| "PreCompact hook stopped execution".to_string()), + }); + } else if let Some(invalid_reason) = parsed.invalid_reason { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: invalid_reason, + }); + } + } else if output_parser::looks_like_json(&run_result.stdout) { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: "hook returned invalid PreCompact hook JSON output".to_string(), + }); + } + } + Some(code) => { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: common::trimmed_non_empty(&run_result.stderr) + .unwrap_or_else(|| format!("hook exited with code {code}")), + }); + } + None => { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: "hook process terminated without an exit code".to_string(), + }); + } + }, + } + + dispatcher::ParsedHandler { + completed: HookCompletedEvent { + turn_id, + run: dispatcher::completed_summary(handler, &run_result, status, entries), + }, + data: CompactHandlerData { + should_stop, + stop_reason, + }, + } +} + +fn parse_post_completed( + handler: &ConfiguredHandler, + run_result: CommandRunResult, + turn_id: Option, +) -> dispatcher::ParsedHandler { + parse_completed( + handler, + run_result, + turn_id, + "PostCompact", + output_parser::parse_post_compact, + ) +} + +fn parse_completed( + handler: &ConfiguredHandler, + run_result: CommandRunResult, + turn_id: Option, + event_label: &'static str, + parse_output: fn(&str) -> Option, +) -> dispatcher::ParsedHandler { + let mut entries = Vec::new(); + let mut status = HookRunStatus::Completed; + let mut should_stop = false; + let mut stop_reason = None; + + match run_result.error.as_deref() { + Some(error) => { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: error.to_string(), + }); + } + None => match run_result.exit_code { + Some(0) => { + let trimmed_stdout = run_result.stdout.trim(); + if trimmed_stdout.is_empty() { + } else if let Some(parsed) = parse_output(&run_result.stdout) { + if let Some(system_message) = parsed.universal.system_message { + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Warning, + text: system_message, + }); + } + let _ = parsed.universal.suppress_output; + if !parsed.universal.continue_processing { + status = HookRunStatus::Stopped; + should_stop = true; + stop_reason = parsed.universal.stop_reason.clone(); + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Stop, + text: parsed + .universal + .stop_reason + .unwrap_or_else(|| format!("{event_label} hook stopped execution")), + }); + } else if let Some(invalid_reason) = parsed.invalid_reason { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: invalid_reason, + }); + } + } else if output_parser::looks_like_json(&run_result.stdout) { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: format!("hook returned invalid {event_label} hook JSON output"), + }); + } + } + Some(code) => { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: common::trimmed_non_empty(&run_result.stderr) + .unwrap_or_else(|| format!("hook exited with code {code}")), + }); + } + None => { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: "hook process terminated without an exit code".to_string(), + }); + } + }, + } + + dispatcher::ParsedHandler { + completed: HookCompletedEvent { + turn_id, + run: dispatcher::completed_summary(handler, &run_result, status, entries), + }, + data: CompactHandlerData { + should_stop, + stop_reason, + }, + } +} + +#[cfg(test)] +mod tests { + use codex_protocol::ThreadId; + use codex_protocol::protocol::HookEventName; + use codex_protocol::protocol::HookOutputEntry; + use codex_protocol::protocol::HookOutputEntryKind; + use codex_protocol::protocol::HookRunStatus; + use codex_utils_absolute_path::test_support::PathBufExt; + use codex_utils_absolute_path::test_support::test_path_buf; + use pretty_assertions::assert_eq; + use serde_json::json; + + use super::parse_post_completed; + use super::parse_pre_completed; + use super::post_command_input_json; + use super::pre_command_input_json; + use crate::engine::ConfiguredHandler; + use crate::engine::command_runner::CommandRunResult; + + #[test] + fn pre_compact_input_includes_lifecycle_metadata() { + let input_json = pre_command_input_json(&pre_request()).expect("serialize command input"); + let input: serde_json::Value = + serde_json::from_str(&input_json).expect("parse command input"); + + assert_eq!( + input, + json!({ + "session_id": pre_request().session_id.to_string(), + "turn_id": "turn-1", + "transcript_path": null, + "cwd": test_path_buf("/tmp").display().to_string(), + "hook_event_name": "PreCompact", + "model": "gpt-test", + "trigger": "manual", + }) + ); + } + + #[test] + fn post_compact_input_includes_lifecycle_metadata() { + let input_json = post_command_input_json(&post_request()).expect("serialize command input"); + let input: serde_json::Value = + serde_json::from_str(&input_json).expect("parse command input"); + + assert_eq!( + input, + json!({ + "session_id": post_request().session_id.to_string(), + "turn_id": "turn-1", + "transcript_path": null, + "cwd": test_path_buf("/tmp").display().to_string(), + "hook_event_name": "PostCompact", + "model": "gpt-test", + "trigger": "manual", + }) + ); + } + + #[test] + fn block_decision_is_not_supported_for_pre_compact() { + let parsed = parse_pre_completed( + &handler(HookEventName::PreCompact), + run_result( + Some(0), + r#"{"decision":"block","reason":"policy blocked compaction"}"#, + "", + ), + Some("turn-1".to_string()), + ); + + assert_eq!(parsed.completed.run.status, HookRunStatus::Failed); + assert_eq!( + parsed.completed.run.entries, + vec![HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: "hook returned invalid PreCompact hook JSON output".to_string(), + }] + ); + } + + #[test] + fn continue_false_stops_before_compaction() { + let parsed = parse_pre_completed( + &handler(HookEventName::PreCompact), + run_result(Some(0), r#"{"continue":false,"stopReason":"nope"}"#, ""), + Some("turn-1".to_string()), + ); + + assert_eq!(parsed.completed.run.status, HookRunStatus::Stopped); + assert_eq!(parsed.data.should_stop, true); + assert_eq!(parsed.data.stop_reason, Some("nope".to_string())); + assert_eq!( + parsed.completed.run.entries, + vec![HookOutputEntry { + kind: HookOutputEntryKind::Stop, + text: "nope".to_string(), + }] + ); + } + + #[test] + fn post_compact_continue_false_stops_after_compaction() { + let parsed = parse_post_completed( + &handler(HookEventName::PostCompact), + run_result( + Some(0), + r#"{"continue":false,"stopReason":"pause after compact"}"#, + "", + ), + Some("turn-1".to_string()), + ); + + assert_eq!(parsed.completed.run.status, HookRunStatus::Stopped); + assert_eq!(parsed.data.should_stop, true); + assert_eq!( + parsed.data.stop_reason, + Some("pause after compact".to_string()) + ); + assert_eq!( + parsed.completed.run.entries, + vec![HookOutputEntry { + kind: HookOutputEntryKind::Stop, + text: "pause after compact".to_string(), + }] + ); + } + + #[test] + fn pre_compact_ignores_plain_stdout() { + let parsed = parse_pre_completed( + &handler(HookEventName::PreCompact), + run_result(Some(0), "checking compact policy\n", ""), + Some("turn-1".to_string()), + ); + + assert_eq!(parsed.completed.run.status, HookRunStatus::Completed); + assert_eq!(parsed.completed.run.entries, Vec::new()); + } + + #[test] + fn post_compact_ignores_plain_stdout() { + let parsed = parse_post_completed( + &handler(HookEventName::PostCompact), + run_result(Some(0), "logged compact summary\n", ""), + Some("turn-1".to_string()), + ); + + assert_eq!(parsed.completed.run.status, HookRunStatus::Completed); + assert_eq!(parsed.completed.run.entries, Vec::new()); + } + + fn pre_request() -> super::PreCompactRequest { + super::PreCompactRequest { + session_id: ThreadId::from_string("00000000-0000-4000-8000-000000000001") + .expect("valid thread id"), + turn_id: "turn-1".to_string(), + cwd: test_path_buf("/tmp").abs(), + transcript_path: None, + model: "gpt-test".to_string(), + trigger: "manual".to_string(), + } + } + + fn post_request() -> super::PostCompactRequest { + super::PostCompactRequest { + session_id: ThreadId::from_string("00000000-0000-4000-8000-000000000002") + .expect("valid thread id"), + turn_id: "turn-1".to_string(), + cwd: test_path_buf("/tmp").abs(), + transcript_path: None, + model: "gpt-test".to_string(), + trigger: "manual".to_string(), + } + } + + fn handler(event_name: HookEventName) -> ConfiguredHandler { + ConfiguredHandler { + event_name, + matcher: None, + command: "python3 compact_hook.py".to_string(), + timeout_sec: 5, + status_message: Some("running compact hook".to_string()), + source_path: test_path_buf("/tmp/hooks.json").abs(), + source: codex_protocol::protocol::HookSource::User, + display_order: 0, + env: std::collections::HashMap::new(), + } + } + + fn run_result(exit_code: Option, stdout: &str, stderr: &str) -> CommandRunResult { + CommandRunResult { + started_at: 1_700_000_000, + completed_at: 1_700_000_001, + duration_ms: 12, + exit_code, + stdout: stdout.to_string(), + stderr: stderr.to_string(), + error: None, + } + } +} diff --git a/codex-rs/hooks/src/events/mod.rs b/codex-rs/hooks/src/events/mod.rs index 52148324e2..5ec24462b9 100644 --- a/codex-rs/hooks/src/events/mod.rs +++ b/codex-rs/hooks/src/events/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod common; +pub mod compact; pub mod permission_request; pub mod post_tool_use; pub mod pre_tool_use; diff --git a/codex-rs/hooks/src/events/permission_request.rs b/codex-rs/hooks/src/events/permission_request.rs index 2cebd0e002..11ab4d2e47 100644 --- a/codex-rs/hooks/src/events/permission_request.rs +++ b/codex-rs/hooks/src/events/permission_request.rs @@ -232,7 +232,7 @@ fn parse_completed( } } } - } else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') { + } else if output_parser::looks_like_json(&run_result.stdout) { status = HookRunStatus::Failed; entries.push(HookOutputEntry { kind: HookOutputEntryKind::Error, diff --git a/codex-rs/hooks/src/events/post_tool_use.rs b/codex-rs/hooks/src/events/post_tool_use.rs index 63045ef425..223efa7260 100644 --- a/codex-rs/hooks/src/events/post_tool_use.rs +++ b/codex-rs/hooks/src/events/post_tool_use.rs @@ -245,7 +245,7 @@ fn parse_completed( feedback_messages_for_model.push(reason); } } - } else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') { + } else if output_parser::looks_like_json(&run_result.stdout) { status = HookRunStatus::Failed; entries.push(HookOutputEntry { kind: HookOutputEntryKind::Error, diff --git a/codex-rs/hooks/src/events/pre_tool_use.rs b/codex-rs/hooks/src/events/pre_tool_use.rs index 39d0e61258..77e6d3f3fa 100644 --- a/codex-rs/hooks/src/events/pre_tool_use.rs +++ b/codex-rs/hooks/src/events/pre_tool_use.rs @@ -205,7 +205,7 @@ fn parse_completed( }); } } - } else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') { + } else if output_parser::looks_like_json(&run_result.stdout) { status = HookRunStatus::Failed; entries.push(HookOutputEntry { kind: HookOutputEntryKind::Error, diff --git a/codex-rs/hooks/src/events/session_start.rs b/codex-rs/hooks/src/events/session_start.rs index f064f67b20..195bb11257 100644 --- a/codex-rs/hooks/src/events/session_start.rs +++ b/codex-rs/hooks/src/events/session_start.rs @@ -190,7 +190,7 @@ fn parse_completed( } } // Preserve plain-text context support without treating malformed JSON as context. - } else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') { + } else if output_parser::looks_like_json(&run_result.stdout) { status = HookRunStatus::Failed; entries.push(HookOutputEntry { kind: HookOutputEntryKind::Error, diff --git a/codex-rs/hooks/src/events/user_prompt_submit.rs b/codex-rs/hooks/src/events/user_prompt_submit.rs index a04711eb40..a10798ea62 100644 --- a/codex-rs/hooks/src/events/user_prompt_submit.rs +++ b/codex-rs/hooks/src/events/user_prompt_submit.rs @@ -194,7 +194,7 @@ fn parse_completed( }); } } - } else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') { + } else if output_parser::looks_like_json(&run_result.stdout) { status = HookRunStatus::Failed; entries.push(HookOutputEntry { kind: HookOutputEntryKind::Error, diff --git a/codex-rs/hooks/src/lib.rs b/codex-rs/hooks/src/lib.rs index ad627b497a..6c4c672bca 100644 --- a/codex-rs/hooks/src/lib.rs +++ b/codex-rs/hooks/src/lib.rs @@ -9,10 +9,12 @@ mod types; pub use engine::HookListEntry; /// Hook event names as they appear in hooks JSON and config files. -pub const HOOK_EVENT_NAMES: [&str; 6] = [ +pub const HOOK_EVENT_NAMES: [&str; 8] = [ "PreToolUse", "PermissionRequest", "PostToolUse", + "PreCompact", + "PostCompact", "SessionStart", "UserPromptSubmit", "Stop", @@ -21,14 +23,21 @@ pub const HOOK_EVENT_NAMES: [&str; 6] = [ /// Hook event names whose matcher fields are meaningful during dispatch. /// /// Other events can appear in hooks JSON, but Codex ignores their matcher -/// fields because those events do not dispatch against a tool or session-start -/// source. -pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 4] = [ +/// fields because those events do not dispatch against a tool, compaction +/// trigger, or session-start source. +pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 6] = [ "PreToolUse", "PermissionRequest", "PostToolUse", + "PreCompact", + "PostCompact", "SessionStart", ]; + +pub use events::compact::PostCompactRequest; +pub use events::compact::PreCompactOutcome; +pub use events::compact::PreCompactRequest; +pub use events::compact::StatelessHookOutcome; pub use events::permission_request::PermissionRequestDecision; pub use events::permission_request::PermissionRequestOutcome; pub use events::permission_request::PermissionRequestRequest; diff --git a/codex-rs/hooks/src/registry.rs b/codex-rs/hooks/src/registry.rs index ae80015729..74c9a84539 100644 --- a/codex-rs/hooks/src/registry.rs +++ b/codex-rs/hooks/src/registry.rs @@ -5,6 +5,10 @@ use tokio::process::Command; use crate::engine::ClaudeHooksEngine; use crate::engine::CommandShell; use crate::engine::HookListEntry; +use crate::events::compact::PostCompactRequest; +use crate::events::compact::PreCompactOutcome; +use crate::events::compact::PreCompactRequest; +use crate::events::compact::StatelessHookOutcome; use crate::events::permission_request::PermissionRequestOutcome; use crate::events::permission_request::PermissionRequestRequest; use crate::events::post_tool_use::PostToolUseOutcome; @@ -154,6 +158,28 @@ impl Hooks { self.engine.run_post_tool_use(request).await } + pub fn preview_pre_compact( + &self, + request: &PreCompactRequest, + ) -> Vec { + self.engine.preview_pre_compact(request) + } + + pub async fn run_pre_compact(&self, request: PreCompactRequest) -> PreCompactOutcome { + self.engine.run_pre_compact(request).await + } + + pub fn preview_post_compact( + &self, + request: &PostCompactRequest, + ) -> Vec { + self.engine.preview_post_compact(request) + } + + pub async fn run_post_compact(&self, request: PostCompactRequest) -> StatelessHookOutcome { + self.engine.run_post_compact(request).await + } + pub fn preview_user_prompt_submit( &self, request: &UserPromptSubmitRequest, diff --git a/codex-rs/hooks/src/schema.rs b/codex-rs/hooks/src/schema.rs index d08cce6ee2..d4f408d8c3 100644 --- a/codex-rs/hooks/src/schema.rs +++ b/codex-rs/hooks/src/schema.rs @@ -17,8 +17,12 @@ const POST_TOOL_USE_INPUT_FIXTURE: &str = "post-tool-use.command.input.schema.js const POST_TOOL_USE_OUTPUT_FIXTURE: &str = "post-tool-use.command.output.schema.json"; const PERMISSION_REQUEST_INPUT_FIXTURE: &str = "permission-request.command.input.schema.json"; const PERMISSION_REQUEST_OUTPUT_FIXTURE: &str = "permission-request.command.output.schema.json"; +const POST_COMPACT_INPUT_FIXTURE: &str = "post-compact.command.input.schema.json"; +const POST_COMPACT_OUTPUT_FIXTURE: &str = "post-compact.command.output.schema.json"; const PRE_TOOL_USE_INPUT_FIXTURE: &str = "pre-tool-use.command.input.schema.json"; const PRE_TOOL_USE_OUTPUT_FIXTURE: &str = "pre-tool-use.command.output.schema.json"; +const PRE_COMPACT_INPUT_FIXTURE: &str = "pre-compact.command.input.schema.json"; +const PRE_COMPACT_OUTPUT_FIXTURE: &str = "pre-compact.command.output.schema.json"; const SESSION_START_INPUT_FIXTURE: &str = "session-start.command.input.schema.json"; const SESSION_START_OUTPUT_FIXTURE: &str = "session-start.command.output.schema.json"; const USER_PROMPT_SUBMIT_INPUT_FIXTURE: &str = "user-prompt-submit.command.input.schema.json"; @@ -75,6 +79,10 @@ pub(crate) enum HookEventNameWire { PermissionRequest, #[serde(rename = "PostToolUse")] PostToolUse, + #[serde(rename = "PreCompact")] + PreCompact, + #[serde(rename = "PostCompact")] + PostCompact, #[serde(rename = "SessionStart")] SessionStart, #[serde(rename = "UserPromptSubmit")] @@ -124,6 +132,24 @@ pub(crate) struct PermissionRequestCommandOutputWire { pub hook_specific_output: Option, } +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +#[serde(deny_unknown_fields)] +#[schemars(rename = "pre-compact.command.output")] +pub(crate) struct PreCompactCommandOutputWire { + #[serde(flatten)] + pub universal: HookUniversalOutputWire, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +#[serde(deny_unknown_fields)] +#[schemars(rename = "post-compact.command.output")] +pub(crate) struct PostCompactCommandOutputWire { + #[serde(flatten)] + pub universal: HookUniversalOutputWire, +} + #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] @@ -267,6 +293,38 @@ pub(crate) struct PostToolUseCommandInput { pub tool_use_id: String, } +#[derive(Debug, Clone, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(rename = "pre-compact.command.input")] +pub(crate) struct PreCompactCommandInput { + pub session_id: String, + /// Codex extension: expose the active turn id to internal turn-scoped hooks. + pub turn_id: String, + pub transcript_path: NullableString, + pub cwd: String, + #[schemars(schema_with = "pre_compact_hook_event_name_schema")] + pub hook_event_name: String, + pub model: String, + #[schemars(schema_with = "compaction_trigger_schema")] + pub trigger: String, +} + +#[derive(Debug, Clone, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(rename = "post-compact.command.input")] +pub(crate) struct PostCompactCommandInput { + pub session_id: String, + /// Codex extension: expose the active turn id to internal turn-scoped hooks. + pub turn_id: String, + pub transcript_path: NullableString, + pub cwd: String, + #[schemars(schema_with = "post_compact_hook_event_name_schema")] + pub hook_event_name: String, + pub model: String, + #[schemars(schema_with = "compaction_trigger_schema")] + pub trigger: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] @@ -424,6 +482,22 @@ pub fn write_schema_fixtures(schema_root: &Path) -> anyhow::Result<()> { &generated_dir.join(PERMISSION_REQUEST_OUTPUT_FIXTURE), schema_json::()?, )?; + write_schema( + &generated_dir.join(POST_COMPACT_INPUT_FIXTURE), + schema_json::()?, + )?; + write_schema( + &generated_dir.join(POST_COMPACT_OUTPUT_FIXTURE), + schema_json::()?, + )?; + write_schema( + &generated_dir.join(PRE_COMPACT_INPUT_FIXTURE), + schema_json::()?, + )?; + write_schema( + &generated_dir.join(PRE_COMPACT_OUTPUT_FIXTURE), + schema_json::()?, + )?; write_schema( &generated_dir.join(PRE_TOOL_USE_INPUT_FIXTURE), schema_json::()?, @@ -519,6 +593,14 @@ fn post_tool_use_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema { string_const_schema("PostToolUse") } +fn pre_compact_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema { + string_const_schema("PreCompact") +} + +fn post_compact_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema { + string_const_schema("PostCompact") +} + fn pre_tool_use_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema { string_const_schema("PreToolUse") } @@ -549,6 +631,10 @@ fn session_start_source_schema(_gen: &mut SchemaGenerator) -> Schema { string_enum_schema(&["startup", "resume", "clear"]) } +fn compaction_trigger_schema(_gen: &mut SchemaGenerator) -> Schema { + string_enum_schema(&["manual", "auto"]) +} + fn string_const_schema(value: &str) -> Schema { let mut schema = SchemaObject { instance_type: Some(InstanceType::String.into()), @@ -580,12 +666,18 @@ fn default_continue() -> bool { mod tests { use super::PERMISSION_REQUEST_INPUT_FIXTURE; use super::PERMISSION_REQUEST_OUTPUT_FIXTURE; + use super::POST_COMPACT_INPUT_FIXTURE; + use super::POST_COMPACT_OUTPUT_FIXTURE; use super::POST_TOOL_USE_INPUT_FIXTURE; use super::POST_TOOL_USE_OUTPUT_FIXTURE; + use super::PRE_COMPACT_INPUT_FIXTURE; + use super::PRE_COMPACT_OUTPUT_FIXTURE; use super::PRE_TOOL_USE_INPUT_FIXTURE; use super::PRE_TOOL_USE_OUTPUT_FIXTURE; use super::PermissionRequestCommandInput; + use super::PostCompactCommandInput; use super::PostToolUseCommandInput; + use super::PreCompactCommandInput; use super::PreToolUseCommandInput; use super::SESSION_START_INPUT_FIXTURE; use super::SESSION_START_OUTPUT_FIXTURE; @@ -615,6 +707,18 @@ mod tests { PERMISSION_REQUEST_OUTPUT_FIXTURE => { include_str!("../schema/generated/permission-request.command.output.schema.json") } + POST_COMPACT_INPUT_FIXTURE => { + include_str!("../schema/generated/post-compact.command.input.schema.json") + } + POST_COMPACT_OUTPUT_FIXTURE => { + include_str!("../schema/generated/post-compact.command.output.schema.json") + } + PRE_COMPACT_INPUT_FIXTURE => { + include_str!("../schema/generated/pre-compact.command.input.schema.json") + } + PRE_COMPACT_OUTPUT_FIXTURE => { + include_str!("../schema/generated/pre-compact.command.output.schema.json") + } PRE_TOOL_USE_INPUT_FIXTURE => { include_str!("../schema/generated/pre-tool-use.command.input.schema.json") } @@ -658,6 +762,10 @@ mod tests { POST_TOOL_USE_OUTPUT_FIXTURE, PERMISSION_REQUEST_INPUT_FIXTURE, PERMISSION_REQUEST_OUTPUT_FIXTURE, + POST_COMPACT_INPUT_FIXTURE, + POST_COMPACT_OUTPUT_FIXTURE, + PRE_COMPACT_INPUT_FIXTURE, + PRE_COMPACT_OUTPUT_FIXTURE, PRE_TOOL_USE_INPUT_FIXTURE, PRE_TOOL_USE_OUTPUT_FIXTURE, SESSION_START_INPUT_FIXTURE, @@ -688,6 +796,14 @@ mod tests { .expect("serialize post tool use input schema"), ) .expect("parse post tool use input schema"); + let pre_compact: Value = serde_json::from_slice( + &schema_json::().expect("serialize pre compact input schema"), + ) + .expect("parse pre compact input schema"); + let post_compact: Value = serde_json::from_slice( + &schema_json::().expect("serialize post compact input schema"), + ) + .expect("parse post compact input schema"); let permission_request: Value = serde_json::from_slice( &schema_json::() .expect("serialize permission request input schema"), @@ -707,6 +823,8 @@ mod tests { &pre_tool_use, &permission_request, &post_tool_use, + &pre_compact, + &post_compact, &user_prompt_submit, &stop, ] { diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index 00611b3a8c..b462022dbc 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -362,6 +362,7 @@ async fn run_codex_tool_session_inner( | EventMsg::AgentMessageContentDelta(_) | EventMsg::ReasoningContentDelta(_) | EventMsg::ReasoningRawContentDelta(_) + | EventMsg::SkillsUpdateAvailable | EventMsg::ExitedReviewMode(_) | EventMsg::RequestUserInput(_) | EventMsg::RequestPermissions(_) diff --git a/codex-rs/mcp-server/src/lib.rs b/codex-rs/mcp-server/src/lib.rs index 2fd94e586a..d86f67522a 100644 --- a/codex-rs/mcp-server/src/lib.rs +++ b/codex-rs/mcp-server/src/lib.rs @@ -84,6 +84,7 @@ pub async fn run_main( std::io::Error::new(ErrorKind::InvalidData, format!("error loading config: {e}")) })?; set_default_client_residency_requirement(config.enforce_residency.value()); + let state_db = codex_core::init_state_db(&config).await; let otel = codex_core::otel_init::build_provider( &config, @@ -141,19 +142,16 @@ pub async fn run_main( // Task: process incoming messages. let processor_handle = tokio::spawn({ let outgoing_message_sender = OutgoingMessageSender::new(outgoing_tx); - let processor = MessageProcessor::new( + let mut processor = MessageProcessor::new( outgoing_message_sender, arg0_paths, Arc::new(config), environment_manager, + state_db, installation_id, ) .await; async move { - let Some(mut processor) = processor else { - error!("failed to initialize MCP processor"); - return; - }; while let Some(msg) = incoming_rx.recv().await { match msg { JsonRpcMessage::Request(r) => processor.process_request(r).await, diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index 73cdb6193b..d64fc43b1b 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -2,10 +2,9 @@ use std::collections::HashMap; use std::sync::Arc; use codex_arg0::Arg0DispatchPaths; +use codex_core::StateDbHandle; use codex_core::ThreadManager; -use codex_core::agent_graph_store_from_state_db; use codex_core::config::Config; -use codex_core::init_state_db_from_config; use codex_core::thread_store_from_config; use codex_exec_server::EnvironmentManager; use codex_login::AuthManager; @@ -55,35 +54,32 @@ impl MessageProcessor { arg0_paths: Arg0DispatchPaths, config: Arc, environment_manager: Arc, + state_db: Option, installation_id: String, - ) -> Option { + ) -> Self { let outgoing = Arc::new(outgoing); let auth_manager = AuthManager::shared_from_config( config.as_ref(), /*enable_codex_api_key_env*/ false, ) .await; - let state_db = init_state_db_from_config(config.as_ref()).await?; - let thread_store = thread_store_from_config(config.as_ref(), state_db.clone()); - let agent_graph_store = agent_graph_store_from_state_db(state_db.clone()); let thread_manager = Arc::new(ThreadManager::new( config.as_ref(), auth_manager, SessionSource::Mcp, environment_manager, /*analytics_events_client*/ None, - state_db, - thread_store, - agent_graph_store, + thread_store_from_config(config.as_ref(), state_db.clone()), + state_db.clone(), installation_id, )); - Some(Self { + Self { outgoing, initialized: false, arg0_paths, thread_manager, running_requests_id_to_codex_uuid: Arc::new(Mutex::new(HashMap::new())), - }) + } } pub(crate) async fn process_request(&mut self, request: JsonRpcRequest) { diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 5c8f268e2c..30e33abe43 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -1401,6 +1401,9 @@ pub enum EventMsg { /// List of voices supported by realtime conversation streams. RealtimeConversationListVoicesResponse(RealtimeConversationListVoicesResponseEvent), + /// Notification that skill data may have been updated and clients may want to reload. + SkillsUpdateAvailable, + PlanUpdate(UpdatePlanArgs), TurnAborted(TurnAbortedEvent), @@ -1454,6 +1457,8 @@ pub enum HookEventName { PreToolUse, PermissionRequest, PostToolUse, + PreCompact, + PostCompact, SessionStart, UserPromptSubmit, Stop, diff --git a/codex-rs/rollout-trace/src/protocol_event.rs b/codex-rs/rollout-trace/src/protocol_event.rs index 1e49c82be2..3d52798b8d 100644 --- a/codex-rs/rollout-trace/src/protocol_event.rs +++ b/codex-rs/rollout-trace/src/protocol_event.rs @@ -260,6 +260,7 @@ pub(crate) fn tool_runtime_trace_event(event: &EventMsg) -> Option Option<&'static s | EventMsg::PatchApplyEnd(_) | EventMsg::TurnDiff(_) | EventMsg::RealtimeConversationListVoicesResponse(_) + | EventMsg::SkillsUpdateAvailable | EventMsg::PlanUpdate(_) | EventMsg::EnteredReviewMode(_) | EventMsg::ExitedReviewMode(_) diff --git a/codex-rs/rollout/src/policy.rs b/codex-rs/rollout/src/policy.rs index 21b98b4e8d..558c3fef98 100644 --- a/codex-rs/rollout/src/policy.rs +++ b/codex-rs/rollout/src/policy.rs @@ -169,6 +169,7 @@ fn event_msg_persistence_mode(ev: &EventMsg) -> Option { | EventMsg::ReasoningContentDelta(_) | EventMsg::ReasoningRawContentDelta(_) | EventMsg::ImageGenerationBegin(_) + | EventMsg::SkillsUpdateAvailable | EventMsg::CollabAgentSpawnBegin(_) | EventMsg::CollabAgentInteractionBegin(_) | EventMsg::CollabWaitingBegin(_) diff --git a/codex-rs/thread-manager-sample/src/main.rs b/codex-rs/thread-manager-sample/src/main.rs index 4ad937f9af..6817f677e6 100644 --- a/codex-rs/thread-manager-sample/src/main.rs +++ b/codex-rs/thread-manager-sample/src/main.rs @@ -52,11 +52,10 @@ use codex_core_api::TuiNotificationSettings; use codex_core_api::UriBasedFileOpener; use codex_core_api::UserInput; use codex_core_api::WebSearchMode; -use codex_core_api::agent_graph_store_from_state_db; use codex_core_api::arg0_dispatch_or_else; use codex_core_api::built_in_model_providers; use codex_core_api::find_codex_home; -use codex_core_api::init_state_db_from_config; +use codex_core_api::init_state_db; use codex_core_api::item_event_to_server_notification; use codex_core_api::resolve_installation_id; use codex_core_api::set_default_originator; @@ -106,6 +105,7 @@ async fn run_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { }; let config = new_config(args.model, arg0_paths)?; + let state_db = init_state_db(&config).await; let auth_manager = AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await; @@ -113,11 +113,7 @@ async fn run_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { config.codex_self_exe.clone(), config.codex_linux_sandbox_exe.clone(), )?; - let Some(state_db) = init_state_db_from_config(&config).await else { - bail!("thread manager sample requires state db"); - }; let thread_store = thread_store_from_config(&config, state_db.clone()); - let agent_graph_store = agent_graph_store_from_state_db(state_db.clone()); let environment_manager = Arc::new(EnvironmentManager::new(EnvironmentManagerArgs::new(local_runtime_paths)).await); let installation_id = resolve_installation_id(&config.codex_home).await?; @@ -127,9 +123,8 @@ async fn run_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { SessionSource::Exec, environment_manager, /*analytics_events_client*/ None, - state_db, Arc::clone(&thread_store), - agent_graph_store, + state_db, installation_id, ); diff --git a/codex-rs/thread-store/src/local/archive_thread.rs b/codex-rs/thread-store/src/local/archive_thread.rs index 268a6ffc47..8fb214e98c 100644 --- a/codex-rs/thread-store/src/local/archive_thread.rs +++ b/codex-rs/thread-store/src/local/archive_thread.rs @@ -13,11 +13,11 @@ pub(super) async fn archive_thread( params: ArchiveThreadParams, ) -> ThreadStoreResult<()> { let thread_id = params.thread_id; - let state_db = store.state_db(); + let state_db_ctx = store.state_db().await; let rollout_path = find_thread_path_by_id_str( store.config.codex_home.as_path(), &thread_id.to_string(), - Some(state_db.as_ref()), + state_db_ctx.as_deref(), ) .await .map_err(|err| ThreadStoreError::InvalidRequest { @@ -52,10 +52,11 @@ pub(super) async fn archive_thread( } })?; - let _ = store - .state_db() - .mark_archived(thread_id, archived_path.as_path(), Utc::now()) - .await; + if let Some(ctx) = state_db_ctx { + let _ = ctx + .mark_archived(thread_id, archived_path.as_path(), Utc::now()) + .await; + } Ok(()) } @@ -74,15 +75,13 @@ mod tests { use crate::ThreadSortKey; use crate::ThreadStore; use crate::local::LocalThreadStore; - use crate::local::test_support::init_test_state_db; use crate::local::test_support::test_config; - use crate::local::test_support::test_store; use crate::local::test_support::write_session_file; #[tokio::test] async fn archive_thread_moves_rollout_to_archived_collection() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(201); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let active_path = @@ -128,12 +127,21 @@ mod tests { async fn archive_thread_updates_sqlite_metadata_when_present() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(202); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let active_path = write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file"); + let runtime = codex_state::StateRuntime::init( + home.path().to_path_buf(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); + runtime + .mark_backfill_complete(/*last_watermark*/ None) + .await + .expect("backfill should be complete"); let mut builder = codex_state::ThreadMetadataBuilder::new( thread_id, active_path.clone(), diff --git a/codex-rs/thread-store/src/local/create_thread.rs b/codex-rs/thread-store/src/local/create_thread.rs index 44938e6e8e..d181149406 100644 --- a/codex-rs/thread-store/src/local/create_thread.rs +++ b/codex-rs/thread-store/src/local/create_thread.rs @@ -22,12 +22,12 @@ pub(super) async fn create_thread( })?; let config = RolloutConfig { codex_home: store.config.codex_home.clone(), - sqlite_home: store.sqlite_home(), + sqlite_home: store.config.sqlite_home.clone(), cwd, model_provider_id: params.metadata.model_provider.clone(), generate_memories: matches!(params.metadata.memory_mode, ThreadMemoryMode::Enabled), }; - let state_db_ctx = Some(store.state_db()); + let state_db_ctx = store.state_db().await; let recorder = RolloutRecorder::new( &config, RolloutRecorderParams::new( diff --git a/codex-rs/thread-store/src/local/list_threads.rs b/codex-rs/thread-store/src/local/list_threads.rs index 5cf1f27aa1..e470ad2be9 100644 --- a/codex-rs/thread-store/src/local/list_threads.rs +++ b/codex-rs/thread-store/src/local/list_threads.rs @@ -39,16 +39,16 @@ pub(super) async fn list_threads( SortDirection::Asc => codex_rollout::SortDirection::Asc, SortDirection::Desc => codex_rollout::SortDirection::Desc, }; + let state_db = store.state_db().await; let rollout_config = RolloutConfig { codex_home: store.config.codex_home.clone(), - sqlite_home: store.sqlite_home(), + sqlite_home: store.config.sqlite_home.clone(), cwd: store.config.codex_home.clone(), model_provider_id: store.config.default_model_provider_id.clone(), generate_memories: false, }; - let state_db_ctx = Some(store.state_db()); let page = list_rollout_threads( - state_db_ctx, + state_db, &rollout_config, store.config.default_model_provider_id.as_str(), ¶ms, @@ -80,13 +80,14 @@ pub(super) async fn list_threads( .map(|thread| thread.thread_id) .collect::>(); let mut names = HashMap::::with_capacity(thread_ids.len()); - let state_db_ctx = store.state_db(); - for &thread_id in &thread_ids { - let Ok(Some(metadata)) = state_db_ctx.get_thread(thread_id).await else { - continue; - }; - if let Some(title) = distinct_thread_metadata_title(&metadata) { - names.insert(thread_id, title); + if let Some(state_db_ctx) = store.state_db().await { + for &thread_id in &thread_ids { + let Ok(Some(metadata)) = state_db_ctx.get_thread(thread_id).await else { + continue; + }; + if let Some(title) = distinct_thread_metadata_title(&metadata) { + names.insert(thread_id, title); + } } } if names.len() < thread_ids.len() @@ -107,9 +108,9 @@ pub(super) async fn list_threads( } async fn list_rollout_threads( - state_db_ctx: Option, + state_db: Option, config: &RolloutConfig, - default_model_provider: &str, + default_model_provider_id: &str, params: &ListThreadsParams, cursor: Option<&codex_rollout::Cursor>, sort_key: codex_rollout::ThreadSortKey, @@ -117,7 +118,7 @@ async fn list_rollout_threads( ) -> ThreadStoreResult { let page = if params.use_state_db_only && params.archived { RolloutRecorder::list_archived_threads_from_state_db( - state_db_ctx.clone(), + state_db, config, params.page_size, cursor, @@ -126,13 +127,13 @@ async fn list_rollout_threads( params.allowed_sources.as_slice(), params.model_providers.as_deref(), params.cwd_filters.as_deref(), - default_model_provider, + default_model_provider_id, params.search_term.as_deref(), ) .await } else if params.use_state_db_only { RolloutRecorder::list_threads_from_state_db( - state_db_ctx.clone(), + state_db, config, params.page_size, cursor, @@ -141,13 +142,13 @@ async fn list_rollout_threads( params.allowed_sources.as_slice(), params.model_providers.as_deref(), params.cwd_filters.as_deref(), - default_model_provider, + default_model_provider_id, params.search_term.as_deref(), ) .await } else if params.archived { RolloutRecorder::list_archived_threads( - state_db_ctx.clone(), + state_db, config, params.page_size, cursor, @@ -156,13 +157,13 @@ async fn list_rollout_threads( params.allowed_sources.as_slice(), params.model_providers.as_deref(), params.cwd_filters.as_deref(), - default_model_provider, + default_model_provider_id, params.search_term.as_deref(), ) .await } else { RolloutRecorder::list_threads( - state_db_ctx, + state_db, config, params.page_size, cursor, @@ -171,7 +172,7 @@ async fn list_rollout_threads( params.allowed_sources.as_slice(), params.model_providers.as_deref(), params.cwd_filters.as_deref(), - default_model_provider, + default_model_provider_id, params.search_term.as_deref(), ) .await @@ -194,9 +195,7 @@ mod tests { use super::*; use crate::ThreadStore; use crate::local::LocalThreadStore; - use crate::local::test_support::init_test_state_db; use crate::local::test_support::test_config; - use crate::local::test_support::test_store; use crate::local::test_support::write_archived_session_file; use crate::local::test_support::write_session_file; use crate::local::test_support::write_session_file_with; @@ -204,7 +203,7 @@ mod tests { #[tokio::test] async fn list_threads_uses_default_provider_when_rollout_omits_provider() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); write_session_file_with( home.path(), home.path().join("sessions/2025/01/03"), @@ -239,13 +238,22 @@ mod tests { async fn list_threads_preserves_sqlite_title_search_results() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(103); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let rollout_path = home.path().join("rollout-title-search.jsonl"); fs::write(&rollout_path, "").expect("placeholder rollout file"); + let runtime = codex_state::StateRuntime::init( + home.path().to_path_buf(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); + runtime + .mark_backfill_complete(/*last_watermark*/ None) + .await + .expect("backfill should be complete"); let created_at = Utc::now(); let mut builder = codex_state::ThreadMetadataBuilder::new( thread_id, @@ -259,10 +267,6 @@ mod tests { let mut metadata = builder.build(config.default_model_provider_id.as_str()); metadata.title = "needle title".to_string(); metadata.first_user_message = Some("plain preview".to_string()); - runtime - .mark_backfill_complete(/*last_watermark*/ None) - .await - .expect("backfill should be complete"); runtime .upsert_thread(&metadata) .await @@ -299,7 +303,7 @@ mod tests { #[tokio::test] async fn list_threads_selects_active_or_archived_collection() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let active_uuid = Uuid::from_u128(105); let archived_uuid = Uuid::from_u128(106); write_session_file(home.path(), "2025-01-03T12-00-00", active_uuid) @@ -368,7 +372,7 @@ mod tests { async fn list_threads_returns_local_rollout_summary() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let store = LocalThreadStore::new(config.clone(), init_test_state_db(&config).await); + let store = LocalThreadStore::new(config, /*state_db*/ None); let uuid = Uuid::from_u128(101); let path = write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file"); @@ -407,7 +411,7 @@ mod tests { #[tokio::test] async fn list_threads_rejects_invalid_cursor() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let err = store .list_threads(ListThreadsParams { diff --git a/codex-rs/thread-store/src/local/live_writer.rs b/codex-rs/thread-store/src/local/live_writer.rs index 37d9758973..643207b59d 100644 --- a/codex-rs/thread-store/src/local/live_writer.rs +++ b/codex-rs/thread-store/src/local/live_writer.rs @@ -66,12 +66,12 @@ pub(super) async fn resume_thread( })?; let config = RolloutConfig { codex_home: store.config.codex_home.clone(), - sqlite_home: store.sqlite_home(), + sqlite_home: store.config.sqlite_home.clone(), cwd, model_provider_id: params.metadata.model_provider.clone(), generate_memories: matches!(params.metadata.memory_mode, ThreadMemoryMode::Enabled), }; - let state_db_ctx = Some(store.state_db()); + let state_db_ctx = store.state_db().await; let recorder = RolloutRecorder::new( &config, RolloutRecorderParams::resume( diff --git a/codex-rs/thread-store/src/local/mod.rs b/codex-rs/thread-store/src/local/mod.rs index 8872442073..07aa5e925f 100644 --- a/codex-rs/thread-store/src/local/mod.rs +++ b/codex-rs/thread-store/src/local/mod.rs @@ -41,7 +41,7 @@ use crate::UpdateThreadMetadataParams; pub struct LocalThreadStore { pub(super) config: LocalThreadStoreConfig, live_recorders: Arc>>, - state_db: StateDbHandle, + state_db: Option, } /// Process-scoped configuration for local thread storage. @@ -51,6 +51,7 @@ pub struct LocalThreadStore { #[derive(Clone, Debug, PartialEq, Eq)] pub struct LocalThreadStoreConfig { pub codex_home: PathBuf, + pub sqlite_home: PathBuf, /// Provider used only when older local metadata does not contain one. pub default_model_provider_id: String, } @@ -59,6 +60,7 @@ impl LocalThreadStoreConfig { pub fn from_config(config: &impl codex_rollout::RolloutConfigView) -> Self { Self { codex_home: config.codex_home().to_path_buf(), + sqlite_home: config.sqlite_home().to_path_buf(), default_model_provider_id: config.model_provider_id().to_string(), } } @@ -73,9 +75,8 @@ impl std::fmt::Debug for LocalThreadStore { } impl LocalThreadStore { - /// Create a local store from process-scoped local storage configuration and - /// the caller-provided shared state DB handle. - pub fn new(config: LocalThreadStoreConfig, state_db: StateDbHandle) -> Self { + /// Create a local store using an already initialized state DB handle. + pub fn new(config: LocalThreadStoreConfig, state_db: Option) -> Self { Self { config, live_recorders: Arc::new(Mutex::new(HashMap::new())), @@ -84,14 +85,10 @@ impl LocalThreadStore { } /// Return the state DB handle used by local rollout writers. - pub fn state_db(&self) -> StateDbHandle { + pub async fn state_db(&self) -> Option { self.state_db.clone() } - pub(super) fn sqlite_home(&self) -> PathBuf { - self.state_db.codex_home().to_path_buf() - } - /// Read a local rollout-backed thread by path. pub async fn read_thread_by_rollout_path( &self, @@ -285,16 +282,14 @@ mod tests { use super::*; use crate::ThreadEventPersistenceMode; use crate::ThreadPersistenceMetadata; - use crate::local::test_support::init_test_state_db; use crate::local::test_support::test_config; - use crate::local::test_support::test_store; use crate::local::test_support::write_archived_session_file; use crate::local::test_support::write_session_file; #[tokio::test] async fn live_writer_lifecycle_writes_and_closes() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let thread_id = ThreadId::default(); store @@ -343,7 +338,7 @@ mod tests { #[tokio::test] async fn create_thread_rejects_missing_cwd() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let thread_id = ThreadId::default(); let mut params = create_thread_params(thread_id); params.metadata.cwd = None; @@ -363,7 +358,7 @@ mod tests { #[tokio::test] async fn discard_thread_drops_unmaterialized_live_writer() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let thread_id = ThreadId::default(); store @@ -401,9 +396,8 @@ mod tests { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); let thread_id = ThreadId::default(); - let state_db = init_test_state_db(&config).await; - let first_store = LocalThreadStore::new(config.clone(), state_db.clone()); + let first_store = LocalThreadStore::new(config.clone(), /*state_db*/ None); first_store .create_thread(create_thread_params(thread_id)) .await @@ -432,7 +426,7 @@ mod tests { .await .expect("shutdown initial writer"); - let resumed_store = LocalThreadStore::new(config, state_db); + let resumed_store = LocalThreadStore::new(config, /*state_db*/ None); resumed_store .resume_thread(ResumeThreadParams { thread_id, @@ -463,7 +457,7 @@ mod tests { #[tokio::test] async fn create_thread_rejects_duplicate_live_writer() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let thread_id = ThreadId::default(); store @@ -483,7 +477,7 @@ mod tests { #[tokio::test] async fn resume_thread_rejects_duplicate_live_writer() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let thread_id = ThreadId::default(); store @@ -512,7 +506,7 @@ mod tests { #[tokio::test] async fn resume_thread_rejects_missing_cwd() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = uuid::Uuid::from_u128(407); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let rollout_path = @@ -541,7 +535,7 @@ mod tests { async fn load_history_uses_live_writer_rollout_path() { let home = TempDir::new().expect("temp dir"); let external_home = TempDir::new().expect("external temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = uuid::Uuid::from_u128(404); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let rollout_path = write_session_file(external_home.path(), "2025-01-04T10-00-00", uuid) @@ -590,7 +584,7 @@ mod tests { async fn read_thread_uses_live_writer_rollout_path_for_external_resume() { let home = TempDir::new().expect("temp dir"); let external_home = TempDir::new().expect("external temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = uuid::Uuid::from_u128(406); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let rollout_path = write_session_file(external_home.path(), "2025-01-04T11-00-00", uuid) @@ -629,7 +623,7 @@ mod tests { #[tokio::test] async fn load_history_uses_live_writer_rollout_path_for_archived_source() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = uuid::Uuid::from_u128(405); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let rollout_path = write_archived_session_file(home.path(), "2025-01-04T10-30-00", uuid) @@ -697,7 +691,7 @@ mod tests { #[tokio::test] async fn read_thread_by_rollout_path_includes_history() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let thread_id = ThreadId::default(); store diff --git a/codex-rs/thread-store/src/local/read_thread.rs b/codex-rs/thread-store/src/local/read_thread.rs index dd6e8494ab..9d685aace6 100644 --- a/codex-rs/thread-store/src/local/read_thread.rs +++ b/codex-rs/thread-store/src/local/read_thread.rs @@ -176,12 +176,12 @@ async fn resolve_rollout_path( return Ok(Some(path)); } - let state_db = store.state_db(); + let state_db_ctx = store.state_db().await; if include_archived { match find_thread_path_by_id_str( store.config.codex_home.as_path(), &thread_id.to_string(), - Some(state_db.as_ref()), + state_db_ctx.as_deref(), ) .await .map_err(|err| ThreadStoreError::InvalidRequest { @@ -191,7 +191,7 @@ async fn resolve_rollout_path( None => find_archived_thread_path_by_id_str( store.config.codex_home.as_path(), &thread_id.to_string(), - Some(state_db.as_ref()), + state_db_ctx.as_deref(), ) .await .map_err(|err| ThreadStoreError::InvalidRequest { @@ -202,7 +202,7 @@ async fn resolve_rollout_path( find_thread_path_by_id_str( store.config.codex_home.as_path(), &thread_id.to_string(), - Some(state_db.as_ref()), + state_db_ctx.as_deref(), ) .await .map_err(|err| ThreadStoreError::InvalidRequest { @@ -260,7 +260,8 @@ async fn read_sqlite_metadata( store: &LocalThreadStore, thread_id: codex_protocol::ThreadId, ) -> Option { - store.state_db().get_thread(thread_id).await.ok().flatten() + let runtime = store.state_db().await?; + runtime.get_thread(thread_id).await.ok().flatten() } async fn stored_thread_from_sqlite_metadata( @@ -414,9 +415,7 @@ mod tests { use super::*; use crate::ThreadStore; use crate::local::LocalThreadStore; - use crate::local::test_support::init_test_state_db; use crate::local::test_support::test_config; - use crate::local::test_support::test_store; use crate::local::test_support::write_archived_session_file; use crate::local::test_support::write_session_file; use crate::local::test_support::write_session_file_with_fork; @@ -424,7 +423,7 @@ mod tests { #[tokio::test] async fn read_thread_returns_active_rollout_summary() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(205); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let active_path = @@ -452,7 +451,7 @@ mod tests { #[tokio::test] async fn read_thread_returns_rollout_path_summary() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(211); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let active_path = @@ -483,12 +482,17 @@ mod tests { async fn read_thread_by_rollout_path_prefers_sqlite_git_info() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(223); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let active_path = write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file"); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); let mut builder = ThreadMetadataBuilder::new( thread_id, active_path.clone(), @@ -526,7 +530,7 @@ mod tests { #[tokio::test] async fn read_thread_returns_archived_rollout_when_requested() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(207); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let archived_path = write_archived_session_file(home.path(), "2025-01-03T12-00-00", uuid) @@ -567,7 +571,7 @@ mod tests { #[tokio::test] async fn read_thread_prefers_active_rollout_over_archived() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(208); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let active_path = @@ -592,7 +596,7 @@ mod tests { #[tokio::test] async fn read_thread_returns_forked_from_id() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(209); let parent_uuid = Uuid::from_u128(210); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); @@ -625,12 +629,17 @@ mod tests { async fn read_thread_applies_sqlite_thread_name() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(212); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let rollout_path = write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file"); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); let mut builder = ThreadMetadataBuilder::new(thread_id, rollout_path, Utc::now(), SessionSource::Cli); builder.model_provider = Some(config.default_model_provider_id.clone()); @@ -660,8 +669,13 @@ mod tests { async fn read_thread_preserves_rollout_cwd_when_sqlite_metadata_exists() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); let uuid = Uuid::from_u128(224); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let day_dir = home.path().join("sessions/2025/01/03"); @@ -730,7 +744,7 @@ mod tests { #[tokio::test] async fn read_thread_uses_legacy_thread_name_when_sqlite_title_is_missing() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(213); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file"); @@ -754,8 +768,6 @@ mod tests { async fn read_thread_uses_sqlite_metadata_for_rollout_without_user_preview() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(217); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let day_dir = home.path().join("sessions/2025/01/03"); @@ -777,6 +789,13 @@ mod tests { }); writeln!(file, "{meta}").expect("write session meta"); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); let mut builder = ThreadMetadataBuilder::new( thread_id, rollout_path.clone(), @@ -819,13 +838,18 @@ mod tests { let home = TempDir::new().expect("temp dir"); let external = TempDir::new().expect("external temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(220); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let rollout_path = write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file"); let stale_path = external.path().join("missing-rollout.jsonl"); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); let mut builder = ThreadMetadataBuilder::new( thread_id, stale_path.clone(), @@ -863,8 +887,6 @@ mod tests { let home = TempDir::new().expect("temp dir"); let external = TempDir::new().expect("external temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(221); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let rollout_path = @@ -872,6 +894,13 @@ mod tests { let other_uuid = Uuid::from_u128(222); let stale_path = write_session_file(external.path(), "2025-01-04T12-00-00", other_uuid) .expect("other session file"); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); let mut builder = ThreadMetadataBuilder::new(thread_id, stale_path, Utc::now(), SessionSource::Cli); builder.model_provider = Some("wrong-sqlite-provider".to_string()); @@ -903,7 +932,7 @@ mod tests { #[tokio::test] async fn read_thread_uses_session_meta_for_rollout_without_user_preview_or_sqlite_metadata() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(218); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let day_dir = home.path().join("sessions/2025/01/03"); @@ -958,13 +987,18 @@ mod tests { let home = TempDir::new().expect("temp dir"); let external = TempDir::new().expect("external temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(214); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let rollout_path = external .path() .join(format!("rollout-2025-01-03T12-00-00-{uuid}.jsonl")); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); let mut builder = ThreadMetadataBuilder::new( thread_id, rollout_path.clone(), @@ -1011,15 +1045,20 @@ mod tests { let home = TempDir::new().expect("temp dir"); let external = TempDir::new().expect("external temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(216); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let rollout_path = external .path() .join(format!("rollout-2025-01-03T12-00-00-{uuid}.jsonl")); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); let mut builder = ThreadMetadataBuilder::new(thread_id, rollout_path, Utc::now(), SessionSource::Cli); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); builder.archived_at = Some(Utc::now()); let mut metadata = builder.build(config.default_model_provider_id.as_str()); metadata.first_user_message = Some("Archived SQLite preview".to_string()); @@ -1062,12 +1101,17 @@ mod tests { async fn read_thread_sqlite_fallback_loads_archived_history() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(219); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let archived_path = write_archived_session_file(home.path(), "2025-01-03T12-00-00", uuid) .expect("archived session file"); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); let mut builder = ThreadMetadataBuilder::new( thread_id, archived_path.clone(), @@ -1103,7 +1147,7 @@ mod tests { #[tokio::test] async fn read_thread_fails_without_rollout() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(206); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); diff --git a/codex-rs/thread-store/src/local/test_support.rs b/codex-rs/thread-store/src/local/test_support.rs index 597014efe9..98321880ff 100644 --- a/codex-rs/thread-store/src/local/test_support.rs +++ b/codex-rs/thread-store/src/local/test_support.rs @@ -4,34 +4,18 @@ use std::path::Path; use std::path::PathBuf; use codex_rollout::ARCHIVED_SESSIONS_SUBDIR; -use codex_rollout::StateDbHandle; use uuid::Uuid; -use super::LocalThreadStore; use super::LocalThreadStoreConfig; pub(super) fn test_config(codex_home: &Path) -> LocalThreadStoreConfig { LocalThreadStoreConfig { codex_home: codex_home.to_path_buf(), + sqlite_home: codex_home.to_path_buf(), default_model_provider_id: "test-provider".to_string(), } } -pub(super) async fn init_test_state_db(config: &LocalThreadStoreConfig) -> StateDbHandle { - codex_state::StateRuntime::init( - config.codex_home.clone(), - config.default_model_provider_id.clone(), - ) - .await - .expect("state db should initialize") -} - -pub(super) async fn test_store(codex_home: &Path) -> LocalThreadStore { - let config = test_config(codex_home); - let state_db = init_test_state_db(&config).await; - LocalThreadStore::new(config, state_db) -} - pub(super) fn write_session_file(root: &Path, ts: &str, uuid: Uuid) -> std::io::Result { write_session_file_with( root, diff --git a/codex-rs/thread-store/src/local/unarchive_thread.rs b/codex-rs/thread-store/src/local/unarchive_thread.rs index 7ac3f01a0f..ad41db69ac 100644 --- a/codex-rs/thread-store/src/local/unarchive_thread.rs +++ b/codex-rs/thread-store/src/local/unarchive_thread.rs @@ -17,11 +17,11 @@ pub(super) async fn unarchive_thread( params: ArchiveThreadParams, ) -> ThreadStoreResult { let thread_id = params.thread_id; - let state_db = store.state_db(); + let state_db_ctx = store.state_db().await; let archived_path = find_archived_thread_path_by_id_str( store.config.codex_home.as_path(), &thread_id.to_string(), - Some(state_db.as_ref()), + state_db_ctx.as_deref(), ) .await .map_err(|err| ThreadStoreError::InvalidRequest { @@ -73,10 +73,11 @@ pub(super) async fn unarchive_thread( message: format!("failed to update unarchived thread timestamp: {err}"), })?; - let _ = store - .state_db() - .mark_unarchived(thread_id, restored_path.as_path()) - .await; + if let Some(ctx) = state_db_ctx { + let _ = ctx + .mark_unarchived(thread_id, restored_path.as_path()) + .await; + } let item = read_thread_item_from_rollout(restored_path.clone()) .await @@ -111,15 +112,13 @@ mod tests { use super::*; use crate::ThreadStore; use crate::local::LocalThreadStore; - use crate::local::test_support::init_test_state_db; use crate::local::test_support::test_config; - use crate::local::test_support::test_store; use crate::local::test_support::write_archived_session_file; #[tokio::test] async fn unarchive_thread_restores_rollout_and_returns_updated_thread() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(203); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let archived_path = write_archived_session_file(home.path(), "2025-01-03T13-00-00", uuid) @@ -150,12 +149,21 @@ mod tests { async fn unarchive_thread_updates_sqlite_metadata_when_present() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(204); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let archived_path = write_archived_session_file(home.path(), "2025-01-03T13-00-00", uuid) .expect("archived session file"); + let runtime = codex_state::StateRuntime::init( + home.path().to_path_buf(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); + runtime + .mark_backfill_complete(/*last_watermark*/ None) + .await + .expect("backfill should be complete"); let mut builder = codex_state::ThreadMetadataBuilder::new( thread_id, archived_path.clone(), diff --git a/codex-rs/thread-store/src/local/update_thread_metadata.rs b/codex-rs/thread-store/src/local/update_thread_metadata.rs index 15a7292124..ef69cfa8b8 100644 --- a/codex-rs/thread-store/src/local/update_thread_metadata.rs +++ b/codex-rs/thread-store/src/local/update_thread_metadata.rs @@ -55,8 +55,9 @@ pub(super) async fn update_thread_metadata( .await?; } + let state_db_ctx = store.state_db().await; codex_rollout::state_db::reconcile_rollout( - Some(store.state_db()).as_deref(), + state_db_ctx.as_deref(), resolved_rollout_path.path.as_path(), store.config.default_model_provider_id.as_str(), /*builder*/ None, @@ -72,7 +73,11 @@ pub(super) async fn update_thread_metadata( let resolved_git_info = match git_info { Some(git_info) => { - let state_db = store.state_db(); + let Some(state_db) = store.state_db().await else { + return Err(ThreadStoreError::Internal { + message: format!("sqlite state db unavailable for thread {thread_id}"), + }); + }; let metadata = state_db .get_thread(thread_id) @@ -152,7 +157,11 @@ async fn apply_thread_git_info( branch: &Option, origin_url: &Option, ) -> ThreadStoreResult<()> { - let state_db = store.state_db(); + let Some(state_db) = store.state_db().await else { + return Err(ThreadStoreError::Internal { + message: format!("sqlite state db unavailable for thread {thread_id}"), + }); + }; let updated = state_db .update_thread_git_info( thread_id, @@ -232,17 +241,18 @@ async fn apply_thread_name( thread_id: ThreadId, name: String, ) -> ThreadStoreResult<()> { - let updated = store - .state_db() - .update_thread_title(thread_id, &name) - .await - .map_err(|err| ThreadStoreError::Internal { - message: format!("failed to set thread name: {err}"), - })?; - if !updated { - return Err(ThreadStoreError::Internal { - message: format!("thread metadata unavailable before name update: {thread_id}"), - }); + if let Some(state_db) = store.state_db().await { + let updated = state_db + .update_thread_title(thread_id, &name) + .await + .map_err(|err| ThreadStoreError::Internal { + message: format!("failed to set thread name: {err}"), + })?; + if !updated { + return Err(ThreadStoreError::Internal { + message: format!("thread metadata unavailable before name update: {thread_id}"), + }); + } } append_thread_name(store.config.codex_home.as_path(), thread_id, &name) @@ -300,11 +310,11 @@ async fn resolve_rollout_path( return Ok(ResolvedRolloutPath { path, archived }); } - let state_db = store.state_db(); + let state_db_ctx = store.state_db().await; let active_path = find_thread_path_by_id_str( store.config.codex_home.as_path(), &thread_id.to_string(), - Some(state_db.as_ref()), + state_db_ctx.as_deref(), ) .await .map_err(|err| ThreadStoreError::InvalidRequest { @@ -324,7 +334,7 @@ async fn resolve_rollout_path( find_archived_thread_path_by_id_str( store.config.codex_home.as_path(), &thread_id.to_string(), - Some(state_db.as_ref()), + state_db_ctx.as_deref(), ) .await .map_err(|err| ThreadStoreError::InvalidRequest { @@ -359,16 +369,14 @@ mod tests { use crate::ThreadPersistenceMetadata; use crate::ThreadStore; use crate::local::LocalThreadStore; - use crate::local::test_support::init_test_state_db; use crate::local::test_support::test_config; - use crate::local::test_support::test_store; use crate::local::test_support::write_archived_session_file; use crate::local::test_support::write_session_file; #[tokio::test] async fn update_thread_metadata_sets_name_on_active_rollout_and_indexes_name() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(301); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); write_session_file(home.path(), "2025-01-03T14-00-00", uuid).expect("session file"); @@ -390,26 +398,24 @@ mod tests { .await .expect("find thread name"); assert_eq!(latest_name.as_deref(), Some("A sharper name")); - - let metadata = store - .state_db() - .get_thread(thread_id) - .await - .expect("get metadata") - .expect("metadata"); - assert_eq!(metadata.title, "A sharper name"); } #[tokio::test] async fn update_thread_metadata_sets_memory_mode_on_active_rollout() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(302); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let path = write_session_file(home.path(), "2025-01-03T14-30-00", uuid).expect("session file"); + let runtime = codex_state::StateRuntime::init( + home.path().to_path_buf(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); + let thread = store .update_thread_metadata(UpdateThreadMetadataParams { thread_id, @@ -442,8 +448,13 @@ mod tests { let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let path = write_session_file(home.path(), "2025-01-03T18-30-00", uuid).expect("session file"); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); store .update_thread_metadata(UpdateThreadMetadataParams { @@ -502,7 +513,7 @@ mod tests { async fn update_thread_metadata_uses_live_rollout_path_for_external_resume() { let home = TempDir::new().expect("temp dir"); let external_home = TempDir::new().expect("external temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(307); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let path = write_session_file(external_home.path(), "2025-01-03T14-45-00", uuid) @@ -543,8 +554,13 @@ mod tests { async fn update_thread_metadata_sets_git_info() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config, runtime); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config, Some(runtime)); let uuid = Uuid::from_u128(309); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); write_session_file(home.path(), "2025-01-03T17-00-00", uuid).expect("session file"); @@ -581,8 +597,13 @@ mod tests { async fn update_thread_metadata_partially_updates_git_info() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config, runtime); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config, Some(runtime)); let uuid = Uuid::from_u128(310); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); write_session_file(home.path(), "2025-01-03T17-30-00", uuid).expect("session file"); @@ -634,8 +655,13 @@ mod tests { async fn update_thread_metadata_clears_git_info_fields() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); let uuid = Uuid::from_u128(311); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let path = @@ -799,7 +825,7 @@ mod tests { #[tokio::test] async fn update_thread_metadata_rejects_mismatched_session_meta_id() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let filename_uuid = Uuid::from_u128(303); let metadata_uuid = Uuid::from_u128(304); let thread_id = ThreadId::from_string(&filename_uuid.to_string()).expect("valid thread id"); @@ -831,7 +857,7 @@ mod tests { #[tokio::test] async fn update_thread_metadata_rejects_multi_field_patch_without_partial_write() { let home = TempDir::new().expect("temp dir"); - let store = test_store(home.path()).await; + let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); let uuid = Uuid::from_u128(305); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let path = @@ -866,12 +892,21 @@ mod tests { async fn update_thread_metadata_keeps_archived_thread_archived_in_sqlite() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(306); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let archived_path = write_archived_session_file(home.path(), "2025-01-03T16-00-00", uuid) .expect("archived session file"); + let runtime = codex_state::StateRuntime::init( + home.path().to_path_buf(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); + runtime + .mark_backfill_complete(/*last_watermark*/ None) + .await + .expect("backfill should be complete"); codex_rollout::state_db::reconcile_rollout( Some(runtime.as_ref()), archived_path.as_path(), @@ -920,12 +955,21 @@ mod tests { async fn update_thread_metadata_keeps_live_archived_thread_archived_in_sqlite() { let home = TempDir::new().expect("temp dir"); let config = test_config(home.path()); - let runtime = init_test_state_db(&config).await; - let store = LocalThreadStore::new(config.clone(), runtime.clone()); let uuid = Uuid::from_u128(308); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); let archived_path = write_archived_session_file(home.path(), "2025-01-03T16-30-00", uuid) .expect("archived session file"); + let runtime = codex_state::StateRuntime::init( + home.path().to_path_buf(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = LocalThreadStore::new(config.clone(), Some(runtime.clone())); + runtime + .mark_backfill_complete(/*last_watermark*/ None) + .await + .expect("backfill should be complete"); codex_rollout::state_db::reconcile_rollout( Some(runtime.as_ref()), archived_path.as_path(), diff --git a/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs b/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs index c146bae8b4..7e1a41cf30 100644 --- a/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs +++ b/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs @@ -662,6 +662,8 @@ fn event_label(event_name: HookEventName) -> &'static str { HookEventName::PreToolUse => "PreToolUse", HookEventName::PermissionRequest => "PermissionRequest", HookEventName::PostToolUse => "PostToolUse", + HookEventName::PreCompact => "PreCompact", + HookEventName::PostCompact => "PostCompact", HookEventName::SessionStart => "SessionStart", HookEventName::UserPromptSubmit => "UserPromptSubmit", HookEventName::Stop => "Stop", @@ -673,6 +675,8 @@ fn event_description(event_name: HookEventName) -> &'static str { HookEventName::PreToolUse => "Before a tool executes", HookEventName::PermissionRequest => "When permission is requested", HookEventName::PostToolUse => "After a tool executes", + HookEventName::PreCompact => "Before context compaction", + HookEventName::PostCompact => "After context compaction", HookEventName::SessionStart => "When a new session starts", HookEventName::UserPromptSubmit => "When the user submits a prompt", HookEventName::Stop => "Right before Codex ends its turn", diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events.snap index 522105c30d..34c1d8ceec 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events.snap @@ -10,6 +10,8 @@ expression: "render_lines(&view, 112)" PreToolUse 2 1 Before a tool executes PermissionRequest 1 1 When permission is requested PostToolUse 0 0 After a tool executes + PreCompact 0 0 Before context compaction + PostCompact 0 0 After context compaction SessionStart 0 0 When a new session starts UserPromptSubmit 0 0 When the user submits a prompt Stop 0 0 Right before Codex ends its turn diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_issues.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_issues.snap index 18e3b9f849..511f173813 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_issues.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_issues.snap @@ -14,6 +14,8 @@ expression: "render_lines(&view, 112)" PreToolUse 0 0 Before a tool executes PermissionRequest 0 0 When permission is requested PostToolUse 0 0 After a tool executes + PreCompact 0 0 Before context compaction + PostCompact 0 0 After context compaction SessionStart 0 0 When a new session starts UserPromptSubmit 0 0 When the user submits a prompt Stop 0 0 Right before Codex ends its turn diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_review_column.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_review_column.snap index 85e930c68c..d6768118ca 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_review_column.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_review_column.snap @@ -10,6 +10,8 @@ expression: "render_lines(&view, 112)" PreToolUse 1 0 1 Before a tool executes PermissionRequest 0 0 0 When permission is requested PostToolUse 0 0 0 After a tool executes + PreCompact 0 0 0 Before context compaction + PostCompact 0 0 0 After context compaction SessionStart 0 0 0 When a new session starts UserPromptSubmit 0 0 0 When the user submits a prompt Stop 0 0 0 Right before Codex ends its turn diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hooks_popup_shows_list_diagnostics.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hooks_popup_shows_list_diagnostics.snap index 865d19031f..5224197d2f 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hooks_popup_shows_list_diagnostics.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hooks_popup_shows_list_diagnostics.snap @@ -13,6 +13,8 @@ expression: popup PreToolUse 0 0 Before a tool executes PermissionRequest 0 0 When permission is requested PostToolUse 0 0 After a tool executes + PreCompact 0 0 Before context compaction + PostCompact 0 0 After context compaction SessionStart 0 0 When a new session starts UserPromptSubmit 0 0 When the user submits a prompt Stop 0 0 Right before Codex ends its turn diff --git a/codex-rs/tui/src/chatwidget/tests/helpers.rs b/codex-rs/tui/src/chatwidget/tests/helpers.rs index b5a6dad825..56fe0b5b5d 100644 --- a/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -1677,6 +1677,8 @@ fn hook_event_label(event_name: codex_app_server_protocol::HookEventName) -> &'s codex_app_server_protocol::HookEventName::PreToolUse => "PreToolUse", codex_app_server_protocol::HookEventName::PermissionRequest => "PermissionRequest", codex_app_server_protocol::HookEventName::PostToolUse => "PostToolUse", + codex_app_server_protocol::HookEventName::PreCompact => "PreCompact", + codex_app_server_protocol::HookEventName::PostCompact => "PostCompact", codex_app_server_protocol::HookEventName::SessionStart => "SessionStart", codex_app_server_protocol::HookEventName::UserPromptSubmit => "UserPromptSubmit", codex_app_server_protocol::HookEventName::Stop => "Stop", diff --git a/codex-rs/tui/src/history_cell/hook_cell.rs b/codex-rs/tui/src/history_cell/hook_cell.rs index 3b87eff6d3..e78ce27fb0 100644 --- a/codex-rs/tui/src/history_cell/hook_cell.rs +++ b/codex-rs/tui/src/history_cell/hook_cell.rs @@ -716,6 +716,8 @@ fn hook_event_label(event_name: HookEventName) -> &'static str { HookEventName::PreToolUse => "PreToolUse", HookEventName::PermissionRequest => "PermissionRequest", HookEventName::PostToolUse => "PostToolUse", + HookEventName::PreCompact => "PreCompact", + HookEventName::PostCompact => "PostCompact", HookEventName::SessionStart => "SessionStart", HookEventName::UserPromptSubmit => "UserPromptSubmit", HookEventName::Stop => "Stop", diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index b2e92a19b4..5622c59f65 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -881,40 +881,38 @@ pub async fn run_main( AppServerTarget::Remote { .. } => state_db::get_state_db(&config).await, }; - if let Some(state_db) = state_db.clone() { - let effective_toml = config.config_layer_stack.effective_config(); - match effective_toml.try_into() { - Ok(config_toml) => { - match crate::legacy_core::personality_migration::maybe_migrate_personality( - &config.codex_home, - &config_toml, - state_db, - ) - .await - { - Ok( - crate::legacy_core::personality_migration::PersonalityMigrationStatus::Applied, - ) => { - config = load_config_or_exit( - cli_kv_overrides.clone(), - overrides.clone(), - cloud_requirements.clone(), - ) - .await; - } - Ok( - crate::legacy_core::personality_migration::PersonalityMigrationStatus::SkippedMarker - | crate::legacy_core::personality_migration::PersonalityMigrationStatus::SkippedExplicitPersonality - | crate::legacy_core::personality_migration::PersonalityMigrationStatus::SkippedNoSessions, - ) => {} - Err(err) => { - tracing::warn!(error = %err, "failed to run personality migration"); - } + let effective_toml = config.config_layer_stack.effective_config(); + match effective_toml.try_into() { + Ok(config_toml) => { + match crate::legacy_core::personality_migration::maybe_migrate_personality( + &config.codex_home, + &config_toml, + state_db.clone(), + ) + .await + { + Ok( + crate::legacy_core::personality_migration::PersonalityMigrationStatus::Applied, + ) => { + config = load_config_or_exit( + cli_kv_overrides.clone(), + overrides.clone(), + cloud_requirements.clone(), + ) + .await; + } + Ok( + crate::legacy_core::personality_migration::PersonalityMigrationStatus::SkippedMarker + | crate::legacy_core::personality_migration::PersonalityMigrationStatus::SkippedExplicitPersonality + | crate::legacy_core::personality_migration::PersonalityMigrationStatus::SkippedNoSessions, + ) => {} + Err(err) => { + tracing::warn!(error = %err, "failed to run personality migration"); } } - Err(err) => { - tracing::warn!(error = %err, "failed to deserialize config for personality migration"); - } + } + Err(err) => { + tracing::warn!(error = %err, "failed to deserialize config for personality migration"); } } diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 08bd6657bf..66e26d9778 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -5737,7 +5737,6 @@ session_picker_view = "dense" name: None, turns: vec![codex_app_server_protocol::Turn { id: String::from("turn-1"), - items_view: codex_app_server_protocol::TurnItemsView::Full, items: vec![ ThreadItem::UserMessage { id: String::from("user-1"), @@ -5757,6 +5756,7 @@ session_picker_view = "dense" text: String::from("1. Do the thing"), }, ], + items_view: codex_app_server_protocol::TurnItemsView::Full, status: codex_app_server_protocol::TurnStatus::Completed, error: None, started_at: None, @@ -5804,12 +5804,12 @@ session_picker_view = "dense" name: None, turns: vec![codex_app_server_protocol::Turn { id: String::from("turn-1"), - items_view: codex_app_server_protocol::TurnItemsView::Full, items: vec![ThreadItem::Reasoning { id: String::from("reasoning-1"), summary: Vec::new(), content: vec![String::from("private raw chain of thought")], }], + items_view: codex_app_server_protocol::TurnItemsView::Full, status: codex_app_server_protocol::TurnStatus::Completed, error: None, started_at: None, @@ -5861,12 +5861,12 @@ session_picker_view = "dense" name: None, turns: vec![codex_app_server_protocol::Turn { id: String::from("turn-1"), - items_view: codex_app_server_protocol::TurnItemsView::Full, items: vec![ThreadItem::Reasoning { id: String::from("reasoning-1"), summary: vec![String::from("public summary")], content: vec![String::from("raw reasoning content")], }], + items_view: codex_app_server_protocol::TurnItemsView::Full, status: codex_app_server_protocol::TurnStatus::Completed, error: None, started_at: None, diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 24f6e6f946..06417e31ea 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -3,6 +3,7 @@ use std::future::Future; use std::io::IsTerminal; use std::io::Result; use std::io::Stdout; +use std::io::Write; use std::io::stdin; use std::io::stdout; use std::panic; @@ -76,8 +77,15 @@ fn should_emit_notification(condition: NotificationCondition, terminal_focused: #[cfg(test)] mod tests { + use std::io::Write as _; + + use super::clear_for_viewport_change; use super::should_emit_notification; + use crate::custom_terminal::Terminal as CustomTerminal; + use crate::test_backend::VT100Backend; use codex_config::types::NotificationCondition; + use ratatui::layout::Position; + use ratatui::layout::Rect; #[test] fn unfocused_notification_condition_is_suppressed_when_focused() { @@ -102,6 +110,47 @@ mod tests { /*terminal_focused*/ false )); } + + #[test] + fn first_viewport_change_clears_from_new_viewport_when_old_viewport_is_empty() { + let width = 12; + let height = 4; + let backend = VT100Backend::new(width, height); + let mut terminal = + CustomTerminal::with_options_and_cursor_position(backend, Position { x: 0, y: 1 }) + .expect("terminal"); + write!( + terminal.backend_mut(), + "shell line\r\nstale cells\r\nmore stale" + ) + .expect("prefill terminal"); + + clear_for_viewport_change( + &mut terminal, + Rect::new( + /*x*/ 0, + /*y*/ 1, + /*width*/ width, + /*height*/ height - 1, + ), + ) + .expect("clear transition"); + + let rows: Vec = terminal + .backend() + .vt100() + .screen() + .rows(/*start*/ 0, width) + .collect(); + assert!( + rows[0].contains("shell line"), + "expected content before the viewport to remain visible, rows: {rows:?}" + ); + assert!( + !rows.iter().skip(1).any(|row| row.contains("stale")), + "expected stale cells inside the new viewport to be cleared, rows: {rows:?}" + ); + } } pub fn set_modes() -> Result<()> { @@ -391,6 +440,18 @@ struct PendingHistoryLines { wrap_policy: HistoryLineWrapPolicy, } +fn clear_for_viewport_change(terminal: &mut CustomTerminal, new_area: Rect) -> Result<()> +where + B: Backend + Write, +{ + let clear_position = if terminal.viewport_area.is_empty() { + new_area.as_position() + } else { + terminal.viewport_area.as_position() + }; + terminal.clear_after_position(clear_position) +} + impl Tui { pub fn new(terminal: Terminal) -> Self { let (draw_tx, _) = broadcast::channel(1); @@ -642,8 +703,9 @@ impl Tui { area.y = size.height - area.height; } if area != terminal.viewport_area { - // TODO(nornagon): probably this could be collapsed with the clear + set_viewport_area above. - terminal.clear()?; + // On startup, the old viewport can still be empty. Clear from the + // new viewport top so stale shell cells do not show through spaces. + clear_for_viewport_change(terminal, area)?; terminal.set_viewport_area(area); }