Adapt goal app-server wiring to GoalService

This commit is contained in:
jif-oai
2026-06-01 10:41:54 +01:00
parent 374072c3b6
commit da6d486053
9 changed files with 165 additions and 94 deletions
+1
View File
@@ -2984,6 +2984,7 @@ dependencies = [
"codex-extension-api",
"codex-otel",
"codex-protocol",
"codex-rollout",
"codex-state",
"codex-tools",
"codex-utils-template",
+16
View File
@@ -12,11 +12,14 @@ use codex_extension_api::AgentSpawner;
use codex_extension_api::ExtensionEventSink;
use codex_extension_api::ExtensionRegistry;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_features::Feature;
use codex_goal_extension::GoalService;
use codex_login::AuthManager;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_rollout::StateDbHandle;
use crate::outgoing_message::OutgoingMessageSender;
@@ -24,12 +27,25 @@ pub(crate) fn thread_extensions<S>(
guardian_agent_spawner: S,
event_sink: Arc<dyn ExtensionEventSink>,
auth_manager: Arc<AuthManager>,
state_db: Option<StateDbHandle>,
thread_manager: Weak<ThreadManager>,
goal_service: Arc<GoalService>,
) -> Arc<ExtensionRegistry<Config>>
where
S: AgentSpawner<StartThreadOptions, Spawned = NewThread, Error = CodexErr> + 'static,
{
let mut builder = ExtensionRegistryBuilder::<Config>::with_event_sink(event_sink);
codex_guardian::install(&mut builder, guardian_agent_spawner);
if let Some(state_db) = state_db {
codex_goal_extension::install_with_backend(
&mut builder,
state_db,
codex_otel::global(),
thread_manager,
goal_service,
|config: &Config| config.features.enabled(Feature::Goals),
);
}
codex_memories_extension::install(&mut builder, codex_otel::global());
codex_web_search_extension::install(&mut builder, auth_manager.clone());
codex_image_generation_extension::install(&mut builder, auth_manager);
+4
View File
@@ -180,6 +180,7 @@ mod tests {
let state_db = init_state_db(&good_config)
.await
.expect("refresh tests require state db");
let goal_service = Arc::new(codex_goal_extension::GoalService::new());
let thread_store = thread_store_from_config(&good_config, Some(state_db.clone()));
let thread_manager = Arc::new_cyclic(|thread_manager| {
ThreadManager::new(
@@ -191,6 +192,9 @@ mod tests {
guardian_agent_spawner(thread_manager.clone()),
Arc::new(NoopExtensionEventSink),
auth_manager.clone(),
Some(state_db.clone()),
thread_manager.clone(),
Arc::clone(&goal_service),
),
/*analytics_events_client*/ None,
Arc::clone(&thread_store),
@@ -70,6 +70,7 @@ use codex_core::ThreadManager;
use codex_core::config::Config;
use codex_exec_server::EnvironmentManager;
use codex_feedback::CodexFeedback;
use codex_goal_extension::GoalService;
use codex_login::AuthManager;
use codex_login::auth::ExternalAuth;
use codex_login::auth::ExternalAuthRefreshContext;
@@ -305,6 +306,7 @@ impl MessageProcessor {
// resumed, or forked threads to a different persistence backend/root.
let thread_store = codex_core::thread_store_from_config(config.as_ref(), state_db.clone());
let environment_manager_for_requests = Arc::clone(&environment_manager);
let goal_service = Arc::new(GoalService::new());
let thread_manager = Arc::new_cyclic(|thread_manager| {
ThreadManager::new(
config.as_ref(),
@@ -315,6 +317,9 @@ impl MessageProcessor {
guardian_agent_spawner(thread_manager.clone()),
app_server_extension_event_sink(outgoing.clone()),
auth_manager.clone(),
state_db.clone(),
thread_manager.clone(),
Arc::clone(&goal_service),
),
Some(analytics_events_client.clone()),
Arc::clone(&thread_store),
@@ -416,6 +421,7 @@ impl MessageProcessor {
Arc::clone(&config),
thread_state_manager.clone(),
state_db.clone(),
Arc::clone(&goal_service),
);
let thread_processor = ThreadRequestProcessor::new(
auth_manager.clone(),
@@ -406,7 +406,6 @@ use codex_rmcp_client::perform_oauth_login_return_url;
use codex_rollout::EventPersistenceMode;
use codex_rollout::is_persisted_rollout_item;
use codex_rollout::state_db::StateDbHandle;
use codex_rollout::state_db::reconcile_rollout;
use codex_state::ThreadMetadata;
use codex_state::log_db::LogDbLayer;
use codex_thread_store::ArchiveThreadParams as StoreArchiveThreadParams;
@@ -1,8 +1,9 @@
use super::*;
use codex_goal_extension::GoalApi;
use codex_goal_extension::GoalApiError;
use codex_goal_extension::GoalObjectiveUpdate;
use codex_goal_extension::GoalService;
use codex_goal_extension::GoalServiceError;
use codex_goal_extension::GoalSetRequest;
use codex_goal_extension::GoalThreadAccess;
use codex_goal_extension::GoalTokenBudgetUpdate;
#[derive(Clone)]
@@ -12,7 +13,7 @@ pub(crate) struct ThreadGoalRequestProcessor {
config: Arc<Config>,
thread_state_manager: ThreadStateManager,
state_db: Option<StateDbHandle>,
goal_api: Arc<GoalApi>,
goal_service: Arc<GoalService>,
}
impl ThreadGoalRequestProcessor {
@@ -22,6 +23,7 @@ impl ThreadGoalRequestProcessor {
config: Arc<Config>,
thread_state_manager: ThreadStateManager,
state_db: Option<StateDbHandle>,
goal_service: Arc<GoalService>,
) -> Self {
Self {
thread_manager,
@@ -29,7 +31,7 @@ impl ThreadGoalRequestProcessor {
config,
thread_state_manager,
state_db,
goal_api: Arc::new(GoalApi::new()),
goal_service,
}
}
@@ -105,35 +107,11 @@ impl ThreadGoalRequestProcessor {
}
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self.state_db_for_materialized_thread(thread_id).await?;
let running_thread = self.thread_manager.get_thread(thread_id).await.ok();
let rollout_path = match running_thread.as_ref() {
Some(thread) => thread.rollout_path().ok_or_else(|| {
invalid_request(format!(
"ephemeral thread does not support goals: {thread_id}"
))
})?,
None => codex_rollout::find_thread_path_by_id_str(
&self.config.codex_home,
&thread_id.to_string(),
self.state_db.as_deref(),
)
let state_db = self
.goal_service
.state_db_for_materialized_thread_mutation(self.goal_thread_access(), thread_id)
.await
.map_err(|err| {
internal_error(format!("failed to locate thread id {thread_id}: {err}"))
})?
.ok_or_else(|| invalid_request(format!("thread not found: {thread_id}")))?,
};
reconcile_rollout(
Some(&state_db),
rollout_path.as_path(),
self.config.model_provider_id.as_str(),
/*builder*/ None,
&[],
/*archived_only*/ None,
/*new_thread_memory_mode*/ None,
)
.await;
.map_err(goal_service_error)?;
let listener_command_tx = {
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
@@ -141,7 +119,7 @@ impl ThreadGoalRequestProcessor {
thread_state.listener_command_tx()
};
let outcome = self
.goal_api
.goal_service
.set_thread_goal(
&state_db,
GoalSetRequest {
@@ -157,7 +135,7 @@ impl ThreadGoalRequestProcessor {
},
)
.await
.map_err(goal_api_error)?;
.map_err(goal_service_error)?;
let goal: ThreadGoal = outcome.goal.clone().into();
self.outgoing
.send_response(
@@ -167,7 +145,7 @@ impl ThreadGoalRequestProcessor {
.await;
self.emit_thread_goal_updated_ordered(thread_id, goal, listener_command_tx)
.await;
outcome.apply_runtime_effects(&self.goal_api).await;
outcome.apply_runtime_effects(&self.goal_service).await;
Ok(())
}
@@ -182,10 +160,10 @@ impl ThreadGoalRequestProcessor {
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self.state_db_for_materialized_thread(thread_id).await?;
let goal = self
.goal_api
.goal_service
.get_thread_goal(&state_db, thread_id)
.await
.map_err(goal_api_error)?
.map_err(goal_service_error)?
.map(ThreadGoal::from);
Ok(ThreadGoalGetResponse { goal })
}
@@ -200,35 +178,11 @@ impl ThreadGoalRequestProcessor {
}
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self.state_db_for_materialized_thread(thread_id).await?;
let running_thread = self.thread_manager.get_thread(thread_id).await.ok();
let rollout_path = match running_thread.as_ref() {
Some(thread) => thread.rollout_path().ok_or_else(|| {
invalid_request(format!(
"ephemeral thread does not support goals: {thread_id}"
))
})?,
None => codex_rollout::find_thread_path_by_id_str(
&self.config.codex_home,
&thread_id.to_string(),
self.state_db.as_deref(),
)
let state_db = self
.goal_service
.state_db_for_materialized_thread_mutation(self.goal_thread_access(), thread_id)
.await
.map_err(|err| {
internal_error(format!("failed to locate thread id {thread_id}: {err}"))
})?
.ok_or_else(|| invalid_request(format!("thread not found: {thread_id}")))?,
};
reconcile_rollout(
Some(&state_db),
rollout_path.as_path(),
self.config.model_provider_id.as_str(),
/*builder*/ None,
&[],
/*archived_only*/ None,
/*new_thread_memory_mode*/ None,
)
.await;
.map_err(goal_service_error)?;
let listener_command_tx = {
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
@@ -236,10 +190,10 @@ impl ThreadGoalRequestProcessor {
thread_state.listener_command_tx()
};
let cleared = self
.goal_api
.goal_service
.clear_thread_goal(&state_db, thread_id)
.await
.map_err(goal_api_error)?;
.map_err(goal_service_error)?;
self.outgoing
.send_response(request_id, ThreadGoalClearResponse { cleared })
@@ -255,31 +209,19 @@ impl ThreadGoalRequestProcessor {
&self,
thread_id: ThreadId,
) -> Result<StateDbHandle, JSONRPCErrorError> {
if let Ok(thread) = self.thread_manager.get_thread(thread_id).await {
if thread.rollout_path().is_none() {
return Err(invalid_request(format!(
"ephemeral thread does not support goals: {thread_id}"
)));
}
if let Some(state_db) = thread.state_db() {
return Ok(state_db);
}
} else {
codex_rollout::find_thread_path_by_id_str(
&self.config.codex_home,
&thread_id.to_string(),
self.state_db.as_deref(),
)
self.goal_service
.state_db_for_materialized_thread(self.goal_thread_access(), thread_id)
.await
.map_err(|err| {
internal_error(format!("failed to locate thread id {thread_id}: {err}"))
})?
.ok_or_else(|| invalid_request(format!("thread not found: {thread_id}")))?;
}
.map_err(goal_service_error)
}
self.state_db
.clone()
.ok_or_else(|| internal_error("sqlite state db unavailable for thread goals"))
fn goal_thread_access(&self) -> GoalThreadAccess<'_> {
GoalThreadAccess {
thread_manager: self.thread_manager.as_ref(),
codex_home: self.config.codex_home.as_path(),
model_provider_id: self.config.model_provider_id.as_str(),
fallback_state_db: self.state_db.as_ref(),
}
}
async fn emit_thread_goal_snapshot(&self, thread_id: ThreadId) {
@@ -393,9 +335,9 @@ fn parse_thread_id_for_request(thread_id: &str) -> Result<ThreadId, JSONRPCError
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))
}
fn goal_api_error(err: GoalApiError) -> JSONRPCErrorError {
fn goal_service_error(err: GoalServiceError) -> JSONRPCErrorError {
match err {
GoalApiError::InvalidRequest(message) => invalid_request(message),
GoalApiError::Internal(message) => internal_error(message),
GoalServiceError::InvalidRequest(message) => invalid_request(message),
GoalServiceError::Internal(message) => internal_error(message),
}
}
+1
View File
@@ -19,6 +19,7 @@ codex-core = { workspace = true }
codex-extension-api = { workspace = true }
codex-otel = { workspace = true }
codex-protocol = { workspace = true }
codex-rollout = { workspace = true }
codex-state = { workspace = true }
codex-tools = { workspace = true }
codex-utils-template = { workspace = true }
+101
View File
@@ -1,14 +1,20 @@
use std::collections::HashMap;
use std::fmt;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::sync::Weak;
use codex_core::ThreadManager;
use codex_protocol::ThreadId;
use codex_protocol::protocol::ThreadGoal;
use codex_protocol::protocol::ThreadGoalStatus;
use codex_protocol::protocol::validate_thread_goal_objective;
use codex_rollout::StateDbHandle;
use codex_rollout::find_thread_path_by_id_str;
use codex_rollout::state_db::reconcile_rollout;
use crate::runtime::GoalRuntimeHandle;
use crate::runtime::PreviousGoalSnapshot;
@@ -53,6 +59,14 @@ pub struct GoalSetRequest<'a> {
pub token_budget: GoalTokenBudgetUpdate,
}
#[derive(Clone, Copy)]
pub struct GoalThreadAccess<'a> {
pub thread_manager: &'a ThreadManager,
pub codex_home: &'a Path,
pub model_provider_id: &'a str,
pub fallback_state_db: Option<&'a StateDbHandle>,
}
#[derive(Clone, Debug)]
pub struct GoalSetOutcome {
pub goal: ThreadGoal,
@@ -82,6 +96,35 @@ impl GoalService {
Self::default()
}
pub async fn state_db_for_materialized_thread(
&self,
access: GoalThreadAccess<'_>,
thread_id: ThreadId,
) -> Result<StateDbHandle, GoalServiceError> {
self.materialized_thread_state(access, thread_id)
.await
.map(|state| state.state_db)
}
pub async fn state_db_for_materialized_thread_mutation(
&self,
access: GoalThreadAccess<'_>,
thread_id: ThreadId,
) -> Result<StateDbHandle, GoalServiceError> {
let state = self.materialized_thread_state(access, thread_id).await?;
reconcile_rollout(
Some(&state.state_db),
state.rollout_path.as_path(),
access.model_provider_id,
/*builder*/ None,
&[],
/*archived_only*/ None,
/*new_thread_memory_mode*/ None,
)
.await;
Ok(state.state_db)
}
pub async fn get_thread_goal(
&self,
state_db: &codex_state::StateRuntime,
@@ -283,4 +326,62 @@ impl GoalService {
fn runtimes(&self) -> std::sync::MutexGuard<'_, HashMap<String, Weak<GoalRuntimeHandle>>> {
self.runtimes.lock().unwrap_or_else(PoisonError::into_inner)
}
async fn materialized_thread_state(
&self,
access: GoalThreadAccess<'_>,
thread_id: ThreadId,
) -> Result<MaterializedThreadState, GoalServiceError> {
let thread_id_str = thread_id.to_string();
let (state_db, rollout_path) = match access.thread_manager.get_thread(thread_id).await {
Ok(thread) => {
let rollout_path = thread.rollout_path().ok_or_else(|| {
GoalServiceError::InvalidRequest(format!(
"ephemeral thread does not support goals: {thread_id}"
))
})?;
let state_db = thread
.state_db()
.or_else(|| access.fallback_state_db.cloned())
.ok_or_else(|| {
GoalServiceError::Internal(
"sqlite state db unavailable for thread goals".to_string(),
)
})?;
(state_db, rollout_path)
}
Err(_) => {
let rollout_path = find_thread_path_by_id_str(
access.codex_home,
thread_id_str.as_str(),
access.fallback_state_db.map(Arc::as_ref),
)
.await
.map_err(|err| {
GoalServiceError::Internal(format!(
"failed to locate thread id {thread_id}: {err}"
))
})?
.ok_or_else(|| {
GoalServiceError::InvalidRequest(format!("thread not found: {thread_id}"))
})?;
let state_db = access.fallback_state_db.cloned().ok_or_else(|| {
GoalServiceError::Internal(
"sqlite state db unavailable for thread goals".to_string(),
)
})?;
(state_db, rollout_path)
}
};
Ok(MaterializedThreadState {
state_db,
rollout_path,
})
}
}
struct MaterializedThreadState {
state_db: StateDbHandle,
rollout_path: PathBuf,
}
+1
View File
@@ -19,6 +19,7 @@ pub use api::GoalService;
pub use api::GoalServiceError;
pub use api::GoalSetOutcome;
pub use api::GoalSetRequest;
pub use api::GoalThreadAccess;
pub use api::GoalTokenBudgetUpdate;
pub use extension::GoalExtension;
pub use extension::GoalExtensionConfig;