Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,31 @@
//! Build account API clients from the latest config and captured account authority.
use super::*;
use futures::future::BoxFuture;
impl AccountRequestProcessor {
// Keep config loading and runtime bootstrap out of request-handler future types.
#[inline(never)]
pub(super) fn backend_client<'a>(
&'a self,
auth: &'a CodexAuth,
http_client_factory: codex_http_client::HttpClientFactory,
) -> BoxFuture<'a, Result<BackendClient, JSONRPCErrorError>> {
Box::pin(async move {
let config = self.load_latest_config().await;
let runtime = self
.thread_manager
.runtime_auth_for_config(&config)
.map_err(|error| internal_error(error.to_string()))?;
BackendClient::from_auth_with_runtime(
config.chatgpt_base_url.clone(),
auth,
http_client_factory,
runtime.as_ref(),
/*headers*/ &Default::default(),
)
.await
.map_err(|error| internal_error(error.to_string()))
})
}
}

View File

@@ -0,0 +1,107 @@
//! Post-login GovCloud checks use current authentication and freshly loaded configuration.
//! Official endpoint hostnames take precedence over credential and configured AWS regions.
//! Results are advisory; configuration and region resolution failures remain RPC errors.
use super::AccountRequestProcessor;
use crate::error_code::internal_error;
use codex_app_server_protocol::BedrockCheckGovCloudRequirementsResponse;
use codex_app_server_protocol::ClientResponsePayload;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_config::NetworkDomainPermissionToml;
use codex_model_provider::is_amazon_bedrock_gov_cloud_region;
use codex_model_provider::resolve_amazon_bedrock_region;
use codex_protocol::config_types::ForcedLoginMethod;
impl AccountRequestProcessor {
pub(crate) async fn bedrock_check_gov_cloud_requirements(
&self,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let config = self
.config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
.map_err(|err| internal_error(format!("failed to load configuration: {err}")))?;
let provider = &config.model_provider;
if !provider.is_amazon_bedrock() {
return Ok(Some(
BedrockCheckGovCloudRequirementsResponse {
is_gov_cloud: false,
should_warn: false,
}
.into(),
));
}
let endpoint_domain = provider
.base_url
.as_deref()
.map(|base_url| {
url::Url::parse(base_url)
.ok()
.and_then(|url| {
url.host_str()
.map(|host| host.trim_end_matches('.').to_string())
})
.ok_or_else(|| internal_error("Amazon Bedrock endpoint has no valid hostname"))
})
.transpose()?;
let endpoint_region = endpoint_domain.as_deref().and_then(|domain| {
let (service, rest) = domain.split_once('.')?;
let region = match service {
"bedrock-mantle" => rest.strip_suffix(".api.aws"),
"bedrock-runtime" | "bedrock-runtime-fips" => rest.strip_suffix(".amazonaws.com"),
_ => None,
}?;
// Require a single region label, not a substring in a proxy hostname.
(!region.is_empty() && !region.contains('.')).then_some(region)
});
let region = match endpoint_region {
Some(region) => region.to_string(),
None => {
resolve_amazon_bedrock_region(provider.clone(), Some(self.auth_manager.clone()))
.await
.map_err(|err| {
internal_error(format!("failed to resolve Amazon Bedrock region: {err}"))
})?
}
};
let is_gov_cloud = is_amazon_bedrock_gov_cloud_region(&region);
let mut should_warn = false;
if is_gov_cloud {
let domain = if let Some(domain) = endpoint_domain {
domain
} else if provider.is_amazon_bedrock_runtime() {
format!("bedrock-runtime.{region}.amazonaws.com")
} else {
format!("bedrock-mantle.{region}.api.aws")
};
let requirements = config.config_layer_stack.requirements_toml();
let api_only = requirements
.allowed_login_methods
.as_ref()
.is_some_and(|methods| {
!methods.is_empty()
&& methods
.iter()
.all(|method| *method == ForcedLoginMethod::Api)
});
let network_allowed = requirements
.application
.as_ref()
.and_then(|application| application.network.as_ref())
.is_some_and(|network| {
network.enabled
&& network.domains.get(&domain) == Some(&NetworkDomainPermissionToml::Allow)
});
should_warn = !api_only || !network_allowed;
}
Ok(Some(
BedrockCheckGovCloudRequirementsResponse {
is_gov_cloud,
should_warn,
}
.into(),
))
}
}

View File

@@ -0,0 +1,148 @@
use super::super::bedrock_auth::BedrockProviderConfig;
use super::super::bedrock_auth::prepare_bedrock_provider;
use super::super::config_processor::map_error as map_config_error;
use super::AccountRequestProcessor;
use super::CloudLoginProvider;
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use codex_app_server_protocol::AwsCredentialType;
use codex_app_server_protocol::BedrockAwsProfile;
use codex_app_server_protocol::BedrockDiscoverParams;
use codex_app_server_protocol::BedrockDiscoverResponse;
use codex_app_server_protocol::BedrockEnvironmentCredential;
use codex_app_server_protocol::BedrockSetupParams;
use codex_app_server_protocol::BedrockSetupResponse;
use codex_app_server_protocol::ClientResponsePayload;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_login::CodexAuth;
use codex_model_provider::is_supported_amazon_bedrock_region;
const AWS_ACCESS_KEY_ID: &str = "AWS_ACCESS_KEY_ID";
const AWS_SECRET_ACCESS_KEY: &str = "AWS_SECRET_ACCESS_KEY";
const AWS_BEARER_TOKEN_BEDROCK: &str = "AWS_BEARER_TOKEN_BEDROCK";
impl AccountRequestProcessor {
pub(crate) async fn bedrock_discover(
&self,
_params: BedrockDiscoverParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.ensure_provider_login_allowed(CloudLoginProvider::AmazonBedrock)?;
let profiles = codex_aws_auth::discover_aws_profiles()
.await
.map_err(|err| internal_error(format!("failed to discover AWS profiles: {err}")))?
.into_iter()
.map(|profile| BedrockAwsProfile {
name: profile.name,
region: profile.region,
})
.collect();
let region = non_empty_env_var("AWS_REGION");
let environment_credentials = [
(
AwsCredentialType::AccessKeys,
non_empty_env_var(AWS_ACCESS_KEY_ID).is_some()
&& non_empty_env_var(AWS_SECRET_ACCESS_KEY).is_some(),
),
(
AwsCredentialType::BedrockApiKey,
non_empty_env_var(AWS_BEARER_TOKEN_BEDROCK).is_some(),
),
]
.into_iter()
.filter(|(_, available)| *available)
.map(|(credential_type, _)| BedrockEnvironmentCredential {
credential_type,
region: region.clone(),
})
.collect();
Ok(Some(
BedrockDiscoverResponse {
profiles,
environment_credentials,
}
.into(),
))
}
pub(crate) async fn bedrock_setup(
&self,
params: BedrockSetupParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.ensure_provider_login_allowed(CloudLoginProvider::AmazonBedrock)?;
let (profile, region) = match &params {
BedrockSetupParams::Profile { profile, region } => {
(Some(profile.trim()), region.trim())
}
BedrockSetupParams::Environment { region } => (None, region.trim()),
};
let write = prepare_bedrock_provider(
&self.config_manager,
BedrockProviderConfig {
region: Some(region),
profile,
},
)
.await?;
if profile.is_none()
&& matches!(
self.auth_manager.auth_cached(),
Some(CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_))
)
{
return Err(invalid_request(
"Codex-managed Bedrock credentials are already configured and take priority over AWS environment credentials. Run `codex logout` and try again.",
));
}
if !is_supported_amazon_bedrock_region(region) {
return Err(invalid_request(format!(
"Amazon Bedrock does not support region `{region}`"
)));
}
if let Some(profile) = profile {
if profile.is_empty() {
return Err(invalid_request("AWS profile name must not be empty."));
}
codex_aws_auth::validate_aws_profile(
profile,
region,
self.config.http_client_factory(),
)
.await
.map_err(|err| {
invalid_request(format!(
"failed to load credentials for AWS profile `{profile}`: {err}"
))
})?;
} else {
let has_bedrock_api_key = non_empty_env_var(AWS_BEARER_TOKEN_BEDROCK).is_some();
let has_access_keys = non_empty_env_var(AWS_ACCESS_KEY_ID).is_some()
&& non_empty_env_var(AWS_SECRET_ACCESS_KEY).is_some();
if !has_bedrock_api_key && !has_access_keys {
return Err(invalid_request(
"No AWS credentials found. Please Configure AWS credentials or complete AWS sign-in, then try again.",
));
}
}
// TODO: Validate the selected credentials against Bedrock ListModels once supported.
self.cancel_active_login().await;
self.config_manager
.commit_provider_config(write)
.await
.map_err(map_config_error)?;
self.model_catalog.invalidate().await;
Ok(Some(BedrockSetupResponse {}.into()))
}
}
fn non_empty_env_var(name: &str) -> Option<String> {
std::env::var(name)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}

View File

@@ -0,0 +1,313 @@
//! Owns one explicit enterprise sign-in attempt for a configured MCP server.
//! Start, replacement, cancellation, and local commit admission all pass through this state.
//! The credential store separately fences logins invalidated by another process.
use super::*;
use anyhow::Context;
use codex_config::McpEmaRegistration;
use codex_config::types::AuthKeyringBackendKind;
use codex_mcp::ema_auth_scope;
use codex_rmcp_client::EmaErrorDetail;
use codex_rmcp_client::EnterpriseOAuthLoginRequest;
use codex_rmcp_client::perform_enterprise_oauth_login_return_url;
use futures::FutureExt;
use tokio::sync::watch;
pub(crate) struct EnterpriseLoginTarget {
pub(crate) thread_id: String,
pub(crate) server_name: String,
pub(crate) registration: McpEmaRegistration,
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub(crate) enum EnterpriseLoginCompletion {
Pending,
Succeeded,
Failed(EmaErrorDetail),
}
impl EnterpriseLoginCompletion {
pub(crate) fn is_complete(self) -> bool {
matches!(self, Self::Succeeded | Self::Failed(_))
}
}
pub(crate) struct EnterpriseLogin {
pub(crate) login_id: String,
pub(crate) authorization_url: String,
pub(crate) completion: watch::Receiver<EnterpriseLoginCompletion>,
}
pub(crate) struct EnterpriseLoginState {
auth_manager: Arc<AuthManager>,
thread_manager: Arc<ThreadManager>,
config_manager: ConfigManager,
// Cancellation and commit admission use this same lock. A cancelled attempt cannot commit.
active: Mutex<Option<EnterpriseLoginAttempt>>,
// Start and cancel hold this through callback shutdown; the worker never acquires it.
start_gate: Mutex<()>,
// Account changes cancel queued and running setup before waiting for start_gate.
setup_cancel: Mutex<CancellationToken>,
}
struct EnterpriseLoginAttempt {
login_id: String,
cancel: CancellationToken,
completion: watch::Receiver<EnterpriseLoginCompletion>,
}
impl Drop for EnterpriseLoginAttempt {
fn drop(&mut self) {
self.cancel.cancel();
}
}
impl EnterpriseLoginState {
pub(super) fn new(
auth_manager: Arc<AuthManager>,
thread_manager: Arc<ThreadManager>,
config_manager: ConfigManager,
) -> Self {
Self {
auth_manager,
thread_manager,
config_manager,
active: Mutex::new(None),
start_gate: Mutex::new(()),
setup_cancel: Mutex::new(CancellationToken::new()),
}
}
#[expect(
clippy::await_holding_invalid_type,
reason = "serialize start/cancel through callback shutdown; the worker uses a separate state lock"
)]
pub(super) async fn cancel(&self, login_id: Option<&str>) -> bool {
if login_id.is_none() {
let mut setup_cancel = self.setup_cancel.lock().await;
setup_cancel.cancel();
*setup_cancel = CancellationToken::new();
}
let (login_id, mut completion) = {
let active = self.active.lock().await;
if login_id.is_some_and(|id| active.as_ref().is_none_or(|a| a.login_id != id)) {
return false;
}
let Some(attempt) = active.as_ref() else {
return false;
};
attempt.cancel.cancel();
(attempt.login_id.clone(), attempt.completion.clone())
};
// A partial callback request can stall the blocking HTTP worker. Cancellation
// already fences commit; primary logout must not wait indefinitely for I/O.
if tokio::time::timeout(std::time::Duration::from_secs(10), async {
let _start = self.start_gate.lock().await;
completion.wait_for(|state| state.is_complete()).await
})
.await
.is_ok()
{
self.clear(&login_id).await;
}
// Retain a timed-out attempt so a replacement still waits for port cleanup.
true
}
async fn clear(&self, login_id: &str) {
let mut active = self.active.lock().await;
if active
.as_ref()
.is_some_and(|attempt| attempt.login_id == login_id)
{
*active = None;
}
}
async fn configuration_is_current(
&self,
target: &EnterpriseLoginTarget,
keyring_backend: AuthKeyringBackendKind,
) -> bool {
let Ok(thread_id) = ThreadId::from_string(&target.thread_id) else {
return false;
};
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
return false;
};
let current = thread.config().await;
let Ok(config) = self
.config_manager
.load_latest_config_with_session_layers(&current.config_layer_stack, &current.cwd)
.await
else {
return false;
};
let config = thread.runtime_mcp_config_and_context(&config).await.0;
let auth = self.auth_manager.auth_cached();
let servers = codex_mcp::effective_mcp_servers(&config, auth.as_ref());
config.xaa_enabled
&& config.auth_keyring_backend_kind == keyring_backend
&& servers.get(&target.server_name).is_some_and(|server| {
server.config().enabled
&& server.config().ema_registration() == Some(&target.registration)
})
}
#[expect(
clippy::await_holding_invalid_type,
reason = "serialize start/cancel through callback shutdown; the worker uses a separate state lock"
)]
pub(crate) async fn start(
self: &Arc<Self>,
request: EnterpriseOAuthLoginRequest<'_>,
scope: codex_config::McpEmaAuthScope,
target: EnterpriseLoginTarget,
) -> Result<EnterpriseLogin, JSONRPCErrorError> {
// MCP requests are not in the account request queue. Serialize start and
// cancellation here; the separate commit gate stays responsive to the worker.
let setup_cancel = self.setup_cancel.lock().await.child_token();
let _start = tokio::select! {
biased;
_ = setup_cancel.cancelled() => return Err(internal_error("enterprise sign-in was cancelled")),
guard = self.start_gate.lock() => guard,
};
let previous = {
let active = self.active.lock().await;
// Keep the cancelled attempt installed until its callback worker closes.
// A cancelled replacement request leaves the next start responsible for waiting.
active.as_ref().map(|attempt| {
attempt.cancel.cancel();
(attempt.login_id.clone(), attempt.completion.clone())
})
};
if let Some((login_id, mut completion)) = previous {
// An abandoned setup request drops its flow and closes this channel.
let _ = tokio::select! {
biased;
_ = setup_cancel.cancelled() => return Err(internal_error("enterprise sign-in was cancelled")),
result = tokio::time::timeout(
std::time::Duration::from_secs(10),
completion.wait_for(|state| state.is_complete()),
) => result.map_err(|_| internal_error("previous enterprise sign-in did not close"))?,
};
self.clear(&login_id).await;
}
let login_generation = self
.auth_manager
.auth_change_state_receiver()
.borrow()
.login_generation;
let account = self
.auth_manager
.auth_cached()
.filter(|auth| ema_auth_scope(Some(auth)).as_ref() == Some(&scope))
.ok_or_else(|| internal_error("Codex account changed during enterprise sign-in"))?;
if !self
.auth_manager
.account_login_is_current(&account)
.await
.unwrap_or(false)
{
return Err(internal_error(
"Codex account changed during enterprise sign-in",
));
}
let keyring_backend = request.keyring_backend_kind;
// Keep commit cancellation under `active`; cancelling the setup epoch must
// not race an already-admitted synchronous credential write.
let cancel = CancellationToken::new();
let login_id = Uuid::new_v4().to_string();
let (completed, completion) = watch::channel(EnterpriseLoginCompletion::Pending);
*self.active.lock().await = Some(EnterpriseLoginAttempt {
login_id: login_id.clone(),
cancel: cancel.clone(),
completion: completion.clone(),
});
let handle = tokio::select! {
biased;
_ = setup_cancel.cancelled() => Err(internal_error("enterprise sign-in was cancelled")),
_ = cancel.cancelled() => Err(internal_error("enterprise sign-in was cancelled")),
result = perform_enterprise_oauth_login_return_url(request) =>
result.map_err(|error| internal_error(
EmaErrorDetail::from_error(
&error.context(EmaErrorDetail::new("failed to start enterprise sign-in")),
).to_string(),
)),
};
let handle = match handle {
Ok(handle) => handle,
Err(error) => {
self.clear(&login_id).await;
completed.send_replace(EnterpriseLoginCompletion::Failed(EmaErrorDetail::new(
"failed to start enterprise sign-in",
)));
return Err(error);
}
};
let callback_closed = handle.callback_closed().shared();
let authorization_url = handle.authorization_url();
let lifecycle = Arc::clone(self);
let completion_id = login_id.clone();
tokio::spawn(async move {
let result = tokio::select! {
biased;
_ = cancel.cancelled() =>
Err(EmaErrorDetail::new("Enterprise sign-in was cancelled.").into()),
result = async {
let credentials = handle.wait().await.context(EmaErrorDetail::new(
"Enterprise sign-in authorization failed.",
))?;
callback_closed.clone().await;
let mut active = credentials.commit_if(|| async {
lifecycle.auth_manager.reload().await;
let eligible = lifecycle.auth_manager.account_login_is_current(&account).await.unwrap_or(false)
&& lifecycle.configuration_is_current(&target, keyring_backend).await;
// Reread persisted account authority after acquiring the credential
// lock, including changes made by another app-server process.
lifecycle.auth_manager.reload().await;
if !eligible || !lifecycle.auth_manager.account_login_is_current(&account).await.unwrap_or(false) {
return None;
}
// Keep cancellation responsive during the async checks above.
// Once admitted, retain this guard through the synchronous write.
let active = lifecycle.active.lock().await;
let current = active.as_ref().is_some_and(|attempt| {
attempt.login_id == completion_id && !attempt.cancel.is_cancelled()
})
&& lifecycle.auth_manager.auth_change_state_receiver().borrow().login_generation == login_generation
&& ema_auth_scope(lifecycle.auth_manager.auth_cached().as_ref()).as_ref() == Some(&scope);
if !current {
return None;
}
// The credential lock is held: revoke cached bearers before replacing
// the grant, and let new threads pin only the committed credential.
lifecycle.config_manager.revoke_mcp_ema();
Some(active)
}).await.context(EmaErrorDetail::new(
"Enterprise sign-in credential commit failed.",
))?;
// A successful commit is no longer cancelable. Clear it while
// still holding the commit gate.
*active = None;
Ok(())
} => result,
};
// The canceled wait future has dropped its listener guard. Also wait
// for the blocking callback worker before allowing a fixed-port retry.
callback_closed.await;
if result.is_err() {
lifecycle.clear(&completion_id).await;
}
completed.send_replace(match result {
Ok(()) => EnterpriseLoginCompletion::Succeeded,
Err(error) => EnterpriseLoginCompletion::Failed(EmaErrorDetail::from_error(&error)),
});
});
Ok(EnterpriseLogin {
login_id,
authorization_url,
completion,
})
}
}

View File

@@ -0,0 +1,200 @@
//! Gateway sign-in RPCs share credentials with inference and bind cancellation to the initiating connection.
//! Cancellation is acknowledged only after the active login releases its slot.
use super::*;
use crate::gateway_oauth_notifications::status_fields;
use crate::transport::ConnectionId;
use codex_app_server_protocol::GatewayOAuthCancelResponse;
use codex_app_server_protocol::GatewayOAuthLoginResponse;
use codex_app_server_protocol::GatewayOAuthReadResponse;
use codex_login::OAuthSessionManager;
use codex_model_provider::GatewayAuthManager;
use std::sync::PoisonError;
pub(super) struct ActiveGatewayLogin {
owner: ConnectionId,
cancel: CancellationToken,
finished: CancellationToken,
}
struct LoginGuard(Arc<std::sync::Mutex<Option<ActiveGatewayLogin>>>);
impl Drop for LoginGuard {
fn drop(&mut self) {
if let Some(active) = self.0.lock().unwrap_or_else(PoisonError::into_inner).take() {
active.finished.cancel();
}
}
}
impl AccountRequestProcessor {
async fn gateway_client(
&self,
model_provider: Option<String>,
) -> Result<(Arc<Config>, Option<Arc<OAuthSessionManager>>), JSONRPCErrorError> {
let config = match model_provider.as_deref() {
Some(provider_id) => {
let config = config_for_provider(&self.config, provider_id)?;
// Explicit selectors use startup definitions, so validate against current policy.
self.config_manager
.check_thread_model_provider(&config)
.await
.map_err(|err| config_load_error(&err))?;
config
}
None => Arc::new(
self.config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
.map_err(|err| config_load_error(&err))?,
),
};
let manager = codex_model_provider::create_model_provider(
config.model_provider.clone(),
Some(Arc::clone(&self.auth_manager)),
)
.gateway_auth_manager()
.map_err(|error| internal_error(error.to_string()))?;
let session = manager
.as_deref()
.and_then(GatewayAuthManager::oauth_session);
// Keep sign-in status alive when clients alternate between providers.
if let Some(manager) = &manager {
self.gateway_clients
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(config.model_provider_id.clone(), Arc::clone(manager));
}
Ok((config, session))
}
pub(crate) async fn gateway_oauth_read(
&self,
params: codex_app_server_protocol::GatewayOAuthReadParams,
) -> Result<GatewayOAuthReadResponse, JSONRPCErrorError> {
let (config, client) = self.gateway_client(params.model_provider).await?;
let state = if let Some(client) = client {
Some(status_fields(
client
.status()
.await
.map_err(|err| internal_error(err.to_string()))?,
))
} else {
None
};
Ok(GatewayOAuthReadResponse {
provider_id: config.model_provider_id.clone(),
provider_name: config.model_provider.name.clone(),
required: state.is_some(),
status: state.as_ref().map(|state| state.0),
error: state.and_then(|state| state.1),
})
}
pub(crate) async fn gateway_oauth_login(
&self,
params: codex_app_server_protocol::GatewayOAuthLoginParams,
owner: ConnectionId,
connection_gate: &crate::connection_rpc_gate::ConnectionRpcGate,
) -> Result<GatewayOAuthLoginResponse, JSONRPCErrorError> {
let cancel = CancellationToken::new();
let guard = {
let mut active = self
.gateway_login
.lock()
.unwrap_or_else(PoisonError::into_inner);
if connection_gate.is_closed() {
return Err(invalid_request("The connection is closed"));
}
if active.is_some() {
return Err(invalid_request("Gateway sign-in is already in progress"));
}
*active = Some(ActiveGatewayLogin {
owner,
cancel: cancel.clone(),
finished: CancellationToken::new(),
});
LoginGuard(Arc::clone(&self.gateway_login))
};
let (config, client) = self.gateway_client(params.model_provider).await?;
let client = client
.ok_or_else(|| invalid_request("The selected provider does not use gateway OAuth"))?;
if config.model_provider.requires_openai_auth
&& config.model_provider.env_key.is_none()
&& config.model_provider.experimental_bearer_token.is_none()
&& config.model_provider.auth.is_none()
&& self.auth_manager.auth_cached().is_none()
{
return Err(invalid_request(
"Sign in to your primary account before signing in to the gateway",
));
}
let (url_tx, url_rx) = tokio::sync::oneshot::channel();
let login = client.login_with_browser(cancel.cancelled(), |url| {
let _ = url_tx.send(url.to_string());
});
tokio::pin!(login);
let result = tokio::select! {
result = &mut login => result,
url = url_rx => {
if let Ok(url) = url {
self.outgoing.send_server_notification_to_connections(&[owner], ServerNotification::GatewayOAuthChanged(codex_app_server_protocol::GatewayOAuthChangedNotification {
auth_url: Some(url), provider_id: config.model_provider_id.clone(),
status: codex_app_server_protocol::GatewayOAuthStatus::Started, error: None,
})).await;
}
login.await
}
};
result.map_err(|err| internal_error(err.to_string()))?;
drop(guard);
Ok(GatewayOAuthLoginResponse {})
}
pub(crate) async fn gateway_oauth_cancel(
&self,
owner: ConnectionId,
) -> Result<GatewayOAuthCancelResponse, JSONRPCErrorError> {
let finished = {
let active = self
.gateway_login
.lock()
.unwrap_or_else(PoisonError::into_inner);
let Some(active) = active.as_ref() else {
return Ok(GatewayOAuthCancelResponse {});
};
if active.owner != owner {
return Err(invalid_request(
"Gateway sign-in belongs to another connection",
));
}
active.cancel.cancel();
active.finished.clone()
};
finished.cancelled().await;
Ok(GatewayOAuthCancelResponse {})
}
pub(crate) fn gateway_connection_closed(&self, owner: ConnectionId) {
let active = self
.gateway_login
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(active) = active.as_ref()
&& active.owner == owner
{
active.cancel.cancel();
}
}
pub(super) fn cancel_gateway_login(&self) {
let active = self
.gateway_login
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(active) = active.as_ref() {
active.cancel.cancel();
}
}
}

View File

@@ -0,0 +1,207 @@
//! Validates and persists GCP setup without changing saved login credentials or existing threads.
use super::super::config_processor::map_error as map_config_error;
use super::AccountRequestProcessor;
use super::CloudLoginProvider;
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use codex_app_server_protocol::ClientResponsePayload;
use codex_app_server_protocol::GcpSetupParams;
use codex_app_server_protocol::GcpSetupResponse;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_config::apply_default_gcp_auth;
use codex_login::RefreshTokenError;
use codex_model_provider::create_model_provider;
use codex_model_provider_info::GCP_PROVIDER_ID;
use codex_model_provider_info::ModelProviderInfo;
use codex_model_provider_info::merge_gcp_provider_overrides;
use codex_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::de::MapAccess;
use serde::de::Visitor;
use serde::de::value::MapAccessDeserializer;
use serde_json::json;
use std::fmt;
use std::io::BufReader;
use std::io::ErrorKind;
use std::path::Path;
use std::path::PathBuf;
use tokio::fs::File;
pub(crate) async fn handle_gcp_setup(
processor: &AccountRequestProcessor,
params: GcpSetupParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
processor.ensure_provider_login_allowed(CloudLoginProvider::Gcp)?;
let network_policy = processor
.auth_manager
.application_network_policy()
.for_current_account();
let layers = processor
.model_catalog
.load_startup_config_layers()
.await
.map_err(|err| internal_error(format!("failed to load configuration layers: {err}")))?;
let (write, provider) = processor
.config_manager
.prepare_provider_config(
&layers,
GCP_PROVIDER_ID,
[
("project_id", Some(params.project_id.trim())),
(
"location",
Some(params.location.as_deref().unwrap_or("global").trim()),
),
("credential_file", params.credential_file.as_deref()),
],
)
.map_err(map_config_error)?;
if provider.base_url.is_some() {
return Err(invalid_request(
"Google Cloud has a custom `base_url`. Clear `model_providers.gcp.base_url` before configuring a project and location.",
));
}
// Even checking a Windows UNC credential path can contact the remote host.
let permit = network_policy
.acquire_for_unsupported_sdk()
.map_err(|err| invalid_request(err.to_string()))?;
permit
.run(verify_credentials(provider, &processor.config.cwd))
.await
.map_err(|err| invalid_request(err.to_string()))??;
processor
.config_manager
.commit_provider_config(write)
.await
.map_err(map_config_error)?;
processor.cancel_active_login().await;
processor.model_catalog.invalidate().await;
Ok(Some(GcpSetupResponse {}.into()))
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
enum AuthErrorReason {
GcloudNotInstalled,
CredentialFileInvalid,
AuthCommandFailed,
}
impl AuthErrorReason {
fn error(self, message: impl Into<String>) -> JSONRPCErrorError {
let mut error = invalid_request(message);
error.data = Some(json!({ "reason": self }));
error
}
}
async fn open_credential_file(path: &Path) -> std::io::Result<File> {
if !tokio::fs::metadata(path).await?.is_file() {
return Err(std::io::Error::new(
ErrorKind::InvalidInput,
"expected a regular file",
));
}
File::open(path).await
}
// Require a JSON object. Serde also accepts positional arrays when deserializing a struct.
struct AdcObject;
impl<'de> Visitor<'de> for AdcObject {
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a Google Cloud credential object")
}
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<(), A::Error> {
#[derive(Deserialize)]
struct Adc {
#[serde(rename = "type")]
kind: String,
}
let adc = Adc::deserialize(MapAccessDeserializer::new(map))?;
if adc.kind.trim().is_empty() {
return Err(serde::de::Error::custom(
"expected a nonempty credential type",
));
}
Ok(())
}
}
async fn validate_adc_file(file: File) -> std::io::Result<()> {
let file = file.into_std().await;
tokio::task::spawn_blocking(move || {
// Stream past type-specific fields without retaining the credential contents.
let mut json = serde_json::Deserializer::from_reader(BufReader::new(file));
json.deserialize_map(AdcObject)?;
json.end()?;
Ok(())
})
.await?
}
async fn verify_credentials(
configured: ModelProviderInfo,
cwd: &AbsolutePathBuf,
) -> Result<(), JSONRPCErrorError> {
configured
.validate_gcp_credential_file()
.map_err(|err| AuthErrorReason::CredentialFileInvalid.error(err))?;
let default_gcloud = configured.auth.is_none();
let mut candidate = ModelProviderInfo::create_gcp_provider();
merge_gcp_provider_overrides(Some(&mut candidate), configured).map_err(invalid_request)?;
apply_default_gcp_auth(&mut candidate, cwd);
candidate.validate().map_err(invalid_request)?;
let auth_file = candidate.credential_file.clone().or_else(|| {
if default_gcloud {
std::env::var_os("GOOGLE_APPLICATION_CREDENTIALS").map(PathBuf::from)
} else {
None
}
});
if let Some(path) = auth_file {
let path = cwd.as_path().join(path);
let file = open_credential_file(&path).await.map_err(|err| {
AuthErrorReason::CredentialFileInvalid.error(format!(
"Cannot read the Google Cloud credential file: {err}"
))
})?;
if default_gcloud {
validate_adc_file(file).await.map_err(|_| AuthErrorReason::CredentialFileInvalid.error(
"Expected a Google Cloud credential file containing a JSON object with a nonempty string type.",
))?;
}
}
let provider = create_model_provider(candidate, /*auth_manager*/ None);
provider
.runtime_base_url()
.await
.map_err(|err| invalid_request(err.to_string()))?;
// This fresh provider owns a command-backed manager. A refresh runs that command
// once and preserves errors that the inference auth path reduces to missing auth.
let auth_manager = provider
.auth_manager()
.ok_or_else(|| internal_error("Missing GCP auth manager."))?;
if let Err(err) = auth_manager.refresh_token().await {
if default_gcloud
&& let RefreshTokenError::Transient(err) = err
&& err.kind() == ErrorKind::NotFound
&& cwd.as_path().is_dir()
{
return Err(AuthErrorReason::GcloudNotInstalled.error(
"Cannot find gcloud on the app-server host. Check its installation and PATH.",
));
}
return Err(AuthErrorReason::AuthCommandFailed
.error("The Google Cloud auth command could not obtain an access token."));
}
Ok(())
}

View File

@@ -0,0 +1,169 @@
use super::*;
const RATE_LIMIT_RESET_REQUEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
const RATE_LIMIT_RESET_DETAILS_REQUEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5);
#[cfg(debug_assertions)]
const RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR: &str =
"CODEX_TEST_RATE_LIMIT_RESET_REQUEST_TIMEOUT_MS";
impl AccountRequestProcessor {
pub(super) async fn detailed_rate_limit_reset_credits(
client: &BackendClient,
) -> Option<RateLimitResetCreditsSummary> {
let details = match tokio::time::timeout(
RATE_LIMIT_RESET_DETAILS_REQUEST_TIMEOUT,
client.list_rate_limit_reset_credits(),
)
.await
{
Ok(Ok(details)) => details,
Ok(Err(err)) => {
tracing::warn!(
"failed to fetch rate limit reset credit details; falling back to the usage response: {err}"
);
return None;
}
Err(_) => {
tracing::warn!(
"rate limit reset credit detail request timed out; falling back to the usage response"
);
return None;
}
};
match rate_limit_reset_credits_from_backend(details) {
Ok(summary) => Some(summary),
Err(err) => {
tracing::warn!(
"failed to parse rate limit reset credit details; falling back to the usage response: {err}"
);
None
}
}
}
pub(crate) async fn consume_account_rate_limit_reset_credit(
&self,
params: ConsumeAccountRateLimitResetCreditParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
if params.idempotency_key.is_empty() {
return Err(invalid_request("idempotencyKey must not be empty"));
}
if params.credit_id.as_deref().is_some_and(str::is_empty) {
return Err(invalid_request("creditId must not be empty"));
}
let client = self.rate_limit_reset_backend_client().await?;
let request_timeout = RATE_LIMIT_RESET_REQUEST_TIMEOUT;
#[cfg(debug_assertions)]
let request_timeout = std::env::var(RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR)
.ok()
.and_then(|value| value.parse::<u64>().ok())
.map(Duration::from_millis)
.unwrap_or(request_timeout);
let response = tokio::time::timeout(request_timeout, async {
match params.credit_id.as_deref() {
Some(credit_id) => {
client
.consume_rate_limit_reset_credit_by_id(&params.idempotency_key, credit_id)
.await
}
None => {
client
.consume_rate_limit_reset_credit(&params.idempotency_key)
.await
}
}
})
.await
.map_err(|_| internal_error("rate limit reset consume timed out"))?
.map_err(|err| internal_error(format!("failed to consume rate limit reset: {err}")))?;
let outcome = match response.code {
BackendConsumeRateLimitResetCreditCode::Reset => {
ConsumeAccountRateLimitResetCreditOutcome::Reset
}
BackendConsumeRateLimitResetCreditCode::NothingToReset => {
ConsumeAccountRateLimitResetCreditOutcome::NothingToReset
}
BackendConsumeRateLimitResetCreditCode::NoCredit => {
ConsumeAccountRateLimitResetCreditOutcome::NoCredit
}
BackendConsumeRateLimitResetCreditCode::AlreadyRedeemed => {
ConsumeAccountRateLimitResetCreditOutcome::AlreadyRedeemed
}
};
Ok(Some(
ConsumeAccountRateLimitResetCreditResponse { outcome }.into(),
))
}
async fn rate_limit_reset_backend_client(&self) -> Result<BackendClient, JSONRPCErrorError> {
let Some((auth, http_client_factory)) =
self.auth_manager.auth_with_http_client_factory().await
else {
return Err(invalid_request(
"codex account authentication required for rate limit reset credits",
));
};
if !auth.uses_codex_backend() {
return Err(invalid_request(
"chatgpt authentication required for rate limit reset credits",
));
}
self.backend_client(&auth, http_client_factory).await
}
}
fn rate_limit_reset_credits_from_backend(
details: BackendRateLimitResetCreditsDetails,
) -> Result<RateLimitResetCreditsSummary, String> {
let credits = details
.credits
.into_iter()
.map(rate_limit_reset_credit_from_backend)
.collect::<Result<Vec<_>, _>>()?;
Ok(RateLimitResetCreditsSummary {
available_count: details.available_count,
credits: Some(credits),
})
}
fn rate_limit_reset_credit_from_backend(
credit: BackendRateLimitResetCreditDetails,
) -> Result<RateLimitResetCredit, String> {
let reset_type = match credit.reset_type.as_str() {
"codex_rate_limits" => RateLimitResetType::CodexRateLimits,
_ => RateLimitResetType::Unknown,
};
let status = match credit.status.as_str() {
"available" => RateLimitResetCreditStatus::Available,
"redeeming" => RateLimitResetCreditStatus::Redeeming,
"redeemed" => RateLimitResetCreditStatus::Redeemed,
_ => RateLimitResetCreditStatus::Unknown,
};
let granted_at = rate_limit_reset_credit_timestamp(&credit.granted_at)
.map_err(|err| format!("invalid granted_at for credit `{}`: {err}", credit.id))?;
let expires_at = credit
.expires_at
.as_deref()
.map(rate_limit_reset_credit_timestamp)
.transpose()
.map_err(|err| format!("invalid expires_at for credit `{}`: {err}", credit.id))?;
Ok(RateLimitResetCredit {
id: credit.id,
reset_type,
status,
granted_at,
expires_at,
title: credit.title,
description: credit.description,
})
}
fn rate_limit_reset_credit_timestamp(timestamp: &str) -> Result<i64, String> {
DateTime::parse_from_rfc3339(timestamp)
.map(|timestamp| timestamp.timestamp())
.map_err(|err| format!("failed to parse timestamp `{timestamp}`: {err}"))
}

View File

@@ -0,0 +1,115 @@
//! Keep optional security reminders on the app-server's existing runtime identity.
//! Only saved ChatGPT credentials matching the active login may fetch a notice.
use super::*;
use codex_app_server_protocol::AccountSecuritySetupAction;
use codex_app_server_protocol::AccountSecuritySetupNotice;
use codex_app_server_protocol::GetAccountSecuritySetupResponse;
use codex_http_client::ClientRouteClass;
use codex_http_client::RouteAwareClientPool;
use serde::Deserialize;
#[derive(Deserialize)]
struct Response {
notice: Option<Notice>,
}
#[derive(Deserialize)]
struct Notice {
title: String,
description: String,
action: AccountSecuritySetupAction,
}
impl AccountRequestProcessor {
pub(crate) async fn get_account_security_setup(&self) -> GetAccountSecuritySetupResponse {
let notice = tokio::time::timeout(Duration::from_secs(/*secs*/ 3), async {
let config = self.load_latest_config().await;
let (auth, factory) = self.auth_manager.auth_with_http_client_factory().await?;
let source_generation = self
.auth_manager
.auth_change_state_for(&auth)?
.source_generation;
let saved = config
.auth_config()
.load_auth(/*enable_codex_api_key_env*/ false)
.await
.ok()
.flatten()?;
if !matches!(saved, CodexAuth::Chatgpt(_)) || saved.is_fedramp_account() {
return None;
}
if auth.auth_mode() != codex_protocol::auth::AuthMode::Chatgpt
|| saved.get_token().ok()? != auth.get_token().ok()?
{
return None;
}
let account_id = auth.get_account_id()?;
let user_id = auth.get_chatgpt_user_id()?;
let url = format!(
"{}/wham/security-setup",
config.chatgpt_base_url.trim_end_matches('/')
);
let runtime = self
.thread_manager
.runtime_auth_for_config(&config)
.ok()?
.filter(|_| codex_runtime_agent_instance::is_openai_api_url(&url));
let resolved = codex_model_provider::auth_provider_for_request(
&auth,
runtime.as_ref(),
/*headers*/ &Default::default(),
)
.await
.ok()?;
let factory = resolved.bind_http_client_factory(factory).ok()?;
let client =
RouteAwareClientPool::new_without_redirects(factory, ClientRouteClass::Api);
let mut headers = resolved
.auth
.apply_auth_headers(Default::default())
.await
.ok()?;
headers.insert("chatgpt-account-id", account_id.parse().ok()?);
resolved.validate_headers(&headers).ok()?;
let response = client
.get(&url)
.headers(headers)
.header(
"User-Agent",
codex_login::default_client::get_codex_user_agent(),
)
.send()
.await
.ok()?;
if !response.status().is_success() {
return None;
}
let notice = response.json::<Response>().await.ok()?.notice?;
let current = self.auth_manager.auth().await?;
if self
.auth_manager
.auth_change_state_for(&auth)?
.source_generation
!= source_generation
|| current.auth_mode() != codex_protocol::auth::AuthMode::Chatgpt
|| current.get_account_id().as_ref() != Some(&account_id)
|| current.get_chatgpt_user_id().as_ref() != Some(&user_id)
|| current.is_fedramp_account()
{
return None;
}
Some(AccountSecuritySetupNotice {
account_id,
user_id,
title: notice.title,
description: notice.description,
action: notice.action,
})
})
.await
.ok()
.flatten();
GetAccountSecuritySetupResponse { notice }
}
}

View File

@@ -0,0 +1,641 @@
//! Discovers routing for the selected ChatGPT workspace without crossing auth owners.
//! Discovery is coordinated per routing key; a cache miss never proves independence.
//! Credential refreshes invalidate the cache, but do not cancel same-owner discovery.
//! Model sessions retain their original bootstrap scope across configuration changes.
use super::*;
use codex_app_server_protocol::AccountRoutingOverride;
use codex_backend_client::AccountEntry;
use codex_config::ConfigLoadError;
use codex_http_client::NetworkPolicyDenied;
use codex_login::RefreshTokenError;
use codex_login::WorkspaceRouting;
use codex_login::WorkspaceRoutingRequest;
use codex_login::WorkspaceRoutingResolver;
use codex_login::auth::RefreshTokenFailedError;
use codex_model_provider::ProviderAccount;
use codex_model_provider::ProviderAccountError;
use codex_model_provider::ProviderAccountState;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::Weak;
use tokio::sync::Semaphore;
use url::Url;
#[derive(Clone, PartialEq, Eq, Hash)]
pub(super) struct WorkspaceRoutingKey {
auth_generation: u64,
chatgpt_account_id: String,
effective_chatgpt_base_url: String,
required_chatgpt_base_url: Option<String>,
}
// Results live through same-key waiters, even if another key replaces the cache.
// Weak entries are pruned on the next read after those requests finish.
pub(super) type WorkspaceRoutingFetches = HashMap<WorkspaceRoutingKey, Weak<WorkspaceRoutingFetch>>;
pub(super) struct WorkspaceRoutingFetch {
discovery: Semaphore,
routing: Mutex<Option<CachedWorkspaceRouting>>,
}
#[derive(Clone)]
pub(super) struct CachedWorkspaceRouting {
key: WorkspaceRoutingKey,
routing: WorkspaceRouting,
name: Option<String>,
}
pub(super) struct AccountRead {
account_state: ProviderAccountState,
user_id: Option<String>,
pub(super) workspace_routing: Option<WorkspaceRouting>,
workspace_name: Option<String>,
}
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum AccountReadError {
#[error(transparent)]
InvalidAccount(#[from] ProviderAccountError),
#[error(transparent)]
Routing(#[from] WorkspaceRoutingError),
}
/// Routing failures carry no account, URL, or backend data. Config failures retain
/// only a location or structured error category, never the raw config error.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum WorkspaceRoutingError {
#[error("failed to load workspace requirements: {0}")]
RequirementsLoad(String),
#[error("workspace routing requires a ChatGPT account id")]
MissingAccountId,
#[error("workspace routing discovery cancelled")]
DiscoveryCancelled,
#[error("account changed during workspace routing discovery")]
AccountChanged,
#[error("workspace routing discovery unauthorized (401)")]
DiscoveryUnauthorized,
#[error(transparent)]
RefreshTokenRejected(RefreshTokenFailedError),
#[error("workspace routing discovery failed")]
DiscoveryFailed,
#[error("selected workspace missing from routing discovery")]
MissingWorkspace,
#[error("duplicate workspace in routing discovery")]
DuplicateWorkspace,
#[error("failed to reload workspace requirements: {0}")]
RequirementsReload(String),
#[error("configuration changed during workspace routing discovery; retry account/read")]
ConfigurationChanged,
#[error("invalid model provider URL")]
InvalidProviderUrl,
#[error("invalid ChatGPT backend URL")]
InvalidBootstrapUrl,
#[error("invalid session ChatGPT backend URL")]
InvalidSessionBootstrapUrl,
#[error("ChatGPT backend changed; start a new thread before sending more content")]
SessionBackendChanged,
#[error("workspace routing discovery cancelled during shutdown")]
Shutdown,
#[error("workspace routing discovery timed out")]
DiscoveryTimeout,
#[error("workspace routing discovery missing backend origin")]
MissingBackendOrigin,
#[error("workspace routing discovery has invalid account routing override")]
InvalidRoutingOverride,
#[error("workspace routing discovery must return an origin")]
BackendIsNotOrigin,
#[error("required ChatGPT backend conflicts with workspace routing")]
BackendConflict,
#[error("invalid workspace backend URL")]
InvalidBackendUrl,
#[error("workspace backend must use an HTTPS origin without credentials")]
InvalidBackendOrigin,
}
fn workspace_config_load_reason(error: &io::Error) -> String {
// Parser messages and cloud bundle errors can quote secrets, even without
// their source snippets. Retain only structured diagnostics before these
// errors reach JSON-RPC clients, login notifications, or tracing.
let mut current = error
.get_ref()
.map(|source| source as &(dyn std::error::Error + 'static));
while let Some(source) = current {
if let Some(config) = source.downcast_ref::<ConfigLoadError>() {
let config = config.config_error();
let start = config.range.start;
// Non-file diagnostics store a display name, which can contain
// backend-supplied policy names and IDs, in this field.
if !config.path.is_absolute() {
return format!(
"invalid non-file configuration at line {}, column {}",
start.line, start.column
);
}
return format!(
"invalid configuration at {}:{}:{}",
config.path.display(),
start.line,
start.column
);
}
if let Some(cloud) = source.downcast_ref::<CloudConfigBundleLoadError>() {
let reason = match cloud.code() {
CloudConfigBundleLoadErrorCode::Timeout => "request timed out",
CloudConfigBundleLoadErrorCode::Auth
| CloudConfigBundleLoadErrorCode::RequestFailed => {
// Cloud loading currently erases the typed denial. Match
// only known safe policy messages, never forward raw text.
let message = cloud.to_string();
if let Some(policy) = [
NetworkPolicyDenied::Unavailable,
NetworkPolicyDenied::Destination,
NetworkPolicyDenied::Revoked,
NetworkPolicyDenied::UnsupportedTransport,
]
.into_iter()
.find(|policy| policy.to_string() == message)
{
return policy.to_string();
}
if cloud.code() == CloudConfigBundleLoadErrorCode::Auth {
"authentication failed"
} else {
"request failed"
}
}
CloudConfigBundleLoadErrorCode::InvalidBundle => "invalid bundle",
CloudConfigBundleLoadErrorCode::Internal => "internal error",
};
return match cloud.status_code() {
Some(status) => format!("cloud config: {reason} (HTTP {status})"),
None => format!("cloud config: {reason}"),
};
}
if let Some(policy) = source.downcast_ref::<NetworkPolicyDenied>() {
return policy.to_string();
}
current = source.source();
}
// Use the OS error or kind, never an untyped error's potentially secret message.
match error.raw_os_error() {
Some(code) => io::Error::from_raw_os_error(code).to_string(),
None => error.kind().to_string(),
}
}
impl WorkspaceRoutingResolver for AccountRequestProcessor {
fn resolve(
&self,
request: WorkspaceRoutingRequest,
) -> Pin<Box<dyn Future<Output = io::Result<Option<WorkspaceRouting>>> + Send + '_>> {
Box::pin(async move {
self.read_account(Some(&request))
.await
.map(|account| account.workspace_routing)
.map_err(|error| match error {
AccountReadError::InvalidAccount(error) => io::Error::other(error),
AccountReadError::Routing(WorkspaceRoutingError::RefreshTokenRejected(
error,
)) => io::Error::new(io::ErrorKind::PermissionDenied, error),
AccountReadError::Routing(error) => io::Error::new(
if error == WorkspaceRoutingError::DiscoveryUnauthorized {
io::ErrorKind::PermissionDenied
} else {
io::ErrorKind::Other
},
error,
),
})
})
}
}
impl AccountRequestProcessor {
pub(super) async fn read_account_for_background_workspace_routing(
&self,
) -> Result<Option<AccountRead>, AccountReadError> {
if !self
.auth_manager
.auth_cached()
.as_ref()
.is_some_and(CodexAuth::is_chatgpt_auth)
{
return Ok(None);
}
self.read_account(/*request*/ None).await.map(Some)
}
pub(crate) fn notify_workspace_routing_to_connection(&self, connection_id: ConnectionId) {
let processor = self.clone();
let auth_changes = self.auth_manager.auth_change_state_receiver();
let owner_generation = auth_changes.borrow().owner_generation;
tokio::spawn(async move {
if auth_changes.borrow().owner_generation != owner_generation {
return;
}
if let Ok(Some(response)) = processor
.read_account_for_background_workspace_routing()
.await
&& response.workspace_routing.is_some()
&& auth_changes.borrow().owner_generation == owner_generation
{
let notification = processor.current_account_updated_notification();
processor
.outgoing
.send_account_notification(
Some(connection_id),
&auth_changes,
owner_generation,
AccountNotification::Updated(notification),
)
.await;
}
});
}
pub(crate) async fn get_account(
&self,
params: GetAccountParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.refresh_token_if_requested(params.refresh_token).await;
let read = self
.read_account(/*request*/ None)
.await
.map_err(|error| match error {
AccountReadError::InvalidAccount(error) => invalid_request(error.to_string()),
AccountReadError::Routing(error) => internal_error(error.to_string()),
})?;
let mut account = read.account_state.account.map(Account::from);
if let Some(Account::Chatgpt { workspace_name, .. }) = &mut account {
*workspace_name = read.workspace_name;
}
Ok(Some(
GetAccountResponse {
account,
user_id: read.user_id,
requires_openai_auth: read.account_state.requires_openai_auth,
workspace_routing: read.workspace_routing.map(|routing| {
codex_app_server_protocol::WorkspaceRouting {
chatgpt_account_id: routing.chatgpt_account_id,
backend_origin: routing.backend_origin,
account_routing_override: match routing.account_routing_override.as_str() {
"NO_CONSTRAINT" => AccountRoutingOverride::NoConstraint,
"us" => AccountRoutingOverride::Us,
"us_cr" => AccountRoutingOverride::UsCr,
_ => unreachable!("routing discovery validates the override"),
},
}
}),
}
.into(),
))
}
pub(super) async fn read_account(
&self,
request: Option<&WorkspaceRoutingRequest>,
) -> Result<AccountRead, AccountReadError> {
let mut auth_changes = self.auth_manager.auth_change_state_receiver();
let auth_state = *auth_changes.borrow_and_update();
let current_auth_changes = auth_changes.clone();
let read = Box::pin(async {
let load_config = async || {
match request.and_then(|request| request.session.as_deref()) {
Some(session) => {
self.config_manager
.load_retained_session_config(&session.config_layer_stack, &session.cwd)
.await
}
None => {
self.config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
}
}
};
let config = match load_config().await {
Ok(config) => config,
Err(_)
if !self
.auth_manager
.auth_cached()
.as_ref()
.is_some_and(CodexAuth::is_chatgpt_auth) =>
{
self.config.as_ref().clone()
}
Err(error) => {
return Err(WorkspaceRoutingError::RequirementsLoad(
workspace_config_load_reason(&error),
)
.into());
}
};
let auth = self.auth_manager.auth_cached();
let provider = create_model_provider(
config.model_provider.clone(),
Some(self.auth_manager.clone()),
);
let account_state = provider
.account_state()
.map_err(AccountReadError::InvalidAccount)?;
let user_id = auth
.as_ref()
.filter(|_| {
matches!(
&account_state.account,
Some(ProviderAccount::Chatgpt { .. })
)
})
.and_then(CodexAuth::get_chatgpt_user_id);
let mut workspace_routing = if let Some((auth, account_id)) = auth
.as_ref()
.filter(|auth| {
auth.is_chatgpt_auth()
&& (request.is_some()
|| matches!(
account_state.account,
Some(ProviderAccount::Chatgpt { .. })
))
})
.and_then(|auth| auth.get_account_id().map(|account_id| (auth, account_id)))
{
if account_id.is_empty() {
return Err(WorkspaceRoutingError::MissingAccountId.into());
}
let required_chatgpt_base_url = config
.config_layer_stack
.requirements_toml()
.chatgpt_base_url
.clone();
let key = WorkspaceRoutingKey {
auth_generation: auth_state.generation,
chatgpt_account_id: account_id.clone(),
effective_chatgpt_base_url: config.chatgpt_base_url.clone(),
required_chatgpt_base_url: required_chatgpt_base_url.clone(),
};
let fetch = {
let mut fetches = self.workspace_routing_fetches.lock().await;
fetches.retain(|_, fetch| fetch.strong_count() > 0);
if let Some(fetch) = fetches.get(&key).and_then(Weak::upgrade) {
fetch
} else {
let fetch = Arc::new(WorkspaceRoutingFetch {
discovery: Semaphore::new(/*permits*/ 1),
routing: Mutex::new(/*t*/ None),
});
fetches.insert(key.clone(), Arc::downgrade(&fetch));
fetch
}
};
let _permit = fetch
.discovery
.acquire()
.await
.map_err(|_| WorkspaceRoutingError::DiscoveryCancelled)?;
let fetched = fetch.routing.lock().await.clone();
let cached = match fetched {
Some(routing) => Some(routing),
None => self
.workspace_routing
.lock()
.await
.as_ref()
.filter(|cached| cached.key == key)
.cloned(),
};
let routing = if let Some(cached) = cached {
cached
} else {
let runtime = self
.thread_manager
.runtime_auth_for_config(&config)
.map_err(|_| WorkspaceRoutingError::DiscoveryFailed)?;
let mut recovery = self.auth_manager.unauthorized_recovery();
let mut discovery_auth = auth.clone();
let mut discovery_generation = auth_state.generation;
let response = loop {
let client = BackendClient::from_auth_with_runtime(
&config.chatgpt_base_url,
&discovery_auth,
config.http_client_factory(),
runtime.as_ref(),
/*headers*/ &Default::default(),
)
.await
.map_err(|_| WorkspaceRoutingError::DiscoveryFailed)?;
match client.get_accounts_check().await {
Ok(response) => break response,
Err(error) => {
let unauthorized = error.is_unauthorized();
if unauthorized && recovery.has_next() {
let result = recovery.next().await;
let refreshed = *current_auth_changes.borrow();
if refreshed.owner_generation != auth_state.owner_generation {
return Err(WorkspaceRoutingError::AccountChanged.into());
}
if let Err(error) = result
&& refreshed.generation == discovery_generation
{
let cached_failure = self
.auth_manager
.refresh_failure_for_auth(&discovery_auth);
if let RefreshTokenError::Permanent(failed) = error
&& !self.auth_manager.has_external_auth()
&& cached_failure.as_ref() == Some(&failed)
{
return Err(
WorkspaceRoutingError::RefreshTokenRejected(failed)
.into(),
);
}
return Err(
WorkspaceRoutingError::DiscoveryUnauthorized.into()
);
}
discovery_generation = refreshed.generation;
discovery_auth = self
.auth_manager
.auth_cached()
.ok_or(WorkspaceRoutingError::AccountChanged)?;
continue;
}
return Err(if unauthorized {
WorkspaceRoutingError::DiscoveryUnauthorized
} else {
WorkspaceRoutingError::DiscoveryFailed
}
.into());
}
}
};
let mut accounts = response
.accounts
.into_iter()
.filter(|account| account.id == account_id);
let mut entry = accounts
.next()
.ok_or(WorkspaceRoutingError::MissingWorkspace)?;
if accounts.next().is_some() {
return Err(WorkspaceRoutingError::DuplicateWorkspace.into());
}
let latest_config = load_config().await.map_err(|error| {
WorkspaceRoutingError::RequirementsReload(workspace_config_load_reason(
&error,
))
})?;
if latest_config.chatgpt_base_url != config.chatgpt_base_url
|| latest_config.model_provider != config.model_provider
|| latest_config
.config_layer_stack
.requirements_toml()
.chatgpt_base_url
!= required_chatgpt_base_url
{
return Err(WorkspaceRoutingError::ConfigurationChanged.into());
}
let name = entry.name.take();
let routing = resolve_routing(
entry,
required_chatgpt_base_url.as_deref(),
&config.chatgpt_base_url,
)?;
let mut cached = self.workspace_routing.lock().await;
if current_auth_changes.borrow().owner_generation != auth_state.owner_generation
{
return Err(WorkspaceRoutingError::AccountChanged.into());
}
let routing = CachedWorkspaceRouting {
key: WorkspaceRoutingKey {
auth_generation: discovery_generation,
..key
},
routing,
name,
};
// Same-owner refresh can complete a newer discovery first.
if current_auth_changes.borrow().generation == discovery_generation {
*cached = Some(routing.clone());
}
routing
};
*fetch.routing.lock().await = Some(routing.clone());
Some(routing)
} else {
*self.workspace_routing.lock().await = None;
None
};
if let Some(request) = request.filter(|_| workspace_routing.is_some()) {
let origin = Url::parse(&request.provider_base_url)
.map_err(|_| WorkspaceRoutingError::InvalidProviderUrl)?
.origin();
let bootstrap_origin = Url::parse(&config.chatgpt_base_url)
.map_err(|_| WorkspaceRoutingError::InvalidBootstrapUrl)?
.origin();
let session_bootstrap_origin = Url::parse(&request.chatgpt_base_url)
.map_err(|_| WorkspaceRoutingError::InvalidSessionBootstrapUrl)?
.origin();
let selected_backend = workspace_routing.as_ref().is_some_and(|routing| {
routing.routing.backend_origin == origin.ascii_serialization()
});
let workspace_bound = request.previously_routed
|| request.provider_base_url == codex_model_provider::CHATGPT_CODEX_BASE_URL
|| origin == session_bootstrap_origin
|| (session_bootstrap_origin == bootstrap_origin && selected_backend);
if !workspace_bound {
workspace_routing = None;
} else if session_bootstrap_origin != bootstrap_origin {
return Err(WorkspaceRoutingError::SessionBackendChanged.into());
}
}
let (workspace_routing, workspace_name) = workspace_routing
.map(|workspace| (Some(workspace.routing), workspace.name))
.unwrap_or_default();
Ok(AccountRead {
account_state,
user_id,
workspace_routing,
workspace_name,
})
});
let result = tokio::select! {
biased;
_ = self.workspace_routing_shutdown.cancelled() => {
return Err(WorkspaceRoutingError::Shutdown.into());
}
_ = auth_changes.wait_for(|state| state.owner_generation != auth_state.owner_generation) => {
return Err(WorkspaceRoutingError::AccountChanged.into());
}
result = tokio::time::timeout(Duration::from_secs(/*secs*/ 15), read) => {
result.map_err(|_| WorkspaceRoutingError::DiscoveryTimeout)?
}
};
if auth_changes.borrow().owner_generation != auth_state.owner_generation {
return Err(WorkspaceRoutingError::AccountChanged.into());
}
result
}
}
fn resolve_routing(
entry: AccountEntry,
required_chatgpt_base_url: Option<&str>,
effective_base_url: &str,
) -> Result<WorkspaceRouting, AccountReadError> {
let backend = entry
.workspace_backend_origin
.ok_or(WorkspaceRoutingError::MissingBackendOrigin)?;
let account_routing_override = match entry.account_routing_override.as_deref() {
Some(value @ ("NO_CONSTRAINT" | "us" | "us_cr")) => value.to_owned(),
_ => {
return Err(WorkspaceRoutingError::InvalidRoutingOverride.into());
}
};
let required = required_chatgpt_base_url
.map(parse_backend_url)
.transpose()?;
let discovered = if backend == "NO_CONSTRAINT" {
None
} else {
let url = parse_backend_url(&backend)?;
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
return Err(WorkspaceRoutingError::BackendIsNotOrigin.into());
}
Some(url)
};
let origin = match (required, discovered) {
(Some(required), Some(discovered)) => {
if required.origin() != discovered.origin() {
return Err(WorkspaceRoutingError::BackendConflict.into());
}
required.origin()
}
(Some(url), None) | (None, Some(url)) => url.origin(),
(None, None) => parse_backend_url(effective_base_url)?.origin(),
};
Ok(WorkspaceRouting {
chatgpt_account_id: entry.id,
backend_origin: origin.ascii_serialization(),
account_routing_override,
})
}
fn parse_backend_url(value: &str) -> Result<Url, AccountReadError> {
let url = Url::parse(value).map_err(|_| WorkspaceRoutingError::InvalidBackendUrl)?;
if url.scheme() != "https"
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| value.trim() != value
{
return Err(WorkspaceRoutingError::InvalidBackendOrigin.into());
}
Ok(url)
}
#[cfg(test)]
#[path = "workspace_routing_tests.rs"]
mod tests;

View File

@@ -0,0 +1,246 @@
//! Origin resolution, strict discovery validation, and background read eligibility.
use super::*;
use pretty_assertions::assert_eq;
use serde_json::Value;
use test_case::test_case;
#[test_case(CloudConfigBundleLoadErrorCode::RequestFailed, "cloud config: request failed"; "request")]
#[test_case(CloudConfigBundleLoadErrorCode::Auth, "cloud config: authentication failed"; "refresh")]
fn cloud_failures_preserve_policy_denials_but_redact_other_messages(
code: CloudConfigBundleLoadErrorCode,
redacted: &str,
) {
let denied = NetworkPolicyDenied::Destination.to_string();
for (message, expected) in [
(denied.clone(), denied),
(
"destination denied by application network policy: sk-test-private-value".into(),
redacted.into(),
),
] {
let error = io::Error::other(CloudConfigBundleLoadError::new(
code, /*status_code*/ None, message,
));
assert_eq!(workspace_config_load_reason(&error), expected);
}
}
#[test_case(None; "signed_out")]
#[test_case(Some("dummy"); "api_key")]
#[tokio::test]
async fn background_routing_skips_config_until_chatgpt_sign_in(
api_key: Option<&str>,
) -> anyhow::Result<()> {
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::types::AuthCredentialsStoreMode;
use codex_exec_server::EnvironmentManager;
use codex_login::AuthKeyringBackendKind;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
let home = tempfile::tempdir()?;
let backend = wiremock::MockServer::start().await;
app_test_support::mount_workspace_routing(&backend).await;
let loads = Arc::new(AtomicUsize::new(/*v*/ 0));
let calls = Arc::clone(&loads);
let loader = CloudConfigBundleLoader::from_getter(move || {
calls.fetch_add(/*val*/ 1, Ordering::SeqCst);
async { Ok(None) }
});
let manager = ConfigManager::new_for_tests(
home.path().to_path_buf(),
vec![(
"chatgpt_base_url".into(),
format!("{}/backend-api", backend.uri()).into(),
)],
LoaderOverrides::without_managed_config_for_tests(),
loader,
);
let config = Arc::new(
manager
.load_latest_config(Some(home.path().to_path_buf()))
.await?,
);
if let Some(api_key) = api_key {
codex_login::login_with_api_key(
home.path(),
api_key,
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
}
let auth_manager = Arc::new(
AuthManager::new(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
Some(config.chatgpt_base_url.clone()),
AuthKeyringBackendKind::default(),
config.auth_config().auth_route_config,
)
.await,
);
let threads = Arc::new(
codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::from_api_key("dummy"),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::new(EnvironmentManager::default_for_tests()),
),
);
let (sender, _receiver) = tokio::sync::mpsc::channel(16);
let outgoing = Arc::new(OutgoingMessageSender::new(
sender,
codex_analytics::AnalyticsEventsClient::disabled(),
));
let model_catalog = Arc::new(crate::model_catalog::ModelCatalog::new(
manager.clone(),
Some(config.cwd.to_path_buf()),
Arc::clone(&config),
Arc::clone(&threads),
));
let processor = AccountRequestProcessor::new(
Arc::clone(&auth_manager),
threads,
outgoing,
config,
manager,
model_catalog,
);
let initial_loads = loads.load(Ordering::SeqCst);
for _ in 0..3 {
assert!(
processor
.read_account_for_background_workspace_routing()
.await?
.is_none()
);
}
assert_eq!(loads.load(Ordering::SeqCst), initial_loads);
processor.read_account(/*request*/ None).await?;
assert!(loads.load(Ordering::SeqCst) > initial_loads);
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("access-chatgpt").account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
assert!(auth_manager.reload().await);
let initial_loads = loads.load(Ordering::SeqCst);
let read = processor
.read_account_for_background_workspace_routing()
.await?
.unwrap();
assert_eq!(
read.workspace_routing,
Some(WorkspaceRouting {
chatgpt_account_id: "account-123".into(),
backend_origin: "https://chatgpt.com".into(),
account_routing_override: "NO_CONSTRAINT".into(),
})
);
assert!(loads.load(Ordering::SeqCst) > initial_loads);
let config_path = home.path().join("config.toml");
std::fs::write(&config_path, "invalid = [ 'sk-test-private-value',")?;
let Err(error) = processor
.read_account_for_background_workspace_routing()
.await
else {
panic!("invalid config must prevent workspace routing");
};
let message = error.to_string();
assert!(
message.starts_with(&format!(
"failed to load workspace requirements: invalid configuration at {}:1:",
config_path.display(),
)),
"{message}"
);
assert!(!message.contains("sk-test-private-value"), "{message}");
Ok(())
}
#[test_case(Some("https://gov.chatgpt.com/backend-api/"), "NO_CONSTRAINT", "https://gov.chatgpt.com"; "configured_only")]
#[test_case(None, "https://gov.chatgpt.com", "https://gov.chatgpt.com"; "discovered_only")]
#[test_case(Some("https://GOV.chatgpt.com:443/backend-api/"), "https://gov.chatgpt.com", "https://gov.chatgpt.com"; "matching_effective_port")]
#[test_case(Some("https://example.com:8443/backend-api/"), "https://example.com:8443", "https://example.com:8443"; "custom_port")]
#[test_case(None, "NO_CONSTRAINT", "https://chatgpt.com"; "existing_default")]
fn resolves_origins(required: Option<&str>, discovered: &str, expected: &str) {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": discovered,
"account_routing_override": "NO_CONSTRAINT",
}))
.unwrap();
assert_eq!(
resolve_routing(entry, required, "https://chatgpt.com/backend-api/").unwrap(),
WorkspaceRouting {
chatgpt_account_id: "workspace".into(),
backend_origin: expected.into(),
account_routing_override: "NO_CONSTRAINT".into(),
}
);
}
#[test_case("https://other.example/backend-api/", "https://gov.chatgpt.com"; "host_conflict")]
#[test_case("http://gov.chatgpt.com/backend-api/", "https://gov.chatgpt.com"; "scheme_conflict")]
#[test_case("https://gov.chatgpt.com:444/backend-api/", "https://gov.chatgpt.com"; "port_conflict")]
fn rejects_conflicting_origins(required: &str, discovered: &str) {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": discovered,
"account_routing_override": "us_cr",
}))
.unwrap();
assert!(resolve_routing(entry, Some(required), "https://chatgpt.com").is_err());
}
#[test_case(serde_json::json!(null), serde_json::json!("us_cr"), WorkspaceRoutingError::MissingBackendOrigin; "null_origin")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(null), WorkspaceRoutingError::InvalidRoutingOverride; "null_routing")]
#[test_case(serde_json::json!(""), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendUrl; "empty_origin")]
#[test_case(serde_json::json!("https://example.com/backend-api/"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_path")]
#[test_case(serde_json::json!("https://example.com?query"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_query")]
#[test_case(serde_json::json!("https://example.com#fragment"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_fragment")]
#[test_case(serde_json::json!("https://user:pass@example.com"), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendOrigin; "credentials")]
#[test_case(serde_json::json!("http://example.com"), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendOrigin; "insecure_origin")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!("unknown"), WorkspaceRoutingError::InvalidRoutingOverride; "unknown_routing")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(""), WorkspaceRoutingError::InvalidRoutingOverride; "empty_routing")]
fn rejects_invalid_discovery(backend: Value, routing: Value, expected: WorkspaceRoutingError) {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": backend, "account_routing_override": routing,
}))
.unwrap();
assert_eq!(
resolve_routing(
entry,
/*required_chatgpt_base_url*/ None,
"https://chatgpt.com"
),
Err(AccountReadError::Routing(expected))
);
}
#[test]
fn unrestricted_discovery_uses_effective_custom_backend() {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": "NO_CONSTRAINT", "account_routing_override": "us",
})).unwrap();
assert_eq!(
resolve_routing(
entry,
/*required_chatgpt_base_url*/ None,
"https://custom.example:8443/backend-api/"
)
.unwrap(),
WorkspaceRouting {
chatgpt_account_id: "workspace".into(),
backend_origin: "https://custom.example:8443".into(),
account_routing_override: "us".into(),
}
);
}

View File

@@ -0,0 +1,255 @@
//! Lists the active managed login and switches its workspace through the account-session API.
use super::*;
use codex_app_server_protocol::AccountSession;
use codex_app_server_protocol::AccountSessionWorkspace;
use codex_app_server_protocol::AccountSessionWorkspaceKind;
use codex_app_server_protocol::AccountSessionsListParams;
use codex_app_server_protocol::AccountSessionsResponse;
use codex_app_server_protocol::AccountSessionsSwitchParams;
use codex_app_server_protocol::AccountSessionsSwitchResponse;
impl AccountRequestProcessor {
pub(crate) async fn list_account_sessions(
&self,
params: AccountSessionsListParams,
) -> Result<AccountSessionsResponse, JSONRPCErrorError> {
let auth = if params.refresh_workspace_metadata {
self.auth_manager.auth().await
} else {
self.auth_manager.auth_cached()
}
.filter(|_| !self.auth_manager.has_external_auth());
let session_id = auth
.as_ref()
.and_then(CodexAuth::managed_account_session_id);
let (Some(auth), Some(session_id)) = (auth, session_id) else {
return Ok(AccountSessionsResponse {
active_session_id: None,
sessions: vec![],
});
};
let account_id = auth.get_account_id();
let mut workspaces = account_id
.iter()
.map(|id| AccountSessionWorkspace {
account_id: id.clone(),
name: None,
image_url: None,
kind: None,
})
.collect();
if params.refresh_workspace_metadata {
let accounts = self.workspace_memberships(&auth).await?;
workspaces = accounts
.accounts
.into_iter()
.map(|account| AccountSessionWorkspace {
account_id: account.id,
name: account.name,
image_url: account.profile_picture_url,
kind: match account.structure.as_str() {
"personal" => Some(AccountSessionWorkspaceKind::Personal),
"workspace" => Some(AccountSessionWorkspaceKind::Workspace),
_ => None,
},
})
.collect::<Vec<_>>();
workspaces.sort_by_key(|workspace| {
accounts
.account_ordering
.iter()
.position(|id| id == &workspace.account_id)
.unwrap_or(usize::MAX)
});
let current = self.auth_manager.auth_cached();
if self.auth_manager.has_external_auth()
|| current
.as_ref()
.and_then(CodexAuth::managed_account_session_id)
.as_deref()
!= Some(&session_id)
|| current.and_then(|auth| auth.get_account_id()) != account_id
{
return Err(invalid_request(
"Authentication changed while listing account sessions",
));
}
}
Ok(AccountSessionsResponse {
active_session_id: Some(session_id.clone()),
sessions: vec![AccountSession {
session_id,
email: auth.get_account_email(),
user_id: auth.get_chatgpt_user_id(),
display_name: None,
image_url: None,
last_used_at: chrono::Utc::now().timestamp(),
is_active: true,
selected_workspace_account_id: account_id,
workspaces,
}],
})
}
async fn workspace_memberships(
&self,
auth: &CodexAuth,
) -> Result<codex_backend_client::AccountsCheckResponse, JSONRPCErrorError> {
let client = BackendClient::from_auth(
self.config.chatgpt_base_url.clone(),
auth,
self.config.http_client_factory(),
);
tokio::time::timeout(
Duration::from_secs(/*secs*/ 30),
client.get_accounts_check(),
)
.await
.map_err(|_| internal_error("Workspace metadata request timed out"))?
.map_err(|_| internal_error("Failed to fetch workspace metadata"))
}
pub(crate) async fn switch_account_session(
&self,
params: AccountSessionsSwitchParams,
threads: &crate::request_processors::ThreadRequestProcessor,
admission: &crate::turn_admission::TurnAdmission,
) -> Result<AccountSessionsSwitchResponse, JSONRPCErrorError> {
if self.active_login.lock().await.is_some() {
return Err(invalid_request(
"Finish or cancel the current login before switching workspaces",
));
}
self.auth_manager
.validate_workspace_switch(&params.session_id, &params.account_id)
.map_err(|error| invalid_request(error.to_string()))?;
if self
.auth_manager
.auth_cached()
.and_then(|auth| auth.get_account_id())
.as_deref()
== Some(&params.account_id)
{
return self.account_session_switch_response(&params).await;
}
let auth = self
.auth_manager
.auth_cached()
.ok_or_else(|| invalid_request("Authentication is unavailable"))?;
let memberships = self.workspace_memberships(&auth).await?;
let mut matches = memberships
.accounts
.iter()
.filter(|account| account.id == params.account_id);
let Some(target) = matches.next() else {
return Err(invalid_request("The selected workspace is unavailable"));
};
if matches.next().is_some() || target.is_deactivated {
return Err(invalid_request("The selected workspace is unavailable"));
}
// The exchange strips the FedRAMP hint from the server session's token templates.
if auth.is_fedramp_account()
|| target.is_fedramp_compliant_workspace
|| target.workspace_backend_origin.as_deref() == Some("https://gov.chatgpt.com")
{
return Err(invalid_request("Sign in to switch government workspaces"));
}
self.auth_manager
.validate_workspace_switch(&params.session_id, &params.account_id)
.map_err(|error| invalid_request(error.to_string()))?;
if target.can_access_with_session == Some(false) {
if !params.allow_browser_login {
return Err(invalid_request(
"The selected workspace requires a new sign-in",
));
}
let mut opts = self
.login_chatgpt_common(
/*codex_streamlined_login*/ true,
LoginSuccessPage::default(),
)
.await?;
opts.workspace_login = Some(
auth.workspace_login(
&params.session_id,
params.account_id.clone(),
target.sso_connection_name.clone(),
)
.map_err(|error| invalid_request(error.to_string()))?,
);
opts.forced_chatgpt_workspace_id = Some(vec![params.account_id]);
let pause = admission.pause().await?;
threads.unload_for_workspace_switch().await?;
let (login_id, auth_url) = self.start_browser_login(opts, Some(pause)).await?;
return Ok(AccountSessionsSwitchResponse::BrowserLogin { login_id, auth_url });
}
let _pause = admission.pause().await?;
threads.unload_for_workspace_switch().await?;
let switched = self
.auth_manager
.switch_workspace(&params.session_id, &params.account_id)
.await
.map_err(|error| invalid_request(error.to_string()))?;
let auth_changes = self.auth_manager.auth_change_state_receiver();
let owner_generation = auth_changes.borrow().owner_generation;
self.reload_workspace_config().await;
// Routing includes fatal authorization and policy checks. Restore the
// previous login on any failure, unless another auth operation replaced it.
if let Err(error) = self.read_account(/*request*/ None).await {
let rollback = self.auth_manager.rollback_workspace_switch(switched).await;
self.reload_workspace_config().await;
rollback.map_err(|rollback| internal_error(format!("Workspace validation failed: {error}; could not restore the previous workspace: {rollback}")))?;
return Err(internal_error(format!(
"Workspace validation failed: {error}"
)));
}
self.thread_manager.invalidate_mcp_runtimes().await;
self.model_catalog.invalidate().await;
Self::maybe_refresh_plugin_caches_for_current_config(
&self.config_manager,
&self.thread_manager,
self.auth_manager.auth_cached(),
)
.await;
self.outgoing
.send_account_notification(
/*connection_id*/ None,
&auth_changes,
owner_generation,
AccountNotification::Updated(self.current_account_updated_notification()),
)
.await;
self.account_session_switch_response(&params).await
}
async fn reload_workspace_config(&self) {
self.config_manager
.update_managed_config_loader(self.auth_manager.clone(), &self.config);
self.config_manager
.sync_default_client_residency_requirement()
.await;
}
async fn account_session_switch_response(
&self,
params: &AccountSessionsSwitchParams,
) -> Result<AccountSessionsSwitchResponse, JSONRPCErrorError> {
let response = self
.list_account_sessions(AccountSessionsListParams {
refresh_workspace_metadata: false,
})
.await?;
if response.active_session_id.as_deref() != Some(&params.session_id)
|| !response.sessions.iter().any(|session| {
session.session_id == params.session_id
&& session.selected_workspace_account_id.as_deref() == Some(&params.account_id)
})
{
return Err(invalid_request(
"Authentication changed during workspace switching",
));
}
Ok(AccountSessionsSwitchResponse::Switched { sessions: response })
}
}

View File

@@ -0,0 +1,497 @@
use super::*;
use crate::app_info::app_info_to_api;
use codex_connectors::AppToolPolicyEvaluator;
mod installed;
mod read;
pub(super) use read::APP_READ_MAX_IDS;
pub(crate) struct AppsRequestProcessor {
thread_manager: Arc<ThreadManager>,
outgoing: Arc<OutgoingMessageSender>,
config_manager: ConfigManager,
shutdown_token: CancellationToken,
_shutdown_drop_guard: DropGuard,
}
impl AppsRequestProcessor {
pub(crate) fn new(
thread_manager: Arc<ThreadManager>,
outgoing: Arc<OutgoingMessageSender>,
config_manager: ConfigManager,
shutdown_token: CancellationToken,
) -> Self {
let shutdown_drop_guard = shutdown_token.clone().drop_guard();
Self {
thread_manager,
outgoing,
config_manager,
shutdown_token,
_shutdown_drop_guard: shutdown_drop_guard,
}
}
pub(crate) async fn apps_list(
&self,
request_id: &ConnectionRequestId,
params: AppsListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.apps_list_inner(request_id, params)
.await
.map(|response| response.map(Into::into))
}
async fn apps_list_inner(
&self,
request_id: &ConnectionRequestId,
params: AppsListParams,
) -> Result<Option<AppsListResponse>, JSONRPCErrorError> {
let installed_start = Instant::now();
let reload = params.force_refetch;
let thread = if let Some(thread_id) = params.thread_id.as_deref() {
let (_, loaded_thread) = self.load_thread(thread_id).await?;
Some(loaded_thread)
} else {
None
};
let fallback_cwd = match thread.as_ref() {
Some(thread) => Some(thread.config_snapshot().await.cwd().to_path_buf()),
None => None,
};
let mut config = self.load_latest_config(fallback_cwd).await?;
if let Some(thread) = thread.as_ref() {
let _ = config
.features
.set_enabled(Feature::Apps, thread.enabled(Feature::Apps));
}
let mcp_manager = thread
.as_ref()
.map(|thread| thread.mcp_manager())
.unwrap_or_else(|| self.thread_manager.mcp_manager());
self.thread_manager
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
.map_err(|error| internal_error(error.to_string()))?;
let auth_manager = mcp_manager.auth_manager();
if params.force_refetch && !auth_manager.has_external_auth() {
auth_manager
.reload_with_cached_auth()
.await
.map_err(|error| internal_error(error.to_string()))?;
}
let auth = auth_manager.auth().await;
if !config
.features
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend))
{
let response = AppsListResponse {
data: Vec::new(),
next_cursor: None,
};
record_legacy_apps_installed_duration(installed_start, reload);
return Ok(Some(response));
}
let request = request_id.clone();
let outgoing = Arc::clone(&self.outgoing);
let environment_manager = self.thread_manager.environment_manager();
let plugins_manager = mcp_manager.plugins_manager();
let shutdown_token = self.shutdown_token.child_token();
tokio::spawn(async move {
tokio::select! {
_ = shutdown_token.cancelled() => {}
_ = Self::apps_list_task(
outgoing,
request,
params,
config,
environment_manager,
mcp_manager,
plugins_manager,
installed_start,
) => {}
}
});
Ok(None)
}
pub(crate) fn shutdown(&self) {
self.shutdown_token.cancel();
}
#[allow(clippy::too_many_arguments)]
async fn apps_list_task(
outgoing: Arc<OutgoingMessageSender>,
request_id: ConnectionRequestId,
params: AppsListParams,
config: Config,
environment_manager: Arc<EnvironmentManager>,
mcp_manager: Arc<McpManager>,
plugins_manager: Arc<PluginsManager>,
installed_start: Instant,
) {
let reload = params.force_refetch;
let retry_params = params.clone();
let retry_config = config.clone();
let retry_environment_manager = Arc::clone(&environment_manager);
let retry_mcp_manager = Arc::clone(&mcp_manager);
let retry_plugins_manager = Arc::clone(&plugins_manager);
let result = Self::apps_list_response(
&outgoing,
params,
config,
environment_manager,
mcp_manager,
plugins_manager,
)
.await;
if result.is_ok() {
record_legacy_apps_installed_duration(installed_start, reload);
}
let should_retry = result
.as_ref()
.is_ok_and(|(_, codex_apps_ready)| !codex_apps_ready);
outgoing
.send_result(request_id, result.map(|(response, _)| response))
.await;
if should_retry && !retry_params.force_refetch {
let mut retry_params = retry_params;
retry_params.force_refetch = true;
if let Err(err) = Self::apps_list_response(
&outgoing,
retry_params,
retry_config,
retry_environment_manager,
retry_mcp_manager,
retry_plugins_manager,
)
.await
{
warn!("failed to refresh app list after codex-apps readiness retry: {err:?}");
}
}
}
async fn apps_list_response(
outgoing: &Arc<OutgoingMessageSender>,
params: AppsListParams,
config: Config,
environment_manager: Arc<EnvironmentManager>,
mcp_manager: Arc<McpManager>,
plugins_manager: Arc<PluginsManager>,
) -> Result<(AppsListResponse, bool), JSONRPCErrorError> {
let AppsListParams {
cursor,
limit,
thread_id: _,
force_refetch,
} = params;
let start = match cursor {
Some(cursor) => match cursor.parse::<usize>() {
Ok(idx) => idx,
Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))),
},
None => 0,
};
let loaded_plugins = plugins_manager
.plugins_for_config(&config.plugins_config_input())
.await;
let connector_snapshot =
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(
loaded_plugins.capability_summaries(),
);
let plugin_apps = connector_snapshot.connector_ids().to_vec();
let mut config = config;
let auth = match mcp_manager
.auth_manager()
.auth_with_http_client_factory()
.await
{
Some((auth, factory)) => {
config.application_network_policy = factory.network_policy().clone();
Some(auth)
}
None => None,
};
let runtime = mcp_manager
.runtime_auth_for_config(&config)
.map(|(slot, mode)| {
slot.get()
.cloned()
.map(|runtime| (runtime, mode))
.ok_or_else(|| {
internal_error("runtime authentication is not initialized".to_string())
})
})
.transpose()?;
let mut accessible_connectors =
connectors::list_cached_accessible_connectors_from_mcp_tools(&config, auth.as_ref());
let mut all_connectors =
connectors::list_cached_all_connectors(&config, auth.as_ref(), &plugin_apps);
let cached_all_connectors = all_connectors.clone();
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let accessible_config = config.clone();
let accessible_tx = tx.clone();
tokio::spawn(async move {
let result = connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager(
&accessible_config,
force_refetch,
Arc::clone(&environment_manager),
mcp_manager,
)
.await
.map_err(|err| format!("failed to load accessible apps: {err}"));
let _ = accessible_tx.send(AppListLoadResult::Accessible(result));
});
let all_config = config.clone();
let all_plugin_apps = plugin_apps.clone();
tokio::spawn(async move {
let result = connectors::list_all_connectors_with_options(
&all_config,
auth.as_ref(),
runtime.as_ref(),
force_refetch,
&all_plugin_apps,
)
.await
.map_err(|err| format!("failed to list apps: {err}"));
let _ = tx.send(AppListLoadResult::Directory(result));
});
let app_list_deadline = tokio::time::Instant::now() + APP_LIST_LOAD_TIMEOUT;
let mut accessible_loaded = false;
let mut all_loaded = false;
let mut codex_apps_ready = true;
let mut last_notified_apps = None;
let mut sent_app_list_update = false;
let app_policy = AppToolPolicyEvaluator::new(&config.config_layer_stack);
if accessible_connectors.is_some() || all_connectors.is_some() {
let merged = app_policy.apply_app_enabled_state(merge_loaded_apps(
all_connectors.as_deref(),
accessible_connectors.as_deref(),
));
if !force_refetch {
last_notified_apps = Some(merged);
} else if should_send_app_list_updated_notification(
merged.as_slice(),
accessible_loaded,
all_loaded,
) {
send_app_list_updated_notification(outgoing, merged.clone()).await;
last_notified_apps = Some(merged);
sent_app_list_update = true;
}
}
loop {
let result = match tokio::time::timeout_at(app_list_deadline, rx.recv()).await {
Ok(Some(result)) => result,
Ok(None) => {
return Err(internal_error("failed to load app lists"));
}
Err(_) => {
let timeout_seconds = APP_LIST_LOAD_TIMEOUT.as_secs();
return Err(internal_error(format!(
"timed out waiting for app lists after {timeout_seconds} seconds"
)));
}
};
match result {
AppListLoadResult::Accessible(Ok(status)) => {
accessible_connectors = Some(status.connectors);
accessible_loaded = true;
codex_apps_ready = status.codex_apps_ready;
}
AppListLoadResult::Accessible(Err(err)) => {
return Err(internal_error(err));
}
AppListLoadResult::Directory(Ok(connectors)) => {
all_connectors = Some(connectors);
all_loaded = true;
}
AppListLoadResult::Directory(Err(err)) => {
return Err(internal_error(err));
}
}
let showing_interim_force_refetch = force_refetch && !(accessible_loaded && all_loaded);
let all_connectors_for_update =
if showing_interim_force_refetch && cached_all_connectors.is_some() {
cached_all_connectors.as_deref()
} else {
all_connectors.as_deref()
};
let accessible_connectors_for_update =
if showing_interim_force_refetch && !accessible_loaded {
None
} else {
accessible_connectors.as_deref()
};
let merged = app_policy.apply_app_enabled_state(merge_loaded_apps(
all_connectors_for_update,
accessible_connectors_for_update,
));
if should_send_app_list_updated_notification(
merged.as_slice(),
accessible_loaded,
all_loaded,
) && (last_notified_apps.as_ref() != Some(&merged)
|| (!force_refetch
&& start == 0
&& accessible_loaded
&& all_loaded
&& !sent_app_list_update))
{
send_app_list_updated_notification(outgoing, merged.clone()).await;
last_notified_apps = Some(merged.clone());
sent_app_list_update = true;
}
if accessible_loaded && all_loaded {
let response = paginate_apps(merged.as_slice(), start, limit)?;
return Ok((response, codex_apps_ready));
}
}
}
async fn load_thread(
&self,
thread_id: &str,
) -> Result<(ThreadId, Arc<CodexThread>), JSONRPCErrorError> {
let thread_id = ThreadId::from_string(thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
let thread = self
.thread_manager
.get_thread(thread_id)
.await
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
Ok((thread_id, thread))
}
async fn load_latest_config(
&self,
fallback_cwd: Option<PathBuf>,
) -> Result<Config, JSONRPCErrorError> {
self.config_manager
.load_latest_config(fallback_cwd)
.await
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
}
async fn load_apps_config(
&self,
thread_id: Option<&str>,
) -> Result<(Config, Arc<McpManager>), JSONRPCErrorError> {
let Some(thread_id) = thread_id else {
let config = self.load_latest_config(/*fallback_cwd*/ None).await?;
self.thread_manager
.runtime_auth_for_config(&config)
.map_err(|error| internal_error(error.to_string()))?;
return Ok((config, self.thread_manager.mcp_manager()));
};
let (_, thread) = self.load_thread(thread_id).await?;
let thread_config = thread.config().await;
let config = self
.config_manager
.load_latest_config_with_session_layers(
&thread_config.config_layer_stack,
&thread_config.cwd,
)
.await
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?;
let mcp_manager = thread.mcp_manager();
self.thread_manager
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
.map_err(|error| internal_error(error.to_string()))?;
Ok((config, mcp_manager))
}
}
const APP_LIST_LOAD_TIMEOUT: Duration = Duration::from_secs(90);
// `app/list` is the legacy request-path baseline for the `app/installed` endpoint;
// `path=legacy` keeps it separate from the new snapshot-backed implementation in dashboards.
const APPS_INSTALLED_DURATION_METRIC: &str = "codex.apps.installed.duration_ms";
fn record_legacy_apps_installed_duration(started_at: Instant, reload: bool) {
let reload = if reload { "true" } else { "false" };
if let Some(metrics) = codex_otel::global() {
let _ = metrics.record_duration(
APPS_INSTALLED_DURATION_METRIC,
started_at.elapsed(),
&[("path", "legacy"), ("reload", reload)],
);
}
}
enum AppListLoadResult {
Accessible(Result<AccessibleConnectorsStatus, String>),
Directory(Result<Vec<AppInfo>, String>),
}
fn merge_loaded_apps(
all_connectors: Option<&[AppInfo]>,
accessible_connectors: Option<&[AppInfo]>,
) -> Vec<AppInfo> {
let all_connectors_loaded = all_connectors.is_some();
let all = all_connectors.map_or_else(Vec::new, <[AppInfo]>::to_vec);
let accessible = accessible_connectors.map_or_else(Vec::new, <[AppInfo]>::to_vec);
connectors::merge_connectors_with_accessible(all, accessible, all_connectors_loaded)
}
fn should_send_app_list_updated_notification(
connectors: &[AppInfo],
accessible_loaded: bool,
all_loaded: bool,
) -> bool {
connectors.iter().any(|connector| connector.is_accessible) || (accessible_loaded && all_loaded)
}
fn paginate_apps(
connectors: &[AppInfo],
start: usize,
limit: Option<u32>,
) -> Result<AppsListResponse, JSONRPCErrorError> {
let total = connectors.len();
if start > total {
return Err(invalid_request(format!(
"cursor {start} exceeds total apps {total}"
)));
}
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
let end = start.saturating_add(effective_limit).min(total);
let data = connectors[start..end]
.iter()
.cloned()
.map(app_info_to_api)
.collect();
let next_cursor = if end < total {
Some(end.to_string())
} else {
None
};
Ok(AppsListResponse { data, next_cursor })
}
async fn send_app_list_updated_notification(
outgoing: &Arc<OutgoingMessageSender>,
data: Vec<AppInfo>,
) {
let data = data.into_iter().map(app_info_to_api).collect();
outgoing
.send_server_notification(ServerNotification::AppListUpdated(
AppListUpdatedNotification { data },
))
.await;
}

View File

@@ -0,0 +1,293 @@
use super::*;
use codex_connectors::ConnectorRuntimeTool;
use codex_connectors::connector_runtime_context_key;
use codex_connectors::connector_tool_is_synthetic;
use codex_connectors::installed_connector_runtime;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_mcp::MCP_TOOL_CODEX_APPS_META_KEY;
use codex_mcp::McpRuntime;
use codex_mcp::McpRuntimeInput;
use codex_mcp::McpStartupPolicy;
use codex_mcp::ToolInfo;
use codex_mcp::effective_mcp_servers;
use codex_mcp::host_owned_codex_apps_enabled;
use codex_mcp::tool_is_model_visible;
use codex_protocol::mcp::ClientMcpExtensions;
#[cfg(test)]
#[path = "installed_tests.rs"]
mod tests;
const CONNECTOR_RUNTIME_REFRESH_TIMEOUT: Duration = Duration::from_secs(30);
const APPS_INSTALLED_SUBMIT_ID: &str = "app-installed";
const APPS_INSTALLED_RESPONSE_BYTES_METRIC: &str = "codex.apps.installed.response_bytes";
const APPS_INSTALLED_CONNECTOR_COUNT_METRIC: &str = "codex.apps.installed.connector_count";
const APPS_INSTALLED_TOOL_COUNT_METRIC: &str = "codex.apps.installed.tool_count";
const APPS_SNAPSHOT_AGE_METRIC: &str = "codex.apps.snapshot.age_ms";
struct AppsInstalledSnapshotMetrics {
age: Option<Duration>,
tool_count: usize,
}
impl AppsRequestProcessor {
pub(crate) async fn apps_installed(
&self,
params: AppsInstalledParams,
) -> Result<AppsInstalledResponse, JSONRPCErrorError> {
let started_at = Instant::now();
let force_refresh = params.force_refresh;
let mut retained_previous_snapshot = false;
let mut refresh_disposition = if force_refresh {
"not_started"
} else {
"not_requested"
};
let mut snapshot_age = None;
let mut snapshot_tool_count = 0;
let result = async {
let (config, thread) = match params.thread_id.as_deref() {
Some(thread_id) => {
let (_, thread) = self.load_thread(thread_id).await?;
let config = thread.config().await;
(config.as_ref().clone(), Some(thread))
}
None => (
self.load_latest_config(/*fallback_cwd*/ None).await?,
None,
),
};
let mcp_manager = thread.as_ref().map(|thread| thread.mcp_manager())
.unwrap_or_else(|| self.thread_manager.mcp_manager());
let auth_manager = mcp_manager.auth_manager();
let auth = auth_manager.auth().await;
let runtime_enabled = config
.features
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend));
let cache_key = connector_runtime_context_key(auth.as_ref());
let previous_snapshot = mcp_manager
.codex_apps_tools_cache()
.current_snapshot(config.codex_home.to_path_buf(), cache_key.clone());
let mut model_visible_tool_names = None;
let tools = if force_refresh && runtime_enabled {
let refresh_result = async {
if let Some(thread) = thread {
let snapshot = thread.refresh_codex_apps_tools().await?;
model_visible_tool_names = Some(snapshot.model_visible_tool_names);
snapshot_age = Some(Duration::ZERO);
return Ok(snapshot.tools);
}
let mcp_config = mcp_manager.runtime_config(&config).await;
let mut mcp_servers = effective_mcp_servers(&mcp_config, auth.as_ref());
mcp_servers.retain(|name, _| name == CODEX_APPS_MCP_SERVER_NAME);
let mcp_config = Arc::new(mcp_config.for_threadless_operations(&mcp_servers));
anyhow::ensure!(
!mcp_servers.is_empty(),
"host-owned MCP server '{CODEX_APPS_MCP_SERVER_NAME}' is not enabled"
);
let startup_timeout = mcp_servers
.get(CODEX_APPS_MCP_SERVER_NAME)
.and_then(|server| server.config().startup_timeout_sec)
.unwrap_or(CONNECTOR_RUNTIME_REFRESH_TIMEOUT);
let runtime_context = McpRuntimeContext::new(
self.thread_manager.environment_manager(),
config.cwd.to_path_buf(),
);
let cancellation_token = CancellationToken::new();
let codex_apps_auth_manager =
host_owned_codex_apps_enabled(&mcp_config, auth.as_ref())
.then(|| Arc::clone(&auth_manager));
self.thread_manager.runtime_auth_for_mcp_manager(&config, &mcp_manager)?;
let runtime = McpRuntime::new(McpRuntimeInput {
network_policy_metadata: None,
runtime_auth: mcp_manager.runtime_auth_for_config(&config),
startup_policy: McpStartupPolicy::Eager,
config: Arc::clone(&mcp_config),
plugins_available: false,
ready_selected_capability_roots: Vec::new(),
mcp_servers,
submit_id: APPS_INSTALLED_SUBMIT_ID.to_string(),
tx_event: None,
startup_cancellation_token: cancellation_token.clone(),
runtime_context,
codex_apps_tools_cache: mcp_manager.codex_apps_tools_cache(),
tool_catalog_cache: mcp_manager.tool_catalog_cache(),
codex_apps_tools_cache_key: cache_key.clone(),
client_mcp_extensions: ClientMcpExtensions::default(),
auth: auth.clone(),
auth_manager: codex_apps_auth_manager,
elicitation_reviewer: None,
elicitation_lifecycle: None,
})
.await;
let result = if runtime
.latest_wait_for_server_ready(
CODEX_APPS_MCP_SERVER_NAME,
startup_timeout,
)
.await
{
mcp_manager
.codex_apps_tools_cache()
.current_snapshot(config.codex_home.to_path_buf(), cache_key.clone())
.ok_or_else(|| {
anyhow::anyhow!(
"hosted connector refresh completed without publishing a snapshot"
)
})
} else {
Err(anyhow::anyhow!(
"failed to refresh tools for MCP server '{CODEX_APPS_MCP_SERVER_NAME}'"
))
};
cancellation_token.cancel();
runtime.shutdown().await;
result.map(|snapshot| {
snapshot_age = Some(snapshot.age());
snapshot.tools().to_vec()
})
}
.await;
match refresh_result {
Ok(tools) => {
refresh_disposition = "success";
tools
}
Err(err) => {
refresh_disposition = "error";
retained_previous_snapshot = previous_snapshot.is_some();
return Err(internal_error(format!(
"failed to refresh installed connector runtime state: {err:#}"
)));
}
}
} else {
if force_refresh {
refresh_disposition = "skipped_apps_disabled";
retained_previous_snapshot = previous_snapshot.is_some();
}
previous_snapshot.map_or_else(Vec::new, |snapshot| {
snapshot_age = Some(snapshot.age());
snapshot.tools().to_vec()
})
};
snapshot_tool_count = tools.len();
let apps = installed_connector_runtime(
&config.config_layer_stack,
tools.iter().map(|tool| {
let mut runtime_tool = connector_runtime_tool(tool);
if let Some(names) = &model_visible_tool_names {
runtime_tool.model_visible &= names.contains(tool.tool.name.as_ref());
}
runtime_tool
}),
)
.into_iter()
.map(|app| InstalledApp {
id: app.id,
runtime_name: app.runtime_name,
enabled: runtime_enabled && app.enabled,
callable: runtime_enabled && app.callable,
})
.collect();
Ok(AppsInstalledResponse { apps })
}
.await;
if let Some(metrics) = codex_otel::global() {
record_apps_installed_metrics(
&metrics,
started_at,
force_refresh,
retained_previous_snapshot,
refresh_disposition,
AppsInstalledSnapshotMetrics {
age: snapshot_age,
tool_count: snapshot_tool_count,
},
result.as_ref().ok(),
);
}
result
}
}
fn connector_runtime_tool(tool: &ToolInfo) -> ConnectorRuntimeTool<'_> {
let annotations = tool.tool.annotations.as_ref();
ConnectorRuntimeTool {
connector_id: tool.connector_id.as_deref(),
connector_name: tool.connector_name.as_deref(),
tool_name: &tool.tool.name,
tool_title: tool.tool.title.as_deref(),
destructive_hint: annotations.and_then(|annotations| annotations.destructive_hint),
open_world_hint: annotations.and_then(|annotations| annotations.open_world_hint),
synthetic: connector_tool_is_synthetic(
tool.tool
.meta
.as_deref()
.and_then(|meta| meta.get(MCP_TOOL_CODEX_APPS_META_KEY)),
),
model_visible: tool_is_model_visible(tool),
}
}
fn record_apps_installed_metrics(
metrics: &codex_otel::MetricsClient,
started_at: Instant,
force_refresh: bool,
retained_previous_snapshot: bool,
refresh_disposition: &'static str,
snapshot_metrics: AppsInstalledSnapshotMetrics,
response: Option<&AppsInstalledResponse>,
) {
let Some(response) = response else {
return;
};
let force_refresh = if force_refresh { "true" } else { "false" };
let retained_previous_snapshot = if retained_previous_snapshot {
"true"
} else {
"false"
};
let _ = metrics.record_duration(
APPS_INSTALLED_DURATION_METRIC,
started_at.elapsed(),
&[
("path", "installed"),
("reload", force_refresh),
("force_refresh", force_refresh),
("refresh", refresh_disposition),
("outcome", "success"),
("retained_previous_snapshot", retained_previous_snapshot),
],
);
if let Ok(bytes) = serde_json::to_vec(response) {
let _ = metrics.histogram(
APPS_INSTALLED_RESPONSE_BYTES_METRIC,
i64::try_from(bytes.len()).unwrap_or(i64::MAX),
&[("path", "new")],
);
}
let _ = metrics.histogram(
APPS_INSTALLED_CONNECTOR_COUNT_METRIC,
i64::try_from(response.apps.len()).unwrap_or(i64::MAX),
&[("path", "new")],
);
let _ = metrics.histogram(
APPS_INSTALLED_TOOL_COUNT_METRIC,
i64::try_from(snapshot_metrics.tool_count).unwrap_or(i64::MAX),
&[("path", "new")],
);
if let Some(snapshot_age) = snapshot_metrics.age {
let _ = metrics.record_duration(
APPS_SNAPSHOT_AGE_METRIC,
snapshot_age,
&[("path", "new"), ("observation", "installed")],
);
}
}

View File

@@ -0,0 +1,149 @@
use super::APPS_INSTALLED_DURATION_METRIC;
use super::AppsInstalledSnapshotMetrics;
use super::record_apps_installed_metrics;
use anyhow::Result;
use codex_app_server_protocol::AppsInstalledResponse;
use codex_otel::MetricsClient;
use codex_otel::MetricsConfig;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use opentelemetry_sdk::metrics::data::ScopeMetrics;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::time::Instant;
fn test_metrics() -> Result<MetricsClient> {
Ok(MetricsClient::new(
MetricsConfig::in_memory(
"test",
"codex-app-server",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)?)
}
#[test]
fn installed_duration_records_one_sample_per_success_with_legacy_comparison_dimensions()
-> Result<()> {
let metrics = test_metrics()?;
let response = AppsInstalledResponse { apps: Vec::new() };
record_apps_installed_metrics(
&metrics,
Instant::now(),
/*force_refresh*/ false,
/*retained_previous_snapshot*/ false,
"not_requested",
AppsInstalledSnapshotMetrics {
age: None,
tool_count: 0,
},
Some(&response),
);
record_apps_installed_metrics(
&metrics,
Instant::now(),
/*force_refresh*/ true,
/*retained_previous_snapshot*/ false,
"success",
AppsInstalledSnapshotMetrics {
age: None,
tool_count: 0,
},
Some(&response),
);
let snapshot = metrics.snapshot()?;
let metric = snapshot
.scope_metrics()
.flat_map(ScopeMetrics::metrics)
.find(|metric| metric.name() == APPS_INSTALLED_DURATION_METRIC)
.expect("installed duration metric should be recorded");
let mut points = match metric.data() {
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => histogram
.data_points()
.map(|point| {
let attributes = point
.attributes()
.map(|attribute| {
(
attribute.key.as_str().to_string(),
attribute.value.as_str().to_string(),
)
})
.collect::<BTreeMap<_, _>>();
(attributes, point.count())
})
.collect::<Vec<_>>(),
_ => panic!("installed duration should be a floating-point histogram"),
};
points.sort_by(|(left, _), (right, _)| left.cmp(right));
assert_eq!(
points,
vec![
(
BTreeMap::from([
("force_refresh".to_string(), "false".to_string()),
("outcome".to_string(), "success".to_string()),
("path".to_string(), "installed".to_string()),
("refresh".to_string(), "not_requested".to_string()),
("reload".to_string(), "false".to_string()),
(
"retained_previous_snapshot".to_string(),
"false".to_string()
),
]),
1,
),
(
BTreeMap::from([
("force_refresh".to_string(), "true".to_string()),
("outcome".to_string(), "success".to_string()),
("path".to_string(), "installed".to_string()),
("refresh".to_string(), "success".to_string()),
("reload".to_string(), "true".to_string()),
(
"retained_previous_snapshot".to_string(),
"false".to_string()
),
]),
1,
),
]
);
Ok(())
}
#[test]
fn installed_duration_does_not_record_failed_requests() -> Result<()> {
let metrics = test_metrics()?;
record_apps_installed_metrics(
&metrics,
Instant::now(),
/*force_refresh*/ true,
/*retained_previous_snapshot*/ true,
"error",
AppsInstalledSnapshotMetrics {
age: None,
tool_count: 0,
},
/*response*/ None,
);
let snapshot = metrics.snapshot()?;
assert!(
snapshot
.scope_metrics()
.flat_map(ScopeMetrics::metrics)
.all(|metric| metric.name() != APPS_INSTALLED_DURATION_METRIC),
"failed installed requests must not record a successful duration sample",
);
Ok(())
}

View File

@@ -0,0 +1,108 @@
use super::*;
use crate::app_info::connector_metadata_to_api;
pub(in crate::request_processors) const APP_READ_MAX_IDS: usize = 100;
const APPS_READ_DURATION_METRIC: &str = "codex.apps.read.duration_ms";
impl AppsRequestProcessor {
pub(crate) async fn apps_read(
&self,
params: AppsReadParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let started_at = Instant::now();
let AppsReadParams {
app_ids,
thread_id,
include_tools,
} = params;
if app_ids.len() > APP_READ_MAX_IDS {
return Err(invalid_params(format!(
"app/read accepts at most {APP_READ_MAX_IDS} appIds"
)));
}
let mut seen_app_ids = HashSet::new();
let app_ids = app_ids
.into_iter()
.filter(|app_id| seen_app_ids.insert(app_id.clone()))
.collect::<Vec<_>>();
let (mut config, mcp_manager) = self.load_apps_config(thread_id.as_deref()).await?;
let auth = match mcp_manager
.auth_manager()
.auth_with_http_client_factory()
.await
{
Some((auth, factory)) => {
config.application_network_policy = factory.network_policy().clone();
Some(auth)
}
None => None,
};
let runtime = self
.thread_manager
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
.map_err(|error| internal_error(error.to_string()))?;
if !config
.features
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend))
{
let response = AppsReadResponse {
apps: Vec::new(),
missing_app_ids: app_ids,
};
record_apps_read_duration(started_at, include_tools);
return Ok(Some(response.into()));
}
let auth = auth
.as_ref()
.ok_or_else(|| internal_error("app/read requires ChatGPT auth".to_string()))?;
let connectors::ConnectorMetadataReadResult {
apps,
missing_app_ids,
} = connectors::read_connector_metadata(
&config,
auth,
runtime.as_ref(),
&app_ids,
include_tools,
)
.await
.map_err(|err| internal_error(format!("failed to read app metadata: {err}")))?;
let loaded_plugins = mcp_manager
.plugins_manager()
.plugins_for_config(&config.plugins_config_input())
.await;
let connector_snapshot =
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(
loaded_plugins.capability_summaries(),
);
let apps = apps
.into_iter()
.map(|metadata| {
let mut app = connector_metadata_to_api(metadata);
app.plugin_display_names = connector_snapshot
.plugin_display_names_for_connector_id(app.id.as_str())
.to_vec();
app
})
.collect();
let response = AppsReadResponse {
apps,
missing_app_ids,
};
record_apps_read_duration(started_at, include_tools);
Ok(Some(response.into()))
}
}
fn record_apps_read_duration(started_at: Instant, include_tools: bool) {
let include_tools = if include_tools { "true" } else { "false" };
if let Some(metrics) = codex_otel::global() {
let _ = metrics.record_duration(
APPS_READ_DURATION_METRIC,
started_at.elapsed(),
&[("include_tools", include_tools)],
);
}
}

View File

@@ -0,0 +1,98 @@
use super::config_processor::map_error as map_config_error;
use crate::config_manager::ConfigManager;
use crate::config_manager_service::PreparedProviderWrite;
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use codex_app_server_protocol::ConfigBatchWriteParams;
use codex_app_server_protocol::ConfigEdit;
use codex_app_server_protocol::ConfigWriteErrorCode;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::MergeStrategy;
use codex_core::config::Config;
use codex_core::config::edit::ConfigEditsBuilder;
use codex_model_provider::AMAZON_BEDROCK_PROVIDER_ID;
pub(super) struct BedrockProviderConfig<'a> {
pub(super) region: Option<&'a str>,
pub(super) profile: Option<&'a str>,
}
pub(super) async fn prepare_bedrock_provider(
config_manager: &ConfigManager,
config: BedrockProviderConfig<'_>,
) -> Result<PreparedProviderWrite, JSONRPCErrorError> {
let layers = config_manager
.load_config_layers(/*cwd*/ None)
.await
.map_err(|err| internal_error(format!("failed to load configuration layers: {err}")))?;
let mut settings = vec![("aws.profile", config.profile)];
if let Some(region) = config.region {
settings.push(("aws.region", Some(region)));
}
let (write, provider) = config_manager
.prepare_provider_config(&layers, AMAZON_BEDROCK_PROVIDER_ID, settings)
.map_err(map_config_error)?;
if provider
.aws
.is_some_and(|aws| aws.credential_export.is_some())
{
return Err(invalid_request(
"Amazon Bedrock is configured to use `aws.credential_export`. Please clear this setting to use another sign-in method.",
));
}
Ok(write)
}
pub(super) async fn clear_user_model_provider_if_bedrock(
config_manager: &ConfigManager,
config: &Config,
) -> Result<(), JSONRPCErrorError> {
let mut latest_config = None;
loop {
let config = latest_config.as_ref().unwrap_or(config);
let Some(key_paths) = ConfigEditsBuilder::bedrock_provider_config_paths_to_clear(config)
else {
return Ok(());
};
let expected_version = config
.config_layer_stack
.get_active_user_layer()
.map(|layer| layer.version.clone());
let result = config_manager
.batch_write(ConfigBatchWriteParams {
edits: key_paths
.into_iter()
.map(|segments| ConfigEdit {
key_path: segments.join("."),
value: serde_json::Value::Null,
merge_strategy: MergeStrategy::Replace,
})
.collect(),
file_path: None,
expected_version,
reload_user_config: false,
})
.await;
if let Err(err) = &result
&& latest_config.is_none()
&& err.write_error_code() == Some(ConfigWriteErrorCode::ConfigVersionConflict)
{
tracing::warn!(
"configuration changed while clearing Amazon Bedrock settings; retrying once"
);
latest_config = Some(
config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
.map_err(|err| {
internal_error(format!(
"failed to reload Amazon Bedrock configuration: {err}"
))
})?,
);
continue;
}
return result.map(|_| ()).map_err(map_config_error);
}
}

View File

@@ -0,0 +1,783 @@
use super::*;
use crate::model_catalog::ModelCatalog;
use codex_config::ConfigPathContext;
use codex_core::config::permission_profile_catalog;
use codex_hooks::HookListEntryHandler;
use codex_utils_absolute_path::AbsolutePathBufGuard;
use codex_utils_path_uri::PathConvention;
use codex_utils_path_uri::PathUri;
use futures::StreamExt;
#[derive(Clone)]
pub(crate) struct CatalogRequestProcessor {
pub(super) outgoing: Arc<OutgoingMessageSender>,
pub(super) skills_watcher: Arc<SkillsWatcher>,
pub(super) thread_manager: Arc<ThreadManager>,
pub(super) config: Arc<Config>,
pub(super) config_manager: ConfigManager,
model_catalog: Arc<ModelCatalog>,
}
const SKILLS_LIST_CWD_CONCURRENCY: usize = 5;
fn skills_to_info(
skills: &[codex_skills::SkillMetadata],
disabled_paths: &HashSet<PathUri>,
) -> Vec<codex_app_server_protocol::SkillMetadata> {
skills
.iter()
.map(|skill| {
let enabled = !disabled_paths.contains(&skill.path_to_skills_md);
codex_app_server_protocol::SkillMetadata {
name: skill.name.clone(),
description: skill.description.clone(),
short_description: skill.short_description.clone(),
interface: skill.interface.clone().map(|interface| {
codex_app_server_protocol::SkillInterface {
display_name: interface.display_name,
short_description: interface.short_description,
icon_small: interface.icon_small,
icon_large: interface.icon_large,
icon_small_url: None,
icon_large_url: None,
brand_color: interface.brand_color,
default_prompt: interface.default_prompt,
}
}),
dependencies: skill.dependencies.clone().map(|dependencies| {
codex_app_server_protocol::SkillDependencies {
tools: dependencies
.tools
.into_iter()
.map(|tool| codex_app_server_protocol::SkillToolDependency {
r#type: tool.r#type,
value: tool.value,
description: tool.description,
transport: tool.transport,
command: tool.command,
url: tool.url,
})
.collect(),
}
}),
path: skill.path_to_skills_md.clone().into(),
scope: skill.scope.into(),
enabled,
plugin_id: skill.plugin_id.clone(),
}
})
.collect()
}
fn hooks_to_info(hooks: &[codex_hooks::HookListEntry]) -> Vec<HookMetadata> {
hooks
.iter()
.filter(|hook| !hook.builtin)
.map(|hook| {
let handler = match &hook.handler {
HookListEntryHandler::Command { command, r#async } => {
HookHandlerMetadata::Command {
command: command.clone(),
r#async: *r#async,
}
}
HookListEntryHandler::McpTool { server, tool } => HookHandlerMetadata::McpTool {
server: server.clone(),
tool: tool.clone(),
},
};
HookMetadata {
key: hook.key.clone(),
event_name: hook.event_name.into(),
handler,
matcher: hook.matcher.clone(),
timeout_sec: hook.timeout_sec,
status_message: hook.status_message.clone(),
additional_context_limit: hook.additional_context_limit,
source_path: hook.source_path.clone(),
source: hook.source.into(),
plugin_id: hook.plugin_id.clone(),
environment_id: hook.environment_id.clone(),
display_order: hook.display_order,
enabled: hook.enabled,
is_managed: hook.is_managed,
current_hash: hook.current_hash.clone(),
trust_status: hook.trust_status.into(),
}
})
.collect()
}
fn errors_to_info(
errors: &[codex_skills::SkillError],
) -> Vec<codex_app_server_protocol::SkillErrorInfo> {
errors
.iter()
.map(|err| codex_app_server_protocol::SkillErrorInfo {
path: err.path.to_path_buf(),
message: err.message.clone(),
})
.collect()
}
impl CatalogRequestProcessor {
pub(crate) fn new(
outgoing: Arc<OutgoingMessageSender>,
skills_watcher: Arc<SkillsWatcher>,
thread_manager: Arc<ThreadManager>,
config: Arc<Config>,
config_manager: ConfigManager,
model_catalog: Arc<ModelCatalog>,
) -> Self {
Self {
outgoing,
skills_watcher,
thread_manager,
config,
config_manager,
model_catalog,
}
}
pub(crate) async fn skills_list(
&self,
params: SkillsListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.skills_list_response(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn hooks_list(
&self,
params: HooksListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.hooks_list_response(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn skills_config_write(
&self,
params: SkillsConfigWriteParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.skills_config_write_response_inner(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn skills_extra_roots_set(
&self,
params: SkillsExtraRootsSetParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.skills_extra_roots_set_response(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn model_list(
&self,
params: ModelListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let (active_config, active_models_manager) = self
.model_catalog
.current()
.await
.map_err(|err| config_load_error(&err))?;
let (config, models_manager) = match params.model_provider.as_deref() {
None => (active_config, active_models_manager),
Some(provider_id) => {
let config = config_for_provider(&self.config, provider_id)?;
if provider_id == active_config.model_provider_id
&& config.model_provider == active_config.model_provider
{
(active_config, active_models_manager)
} else {
// Temporary catalogs must not replace the active provider's disk cache.
let manager = self.thread_manager.temporary_models_manager_for_config(
&config,
&codex_models_manager::manager::ModelCatalogSettings::default(),
);
(config, manager)
}
}
};
// Gate the same provider used by the catalog, including when its model cache is warm.
// Resolving credentials may refresh them, but explicit host policy prevents browser login.
if let Some(gateway) = codex_model_provider::create_model_provider(
config.model_provider.clone(),
Some(self.thread_manager.auth_manager()),
)
.gateway_auth_manager()
.map_err(|error| internal_error(error.to_string()))?
{
// Refreshing credentials can contact the gateway before the catalog's own check.
self.config_manager
.check_thread_model_provider(&config)
.await
.map_err(|err| config_load_error(&err))?;
if let Err(error) = gateway.resolve_access_token().await {
let current = self
.config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
.map_err(|err| config_load_error(&err))?;
// An explicit selection need not match the current default.
if current.model_providers.get(&config.model_provider_id)
!= Some(&config.model_provider)
|| (params.model_provider.is_none()
&& current.model_provider_id != config.model_provider_id)
{
return Err(invalid_request(
"Model provider settings changed. Restart Codex to apply them, then retry fetching the model list",
));
}
return Err(invalid_request(error.to_string()));
}
}
self.list_models(params, config, models_manager)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn experimental_feature_list(
&self,
params: ExperimentalFeatureListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.experimental_feature_list_response(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn permission_profile_list(
&self,
params: PermissionProfileListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.permission_profile_list_response(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn collaboration_mode_list(
&self,
params: CollaborationModeListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
Self::list_collaboration_modes(self.thread_manager.clone(), params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn mock_experimental_method(
&self,
params: MockExperimentalMethodParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.mock_experimental_method_inner(params)
.await
.map(|response| Some(response.into()))
}
async fn resolve_cwd_config(
&self,
cwd: &Path,
) -> Result<(AbsolutePathBuf, ConfigLayerStack), String> {
let cwd_abs =
AbsolutePathBuf::relative_to_current_dir(cwd).map_err(|err| err.to_string())?;
let config_layer_stack = self
.config_manager
.load_config_layers_for_cwd(cwd_abs.clone())
.await
.map_err(|err| err.to_string())?;
Ok((cwd_abs, config_layer_stack))
}
async fn load_latest_config(
&self,
fallback_cwd: Option<PathBuf>,
) -> Result<Config, JSONRPCErrorError> {
self.config_manager
.load_latest_config(fallback_cwd)
.await
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
}
async fn list_models(
&self,
params: ModelListParams,
config: Arc<Config>,
models_manager: codex_models_manager::manager::SharedModelsManager,
) -> Result<ModelListResponse, JSONRPCErrorError> {
let ModelListParams {
limit,
cursor,
include_hidden,
model_provider: _,
} = params;
let presets = self
.model_catalog
.list_models_from_snapshot(
config,
models_manager,
codex_models_manager::manager::RefreshStrategy::OnlineIfUncached,
)
.await
.map_err(|err| config_load_error(&err))?;
let models = supported_models(presets, include_hidden.unwrap_or(false));
let total = models.len();
if total == 0 {
return Ok(ModelListResponse {
data: Vec::new(),
next_cursor: None,
});
}
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
let effective_limit = effective_limit.min(total);
let start = match cursor {
Some(cursor) => cursor
.parse::<usize>()
.map_err(|_| invalid_request(format!("invalid cursor: {cursor}")))?,
None => 0,
};
if start > total {
return Err(invalid_request(format!(
"cursor {start} exceeds total models {total}"
)));
}
let end = start.saturating_add(effective_limit).min(total);
let items = models[start..end].to_vec();
let next_cursor = if end < total {
Some(end.to_string())
} else {
None
};
Ok(ModelListResponse {
data: items,
next_cursor,
})
}
async fn list_collaboration_modes(
thread_manager: Arc<ThreadManager>,
params: CollaborationModeListParams,
) -> Result<CollaborationModeListResponse, JSONRPCErrorError> {
let CollaborationModeListParams {} = params;
let items = thread_manager
.list_collaboration_modes()
.into_iter()
.map(Into::into)
.collect();
let response = CollaborationModeListResponse { data: items };
Ok(response)
}
async fn experimental_feature_list_response(
&self,
params: ExperimentalFeatureListParams,
) -> Result<ExperimentalFeatureListResponse, JSONRPCErrorError> {
let ExperimentalFeatureListParams {
cursor,
limit,
thread_id,
} = params;
let config = match thread_id.as_deref() {
Some(thread_id) => {
let thread_id = ThreadId::from_string(thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
let thread = self
.thread_manager
.get_thread(thread_id)
.await
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
let thread_config = thread.config().await;
self.config_manager
.load_latest_config_with_session_layers(
&thread_config.config_layer_stack,
&thread_config.cwd,
)
.await
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?
}
None => self.load_latest_config(/*fallback_cwd*/ None).await?,
};
let data = FEATURES
.iter()
.map(|spec| {
let (stage, display_name, description, announcement) = match spec.stage {
Stage::Experimental {
name,
menu_description,
announcement,
} => (
ApiExperimentalFeatureStage::Beta,
Some(name.to_string()),
Some(menu_description.to_string()),
Some(announcement.to_string()),
),
Stage::UnderDevelopment => (
ApiExperimentalFeatureStage::UnderDevelopment,
None,
None,
None,
),
Stage::Stable => (ApiExperimentalFeatureStage::Stable, None, None, None),
Stage::Deprecated => {
(ApiExperimentalFeatureStage::Deprecated, None, None, None)
}
Stage::Removed => (ApiExperimentalFeatureStage::Removed, None, None, None),
};
ApiExperimentalFeature {
name: spec.key.to_string(),
stage,
display_name,
description,
announcement,
enabled: config.features.enabled(spec.id),
default_enabled: spec.default_enabled,
}
})
.collect::<Vec<_>>();
let total = data.len();
if total == 0 {
return Ok(ExperimentalFeatureListResponse {
data: Vec::new(),
next_cursor: None,
});
}
// Clamp to 1 so limit=0 cannot return a non-advancing page.
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
let effective_limit = effective_limit.min(total);
let start = match cursor {
Some(cursor) => match cursor.parse::<usize>() {
Ok(idx) => idx,
Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))),
},
None => 0,
};
if start > total {
return Err(invalid_request(format!(
"cursor {start} exceeds total feature flags {total}"
)));
}
let end = start.saturating_add(effective_limit).min(total);
let data = data[start..end].to_vec();
let next_cursor = if end < total {
Some(end.to_string())
} else {
None
};
Ok(ExperimentalFeatureListResponse { data, next_cursor })
}
async fn permission_profile_list_response(
&self,
params: PermissionProfileListParams,
) -> Result<PermissionProfileListResponse, JSONRPCErrorError> {
let PermissionProfileListParams { cursor, limit, cwd } = params;
let (cwd, config_layer_stack) = match cwd {
Some(cwd) => self
.resolve_cwd_config(&PathBuf::from(cwd))
.await
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?,
None => (
self.config.cwd.clone(),
self.config_manager
.load_config_layers(/*cwd*/ None)
.await
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?,
),
};
let context = ConfigPathContext::new(
PathConvention::native(),
Some(PathUri::from_abs_path(&cwd)),
AbsolutePathBufGuard::home_directory()
.and_then(|home| PathUri::from_host_native_path(home).ok()),
);
let profiles = permission_profile_catalog(&config_layer_stack, &context)
.map_err(|err| internal_error(format!("failed to resolve permission profiles: {err}")))?
.into_iter()
.map(|profile| PermissionProfileSummary {
id: profile.id,
description: profile.description,
allowed: profile.allowed,
})
.collect::<Vec<_>>();
let total = profiles.len();
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
let effective_limit = effective_limit.min(total);
let start = match cursor {
Some(cursor) => cursor
.parse::<usize>()
.map_err(|_| invalid_request(format!("invalid cursor: {cursor}")))?,
None => 0,
};
if start > total {
return Err(invalid_request(format!(
"cursor {start} exceeds total permission profiles {total}"
)));
}
let end = start.saturating_add(effective_limit).min(total);
let data = profiles[start..end].to_vec();
let next_cursor = (end < total).then_some(end.to_string());
Ok(PermissionProfileListResponse { data, next_cursor })
}
async fn mock_experimental_method_inner(
&self,
params: MockExperimentalMethodParams,
) -> Result<MockExperimentalMethodResponse, JSONRPCErrorError> {
let MockExperimentalMethodParams { value } = params;
let response = MockExperimentalMethodResponse { echoed: value };
Ok(response)
}
async fn skills_list_response(
&self,
params: SkillsListParams,
) -> Result<SkillsListResponse, JSONRPCErrorError> {
let SkillsListParams { cwds, force_reload } = params;
let cwds = if cwds.is_empty() {
vec![self.config.cwd.to_path_buf()]
} else {
cwds
};
let skills_service = self.thread_manager.skills_service();
let plugins_manager = self.thread_manager.plugins_manager();
if force_reload {
plugins_manager.clear_cache();
skills_service.clear_cache();
}
let fs = self
.thread_manager
.environment_manager()
.default_environment()
.map(|environment| environment.get_filesystem());
let skills_request = skills_service.for_request();
let mut data = futures::stream::iter(cwds.into_iter().enumerate())
.map(|(index, cwd)| {
let fs = fs.clone();
let skills_request = &skills_request;
let plugins_manager = Arc::clone(&plugins_manager);
async move {
let config = match self.load_latest_config(Some(cwd.clone())).await {
Ok(resolved) => resolved,
Err(error) => {
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: error.message,
}],
},
);
}
};
let plugins_input = config.plugins_config_input();
let plugins = plugins_manager.plugins_for_config(&plugins_input).await;
let plugin_skill_snapshots =
plugins_manager.plugin_skill_snapshots_for_config(&plugins_input);
let skills_input = codex_skills_extension::HostSkillsLoadInput::new(
config.cwd.clone(),
plugins.effective_plugin_skill_roots(),
config.config_layer_stack,
)
.with_plugin_skill_snapshots(plugin_skill_snapshots);
let skills_input = match self
.thread_manager
.environment_manager()
.default_environment_id()
{
Some(environment_id) => skills_input.with_environment_id(environment_id),
None => skills_input,
};
let snapshot = skills_request
.snapshot_for_cwd(&skills_input, force_reload, fs)
.await;
let outcome = snapshot.outcome();
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,
},
)
}
})
.buffer_unordered(SKILLS_LIST_CWD_CONCURRENCY)
.collect::<Vec<_>>()
.await;
data.sort_unstable_by_key(|(index, _)| *index);
let data = data.into_iter().map(|(_, entry)| entry).collect();
Ok(SkillsListResponse { data })
}
async fn skills_extra_roots_set_response(
&self,
params: SkillsExtraRootsSetParams,
) -> Result<SkillsExtraRootsSetResponse, JSONRPCErrorError> {
let SkillsExtraRootsSetParams { extra_roots } = params;
self.skills_watcher
.register_runtime_extra_roots(&extra_roots);
self.thread_manager
.skills_service()
.set_extra_roots(extra_roots);
self.outgoing
.send_server_notification(ServerNotification::SkillsChanged(
codex_app_server_protocol::SkillsChangedNotification {},
))
.await;
Ok(SkillsExtraRootsSetResponse {})
}
/// Resolve a loaded thread's hook inventory, or inspect configuration for each requested cwd.
async fn hooks_list_response(
&self,
params: HooksListParams,
) -> Result<HooksListResponse, JSONRPCErrorError> {
let HooksListParams { cwds, thread_id } = params;
if let Some(thread_id) = thread_id {
if !cwds.is_empty() {
return Err(invalid_request("specify either threadId or cwds"));
}
let thread_id = ThreadId::from_string(&thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
let thread = self
.thread_manager
.get_thread(thread_id)
.await
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
let cwd = thread.config_snapshot().await.cwd().to_path_buf();
let hooks = thread.list_hooks();
return Ok(HooksListResponse {
data: vec![codex_app_server_protocol::HooksListEntry {
cwd,
hooks: hooks_to_info(&hooks.hooks),
warnings: hooks.warnings,
errors: Vec::new(),
}],
});
}
let cwds = if cwds.is_empty() {
vec![self.config.cwd.to_path_buf()]
} else {
cwds
};
let plugins_manager = self.thread_manager.plugins_manager();
let mut data = Vec::new();
for cwd in cwds {
let config = match self
.config_manager
.load_for_cwd(
/*request_overrides*/ None,
ConfigOverrides::default(),
Some(cwd.clone()),
)
.await
{
Ok(config) => config,
Err(err) => {
let error_path = cwd.clone();
data.push(codex_app_server_protocol::HooksListEntry {
cwd,
hooks: Vec::new(),
warnings: Vec::new(),
errors: vec![codex_app_server_protocol::HookErrorInfo {
path: error_path,
message: err.to_string(),
}],
});
continue;
}
};
let hooks_enabled = config.features.enabled(Feature::CodexHooks);
let plugin_hooks = if hooks_enabled && config.features.enabled(Feature::Plugins) {
let plugins_input = config.plugins_config_input();
let plugin_outcome = plugins_manager.plugins_for_config(&plugins_input).await;
codex_core_plugins::PluginHookLoadOutcome {
hook_sources: plugin_outcome.effective_plugin_hook_sources(),
hook_load_warnings: plugin_outcome.effective_plugin_hook_warnings(),
}
} else {
codex_core_plugins::PluginHookLoadOutcome::default()
};
let hooks_config = codex_hooks::HooksConfig {
feature_enabled: hooks_enabled,
bypass_hook_trust: config.bypass_hook_trust,
config_layer_stack: Some(config.config_layer_stack),
plugin_hook_sources: plugin_hooks.hook_sources,
plugin_hook_load_warnings: plugin_hooks.hook_load_warnings,
..Default::default()
};
let hooks = tokio::task::spawn_blocking(move || codex_hooks::list_hooks(hooks_config))
.await
.map_err(|err| internal_error(format!("hook discovery task failed: {err}")))?;
data.push(codex_app_server_protocol::HooksListEntry {
cwd,
hooks: hooks_to_info(&hooks.hooks),
warnings: hooks.warnings,
errors: Vec::new(),
});
}
Ok(HooksListResponse { data })
}
async fn skills_config_write_response_inner(
&self,
params: SkillsConfigWriteParams,
) -> Result<SkillsConfigWriteResponse, JSONRPCErrorError> {
let SkillsConfigWriteParams {
path,
name,
enabled,
} = params;
let edit = match (path, name) {
(Some(path), None) => ConfigEdit::SetSkillConfig {
path: path.into_path_buf(),
enabled,
},
(None, Some(name)) if !name.trim().is_empty() => {
ConfigEdit::SetSkillConfigByName { name, enabled }
}
_ => {
return Err(invalid_params(
"skills/config/write requires exactly one of path or name",
));
}
};
let edits = vec![edit];
ConfigEditsBuilder::new(&self.config.codex_home)
.with_edits(edits)
.apply()
.await
.map(|()| {
self.thread_manager.plugins_manager().clear_cache();
self.thread_manager.skills_service().clear_cache();
SkillsConfigWriteResponse {
effective_enabled: enabled,
}
})
.map_err(|err| internal_error(format!("failed to update skill settings: {err}")))
}
}

View File

@@ -0,0 +1,344 @@
use super::*;
use codex_core::exec_env::inject_apply_patch_env;
use codex_core::windows_sandbox::local_binding_policy_for_sandbox;
use codex_core::windows_sandbox::managed_proxy_routing_for_windows_sandbox;
use codex_protocol::shell_environment::is_non_inheritable_env_var;
#[derive(Clone)]
pub(crate) struct CommandExecRequestProcessor {
arg0_paths: Arg0DispatchPaths,
config: Arc<Config>,
outgoing: Arc<OutgoingMessageSender>,
config_manager: ConfigManager,
environment_manager: Arc<EnvironmentManager>,
command_exec_manager: CommandExecManager,
}
impl CommandExecRequestProcessor {
pub(crate) fn new(
arg0_paths: Arg0DispatchPaths,
config: Arc<Config>,
outgoing: Arc<OutgoingMessageSender>,
config_manager: ConfigManager,
environment_manager: Arc<EnvironmentManager>,
) -> Self {
Self {
arg0_paths,
config,
outgoing,
config_manager,
environment_manager,
command_exec_manager: CommandExecManager::default(),
}
}
pub(crate) async fn one_off_command_exec(
&self,
request_id: &ConnectionRequestId,
params: CommandExecParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.require_local_environment()?;
self.exec_one_off_command(request_id, params)
.await
.map(|()| None)
}
pub(crate) async fn command_exec_write(
&self,
request_id: ConnectionRequestId,
params: CommandExecWriteParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.command_exec_manager
.write(request_id, params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn command_exec_resize(
&self,
request_id: ConnectionRequestId,
params: CommandExecResizeParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.command_exec_manager
.resize(request_id, params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn command_exec_terminate(
&self,
request_id: ConnectionRequestId,
params: CommandExecTerminateParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.command_exec_manager
.terminate(request_id, params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn connection_closed(&self, connection_id: ConnectionId) {
self.command_exec_manager
.connection_closed(connection_id)
.await;
}
fn require_local_environment(&self) -> Result<(), JSONRPCErrorError> {
self.environment_manager
.try_local_environment()
.is_some()
.then_some(())
.ok_or_else(|| internal_error("local environment is not configured"))
}
async fn exec_one_off_command(
&self,
request_id: &ConnectionRequestId,
params: CommandExecParams,
) -> Result<(), JSONRPCErrorError> {
self.exec_one_off_command_inner(request_id.clone(), params)
.await
}
async fn exec_one_off_command_inner(
&self,
request_id: ConnectionRequestId,
params: CommandExecParams,
) -> Result<(), JSONRPCErrorError> {
tracing::debug!("ExecOneOffCommand params: {params:?}");
let request = request_id.clone();
if params.command.is_empty() {
return Err(invalid_request("command must not be empty"));
}
let CommandExecParams {
command,
process_id,
tty,
stream_stdin,
stream_stdout_stderr,
output_bytes_cap,
disable_output_cap,
disable_timeout,
timeout_ms,
cwd,
env: env_overrides,
size,
sandbox_policy,
permission_profile,
} = params;
if sandbox_policy.is_some() && permission_profile.is_some() {
return Err(invalid_request(
"`permissionProfile` cannot be combined with `sandboxPolicy`",
));
}
if size.is_some() && !tty {
return Err(invalid_params("command/exec size requires tty: true"));
}
if disable_output_cap && output_bytes_cap.is_some() {
return Err(invalid_params(
"command/exec cannot set both outputBytesCap and disableOutputCap",
));
}
if disable_timeout && timeout_ms.is_some() {
return Err(invalid_params(
"command/exec cannot set both timeoutMs and disableTimeout",
));
}
let cwd = cwd.map_or_else(|| self.config.cwd.clone(), |cwd| self.config.cwd.join(cwd));
let mut env = create_env(
&self.config.permissions.shell_environment_policy,
/*thread_id*/ None,
);
if let Some(env_overrides) = env_overrides {
for (key, value) in env_overrides {
match value {
Some(value) => {
env.insert(key, value);
}
None => {
env.remove(&key);
}
}
}
}
env.retain(|name, _| !is_non_inheritable_env_var(name));
inject_apply_patch_env(&mut env);
let timeout_ms = match timeout_ms {
Some(timeout_ms) => match u64::try_from(timeout_ms) {
Ok(timeout_ms) => Some(timeout_ms),
Err(_) => {
return Err(invalid_params(format!(
"command/exec timeoutMs must be non-negative, got {timeout_ms}"
)));
}
},
None => None,
};
let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config);
let output_bytes_cap = if disable_output_cap {
None
} else {
Some(output_bytes_cap.unwrap_or(DEFAULT_OUTPUT_BYTES_CAP))
};
let expiration = if disable_timeout {
ExecExpiration::Cancellation(CancellationToken::new())
} else {
match timeout_ms {
Some(timeout_ms) => timeout_ms.into(),
None => ExecExpiration::DefaultTimeout,
}
};
let capture_policy = if disable_output_cap {
ExecCapturePolicy::FullBuffer
} else {
ExecCapturePolicy::ShellTool
};
let sandbox_cwd = if permission_profile.is_some() {
cwd.clone()
} else {
self.config.cwd.clone()
};
let (
effective_permission_profile,
network_proxy_spec,
network_proxy_permission_profile,
managed_network_requirements_enabled,
windows_sandbox_workspace_roots,
) = if let Some(permission_profile) = permission_profile {
let overrides = ConfigOverrides {
cwd: Some(cwd.to_path_buf()),
default_permissions: Some(permission_profile),
..Default::default()
};
let config = self
.config_manager
.load_for_cwd(
/*request_overrides*/ None,
overrides,
Some(self.config.cwd.to_path_buf()),
)
.await
.map_err(|err| invalid_request(format!("invalid permission profile: {err}")))?;
if let Some(warning) = config.startup_warnings.iter().find(|warning| {
warning.contains("Configured value for `permission_profile` is disallowed")
}) {
return Err(invalid_request(format!(
"invalid permission profile: {warning}"
)));
}
(
config.permissions.effective_permission_profile(),
config.permissions.network.clone(),
config.permissions.permission_profile().clone(),
config.managed_network_requirements_enabled(),
config.effective_workspace_roots(),
)
} else if let Some(policy) = sandbox_policy.map(|policy| policy.to_core()) {
let mut permissions = self.config.permissions.clone();
permissions
.set_legacy_sandbox_policy(policy, &sandbox_cwd)
.map_err(|err| invalid_request(format!("invalid sandbox policy: {err}")))?;
(
permissions.effective_permission_profile(),
self.config.permissions.network.clone(),
self.config.permissions.permission_profile().clone(),
self.config.managed_network_requirements_enabled(),
self.config.effective_workspace_roots(),
)
} else {
(
self.config.permissions.effective_permission_profile(),
self.config.permissions.network.clone(),
self.config.permissions.permission_profile().clone(),
self.config.managed_network_requirements_enabled(),
self.config.effective_workspace_roots(),
)
};
let started_network_proxy = match network_proxy_spec.as_ref() {
Some(spec) => match spec
.start_proxy(
&network_proxy_permission_profile,
managed_proxy_routing_for_windows_sandbox(
self.config.effective_local_windows_sandbox_type(),
),
local_binding_policy_for_sandbox(
self.config.effective_local_windows_sandbox_type(),
Some(std::env::consts::OS),
),
/*policy_decider*/ None,
/*blocked_request_observer*/ None,
managed_network_requirements_enabled,
NetworkProxyAuditMetadata::default(),
)
.await
{
Ok(started) => Some(started),
Err(err) => {
return Err(internal_error(format!(
"failed to start managed network proxy: {err}"
)));
}
},
None => None,
};
let exec_params = ExecParams {
command,
cwd: cwd.clone(),
expiration,
capture_policy,
env,
network: started_network_proxy
.as_ref()
.map(codex_core::config::StartedNetworkProxy::proxy),
network_environment_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level,
justification: None,
arg0: None,
};
let codex_linux_sandbox_exe = self.arg0_paths.codex_linux_sandbox_exe.clone();
let outgoing = self.outgoing.clone();
let request_for_task = request.clone();
let started_network_proxy_for_task = started_network_proxy;
let use_legacy_landlock = self.config.features.use_legacy_landlock();
let size = match size.map(crate::command_exec::terminal_size_from_protocol) {
Some(Ok(size)) => Some(size),
Some(Err(error)) => return Err(error),
None => None,
};
let exec_request = codex_core::exec::build_exec_request(
exec_params,
&effective_permission_profile,
&sandbox_cwd,
windows_sandbox_workspace_roots.as_slice(),
&codex_linux_sandbox_exe,
&self.arg0_paths.codex_self_exe,
self.config.effective_local_windows_sandbox_type(),
use_legacy_landlock,
)
.await
.map_err(|err| internal_error(format!("exec failed: {err}")))?;
self.command_exec_manager
.start(StartCommandExecParams {
outgoing,
request_id: request_for_task,
process_id,
exec_request,
started_network_proxy: started_network_proxy_for_task,
tty,
stream_stdin,
stream_stdout_stderr,
output_bytes_cap,
size,
})
.await
}
}

View File

@@ -0,0 +1,50 @@
use super::*;
fn cloud_config_bundle_load_error(err: &std::io::Error) -> Option<&CloudConfigBundleLoadError> {
let mut current: Option<&(dyn std::error::Error + 'static)> = err
.get_ref()
.map(|source| source as &(dyn std::error::Error + 'static));
while let Some(source) = current {
if let Some(cloud_error) = source.downcast_ref::<CloudConfigBundleLoadError>() {
return Some(cloud_error);
}
current = source.source();
}
None
}
pub(super) fn model_provider_error(provider: &ModelProviderError) -> JSONRPCErrorError {
let mut error = invalid_request(provider.to_string());
error.data = serde_json::to_value(provider).ok();
error
}
pub(crate) fn config_load_error(err: &std::io::Error) -> JSONRPCErrorError {
let mut current = err
.get_ref()
.map(|error| error as &(dyn std::error::Error + 'static));
while let Some(source) = current {
if let Some(provider_error) = source.downcast_ref::<ModelProviderError>() {
return model_provider_error(provider_error);
}
current = source.source();
}
let data = cloud_config_bundle_load_error(err).map(|cloud_error| {
let mut data = serde_json::json!({
"reason": "cloudConfigBundle",
"errorCode": format!("{:?}", cloud_error.code()),
"detail": cloud_error.to_string(),
});
if let Some(status_code) = cloud_error.status_code() {
data["statusCode"] = serde_json::json!(status_code);
}
if cloud_error.code() == CloudConfigBundleLoadErrorCode::Auth {
data["action"] = serde_json::json!("relogin");
}
data
});
let mut error = invalid_request(format!("failed to load configuration: {err}"));
error.data = data;
error
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,252 @@
//! Regressions for reload entry points composing the final thread configuration.
use super::config_processor::reload_user_config;
use crate::config_manager::ConfigManager;
use crate::mcp_refresh::reload_mcp_config;
use codex_config::types::AuthKeyringBackendKind;
use codex_core::config::ConfigOverrides;
use codex_exec_server::EnvironmentManager;
use codex_login::CodexAuth;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;
#[tokio::test]
async fn reloads_accept_a_provider_supplied_by_thread_overrides() -> anyhow::Result<()> {
let home = tempfile::tempdir()?;
let manager = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf());
let initial = manager
.load_for_cwd(
Some(HashMap::from([
("model_provider".to_string(), json!("thread-provider")),
(
"model_providers.thread-provider".to_string(),
json!({"name": "Thread provider", "base_url": "https://provider.example/v1", "wire_api": "responses"}),
),
])),
ConfigOverrides::default(),
Some(home.path().to_path_buf()),
)
.await?;
let threads = Arc::new(
codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::from_api_key("dummy"),
initial.model_provider.clone(),
initial.codex_home.to_path_buf(),
Arc::new(EnvironmentManager::default_for_tests()),
),
);
let thread = threads
.start_thread(codex_core::StartThreadOptions::new(initial))
.await?
.thread;
for enabled in [true, false] {
std::fs::write(
home.path().join(codex_config::CONFIG_TOML_FILE),
format!(
"model_provider = 'missing-provider'\n[features]\nsecret_auth_storage = {enabled}\n"
),
)?;
if enabled {
reload_mcp_config(&threads, &manager).await?;
} else {
reload_user_config(&manager, &threads).await;
}
let config = thread.config().await;
assert_eq!(config.model_provider_id, "thread-provider");
assert_eq!(
config.auth_keyring_backend_kind(),
if enabled {
AuthKeyringBackendKind::Secrets
} else {
AuthKeyringBackendKind::Direct
}
);
}
Ok(())
}
#[tokio::test]
async fn user_reload_promotes_plugin_and_feature_requirements_without_server_changes()
-> anyhow::Result<()> {
let home = tempfile::tempdir()?;
let requirements_path = home.path().join("requirements.toml");
std::fs::write(&requirements_path, "")?;
std::fs::write(
home.path().join(codex_config::CONFIG_TOML_FILE),
"[features]\nenable_mcp_apps = true\n",
)?;
let mut overrides = codex_config::LoaderOverrides::without_managed_config_for_tests();
overrides.ignore_managed_requirements = false;
overrides.system_requirements_path = Some(requirements_path.clone());
let manager = ConfigManager::new(
home.path().to_path_buf(),
Vec::new(),
overrides,
/*strict_config*/ false,
codex_config::CloudConfigBundleLoader::default(),
codex_arg0::Arg0DispatchPaths::default(),
Arc::new(codex_config::NoopThreadConfigLoader),
);
let initial = manager
.load_latest_config(Some(home.path().to_path_buf()))
.await?;
let threads = Arc::new(
codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::from_api_key("dummy"),
initial.model_provider.clone(),
initial.codex_home.to_path_buf(),
Arc::new(EnvironmentManager::default_for_tests()),
),
);
assert!(
initial
.features
.enabled(codex_features::Feature::EnableMcpApps)
);
let original_servers = initial.mcp_servers.get().clone();
let thread = threads
.start_thread(codex_core::StartThreadOptions::new(initial))
.await?
.thread;
std::fs::write(
&requirements_path,
"[features]\nenable_mcp_apps = false\n[plugins.example.mcp_servers]\n",
)?;
tokio::time::timeout(
std::time::Duration::from_secs(10),
reload_user_config(&manager, &threads),
)
.await
.expect("policy promotion must terminate");
let config = thread.config().await;
assert_eq!(config.mcp_servers.get(), &original_servers);
assert!(
!config
.features
.enabled(codex_features::Feature::EnableMcpApps)
);
assert!(
config
.config_layer_stack
.requirements()
.plugins
.as_ref()
.unwrap()
.value
.get("example")
.unwrap()
.mcp_servers
.as_ref()
.unwrap()
.is_empty()
);
assert!(
config
.config_layer_stack
.requirements()
.feature_requirements
.is_some()
);
Ok(())
}
#[test_case::test_case(codex_config::CloudConfigBundleBindingStatus::Stale)]
#[test_case::test_case(codex_config::CloudConfigBundleBindingStatus::Suspended)]
#[tokio::test]
async fn mcp_refresh_rejects_superseded_app_server_policy(
status: codex_config::CloudConfigBundleBindingStatus,
) -> anyhow::Result<()> {
use codex_config::CloudConfigBundle;
use codex_config::CloudConfigBundleLoader;
use codex_config::CloudConfigBundlePolicy;
use codex_config::CloudConfigBundleSnapshot;
use codex_core::ConfigRefreshOutcome;
let home = tempfile::tempdir()?;
let policy = CloudConfigBundlePolicy::default();
let mut snapshot = CloudConfigBundleSnapshot {
config_server: None,
bundle: Ok(None),
binding: None,
};
policy.publish_snapshot(&mut snapshot);
let loader =
CloudConfigBundleLoader::default().with_ema_policy_snapshots(policy.clone(), move || {
let snapshot = snapshot.clone();
async move { snapshot }
});
let manager = ConfigManager::new(
home.path().to_path_buf(),
Vec::new(),
codex_config::LoaderOverrides::without_managed_config_for_tests(),
/*strict_config*/ false,
loader,
codex_arg0::Arg0DispatchPaths::default(),
Arc::new(codex_config::NoopThreadConfigLoader),
);
let initial = manager
.load_latest_config(Some(home.path().to_path_buf()))
.await?;
let threads = codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::from_api_key("dummy"),
initial.model_provider.clone(),
initial.codex_home.to_path_buf(),
Arc::new(EnvironmentManager::default_for_tests()),
);
let thread = threads
.start_thread(codex_core::StartThreadOptions::new(initial))
.await?
.thread;
let current = thread.config().await;
let next = manager
.load_latest_config_with_session_layers(&current.config_layer_stack, &current.cwd)
.await?;
let mut replacement = CloudConfigBundle::default();
replacement
.config_toml
.enterprise_managed
.push(codex_config::CloudConfigFragment {
id: "replacement".into(),
name: "replacement".into(),
contents: "model = 'replacement-model'".into(),
});
policy.observe_remote_bundle(&replacement);
if status == codex_config::CloudConfigBundleBindingStatus::Stale {
policy.publish_snapshot(&mut CloudConfigBundleSnapshot {
config_server: None,
bundle: Ok(Some(replacement)),
binding: None,
});
}
assert_eq!(
next.config_layer_stack
.cloud_config_binding()
.expect("app-server must retain the policy binding")
.read()
.status,
status,
);
let outcome = thread.refresh_mcp_config(Arc::clone(&current), next).await;
let expected = match status {
codex_config::CloudConfigBundleBindingStatus::Stale => ConfigRefreshOutcome::Stale,
codex_config::CloudConfigBundleBindingStatus::Suspended => ConfigRefreshOutcome::Rejected,
codex_config::CloudConfigBundleBindingStatus::Current => unreachable!(),
};
assert_eq!(outcome, expected);
if status == codex_config::CloudConfigBundleBindingStatus::Stale {
assert!(Arc::ptr_eq(&current, &thread.config().await));
} else {
assert!(
thread
.config()
.await
.config_layer_stack
.cloud_config_binding()
.is_none()
);
}
Ok(())
}

View File

@@ -0,0 +1,141 @@
//! Attempts one new continuation turn immediately after daemon thread restoration.
//! Completed or superseded work is discarded; recovery never waits for a later idle event.
//! Permissions and the saved local executor selection must match the resumed runtime.
use super::ThreadRequestProcessor;
use codex_app_server_protocol::ThreadEnvironment;
use codex_app_server_transport::daemon_recovery::InterruptedTurn;
use codex_core::TurnInput;
use codex_core::TurnInputRequest;
use codex_core::TurnInputSubmission;
use codex_core::TurnStartOptions;
use codex_core::context::ContextualUserFragment;
use codex_core::context::InternalContextSource;
use codex_core::context::InternalModelContextFragment;
use codex_protocol::ThreadId;
use codex_protocol::protocol::EnvironmentConfigState;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::TurnAbortReason;
use codex_protocol::protocol::TurnAbortedEvent;
use codex_rollout::RolloutItem;
impl ThreadRequestProcessor {
pub(crate) async fn continue_daemon_turn(&self, thread_id: &str, saved: InterruptedTurn) {
let Ok(thread_id) = ThreadId::from_string(thread_id) else {
return;
};
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
return;
};
let Some(path) = thread.rollout_path() else {
return;
};
let history = match codex_rollout::RolloutRecorder::load_rollout_items(&path).await {
Ok((history, _, _)) => history,
Err(err) => {
tracing::warn!(%thread_id, %err, "failed to read interrupted turn history");
return;
}
};
// The snapshot has complete recorded input, but the old process may have
// completed or replaced its turn during the shutdown grace period.
let Some(start) = history
.iter()
.rposition(|item| matches!(item, RolloutItem::EventMsg(EventMsg::TurnStarted(_))))
else {
return;
};
if !matches!(&history[start], RolloutItem::EventMsg(EventMsg::TurnStarted(event))
if event.turn_id == saved.turn_id)
|| history[start..].iter().any(|item| match item {
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => {
event.turn_id == saved.turn_id
}
RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => event
.turn_id
.as_ref()
.is_none_or(|turn_id| turn_id == &saved.turn_id),
_ => false,
})
{
return;
}
let previous_context = history.iter().rev().find_map(|item| match item {
RolloutItem::TurnContext(context)
if context.turn_id.as_ref() == Some(&saved.turn_id) =>
{
Some(context)
}
_ => None,
});
let Some(previous_context) = previous_context else {
return;
};
let config = thread.config_snapshot().await;
let [environment] = config.environment_selections() else {
return;
};
if environment.environment_id != codex_exec_server::LOCAL_ENVIRONMENT_ID
|| environment.config != EnvironmentConfigState::FromThread
|| saved.local_environment.as_ref() != Some(&ThreadEnvironment::from(environment))
{
return;
}
// Recovery must not override a stricter saved or newly configured policy.
if previous_context.permission_profile != config.permission_profile {
return;
}
let continuation = ContextualUserFragment::into(InternalModelContextFragment::new(
InternalContextSource::from_static("daemon_recovery"),
"The server restarted and interrupted the previous turn. Continue the unfinished work from the saved conversation. Check the current state before repeating actions that may already have completed.",
));
let request = TurnInputRequest::new(TurnInput::ResponseItem(continuation)).on_start(
TurnStartOptions {
turn_trigger: Some("daemon_recovery".to_string()),
final_output_json_schema: saved.output_schema,
service_tier: saved.service_tier,
cyber_access_program: saved.cyber_access_program,
root_turn_id: previous_context.root_turn_id.clone(),
..Default::default()
},
);
// Close the old turn in persisted history before exposing a new running turn.
if let Err(err) = thread
.append_rollout_items(&[RolloutItem::EventMsg(EventMsg::TurnAborted(
TurnAbortedEvent {
root_turn_id: None,
turn_id: Some(saved.turn_id.clone()),
reason: TurnAbortReason::Interrupted,
error: None,
started_at: None,
completed_at: None,
duration_ms: None,
},
))])
.await
{
tracing::warn!(%thread_id, %err, "failed to close interrupted turn history");
return;
}
match thread.continue_turn_if_idle(request, saved.turn_id).await {
Ok(TurnInputSubmission::Started { .. }) => {
crate::extensions::send_thread_warning(
&self.outgoing,
&self.thread_state_manager,
thread_id,
"Resuming interrupted work".to_string(),
)
.await;
}
Ok(TurnInputSubmission::NotSubmitted { reason }) => {
tracing::debug!(%thread_id, ?reason, "recovery continuation was not started");
}
Ok(TurnInputSubmission::Steered { .. } | TurnInputSubmission::Accepted) => {
// continue_turn_if_idle uses start_if_idle, which cannot steer or
// enter the agent-message path that returns Accepted.
unreachable!("continuation must start or decline")
}
Err(err) => tracing::warn!(%thread_id, %err, "recovery continuation failed"),
}
}
}

View File

@@ -0,0 +1,56 @@
//! Selects persistent root threads for managed daemon recovery using normal resume semantics.
//! Only threads successfully persisted through the existing thread store become candidates.
use super::ThreadRequestProcessor;
use codex_app_server_transport::daemon_recovery::InterruptedTurn;
use codex_app_server_transport::daemon_recovery::RecoverySnapshot;
use codex_thread_store::PersistContext;
use tracing::warn;
impl ThreadRequestProcessor {
#[expect(
clippy::await_holding_invalid_type,
reason = "snapshot selection must be serialized against pending unloads"
)]
pub(crate) async fn daemon_recovery_snapshot(&self) -> RecoverySnapshot {
let mut snapshot = RecoverySnapshot::default();
for thread_id in self.thread_manager.list_thread_ids().await {
let pending_unloads = self.pending_thread_unloads.lock().await;
if pending_unloads.contains_key(&thread_id) {
continue;
}
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
continue;
};
let config = thread.config_snapshot().await;
if !config.ephemeral
&& config.parent_thread_id.is_none()
&& !config.session_source.is_non_root_agent()
{
let interrupted = thread.interrupted_turn().await;
if let Err(err) = self
.thread_store
.persist_thread(thread_id, PersistContext::Standard)
.await
{
warn!(%thread_id, %err, "skipping daemon restore for thread that could not be persisted");
continue;
}
snapshot.loaded.insert(thread_id.to_string());
if let Some((turn_id, options, environment)) = interrupted {
snapshot.interrupted.insert(
thread_id.to_string(),
InterruptedTurn {
turn_id,
output_schema: options.final_output_json_schema,
service_tier: options.service_tier,
cyber_access_program: options.cyber_access_program,
local_environment: Some((&environment).into()),
},
);
}
}
}
snapshot
}
}

View File

@@ -0,0 +1,23 @@
use codex_app_server_protocol::ServerDiagnosticsGauge;
use codex_app_server_protocol::ServerDiagnosticsProcess;
use codex_app_server_protocol::ServerDiagnosticsResponse;
pub(crate) fn read_server_diagnostics() -> ServerDiagnosticsResponse {
let diagnostics = codex_diagnostics::snapshot();
ServerDiagnosticsResponse {
process: ServerDiagnosticsProcess {
id: diagnostics.process.id,
resident_memory_bytes: diagnostics.process.resident_memory_bytes,
physical_footprint_bytes: diagnostics.process.physical_footprint_bytes,
},
gauges: diagnostics
.gauges
.into_iter()
.map(|gauge| ServerDiagnosticsGauge {
name: gauge.name.to_string(),
value: gauge.value,
})
.collect(),
}
}

View File

@@ -0,0 +1,101 @@
use super::*;
use codex_config::ScopedSkillsConfig;
use codex_exec_server::RemoteEnvironmentOptions;
use std::time::Duration;
#[derive(Clone)]
pub(crate) struct EnvironmentRequestProcessor {
environment_manager: Arc<EnvironmentManager>,
}
impl EnvironmentRequestProcessor {
pub(crate) fn new(environment_manager: Arc<EnvironmentManager>) -> Self {
Self {
environment_manager,
}
}
pub(crate) async fn environment_add(
&self,
params: EnvironmentAddParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let skills = ScopedSkillsConfig {
required: params
.skills
.and_then(|skills| skills.required)
.unwrap_or_default(),
};
let options = RemoteEnvironmentOptions {
exec_server_url: params.exec_server_url,
connect_timeout: params.connect_timeout_ms.map(Duration::from_millis),
http_headers: params
.auth_bearer_token
.into_iter()
.map(|token| {
(
"Authorization".to_string(),
format!("Bearer {}", token.into_inner()),
)
})
.chain(
params
.websocket_request_id
.map(|request_id| ("X-Request-ID".to_string(), request_id)),
)
.collect(),
};
self.environment_manager
.upsert_environment_with_options(params.environment_id, options, skills)
.map_err(|err| invalid_request(err.to_string()))?;
Ok(Some(EnvironmentAddResponse {}.into()))
}
pub(crate) async fn environment_info(
&self,
params: EnvironmentInfoParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let environment_id = params.environment_id;
let environment = self
.environment_manager
.get_environment(&environment_id)
.ok_or_else(|| invalid_request(format!("unknown environment id `{environment_id}`")))?;
let info = environment.force_info().await.map_err(|err| {
internal_error(format!(
"failed to get info for environment `{environment_id}`: {err}"
))
})?;
Ok(Some(
EnvironmentInfoResponse {
shell: EnvironmentShellInfo {
name: info.shell.name,
path: info.shell.path,
},
cwd: info.cwd,
}
.into(),
))
}
pub(crate) async fn environment_status(
&self,
params: EnvironmentStatusParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let environment_id = params.environment_id;
let (status, error) = match self
.environment_manager
.get_environment_status(&environment_id)
.await
{
Some(EnvironmentObservedStatus::Ready) => (EnvironmentStatusKind::Ready, None),
Some(EnvironmentObservedStatus::Pending) => (EnvironmentStatusKind::Pending, None),
Some(EnvironmentObservedStatus::Disconnected { error }) => {
(EnvironmentStatusKind::Disconnected, Some(error))
}
None => (
EnvironmentStatusKind::Unknown,
Some(format!("unknown environment id `{environment_id}`")),
),
};
Ok(Some(EnvironmentStatusResponse { status, error }.into()))
}
}

View File

@@ -0,0 +1,259 @@
//! Builds a redacted doctor report attachment for feedback uploads.
//!
//! Feedback upload should never depend on doctor succeeding. This module runs
//! the configured Codex executable as a subprocess, accepts only valid JSON from
//! `codex doctor --json --feedback`, derives a small set of Sentry tags, and otherwise
//! skips the attachment with a warning. Keeping the report generation out of the
//! app-server process avoids sharing doctor internals across crates while still
//! using the CLI's JSON report format with bounded database scans.
use std::collections::BTreeMap;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use codex_core::config::Config;
use codex_feedback::DOCTOR_REPORT_ATTACHMENT_FILENAME;
use codex_feedback::FeedbackAttachment;
use serde_json::Value;
use tokio::process::Command;
use tokio::time::timeout;
use tracing::warn;
// Keep the existing 25-second diagnostic allowance plus the filesystem
// probe budget (eight seconds) and a small amount of process overhead.
const DOCTOR_FEEDBACK_REPORT_TIMEOUT: Duration = Duration::from_secs(35);
const MAX_DOCTOR_TAG_VALUE_LEN: usize = 256;
/// Redacted doctor report data that can be merged into a feedback upload.
pub(crate) struct DoctorFeedbackReport {
/// JSON support report to upload as `codex-doctor-report.json`.
pub(crate) attachment: FeedbackAttachment,
/// Low-cardinality Sentry tags derived from the report status and check ids.
pub(crate) tags: BTreeMap<String, String>,
}
/// Runs `codex --cd <workspace> doctor --json --feedback` and returns a best-effort
/// feedback attachment.
///
/// Failure to spawn Codex, finish before the timeout, or parse JSON means the
/// feedback upload proceeds without the doctor report. Callers should merge the
/// returned tags without overriding explicit client-provided tags.
pub(crate) async fn doctor_feedback_report(
config: &Config,
workspace: &Path,
) -> Option<DoctorFeedbackReport> {
let executable = config
.codex_self_exe
.clone()
.or_else(|| std::env::current_exe().ok())?;
let mut command = doctor_command(&executable, workspace, config.codex_home.as_path());
command.stdin(Stdio::null());
command.kill_on_drop(/*kill_on_drop*/ true);
let output = match timeout(DOCTOR_FEEDBACK_REPORT_TIMEOUT, command.output()).await {
Ok(Ok(output)) => output,
Ok(Err(err)) => {
warn!(
executable = %executable.display(),
error = %err,
"failed to run doctor report for feedback; skipping attachment"
);
return None;
}
Err(_) => {
warn!(
executable = %executable.display(),
"timed out running doctor report for feedback; skipping attachment"
);
return None;
}
};
let stdout = String::from_utf8_lossy(&output.stdout);
let Some(json_start) = stdout.find('{') else {
warn!(
executable = %executable.display(),
status = %output.status,
stderr = %String::from_utf8_lossy(&output.stderr),
"doctor report for feedback did not produce JSON; skipping attachment"
);
return None;
};
let json = stdout[json_start..].trim();
let report: Value = match serde_json::from_str(json) {
Ok(report) => report,
Err(err) => {
warn!(
executable = %executable.display(),
status = %output.status,
error = %err,
"doctor report for feedback was not valid JSON; skipping attachment"
);
return None;
}
};
let pretty = serde_json::to_vec_pretty(&report).unwrap_or_else(|_| json.as_bytes().to_vec());
Some(DoctorFeedbackReport {
tags: doctor_report_tags(&report),
attachment: FeedbackAttachment {
filename: DOCTOR_REPORT_ATTACHMENT_FILENAME.to_string(),
content_type: Some("application/json".to_string()),
buffer: pretty,
},
})
}
fn doctor_command(executable: &Path, cwd: &Path, codex_home: &Path) -> Command {
let mut command = Command::from(codex_utils_process::background_command(executable));
command
.arg("--cd")
.arg(cwd)
.arg("doctor")
.arg("--json")
.arg("--feedback")
.current_dir(codex_home)
.env("CODEX_HOME", codex_home);
command
}
fn doctor_report_tags(report: &Value) -> BTreeMap<String, String> {
let mut tags = BTreeMap::new();
if let Some(overall_status) = report.get("overallStatus").and_then(Value::as_str) {
tags.insert(
"doctor_overall_status".to_string(),
truncate_tag_value(overall_status),
);
}
let mut ok_count = 0usize;
let mut warning_count = 0usize;
let mut fail_count = 0usize;
let mut failed_checks = Vec::new();
let mut warning_checks = Vec::new();
if let Some(checks) = report.get("checks") {
for check in check_values(checks) {
let status = check.get("status").and_then(Value::as_str);
let id = check.get("id").and_then(Value::as_str).unwrap_or("unknown");
match status {
Some("ok") => ok_count += 1,
Some("warning") => {
warning_count += 1;
warning_checks.push(id.to_string());
}
Some("fail") => {
fail_count += 1;
failed_checks.push(id.to_string());
}
_ => {}
}
}
}
tags.insert("doctor_ok_count".to_string(), ok_count.to_string());
tags.insert(
"doctor_warning_count".to_string(),
warning_count.to_string(),
);
tags.insert("doctor_fail_count".to_string(), fail_count.to_string());
if !failed_checks.is_empty() {
tags.insert(
"doctor_failed_checks".to_string(),
truncate_tag_value(&failed_checks.join(",")),
);
}
if !warning_checks.is_empty() {
tags.insert(
"doctor_warning_checks".to_string(),
truncate_tag_value(&warning_checks.join(",")),
);
}
tags
}
/// Iterates checks from both the current keyed JSON shape and older array reports.
fn check_values(checks: &Value) -> Box<dyn Iterator<Item = &Value> + '_> {
match checks {
Value::Array(values) => Box::new(values.iter()),
Value::Object(values) => Box::new(values.values()),
_ => Box::new(std::iter::empty()),
}
}
fn truncate_tag_value(value: &str) -> String {
if value.chars().count() <= MAX_DOCTOR_TAG_VALUE_LEN {
return value.to_string();
}
let prefix = value
.chars()
.take(MAX_DOCTOR_TAG_VALUE_LEN.saturating_sub(3))
.collect::<String>();
format!("{prefix}...")
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::tempdir;
#[test]
fn doctor_command_keeps_missing_workspace_out_of_process_cwd() {
let codex_home = tempdir().expect("codex home");
let workspace = codex_home.path().join("deleted-workspace");
let command = doctor_command(Path::new("codex"), &workspace, codex_home.path());
let command = command.as_std();
assert_eq!(command.get_current_dir(), Some(codex_home.path()));
assert_eq!(
command.get_args().collect::<Vec<_>>(),
[
"--cd".as_ref(),
workspace.as_os_str(),
"doctor".as_ref(),
"--json".as_ref(),
"--feedback".as_ref()
]
);
assert_eq!(
command.get_envs().collect::<Vec<_>>(),
[("CODEX_HOME".as_ref(), Some(codex_home.path().as_os_str()))]
);
}
#[test]
fn doctor_report_tags_summarize_status_counts() {
let report = json!({
"overallStatus": "fail",
"checks": {
"runtime.provenance": {"id": "runtime.provenance", "status": "ok"},
"websocket.reachability": {
"id": "websocket.reachability",
"status": "warning"
},
"auth.credentials": {"id": "auth.credentials", "status": "fail"}
}
});
let tags = doctor_report_tags(&report);
let expected = BTreeMap::from([
("doctor_fail_count".to_string(), "1".to_string()),
(
"doctor_failed_checks".to_string(),
"auth.credentials".to_string(),
),
("doctor_ok_count".to_string(), "1".to_string()),
("doctor_overall_status".to_string(), "fail".to_string()),
(
"doctor_warning_checks".to_string(),
"websocket.reachability".to_string(),
),
("doctor_warning_count".to_string(), "1".to_string()),
]);
assert_eq!(tags, expected);
}
}

View File

@@ -0,0 +1,187 @@
//! Exercises SQLite log collection, legacy storage, and feedback snapshot ordering.
use super::*;
use codex_core::config::ConfigBuilder;
use codex_state::SqliteConfig;
use codex_state::StateRuntime;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use tracing_subscriber::prelude::*;
#[derive(PartialEq)]
enum Scenario {
Healthy,
WriteFailure,
Corruption,
}
#[tokio::test]
async fn feedback_includes_flush_and_query_failures_in_the_same_submission() -> anyhow::Result<()> {
for scenario in [
Scenario::Healthy,
Scenario::WriteFailure,
Scenario::Corruption,
] {
let home = tempfile::tempdir()?;
let config = core_test_support::load_default_config_for_test(&home).await;
let sqlite = &config.sqlite;
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
let pool = sqlite.open_read_write_pool(&sqlite.logs_db_path()).await?;
let feedback = CodexFeedback::new();
let writer =
codex_state::log_db::start(runtime.clone(), std::sync::Arc::new(feedback.clone()));
let _guard = tracing_subscriber::registry()
.with(feedback.logger_layer())
.with(writer.clone())
.set_default();
let thread_id = ThreadId::new();
tracing::info_span!("thread", thread_id = %thread_id)
.in_scope(|| tracing::info!("persisted log"));
writer.flush().await;
match scenario {
Scenario::WriteFailure => {
sqlx::query("CREATE TRIGGER fail_log_insert BEFORE INSERT ON logs BEGIN SELECT RAISE(ABORT, 'synthetic-secret'); END").execute(&pool).await?;
}
Scenario::Corruption => {
sqlx::raw_sql("PRAGMA writable_schema = ON; UPDATE sqlite_schema SET rootpage = 2147483647 WHERE name = 'logs'; PRAGMA schema_version = 1000000;").execute(&pool).await?;
}
Scenario::Healthy => {}
}
let snapshot = feedback.snapshot(Some(thread_id));
tracing::info_span!("thread", thread_id = %thread_id)
.in_scope(|| tracing::info!("latest log"));
let (snapshot, sqlite_logs, legacy_logs) = collect_feedback_logs(
&feedback,
Some(&writer),
Some(&runtime),
&config,
snapshot,
&[thread_id],
)
.await;
assert_eq!(legacy_logs, None);
assert_eq!(sqlite_logs.is_some(), scenario == Scenario::Healthy);
let logs = String::from_utf8(snapshot.log_attachment(sqlite_logs).buffer)?;
assert!(logs.contains("persisted log"));
assert!(logs.contains("latest log"));
let expected_error = match scenario {
Scenario::Healthy => None,
Scenario::WriteFailure => Some("constraint"),
Scenario::Corruption => Some("corrupt"),
};
assert_eq!(
logs.matches("failed to flush logs to SQLite").count(),
usize::from(expected_error.is_some())
);
if let Some(error) = expected_error {
assert!(logs.contains(&format!("failed to flush logs to SQLite error={error:?}")));
}
assert_eq!(
logs.contains("failed to query feedback logs from sqlite"),
scenario == Scenario::Corruption
);
pool.close().await;
runtime.close().await;
}
Ok(())
}
#[tokio::test]
async fn feedback_preserves_legacy_logs_when_the_directory_is_unset_or_current_logs_are_empty()
-> anyhow::Result<()> {
for configured_log_dir in [false, true] {
let home = tempfile::tempdir()?;
let sqlite_home = home.path().join("sqlite");
let mut overrides = vec![(
"sqlite_home".to_string(),
toml::Value::String(sqlite_home.to_string_lossy().into_owned()),
)];
if configured_log_dir {
overrides.push((
"log_dir".to_string(),
toml::Value::String(home.path().join("log").to_string_lossy().into_owned()),
));
}
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.loader_overrides(codex_config::LoaderOverrides::without_managed_config_for_tests())
.cli_overrides(overrides)
.build()
.await?;
let legacy_sqlite = SqliteConfig::new_for_testing(sqlite_home.abs());
let legacy = StateRuntime::init(legacy_sqlite.clone(), "test-provider".to_string()).await?;
let pool = legacy_sqlite
.open_read_write_pool(&legacy_sqlite.logs_db_path())
.await?;
let thread_id = ThreadId::new();
let now = chrono::Utc::now();
let timestamp = now.format("%Y-%m-%dT%H:%M:%S.000000Z");
for (id, body) in [
(thread_id, "legacy history"),
(ThreadId::new(), "unrelated history"),
] {
sqlx::query(
"INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body, thread_id)
VALUES (?, 0, 'INFO', 'test', ?, ?)",
)
.bind(now.timestamp())
.bind(body)
.bind(id.to_string())
.execute(&pool)
.await?;
}
pool.close().await;
legacy.close().await;
let legacy_before = std::fs::read(legacy_sqlite.logs_db_path())?;
let runtime =
StateRuntime::init(config.sqlite.clone(), "test-provider".to_string()).await?;
let pool = config
.sqlite
.open_read_write_pool(&config.sqlite.logs_db_path())
.await?;
let feedback = CodexFeedback::new();
for current_has_logs in [false, true] {
if current_has_logs {
sqlx::query(
"INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body, thread_id)
VALUES (?, 0, 'INFO', 'test', 'current history', ?)",
)
.bind(now.timestamp())
.bind(thread_id.to_string())
.execute(&pool)
.await?;
}
let (_, current_logs, legacy_logs) = collect_feedback_logs(
&feedback,
/*log_db*/ None,
Some(&runtime),
&config,
feedback.snapshot(Some(thread_id)),
&[thread_id],
)
.await;
let mut expected_current = String::new();
if !configured_log_dir {
expected_current.push_str(&format!("{timestamp} INFO legacy history\n"));
}
if current_has_logs {
expected_current.push_str(&format!("{timestamp} INFO current history\n"));
}
assert_eq!(
current_logs,
(!expected_current.is_empty()).then(|| expected_current.into_bytes())
);
assert_eq!(
legacy_logs,
(configured_log_dir && !current_has_logs)
.then(|| format!("{timestamp} INFO legacy history\n").into_bytes())
);
}
if configured_log_dir {
assert_eq!(std::fs::read(legacy_sqlite.logs_db_path())?, legacy_before);
}
pool.close().await;
runtime.close().await;
}
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,136 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use codex_feedback::FeedbackAttachment;
use codex_feedback::FeedbackAttachmentPath;
use codex_feedback::MAX_ATTACHMENT_BYTES;
use codex_feedback::MAX_ATTACHMENTS_BYTES;
use codex_rollout::find_rollout_path_by_rollout_id;
use codex_rollout::read_session_meta_line;
use codex_rollout::rollout_id_from_path;
const MAX_HISTORY_ROLLOUTS: usize = 64;
const HISTORY_LOOKUP_TIMEOUT: Duration = Duration::from_secs(5);
pub(super) async fn history_base_attachments(
codex_home: &Path,
attachments: &[FeedbackAttachmentPath],
) -> Vec<FeedbackAttachment> {
let selected = attachments
.iter()
.filter_map(|attachment| rollout_id_from_path(&attachment.path))
.collect::<HashSet<_>>();
let mut pending = attachments
.iter()
.filter(|attachment| rollout_id_from_path(&attachment.path).is_some())
.map(|attachment| attachment.path.clone())
.collect::<Vec<_>>();
let mut positions = HashMap::new();
let mut ancestors: Vec<(PathBuf, usize)> = Vec::new();
// Preserve discovered prefixes if the bounded filesystem walk times out.
let discovery = async {
let mut next = 0;
while next < pending.len() {
let path = &pending[next];
next += 1;
let meta = match read_session_meta_line(path).await {
Ok(meta) => meta,
Err(err) => {
tracing::error!(
?err,
"failed to read feedback history metadata at {}",
path.display()
);
continue;
}
};
let Some(base) = meta.meta.history_base else {
continue;
};
if selected.contains(&base.thread_id) {
continue;
}
let Ok(end_byte_offset) = usize::try_from(base.end_byte_offset) else {
continue;
};
if end_byte_offset > MAX_ATTACHMENT_BYTES {
continue;
}
if let Some(&index) = positions.get(&base.thread_id) {
let (_, previous_end_byte_offset): &mut (PathBuf, usize) = &mut ancestors[index];
*previous_end_byte_offset = (*previous_end_byte_offset).max(end_byte_offset);
continue;
}
if positions.len() == MAX_HISTORY_ROLLOUTS {
tracing::error!("feedback history rollout limit reached");
break;
}
// The wire field names an immutable rollout, not the owner's current thread.
let path = match find_rollout_path_by_rollout_id(codex_home, base.thread_id).await {
Ok(Some(path)) => path,
Ok(None) => continue,
Err(err) => {
tracing::error!(
?err,
"failed to locate feedback history rollout {}",
base.thread_id
);
continue;
}
};
positions.insert(base.thread_id, ancestors.len());
pending.push(path.clone());
ancestors.push((path, end_byte_offset));
}
};
if tokio::time::timeout(HISTORY_LOOKUP_TIMEOUT, discovery)
.await
.is_err()
{
tracing::error!("feedback history lookup timed out");
}
// Freeze exactly the inherited bytes before upload. Unreadable or oversized
// ancestors are best effort and cannot turn an accepted report into an error.
tokio::task::spawn_blocking(move || {
let mut remaining = MAX_ATTACHMENTS_BYTES;
let mut result = Vec::new();
for (path, end_byte_offset) in ancestors {
if end_byte_offset > remaining {
continue;
}
let plain_path = codex_rollout::plain_rollout_path(&path);
let Some(filename) = plain_path.file_name() else {
continue;
};
match codex_rollout::read_rollout_prefix(&path, end_byte_offset) {
Ok(Some(buffer)) if buffer.len() == end_byte_offset => {
remaining -= buffer.len();
result.push(FeedbackAttachment {
buffer,
filename: filename.to_string_lossy().into_owned(),
content_type: Some("application/jsonl".to_string()),
});
}
Ok(_) => tracing::error!(
"couldn't attach history: incomplete feedback history prefix at {}",
path.display()
),
Err(err) => tracing::error!(
?err,
"couldn't read feedback history prefix at {}",
path.display()
),
}
}
result
})
.await
.unwrap_or_default() // Keep uploading the selected rollouts if this task fails.
}
#[cfg(test)]
#[path = "feedback_rollout_history_tests.rs"]
mod tests;

View File

@@ -0,0 +1,70 @@
use super::*;
use codex_protocol::ThreadId;
use codex_protocol::protocol::HistoryPosition;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
#[tokio::test]
async fn includes_nested_history_bases() -> anyhow::Result<()> {
let home = TempDir::new()?;
let directory = home.path().join("sessions");
std::fs::create_dir_all(&directory)?;
let (grandparent, grandparent_end) = write_rollout(&directory, /*base*/ None)?;
let (parent, parent_end) = write_rollout(&directory, Some(grandparent_end))?;
let (rollout, _) = write_rollout(&directory, Some(parent_end))?;
let attachments = history_base_attachments(
home.path(),
&[FeedbackAttachmentPath {
path: rollout,
attachment_filename_override: None,
}],
)
.await;
let expected = [parent, grandparent]
.into_iter()
.map(|path| {
Ok((
path.file_name().unwrap().to_string_lossy().into_owned(),
std::fs::read(path)?,
))
})
.collect::<anyhow::Result<Vec<_>>>()?;
assert_eq!(
attachments
.into_iter()
.map(|attachment| (attachment.filename, attachment.buffer))
.collect::<Vec<_>>(),
expected
);
Ok(())
}
fn write_rollout(
directory: &Path,
base: Option<HistoryPosition>,
) -> anyhow::Result<(PathBuf, HistoryPosition)> {
let id = ThreadId::new();
let ordinal = base.map_or(0, |base| base.end_ordinal_exclusive);
let path = directory.join(format!("rollout-2026-09-22T12-00-00-{id}.jsonl"));
let meta = json!({
"ordinal": ordinal,
"timestamp": "2026-09-22T12:00:00Z", "type": "session_meta",
"payload": {
"id": id, "timestamp": "2026-09-22T12:00:00Z", "cwd": directory,
"originator": "test", "cli_version": "test", "history_mode": "paginated", "history_base": base,
},
});
let contents = format!("{meta}\n");
std::fs::write(&path, &contents)?;
Ok((
path,
HistoryPosition {
thread_id: id,
end_ordinal_exclusive: ordinal + 1,
end_byte_offset: contents.len() as u64,
},
))
}

View File

@@ -0,0 +1,93 @@
//! Selects a bounded set of spawned descendants and directly attached threads for feedback,
//! preserving the reported thread and prioritizing children with retained failed reviews.
//! Filenames identify selected archive entries or fallback attachments. Delivery is best effort.
use codex_feedback::FeedbackAttachment;
use codex_feedback::GuardianReviewFailures;
use codex_protocol::ThreadId;
use serde::Serialize;
use std::cmp::Reverse;
use std::collections::HashSet;
const MAX_FEEDBACK_TREE_THREADS: usize = 8;
const MAX_LISTED_OMISSIONS: usize = 64;
#[derive(Serialize)]
pub(super) struct FeedbackThreadIndex {
pub(super) rollout_archive_filename: Option<&'static str>,
pub threads: Vec<FeedbackThread>,
retained_failure_thread_ids: Vec<ThreadId>,
omitted_thread_ids: Vec<ThreadId>,
unlisted_omitted_thread_count: usize,
process_discarded_review_records: usize,
notes: &'static str,
}
#[derive(Serialize)]
pub(super) struct FeedbackThread {
pub thread_id: ThreadId,
pub rollout_filename: Option<String>,
pub guardian_rollout_filename: Option<String>,
}
impl FeedbackThreadIndex {
pub fn new(
reported_thread_id: ThreadId,
mut subtree: Vec<ThreadId>,
failures: &GuardianReviewFailures,
) -> Self {
// UUIDv7 ordering provides a deterministic newest-child fallback.
subtree.sort_unstable_by_key(|id| Reverse(id.to_string()));
subtree.dedup();
subtree.retain(|id| *id != reported_thread_id);
let descendants = subtree.iter().copied().collect::<HashSet<_>>();
let mut selected = HashSet::from([reported_thread_id]);
let mut thread_ids = vec![reported_thread_id];
for id in failures.thread_ids.iter().chain(&subtree) {
if thread_ids.len() == MAX_FEEDBACK_TREE_THREADS {
break;
}
if descendants.contains(id) && selected.insert(*id) {
thread_ids.push(*id);
}
}
let omitted_count = subtree.len().saturating_sub(thread_ids.len() - 1);
let omitted_thread_ids = subtree
.into_iter()
.filter(|id| !selected.contains(id))
.take(MAX_LISTED_OMISSIONS)
.collect::<Vec<_>>();
Self {
rollout_archive_filename: Some("rollouts.tar.gz"),
threads: thread_ids
.into_iter()
.map(|thread_id| FeedbackThread {
thread_id,
rollout_filename: None,
guardian_rollout_filename: None,
})
.collect(),
retained_failure_thread_ids: failures.thread_ids.clone(),
unlisted_omitted_thread_count: omitted_count - omitted_thread_ids.len(),
omitted_thread_ids,
process_discarded_review_records: failures.process_discarded_records,
notes: "Selection only, not an upload receipt. Null filenames mean no path was available. \
Omitted threads exceeded the rollout thread limit; their retained reviews are \
still in auto-review-failures.jsonl. Review evidence is persisted and bounded; \
missing evidence does not imply no denial. The discarded-record count covers \
only the process-wide in-memory fallback and resets on restart.",
}
}
pub fn attachment(&self) -> serde_json::Result<FeedbackAttachment> {
Ok(FeedbackAttachment {
filename: "feedback-thread-index.json".to_string(),
buffer: serde_json::to_vec(self)?,
content_type: Some("application/json".to_string()),
})
}
}
#[cfg(test)]
#[path = "feedback_thread_index_tests.rs"]
mod tests;

View File

@@ -0,0 +1,81 @@
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
fn thread_ids(count: usize) -> Vec<ThreadId> {
(0..count)
.map(|index| {
ThreadId::from_string(&format!("00000000-0000-7000-8000-{index:012x}"))
.expect("thread id")
})
.collect()
}
#[test]
fn old_failed_child_precedes_new_children_and_index_explains_selection() -> anyhow::Result<()> {
let ids = thread_ids(/*count*/ 12);
let failures = GuardianReviewFailures {
attachment: None,
thread_ids: vec![ids[1], ids[0]],
process_discarded_records: 3,
};
let mut index = FeedbackThreadIndex::new(ids[0], ids.clone(), &failures);
index.threads[0].rollout_filename = Some("parent.jsonl".to_string());
index.threads[1].rollout_filename = Some("child.jsonl".to_string());
index.threads[1].guardian_rollout_filename = Some("child-reviewer.jsonl".to_string());
let attachment = index.attachment()?;
let selected = [0, 1, 11, 10, 9, 8, 7, 6];
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&attachment.buffer)?,
json!({
"rollout_archive_filename": "rollouts.tar.gz",
"threads": selected.into_iter().map(|i| json!({
"thread_id": ids[i],
"rollout_filename": match i {
0 => Some("parent.jsonl"),
1 => Some("child.jsonl"),
_ => None,
},
"guardian_rollout_filename": (i == 1).then_some("child-reviewer.jsonl"),
})).collect::<Vec<_>>(),
"retained_failure_thread_ids": [ids[1], ids[0]],
"omitted_thread_ids": [ids[5], ids[4], ids[3], ids[2]],
"unlisted_omitted_thread_count": 0,
"process_discarded_review_records": 3,
"notes": index.notes,
})
);
Ok(())
}
#[test]
fn failure_priority_keeps_the_reported_thread_and_bounds_omission_details() {
let ids = thread_ids(/*count*/ 100);
let failures = GuardianReviewFailures {
attachment: None,
thread_ids: ids[1..10].to_vec(),
process_discarded_records: 0,
};
// Exercise unsorted and duplicate subtree entries without inflating omission counts.
let mut subtree = ids.iter().rev().copied().collect::<Vec<_>>();
subtree.extend_from_slice(&ids[..3]);
let index = FeedbackThreadIndex::new(ids[0], subtree, &failures);
assert_eq!(
(
index
.threads
.iter()
.map(|thread| thread.thread_id)
.collect::<Vec<_>>(),
index.omitted_thread_ids,
index.unlisted_omitted_thread_count,
index.retained_failure_thread_ids,
),
(
ids[..8].to_vec(),
ids[36..].iter().rev().copied().collect::<Vec<_>>(),
28,
failures.thread_ids,
)
);
}

View File

@@ -0,0 +1,221 @@
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use crate::fs_watch::FsWatchManager;
use crate::outgoing_message::ConnectionId;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use codex_app_server_protocol::FsCopyParams;
use codex_app_server_protocol::FsCopyResponse;
use codex_app_server_protocol::FsCreateDirectoryParams;
use codex_app_server_protocol::FsCreateDirectoryResponse;
use codex_app_server_protocol::FsGetMetadataParams;
use codex_app_server_protocol::FsGetMetadataResponse;
use codex_app_server_protocol::FsReadDirectoryEntry;
use codex_app_server_protocol::FsReadDirectoryParams;
use codex_app_server_protocol::FsReadDirectoryResponse;
use codex_app_server_protocol::FsReadFileParams;
use codex_app_server_protocol::FsReadFileResponse;
use codex_app_server_protocol::FsRemoveParams;
use codex_app_server_protocol::FsRemoveResponse;
use codex_app_server_protocol::FsUnwatchParams;
use codex_app_server_protocol::FsUnwatchResponse;
use codex_app_server_protocol::FsWatchParams;
use codex_app_server_protocol::FsWatchResponse;
use codex_app_server_protocol::FsWriteFileParams;
use codex_app_server_protocol::FsWriteFileResponse;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_exec_server::CopyOptions;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::RemoveOptions;
use codex_utils_path_uri::PathUri;
use std::io;
use std::sync::Arc;
#[derive(Clone)]
pub(crate) struct FsRequestProcessor {
environment_manager: Arc<EnvironmentManager>,
fs_watch_manager: FsWatchManager,
}
impl FsRequestProcessor {
pub(crate) fn new(
environment_manager: Arc<EnvironmentManager>,
fs_watch_manager: FsWatchManager,
) -> Self {
Self {
environment_manager,
fs_watch_manager,
}
}
fn file_system(&self) -> Result<Arc<dyn ExecutorFileSystem>, JSONRPCErrorError> {
self.environment_manager
.try_local_environment()
.map(|environment| environment.get_filesystem())
.ok_or_else(|| internal_error("local filesystem is not configured"))
}
pub(crate) async fn connection_closed(&self, connection_id: ConnectionId) {
self.fs_watch_manager.connection_closed(connection_id).await;
}
pub(crate) async fn read_file(
&self,
params: FsReadFileParams,
) -> Result<FsReadFileResponse, JSONRPCErrorError> {
let path = PathUri::from_abs_path(&params.path);
let bytes = self
.file_system()?
.read_file(&path, Default::default(), /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
Ok(FsReadFileResponse {
data_base64: STANDARD.encode(bytes),
})
}
pub(crate) async fn write_file(
&self,
params: FsWriteFileParams,
) -> Result<FsWriteFileResponse, JSONRPCErrorError> {
let bytes = STANDARD.decode(params.data_base64).map_err(|err| {
invalid_request(format!(
"fs/writeFile requires valid base64 dataBase64: {err}"
))
})?;
let path = PathUri::from_abs_path(&params.path);
self.file_system()?
.write_file(&path, bytes, Default::default(), /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
Ok(FsWriteFileResponse {})
}
pub(crate) async fn create_directory(
&self,
params: FsCreateDirectoryParams,
) -> Result<FsCreateDirectoryResponse, JSONRPCErrorError> {
let path = PathUri::from_abs_path(&params.path);
self.file_system()?
.create_directory(
&path,
CreateDirectoryOptions {
recursive: params.recursive.unwrap_or(true),
follow_symlinks: true,
},
/*sandbox*/ None,
)
.await
.map_err(map_fs_error)?;
Ok(FsCreateDirectoryResponse {})
}
pub(crate) async fn get_metadata(
&self,
params: FsGetMetadataParams,
) -> Result<FsGetMetadataResponse, JSONRPCErrorError> {
let path = PathUri::from_abs_path(&params.path);
let metadata = self
.file_system()?
.get_metadata(&path, Default::default(), /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
Ok(FsGetMetadataResponse {
is_directory: metadata.is_directory,
is_file: metadata.is_file,
is_symlink: metadata.is_symlink,
created_at_ms: metadata.created_at_ms,
modified_at_ms: metadata.modified_at_ms,
})
}
pub(crate) async fn read_directory(
&self,
params: FsReadDirectoryParams,
) -> Result<FsReadDirectoryResponse, JSONRPCErrorError> {
let path = PathUri::from_abs_path(&params.path);
let entries = self
.file_system()?
.read_directory(&path, /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
Ok(FsReadDirectoryResponse {
entries: entries
.into_iter()
.map(|entry| FsReadDirectoryEntry {
file_name: entry.file_name,
is_directory: entry.is_directory,
is_file: entry.is_file,
})
.collect(),
})
}
pub(crate) async fn remove(
&self,
params: FsRemoveParams,
) -> Result<FsRemoveResponse, JSONRPCErrorError> {
let path = PathUri::from_abs_path(&params.path);
self.file_system()?
.remove(
&path,
RemoveOptions {
recursive: params.recursive.unwrap_or(true),
force: params.force.unwrap_or(true),
follow_symlinks: true,
},
/*sandbox*/ None,
)
.await
.map_err(map_fs_error)?;
Ok(FsRemoveResponse {})
}
pub(crate) async fn copy(
&self,
params: FsCopyParams,
) -> Result<FsCopyResponse, JSONRPCErrorError> {
let source_path = PathUri::from_abs_path(&params.source_path);
let destination_path = PathUri::from_abs_path(&params.destination_path);
self.file_system()?
.copy(
&source_path,
&destination_path,
CopyOptions {
recursive: params.recursive,
},
/*sandbox*/ None,
)
.await
.map_err(map_fs_error)?;
Ok(FsCopyResponse {})
}
pub(crate) async fn watch(
&self,
connection_id: ConnectionId,
params: FsWatchParams,
) -> Result<FsWatchResponse, JSONRPCErrorError> {
self.file_system()?;
self.fs_watch_manager.watch(connection_id, params).await
}
pub(crate) async fn unwatch(
&self,
connection_id: ConnectionId,
params: FsUnwatchParams,
) -> Result<FsUnwatchResponse, JSONRPCErrorError> {
self.file_system()?;
self.fs_watch_manager.unwatch(connection_id, params).await
}
}
fn map_fs_error(err: io::Error) -> JSONRPCErrorError {
if err.kind() == io::ErrorKind::InvalidInput {
invalid_request(err.to_string())
} else {
internal_error(err.to_string())
}
}

View File

@@ -0,0 +1,36 @@
use super::*;
#[derive(Clone)]
pub(crate) struct GitRequestProcessor;
impl GitRequestProcessor {
pub(crate) fn new() -> Self {
Self
}
pub(crate) async fn git_diff_to_remote(
&self,
params: GitDiffToRemoteParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.git_diff_to_origin(params.cwd)
.await
.map(|response| Some(response.into()))
}
async fn git_diff_to_origin(
&self,
cwd: PathBuf,
) -> Result<GitDiffToRemoteResponse, JSONRPCErrorError> {
git_diff_to_remote(&cwd)
.await
.map(|value| GitDiffToRemoteResponse {
sha: value.sha,
diff: value.diff,
})
.ok_or_else(|| {
invalid_request(format!(
"failed to compute git diff to remote for cwd: {cwd:?}"
))
})
}
}

View File

@@ -0,0 +1,243 @@
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use axum::http::HeaderValue;
use codex_analytics::AppServerRpcTransport;
use codex_login::default_client::SetOriginatorError;
use codex_login::default_client::USER_AGENT_SUFFIX;
use codex_login::default_client::get_codex_user_agent;
use codex_login::default_client::set_default_client_residency_requirement;
use codex_login::default_client::set_default_originator;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::mcp::OPENAI_ELICITATION_EXTENSION_ID;
use super::*;
use crate::message_processor::ConnectionSessionState;
use crate::message_processor::InitializedConnectionSessionState;
use crate::transport::ConnectionOrigin;
const NON_ORIGINATING_CLIENT_NAMES: &[&str] = &["codex_app_server_daemon", "codex-backend"];
#[derive(Clone)]
pub(crate) struct InitializeRequestProcessor {
gateway_login_control: Arc<codex_login::GatewayLoginControl>,
gateway_login_initialized: Arc<std::sync::OnceLock<()>>,
outgoing: Arc<OutgoingMessageSender>,
analytics_events_client: AnalyticsEventsClient,
config: Arc<Config>,
rpc_transport: AppServerRpcTransport,
user_verification: Arc<crate::user_verification::Service>,
}
impl InitializeRequestProcessor {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
gateway_login_control: Arc<codex_login::GatewayLoginControl>,
outgoing: Arc<OutgoingMessageSender>,
analytics_events_client: AnalyticsEventsClient,
config: Arc<Config>,
rpc_transport: AppServerRpcTransport,
user_verification: Arc<crate::user_verification::Service>,
) -> Self {
Self {
gateway_login_control,
gateway_login_initialized: Arc::new(std::sync::OnceLock::new()),
outgoing,
analytics_events_client,
config,
rpc_transport,
user_verification,
}
}
pub(crate) async fn initialize(
&self,
connection_id: ConnectionId,
request_id: RequestId,
params: InitializeParams,
session: &ConnectionSessionState,
// `Some(...)` means the caller wants initialize to immediately mark the
// connection outbound-ready. Websocket JSON-RPC calls pass `None` so
// lib.rs can deliver connection-scoped initialize notifications first.
outbound_initialized: Option<&AtomicBool>,
) -> Result<bool, JSONRPCErrorError> {
let connection_request_id = ConnectionRequestId {
connection_id,
request_id,
};
if session.initialized() {
return Err(invalid_request("Already initialized"));
}
// TODO(maxj): Revisit capability scoping for `experimental_api_enabled`.
// Current behavior is per-connection. Reviewer feedback notes this can
// create odd cross-client behavior (for example dynamic tool calls on a
// shared thread when another connected client did not opt into
// experimental API). Proposed direction is instance-global first-write-wins
// with initialize-time mismatch rejection.
let analytics_initialize_params = params.clone();
let capabilities = params.capabilities.unwrap_or_default();
let experimental_api_enabled = capabilities.experimental_api;
let request_attestation = capabilities.request_attestation;
let extensions = capabilities.extensions.as_ref();
let mut client_mcp_extensions = codex_mcp::client_mcp_extensions(
extensions,
capabilities.mcp_server_openai_form_elicitation,
);
let opt_out_notification_methods = capabilities
.opt_out_notification_methods
.unwrap_or_default();
let ClientInfo {
name,
title: _title,
version,
} = params.client_info;
// Validate before committing; set_default_originator validates while
// mutating process-global metadata.
if HeaderValue::from_str(&name).is_err() {
return Err(invalid_request(format!(
"Invalid clientInfo.name: '{name}'. Must be a valid HTTP header value."
)));
}
// Activate only the embedded TUI and local desktop host. Client-supplied
// extensions cannot opt other hosts into verification.
let user_verification_enabled = experimental_api_enabled
&& matches!(
(session.origin, name.as_str()),
(ConnectionOrigin::InProcess, "codex-tui")
| (ConnectionOrigin::Stdio, "Codex Desktop")
)
&& tokio::task::spawn_blocking(self.user_verification.device_supported)
.await
.unwrap_or(false);
if user_verification_enabled {
let mut extensions = client_mcp_extensions
.iter()
.map(|(id, value)| (id.to_string(), value.clone()))
.collect::<std::collections::HashMap<_, _>>();
let settings = extensions
.entry(OPENAI_ELICITATION_EXTENSION_ID.to_string())
.or_insert_with(|| serde_json::json!({}));
if !settings.is_object() {
*settings = serde_json::json!({});
}
settings["userVerification"] = serde_json::json!({});
client_mcp_extensions = ClientMcpExtensions::new(extensions);
}
let originator = name.clone();
let user_agent_suffix = format!("{name}; {version}");
let mutates_global_identity = !NON_ORIGINATING_CLIENT_NAMES.contains(&name.as_str());
let codex_home = self.config.codex_home.clone();
if session
.initialize(InitializedConnectionSessionState {
experimental_api_enabled,
opted_out_notification_methods: opt_out_notification_methods.into_iter().collect(),
app_server_client_name: name.clone(),
client_version: version,
request_attestation,
client_mcp_extensions,
})
.is_err()
{
return Err(invalid_request("Already initialized"));
}
if experimental_api_enabled && capabilities.required_human_approval {
self.outgoing
.enable_human_approval_connection(connection_id)
.await;
}
if user_verification_enabled {
self.outgoing
.enable_user_verification_connection(connection_id)
.await;
}
if capabilities.explicit_gateway_oauth || mutates_global_identity {
// Only the first originating client may restore legacy automatic login.
// Any explicit opt-in is sticky across subsequent connections.
self.gateway_login_initialized.get_or_init(|| {
if !capabilities.explicit_gateway_oauth {
self.gateway_login_control.allow_automatic_login();
}
});
if capabilities.explicit_gateway_oauth {
self.gateway_login_control.require_explicit_login();
}
}
if mutates_global_identity {
// Only real client initialization may mutate process-global client metadata.
if let Err(error) = set_default_originator(originator.clone()) {
match error {
SetOriginatorError::InvalidHeaderValue => {
tracing::warn!(
client_info_name = %name,
"validated clientInfo.name was rejected while setting originator"
);
}
SetOriginatorError::AlreadyInitialized => {
// No-op. This is expected to happen if the originator is already set via env var.
// TODO(owen): Once we remove support for CODEX_INTERNAL_ORIGINATOR_OVERRIDE,
// this will be an unexpected state and we can return a JSON-RPC error indicating
// internal server error.
}
}
}
}
self.analytics_events_client.track_initialize(
connection_id.0,
analytics_initialize_params,
originator,
self.rpc_transport,
);
set_default_client_residency_requirement(self.config.enforce_residency.value());
if mutates_global_identity && let Ok(mut suffix) = USER_AGENT_SUFFIX.lock() {
*suffix = Some(user_agent_suffix);
}
#[cfg(windows)]
if matches!(session.origin, ConnectionOrigin::Stdio) && name == "Codex Desktop" {
// Uninstall ownership must not depend on account sign-in or sandbox setup.
// Keep this bounded attempt ahead of the response; background registration can race uninstall.
let home = codex_home.clone();
if !matches!(
tokio::task::spawn_blocking(move || {
codex_windows_sandbox::register_desktop_installation(&home)
})
.await,
Ok(Ok(()))
) {
tracing::warn!("could not register desktop uninstall ownership");
}
}
let user_agent = get_codex_user_agent();
let response = InitializeResponse {
user_agent,
codex_home,
platform_family: std::env::consts::FAMILY.to_string(),
platform_os: std::env::consts::OS.to_string(),
};
self.outgoing
.send_response(connection_request_id, response)
.await;
if let Some(outbound_initialized) = outbound_initialized {
outbound_initialized.store(true, Ordering::Release);
return Ok(true);
}
Ok(false)
}
pub(crate) fn track_initialized_request(
&self,
connection_id: ConnectionId,
request_id: RequestId,
request: &ClientRequest,
) {
self.analytics_events_client
.track_request(connection_id.0, request_id, request);
}
}

View File

@@ -0,0 +1,142 @@
use super::*;
use crate::plugin_config_reload;
#[derive(Clone)]
pub(crate) struct MarketplaceRequestProcessor {
config_manager: ConfigManager,
thread_manager: Arc<ThreadManager>,
}
impl MarketplaceRequestProcessor {
pub(crate) fn new(config_manager: ConfigManager, thread_manager: Arc<ThreadManager>) -> Self {
Self {
config_manager,
thread_manager,
}
}
pub(crate) async fn marketplace_add(
&self,
params: MarketplaceAddParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.marketplace_add_inner(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn marketplace_remove(
&self,
params: MarketplaceRemoveParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.marketplace_remove_inner(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn marketplace_upgrade(
&self,
params: MarketplaceUpgradeParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.marketplace_upgrade_response_inner(params)
.await
.map(|response| Some(response.into()))
}
async fn marketplace_remove_inner(
&self,
params: MarketplaceRemoveParams,
) -> Result<MarketplaceRemoveResponse, JSONRPCErrorError> {
let config = self.load_global_config().await?;
remove_marketplace(
config.codex_home.to_path_buf(),
config.config_layer_stack,
CoreMarketplaceRemoveRequest {
marketplace_name: params.marketplace_name,
},
)
.await
.map(|outcome| MarketplaceRemoveResponse {
marketplace_name: outcome.marketplace_name,
installed_root: outcome.removed_installed_root,
})
.map_err(|err| match err {
MarketplaceRemoveError::InvalidRequest(message) => invalid_request(message),
MarketplaceRemoveError::Internal(message) => internal_error(message),
})
}
async fn marketplace_upgrade_response_inner(
&self,
params: MarketplaceUpgradeParams,
) -> Result<MarketplaceUpgradeResponse, JSONRPCErrorError> {
let config = self.load_global_config().await?;
let plugins_manager = self.thread_manager.plugins_manager();
let MarketplaceUpgradeParams { marketplace_name } = params;
let plugins_input = config.plugins_config_input();
let reload_config = plugin_config_reload::global(self.config_manager.clone());
let outcome = tokio::task::spawn_blocking(move || {
plugins_manager.upgrade_configured_marketplaces_for_config(
&plugins_input,
marketplace_name.as_deref(),
&reload_config,
)
})
.await
.map_err(|err| internal_error(format!("failed to upgrade marketplaces: {err}")))?
.map_err(invalid_request)?;
if !outcome.upgraded_roots.is_empty() {
self.thread_manager.plugins_manager().clear_cache();
self.thread_manager.skills_service().clear_cache();
self.thread_manager.invalidate_mcp_runtimes().await;
self.thread_manager.refresh_hook_runtimes().await;
}
Ok(MarketplaceUpgradeResponse {
selected_marketplaces: outcome.selected_marketplaces,
upgraded_roots: outcome.upgraded_roots,
errors: outcome
.errors
.into_iter()
.map(|err| MarketplaceUpgradeErrorInfo {
marketplace_name: err.marketplace_name,
message: err.message,
})
.collect(),
})
}
async fn marketplace_add_inner(
&self,
params: MarketplaceAddParams,
) -> Result<MarketplaceAddResponse, JSONRPCErrorError> {
let config = self.load_global_config().await?;
add_marketplace_to_codex_home(
config.codex_home.to_path_buf(),
config.config_layer_stack.requirements().clone(),
MarketplaceAddRequest {
source: params.source,
ref_name: params.ref_name,
sparse_paths: params.sparse_paths.unwrap_or_default(),
},
)
.await
.map(|outcome| MarketplaceAddResponse {
marketplace_name: outcome.marketplace_name,
installed_root: outcome.installed_root,
already_added: outcome.already_added,
})
.map_err(|err| match err {
MarketplaceAddError::InvalidRequest(message) => invalid_request(message),
MarketplaceAddError::Internal(message) => internal_error(message),
})
}
async fn load_global_config(&self) -> Result<Config, JSONRPCErrorError> {
self.config_manager
.load_non_project_config()
.await
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
}
}

View File

@@ -0,0 +1,335 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::McpServerEventNotification;
use codex_app_server_protocol::McpServerEventStreamNotification;
use codex_app_server_protocol::McpServerEventStreamStartParams;
use codex_app_server_protocol::ServerNotification;
use codex_core::CodexThread;
use codex_login::AuthManager;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_mcp::McpEventStream;
use codex_protocol::ThreadId;
use serde_json::Value;
use tokio::sync::Mutex;
use tokio::sync::oneshot;
use tokio::sync::watch;
use tokio::task::JoinHandle;
use super::mcp_processor::McpRequestProcessor;
use crate::error_code::OVERLOADED_ERROR_CODE;
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use crate::outgoing_message::ConnectionId;
use crate::outgoing_message::OutgoingMessageSender;
const MAX_MCP_EVENT_STREAMS_PER_CONNECTION: usize = 64;
const MAX_MCP_EVENT_STREAM_RECONNECT_ATTEMPTS: u32 = 3;
const MCP_EVENT_STREAM_RECONNECT_DELAY: Duration = Duration::from_secs(/*secs*/ 1);
const MCP_EVENT_STREAM_STARTUP_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 90);
pub(crate) type McpEventStreamReady = oneshot::Receiver<Result<(), JSONRPCErrorError>>;
#[derive(Debug)]
struct McpEventStreamTask {
thread_id: ThreadId,
task: JoinHandle<()>,
}
#[derive(Debug, Default)]
pub(crate) struct McpEventStreams {
tasks: Mutex<HashMap<String, McpEventStreamTask>>,
}
impl McpEventStreams {
pub(crate) async fn start(
&self,
connection_id: ConnectionId,
params: McpServerEventStreamStartParams,
processor: McpRequestProcessor,
) -> Result<McpEventStreamReady, JSONRPCErrorError> {
if params.server != CODEX_APPS_MCP_SERVER_NAME {
return Err(invalid_request(
"MCP event subscriptions are only supported for hosted apps",
));
}
let thread_id = ThreadId::from_string(&params.thread_id)
.map_err(|error| invalid_request(format!("invalid thread id: {error}")))?;
let subscription_id = params.subscription_id.clone();
let (ready_tx, ready_rx) = oneshot::channel();
{
let mut tasks = self.tasks.lock().await;
tasks.retain(|_, task| !task.task.is_finished());
if tasks.contains_key(&subscription_id) {
return Err(invalid_request(format!(
"MCP event subscription '{subscription_id}' already exists"
)));
}
if tasks.len() >= MAX_MCP_EVENT_STREAMS_PER_CONNECTION {
return Err(JSONRPCErrorError {
code: OVERLOADED_ERROR_CODE,
message: format!(
"MCP event subscription limit of {MAX_MCP_EVENT_STREAMS_PER_CONNECTION} reached"
),
data: None,
});
}
let task = tokio::spawn(async move {
let mut auth_changes =
McpEventStreamAuthChanges::new(Arc::clone(&processor.auth_manager));
let opened = tokio::select! {
() = auth_changes.changed() => Err(internal_error(
"MCP event subscription authentication changed during startup",
)),
result = async {
if !processor
.thread_state_manager
.subscribed_connection_ids(thread_id)
.await
.contains(&connection_id)
{
return Err(invalid_request(format!(
"connection is not subscribed to thread '{thread_id}'"
)));
}
let (_, thread) = processor.load_thread(&params.thread_id).await?;
let stream = thread
.start_mcp_event_stream(
&params.name,
params.arguments.clone(),
params.meta.clone(),
)
.await
.map_err(|error| internal_error(format!(
"failed to start MCP event stream for '{}': {error:#}",
params.server
)))?;
Ok((stream, thread))
} => result,
};
match opened {
Ok((stream, thread)) => {
forward_events(
connection_id,
&params,
processor.outgoing.as_ref(),
thread,
stream,
auth_changes,
ready_tx,
)
.await;
}
Err(error) => {
let _ = ready_tx.send(Err(error));
}
}
});
tasks.insert(subscription_id, McpEventStreamTask { thread_id, task });
}
Ok(ready_rx)
}
pub(crate) async fn wait_for_activation(
&self,
subscription_id: &str,
ready: McpEventStreamReady,
) -> Result<(), JSONRPCErrorError> {
match tokio::time::timeout(MCP_EVENT_STREAM_STARTUP_TIMEOUT, ready).await {
Ok(Ok(result)) => result,
Ok(Err(_)) => Err(internal_error(
"MCP event stream ended before becoming active",
)),
Err(_) => {
self.stop(subscription_id).await;
Err(internal_error("MCP event stream startup timed out"))
}
}
}
pub(crate) async fn stop(&self, subscription_id: &str) {
let task = self.tasks.lock().await.remove(subscription_id);
if let Some(task) = task {
task.task.abort();
let _ = task.task.await;
}
}
pub(crate) async fn stop_thread(&self, thread_id: ThreadId) {
self.stop_matching(Some(thread_id)).await;
}
pub(crate) async fn clear(&self) {
self.stop_matching(/*thread_id*/ None).await;
}
async fn stop_matching(&self, thread_id: Option<ThreadId>) {
let tasks = self
.tasks
.lock()
.await
.extract_if(|_, task| thread_id.is_none_or(|id| task.thread_id == id))
.map(|(_, task)| task)
.collect::<Vec<_>>();
for task in tasks {
task.task.abort();
let _ = task.task.await;
}
}
}
async fn forward_events(
connection_id: ConnectionId,
params: &McpServerEventStreamStartParams,
outgoing: &OutgoingMessageSender,
thread: Arc<CodexThread>,
mut stream: McpEventStream,
mut auth_changes: McpEventStreamAuthChanges,
ready: oneshot::Sender<Result<(), JSONRPCErrorError>>,
) {
let mut ready = Some(ready);
let mut reconnect_attempts = 0;
let mut reconnect_deadline = None;
let send = |notification| {
outgoing.send_server_notification_to_connection_and_wait(
connection_id,
ServerNotification::McpServerEventStream(McpServerEventStreamNotification {
subscription_id: params.subscription_id.clone(),
notification,
}),
)
};
loop {
let notification = tokio::select! {
biased;
() = auth_changes.changed() => break,
() = thread.wait_until_terminated() => break,
result = stream.recv() => match result {
Ok(Some(notification)) => notification,
Ok(None)
if ready.is_none()
&& reconnect_attempts < MAX_MCP_EVENT_STREAM_RECONNECT_ATTEMPTS =>
{
reconnect_attempts += 1;
let deadline = *reconnect_deadline.get_or_insert_with(|| {
tokio::time::Instant::now() + MCP_EVENT_STREAM_STARTUP_TIMEOUT
});
tokio::select! {
biased;
() = auth_changes.changed() => break,
() = thread.wait_until_terminated() => break,
result = tokio::time::timeout_at(deadline, async {
tokio::time::sleep(
MCP_EVENT_STREAM_RECONNECT_DELAY
* (1 << (reconnect_attempts - 1)),
)
.await;
let mut stream = thread
.start_mcp_event_stream(
&params.name,
params.arguments.clone(),
params.meta.clone(),
)
.await?;
let notification = stream.recv().await?;
Ok::<_, anyhow::Error>((stream, notification))
}) => match result {
Ok(Ok((reconnected, Some(notification)))) => {
stream = reconnected;
notification
}
Ok(Ok((_, None)) | Err(_)) => continue,
Err(_) => break,
},
}
}
Ok(None) => break,
Err(error) => {
if let Some(ready) = ready.take() {
let _ = ready.send(Err(internal_error(format!("{error:#}"))));
}
break;
}
},
};
let active = notification.method == "notifications/events/active";
let terminated = notification.method == "notifications/events/terminated";
if !send(McpServerEventNotification {
method: notification.method,
params: notification
.params
.unwrap_or_else(|| Value::Object(Default::default())),
})
.await
{
break;
}
if active && let Some(ready) = ready.take() {
let _ = ready.send(Ok(()));
}
if terminated {
return;
}
if !active {
reconnect_attempts = 0;
reconnect_deadline = None;
}
}
if let Some(ready) = ready {
let _ = ready.send(Err(internal_error(
"MCP event stream ended before becoming active",
)));
} else {
send(McpServerEventNotification {
method: "notifications/events/terminated".to_string(),
params: Value::Object(Default::default()),
})
.await;
}
}
struct McpEventStreamAuthChanges {
manager: Arc<AuthManager>,
receiver: watch::Receiver<u64>,
revision: u64,
principal: Option<(Option<String>, Option<String>)>,
}
impl McpEventStreamAuthChanges {
fn new(manager: Arc<AuthManager>) -> Self {
let receiver = manager.auth_change_receiver();
let revision = *receiver.borrow();
let principal = manager
.auth_cached()
.map(|auth| (auth.get_account_id(), auth.get_chatgpt_user_id()));
Self {
manager,
receiver,
revision,
principal,
}
}
async fn changed(&mut self) {
loop {
if self
.manager
.auth_cached()
.map(|auth| (auth.get_account_id(), auth.get_chatgpt_user_id()))
!= self.principal
{
return;
}
if self.receiver.changed().await.is_err() || self.principal == Some((None, None)) {
return;
}
let revision = *self.receiver.borrow_and_update();
if revision.wrapping_sub(self.revision) > 1 {
return;
}
self.revision = revision;
}
}
}

View File

@@ -0,0 +1,826 @@
use super::account_processor::EnterpriseLoginCompletion;
use super::account_processor::EnterpriseLoginTarget;
use super::thread_input::ensure_direct_input_allowed;
use super::*;
use codex_config::types::McpServerAuth;
use codex_mcp::McpServerSource;
use codex_mcp::ReadResourceRequestParams;
use codex_mcp::ema_auth_scope;
use codex_mcp::resolve_oauth_callback;
use codex_otel::auth_storage::AuthStorageOriginator;
use codex_rmcp_client::EnterpriseOAuthLoginRequest;
use std::future::Future;
use crate::thread_state::ThreadStateManager;
const MCP_THREAD_ID_META_KEY: &str = "threadId";
#[derive(Clone)]
pub(crate) struct McpRequestProcessor {
pub(super) auth_manager: Arc<AuthManager>,
thread_manager: Arc<ThreadManager>,
pub(super) outgoing: Arc<OutgoingMessageSender>,
config_manager: ConfigManager,
account_processor: Arc<AccountRequestProcessor>,
pub(super) thread_state_manager: ThreadStateManager,
}
impl McpRequestProcessor {
pub(crate) fn new(
auth_manager: Arc<AuthManager>,
thread_manager: Arc<ThreadManager>,
thread_state_manager: ThreadStateManager,
outgoing: Arc<OutgoingMessageSender>,
config_manager: ConfigManager,
account_processor: Arc<AccountRequestProcessor>,
) -> Self {
Self {
auth_manager,
thread_manager,
outgoing,
config_manager,
account_processor,
thread_state_manager,
}
}
pub(crate) async fn mcp_server_oauth_login(
&self,
params: McpServerOauthLoginParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.mcp_server_oauth_login_response(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) fn mcp_server_refresh(
&self,
params: Option<()>,
) -> impl Future<Output = Result<Option<ClientResponsePayload>, JSONRPCErrorError>> + Send + '_
{
// Keep refresh state behind a pointer before returning to the shared request handler.
Box::pin(async move {
self.mcp_server_refresh_response(params)
.await
.map(|response| Some(response.into()))
})
}
pub(crate) async fn mcp_server_status_list(
&self,
request_id: &ConnectionRequestId,
params: ListMcpServerStatusParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.list_mcp_server_status(request_id, params)
.await
.map(|()| None)
}
pub(crate) async fn mcp_resource_read(
&self,
request_id: &ConnectionRequestId,
params: McpResourceReadParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.read_mcp_resource(request_id, params)
.await
.map(|()| None)
}
pub(crate) async fn mcp_server_tool_call(
&self,
request_id: &ConnectionRequestId,
params: McpServerToolCallParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.call_mcp_server_tool(request_id, params)
.await
.map(|()| None)
}
async fn mcp_server_refresh_response(
&self,
_params: Option<()>,
) -> Result<McpServerRefreshResponse, JSONRPCErrorError> {
crate::mcp_refresh::reload_mcp_config(&self.thread_manager, &self.config_manager)
.await
.map_err(|err| internal_error(format!("failed to refresh MCP servers: {err}")))?;
Ok(McpServerRefreshResponse {})
}
async fn load_global_config(&self) -> Result<Config, JSONRPCErrorError> {
self.config_manager
.load_non_project_config()
.await
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
}
pub(super) async fn load_thread(
&self,
thread_id: &str,
) -> Result<(ThreadId, Arc<CodexThread>), JSONRPCErrorError> {
let thread_id = ThreadId::from_string(thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
let thread = self
.thread_manager
.get_thread(thread_id)
.await
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
Ok((thread_id, thread))
}
async fn mcp_server_oauth_login_response(
&self,
params: McpServerOauthLoginParams,
) -> Result<McpServerOauthLoginResponse, JSONRPCErrorError> {
let McpServerOauthLoginParams {
name,
thread_id,
client_registration,
scopes,
timeout_secs,
} = params;
let auth = self.auth_manager.auth().await;
let (mcp_config, runtime_context) = match thread_id.as_deref() {
Some(thread_id) => {
let (_, thread) = self.load_thread(thread_id).await?;
let (config, runtime_context) =
thread.current_mcp_config_and_runtime_context().await;
((*config).clone(), runtime_context)
}
None => {
let config = self.load_global_config().await?;
let mcp_config = self
.thread_manager
.mcp_manager()
.runtime_config(&config)
.await;
let runtime_context = McpRuntimeContext::new(
self.thread_manager.environment_manager(),
config.cwd.to_path_buf(),
);
(mcp_config, runtime_context)
}
};
let effective_servers = codex_mcp::effective_mcp_servers(&mcp_config, auth.as_ref());
let Some(server) = effective_servers.get(&name) else {
return Err(invalid_request(format!(
"No MCP server named '{name}' found."
)));
};
let redirect_mode = if server.is_agent_plugin() {
StreamableHttpRedirectMode::AgentPluginV1
} else {
StreamableHttpRedirectMode::Legacy
};
let server = server.config();
let enterprise = matches!(server.auth, McpServerAuth::EmaAuth);
let (authorization_url, login_id, completion): (
String,
String,
futures::future::BoxFuture<'static, anyhow::Result<()>>,
) = if enterprise {
let thread_id = thread_id.clone().ok_or_else(|| {
invalid_request("enterprise MCP login requires a connected thread")
})?;
if !mcp_config.xaa_enabled {
return Err(invalid_request(
"enterprise MCP authentication requires `[features].use_xaa = true`",
));
}
if !server.enabled {
return Err(invalid_request(format!("MCP server '{name}' is disabled.")));
}
server
.validate_ema_auth_transport()
.map_err(|reason| invalid_request(format!("MCP server '{name}' {reason}")))?;
if client_registration.is_some() {
return Err(invalid_request(
"enterprise MCP login uses the configured enterprise client and does not support clientRegistration overrides",
));
}
// Resource scopes and per-server callbacks do not alter the shared IdP registration.
let scope = ema_auth_scope(auth.as_ref()).ok_or_else(|| {
invalid_request(
"enterprise MCP authentication requires a signed-in Codex user and workspace",
)
})?;
let idp = server.oauth_idp().ok_or_else(|| {
invalid_request(format!(
"MCP server '{name}' has no configured enterprise IdP"
))
})?;
let registration = server.ema_registration().cloned().ok_or_else(|| {
invalid_request(format!(
"MCP server '{name}' has no validated enterprise registration"
))
})?;
let credential_name = idp.credential_name(&scope);
let http_client =
runtime_context
.resolve_http_client(&name, server)
.map_err(|err| {
internal_error(format!("failed to resolve MCP server runtime: {err}"))
})?;
let login = self
.account_processor
.enterprise_login
.start(
EnterpriseOAuthLoginRequest {
credential_name: &credential_name,
issuer: &idp.issuer,
client_id: &idp.client_id,
client_secret: idp.client_secret.as_ref().map(|secret| secret.as_str()),
token_endpoint_auth_method: idp.token_endpoint_auth_method,
keyring_backend_kind: mcp_config.auth_keyring_backend_kind,
callback_port: mcp_config.mcp_oauth_callback_port,
callback_url: mcp_config.mcp_oauth_callback_url.as_deref(),
timeout_secs,
http_client,
redirect_mode,
},
scope,
EnterpriseLoginTarget {
thread_id,
server_name: name.clone(),
registration,
},
)
.await?;
let mut completion = login.completion;
(
login.authorization_url,
login.login_id,
Box::pin(async move {
match completion.wait_for(|state| state.is_complete()).await {
Ok(result) => match *result {
EnterpriseLoginCompletion::Succeeded => Ok(()),
EnterpriseLoginCompletion::Failed(detail) => Err(detail.into()),
EnterpriseLoginCompletion::Pending => {
Err(anyhow::anyhow!("Enterprise sign-in failed."))
}
},
_ => Err(anyhow::anyhow!("Enterprise sign-in failed.")),
}
}),
)
} else {
let (url, http_headers, env_http_headers) = match &server.transport {
McpServerTransportConfig::StreamableHttp {
url,
http_headers,
env_http_headers,
..
} => (url.clone(), http_headers.clone(), env_http_headers.clone()),
_ => {
return Err(invalid_request(
"OAuth login is only supported for streamable HTTP servers.",
));
}
};
let http_client =
runtime_context
.resolve_http_client(&name, server)
.map_err(|err| {
internal_error(format!("failed to resolve MCP server runtime: {err}"))
})?;
let discovered_scopes = if scopes.is_none() && server.scopes.is_none() {
discover_supported_scopes(
&server.transport,
Arc::clone(&http_client),
codex_rmcp_client::OAuthDiscoveryTimeout::Requested,
redirect_mode,
)
.await
} else {
None
};
let resolved_scopes =
resolve_oauth_scopes(scopes, server.scopes.clone(), discovered_scopes);
let oauth_credential_name = server.oauth_credential_name(&name);
let client_registration = match client_registration.unwrap_or_default() {
McpServerOauthClientRegistration::Auto => McpOAuthClientRegistration::Auto,
McpServerOauthClientRegistration::Cimd => McpOAuthClientRegistration::Cimd,
McpServerOauthClientRegistration::Dcr => McpOAuthClientRegistration::Dcr,
};
let callback_url =
resolve_oauth_callback(server, &url, mcp_config.mcp_oauth_callback_url.as_deref())
.map_err(|err| {
internal_error(format!("failed to resolve MCP OAuth callback: {err}"))
})?;
let handle = perform_oauth_login_return_url(
oauth_credential_name.as_ref(),
&url,
mcp_config.mcp_oauth_credentials_store_mode,
mcp_config.auth_keyring_backend_kind,
http_headers,
env_http_headers,
&resolved_scopes.scopes,
server.oauth.as_ref(),
client_registration,
server.oauth_resource.as_deref(),
timeout_secs,
server.oauth_callback_port(mcp_config.mcp_oauth_callback_port),
callback_url.as_deref(),
mcp_config.mcp_oauth_callback_url.as_deref(),
http_client,
redirect_mode,
)
.await
.map_err(|err| {
internal_error(format!("failed to login to MCP server '{name}': {err}"))
})?;
(
handle.authorization_url().to_string(),
Uuid::now_v7().to_string(),
Box::pin(handle.wait()),
)
};
let notification_name = name.clone();
let notification_thread_id = thread_id;
let notification_login_id = login_id.clone();
let outgoing = Arc::clone(&self.outgoing);
let thread_manager = Arc::clone(&self.thread_manager);
tokio::spawn(async move {
let (success, error) = match completion.await {
Ok(()) => (true, None),
Err(err) => (false, Some(err.to_string())),
};
if success && !enterprise {
thread_manager.invalidate_mcp_runtimes().await;
}
let notification = ServerNotification::McpServerOauthLoginCompleted(
McpServerOauthLoginCompletedNotification {
name: notification_name,
thread_id: notification_thread_id,
login_id: Some(notification_login_id),
success,
error,
},
);
outgoing.send_server_notification(notification).await;
});
Ok(McpServerOauthLoginResponse {
authorization_url,
login_id: Some(login_id),
})
}
async fn list_mcp_server_status(
&self,
request_id: &ConnectionRequestId,
params: ListMcpServerStatusParams,
) -> Result<(), JSONRPCErrorError> {
let request = request_id.clone();
let outgoing = Arc::clone(&self.outgoing);
let thread = match params.thread_id.as_deref() {
Some(thread_id) => Some(self.load_thread(thread_id).await?.1),
None => None,
};
let processor = self.clone();
let task = async move {
let result = processor
.list_mcp_server_status_response(params, thread)
.await;
outgoing.send_result(request, result).await;
};
tokio::spawn(AuthStorageOriginator::current().scope(task));
Ok(())
}
async fn list_mcp_server_status_response(
&self,
params: ListMcpServerStatusParams,
thread: Option<Arc<codex_core::CodexThread>>,
) -> Result<ListMcpServerStatusResponse, JSONRPCErrorError> {
let detail = match params.detail.unwrap_or(McpServerStatusDetail::Full) {
McpServerStatusDetail::Full => McpSnapshotDetail::Full,
McpServerStatusDetail::ToolsAndAuthOnly => McpSnapshotDetail::ToolsAndAuthOnly,
};
let (mcp_config, snapshot) = if let (Some(thread), Some(server)) =
(thread.as_ref(), params.server_name.as_deref())
{
thread
.mcp_server_status_snapshot(server, detail, /*expected_registration*/ None)
.await
.map_err(|error| {
internal_error(format!("failed to read MCP server status: {error:#}"))
})?
} else {
let config = match thread.as_ref() {
Some(thread) => {
let thread_config = thread.config().await;
self.config_manager
.load_latest_config_with_session_layers(
&thread_config.config_layer_stack,
&thread_config.cwd,
)
.await
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?
}
None => self.load_global_config().await?,
};
let mcp_manager = thread
.as_ref()
.map(|thread| thread.mcp_manager())
.unwrap_or_else(|| self.thread_manager.mcp_manager());
self.thread_manager
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
.map_err(|error| internal_error(error.to_string()))?;
let auth = mcp_manager.auth_manager().auth().await;
let runtime_auth = mcp_manager.runtime_auth_for_config(&config);
let (mcp_config, runtime_context) = match thread.as_ref() {
Some(thread) => thread.runtime_mcp_config_and_context(&config).await,
None => (
mcp_manager.runtime_config(&config).await,
McpRuntimeContext::new(
self.thread_manager.environment_manager(),
config.cwd.to_path_buf(),
),
),
};
let mut snapshot = collect_mcp_server_status_snapshot_with_detail(
&mcp_config,
auth.as_ref(),
Some(&self.auth_manager),
runtime_auth,
runtime_context,
mcp_manager.codex_apps_tools_cache(),
mcp_manager.tool_catalog_cache(),
detail,
params.server_name.as_deref(),
)
.await;
if mcp_config.xaa_enabled
&& let Some(thread) = thread.as_ref()
{
// EMA can only use its admitted thread connection. Keep ordinary
// status discovery unchanged and replace the threadless EMA results.
for (name, server) in mcp_config.mcp_server_catalog.configured_servers() {
if !matches!(server.auth, McpServerAuth::EmaAuth) {
continue;
}
let (selected_config, mut selected) = thread
.mcp_server_status_snapshot(
&name,
detail,
mcp_config.mcp_server_catalog.server(&name),
)
.await
.map_err(|error| {
internal_error(format!("failed to read MCP server status: {error:#}"))
})?;
if selected_config.mcp_server_catalog.server(&name)
!= mcp_config.mcp_server_catalog.server(&name)
{
continue;
}
snapshot.server_infos.remove(&name);
snapshot.server_infos.extend(selected.server_infos);
snapshot.server_capabilities.remove(&name);
if let Some(capabilities) = selected.server_capabilities.remove(&name) {
snapshot
.server_capabilities
.insert(name.clone(), capabilities);
}
snapshot.tools_by_server.remove(&name);
snapshot.tools_by_server.extend(selected.tools_by_server);
snapshot.tool_list_meta.remove(&name);
snapshot.tool_list_meta.extend(selected.tool_list_meta);
snapshot.tools_errors.remove(&name);
snapshot.tools_errors.extend(selected.tools_errors);
snapshot.resources.remove(&name);
snapshot.resources.extend(selected.resources);
snapshot.resource_templates.remove(&name);
snapshot
.resource_templates
.extend(selected.resource_templates);
snapshot.auth_statuses.remove(&name);
snapshot.auth_statuses.extend(selected.auth_statuses);
}
}
(Arc::new(mcp_config), snapshot)
};
let runtime_statuses = match thread {
Some(thread) => thread.mcp_connection_statuses(&mcp_config).await,
None => HashMap::new(),
};
let McpServerStatusSnapshot {
mut server_infos,
mut server_capabilities,
mut tool_list_meta,
mut tools_by_server,
mut tools_errors,
mut resources,
mut resource_templates,
mut auth_statuses,
mut server_names,
} = snapshot;
server_names.extend(runtime_statuses.keys().cloned());
server_names.extend(
auth_statuses
.keys()
.cloned()
.chain(resources.keys().cloned())
.chain(resource_templates.keys().cloned()),
);
server_names.sort();
server_names.dedup();
server_names.retain(|name| {
params
.server_name
.as_deref()
.is_none_or(|server| name == server)
});
let total = server_names.len();
let limit = params.limit.unwrap_or(total as u32).max(1) as usize;
let effective_limit = limit.min(total);
let start = match params.cursor {
Some(cursor) => match cursor.parse::<usize>() {
Ok(idx) => idx,
Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))),
},
None => 0,
};
if start > total {
return Err(invalid_request(format!(
"cursor {start} exceeds total MCP servers {total}"
)));
}
let end = start.saturating_add(effective_limit).min(total);
let data: Vec<McpServerStatus> = server_names[start..end]
.iter()
.map(|name| McpServerStatus {
name: name.clone(),
runtime_status: runtime_statuses.get(name).copied().map(Into::into),
plugin_id: mcp_config.mcp_server_catalog.server(name).and_then(
|server| match server.source() {
McpServerSource::Plugin(plugin)
| McpServerSource::SelectedPlugin(plugin) => {
Some(plugin.plugin_id().to_owned())
}
McpServerSource::Config
| McpServerSource::Compatibility { .. }
| McpServerSource::Extension { .. } => None,
},
),
http_origin: mcp_config
.mcp_server_catalog
.server(name)
.and_then(|server| match &server.config().transport {
McpServerTransportConfig::StreamableHttp { url, .. } => {
url::Url::parse(url).ok().and_then(|url| {
matches!(url.scheme(), "http" | "https")
.then(|| url.origin().ascii_serialization())
})
}
McpServerTransportConfig::Stdio { .. } => None,
}),
server_info: server_infos.remove(name),
server_capabilities: server_capabilities.remove(name),
tool_list_meta: tool_list_meta.remove(name).map(Arc::unwrap_or_clone),
tools: tools_by_server.remove(name).unwrap_or_default(),
tools_error: tools_errors.remove(name),
resources: resources.remove(name).unwrap_or_default(),
resource_templates: resource_templates.remove(name).unwrap_or_default(),
auth_status: auth_statuses
.remove(name)
.unwrap_or(CoreMcpAuthStatus::Unsupported)
.into(),
})
.collect();
let next_cursor = if end < total {
Some(end.to_string())
} else {
None
};
Ok(ListMcpServerStatusResponse { data, next_cursor })
}
async fn read_mcp_resource(
&self,
request_id: &ConnectionRequestId,
params: McpResourceReadParams,
) -> Result<(), JSONRPCErrorError> {
let outgoing = Arc::clone(&self.outgoing);
let McpResourceReadParams {
meta,
thread_id,
origin_call_id,
server,
uri,
connector_id,
target,
} = params;
let mut resource_params = ReadResourceRequestParams::new(uri);
let mut meta = meta.unwrap_or_default();
let is_codex_apps = server == codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
let reserved_key = meta.iter().find_map(|(key, value)| match key.as_str() {
"x-codex-turn-metadata"
| MCP_THREAD_ID_META_KEY
| codex_mcp::MCP_CONNECTION_LEASE_META_KEY => Some(key.as_str()),
"connector_id" | "link_id" if is_codex_apps => Some(key.as_str()),
// This legacy routing hint can override an explicit app and account target.
"_codex_apps" if is_codex_apps && value.get("resource_uri").is_some() => {
Some("_codex_apps.resource_uri")
}
_ => None,
});
if let Some(key) = reserved_key {
return Err(invalid_request(format!(
"reserved resource read metadata key: {key}"
)));
}
if let Some(connector_id) = connector_id {
meta.insert(
"x-codex-turn-metadata".to_string(),
serde_json::json!({
"mcp_request_meta": {"selected_connector_ids": [connector_id]},
}),
);
}
if origin_call_id.is_none()
&& let Some(target) = target
{
if !is_codex_apps
|| target.connector_id.trim().is_empty()
|| target
.link_id
.as_ref()
.is_some_and(|id| id.trim().is_empty() || id.starts_with("synthetic_link::"))
{
return Err(invalid_request(
"target requires codex_apps, a connectorId, and a real linkId or null",
));
}
meta.insert(
"connector_id".to_string(),
serde_json::json!(target.connector_id),
);
meta.insert("link_id".to_string(), serde_json::json!(target.link_id));
}
if !meta.is_empty() {
resource_params.meta = Some(meta.into());
}
if let Some(thread_id) = thread_id {
let (_, thread) = self.load_thread(&thread_id).await?;
let request_id = request_id.clone();
let task = async move {
let origin_call_id = origin_call_id.filter(|_| is_codex_apps);
let result = match origin_call_id.as_deref() {
Some(call_id) => {
thread
.read_mcp_resource_for_call(call_id, resource_params)
.await
}
None => thread.read_mcp_resource(&server, resource_params).await,
};
Self::send_mcp_resource_read_response(outgoing, request_id, result, origin_call_id)
.await;
};
tokio::spawn(AuthStorageOriginator::current().scope(task));
return Ok(());
}
if origin_call_id.is_some() {
return Err(invalid_request("originCallId requires threadId"));
}
let config = self.load_global_config().await?;
let mcp_manager = self.thread_manager.mcp_manager();
let mcp_config = mcp_manager.runtime_config(&config).await;
let codex_apps_tools_cache = mcp_manager.codex_apps_tools_cache();
let tool_catalog_cache = mcp_manager.tool_catalog_cache();
self.thread_manager
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
.map_err(|error| internal_error(error.to_string()))?;
let runtime_auth = mcp_manager.runtime_auth_for_config(&config);
let auth = mcp_manager.auth_manager().auth().await;
let environment_manager = self.thread_manager.environment_manager();
// This threadless resource-read path has no turn cwd or turn-selected
// environment. Use config cwd only as the local stdio fallback; named
// environment stdio MCPs must declare their own absolute cwd.
let runtime_context =
McpRuntimeContext::new(Arc::clone(&environment_manager), config.cwd.to_path_buf());
let request_id = request_id.clone();
let task = async move {
let result = read_mcp_resource_without_thread(
&mcp_config,
auth.as_ref(),
runtime_auth,
runtime_context,
codex_apps_tools_cache,
tool_catalog_cache,
&server,
resource_params,
)
.await
.and_then(|result| serde_json::to_value(result).map_err(anyhow::Error::from));
Self::send_mcp_resource_read_response(
outgoing, request_id, result, /*origin_call_id*/ None,
)
.await;
};
tokio::spawn(AuthStorageOriginator::current().scope(task));
Ok(())
}
async fn send_mcp_resource_read_response(
outgoing: Arc<OutgoingMessageSender>,
request_id: ConnectionRequestId,
result: anyhow::Result<serde_json::Value>,
origin_call_id: Option<String>,
) {
let result = result
.map_err(mcp_operation_error)
.and_then(|result| {
serde_json::from_value::<McpResourceReadResponse>(result).map_err(|error| {
internal_error(format!(
"failed to deserialize MCP resource read response: {error}"
))
})
})
.map(|mut response| {
response.origin_call_id = origin_call_id;
response
});
outgoing.send_result(request_id, result).await;
}
async fn call_mcp_server_tool(
&self,
request_id: &ConnectionRequestId,
params: McpServerToolCallParams,
) -> Result<(), JSONRPCErrorError> {
let outgoing = Arc::clone(&self.outgoing);
let thread_id = params.thread_id.clone();
let (_, thread) = self.load_thread(&thread_id).await?;
ensure_direct_input_allowed(thread.as_ref()).await?;
let meta = with_mcp_tool_call_thread_id_meta(params.meta, &thread_id);
let request_id = request_id.clone();
let task = async move {
let result = thread
.call_mcp_tool(&params.server, &params.tool, params.arguments, meta)
.await
.map(McpServerToolCallResponse::from)
.map_err(mcp_operation_error);
outgoing.send_result(request_id, result).await;
};
tokio::spawn(AuthStorageOriginator::current().scope(task));
Ok(())
}
}
fn mcp_operation_error(error: anyhow::Error) -> JSONRPCErrorError {
match codex_rmcp_client::mcp_error(&error) {
Some(error) => JSONRPCErrorError {
code: i64::from(error.code.0),
message: error.message.to_string(),
data: error.data.clone(),
},
None => internal_error(format!("{error:#}")),
}
}
fn with_mcp_tool_call_thread_id_meta(
meta: Option<serde_json::Value>,
thread_id: &str,
) -> Option<serde_json::Value> {
match meta {
Some(serde_json::Value::Object(mut map)) => {
map.insert(
MCP_THREAD_ID_META_KEY.to_string(),
serde_json::Value::String(thread_id.to_string()),
);
Some(serde_json::Value::Object(map))
}
None => {
let mut map = serde_json::Map::new();
map.insert(
MCP_THREAD_ID_META_KEY.to_string(),
serde_json::Value::String(thread_id.to_string()),
);
Some(serde_json::Value::Object(map))
}
other => other,
}
}

View File

@@ -0,0 +1,59 @@
//! Reports v2 readiness without exposing memory contents or persistence details to clients.
use super::*;
use codex_app_server_protocol::MemoryStatusParams;
use codex_app_server_protocol::MemoryStatusResponse;
use codex_protocol::MemoryVersion;
impl ThreadRequestProcessor {
pub(crate) async fn memory_status(
&self,
params: MemoryStatusParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let minimum = params.min_consolidated_threads.unwrap_or(20);
if !(1..=4096).contains(&minimum) {
return Err(invalid_params(
"minConsolidatedThreads must be between 1 and 4096",
));
}
let db = self
.state_db
.as_ref()
.ok_or_else(|| internal_error("sqlite state db unavailable for memory status"))?;
let store = db
.memories_for_version(MemoryVersion::V2)
.await
.map_err(|error| internal_error(format!("failed to open v2 memory state: {error}")))?;
let count = store
.max_consolidated_thread_count()
.await
.map_err(|error| internal_error(format!("failed to read memory progress: {error}")))?;
let root = self
.config
.codex_home
.join(MemoryVersion::V2.directory_name());
let summary = tokio::fs::read_to_string(root.join("memory_summary.md"))
.await
.ok();
let has_v1_workspace = tokio::fs::try_exists(
self.config
.codex_home
.join(MemoryVersion::V1.directory_name()),
)
.await
.map_err(|error| internal_error(format!("failed to check v1 memory workspace: {error}")))?;
// Fresh profiles can start on V2 without consolidating any V1 history first.
let ready = !has_v1_workspace
|| count >= minimum
&& summary
.as_deref()
.is_some_and(codex_memories_write::workspace::is_valid_v2_summary);
Ok(Some(
MemoryStatusResponse {
v2_consolidated_threads: count,
v2_ready: ready,
}
.into(),
))
}
}

View File

@@ -0,0 +1,141 @@
use codex_protocol::ThreadId;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::models::ActivePermissionProfile;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ThreadSettingsSnapshot;
use codex_rollout::InitialHistory;
use codex_rollout::RolloutItem;
#[derive(Debug, PartialEq, Eq)]
pub(super) struct PersistedResumeSettings {
pub(super) approval_policy: AskForApproval,
pub(super) approvals_reviewer: Option<ApprovalsReviewer>,
pub(super) active_permission_profile: Option<ActivePermissionProfile>,
pub(super) unnamed_permission_profile: Option<PermissionProfile>,
}
impl PersistedResumeSettings {
pub(super) fn from_history(history: &[RolloutItem], thread_id: ThreadId) -> Option<Self> {
// A running turn can record stale permissions. Prefer a settings update whose
// owner is known, including a legacy update following that owner's checkpoint.
let mut latest_legacy = None;
for item in history.iter().rev() {
let RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) = item else {
continue;
};
match event.thread_id {
Some(owner) if owner == thread_id => {
return Some(Self::from(latest_legacy.unwrap_or(&event.thread_settings)));
}
Some(_) => latest_legacy = None,
None => {
latest_legacy.get_or_insert(&event.thread_settings);
}
}
}
latest_persisted_resume_settings(history)
}
}
impl From<&ThreadSettingsSnapshot> for PersistedResumeSettings {
fn from(settings: &ThreadSettingsSnapshot) -> Self {
Self {
approval_policy: settings.approval_policy,
approvals_reviewer: Some(
settings
.requested_approvals_reviewer
.unwrap_or(settings.approvals_reviewer),
),
active_permission_profile: settings.active_permission_profile.clone(),
unnamed_permission_profile: settings
.active_permission_profile
.is_none()
.then(|| settings.permission_profile.clone()),
}
}
}
pub(super) fn latest_owned_thread_settings(
history: &[RolloutItem],
thread_id: ThreadId,
) -> Option<&ThreadSettingsSnapshot> {
history.iter().rev().find_map(|item| match item {
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event))
if event.thread_id == Some(thread_id) =>
{
Some(&event.thread_settings)
}
_ => None,
})
}
fn latest_persisted_resume_settings(history: &[RolloutItem]) -> Option<PersistedResumeSettings> {
history
.iter()
.enumerate()
.rev()
.find_map(|(index, item)| match item {
RolloutItem::TurnContext(turn_context) => Some(PersistedResumeSettings {
approval_policy: turn_context.approval_policy,
approvals_reviewer: turn_context.approvals_reviewer.or_else(|| {
history[..index].iter().rev().find_map(|item| match item {
RolloutItem::TurnContext(turn_context) => turn_context.approvals_reviewer,
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) => Some(
event
.thread_settings
.requested_approvals_reviewer
.unwrap_or(event.thread_settings.approvals_reviewer),
),
_ => None,
})
}),
active_permission_profile: turn_context.active_permission_profile.clone(),
unnamed_permission_profile: None,
}),
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) => {
// History without an identifiable owner can supply a profile ID, but
// its raw filesystem grants may belong to another thread or executor.
let settings = &event.thread_settings;
Some(PersistedResumeSettings {
approval_policy: settings.approval_policy,
approvals_reviewer: Some(
settings
.requested_approvals_reviewer
.unwrap_or(settings.approvals_reviewer),
),
active_permission_profile: settings.active_permission_profile.clone(),
unnamed_permission_profile: None,
})
}
_ => None,
})
}
pub(super) fn latest_persisted_model_settings(
history: &InitialHistory,
) -> Option<&ThreadSettingsSnapshot> {
let InitialHistory::Resumed(history) = history else {
return None;
};
let mut crossed_foreign_snapshot = false;
for item in history.history.iter().rev() {
let RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) = item else {
continue;
};
match event.thread_id {
Some(thread_id) if thread_id == history.conversation_id => {
return Some(&event.thread_settings);
}
Some(_) => crossed_foreign_snapshot = true,
None if !crossed_foreign_snapshot => return Some(&event.thread_settings),
None => {}
}
}
None
}
#[cfg(test)]
#[path = "persisted_resume_settings_tests.rs"]
mod tests;

View File

@@ -0,0 +1,242 @@
use super::PersistedResumeSettings;
use super::latest_persisted_resume_settings;
use codex_protocol::ThreadId;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::Settings;
use codex_protocol::models::ActivePermissionProfile;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ThreadSettingsAppliedEvent;
use codex_protocol::protocol::ThreadSettingsSnapshot;
use codex_protocol::protocol::TurnContextItem;
use codex_rollout::RolloutItem;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
fn cwd() -> AbsolutePathBuf {
AbsolutePathBuf::try_from(std::env::current_dir().expect("current directory"))
.expect("absolute current directory")
}
fn settings_item(
thread_id: Option<ThreadId>,
approval_policy: AskForApproval,
approvals_reviewer: ApprovalsReviewer,
active_permission_profile: Option<ActivePermissionProfile>,
) -> RolloutItem {
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(
ThreadSettingsAppliedEvent {
thread_id,
thread_settings: ThreadSettingsSnapshot {
disabled_plugin_ids: Vec::new(),
model: "gpt-5".to_string(),
model_provider_id: "openai".to_string(),
service_tier: None,
approval_policy,
approvals_reviewer,
requested_approvals_reviewer: None,
permission_profile: PermissionProfile::read_only(),
active_permission_profile,
cwd: cwd(),
runtime_workspace_roots: None,
reasoning_effort: None,
reasoning_summary: None,
personality: None,
collaboration_mode: CollaborationMode {
mode: ModeKind::Default,
settings: Settings {
model: "gpt-5".to_string(),
reasoning_effort: None,
developer_instructions: None,
},
},
},
},
))
}
fn turn_context_item(
turn_id: &str,
approval_policy: AskForApproval,
approvals_reviewer: Option<ApprovalsReviewer>,
active_permission_profile: Option<ActivePermissionProfile>,
) -> RolloutItem {
RolloutItem::TurnContext(TurnContextItem {
turn_id: Some(turn_id.to_string()),
root_turn_id: None,
direct_only_tool_namespaces: None,
disabled_plugin_ids: None,
cwd: cwd(),
approval_policy,
approvals_reviewer,
permission_profile: PermissionProfile::read_only(),
active_permission_profile,
model: "gpt-5".to_string(),
comp_hash: None,
collaboration_mode: None,
multi_agent_version: None,
realtime_active: None,
cyber_access_program: None,
effort: None,
summary: Some(codex_protocol::config_types::ReasoningSummary::Auto),
})
}
#[test]
fn latest_settings_snapshot_wins() {
let expected = PersistedResumeSettings {
approval_policy: AskForApproval::OnRequest,
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
active_permission_profile: Some(ActivePermissionProfile::new("dev")),
unnamed_permission_profile: None,
};
let history = vec![
settings_item(
/*thread_id*/ None,
AskForApproval::Never,
ApprovalsReviewer::User,
/*active_permission_profile*/ None,
),
settings_item(
/*thread_id*/ None,
AskForApproval::OnRequest,
ApprovalsReviewer::AutoReview,
Some(ActivePermissionProfile::new("dev")),
),
];
assert_eq!(latest_persisted_resume_settings(&history), Some(expected));
}
#[test]
fn latest_turn_context_wins_over_earlier_settings_update() {
let expected = PersistedResumeSettings {
approval_policy: AskForApproval::UnlessTrusted,
approvals_reviewer: Some(ApprovalsReviewer::User),
active_permission_profile: Some(ActivePermissionProfile::read_only()),
unnamed_permission_profile: None,
};
let history = vec![
settings_item(
/*thread_id*/ None,
AskForApproval::Never,
ApprovalsReviewer::AutoReview,
Some(ActivePermissionProfile::new("dev")),
),
turn_context_item(
"turn-2",
AskForApproval::UnlessTrusted,
Some(ApprovalsReviewer::User),
Some(ActivePermissionProfile::read_only()),
),
];
assert_eq!(latest_persisted_resume_settings(&history), Some(expected));
}
#[test]
fn newer_legacy_permissions_only_supersede_their_own_threads_checkpoint() {
let thread_id = ThreadId::new();
let other_thread_id = ThreadId::new();
let workspace = ActivePermissionProfile::new(":workspace");
let read_only = ActivePermissionProfile::read_only();
let owned = settings_item(
Some(thread_id),
AskForApproval::Never,
ApprovalsReviewer::AutoReview,
Some(workspace.clone()),
);
let legacy = settings_item(
/*thread_id*/ None,
AskForApproval::OnRequest,
ApprovalsReviewer::User,
Some(read_only.clone()),
);
let stale_turn = turn_context_item(
"turn",
AskForApproval::Never,
Some(ApprovalsReviewer::AutoReview),
Some(workspace.clone()),
);
let foreign = settings_item(
Some(other_thread_id),
AskForApproval::Never,
ApprovalsReviewer::AutoReview,
Some(workspace.clone()),
);
let foreign_legacy = settings_item(
/*thread_id*/ None,
AskForApproval::Never,
ApprovalsReviewer::AutoReview,
Some(workspace.clone()),
);
let mut history = vec![owned.clone(), legacy.clone(), stale_turn.clone()];
let expected = Some(PersistedResumeSettings {
approval_policy: AskForApproval::OnRequest,
approvals_reviewer: Some(ApprovalsReviewer::User),
active_permission_profile: Some(read_only),
unnamed_permission_profile: None,
});
assert_eq!(
PersistedResumeSettings::from_history(&history, thread_id),
expected
);
history.extend([foreign.clone(), foreign_legacy]);
assert_eq!(
PersistedResumeSettings::from_history(&history, thread_id),
expected
);
assert_eq!(
PersistedResumeSettings::from_history(&[owned, foreign, legacy, stale_turn], thread_id),
Some(PersistedResumeSettings {
approval_policy: AskForApproval::Never,
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
active_permission_profile: Some(workspace),
unnamed_permission_profile: None,
})
);
}
#[test]
fn older_reviewer_is_used_when_latest_turn_context_omits_it() {
let history = vec![
turn_context_item(
"turn-1",
AskForApproval::Never,
Some(ApprovalsReviewer::AutoReview),
/*active_permission_profile*/ None,
),
turn_context_item(
"turn-2",
AskForApproval::OnRequest,
/*approvals_reviewer*/ None,
/*active_permission_profile*/ None,
),
];
assert_eq!(
latest_persisted_resume_settings(&history),
Some(PersistedResumeSettings {
approval_policy: AskForApproval::OnRequest,
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
active_permission_profile: None,
unnamed_permission_profile: None,
})
);
}
#[test]
fn an_unattributed_snapshot_does_not_restore_unnamed_permissions() {
let history = [settings_item(
/*thread_id*/ None,
AskForApproval::OnRequest,
ApprovalsReviewer::User,
/*active_permission_profile*/ None,
)];
let settings =
PersistedResumeSettings::from_history(&history, ThreadId::new()).expect("legacy settings");
assert_eq!(settings.unnamed_permission_profile, None);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,82 @@
use super::*;
use codex_core::config::ConfigOverrides;
use codex_core_plugins::PluginMarketplaceContext;
use codex_core_plugins::PluginMarketplaceScope;
use codex_core_plugins::marketplace::MarketplaceListError;
use futures::StreamExt;
const CONFIG_LOAD_CONCURRENCY: usize = 5;
impl PluginRequestProcessor {
pub(super) async fn load_catalog_config(
&self,
cwds: &[AbsolutePathBuf],
) -> Result<Config, JSONRPCErrorError> {
if cwds.is_empty() {
self.config_manager
.load_non_project_config()
.await
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
} else {
self.load_latest_config(/*fallback_cwd*/ None).await
}
}
pub(super) async fn load_marketplace_context(
&self,
cwds: Vec<AbsolutePathBuf>,
catalog_config: &Config,
) -> PluginMarketplaceContext {
let global_config = catalog_config.plugins_config_input();
if cwds.is_empty() {
return PluginMarketplaceContext {
global_config: global_config.clone(),
scopes: vec![PluginMarketplaceScope {
cwd: None,
config: global_config,
}],
load_errors: Vec::new(),
};
}
let outcomes = futures::stream::iter(cwds)
.map(|cwd| async move {
match self
.config_manager
.load_with_overrides(
/*request_overrides*/ None,
ConfigOverrides {
cwd: Some(cwd.to_path_buf()),
..Default::default()
},
)
.await
{
Ok(config) => Ok(PluginMarketplaceScope {
cwd: Some(cwd),
config: config.plugins_config_input(),
}),
Err(err) => Err(MarketplaceListError {
path: cwd,
message: format!("failed to reload config: {err}"),
}),
}
})
.buffered(CONFIG_LOAD_CONCURRENCY)
.collect::<Vec<_>>()
.await;
let mut scopes = Vec::new();
let mut load_errors = Vec::new();
for outcome in outcomes {
match outcome {
Ok(scope) => scopes.push(scope),
Err(error) => load_errors.push(error),
}
}
PluginMarketplaceContext {
global_config,
scopes,
load_errors,
}
}
}

View File

@@ -0,0 +1,111 @@
//! Exposes shared installed-plugin reconciliation with hook lifecycle updates.
use super::*;
use crate::effective_plugin_change::trust_materialized_plugin_hooks;
use crate::request_serialization::RequestSerializationAccess;
use crate::request_serialization::RequestSerializationQueueKey;
use crate::request_serialization::RequestSerializationQueues;
use codex_app_server_protocol::PluginReconcileChangedPlugin;
use codex_app_server_protocol::PluginReconcileParams;
use codex_app_server_protocol::PluginReconcileResponse;
use codex_core_plugins::remote::RemotePluginShareDiscoverability;
impl PluginRequestProcessor {
#[tracing::instrument(level = "debug", skip_all, fields(reason = ?params.reason))]
pub(crate) async fn plugin_reconcile(
&self,
params: PluginReconcileParams,
config_processor: ConfigRequestProcessor,
request_serialization_queues: &RequestSerializationQueues,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let config = self.load_latest_config(/*fallback_cwd*/ None).await?;
let plugins_input = config.plugins_config_input();
let auth = self.auth_manager.auth().await;
if !plugins_input.plugins_enabled
|| !auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)
{
return Ok(Some(PluginReconcileResponse::default().into()));
}
// Match background bundle sync: remote_plugin controls catalog visibility, not sync.
// The shared reconciler owns synchronization, auth checks, and cache publication.
let outcome = self
.thread_manager
.plugins_manager()
.reconcile_remote_installed_plugins(&plugins_input, auth.as_ref())
.await
.map_err(|err| {
internal_error(format!(
"failed to reconcile remote installed plugins: {err}"
))
})?;
let hooks_changed = outcome
.changed_plugins
.iter()
.any(|plugin| plugin.capabilities.has_hooks);
// Preserve materialization-owned trust: unchanged background passes cannot recover it.
// Serialize hook updates with config writes, after releasing the bundle writer gate.
// Changes without hooks or eligible materializations still skip this queue.
if hooks_changed
|| outcome.materialized_remote_plugins.iter().any(|plugin| {
plugin.scope == RemotePluginScope::Workspace
&& plugin.discoverability == Some(RemotePluginShareDiscoverability::Listed)
})
{
let materializations = outcome.materialized_remote_plugins.clone();
let processor = self.clone();
let (complete, completion) = tokio::sync::oneshot::channel();
request_serialization_queues
.enqueue_background(
RequestSerializationQueueKey::Global("config"),
RequestSerializationAccess::Exclusive,
async move {
let result = trust_materialized_plugin_hooks(
materializations,
&processor.auth_manager,
&processor.thread_manager,
&processor.config_manager,
&config_processor,
)
.await;
// Removals and disablements have no trust write to rebuild loaded hooks.
// Rebuild after the trust attempt, even if it failed, to drop stale hooks.
if hooks_changed {
processor.thread_manager.refresh_hook_runtimes().await;
}
let _ = complete.send(result);
},
)
.await;
completion
.await
.map_err(|err| {
internal_error(format!("plugin hook trust update was cancelled: {err}"))
})?
.map_err(|err| {
internal_error(format!("failed to trust materialized plugin hooks: {err}"))
})?;
}
Ok(Some(
PluginReconcileResponse {
changed_plugins: outcome
.changed_plugins
.into_iter()
.map(|plugin| PluginReconcileChangedPlugin {
id: plugin.plugin_id,
has_mcps: plugin.capabilities.has_mcps,
has_apps: plugin.capabilities.has_apps,
has_hooks: plugin.capabilities.has_hooks,
has_skills: plugin.capabilities.has_skills,
})
.collect(),
failed_remote_plugin_ids: outcome.failed_remote_plugin_ids,
failed_materialization_remote_plugin_ids: outcome
.failed_materialization_remote_plugin_ids,
}
.into(),
))
}
}

View File

@@ -0,0 +1,350 @@
use super::*;
use codex_app_server_protocol::PluginSearchParams;
use codex_app_server_protocol::PluginSearchResponse;
use codex_app_server_protocol::PluginSearchResult;
use codex_app_server_protocol::PluginSearchScope;
use codex_core_plugins::OPENAI_BUNDLED_MARKETPLACE_NAME;
use codex_core_plugins::remote::RemotePluginSearchRequest;
use codex_core_plugins::remote::search_remote_plugins;
const DEFAULT_PLUGIN_SEARCH_LIMIT: u32 = 16;
const MAX_PLUGIN_SEARCH_LIMIT: u32 = 1_000;
const MAX_LOCAL_PLUGIN_SEARCH_RESULTS: usize = 100;
const PLUGIN_SEARCH_NO_MATCH_RANK: usize = 6;
impl PluginRequestProcessor {
pub(crate) async fn plugin_search(
&self,
params: PluginSearchParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.plugin_search_response(params)
.await
.map(|response| Some(response.into()))
}
async fn plugin_search_response(
&self,
params: PluginSearchParams,
) -> Result<PluginSearchResponse, JSONRPCErrorError> {
let PluginSearchParams {
search_term,
scope,
cwds,
cursor,
limit,
} = params;
let search_term = search_term.trim();
let empty_response = || PluginSearchResponse {
data: Vec::new(),
next_cursor: None,
};
if search_term.is_empty() {
return Ok(empty_response());
}
let config = self
.load_catalog_config(cwds.as_deref().unwrap_or_default())
.await?;
if !config.features.enabled(Feature::Plugins) {
return Ok(empty_response());
}
let plugin_sharing_enabled = config.features.enabled(Feature::PluginSharing);
let auth = self.auth_manager.auth().await;
let auth_mode = auth.as_ref().map(CodexAuth::api_auth_mode);
let remote_plugin_enabled = config.features.enabled(Feature::RemotePlugin);
let use_remote_global_catalog =
remote_plugin_enabled && auth_mode.is_some_and(DomainAuthMode::uses_codex_backend);
let remote_scope = if remote_plugin_enabled {
Some(scope.map(|scope| match scope {
PluginSearchScope::Global => RemotePluginScope::Global,
PluginSearchScope::Workspace => RemotePluginScope::Workspace,
PluginSearchScope::Personal => RemotePluginScope::User,
}))
} else {
match scope {
None | Some(PluginSearchScope::Workspace) => {
Some(Some(RemotePluginScope::Workspace))
}
Some(PluginSearchScope::Global | PluginSearchScope::Personal) => None,
}
};
let limit = limit
.unwrap_or(DEFAULT_PLUGIN_SEARCH_LIMIT)
.clamp(1, MAX_PLUGIN_SEARCH_LIMIT);
let mut next_cursor = None;
let mut remote_results = Vec::new();
if auth_mode.is_some_and(DomainAuthMode::uses_codex_backend)
&& let Some(remote_scope) = remote_scope
{
let page = search_remote_plugins(
&remote_plugin_service_config(&self.thread_manager, &config)?,
auth.as_ref(),
RemotePluginSearchRequest {
query: search_term,
scope: remote_scope,
limit,
page_token: cursor.as_deref(),
},
)
.await
.map_err(|err| {
remote_plugin_catalog_error_to_jsonrpc(err, "search remote plugin catalog")
})?;
next_cursor = page.next_page_token;
remote_results.reserve(page.plugins.len());
let plugin_policy = &config.plugins;
for plugin in page.plugins {
let plugin_id = PluginId::parse(&plugin.id).map_err(|err| {
internal_error(format!("invalid remote plugin search result id: {err}"))
})?;
// NOTE: (brisebois) filter out plugins from the results that belong to "shared"
// marketplaces if plugin sharing is disabled. There is a chance that this filters
// out all results and returns an empty list to the client. Ideally this filtering
// would be done server-side to avoid this problem.
if !plugin_sharing_enabled
&& matches!(
plugin_id.marketplace_name.as_str(),
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME
| REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME
| REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME
)
{
continue;
}
remote_results.push(plugin_search_result(
remote_plugin_summary_to_info(plugin, plugin_policy),
plugin_id.marketplace_name,
/*marketplace_path*/ None,
));
}
}
// All local results are stitched into the first page; if
// we are not on the first page, don't even check local
if cursor.is_some() {
return Ok(PluginSearchResponse {
data: remote_results,
next_cursor,
});
}
let normalized_search_term = normalize_search_text(search_term);
let mut local_results = Vec::new();
if scope != Some(PluginSearchScope::Workspace) {
let roots = cwds.unwrap_or_default();
let plugins_input = config.plugins_config_input();
let plugins_manager = self.thread_manager.plugins_manager();
let shared_plugin_ids_by_local_path = load_shared_plugin_ids_by_local_path(&config)
.unwrap_or_else(|err| {
warn!(
error = %err.message,
"plugin/search could not load shared plugin identities"
);
Default::default()
});
let outcome = tokio::task::spawn_blocking(move || {
plugins_manager.list_marketplaces_for_config(
&plugins_input,
&roots,
/*include_openai_curated*/ !use_remote_global_catalog,
)
})
.await
.map_err(|err| internal_error(format!("failed to list marketplace plugins: {err}")))?
.map_err(|err| Self::marketplace_error(err, "list marketplace plugins"))?;
for error in outcome.errors {
warn!(
marketplace_path = %error.path.as_path().display(),
error = %error.message,
"plugin/search skipped a local marketplace that could not be loaded"
);
}
for marketplace in outcome.marketplaces {
if !marketplace_matches_search_scope(&marketplace.name, scope) {
continue;
}
for plugin in marketplace.plugins {
let plugin = convert_configured_marketplace_plugin_to_plugin_summary(
plugin,
&shared_plugin_ids_by_local_path,
);
local_results.push(plugin_search_result(
plugin,
marketplace.name.clone(),
Some(marketplace.path.clone()),
));
}
}
}
let mut data = Vec::with_capacity(
local_results.len().min(MAX_LOCAL_PLUGIN_SEARCH_RESULTS) + remote_results.len(),
);
let mut local_matches = Vec::new();
let mut remote_results = remote_results.into_iter().map(Some).collect::<Vec<_>>();
let mut seen_local_plugin_identities = HashSet::new();
for local_result in local_results {
let local_remote_plugin_id =
local_result.plugin.remote_plugin_id.as_deref().or_else(|| {
local_result
.plugin
.share_context
.as_ref()
.map(|context| context.remote_plugin_id.as_str())
});
let remote_result_index = remote_results.iter().position(|remote_result| {
remote_result.as_ref().is_some_and(|remote_result| {
local_remote_plugin_id.is_some_and(|remote_plugin_id| {
remote_result.plugin.remote_plugin_id.as_deref() == Some(remote_plugin_id)
}) || local_result.plugin.id == remote_result.plugin.id
|| (is_openai_curated_marketplace_name(&local_result.marketplace_name)
&& remote_result.marketplace_name == REMOTE_GLOBAL_MARKETPLACE_NAME
&& local_result.plugin.name == remote_result.plugin.name)
})
});
if remote_result_index.is_none()
&& plugin_search_match_rank(&local_result.plugin, &normalized_search_term).is_none()
{
continue;
}
let local_identity = local_remote_plugin_id.map_or_else(
|| {
if is_openai_curated_marketplace_name(&local_result.marketplace_name) {
format!("curated:{}", local_result.plugin.name)
} else {
format!("plugin:{}", local_result.plugin.id)
}
},
|remote_plugin_id| format!("remote:{remote_plugin_id}"),
);
if !seen_local_plugin_identities.insert(local_identity) {
continue;
}
if let Some(remote_result_index) = remote_result_index
&& let Some(mut remote_result) = remote_results[remote_result_index].take()
{
remote_result.plugin.installed = local_result.plugin.installed;
remote_result.plugin.local_version = local_result.plugin.local_version;
data.push(remote_result);
} else {
local_matches.push(local_result);
}
}
local_matches.sort_by_key(|result| {
plugin_search_match_rank(&result.plugin, &normalized_search_term)
.unwrap_or(PLUGIN_SEARCH_NO_MATCH_RANK)
});
local_matches.truncate(MAX_LOCAL_PLUGIN_SEARCH_RESULTS);
data.extend(local_matches);
data.extend(remote_results.into_iter().flatten());
data.sort_by_key(|result| {
plugin_search_match_rank(&result.plugin, &normalized_search_term)
.unwrap_or(PLUGIN_SEARCH_NO_MATCH_RANK)
});
Ok(PluginSearchResponse { data, next_cursor })
}
}
/// Plugin discovery does not resolve effective activation, so all results explicitly report
/// `enabled: false`, regardless of their source, installation state, or page.
fn plugin_search_result(
mut plugin: PluginSummary,
marketplace_name: String,
marketplace_path: Option<AbsolutePathBuf>,
) -> PluginSearchResult {
plugin.enabled = false;
PluginSearchResult {
plugin,
marketplace_name,
marketplace_path,
}
}
fn marketplace_matches_search_scope(
marketplace_name: &str,
scope: Option<PluginSearchScope>,
) -> bool {
let is_built_in = is_openai_curated_marketplace_name(marketplace_name)
|| matches!(
marketplace_name,
OPENAI_BUNDLED_MARKETPLACE_NAME
| "openai-bundled-alpha"
| "codex-official"
| "openai-curated-remote"
| "openai-primary-runtime"
);
match scope {
None => true,
Some(PluginSearchScope::Global) => is_built_in,
Some(PluginSearchScope::Workspace) => false,
Some(PluginSearchScope::Personal) => !is_built_in,
}
}
fn normalize_search_text(value: &str) -> String {
let mut normalized = String::with_capacity(value.len());
for character in value.to_lowercase().chars() {
if character.is_alphanumeric() {
normalized.push(character);
} else if !normalized.is_empty() && !normalized.ends_with(' ') {
normalized.push(' ');
}
}
if normalized.ends_with(' ') {
normalized.pop();
}
normalized
}
fn plugin_search_match_rank(plugin: &PluginSummary, normalized_query: &str) -> Option<usize> {
if normalized_query.is_empty() {
return None;
}
let visible_name = normalize_search_text(
plugin
.interface
.as_ref()
.and_then(|interface| interface.display_name.as_deref())
.unwrap_or_default(),
);
let internal_name = normalize_search_text(&plugin.name);
let names = [&visible_name, &internal_name];
let keywords = plugin
.keywords
.iter()
.map(|keyword| normalize_search_text(keyword))
.collect::<Vec<_>>();
let joined_search_values = normalize_search_text(&format!(
"{internal_name} {visible_name} {}",
keywords.join(" ")
));
[
visible_name == normalized_query,
internal_name == normalized_query,
names.iter().any(|name| name.starts_with(normalized_query)),
names.iter().any(|name| name.contains(normalized_query)),
keywords.iter().any(|keyword| keyword == normalized_query),
keywords
.iter()
.any(|keyword| keyword.contains(normalized_query))
|| joined_search_values.contains(normalized_query),
]
.iter()
.position(|matches| *matches)
}

View File

@@ -0,0 +1,765 @@
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::Arc;
use std::time::Duration;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use codex_app_server_protocol::ClientResponsePayload;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::ProcessExitedNotification;
use codex_app_server_protocol::ProcessKillParams;
use codex_app_server_protocol::ProcessKillResponse;
use codex_app_server_protocol::ProcessOutputDeltaNotification;
use codex_app_server_protocol::ProcessOutputStream;
use codex_app_server_protocol::ProcessResizePtyParams;
use codex_app_server_protocol::ProcessResizePtyResponse;
use codex_app_server_protocol::ProcessSpawnParams;
use codex_app_server_protocol::ProcessSpawnResponse;
use codex_app_server_protocol::ProcessTerminalSize;
use codex_app_server_protocol::ProcessWriteStdinParams;
use codex_app_server_protocol::ProcessWriteStdinResponse;
use codex_app_server_protocol::ServerNotification;
use codex_core::exec::ExecExpiration;
use codex_core::exec::ExecExpirationOutcome;
use codex_core::exec::IO_DRAIN_TIMEOUT_MS;
use codex_exec_server::EnvironmentManager;
use codex_protocol::exec_output::bytes_to_string_smart;
use codex_protocol::shell_environment::is_non_inheritable_env_var;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP;
use codex_utils_pty::ProcessHandle;
use codex_utils_pty::SpawnedProcess;
use codex_utils_pty::TerminalSize;
use tokio::sync::Mutex;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
use crate::error_code::internal_error;
use crate::error_code::invalid_params;
use crate::error_code::invalid_request;
use crate::outgoing_message::ConnectionId;
use crate::outgoing_message::ConnectionRequestId;
use crate::outgoing_message::OutgoingMessageSender;
const EXEC_TIMEOUT_EXIT_CODE: i32 = 124;
const OUTPUT_CHUNK_SIZE_HINT: usize = 64 * 1024;
#[derive(Clone)]
pub(crate) struct ProcessExecRequestProcessor {
outgoing: Arc<OutgoingMessageSender>,
environment_manager: Arc<EnvironmentManager>,
process_exec_manager: ProcessExecManager,
}
impl ProcessExecRequestProcessor {
pub(crate) fn new(
outgoing: Arc<OutgoingMessageSender>,
environment_manager: Arc<EnvironmentManager>,
) -> Self {
Self {
outgoing,
environment_manager,
process_exec_manager: ProcessExecManager::default(),
}
}
pub(crate) async fn process_spawn(
&self,
request_id: ConnectionRequestId,
params: ProcessSpawnParams,
) -> Result<(), JSONRPCErrorError> {
self.require_local_environment()?;
let ProcessSpawnParams {
command,
process_handle,
cwd,
tty,
stream_stdin,
stream_stdout_stderr,
output_bytes_cap,
timeout_ms,
env: env_overrides,
size,
} = params;
let method_name = "process/spawn";
tracing::debug!("{method_name} command: {command:?}");
if command.is_empty() {
return Err(invalid_request("command must not be empty"));
}
if process_handle.is_empty() {
return Err(invalid_request("processHandle must not be empty"));
}
if size.is_some() && !tty {
return Err(invalid_params("process/spawn size requires tty: true"));
}
let mut env = std::env::vars().collect::<HashMap<_, _>>();
if let Some(env_overrides) = env_overrides {
for (key, value) in env_overrides {
match value {
Some(value) => {
env.insert(key, value);
}
None => {
env.remove(&key);
}
}
}
}
env.retain(|name, _| !is_non_inheritable_env_var(name));
let expiration = match timeout_ms {
Some(Some(timeout_ms)) => match u64::try_from(timeout_ms) {
Ok(timeout_ms) => timeout_ms.into(),
Err(_) => {
return Err(invalid_params(format!(
"{method_name} timeoutMs must be non-negative, got {timeout_ms}"
)));
}
},
Some(None) => ExecExpiration::Cancellation(CancellationToken::new()),
None => ExecExpiration::DefaultTimeout,
};
let output_bytes_cap = output_bytes_cap.unwrap_or(Some(DEFAULT_OUTPUT_BYTES_CAP));
let size = size.map(terminal_size_from_protocol).transpose()?;
self.process_exec_manager
.start(StartProcessParams {
outgoing: self.outgoing.clone(),
request_id,
process_handle,
command,
cwd,
env,
expiration,
tty,
stream_stdin,
stream_stdout_stderr,
output_bytes_cap,
size,
})
.await?;
Ok(())
}
pub(crate) async fn process_write_stdin(
&self,
request_id: ConnectionRequestId,
params: ProcessWriteStdinParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.process_exec_manager
.write_stdin(request_id, params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn process_resize_pty(
&self,
request_id: ConnectionRequestId,
params: ProcessResizePtyParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.process_exec_manager
.resize_pty(request_id, params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn process_kill(
&self,
request_id: ConnectionRequestId,
params: ProcessKillParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.process_exec_manager
.kill(request_id, params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn connection_closed(&self, connection_id: ConnectionId) {
self.process_exec_manager
.connection_closed(connection_id)
.await;
}
fn require_local_environment(&self) -> Result<(), JSONRPCErrorError> {
self.environment_manager
.try_local_environment()
.is_some()
.then_some(())
.ok_or_else(|| internal_error("local environment is not configured"))
}
}
#[derive(Clone, Default)]
struct ProcessExecManager {
sessions: Arc<Mutex<HashMap<ConnectionProcessHandle, ProcessSession>>>,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct ConnectionProcessHandle {
connection_id: ConnectionId,
process_handle: String,
}
#[derive(Clone)]
struct ProcessSession {
control_tx: mpsc::Sender<ProcessControlRequest>,
}
enum ProcessControl {
Write { delta: Vec<u8>, close_stdin: bool },
Resize { size: TerminalSize },
Kill,
}
struct ProcessControlRequest {
control: ProcessControl,
response_tx: Option<oneshot::Sender<Result<(), JSONRPCErrorError>>>,
}
struct StartProcessParams {
outgoing: Arc<OutgoingMessageSender>,
request_id: ConnectionRequestId,
process_handle: String,
command: Vec<String>,
cwd: AbsolutePathBuf,
env: HashMap<String, String>,
expiration: ExecExpiration,
tty: bool,
stream_stdin: bool,
stream_stdout_stderr: bool,
output_bytes_cap: Option<usize>,
size: Option<TerminalSize>,
}
struct RunProcessParams {
outgoing: Arc<OutgoingMessageSender>,
request_id: ConnectionRequestId,
process_handle: String,
spawned: SpawnedProcess,
control_rx: mpsc::Receiver<ProcessControlRequest>,
stream_stdin: bool,
stream_stdout_stderr: bool,
expiration: ExecExpiration,
output_bytes_cap: Option<usize>,
}
struct SpawnProcessOutputParams {
connection_id: ConnectionId,
process_handle: String,
output_rx: mpsc::Receiver<Vec<u8>>,
reader: Option<tokio::task::AbortHandle>,
process_exited: CancellationToken,
outgoing: Arc<OutgoingMessageSender>,
stream: ProcessOutputStream,
stream_output: bool,
output_bytes_cap: Option<usize>,
}
#[derive(Default)]
struct ProcessOutputCapture {
text: String,
cap_reached: bool,
output_incomplete: bool,
}
impl ProcessExecManager {
async fn start(&self, params: StartProcessParams) -> Result<(), JSONRPCErrorError> {
let StartProcessParams {
outgoing,
request_id,
process_handle,
command,
cwd,
env,
expiration,
tty,
stream_stdin,
stream_stdout_stderr,
output_bytes_cap,
size,
} = params;
let (program, args) = command
.split_first()
.ok_or_else(|| invalid_request("command must not be empty"))?;
let stream_stdin = tty || stream_stdin;
let stream_stdout_stderr = tty || stream_stdout_stderr;
let arg0 = None;
let (control_tx, control_rx) = mpsc::channel(32);
let process_key = ConnectionProcessHandle {
connection_id: request_id.connection_id,
process_handle: process_handle.clone(),
};
{
let mut sessions = self.sessions.lock().await;
match sessions.entry(process_key.clone()) {
Entry::Occupied(_) => {
return Err(invalid_request(format!(
"duplicate active process handle: {process_handle:?}",
)));
}
Entry::Vacant(entry) => {
entry.insert(ProcessSession { control_tx });
}
}
}
let spawned = if tty {
codex_utils_pty::spawn_pty_process(
program,
args,
cwd.as_path(),
&env,
&arg0,
size.unwrap_or_default(),
codex_utils_pty::ChildFds::Inherited(&[]),
)
.await
} else if stream_stdin {
codex_utils_pty::spawn_pipe_process(program, args, cwd.as_path(), &env, &arg0, &[])
.await
} else {
codex_utils_pty::spawn_pipe_process_no_stdin(
program,
args,
cwd.as_path(),
&env,
&arg0,
&[],
)
.await
};
let spawned = match spawned {
Ok(spawned) => spawned,
Err(err) => {
self.sessions.lock().await.remove(&process_key);
return Err(internal_error(format!("failed to spawn process: {err}")));
}
};
outgoing
.send_response(request_id.clone(), ProcessSpawnResponse {})
.await;
let sessions = Arc::clone(&self.sessions);
tokio::spawn(async move {
run_process(RunProcessParams {
outgoing,
request_id,
process_handle,
spawned,
control_rx,
stream_stdin,
stream_stdout_stderr,
expiration,
output_bytes_cap,
})
.await;
sessions.lock().await.remove(&process_key);
});
Ok(())
}
async fn write_stdin(
&self,
request_id: ConnectionRequestId,
params: ProcessWriteStdinParams,
) -> Result<ProcessWriteStdinResponse, JSONRPCErrorError> {
if params.delta_base64.is_none() && !params.close_stdin {
return Err(invalid_params(
"process/writeStdin requires deltaBase64 or closeStdin",
));
}
let delta = match params.delta_base64 {
Some(delta_base64) => STANDARD
.decode(delta_base64)
.map_err(|err| invalid_params(format!("invalid deltaBase64: {err}")))?,
None => Vec::new(),
};
self.send_control(
request_id.connection_id,
params.process_handle,
ProcessControl::Write {
delta,
close_stdin: params.close_stdin,
},
)
.await?;
Ok(ProcessWriteStdinResponse {})
}
async fn kill(
&self,
request_id: ConnectionRequestId,
params: ProcessKillParams,
) -> Result<ProcessKillResponse, JSONRPCErrorError> {
self.send_control(
request_id.connection_id,
params.process_handle,
ProcessControl::Kill,
)
.await?;
Ok(ProcessKillResponse {})
}
async fn resize_pty(
&self,
request_id: ConnectionRequestId,
params: ProcessResizePtyParams,
) -> Result<ProcessResizePtyResponse, JSONRPCErrorError> {
self.send_control(
request_id.connection_id,
params.process_handle,
ProcessControl::Resize {
size: terminal_size_from_protocol(params.size)?,
},
)
.await?;
Ok(ProcessResizePtyResponse {})
}
async fn connection_closed(&self, connection_id: ConnectionId) {
let controls = {
let mut sessions = self.sessions.lock().await;
let process_handles = sessions
.keys()
.filter(|process_handle| process_handle.connection_id == connection_id)
.cloned()
.collect::<Vec<_>>();
let mut controls = Vec::with_capacity(process_handles.len());
for process_handle in process_handles {
if let Some(control) = sessions.remove(&process_handle) {
controls.push(control);
}
}
controls
};
for control in controls {
let _ = control
.control_tx
.send(ProcessControlRequest {
control: ProcessControl::Kill,
response_tx: None,
})
.await;
}
}
async fn send_control(
&self,
connection_id: ConnectionId,
process_handle: String,
control: ProcessControl,
) -> Result<(), JSONRPCErrorError> {
let process_key = ConnectionProcessHandle {
connection_id,
process_handle,
};
let session = self
.sessions
.lock()
.await
.get(&process_key)
.cloned()
.ok_or_else(|| no_active_process_error(&process_key.process_handle))?;
let (response_tx, response_rx) = oneshot::channel();
session
.control_tx
.send(ProcessControlRequest {
control,
response_tx: Some(response_tx),
})
.await
.map_err(|_| process_no_longer_running_error(&process_key.process_handle))?;
response_rx
.await
.map_err(|_| process_no_longer_running_error(&process_key.process_handle))?
}
}
async fn run_process(params: RunProcessParams) {
let RunProcessParams {
outgoing,
request_id,
process_handle,
spawned,
control_rx,
stream_stdin,
stream_stdout_stderr,
expiration,
output_bytes_cap,
} = params;
let mut control_rx = control_rx;
let mut control_open = true;
let expiration = expiration.wait_with_outcome();
tokio::pin!(expiration);
let SpawnedProcess {
session,
stdout_rx,
stderr_rx,
exit_rx,
} = spawned;
tokio::pin!(exit_rx);
let mut expiration_outcome = None;
let process_exited = CancellationToken::new();
let stdout_handle = collect_spawn_process_output(SpawnProcessOutputParams {
connection_id: request_id.connection_id,
process_handle: process_handle.clone(),
output_rx: stdout_rx,
reader: session.stdout_reader(),
process_exited: process_exited.clone(),
outgoing: Arc::clone(&outgoing),
stream: ProcessOutputStream::Stdout,
stream_output: stream_stdout_stderr,
output_bytes_cap,
});
let stderr_handle = collect_spawn_process_output(SpawnProcessOutputParams {
connection_id: request_id.connection_id,
process_handle: process_handle.clone(),
output_rx: stderr_rx,
reader: session.stderr_reader(),
process_exited: process_exited.clone(),
outgoing: Arc::clone(&outgoing),
stream: ProcessOutputStream::Stderr,
stream_output: stream_stdout_stderr,
output_bytes_cap,
});
let exit_code = loop {
tokio::select! {
control = control_rx.recv(), if control_open => {
match control {
Some(ProcessControlRequest { control, response_tx }) => {
let result = match control {
ProcessControl::Write { delta, close_stdin } => {
handle_process_write(
&session,
stream_stdin,
delta,
close_stdin,
).await
}
ProcessControl::Resize { size } => {
handle_process_resize(&session, size)
}
ProcessControl::Kill => {
session.request_terminate();
Ok(())
}
};
if let Some(response_tx) = response_tx
&& response_tx.send(result).is_err()
{
tracing::debug!(
process_handle = %process_handle,
"process control response receiver dropped"
);
}
},
None => {
control_open = false;
session.request_terminate();
}
}
}
outcome = &mut expiration, if expiration_outcome.is_none() => {
expiration_outcome = Some(outcome);
session.request_terminate();
}
exit = &mut exit_rx => {
if matches!(expiration_outcome, Some(ExecExpirationOutcome::TimedOut)) {
break EXEC_TIMEOUT_EXIT_CODE;
} else {
break exit.unwrap_or(-1);
}
}
}
};
drop(control_rx);
process_exited.cancel();
let stdout = stdout_handle.await.unwrap_or_default();
let stderr = stderr_handle.await.unwrap_or_default();
outgoing
.send_server_notification_to_connection_and_wait(
request_id.connection_id,
ServerNotification::ProcessExited(ProcessExitedNotification {
process_handle,
exit_code,
output_drain_timed_out: Some(stdout.output_incomplete || stderr.output_incomplete),
stdout: stdout.text,
stdout_cap_reached: stdout.cap_reached,
stderr: stderr.text,
stderr_cap_reached: stderr.cap_reached,
}),
)
.await;
// On older Windows, ClosePseudoConsole can block until surviving clients disconnect.
#[cfg(windows)]
tokio::task::spawn_blocking(move || drop(session));
}
fn collect_spawn_process_output(
params: SpawnProcessOutputParams,
) -> tokio::task::JoinHandle<ProcessOutputCapture> {
let SpawnProcessOutputParams {
connection_id,
process_handle,
mut output_rx,
reader,
process_exited,
outgoing,
stream,
stream_output,
output_bytes_cap,
} = params;
tokio::spawn(async move {
let mut buffer: Vec<u8> = Vec::new();
let mut observed_num_bytes = 0usize;
let mut cap_reached = false;
let mut drain_timed_out = false;
let mut draining = false;
let drain_timer = tokio::time::sleep(Duration::ZERO);
tokio::pin!(drain_timer);
loop {
let chunk = tokio::select! {
biased;
_ = process_exited.cancelled(), if !draining => {
draining = true;
drain_timer.as_mut().reset(Instant::now() + Duration::from_millis(IO_DRAIN_TIMEOUT_MS));
continue;
}
_ = &mut drain_timer, if draining && !output_rx.is_closed() => {
drain_timed_out = !output_rx.is_closed();
output_rx.close();
if let Some(reader) = &reader {
reader.abort();
}
continue;
}
chunk = output_rx.recv() => chunk,
};
let Some(mut chunk) = chunk else { break };
// The byte cap limits delivery. Keep draining until EOF or the post-exit deadline.
if cap_reached {
continue;
}
while chunk.len() < OUTPUT_CHUNK_SIZE_HINT
&& let Ok(next_chunk) = output_rx.try_recv()
{
chunk.extend_from_slice(&next_chunk);
}
let capped_chunk = match output_bytes_cap {
Some(output_bytes_cap) => {
let capped_chunk_len = output_bytes_cap
.saturating_sub(observed_num_bytes)
.min(chunk.len());
observed_num_bytes += capped_chunk_len;
&chunk[0..capped_chunk_len]
}
None => chunk.as_slice(),
};
cap_reached = Some(observed_num_bytes) == output_bytes_cap;
if stream_output {
let write_started = Instant::now();
outgoing
.send_server_notification_to_connection_and_wait(
connection_id,
ServerNotification::ProcessOutputDelta(ProcessOutputDeltaNotification {
process_handle: process_handle.clone(),
stream,
delta_base64: STANDARD.encode(capped_chunk),
cap_reached,
}),
)
.await;
// A slow client can take longer than the pipe drain budget to accept one chunk.
if draining {
let deadline = drain_timer.deadline() + write_started.elapsed();
drain_timer.as_mut().reset(deadline);
}
} else {
buffer.extend_from_slice(capped_chunk);
}
}
ProcessOutputCapture {
text: bytes_to_string_smart(&buffer),
cap_reached,
output_incomplete: drain_timed_out && output_bytes_cap != Some(observed_num_bytes),
}
})
}
async fn handle_process_write(
session: &ProcessHandle,
stream_stdin: bool,
delta: Vec<u8>,
close_stdin: bool,
) -> Result<(), JSONRPCErrorError> {
if !stream_stdin {
return Err(invalid_request(
"stdin streaming is not enabled for this process",
));
}
if !delta.is_empty() {
session
.writer_sender()
.send(delta)
.await
.map_err(|_| invalid_request("stdin is already closed"))?;
}
if close_stdin {
// Closing drops our sender; the writer task still drains any bytes
// accepted above before its receiver observes EOF and closes stdin.
session.close_stdin();
}
Ok(())
}
fn handle_process_resize(
session: &ProcessHandle,
size: TerminalSize,
) -> Result<(), JSONRPCErrorError> {
session
.resize(size)
.map_err(|err| invalid_request(format!("failed to resize PTY: {err}")))
}
fn terminal_size_from_protocol(
size: ProcessTerminalSize,
) -> Result<TerminalSize, JSONRPCErrorError> {
if size.rows == 0 || size.cols == 0 {
return Err(invalid_params(
"process size rows and cols must be greater than 0",
));
}
Ok(TerminalSize {
rows: size.rows,
cols: size.cols,
})
}
fn no_active_process_error(process_handle: &str) -> JSONRPCErrorError {
invalid_request(format!(
"no active process for process handle {process_handle:?}"
))
}
fn process_no_longer_running_error(process_handle: &str) -> JSONRPCErrorError {
invalid_request(format!("process {process_handle:?} is no longer running"))
}
#[cfg(test)]
#[path = "process_exec_processor_tests.rs"]
mod tests;

View File

@@ -0,0 +1,234 @@
//! Coverage for post-exit output delivery over a backpressured connection.
#![cfg(test)]
use super::*;
use crate::outgoing_message::OutgoingEnvelope;
use crate::outgoing_message::OutgoingMessage;
use codex_analytics::AnalyticsEventsClient;
use pretty_assertions::assert_eq;
fn start_collector(
process_exited: CancellationToken,
) -> (
mpsc::Sender<Vec<u8>>,
mpsc::Receiver<OutgoingEnvelope>,
tokio::task::JoinHandle<ProcessOutputCapture>,
) {
let (output_tx, output_rx) = mpsc::channel(2);
let (tx, notifications) = mpsc::channel(1);
let collector = collect_spawn_process_output(SpawnProcessOutputParams {
connection_id: ConnectionId(1),
process_handle: "test".to_string(),
output_rx,
reader: None,
process_exited,
outgoing: Arc::new(OutgoingMessageSender::new(
tx,
AnalyticsEventsClient::disabled(),
)),
stream: ProcessOutputStream::Stdout,
stream_output: true,
output_bytes_cap: None,
});
(output_tx, notifications, collector)
}
async fn read_delta(
notifications: &mut mpsc::Receiver<OutgoingEnvelope>,
) -> (Vec<u8>, oneshot::Sender<()>) {
let Some(OutgoingEnvelope::ToConnection {
message: OutgoingMessage::AppServerNotification(envelope),
write_complete_tx: Some(written),
..
}) = notifications.recv().await
else {
panic!("expected an output notification");
};
let ServerNotification::ProcessOutputDelta(delta) = envelope.notification else {
panic!("expected an output delta");
};
(STANDARD.decode(delta.delta_base64).unwrap(), written)
}
/// A client can take longer than the drain grace to accept each of several final chunks.
#[tokio::test(start_paused = true)]
async fn slow_writes_deliver_the_entire_tail_after_exit() {
let exited = CancellationToken::new();
let (output, mut notifications, collector) = start_collector(exited.clone());
output.send(vec![1]).await.unwrap();
let (first, written) = read_delta(&mut notifications).await;
exited.cancel();
output.send(vec![2]).await.unwrap();
let slow_write = Duration::from_millis(IO_DRAIN_TIMEOUT_MS * 2);
tokio::time::advance(slow_write).await;
written.send(()).unwrap();
let (second, written) = read_delta(&mut notifications).await;
tokio::time::advance(slow_write).await;
// A descendant can still produce bytes while the previous write is blocked.
output.send(vec![3]).await.unwrap();
written.send(()).unwrap();
let (third, written) = read_delta(&mut notifications).await;
drop(output);
written.send(()).unwrap();
assert_eq!([first, second, third], [vec![1], vec![2], vec![3]]);
let capture = collector.await.unwrap();
assert!(!capture.output_incomplete);
}
/// A descendant that holds a pipe open gets one shared grace period across reads.
#[tokio::test(start_paused = true)]
async fn inherited_pipe_does_not_restart_the_grace_period_for_each_chunk() {
let exited = CancellationToken::new();
exited.cancel();
let (output, mut notifications, collector) = start_collector(exited);
tokio::task::yield_now().await;
let grace = Duration::from_millis(IO_DRAIN_TIMEOUT_MS);
tokio::time::advance(grace / 2).await;
output.send(vec![1]).await.unwrap();
let (_, written) = read_delta(&mut notifications).await;
written.send(()).unwrap();
let capture = tokio::time::timeout(grace / 2 + Duration::from_millis(1), collector)
.await
.expect("the collector must finish within the original drain budget")
.unwrap();
assert!(capture.output_incomplete);
}
/// Even a capped stream closes its OS reader on a genuine timeout while its sibling stays open.
#[cfg(unix)]
#[tokio::test]
async fn timed_out_stderr_closes_while_stdout_is_still_open() {
let dir = tempfile::tempdir().unwrap();
let mut child = codex_utils_pty::spawn_pipe_process_no_stdin(
"/bin/sh",
&[
"-c".into(),
concat!(
"printf cap >&2; (while [ ! -f release ]; do sleep 0.05; done; ",
"if dd if=/dev/zero bs=65536 count=32 >&2 2>/dev/null; ",
"then printf open; else printf closed; fi) &",
)
.into(),
],
dir.path(),
&HashMap::new(),
&None,
&[],
)
.await
.unwrap();
let (tx, _notifications) = mpsc::channel(1);
let process_exited = CancellationToken::new();
let collector = collect_spawn_process_output(SpawnProcessOutputParams {
connection_id: ConnectionId(1),
process_handle: "probe".into(),
output_rx: child.stderr_rx,
reader: child.session.stderr_reader(),
process_exited: process_exited.clone(),
outgoing: Arc::new(OutgoingMessageSender::new(
tx,
AnalyticsEventsClient::disabled(),
)),
stream: ProcessOutputStream::Stderr,
stream_output: false,
output_bytes_cap: Some(3),
});
assert_eq!(child.exit_rx.await.unwrap(), 0);
process_exited.cancel();
let capture = collector.await.unwrap();
assert_eq!(capture.text, "cap");
assert!(capture.cap_reached);
assert!(!capture.output_incomplete);
std::fs::write(dir.path().join("release"), b"").unwrap();
let mut stdout = Vec::new();
tokio::time::timeout(Duration::from_secs(10), async {
while let Some(bytes) = child.stdout_rx.recv().await {
stdout.extend(bytes);
}
})
.await
.expect("the descendant must observe the closed stderr pipe");
assert_eq!(stdout, b"closed");
}
/// The client must receive the root's exit while a surviving Windows console child can still run.
#[cfg(windows)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn windows_terminal_reports_exit_before_closing_the_console() {
let dir = tempfile::tempdir().unwrap();
// Bound the lifetime of the descendant even if the server fails to deliver the exit.
std::fs::write(
dir.path().join("child.cmd"),
concat!(
"@echo off\r\n",
"for /l %%i in (1,1,30) do (\r\n",
" if exist received goto ack\r\n",
" ping.exe -n 2 127.0.0.1 >nul\r\n",
")\r\nexit /b 1\r\n:ack\r\ntype nul >acknowledged\r\n",
),
)
.unwrap();
let spawned = codex_utils_pty::spawn_pty_process(
"cmd.exe",
&[
"/d".into(),
"/c".into(),
"echo complete & start /b cmd.exe /d /c child.cmd".into(),
],
dir.path(),
&std::env::vars().collect(),
/*arg0*/ &None,
TerminalSize::default(),
codex_utils_pty::ChildFds::Inherited(&[]),
)
.await
.unwrap();
let (_control_tx, control_rx) = mpsc::channel(1);
let (tx, mut notifications) = mpsc::channel(1);
let process = tokio::spawn(run_process(RunProcessParams {
outgoing: Arc::new(OutgoingMessageSender::new(
tx,
AnalyticsEventsClient::disabled(),
)),
request_id: ConnectionRequestId {
connection_id: ConnectionId(1),
request_id: codex_app_server_protocol::RequestId::Integer(1),
},
process_handle: "console".into(),
spawned,
control_rx,
stream_stdin: true,
stream_stdout_stderr: false,
expiration: ExecExpiration::DefaultTimeout,
output_bytes_cap: None,
}));
let Some(OutgoingEnvelope::ToConnection {
message: OutgoingMessage::AppServerNotification(envelope),
write_complete_tx: Some(written),
..
}) = tokio::time::timeout(Duration::from_secs(15), notifications.recv())
.await
.expect("exit should arrive while the descendant is still attached")
else {
panic!("expected an exit notification")
};
let ServerNotification::ProcessExited(exit) = envelope.notification else {
panic!("expected process/exited");
};
assert_eq!(exit.exit_code, 0);
assert!(exit.stdout.contains("complete"));
assert_eq!(exit.output_drain_timed_out, Some(true));
std::fs::write(dir.path().join("received"), b"").unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while !dir.path().join("acknowledged").exists() {
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.expect("the attached child should still be alive when the client receives process/exited");
written.send(()).unwrap();
process.await.unwrap();
}

View File

@@ -0,0 +1,402 @@
use std::collections::HashSet;
use std::sync::Arc;
use codex_app_server_protocol::ClientResponsePayload;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::Project;
use codex_app_server_protocol::ProjectChangeType;
use codex_app_server_protocol::ProjectChangedNotification;
use codex_app_server_protocol::ProjectCreateParams;
use codex_app_server_protocol::ProjectCreateResponse;
use codex_app_server_protocol::ProjectDeleteParams;
use codex_app_server_protocol::ProjectDeleteResponse;
use codex_app_server_protocol::ProjectImportParams;
use codex_app_server_protocol::ProjectImportResponse;
use codex_app_server_protocol::ProjectListParams;
use codex_app_server_protocol::ProjectListResponse;
use codex_app_server_protocol::ProjectMoveParams;
use codex_app_server_protocol::ProjectMoveResponse;
use codex_app_server_protocol::ProjectReadParams;
use codex_app_server_protocol::ProjectReadResponse;
use codex_app_server_protocol::ProjectRoot;
use codex_app_server_protocol::ProjectSortKey;
use codex_app_server_protocol::ProjectUpdateParams;
use codex_app_server_protocol::ProjectUpdateResponse;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::SortDirection;
use codex_app_server_protocol::ThreadProjectUpdatedNotification;
use codex_thread_store::CreateProjectParams as StoreCreateProjectParams;
use codex_thread_store::ListProjectsParams as StoreListProjectsParams;
use codex_thread_store::MoveProjectParams as StoreMoveProjectParams;
use codex_thread_store::ProjectMoveOutcome;
use codex_thread_store::ProjectSortKey as StoreProjectSortKey;
use codex_thread_store::SortDirection as StoreSortDirection;
use codex_thread_store::StoredProject;
use codex_thread_store::StoredProjectRoot;
use codex_thread_store::ThreadStore;
use codex_thread_store::ThreadStoreError;
use codex_thread_store::UpdateProjectParams as StoreUpdateProjectParams;
use tokio::sync::Semaphore;
use tokio::sync::SemaphorePermit;
use super::thread_processor::THREAD_LIST_DEFAULT_LIMIT;
use super::thread_processor::THREAD_LIST_MAX_LIMIT;
use crate::error_code::internal_error;
use crate::error_code::invalid_params;
use crate::error_code::method_not_found;
use crate::outgoing_message::OutgoingMessageSender;
#[derive(Clone)]
pub(crate) struct ProjectRequestProcessor {
thread_store: Arc<dyn ThreadStore>,
outgoing: Arc<OutgoingMessageSender>,
thread_list_state_permit: Arc<Semaphore>,
}
impl ProjectRequestProcessor {
pub(crate) fn new(
thread_store: Arc<dyn ThreadStore>,
outgoing: Arc<OutgoingMessageSender>,
thread_list_state_permit: Arc<Semaphore>,
) -> Self {
Self {
thread_store,
outgoing,
thread_list_state_permit,
}
}
pub(crate) async fn project_list(
&self,
params: ProjectListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
if params.sort_key.is_none() && params.sort_direction.is_some() {
return Err(invalid_params("sortDirection requires sortKey"));
}
let sort_key = match params.sort_key.unwrap_or(ProjectSortKey::Position) {
ProjectSortKey::Position => StoreProjectSortKey::Position,
ProjectSortKey::RecencyAt => StoreProjectSortKey::RecencyAt,
};
let sort_direction = match params.sort_direction {
Some(SortDirection::Asc) => StoreSortDirection::Asc,
Some(SortDirection::Desc) => StoreSortDirection::Desc,
None => match sort_key {
StoreProjectSortKey::Position => StoreSortDirection::Asc,
StoreProjectSortKey::RecencyAt => StoreSortDirection::Desc,
},
};
let page = self
.thread_store
.list_projects(StoreListProjectsParams {
cursor: params.cursor,
sort_key,
sort_direction,
limit: params
.limit
.map(|limit| limit as usize)
.unwrap_or(THREAD_LIST_DEFAULT_LIMIT)
.clamp(1, THREAD_LIST_MAX_LIMIT),
})
.await
.map_err(|error| project_store_error("project/list", error))?;
Ok(Some(
ProjectListResponse {
data: page
.projects
.into_iter()
.map(api_project)
.collect::<Result<_, _>>()?,
next_cursor: page.next_cursor,
}
.into(),
))
}
pub(crate) async fn project_read(
&self,
params: ProjectReadParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let project = self
.thread_store
.read_project(params.project_id.clone())
.await
.map_err(|error| project_store_error("project/read", error))?
.ok_or_else(|| invalid_params(format!("project not found: {}", params.project_id)))?;
Ok(Some(
ProjectReadResponse {
project: api_project(project)?,
}
.into(),
))
}
pub(crate) async fn project_create(
&self,
params: ProjectCreateParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let (project, created, _) = self
.create_project(
params.name,
params.roots,
params.metadata,
Vec::new(),
params.idempotency_key,
"project/create",
)
.await?;
if created {
self.notify_project_changed(&project.id, ProjectChangeType::Created)
.await;
}
Ok(Some(ProjectCreateResponse { project }.into()))
}
pub(crate) async fn project_import(
&self,
params: ProjectImportParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let _thread_list_state_permit = self.acquire_thread_list_state_permit().await?;
let (project, created, thread_ids) = self
.create_project(
params.name,
params.roots,
params.metadata,
params.threads.unwrap_or_default(),
params.idempotency_key,
"project/import",
)
.await?;
if created {
self.notify_project_changed(&project.id, ProjectChangeType::Created)
.await;
self.notify_thread_projects(thread_ids, Some(project.id.clone()))
.await;
}
Ok(Some(ProjectImportResponse { project }.into()))
}
pub(crate) async fn project_update(
&self,
params: ProjectUpdateParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let name = params.name.map(validate_name).transpose()?;
let roots = params.roots.map(validate_roots).transpose()?;
let updated = self
.thread_store
.update_project(StoreUpdateProjectParams {
project_id: params.project_id.clone(),
name,
roots,
metadata: params.metadata,
})
.await
.map_err(|error| project_store_error("project/update", error))?
.ok_or_else(|| invalid_params(format!("project not found: {}", params.project_id)))?;
let project = api_project(updated.project)?;
if updated.changed {
self.notify_project_changed(&project.id, ProjectChangeType::Updated)
.await;
}
Ok(Some(ProjectUpdateResponse { project }.into()))
}
pub(crate) async fn project_move(
&self,
params: ProjectMoveParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let project_id = params.project_id;
let outcome = self
.thread_store
.move_project(StoreMoveProjectParams {
project_id: project_id.clone(),
before_project_id: params.before_project_id,
})
.await
.map_err(|error| project_store_error("project/move", error))?
.ok_or_else(|| invalid_params(format!("project not found: {project_id}")))?;
if outcome == ProjectMoveOutcome::Moved {
self.notify_project_changed(&project_id, ProjectChangeType::Updated)
.await;
}
Ok(Some(ProjectMoveResponse {}.into()))
}
pub(crate) async fn project_delete(
&self,
params: ProjectDeleteParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let _thread_list_state_permit = self.acquire_thread_list_state_permit().await?;
let deleted = self
.thread_store
.delete_project(params.project_id.clone())
.await
.map_err(|error| project_store_error("project/delete", error))?
.ok_or_else(|| invalid_params(format!("project not found: {}", params.project_id)))?;
self.notify_project_changed(&params.project_id, ProjectChangeType::Deleted)
.await;
self.notify_thread_projects(deleted.affected_active_thread_ids, /*project_id*/ None)
.await;
Ok(Some(ProjectDeleteResponse {}.into()))
}
async fn create_project(
&self,
name: String,
roots: Vec<ProjectRoot>,
metadata: Option<std::collections::BTreeMap<String, String>>,
thread_ids: Vec<String>,
idempotency_key: String,
operation: &'static str,
) -> Result<(Project, bool, Vec<String>), JSONRPCErrorError> {
let idempotency_key = validate_idempotency_key(idempotency_key)?;
let thread_ids = validate_thread_ids(thread_ids)?;
let created = self
.thread_store
.create_project(StoreCreateProjectParams {
name: validate_name(name)?,
roots: validate_roots(roots)?,
metadata: metadata.unwrap_or_default(),
thread_ids: thread_ids.clone(),
idempotency_key,
})
.await
.map_err(|error| project_store_error(operation, error))?;
Ok((api_project(created.project)?, created.created, thread_ids))
}
async fn notify_project_changed(&self, project_id: &str, change_type: ProjectChangeType) {
self.outgoing
.send_server_notification(ServerNotification::ProjectChanged(
ProjectChangedNotification {
project_id: project_id.to_string(),
change_type,
},
))
.await;
}
async fn notify_thread_projects(&self, thread_ids: Vec<String>, project_id: Option<String>) {
for thread_id in thread_ids {
self.outgoing
.send_server_notification(ServerNotification::ThreadProjectUpdated(
ThreadProjectUpdatedNotification {
thread_id,
project_id: project_id.clone(),
},
))
.await;
}
}
async fn acquire_thread_list_state_permit(
&self,
) -> Result<SemaphorePermit<'_>, JSONRPCErrorError> {
self.thread_list_state_permit
.acquire()
.await
.map_err(|err| {
internal_error(format!("failed to acquire thread list state permit: {err}"))
})
}
}
fn validate_name(name: String) -> Result<String, JSONRPCErrorError> {
let name = name.trim().to_string();
if name.is_empty() {
return Err(invalid_params("project name must not be empty"));
}
Ok(name)
}
fn validate_idempotency_key(key: String) -> Result<String, JSONRPCErrorError> {
if key.trim().is_empty() {
return Err(invalid_params("idempotencyKey must not be empty"));
}
if key.len() > 512 {
return Err(invalid_params("idempotencyKey must be at most 512 bytes"));
}
Ok(key)
}
fn validate_roots(roots: Vec<ProjectRoot>) -> Result<Vec<StoredProjectRoot>, JSONRPCErrorError> {
let mut logical = HashSet::new();
let mut canonical = HashSet::new();
roots
.into_iter()
.map(|root| {
let path = codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path_checked(
root.path.into_path_buf(),
)
.map_err(|error| invalid_params(format!("invalid project root: {error}")))?
.into_path_buf();
if !logical.insert(path.clone()) {
return Err(invalid_params(format!(
"duplicate project root: {}",
path.display()
)));
}
if let Ok(resolved) = std::fs::canonicalize(&path)
&& !canonical.insert(resolved)
{
return Err(invalid_params(format!(
"duplicate resolved project root: {}",
path.display()
)));
}
Ok(StoredProjectRoot {
path: path.display().to_string(),
})
})
.collect()
}
fn validate_thread_ids(thread_ids: Vec<String>) -> Result<Vec<String>, JSONRPCErrorError> {
let mut seen = HashSet::new();
for thread_id in &thread_ids {
if !seen.insert(thread_id.clone()) {
return Err(invalid_params(format!("duplicate thread id: {thread_id}")));
}
}
Ok(thread_ids)
}
fn api_project(project: StoredProject) -> Result<Project, JSONRPCErrorError> {
Ok(Project {
id: project.id,
name: project.name,
roots: project
.roots
.into_iter()
.map(|root| {
Ok(ProjectRoot {
path: codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path(root.path)
.map_err(|error| {
internal_error(format!("stored project root is not absolute: {error}"))
})?,
})
})
.collect::<Result<_, JSONRPCErrorError>>()?,
metadata: project.metadata,
position: project.position,
created_at: project.created_at_ms / 1000,
updated_at: project.updated_at_ms / 1000,
recency_at: project
.recency_at_ms
.map(|timestamp| timestamp.div_euclid(/*rhs*/ 1000)),
})
}
fn project_store_error(operation: &'static str, error: ThreadStoreError) -> JSONRPCErrorError {
match error {
ThreadStoreError::Unsupported { .. } => {
method_not_found(format!("{operation} is unavailable without sqlite state"))
}
ThreadStoreError::InvalidRequest { message } => invalid_params(message),
ThreadStoreError::Internal { message }
if message.contains("thread not found") || message.contains("project not found") =>
{
invalid_params(message)
}
error => internal_error(format!("failed to run {operation}: {error}")),
}
}

View File

@@ -0,0 +1,239 @@
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use crate::transport::RemoteControlEnableError;
use crate::transport::RemoteControlHandle;
use crate::transport::RemoteControlUnavailable;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::RemoteControlClientsListParams;
use codex_app_server_protocol::RemoteControlClientsListResponse;
use codex_app_server_protocol::RemoteControlClientsRevokeParams;
use codex_app_server_protocol::RemoteControlClientsRevokeResponse;
use codex_app_server_protocol::RemoteControlDisableResponse;
use codex_app_server_protocol::RemoteControlEnableResponse;
use codex_app_server_protocol::RemoteControlPairingStartParams;
use codex_app_server_protocol::RemoteControlPairingStartResponse;
use codex_app_server_protocol::RemoteControlPairingStatusParams;
use codex_app_server_protocol::RemoteControlPairingStatusResponse;
use codex_app_server_protocol::RemoteControlStatusReadResponse;
use codex_core::path_utils::write_atomically;
use serde_json::Map;
use serde_json::Value;
use std::fs;
use std::fs::OpenOptions;
use std::fs::TryLockError;
use std::io;
use std::path::PathBuf;
#[derive(Clone)]
pub(crate) struct RemoteControlRequestProcessor {
remote_control_handle: Option<RemoteControlHandle>,
pub(crate) daemon_settings_file: Option<PathBuf>,
}
impl RemoteControlRequestProcessor {
pub(crate) fn new(remote_control_handle: Option<RemoteControlHandle>) -> Self {
Self {
remote_control_handle,
daemon_settings_file: None,
}
}
pub(crate) async fn enable(
&self,
ephemeral: bool,
app_server_client_name: Option<&str>,
) -> Result<RemoteControlEnableResponse, JSONRPCErrorError> {
let handle = self.handle()?;
let status = if ephemeral {
handle.enable_ephemeral().map_err(map_enable_error)?
} else {
handle
.enable(app_server_client_name)
.await
.map_err(map_update_error)?
};
if !ephemeral {
self.persist_daemon_preference(/*enabled*/ true)
.await
.map_err(map_update_error)?;
}
Ok(RemoteControlEnableResponse::from(status))
}
pub(crate) async fn disable(
&self,
ephemeral: bool,
app_server_client_name: Option<&str>,
) -> Result<RemoteControlDisableResponse, JSONRPCErrorError> {
let handle = self.handle()?;
let status = if ephemeral {
handle.disable_ephemeral().await
} else {
handle
.disable(app_server_client_name)
.await
.map_err(map_update_error)?
};
if !ephemeral {
self.persist_daemon_preference(/*enabled*/ false)
.await
.map_err(map_update_error)?;
}
Ok(RemoteControlDisableResponse::from(status))
}
async fn persist_daemon_preference(&self, enabled: bool) -> io::Result<()> {
let Some(path) = self.daemon_settings_file.clone() else {
return Ok(());
};
tokio::task::spawn_blocking(move || {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let lock = OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(path.with_file_name("daemon.lock"))?;
// The daemon may be waiting for this RPC during shutdown. Never wait
// for it: a concurrent lifecycle operation wins over RPC persistence.
match lock.try_lock() {
Ok(()) => {}
Err(TryLockError::WouldBlock) => return Ok(()),
Err(TryLockError::Error(err)) => return Err(err),
}
let mut settings: Map<String, Value> = match fs::read(&path) {
Ok(contents) => serde_json::from_slice(&contents)?,
Err(err) if err.kind() == io::ErrorKind::NotFound => Map::new(),
Err(err) => return Err(err),
};
settings.insert("remoteControlEnabled".to_string(), Value::Bool(enabled));
write_atomically(&path, &serde_json::to_string_pretty(&settings)?)
})
.await
.map_err(io::Error::other)?
}
pub(crate) fn status_read(&self) -> Result<RemoteControlStatusReadResponse, JSONRPCErrorError> {
let status = self.handle()?.status();
Ok(RemoteControlStatusReadResponse {
status: status.status,
server_name: status.server_name,
installation_id: status.installation_id,
environment_id: status.environment_id,
})
}
pub(crate) async fn pairing_start(
&self,
params: RemoteControlPairingStartParams,
app_server_client_name: Option<&str>,
) -> Result<RemoteControlPairingStartResponse, JSONRPCErrorError> {
self.handle()?
.start_pairing(params, app_server_client_name)
.await
.map_err(map_pairing_start_error)
}
pub(crate) async fn pairing_status(
&self,
params: RemoteControlPairingStatusParams,
) -> Result<RemoteControlPairingStatusResponse, JSONRPCErrorError> {
validate_pairing_status_params(&params)?;
let handle = self.handle()?;
handle
.pairing_status(params)
.await
.map_err(map_pairing_start_error)
}
pub(crate) async fn clients_list(
&self,
params: RemoteControlClientsListParams,
) -> Result<RemoteControlClientsListResponse, JSONRPCErrorError> {
self.handle()?
.list_clients(params)
.await
.map_err(map_client_management_error)
}
pub(crate) async fn clients_revoke(
&self,
params: RemoteControlClientsRevokeParams,
) -> Result<RemoteControlClientsRevokeResponse, JSONRPCErrorError> {
self.handle()?
.revoke_client(params)
.await
.map_err(map_client_management_error)
}
fn handle(&self) -> Result<&RemoteControlHandle, JSONRPCErrorError> {
let handle = self
.remote_control_handle
.as_ref()
.ok_or_else(|| internal_error("remote control is unavailable for this app-server"))?;
handle
.ensure_remote_control_allowed()
.map_err(|err| invalid_request(err.to_string()))?;
Ok(handle)
}
}
fn map_enable_error(err: RemoteControlEnableError) -> JSONRPCErrorError {
match err {
RemoteControlEnableError::Unavailable(err) => map_unavailable(err),
RemoteControlEnableError::DisabledByRequirements(err) => invalid_request(err.to_string()),
RemoteControlEnableError::AuthenticationChanged => internal_error(err.to_string()),
}
}
fn map_unavailable(err: RemoteControlUnavailable) -> JSONRPCErrorError {
invalid_request(err.to_string())
}
fn map_update_error(err: io::Error) -> JSONRPCErrorError {
if matches!(
err.kind(),
io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied
) {
invalid_request(err.to_string())
} else {
internal_error(err.to_string())
}
}
fn map_pairing_start_error(err: io::Error) -> JSONRPCErrorError {
if err.kind() == io::ErrorKind::InvalidInput {
invalid_request(err.to_string())
} else {
internal_error(err.to_string())
}
}
fn validate_pairing_status_params(
params: &RemoteControlPairingStatusParams,
) -> Result<(), JSONRPCErrorError> {
match (&params.pairing_code, &params.manual_pairing_code) {
(Some(_), None) | (None, Some(_)) => Ok(()),
(Some(_), Some(_)) => Err(invalid_request(
"remoteControl/pairing/status accepts either pairingCode or manualPairingCode, not both",
)),
(None, None) => Err(invalid_request(
"remoteControl/pairing/status requires pairingCode or manualPairingCode",
)),
}
}
fn map_client_management_error(err: io::Error) -> JSONRPCErrorError {
match err.kind() {
io::ErrorKind::InvalidInput
| io::ErrorKind::NotFound
| io::ErrorKind::PermissionDenied
| io::ErrorKind::WouldBlock => invalid_request(err.to_string()),
_ => internal_error(err.to_string()),
}
}
#[cfg(test)]
mod remote_control_processor_tests;

View File

@@ -0,0 +1,135 @@
use super::*;
use crate::error_code::INTERNAL_ERROR_CODE;
use crate::error_code::INVALID_REQUEST_ERROR_CODE;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn pairing_start_returns_internal_error_when_remote_control_is_unavailable() {
let err = RemoteControlRequestProcessor::new(/*remote_control_handle*/ None)
.pairing_start(
RemoteControlPairingStartParams::default(),
/*app_server_client_name*/ None,
)
.await
.expect_err("missing remote control should fail pairing");
assert_eq!(
err,
JSONRPCErrorError {
code: INTERNAL_ERROR_CODE,
data: None,
message: "remote control is unavailable for this app-server".to_string(),
}
);
}
#[tokio::test]
async fn pairing_status_returns_internal_error_when_remote_control_is_unavailable() {
let err = RemoteControlRequestProcessor::new(/*remote_control_handle*/ None)
.pairing_status(RemoteControlPairingStatusParams {
pairing_code: Some("pairing-code".to_string()),
manual_pairing_code: None,
})
.await
.expect_err("missing remote control should fail pairing status");
assert_eq!(
err,
JSONRPCErrorError {
code: INTERNAL_ERROR_CODE,
data: None,
message: "remote control is unavailable for this app-server".to_string(),
}
);
}
#[test]
fn pairing_status_rejects_missing_pairing_codes() {
assert_eq!(
validate_pairing_status_params(&RemoteControlPairingStatusParams {
pairing_code: None,
manual_pairing_code: None,
}),
Err(JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
data: None,
message: "remoteControl/pairing/status requires pairingCode or manualPairingCode"
.to_string(),
})
);
}
#[test]
fn pairing_status_rejects_conflicting_pairing_codes() {
assert_eq!(
validate_pairing_status_params(&RemoteControlPairingStatusParams {
pairing_code: Some("pairing-code".to_string()),
manual_pairing_code: Some("ABCD-EFGH".to_string()),
}),
Err(JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
data: None,
message:
"remoteControl/pairing/status accepts either pairingCode or manualPairingCode, not both"
.to_string(),
})
);
}
#[test]
fn pairing_start_maps_invalid_input_to_invalid_request() {
assert_eq!(
map_pairing_start_error(io::Error::new(
io::ErrorKind::InvalidInput,
"remote control pairing is unavailable",
)),
JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
data: None,
message: "remote control pairing is unavailable".to_string(),
}
);
}
#[test]
fn pairing_start_maps_backend_failures_to_internal_error() {
assert_eq!(
map_pairing_start_error(io::Error::other("remote control pairing failed")),
JSONRPCErrorError {
code: INTERNAL_ERROR_CODE,
data: None,
message: "remote control pairing failed".to_string(),
}
);
}
#[test]
fn client_management_maps_user_actionable_errors_to_invalid_request() {
for kind in [
io::ErrorKind::InvalidInput,
io::ErrorKind::NotFound,
io::ErrorKind::PermissionDenied,
io::ErrorKind::WouldBlock,
] {
assert_eq!(
map_client_management_error(io::Error::new(kind, "client management unavailable")),
JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
data: None,
message: "client management unavailable".to_string(),
}
);
}
}
#[test]
fn client_management_maps_backend_failures_to_internal_error() {
assert_eq!(
map_client_management_error(io::Error::other("client management failed")),
JSONRPCErrorError {
code: INTERNAL_ERROR_CODE,
data: None,
message: "client management failed".to_string(),
}
);
}

View File

@@ -0,0 +1,9 @@
use super::*;
use codex_protocol::error::CodexErrorDetails;
pub(super) fn environment_selection_error(err: CodexErr) -> JSONRPCErrorError {
match err.details() {
CodexErrorDetails::InvalidRequest(message) => invalid_request(message.clone()),
_ => internal_error(format!("failed to validate environment selections: {err}")),
}
}

View File

@@ -0,0 +1,24 @@
//! Triggers local rollout maintenance without waiting for the background pass.
use super::ThreadRequestProcessor;
use super::thread_processor::unsupported_thread_store_operation;
use codex_app_server_protocol::ClientResponsePayload;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::RolloutCompressResponse;
use codex_thread_store::LocalThreadStore;
impl ThreadRequestProcessor {
pub(crate) fn rollout_compress(
&self,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
if !self.thread_store.as_any().is::<LocalThreadStore>() {
return Err(unsupported_thread_store_operation("rollout/compress"));
}
codex_rollout::spawn_rollout_compression_worker(
self.config.codex_home.to_path_buf(),
codex_rollout::RolloutCompressionTrigger::Rpc,
);
Ok(Some(RolloutCompressResponse {}.into()))
}
}

View File

@@ -0,0 +1,134 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use crate::fuzzy_file_search::FuzzyFileSearchSession;
use crate::fuzzy_file_search::run_fuzzy_file_search;
use crate::fuzzy_file_search::start_fuzzy_file_search_session;
use crate::outgoing_message::OutgoingMessageSender;
use codex_app_server_protocol::FuzzyFileSearchParams;
use codex_app_server_protocol::FuzzyFileSearchResponse;
use codex_app_server_protocol::FuzzyFileSearchSessionStartParams;
use codex_app_server_protocol::FuzzyFileSearchSessionStartResponse;
use codex_app_server_protocol::FuzzyFileSearchSessionStopParams;
use codex_app_server_protocol::FuzzyFileSearchSessionStopResponse;
use codex_app_server_protocol::FuzzyFileSearchSessionUpdateParams;
use codex_app_server_protocol::FuzzyFileSearchSessionUpdateResponse;
use codex_app_server_protocol::JSONRPCErrorError;
use tokio::sync::Mutex;
#[derive(Clone)]
pub(crate) struct SearchRequestProcessor {
outgoing: Arc<OutgoingMessageSender>,
pending_fuzzy_searches: Arc<Mutex<HashMap<String, Arc<AtomicBool>>>>,
fuzzy_search_sessions: Arc<Mutex<HashMap<String, FuzzyFileSearchSession>>>,
}
impl SearchRequestProcessor {
pub(crate) fn new(outgoing: Arc<OutgoingMessageSender>) -> Self {
Self {
outgoing,
pending_fuzzy_searches: Arc::new(Mutex::new(HashMap::new())),
fuzzy_search_sessions: Arc::new(Mutex::new(HashMap::new())),
}
}
pub(crate) async fn fuzzy_file_search(
&self,
params: FuzzyFileSearchParams,
) -> Result<FuzzyFileSearchResponse, JSONRPCErrorError> {
let FuzzyFileSearchParams {
query,
roots,
cancellation_token,
} = params;
let cancel_flag = match cancellation_token.clone() {
Some(token) => {
let mut pending_fuzzy_searches = self.pending_fuzzy_searches.lock().await;
// if a cancellation_token is provided and a pending_request exists for
// that token, cancel it
if let Some(existing) = pending_fuzzy_searches.get(&token) {
existing.store(true, Ordering::Relaxed);
}
let flag = Arc::new(AtomicBool::new(false));
pending_fuzzy_searches.insert(token.clone(), flag.clone());
flag
}
None => Arc::new(AtomicBool::new(false)),
};
let results = match query.as_str() {
"" => vec![],
_ => run_fuzzy_file_search(query, roots, cancel_flag.clone()).await,
};
if let Some(token) = cancellation_token {
let mut pending_fuzzy_searches = self.pending_fuzzy_searches.lock().await;
if let Some(current_flag) = pending_fuzzy_searches.get(&token)
&& Arc::ptr_eq(current_flag, &cancel_flag)
{
pending_fuzzy_searches.remove(&token);
}
}
Ok(FuzzyFileSearchResponse { files: results })
}
pub(crate) async fn fuzzy_file_search_session_start_response(
&self,
params: FuzzyFileSearchSessionStartParams,
) -> Result<FuzzyFileSearchSessionStartResponse, JSONRPCErrorError> {
let FuzzyFileSearchSessionStartParams { session_id, roots } = params;
if session_id.is_empty() {
return Err(invalid_request("sessionId must not be empty"));
}
let session =
start_fuzzy_file_search_session(session_id.clone(), roots, self.outgoing.clone())
.map_err(|err| {
internal_error(format!("failed to start fuzzy file search session: {err}"))
})?;
self.fuzzy_search_sessions
.lock()
.await
.insert(session_id, session);
Ok(FuzzyFileSearchSessionStartResponse {})
}
pub(crate) async fn fuzzy_file_search_session_update_response(
&self,
params: FuzzyFileSearchSessionUpdateParams,
) -> Result<FuzzyFileSearchSessionUpdateResponse, JSONRPCErrorError> {
let FuzzyFileSearchSessionUpdateParams { session_id, query } = params;
let found = {
let sessions = self.fuzzy_search_sessions.lock().await;
if let Some(session) = sessions.get(&session_id) {
session.update_query(query);
true
} else {
false
}
};
if !found {
return Err(invalid_request(format!(
"fuzzy file search session not found: {session_id}"
)));
}
Ok(FuzzyFileSearchSessionUpdateResponse {})
}
pub(crate) async fn fuzzy_file_search_session_stop(
&self,
params: FuzzyFileSearchSessionStopParams,
) -> Result<FuzzyFileSearchSessionStopResponse, JSONRPCErrorError> {
let FuzzyFileSearchSessionStopParams { session_id } = params;
self.fuzzy_search_sessions.lock().await.remove(&session_id);
Ok(FuzzyFileSearchSessionStopResponse {})
}
}

View File

@@ -0,0 +1,294 @@
//! Attachment RPC handling; committed mutations respond before broadcasting updates.
use super::thread_processor::THREAD_LIST_DEFAULT_LIMIT;
use super::thread_processor::ThreadRequestProcessor;
use crate::error_code::internal_error;
use crate::error_code::invalid_params;
use crate::error_code::method_not_found;
use crate::outgoing_message::ConnectionRequestId;
use codex_app_server_protocol::ClientResponsePayload;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadAttachment;
use codex_app_server_protocol::ThreadAttachmentAddOutcome;
use codex_app_server_protocol::ThreadAttachmentAddParams;
use codex_app_server_protocol::ThreadAttachmentAddResponse;
use codex_app_server_protocol::ThreadAttachmentListParams;
use codex_app_server_protocol::ThreadAttachmentListResponse;
use codex_app_server_protocol::ThreadAttachmentOperation;
use codex_app_server_protocol::ThreadAttachmentOwner;
use codex_app_server_protocol::ThreadAttachmentOwnerListParams;
use codex_app_server_protocol::ThreadAttachmentOwnerListResponse;
use codex_app_server_protocol::ThreadAttachmentRemoveParams;
use codex_app_server_protocol::ThreadAttachmentRemoveResponse;
use codex_app_server_protocol::ThreadAttachmentUpdatedNotification;
use codex_protocol::ThreadId;
use codex_state::MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES;
use codex_state::MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE;
use codex_state::MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES;
use codex_state::MAX_THREAD_ATTACHMENT_TYPE_BYTES;
use codex_thread_store::AddThreadAttachmentOutcome;
use codex_thread_store::AddThreadAttachmentParams;
use codex_thread_store::ListThreadAttachmentThreadsParams;
use codex_thread_store::ListThreadAttachmentsParams;
use codex_thread_store::RemoveThreadAttachmentOutcome;
use codex_thread_store::RemoveThreadAttachmentParams;
use codex_thread_store::ThreadAttachment as StoredThreadAttachment;
use codex_thread_store::ThreadAttachmentArchiveFilter;
use codex_thread_store::ThreadStoreError;
impl ThreadRequestProcessor {
pub(crate) async fn thread_attachment_add(
&self,
request_id: ConnectionRequestId,
params: ThreadAttachmentAddParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
const OPERATION: &str = "thread/attachment/add";
self.ensure_thread_attachments_supported(OPERATION)?;
validate_attachment_identity(&params.attachment_type, &params.identity_key)?;
let payload_bytes = serde_json::to_vec(&params.payload)
.map_err(|error| invalid_params(format!("invalid attachment payload: {error}")))?;
if payload_bytes.len() > MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES {
return Err(invalid_params(format!(
"attachment payload must not exceed {MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES} bytes"
)));
}
let thread_id = parse_attachment_thread_id(&params.thread_id)?;
let result = self
.thread_store
.add_thread_attachment(AddThreadAttachmentParams {
thread_id,
attachment_type: params.attachment_type,
identity_key: params.identity_key,
payload: params.payload,
})
.await
.map_err(|error| thread_attachment_store_error(OPERATION, error))?;
let (response, notification) = match result {
AddThreadAttachmentOutcome::Created(attachment) => {
let notification = ThreadAttachmentUpdatedNotification {
thread_id: attachment.thread_id.to_string(),
attachment_type: attachment.attachment_type.clone(),
identity_key: attachment.identity_key.clone(),
attachment_id: attachment.id.clone(),
operation: ThreadAttachmentOperation::Created,
};
(
ThreadAttachmentAddResponse {
outcome: ThreadAttachmentAddOutcome::Created,
attachment: api_thread_attachment(attachment),
},
Some(notification),
)
}
AddThreadAttachmentOutcome::Existing(attachment) => (
ThreadAttachmentAddResponse {
outcome: ThreadAttachmentAddOutcome::Existing,
attachment: api_thread_attachment(attachment),
},
None,
),
};
self.outgoing.send_response(request_id, response).await;
if let Some(notification) = notification {
self.outgoing
.send_server_notification(ServerNotification::ThreadAttachmentUpdated(notification))
.await;
}
Ok(None)
}
pub(crate) async fn thread_attachment_list(
&self,
params: ThreadAttachmentListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
const OPERATION: &str = "thread/attachment/list";
self.ensure_thread_attachments_supported(OPERATION)?;
let thread_id = parse_attachment_thread_id(&params.thread_id)?;
let limit = params
.limit
.map(|limit| limit as usize)
.unwrap_or(THREAD_LIST_DEFAULT_LIMIT)
.clamp(1, MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE);
let page = self
.thread_store
.list_thread_attachments(ListThreadAttachmentsParams {
thread_id,
cursor: params.cursor,
limit,
})
.await
.map_err(|error| thread_attachment_store_error(OPERATION, error))?;
Ok(Some(
ThreadAttachmentListResponse {
data: page
.attachments
.into_iter()
.map(api_thread_attachment)
.collect(),
next_cursor: page.next_cursor,
}
.into(),
))
}
pub(crate) async fn thread_attachment_owner_list(
&self,
params: ThreadAttachmentOwnerListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
const OPERATION: &str = "thread/attachmentOwner/list";
self.ensure_thread_attachments_supported(OPERATION)?;
validate_attachment_identity(&params.attachment_type, &params.identity_key)?;
let limit = params
.limit
.map(|limit| limit as usize)
.unwrap_or(THREAD_LIST_DEFAULT_LIMIT)
.clamp(1, MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE);
let page = self
.thread_store
.list_thread_attachment_threads(ListThreadAttachmentThreadsParams {
attachment_type: params.attachment_type,
identity_key: params.identity_key,
archive_filter: match params.archived {
None => ThreadAttachmentArchiveFilter::All,
Some(false) => ThreadAttachmentArchiveFilter::NonArchived,
Some(true) => ThreadAttachmentArchiveFilter::Archived,
},
cursor: params.cursor,
limit,
})
.await
.map_err(|error| thread_attachment_store_error(OPERATION, error))?;
Ok(Some(
ThreadAttachmentOwnerListResponse {
data: page
.threads
.into_iter()
.map(|thread| ThreadAttachmentOwner {
thread_id: thread.thread_id.to_string(),
archived: thread.archived,
})
.collect(),
next_cursor: page.next_cursor,
}
.into(),
))
}
pub(crate) async fn thread_attachment_remove(
&self,
request_id: ConnectionRequestId,
params: ThreadAttachmentRemoveParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
const OPERATION: &str = "thread/attachment/remove";
self.ensure_thread_attachments_supported(OPERATION)?;
validate_attachment_identity(&params.attachment_type, &params.identity_key)?;
let thread_id = parse_attachment_thread_id(&params.thread_id)?;
let result = self
.thread_store
.remove_thread_attachment(RemoveThreadAttachmentParams {
thread_id,
attachment_type: params.attachment_type,
identity_key: params.identity_key,
})
.await
.map_err(|error| thread_attachment_store_error(OPERATION, error))?;
self.outgoing
.send_response(request_id, ThreadAttachmentRemoveResponse {})
.await;
if let RemoveThreadAttachmentOutcome::Removed(attachment) = result {
self.outgoing
.send_server_notification(ServerNotification::ThreadAttachmentUpdated(
ThreadAttachmentUpdatedNotification {
thread_id: attachment.thread_id.to_string(),
attachment_type: attachment.attachment_type,
identity_key: attachment.identity_key,
attachment_id: attachment.id,
operation: ThreadAttachmentOperation::Deleted,
},
))
.await;
}
Ok(None)
}
fn ensure_thread_attachments_supported(
&self,
operation: &'static str,
) -> Result<(), JSONRPCErrorError> {
if self.thread_store.supports_thread_attachments() {
Ok(())
} else {
Err(unsupported_thread_attachment_operation(operation))
}
}
}
fn validate_attachment_identity(
attachment_type: &str,
identity_key: &str,
) -> Result<(), JSONRPCErrorError> {
if attachment_type.trim().is_empty() {
return Err(invalid_params("attachmentType must not be empty"));
}
if attachment_type.len() > MAX_THREAD_ATTACHMENT_TYPE_BYTES {
return Err(invalid_params(format!(
"attachmentType must not exceed {MAX_THREAD_ATTACHMENT_TYPE_BYTES} bytes"
)));
}
if identity_key.trim().is_empty() {
return Err(invalid_params("identityKey must not be empty"));
}
if identity_key.len() > MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES {
return Err(invalid_params(format!(
"identityKey must not exceed {MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES} bytes"
)));
}
Ok(())
}
fn parse_attachment_thread_id(thread_id: &str) -> Result<ThreadId, JSONRPCErrorError> {
ThreadId::from_string(thread_id)
.map_err(|error| invalid_params(format!("invalid thread id: {error}")))
}
fn api_thread_attachment(attachment: StoredThreadAttachment) -> ThreadAttachment {
ThreadAttachment {
id: attachment.id,
attachment_type: attachment.attachment_type,
identity_key: attachment.identity_key,
payload: attachment.payload,
created_at: attachment.created_at,
}
}
fn unsupported_thread_attachment_operation(operation: &'static str) -> JSONRPCErrorError {
method_not_found(format!(
"{operation} is not supported by the configured thread store"
))
}
fn thread_attachment_store_error(
operation: &'static str,
error: ThreadStoreError,
) -> JSONRPCErrorError {
match error {
ThreadStoreError::Unsupported { .. } => unsupported_thread_attachment_operation(operation),
ThreadStoreError::InvalidRequest { message } => invalid_params(message),
ThreadStoreError::ThreadNotFound { thread_id } => {
invalid_params(format!("thread not found: {thread_id}"))
}
error @ (ThreadStoreError::Conflict { .. }
| ThreadStoreError::Retryable { .. }
| ThreadStoreError::OutcomeUnknown { .. }
| ThreadStoreError::Internal { .. }) => {
internal_error(format!("failed to process {operation}: {error}"))
}
}
}

View File

@@ -0,0 +1,163 @@
//! `thread/delete` request handling.
use super::thread_processor::unsupported_thread_store_operation;
use super::*;
impl ThreadRequestProcessor {
pub(crate) async fn thread_delete(
&self,
request_id: ConnectionRequestId,
params: ThreadDeleteParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let mut deleted_thread_ids = Vec::new();
let result = {
let _thread_list_state_permit = self.acquire_thread_list_state_permit().await?;
self.thread_delete_response(params, &mut deleted_thread_ids)
.await
};
match result {
Ok(response) => {
self.outgoing
.send_response(request_id.clone(), response)
.await;
self.send_thread_deleted_notifications(deleted_thread_ids)
.await;
Ok(None)
}
Err(error) => Err(error),
}
}
async fn thread_delete_response(
&self,
params: ThreadDeleteParams,
deleted_thread_ids: &mut Vec<String>,
) -> Result<ThreadDeleteResponse, JSONRPCErrorError> {
let thread_id = ThreadId::from_string(&params.thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
let thread_ids = self.state_db_spawn_subtree_thread_ids(thread_id).await?;
self.validate_root_thread_delete(thread_id, thread_ids.len() > 1)
.await?;
if let Some(store) = self
.thread_store
.as_any()
.downcast_ref::<LocalThreadStore>()
{
store
.ensure_no_attached_threads(&thread_ids)
.await
.map_err(thread_store_delete_error)?;
}
for thread_id_to_delete in thread_ids.iter().copied() {
self.prepare_thread_for_delete(thread_id_to_delete).await?;
}
let mut delete_order: Vec<_> = thread_ids.iter().skip(1).rev().copied().collect();
delete_order.push(thread_id);
self.thread_store
.delete_threads(StoreDeleteThreadsParams {
thread_ids: delete_order.clone(),
})
.await
.map_err(thread_store_delete_error)?;
deleted_thread_ids.extend(
delete_order
.into_iter()
.map(|thread_id| thread_id.to_string()),
);
Ok(ThreadDeleteResponse {})
}
async fn send_thread_deleted_notifications(&self, deleted_thread_ids: Vec<String>) {
for thread_id in deleted_thread_ids {
self.outgoing
.send_server_notification(ServerNotification::ThreadDeleted(
ThreadDeletedNotification { thread_id },
))
.await;
}
}
async fn validate_root_thread_delete(
&self,
thread_id: ThreadId,
has_descendants: bool,
) -> Result<(), JSONRPCErrorError> {
if let Ok(thread) = self.thread_manager.get_thread(thread_id).await {
if !thread.config_snapshot().await.ephemeral {
return Ok(());
}
return Err(invalid_request(format!(
"thread is not persisted and cannot be deleted: {thread_id}"
)));
}
match self
.thread_store
.read_thread(StoreReadThreadParams {
thread_id,
include_archived: true,
include_history: false,
})
.await
{
Ok(_) => Ok(()),
Err(ThreadStoreError::ThreadNotFound { .. }) => {
if has_descendants {
return Ok(());
}
let Some(state_db) = self.state_db.as_ref() else {
return Err(thread_store_delete_error(
ThreadStoreError::ThreadNotFound { thread_id },
));
};
if state_db
.get_thread(thread_id)
.await
.map_err(|err| {
internal_error(format!(
"failed to read app-server state for {thread_id}: {err}"
))
})?
.is_some()
{
Ok(())
} else {
Err(thread_store_delete_error(
ThreadStoreError::ThreadNotFound { thread_id },
))
}
}
Err(err) => Err(thread_store_delete_error(err)),
}
}
async fn prepare_thread_for_delete(
&self,
thread_id: ThreadId,
) -> Result<(), JSONRPCErrorError> {
self.prepare_thread_for_removal(thread_id, "delete").await?;
if let Some(log_db) = self.log_db.as_ref() {
log_db.flush().await;
}
Ok(())
}
}
fn thread_store_delete_error(err: ThreadStoreError) -> JSONRPCErrorError {
match err {
ThreadStoreError::ThreadNotFound { thread_id } => {
invalid_request(format!("thread not found: {thread_id}"))
}
ThreadStoreError::InvalidRequest { message } | ThreadStoreError::Conflict { message } => {
invalid_request(message)
}
ThreadStoreError::Unsupported { operation } => {
unsupported_thread_store_operation(operation)
}
err => internal_error(format!("failed to delete thread: {err}")),
}
}

View File

@@ -0,0 +1,90 @@
use super::apply_live_thread_settings;
use super::thread_input::can_accept_direct_input;
use crate::thread_status::ThreadWatchManager;
use crate::thread_status::resolve_thread_status;
use codex_app_server_protocol::SessionSource;
use codex_app_server_protocol::Thread;
use codex_app_server_protocol::ThreadStatus;
use codex_core::ThreadManager;
use codex_protocol::ThreadId;
use codex_protocol::protocol::AgentStatus;
use codex_protocol::protocol::SubAgentSource;
use std::collections::HashMap;
pub(super) async fn enrich_loaded_threads<T>(
thread_manager: &ThreadManager,
thread_watch_manager: &ThreadWatchManager,
threads: &mut [T],
mut as_thread: impl FnMut(&mut T) -> &mut Thread,
) {
let statuses = thread_watch_manager
.loaded_statuses_for_threads(
threads
.iter_mut()
.map(&mut as_thread)
.map(|thread| thread.id.clone()),
)
.await;
futures::future::join_all(
threads
.iter_mut()
.map(as_thread)
.map(|thread| enrich_loaded_thread(thread_manager, &statuses, thread)),
)
.await;
}
async fn enrich_loaded_thread(
thread_manager: &ThreadManager,
statuses: &HashMap<String, ThreadStatus>,
thread: &mut Thread,
) {
let watched_status = statuses.get(&thread.id);
if let Some(status) = watched_status {
thread.status = status.clone();
}
if matches!(watched_status, Some(ThreadStatus::NotLoaded)) {
return;
}
let Ok(thread_id) = ThreadId::from_string(&thread.id) else {
return;
};
let Ok(loaded_thread) = thread_manager.get_thread(thread_id).await else {
return;
};
let config_snapshot = loaded_thread.config_snapshot().await;
apply_live_thread_settings(thread, &config_snapshot);
if !matches!(
&thread.source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
) {
return;
}
match loaded_thread.agent_status().await {
AgentStatus::Running => {
if watched_status.is_none() {
thread.status =
resolve_thread_status(ThreadStatus::Idle, /*has_in_progress_turn*/ true);
}
}
AgentStatus::PendingInit | AgentStatus::Interrupted | AgentStatus::Completed(_) => {
if watched_status.is_none() {
thread.status = ThreadStatus::Idle;
}
}
AgentStatus::Errored(_) => {
thread.status = ThreadStatus::SystemError;
}
AgentStatus::Shutdown | AgentStatus::NotFound => {
thread.status = ThreadStatus::NotLoaded;
return;
}
}
thread.can_accept_direct_input = Some(can_accept_direct_input(
loaded_thread.multi_agent_version(),
&config_snapshot.session_source,
));
}

View File

@@ -0,0 +1,28 @@
use codex_protocol::ThreadId;
use codex_protocol::protocol::validate_thread_goal_objective;
use codex_state::StateRuntime;
pub(super) async fn inherit_thread_goal_snapshot(
state_db: &StateRuntime,
source_thread_id: ThreadId,
target_thread_id: ThreadId,
) -> anyhow::Result<bool> {
let Some(mut goal) = state_db
.thread_goals()
.get_thread_goal(source_thread_id)
.await?
else {
return Ok(false);
};
if let Err(err) = validate_thread_goal_objective(&goal.objective) {
tracing::warn!(%source_thread_id, "skipping invalid inherited thread goal: {err}");
return Ok(false);
}
goal.thread_id = target_thread_id;
state_db
.thread_goals()
.replace_thread_goal_snapshot(&goal)
.await?;
Ok(true)
}

View File

@@ -0,0 +1,559 @@
use super::thread_input::DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR;
use super::thread_input::can_accept_direct_input;
use super::thread_input::ensure_direct_input_allowed;
use super::*;
use codex_app_server_protocol::ThreadGoalMutationOrigin;
use codex_core::context::UserGoalUpdate;
use codex_goal_extension::GoalObjectiveUpdate;
use codex_goal_extension::GoalService;
use codex_goal_extension::GoalServiceError;
use codex_goal_extension::GoalSetRequest;
use codex_goal_extension::GoalTokenBudgetUpdate;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_rollout::RolloutRecorder;
use codex_rollout::WriterLockCoordinator;
#[path = "thread_goal_user_context.rs"]
mod user_context;
enum GoalAccess {
Read,
Mutate,
}
#[derive(Clone)]
pub(crate) struct ThreadGoalRequestProcessor {
thread_manager: Arc<ThreadManager>,
outgoing: Arc<OutgoingMessageSender>,
config: Arc<Config>,
thread_state_manager: ThreadStateManager,
state_db: Option<StateDbHandle>,
goal_service: Arc<GoalService>,
config_manager: ConfigManager,
writer_locks: Arc<WriterLockCoordinator>,
}
impl ThreadGoalRequestProcessor {
pub(crate) fn new(
thread_manager: Arc<ThreadManager>,
outgoing: Arc<OutgoingMessageSender>,
config: Arc<Config>,
thread_state_manager: ThreadStateManager,
state_db: Option<StateDbHandle>,
goal_service: Arc<GoalService>,
config_manager: ConfigManager,
) -> Self {
let writer_locks = Arc::new(WriterLockCoordinator::new(&config.codex_home));
Self {
thread_manager,
outgoing,
config,
thread_state_manager,
state_db,
goal_service,
config_manager,
writer_locks,
}
}
pub(crate) async fn thread_goal_set(
&self,
request_id: ConnectionRequestId,
params: ThreadGoalSetParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.thread_goal_set_inner(request_id, params)
.await
.map(|()| None)
}
pub(crate) async fn thread_goal_get(
&self,
params: ThreadGoalGetParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.thread_goal_get_inner(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn thread_goal_clear(
&self,
request_id: ConnectionRequestId,
params: ThreadGoalClearParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.thread_goal_clear_inner(request_id, params)
.await
.map(|()| None)
}
pub(crate) async fn emit_resume_goal_snapshot(&self, thread_id: ThreadId) {
if !self.config.features.enabled(Feature::Goals) {
return;
}
self.emit_thread_goal_snapshot(thread_id).await;
}
pub(crate) async fn pending_resume_goal_state(
&self,
thread: &CodexThread,
) -> (bool, Option<StateDbHandle>) {
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)
}
pub(crate) async fn restore_inherited_goal_runtime(&self, thread_id: ThreadId) {
if let Err(err) = self
.goal_service
.restore_thread_runtime_after_resume(thread_id)
.await
{
warn!("failed to restore inherited goal runtime for {thread_id}: {err}");
}
}
pub(crate) async fn flush_goal_progress_for_fork(
&self,
thread_id: ThreadId,
) -> Result<(), String> {
self.goal_service
.flush_thread_goal_progress_for_fork(thread_id)
.await
.map_err(|err| err.to_string())
}
async fn thread_goal_set_inner(
&self,
request_id: ConnectionRequestId,
params: ThreadGoalSetParams,
) -> Result<(), JSONRPCErrorError> {
if !self.config.features.enabled(Feature::Goals) {
return Err(invalid_request("goals feature is disabled"));
}
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let _goal_resume_guard = self.thread_state_manager.lock_goal_resume(thread_id).await;
let state_db = self
.state_db_for_materialized_thread(thread_id, GoalAccess::Mutate)
.await?;
self.reconcile_thread_goal_rollout(thread_id, &state_db)
.await?;
// Active goals can immediately inject an objective or start an idle turn.
// Stopping a goal must remain possible after managed policy changes.
let existing_goal = self
.goal_service
.get_thread_goal(&state_db, thread_id)
.await
.map_err(goal_service_error)?;
let resulting_status = params
.status
.map(ThreadGoalStatus::to_core)
.or_else(|| existing_goal.as_ref().map(|goal| goal.status))
.unwrap_or(codex_protocol::protocol::ThreadGoalStatus::Active);
if resulting_status == codex_protocol::protocol::ThreadGoalStatus::Active
&& let Ok(thread) = self.thread_manager.get_thread(thread_id).await
{
self.config_manager
.check_thread_model_provider(thread.config().await.as_ref())
.await
.map_err(|error| config_load_error(&error))?;
}
let max_goal_token_budget = match self.thread_manager.get_thread(thread_id).await {
Ok(thread) => thread.config().await.max_goal_token_budget,
Err(_) => self.config.max_goal_token_budget,
};
let listener_command_tx = {
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
let thread_state = thread_state.lock().await;
thread_state.listener_command_tx()
};
let status = params.status.map(ThreadGoalStatus::to_core);
let objective = params.objective.as_deref().map(str::trim);
let outcome = self
.goal_service
.set_thread_goal(
&state_db,
GoalSetRequest {
thread_id,
objective: objective
.map(GoalObjectiveUpdate::Set)
.unwrap_or(GoalObjectiveUpdate::Keep),
status,
token_budget: match params.token_budget {
Some(token_budget) => GoalTokenBudgetUpdate::Set(token_budget),
None => GoalTokenBudgetUpdate::Keep,
},
max_goal_token_budget,
},
Box::pin(async {
if params.origin == Some(ThreadGoalMutationOrigin::User)
&& (objective.is_some() || status.is_some())
{
self.record_user_goal_update(
thread_id,
UserGoalUpdate::Set {
objective: objective.map(str::to_owned),
status,
},
)
.await?;
}
Ok(())
}),
)
.await
.map_err(goal_service_error)?;
let goal = ThreadGoal::from(outcome.goal.clone());
let persist_result = match self.thread_manager.get_thread(thread_id).await {
Ok(thread) => {
let needs_settings_checkpoint = match thread.rollout_path() {
Some(path) => codex_rollout::existing_rollout_path(&path).await.is_none(),
None => false,
};
match thread
.append_rollout_items(&[outcome.thread_goal_updated_item()])
.await
{
// Automatic and legacy callers still need goal-first settings persisted,
// even though they do not record a user instruction.
Ok(()) if needs_settings_checkpoint => {
thread.checkpoint_thread_settings().await
}
result => result,
}
}
Err(_) => Ok(()),
};
if let Err(err) = persist_result {
warn!("failed to persist goal update for live thread {thread_id}: {err}");
}
self.outgoing
.send_response(
request_id.clone(),
ThreadGoalSetResponse { goal: goal.clone() },
)
.await;
self.emit_thread_goal_updated_ordered(thread_id, goal, listener_command_tx)
.await;
outcome.apply_runtime_effects(&self.goal_service).await;
Ok(())
}
async fn thread_goal_get_inner(
&self,
params: ThreadGoalGetParams,
) -> Result<ThreadGoalGetResponse, JSONRPCErrorError> {
if !self.config.features.enabled(Feature::Goals) {
return Err(invalid_request("goals feature is disabled"));
}
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self
.state_db_for_materialized_thread(thread_id, GoalAccess::Read)
.await?;
let goal = self
.goal_service
.get_thread_goal(&state_db, thread_id)
.await
.map_err(goal_service_error)?
.map(ThreadGoal::from);
Ok(ThreadGoalGetResponse { goal })
}
async fn thread_goal_clear_inner(
&self,
request_id: ConnectionRequestId,
params: ThreadGoalClearParams,
) -> Result<(), JSONRPCErrorError> {
if !self.config.features.enabled(Feature::Goals) {
return Err(invalid_request("goals feature is disabled"));
}
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let _goal_resume_guard = self.thread_state_manager.lock_goal_resume(thread_id).await;
let state_db = self
.state_db_for_materialized_thread(thread_id, GoalAccess::Mutate)
.await?;
self.reconcile_thread_goal_rollout(thread_id, &state_db)
.await?;
let listener_command_tx = {
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
let thread_state = thread_state.lock().await;
thread_state.listener_command_tx()
};
let cleared = self
.goal_service
.clear_thread_goal(
&state_db,
thread_id,
Box::pin(async {
if params.origin == Some(ThreadGoalMutationOrigin::User) {
self.record_user_goal_update(thread_id, UserGoalUpdate::Clear)
.await?;
}
Ok(())
}),
)
.await
.map_err(goal_service_error)?;
self.outgoing
.send_response(request_id, ThreadGoalClearResponse { cleared })
.await;
if cleared {
self.emit_thread_goal_cleared_ordered(thread_id, listener_command_tx)
.await;
}
Ok(())
}
async fn state_db_for_materialized_thread(
&self,
thread_id: ThreadId,
access: GoalAccess,
) -> Result<StateDbHandle, JSONRPCErrorError> {
if let Ok(thread) = self.thread_manager.get_thread(thread_id).await {
if matches!(access, GoalAccess::Mutate) {
ensure_direct_input_allowed(thread.as_ref()).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 {
let rollout_path = codex_rollout::find_thread_path_by_id_str(
&self.config.codex_home,
&thread_id.to_string(),
self.state_db.as_deref(),
)
.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}")))?;
if matches!(access, GoalAccess::Mutate) {
let session_meta = codex_rollout::read_session_meta_line(&rollout_path)
.await
.map_err(|err| {
internal_error(format!("failed to read thread ownership: {err}"))
})?;
if session_meta.meta.id != thread_id {
return Err(invalid_request(
"thread metadata does not match requested id",
));
}
if matches!(
session_meta.meta.source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
) {
// Match resume's latest version metadata, including legacy TurnContext
// fallback, rather than trusting only the initial session header.
let history = RolloutRecorder::get_rollout_history(&rollout_path)
.await
.map_err(|err| {
internal_error(format!("failed to read thread ownership: {err}"))
})?;
if !can_accept_direct_input(
history.get_multi_agent_version(),
&session_meta.meta.source,
) {
return Err(invalid_request(
DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR,
));
}
}
}
}
self.state_db
.clone()
.ok_or_else(|| internal_error("sqlite state db unavailable for thread goals"))
}
async fn reconcile_thread_goal_rollout(
&self,
thread_id: ThreadId,
state_db: &StateDbHandle,
) -> Result<(), JSONRPCErrorError> {
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(),
)
.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}")))?,
};
if let Ok(Some(metadata)) = state_db.get_thread(thread_id).await
&& codex_rollout::plain_rollout_path(metadata.rollout_path.as_path())
== codex_rollout::plain_rollout_path(rollout_path.as_path())
&& let Some(existing_path) =
codex_rollout::existing_rollout_path(metadata.rollout_path.as_path()).await
&& codex_rollout::read_session_meta_line(existing_path.as_path())
.await
.is_ok_and(|session_meta| session_meta.meta.id == thread_id)
{
return Ok(());
}
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;
Ok(())
}
pub(crate) async fn emit_thread_goal_snapshot(&self, thread_id: ThreadId) {
let state_db = match self
.state_db_for_materialized_thread(thread_id, GoalAccess::Read)
.await
{
Ok(state_db) => state_db,
Err(err) => {
warn!(
"failed to open state db before emitting thread goal resume snapshot for {thread_id}: {}",
err.message
);
return;
}
};
let listener_command_tx = {
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
let thread_state = thread_state.lock().await;
thread_state.listener_command_tx()
};
if let Some(listener_command_tx) = listener_command_tx {
let command = crate::thread_state::ThreadListenerCommand::EmitThreadGoalSnapshot {
state_db: state_db.clone(),
};
if listener_command_tx.send(command).is_ok() {
return;
}
warn!(
"failed to enqueue thread goal snapshot for {thread_id}: listener command channel is closed"
);
}
send_thread_goal_snapshot_notification(&self.outgoing, thread_id, &state_db).await;
}
async fn emit_thread_goal_updated_ordered(
&self,
thread_id: ThreadId,
goal: ThreadGoal,
listener_command_tx: Option<tokio::sync::mpsc::UnboundedSender<ThreadListenerCommand>>,
) {
if let Some(listener_command_tx) = listener_command_tx {
let command = crate::thread_state::ThreadListenerCommand::EmitThreadGoalUpdated {
turn_id: None,
goal: goal.clone(),
};
if listener_command_tx.send(command).is_ok() {
return;
}
warn!(
"failed to enqueue thread goal update for {thread_id}: listener command channel is closed"
);
}
self.outgoing
.send_server_notification(ServerNotification::ThreadGoalUpdated(
ThreadGoalUpdatedNotification {
thread_id: thread_id.to_string(),
turn_id: None,
goal,
},
))
.await;
}
async fn emit_thread_goal_cleared_ordered(
&self,
thread_id: ThreadId,
listener_command_tx: Option<tokio::sync::mpsc::UnboundedSender<ThreadListenerCommand>>,
) {
if let Some(listener_command_tx) = listener_command_tx {
let command = crate::thread_state::ThreadListenerCommand::EmitThreadGoalCleared;
if listener_command_tx.send(command).is_ok() {
return;
}
warn!(
"failed to enqueue thread goal clear for {thread_id}: listener command channel is closed"
);
}
self.outgoing
.send_server_notification(ServerNotification::ThreadGoalCleared(
ThreadGoalClearedNotification {
thread_id: thread_id.to_string(),
},
))
.await;
}
}
pub(super) fn api_thread_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal {
ThreadGoal {
thread_id: goal.thread_id.to_string(),
objective: goal.objective,
status: api_thread_goal_status_from_state(goal.status),
token_budget: goal.token_budget,
tokens_used: goal.tokens_used,
time_used_seconds: goal.time_used_seconds,
created_at: goal.created_at.timestamp(),
updated_at: goal.updated_at.timestamp(),
}
}
fn api_thread_goal_status_from_state(status: codex_state::ThreadGoalStatus) -> ThreadGoalStatus {
match status {
codex_state::ThreadGoalStatus::Active => ThreadGoalStatus::Active,
codex_state::ThreadGoalStatus::Paused => ThreadGoalStatus::Paused,
codex_state::ThreadGoalStatus::Blocked => ThreadGoalStatus::Blocked,
codex_state::ThreadGoalStatus::UsageLimited => ThreadGoalStatus::UsageLimited,
codex_state::ThreadGoalStatus::BudgetLimited => ThreadGoalStatus::BudgetLimited,
codex_state::ThreadGoalStatus::Complete => ThreadGoalStatus::Complete,
}
}
fn goal_service_error(err: GoalServiceError) -> JSONRPCErrorError {
match err {
GoalServiceError::InvalidRequest(message) => invalid_request(message),
GoalServiceError::Internal(message) => internal_error(message),
}
}
fn parse_thread_id_for_request(thread_id: &str) -> Result<ThreadId, JSONRPCErrorError> {
ThreadId::from_string(thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))
}

View File

@@ -0,0 +1,51 @@
//! Persists explicit user goal mutations with user provenance before goal work resumes.
//! Unloaded threads receive the same item on replay; tool-created goals never use this path.
use super::*;
use codex_core::context::ContextualUserFragment;
use codex_core::context::UserGoalUpdate;
use codex_rollout::RolloutRecorderParams;
impl ThreadGoalRequestProcessor {
pub(super) async fn record_user_goal_update(
&self,
thread_id: ThreadId,
update: UserGoalUpdate,
) -> Result<(), GoalServiceError> {
if let Ok(thread) = self.thread_manager.get_thread(thread_id).await {
return thread.record_user_goal_update(update).await.map_err(|err| {
GoalServiceError::Internal(format!("failed to record goal instruction: {err}"))
});
}
let item = ContextualUserFragment::into(update);
let record_error =
|err| GoalServiceError::Internal(format!("failed to record goal instruction: {err}"));
let writer_lock = Arc::new(self.writer_locks.acquire(thread_id).map_err(record_error)?);
let path = codex_rollout::find_thread_path_by_id_str(
&self.config.codex_home,
&thread_id.to_string(),
self.state_db.as_deref(),
)
.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}"))
})?;
// The writer owns the lock through background IO, even if this RPC is cancelled.
let recorder = RolloutRecorder::new_with_writer_lock(
self.config.as_ref(),
RolloutRecorderParams::resume(path),
writer_lock,
)
.await
.map_err(record_error)?;
recorder
.record_canonical_items(&[RolloutItem::ResponseItem(item.into())])
.await
.map_err(record_error)?;
// Shutdown flushes queued items before acknowledging the goal mutation.
recorder.shutdown().await.map_err(record_error)
}
}

View File

@@ -0,0 +1,37 @@
use super::invalid_request;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_core::CodexThread;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
pub(super) const DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR: &str =
"direct app-server input is not allowed for multi-agent v2 sub-agents";
/// Mirrors the ownership policy in request validation and thread capability responses.
pub(super) fn can_accept_direct_input(
multi_agent_version: Option<MultiAgentVersion>,
session_source: &SessionSource,
) -> bool {
multi_agent_version != Some(MultiAgentVersion::V2)
|| !matches!(
session_source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
)
}
pub(super) async fn ensure_direct_input_allowed(
thread: &CodexThread,
) -> Result<(), JSONRPCErrorError> {
let config_snapshot = thread.config_snapshot().await;
if !can_accept_direct_input(
thread.multi_agent_version(),
&config_snapshot.session_source,
) {
return Err(invalid_request(
DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR,
));
}
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,265 @@
#![cfg(test)]
//! Checks runtime release and notification delivery around listener shutdown.
use super::super::thread_goal_processor::ThreadGoalRequestProcessor;
use super::super::thread_processor::ThreadRequestProcessor;
use super::super::thread_processor::ThreadResumeTarget;
use super::*;
use crate::config_manager::ConfigManager;
use crate::outgoing_message::OutgoingEnvelope;
use crate::outgoing_message::OutgoingMessage;
use crate::thread_sample::SampleResponseRegistry;
use crate::thread_state::ConnectionCapabilities;
use crate::thread_state::PendingNetworkApproval;
use crate::thread_state::resolve_server_request_on_thread_listener;
use anyhow::Context;
use anyhow::Result;
use codex_analytics::AnalyticsEventsClient;
use codex_app_server_protocol::ClientResponsePayload;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadUnsubscribeParams;
use codex_app_server_protocol::ThreadUnsubscribeResponse;
use codex_app_server_protocol::ThreadUnsubscribeStatus;
use codex_arg0::Arg0DispatchPaths;
use codex_goal_extension::GoalService;
use codex_login::AuthManager;
use codex_thread_store::PersistContext;
use core_test_support::test_codex::test_codex;
use pretty_assertions::assert_eq;
use std::collections::HashSet;
use test_case::test_case;
use tokio::sync::Semaphore;
use tokio::sync::mpsc;
#[test_case(true; "listener attached before shutdown")]
#[test_case(false; "listener attached after shutdown")]
#[tokio::test]
async fn listener_shutdown_releases_runtime_and_preserves_other_subscribers(
attach_before_shutdown: bool,
) -> Result<()> {
let server = wiremock::MockServer::start().await;
let test = test_codex().build_with_auto_env(&server).await?;
let thread_id = test.session_configured.thread_id;
test.thread_store
.persist_thread(thread_id, PersistContext::Standard)
.await?;
let thread = test.codex;
let runtime = Arc::downgrade(&thread);
let config = Arc::new(test.config.clone());
let auth =
AuthManager::shared_from_config(config.as_ref(), /*enable_codex_api_key_env*/ false)
.await?;
let config_manager =
ConfigManager::without_managed_config_for_tests(config.codex_home.to_path_buf());
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*buffer*/ 16);
let outgoing = Arc::new(OutgoingMessageSender::new(
outgoing_tx,
AnalyticsEventsClient::disabled(),
));
let thread_state_manager = ThreadStateManager::new();
let thread_watch_manager = ThreadWatchManager::new_with_outgoing(outgoing.clone());
let skills_watcher = SkillsWatcher::new(
test.thread_manager.skills_service(),
&config.codex_home,
outgoing.clone(),
);
let thread_goal_processor = ThreadGoalRequestProcessor::new(
test.thread_manager.clone(),
outgoing.clone(),
config.clone(),
thread_state_manager.clone(),
/*state_db*/ None,
Arc::new(GoalService::new()),
config_manager.clone(),
);
let processor = ThreadRequestProcessor::new(
auth,
test.thread_manager.clone(),
outgoing,
Arg0DispatchPaths::default(),
config,
config_manager,
test.thread_store.clone(),
Default::default(),
thread_state_manager.clone(),
thread_watch_manager.clone(),
Arc::new(Semaphore::new(/*permits*/ 1)),
thread_goal_processor,
/*state_db*/ None,
/*log_db*/ None,
skills_watcher.clone(),
/*turn_cost_worker*/ None,
Vec::new(),
Arc::new(SampleResponseRegistry::default()),
);
let connection_id = ConnectionId(1);
let disconnecting_connection_id = ConnectionId(2);
let remaining_connection_id = ConnectionId(3);
let connection_ids = vec![
connection_id,
disconnecting_connection_id,
remaining_connection_id,
];
for &connection_id in &connection_ids {
processor
.connection_initialized(connection_id, ConnectionCapabilities::default())
.await;
}
let network_request_id = RequestId::Integer(4);
if attach_before_shutdown {
processor
.try_attach_thread_listener(thread_id, Arc::clone(&thread), connection_ids.clone())
.await;
// Leave the prompt outstanding so shutdown runs before the proxy waiter resolves it.
let permission_guard = thread_watch_manager
.note_permission_requested(&thread_id.to_string())
.await;
thread_state_manager
.thread_state(thread_id)
.await
.lock()
.await
.network_approvals
.insert(
"network-approval".to_string(),
PendingNetworkApproval {
request_id: network_request_id.clone(),
permission_guard,
},
);
}
thread.shutdown_and_wait().await?;
let shutdown_result = tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
let resume = processor
.thread_resume(
ThreadResumeTarget::Client(ConnectionRequestId {
connection_id,
request_id: RequestId::Integer(1),
}),
ThreadResumeParams {
thread_id: thread_id.to_string(),
exclude_turns: true,
..Default::default()
},
/*app_server_client_name*/ None,
/*app_server_client_version*/ None,
/*client_mcp_extensions*/ Default::default(),
)
.await;
test.thread_manager.remove_thread(&thread_id).await;
if !attach_before_shutdown {
processor
.try_attach_thread_listener(thread_id, Arc::clone(&thread), connection_ids)
.await;
}
let mut network_resolved = false;
loop {
match outgoing_rx.recv().await.expect("outgoing channel closed") {
OutgoingEnvelope::ToConnection {
connection_id: recipient,
message: OutgoingMessage::AppServerNotification(notification),
..
} if recipient == connection_id
&& matches!(
&notification.notification,
ServerNotification::ServerRequestResolved(resolved)
if resolved.request_id == network_request_id
) =>
{
assert!(!network_resolved, "duplicate network prompt resolution");
network_resolved = true;
}
OutgoingEnvelope::Broadcast {
message: OutgoingMessage::AppServerNotification(notification),
} if matches!(
&notification.notification,
ServerNotification::ThreadStatusChanged(status)
if status.status == ThreadStatus::NotLoaded
) =>
{
break;
}
_ => {}
}
}
assert_eq!(network_resolved, attach_before_shutdown);
drop(thread);
while runtime.upgrade().is_some() {
tokio::task::yield_now().await;
}
let Some(ClientResponsePayload::ThreadUnsubscribe(unsubscribe)) = processor
.thread_unsubscribe(
&ConnectionRequestId {
connection_id,
request_id: RequestId::Integer(2),
},
ThreadUnsubscribeParams {
thread_id: thread_id.to_string(),
},
)
.await
.expect("unsubscribe failed")
else {
panic!("unsubscribe response missing");
};
assert_eq!(
unsubscribe,
ThreadUnsubscribeResponse {
status: ThreadUnsubscribeStatus::NotLoaded,
},
);
assert_eq!(
thread_state_manager
.subscribed_connection_ids(thread_id)
.await
.into_iter()
.collect::<HashSet<_>>(),
HashSet::from([disconnecting_connection_id, remaining_connection_id]),
);
processor
.connection_closed(disconnecting_connection_id)
.await;
assert_eq!(
thread_state_manager
.subscribed_connection_ids(thread_id)
.await,
vec![remaining_connection_id],
);
resolve_server_request_on_thread_listener(
&thread_state_manager.thread_state(thread_id).await,
RequestId::Integer(3),
)
.await;
loop {
if let OutgoingEnvelope::ToConnection {
connection_id: recipient,
message: OutgoingMessage::AppServerNotification(notification),
..
} = outgoing_rx.recv().await.expect("outgoing channel closed")
&& recipient == remaining_connection_id
&& matches!(
&notification.notification,
ServerNotification::ServerRequestResolved(resolved)
if resolved.request_id == RequestId::Integer(3)
)
{
break;
}
}
resume
})
.await;
thread_state_manager.clear_all_listeners().await;
skills_watcher.shutdown();
let resume = shutdown_result.context("terminal listener did not release or relay")?;
assert_eq!(
resume.expect_err("resume accepted a terminated runtime"),
invalid_request(format!(
"thread {thread_id} is closing; retry thread/resume after the thread is closed"
)),
);
Ok(())
}

View File

@@ -0,0 +1,30 @@
//! Reads memory context from the loaded thread's resolved version, without fallback.
use super::*;
use codex_app_server_protocol::ThreadMemoryReadParams;
use codex_app_server_protocol::ThreadMemoryReadResponse;
impl ThreadRequestProcessor {
pub(crate) async fn thread_memory_read(
&self,
params: ThreadMemoryReadParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let (_, thread) = self.load_thread(&params.thread_id).await?;
let config = thread.config().await;
let summary =
if config.features.enabled(Feature::MemoryTool) && config.memories.use_memories {
tokio::fs::read_to_string(
config
.codex_home
.join(config.memories.version.directory_name())
.join("memory_summary.md"),
)
.await
.ok()
.filter(|summary| !summary.trim().is_empty())
} else {
None
};
Ok(Some(ThreadMemoryReadResponse { summary }.into()))
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,34 @@
//! Unloads old-workspace runtimes while turn admission is paused by the account switch.
//! Resuming a thread builds fresh policy and transport state for the new workspace.
use super::*;
impl ThreadRequestProcessor {
pub(crate) async fn unload_for_workspace_switch(&self) -> Result<(), JSONRPCErrorError> {
let report = self
.thread_manager
.shutdown_all_threads_bounded(Duration::from_secs(/*secs*/ 10))
.await;
for thread_id in report.completed {
self.finalize_thread_teardown(thread_id).await;
self.outgoing
.send_server_notification(ServerNotification::ThreadClosed(
codex_app_server_protocol::ThreadClosedNotification {
thread_id: thread_id.to_string(),
},
))
.await;
}
// A delegated child may have started while its parent was shutting down.
// Never replace credentials until every runtime has stopped.
if !report.submit_failed.is_empty()
|| !report.timed_out.is_empty()
|| !self.thread_manager.list_thread_ids().await.is_empty()
{
return Err(internal_error(
"Some threads are still running; retry the workspace switch",
));
}
Ok(())
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,355 @@
use crate::config_manager::ConfigManager;
use std::sync::Arc;
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use crate::outgoing_message::ConnectionRequestId;
use crate::outgoing_message::OutgoingMessageSender;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::QueuedSubmission;
use codex_app_server_protocol::ThreadQueueAddParams;
use codex_app_server_protocol::ThreadQueueAddResponse;
use codex_app_server_protocol::ThreadQueueDeleteParams;
use codex_app_server_protocol::ThreadQueueDeleteResponse;
use codex_app_server_protocol::ThreadQueueListParams;
use codex_app_server_protocol::ThreadQueueListResponse;
use codex_app_server_protocol::ThreadQueueReorderParams;
use codex_app_server_protocol::ThreadQueueReorderResponse;
use codex_app_server_protocol::ThreadQueueStartParams;
use codex_app_server_protocol::ThreadQueueStartResponse;
use codex_app_server_protocol::ThreadQueueUpdateParams;
use codex_app_server_protocol::ThreadQueueUpdateResponse;
use codex_app_server_protocol::Turn;
use codex_app_server_protocol::TurnItemsView;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::UserInput;
use codex_core::CodexThread;
use codex_core::NotSubmittedReason;
use codex_core::StartIfIdleSubmission;
use codex_core::ThreadManager;
use codex_core::TurnInput;
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_queue_extension::QueueServiceError;
use codex_queue_extension::QueuedItem;
use codex_queue_extension::QueuedItemService;
use codex_thread_store::ReadThreadParams;
use codex_thread_store::ThreadStore;
use codex_thread_store::ThreadStoreError;
use super::TurnRequestProcessor;
use super::config_load_error;
use super::thread_input::DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR;
use super::thread_input::can_accept_direct_input;
use super::thread_processor::THREAD_LIST_DEFAULT_LIMIT;
use super::thread_processor::THREAD_LIST_MAX_LIMIT;
use super::turn_processor::validate_user_input_image_urls;
const DIRECT_INPUT_TO_UNLOADED_SUBAGENT_ERROR: &str =
"direct app-server input is not allowed for unloaded spawned sub-agents";
pub(crate) struct ThreadQueueRequestProcessor {
thread_manager: Arc<ThreadManager>,
thread_store: Arc<dyn ThreadStore>,
outgoing: Arc<OutgoingMessageSender>,
config_manager: ConfigManager,
service: Option<Arc<QueuedItemService>>,
}
impl ThreadQueueRequestProcessor {
pub(crate) fn new(
thread_manager: Arc<ThreadManager>,
thread_store: Arc<dyn ThreadStore>,
outgoing: Arc<OutgoingMessageSender>,
config_manager: ConfigManager,
service: Option<Arc<QueuedItemService>>,
) -> Self {
Self {
thread_manager,
thread_store,
outgoing,
config_manager,
service,
}
}
pub(crate) async fn add(
&self,
params: ThreadQueueAddParams,
) -> Result<ThreadQueueAddResponse, JSONRPCErrorError> {
validate_user_input_image_urls(&params.input)?;
let (thread_id, loaded_thread, source) = self.require_thread(&params.thread_id).await?;
ensure_direct_input_allowed(loaded_thread.as_deref(), &source)?;
let queued_item = self
.service()?
.enqueue_with_metadata(
thread_id,
submission_into_turn_input(params.input, Some(params.client_user_message_id)),
params.responsesapi_client_metadata,
)
.await
.map_err(queue_error)?;
Ok(ThreadQueueAddResponse {
queued_submission: api_queued_submission(queued_item)?,
})
}
pub(crate) async fn list(
&self,
params: ThreadQueueListParams,
) -> Result<ThreadQueueListResponse, JSONRPCErrorError> {
let (thread_id, _, _) = self.require_thread(&params.thread_id).await?;
let offset = params
.cursor
.as_deref()
.map(str::parse::<usize>)
.transpose()
.map_err(|error| invalid_request(format!("invalid queue pagination cursor: {error}")))?
.unwrap_or_default();
let limit = params
.limit
.map(|value| value as usize)
.unwrap_or(THREAD_LIST_DEFAULT_LIMIT)
.clamp(1, THREAD_LIST_MAX_LIMIT);
let mut items = self
.service()?
.list_page(thread_id, offset, limit.saturating_add(1))
.await
.map_err(queue_error)?;
let next_cursor = if items.len() > limit {
items.truncate(limit);
Some(offset.saturating_add(limit).to_string())
} else {
None
};
Ok(ThreadQueueListResponse {
data: items
.into_iter()
.map(api_queued_submission)
.collect::<Result<Vec<_>, _>>()?,
next_cursor,
})
}
pub(crate) async fn update(
&self,
params: ThreadQueueUpdateParams,
) -> Result<ThreadQueueUpdateResponse, JSONRPCErrorError> {
validate_user_input_image_urls(&params.input)?;
let (thread_id, loaded_thread, source) = self.require_thread(&params.thread_id).await?;
ensure_direct_input_allowed(loaded_thread.as_deref(), &source)?;
let queued_item = self
.service()?
.update_with_metadata(
thread_id,
params.queued_submission_id.clone(),
submission_into_turn_input(params.input, /*client_user_message_id*/ None),
params.responsesapi_client_metadata,
)
.await
.map_err(queue_error)?
.ok_or_else(|| {
invalid_request(format!(
"queued submission not found: {}",
params.queued_submission_id
))
})?;
Ok(ThreadQueueUpdateResponse {
queued_submission: api_queued_submission(queued_item)?,
})
}
pub(crate) async fn delete(
&self,
params: ThreadQueueDeleteParams,
) -> Result<ThreadQueueDeleteResponse, JSONRPCErrorError> {
let (thread_id, _, _) = self.require_thread(&params.thread_id).await?;
let deleted = self
.service()?
.delete(thread_id, params.queued_submission_id)
.await
.map_err(queue_error)?;
Ok(ThreadQueueDeleteResponse { deleted })
}
pub(crate) async fn reorder(
&self,
params: ThreadQueueReorderParams,
) -> Result<ThreadQueueReorderResponse, JSONRPCErrorError> {
let (thread_id, _, _) = self.require_thread(&params.thread_id).await?;
self.service()?
.reorder(thread_id, params.queued_submission_ids)
.await
.map_err(queue_error)?;
Ok(ThreadQueueReorderResponse {})
}
pub(crate) async fn start(
&self,
request_id: &ConnectionRequestId,
params: ThreadQueueStartParams,
) -> Result<ThreadQueueStartResponse, JSONRPCErrorError> {
let (_, loaded_thread, source) = self.require_thread(&params.thread_id).await?;
ensure_direct_input_allowed(loaded_thread.as_deref(), &source)?;
let thread = loaded_thread
.ok_or_else(|| invalid_request("resume the thread before starting a queued message"))?;
self.config_manager
.check_thread_model_provider(thread.config().await.as_ref())
.await
.map_err(|error| config_load_error(&error))?;
let submission = self
.service()?
.start(
thread.as_ref(),
params.queued_submission_id,
self.outgoing.request_trace_context(request_id).await,
)
.await
.map_err(queue_error)?;
let (turn_id, root_turn_id) = match submission {
StartIfIdleSubmission::Started {
turn_id,
root_turn_id,
} => (turn_id, root_turn_id),
StartIfIdleSubmission::NotSubmitted {
reason: NotSubmittedReason::ServerDraining,
} => return Err(crate::error_code::server_draining_error()),
StartIfIdleSubmission::NotSubmitted {
reason: NotSubmittedReason::NotIdle | NotSubmittedReason::PendingTriggerTurn,
} => {
return Err(invalid_request(
"thread already has an active or pending turn",
));
}
StartIfIdleSubmission::NotSubmitted { reason } => {
return Err(internal_error(format!(
"Core declined to start queued user message: {reason:?}"
)));
}
};
self.outgoing
.record_request_turn_id(request_id, &turn_id)
.await;
Ok(ThreadQueueStartResponse {
turn: Turn {
id: turn_id,
root_turn_id: Some(root_turn_id),
items: vec![],
items_view: TurnItemsView::NotLoaded,
error: None,
status: TurnStatus::InProgress,
started_at: None,
completed_at: None,
duration_ms: None,
},
})
}
fn service(&self) -> Result<&QueuedItemService, JSONRPCErrorError> {
self.service
.as_deref()
.ok_or_else(|| invalid_request("user message queue is unavailable"))
}
async fn require_thread(
&self,
raw_thread_id: &str,
) -> Result<(ThreadId, Option<Arc<CodexThread>>, SessionSource), JSONRPCErrorError> {
let thread_id = ThreadId::from_string(raw_thread_id)
.map_err(|error| invalid_request(format!("invalid thread id: {error}")))?;
let (loaded_thread, source) = if let Ok(thread) =
self.thread_manager.get_thread(thread_id).await
{
let snapshot = thread.config_snapshot().await;
if snapshot.ephemeral {
return Err(invalid_request(format!(
"ephemeral thread does not support queued submissions: {thread_id}"
)));
}
(Some(thread), snapshot.session_source)
} else {
let stored = self
.thread_store
.read_thread(ReadThreadParams {
thread_id,
include_archived: true,
include_history: false,
})
.await
.map_err(|error| match error {
ThreadStoreError::ThreadNotFound { .. } => {
invalid_request(format!("thread not found: {thread_id}"))
}
error => internal_error(format!("failed to read thread: {error}")),
})?;
if stored.archived_at.is_some() {
return Err(invalid_request(format!(
"session {thread_id} is archived. Run `codex unarchive {thread_id}` to unarchive it first."
)));
}
(None, stored.source)
};
Ok((thread_id, loaded_thread, source))
}
}
fn ensure_direct_input_allowed(
loaded_thread: Option<&CodexThread>,
source: &SessionSource,
) -> Result<(), JSONRPCErrorError> {
match loaded_thread {
Some(thread) if !can_accept_direct_input(thread.multi_agent_version(), source) => Err(
invalid_request(DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR),
),
None if matches!(
source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
) =>
{
Err(invalid_request(DIRECT_INPUT_TO_UNLOADED_SUBAGENT_ERROR))
}
_ => Ok(()),
}
}
fn submission_into_turn_input(
input: Vec<UserInput>,
client_user_message_id: Option<String>,
) -> TurnInput {
TurnInput::UserInput {
content: input.into_iter().map(UserInput::into_core).collect(),
client_id: client_user_message_id,
}
}
pub(super) fn queue_error(error: QueueServiceError) -> JSONRPCErrorError {
match error {
QueueServiceError::InputTooLarge { actual_chars } => {
TurnRequestProcessor::input_too_large_error(actual_chars)
}
error @ (QueueServiceError::InvalidInput | QueueServiceError::InvalidAttachment(_)) => {
invalid_request(error.to_string())
}
QueueServiceError::Storage(ThreadStoreError::InvalidRequest { message }) => {
invalid_request(message)
}
error => internal_error(format!("queued submission operation failed: {error}")),
}
}
fn api_queued_submission(value: QueuedItem) -> Result<QueuedSubmission, JSONRPCErrorError> {
let TurnInput::UserInput { content, client_id } = value.input else {
return Err(internal_error(
"queued submission does not contain user input",
));
};
Ok(QueuedSubmission {
id: value.id,
responsesapi_client_metadata: value.responsesapi_client_metadata,
input: content.into_iter().map(Into::into).collect(),
client_user_message_id: client_id
.ok_or_else(|| internal_error("queued submission is missing its client message id"))?,
})
}

View File

@@ -0,0 +1,205 @@
//! Read state for durable local threads. Receipt changes use the thread's usual subscribers.
use super::*;
use crate::error_code::method_not_found;
use codex_app_server_protocol::ThreadReadState;
use codex_app_server_protocol::ThreadReadStateChangedNotification;
use codex_app_server_protocol::ThreadReadStateOperation;
use codex_app_server_protocol::ThreadReadStateUpdateParams;
use codex_app_server_protocol::ThreadReadStateUpdateResponse;
use codex_app_server_protocol::ThreadUnreadPosition;
use codex_state::ReadStateOperation;
use codex_state::ReadStateUpdate;
// These scopes have product notification policy the local server cannot resolve.
// Do not advertise read state for them until their policy reaches this publisher.
fn eligible(thread: &Thread) -> bool {
!thread.ephemeral
&& !matches!(
thread.source,
codex_app_server_protocol::SessionSource::SubAgent(_)
| codex_app_server_protocol::SessionSource::Unknown
)
&& matches!(
thread.thread_source,
None | Some(codex_app_server_protocol::ThreadSource::User)
)
}
fn to_api(state: codex_state::ThreadReadState) -> ThreadReadState {
ThreadReadState {
first_unread: state.first_unread_turn.map(|turn_id| {
if turn_id.is_empty() {
ThreadUnreadPosition::ThreadStart
} else {
ThreadUnreadPosition::Turn { turn_id }
}
}),
revision: state.revision,
}
}
/// Read receipts only for the local store's list/read results, in one bounded batch.
pub(super) async fn snapshots(
db: Option<&StateDbHandle>,
threads: &[Thread],
) -> Option<HashMap<String, ThreadReadState>> {
let db = db?;
let ids = threads
.iter()
.filter(|t| eligible(t))
.filter_map(|t| ThreadId::from_string(&t.id).ok())
.collect::<Vec<_>>();
match db.thread_read_states(&ids).await {
Ok(states) => Some(
states
.into_iter()
.map(|(id, state)| (id.to_string(), to_api(state)))
.collect(),
),
Err(err) => {
tracing::warn!("thread read state unavailable: {err}");
None
}
}
}
pub(super) async fn notify(
db: &StateDbHandle,
manager: &ThreadStateManager,
outgoing: &Arc<OutgoingMessageSender>,
id: ThreadId,
) {
match db.thread_read_states(&[id]).await {
Ok(mut states) => {
if let Some(state) = states.remove(&id) {
let subscribers = manager.subscribed_connection_ids(id).await;
ThreadScopedOutgoingMessageSender::new(Arc::clone(outgoing), subscribers, id)
.send_server_notification(ServerNotification::ThreadReadStateChanged(
ThreadReadStateChangedNotification {
thread_id: id.to_string(),
read_state: to_api(state),
},
))
.await;
}
}
Err(err) => tracing::warn!("could not project committed read state: {err}"),
}
}
/// Runs only on newly delivered Core events, never on history decoding or replay.
pub(super) async fn publish(
event: &codex_protocol::protocol::Event,
id: ThreadId,
conversation: &Arc<CodexThread>,
summary: &crate::thread_state::TurnSummary,
) -> Option<StateDbHandle> {
let db = conversation.state_db()?;
let config = conversation.config_snapshot().await;
if config.ephemeral
|| matches!(
config.session_source,
codex_protocol::protocol::SessionSource::SubAgent(_)
| codex_protocol::protocol::SessionSource::Internal(_)
| codex_protocol::protocol::SessionSource::Unknown
)
|| !matches!(
config.thread_source,
None | Some(codex_protocol::protocol::ThreadSource::User)
)
{
return None;
}
let has_error = summary.last_error.is_some();
let final_text = match summary
.last_agent_message
.as_ref()
.map(|message| &message.payload)
{
Some(ThreadItemPayload::AgentMessage { text, .. }) => Some(text.as_str()),
_ => None,
};
let visible = match &event.msg {
EventMsg::TurnComplete(_) if has_error => true,
EventMsg::TurnComplete(_) => {
let text = final_text?;
if text.contains("<decision>DONT_NOTIFY</decision>") {
return None;
}
// An unfinished goal will resume automatically; it is not a terminal result.
match db.thread_goals().get_thread_goal(id).await {
Ok(Some(goal)) if goal.status == codex_state::ThreadGoalStatus::Active => false,
Ok(_) => !text.trim().is_empty(),
Err(err) => {
tracing::warn!("could not resolve terminal attention policy: {err}");
return None;
}
}
}
EventMsg::TurnAborted(aborted) => {
aborted.error.is_some() || has_error || final_text.is_some()
}
_ => false,
};
if visible {
if let Err(err) = conversation.flush_rollout().await {
tracing::warn!("cannot publish attention before the terminal result is durable: {err}");
return None;
}
match db.publish_thread_attention(id, &event.id).await {
Ok(true) => return Some(db),
Ok(false) => {}
Err(err) => tracing::warn!("failed to publish terminal attention: {err}"),
}
}
None
}
impl ThreadRequestProcessor {
pub(crate) async fn thread_read_state_update(
&self,
params: ThreadReadStateUpdateParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let id = ThreadId::from_string(&params.thread_id)
.map_err(|err| invalid_params(format!("invalid thread id: {err}")))?;
let db = self
.state_db
.as_ref()
.ok_or_else(|| method_not_found("durable thread read state unavailable"))?;
let thread = self
.read_thread_view(id, /*include_turns*/ false)
.await
.map_err(super::thread_processor::thread_read_view_error)?;
if !eligible(&thread) {
return Err(invalid_request("thread read state unavailable"));
}
let operation = match params.operation {
ThreadReadStateOperation::Read => ReadStateOperation::Read,
ThreadReadStateOperation::Unread => ReadStateOperation::Unread,
};
let outcome = db
.update_thread_read_state(id, &params.expected_revision, operation)
.await
.map_err(|err| internal_error(format!("read state was not saved: {err}")))?;
match outcome {
ReadStateUpdate::Applied(state) => {
notify(db, &self.thread_state_manager, &self.outgoing, id).await;
Ok(Some(
ThreadReadStateUpdateResponse {
read_state: to_api(state),
}
.into(),
))
}
ReadStateUpdate::Conflict(state) => {
let mut error = invalid_request("read state changed");
error.data = Some(
serde_json::json!({ "reason": "readStateConflict", "readState": to_api(state) }),
);
Err(error)
}
ReadStateUpdate::Unavailable => Err(invalid_request("thread read state unavailable")),
}
}
}

View File

@@ -0,0 +1,46 @@
//! Applies the rollout-gated CLI account check before resuming or attaching to a local thread.
//! Creator tags are immutable; untagged threads and other clients retain existing behavior.
use crate::error_code::invalid_request;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_features::Feature;
use codex_features::Features;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_thread_store::StoredThread;
pub(super) fn check(
features: &Features,
client_name: Option<&str>,
auth_manager: &AuthManager,
thread: &StoredThread,
) -> Result<(), JSONRPCErrorError> {
if !features.enabled(Feature::CliResumeAccountCheck)
|| !matches!(client_name, Some("codex-tui" | "codex_exec"))
|| thread.rollout_path.is_none()
|| (thread.creator_user_id.is_none() && thread.creator_account_id.is_none())
{
return Ok(());
}
let Some(auth) = auth_manager
.auth_cached()
.filter(CodexAuth::is_chatgpt_auth)
else {
// API keys and other auth modes do not identify a comparable ChatGPT account.
return Ok(());
};
if thread
.creator_user_id
.as_ref()
.is_some_and(|creator| auth.get_chatgpt_user_id().as_ref() != Some(creator))
|| thread
.creator_account_id
.as_ref()
.is_some_and(|creator| auth.get_account_id().as_ref() != Some(creator))
{
return Err(invalid_request(
"This thread was created with a different ChatGPT account or workspace. Sign in with the original account to resume it.",
));
}
Ok(())
}

View File

@@ -0,0 +1,261 @@
#[cfg(test)]
use codex_app_server_protocol::GeneratedImageRef;
use codex_app_server_protocol::McpToolCallResult;
use codex_app_server_protocol::ThreadItemPayload;
use codex_app_server_protocol::Turn;
use serde_json::Value as JsonValue;
// Temporary bandaid for remote clients: thread/resume can include large MCP and
// image-generation payloads. Keep this response-only so persisted rollout
// history, model resume history, and other APIs stay unchanged.
const REDACTED_PAYLOAD: &str = "[redacted]";
const CHATGPT_REMOTE_CLIENT_NAMES: &[&str] =
&["codex_chatgpt_android_remote", "codex_chatgpt_ios_remote"];
pub(super) fn should_redact_thread_resume_payloads(client_name: Option<&str>) -> bool {
client_name.is_some_and(|client_name| CHATGPT_REMOTE_CLIENT_NAMES.contains(&client_name))
}
pub(super) fn redact_thread_resume_payloads(turns: &mut [Turn]) {
for turn in turns {
turn.items.retain_mut(|entry| match &mut entry.payload {
ThreadItemPayload::McpToolCall {
arguments,
result,
error,
..
} => {
*arguments = JsonValue::String(REDACTED_PAYLOAD.to_string());
if result.is_some() {
*result = Some(Box::new(redacted_mcp_tool_call_result()));
}
if let Some(error) = error {
error.message = REDACTED_PAYLOAD.to_string();
}
true
}
ThreadItemPayload::ImageGeneration(_) => false,
_ => true,
});
}
}
fn redacted_mcp_tool_call_result() -> McpToolCallResult {
McpToolCallResult {
content: vec![serde_json::json!({
"type": "text",
"text": REDACTED_PAYLOAD,
})],
structured_content: None,
meta: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use codex_app_server_protocol::ImageGenerationItem;
use codex_app_server_protocol::McpToolCallAppContext;
use codex_app_server_protocol::McpToolCallError;
use codex_app_server_protocol::McpToolCallStatus;
use codex_app_server_protocol::SessionSource;
use codex_app_server_protocol::Thread;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadStatus;
use codex_app_server_protocol::TurnItemsView;
use codex_app_server_protocol::TurnStatus;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
#[test]
fn redacts_mcp_success_result_and_removes_image_generation() {
let mut thread = test_thread(vec![
ThreadItemPayload::AgentMessage {
moderation: None,
id: "agent-1".to_string(),
text: "kept".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
},
ThreadItemPayload::McpToolCall {
id: "mcp-1".to_string(),
server: "docs".to_string(),
tool: "lookup".to_string(),
status: McpToolCallStatus::Completed,
arguments: serde_json::json!({"secret":"argument"}),
app_context: Some(McpToolCallAppContext {
connector_id: "calendar".to_string(),
link_id: Some("link_calendar".to_string()),
resource_uri: Some("ui://widget/lookup.html".to_string()),
app_name: Some("Calendar".to_string()),
action_name: Some("lookup".to_string()),
}),
mcp_app_resource_uri: Some("ui://widget/lookup.html".to_string()),
mcp_app_ui: None,
plugin_id: Some("sample@test".to_string()),
read_only_hint: None,
result: Some(Box::new(McpToolCallResult {
content: vec![serde_json::json!({
"type": "text",
"text": "secret result"
})],
structured_content: Some(serde_json::json!({"secret":"structured"})),
meta: Some(serde_json::json!({"secret":"meta"})),
})),
error: None,
duration_ms: Some(8),
},
ThreadItemPayload::ImageGeneration(ImageGenerationItem {
id: "ig-1".to_string(),
status: "completed".to_string(),
revised_prompt: Some("revised".to_string()),
image: GeneratedImageRef::Inline {
result: "base64-result".to_string(),
},
transparent_background: None,
failure: None,
saved_path: Some(test_path_buf("/tmp/ig-1.png").abs()),
input_images: Vec::new(),
imagegen_request_id: None,
generation_id: None,
}),
]);
thread.turns[0].items[1].started_at_ms = Some(123);
thread.turns[0].items[2].started_at_ms = Some(456);
redact_thread_resume_payloads(&mut thread.turns);
assert_eq!(thread.turns[0].items.len(), 2);
assert_eq!(thread.turns[0].items[1].started_at_ms, Some(123));
assert_eq!(
thread.turns[0].items[0].payload,
ThreadItemPayload::AgentMessage {
moderation: None,
id: "agent-1".to_string(),
text: "kept".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
}
);
assert_eq!(
thread.turns[0].items[1].payload,
ThreadItemPayload::McpToolCall {
id: "mcp-1".to_string(),
server: "docs".to_string(),
tool: "lookup".to_string(),
status: McpToolCallStatus::Completed,
arguments: JsonValue::String(REDACTED_PAYLOAD.to_string()),
app_context: Some(McpToolCallAppContext {
connector_id: "calendar".to_string(),
link_id: Some("link_calendar".to_string()),
resource_uri: Some("ui://widget/lookup.html".to_string()),
app_name: Some("Calendar".to_string()),
action_name: Some("lookup".to_string()),
}),
mcp_app_resource_uri: Some("ui://widget/lookup.html".to_string()),
mcp_app_ui: None,
plugin_id: Some("sample@test".to_string()),
read_only_hint: None,
result: Some(Box::new(redacted_mcp_tool_call_result())),
error: None,
duration_ms: Some(8),
}
);
}
#[test]
fn redacts_mcp_error_message() {
let mut thread = test_thread(vec![ThreadItemPayload::McpToolCall {
id: "mcp-1".to_string(),
server: "docs".to_string(),
tool: "lookup".to_string(),
status: McpToolCallStatus::Failed,
arguments: serde_json::json!({"secret":"argument"}),
app_context: None,
mcp_app_resource_uri: None,
mcp_app_ui: None,
plugin_id: None,
read_only_hint: None,
result: None,
error: Some(McpToolCallError {
message: "secret error".to_string(),
}),
duration_ms: Some(8),
}]);
redact_thread_resume_payloads(&mut thread.turns);
assert_eq!(
thread.turns[0].items[0].payload,
ThreadItemPayload::McpToolCall {
id: "mcp-1".to_string(),
server: "docs".to_string(),
tool: "lookup".to_string(),
status: McpToolCallStatus::Failed,
arguments: JsonValue::String(REDACTED_PAYLOAD.to_string()),
app_context: None,
mcp_app_resource_uri: None,
mcp_app_ui: None,
plugin_id: None,
read_only_hint: None,
result: None,
error: Some(McpToolCallError {
message: REDACTED_PAYLOAD.to_string(),
}),
duration_ms: Some(8),
}
);
}
fn test_thread(items: Vec<ThreadItemPayload>) -> Thread {
Thread {
originator: None,
environments: None,
id: "thread-1".to_string(),
extra: None,
session_id: "session-1".to_string(),
forked_from_id: None,
parent_thread_id: None,
preview: "preview".to_string(),
ephemeral: false,
section: None,
section_entered_at: None,
project_id: None,
daybreak_enabled: None,
history_mode: Default::default(),
model_provider: "mock_provider".to_string(),
model: None,
reasoning_effort: None,
created_at: 0,
updated_at: 0,
recency_at: Some(0),
status: ThreadStatus::Idle,
path: None,
cwd: test_path_buf("/tmp").abs(),
cli_version: "0.0.0".to_string(),
source: SessionSource::Cli,
can_accept_direct_input: None,
thread_source: None,
agent_nickname: None,
agent_role: None,
git_info: None,
name: None,
turns: vec![Turn {
id: "turn-1".to_string(),
root_turn_id: None,
items: items.into_iter().map(ThreadItem::untimed).collect(),
items_view: TurnItemsView::Full,
status: TurnStatus::Completed,
error: None,
started_at: None,
completed_at: None,
duration_ms: None,
}],
}
}
}

View File

@@ -0,0 +1,236 @@
use super::thread_processor::THREAD_LIST_DEFAULT_LIMIT;
use super::thread_processor::THREAD_LIST_MAX_LIMIT;
use super::thread_processor::ThreadRequestProcessor;
use crate::error_code::internal_error;
use crate::error_code::invalid_params;
use crate::error_code::method_not_found;
use codex_app_server_protocol::ClientResponsePayload;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::ThreadSection;
use codex_app_server_protocol::ThreadSectionAppearance;
use codex_app_server_protocol::ThreadSectionCreateParams;
use codex_app_server_protocol::ThreadSectionCreateResponse;
use codex_app_server_protocol::ThreadSectionDeleteParams;
use codex_app_server_protocol::ThreadSectionDeleteResponse;
use codex_app_server_protocol::ThreadSectionListParams;
use codex_app_server_protocol::ThreadSectionListResponse;
use codex_app_server_protocol::ThreadSectionUpdateParams;
use codex_app_server_protocol::ThreadSectionUpdateResponse;
use codex_state::PINNED_THREAD_SECTION_ID;
use codex_thread_store::CreateThreadSectionParams as StoreCreateThreadSectionParams;
use codex_thread_store::DeleteThreadSectionParams as StoreDeleteThreadSectionParams;
use codex_thread_store::ListThreadSectionsParams as StoreListThreadSectionsParams;
use codex_thread_store::RenameThreadSectionParams as StoreRenameThreadSectionParams;
use codex_thread_store::StoredThreadSection;
use codex_thread_store::ThreadStoreError;
const MAX_THREAD_SECTION_APPEARANCE_FIELD_BYTES: usize = 64;
impl ThreadRequestProcessor {
pub(crate) async fn thread_section_list(
&self,
params: ThreadSectionListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
const OPERATION: &str = "threadSection/list";
self.ensure_thread_sections_supported(OPERATION)?;
let limit = params
.limit
.map(|value| value as usize)
.unwrap_or(THREAD_LIST_DEFAULT_LIMIT)
.clamp(1, THREAD_LIST_MAX_LIMIT);
let page = self
.thread_store
.list_thread_sections(StoreListThreadSectionsParams {
cursor: params.cursor,
limit,
})
.await
.map_err(|err| thread_section_store_error(OPERATION, err))?;
Ok(Some(
ThreadSectionListResponse {
data: page.sections.into_iter().map(api_thread_section).collect(),
next_cursor: page.next_cursor,
}
.into(),
))
}
pub(crate) async fn thread_section_create(
&self,
params: ThreadSectionCreateParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
const OPERATION: &str = "threadSection/create";
self.ensure_thread_sections_supported(OPERATION)?;
let name = params.name.trim();
if name.is_empty() {
return Err(invalid_params("section name must not be empty"));
}
if let Some(appearance) = params.appearance.as_ref() {
validate_thread_section_appearance(appearance)?;
}
let section = self
.thread_store
.create_thread_section(StoreCreateThreadSectionParams {
name: name.to_string(),
appearance: params.appearance.map(state_thread_section_appearance),
})
.await
.map_err(|err| thread_section_store_error(OPERATION, err))?;
Ok(Some(
ThreadSectionCreateResponse {
section: api_thread_section(section),
}
.into(),
))
}
pub(crate) async fn thread_section_update(
&self,
params: ThreadSectionUpdateParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
const OPERATION: &str = "threadSection/update";
self.ensure_thread_sections_supported(OPERATION)?;
let name = params.name.trim();
if name.is_empty() {
return Err(invalid_params("section name must not be empty"));
}
if params.section_id.trim().is_empty() {
return Err(invalid_params("sectionId must not be empty"));
}
if params.section_id == PINNED_THREAD_SECTION_ID {
return Err(invalid_params(
"the built-in pinned section cannot be renamed",
));
}
if let Some(Some(appearance)) = params.appearance.as_ref() {
validate_thread_section_appearance(appearance)?;
}
let section = self
.thread_store
.rename_thread_section(StoreRenameThreadSectionParams {
section_id: params.section_id.clone(),
name: name.to_string(),
appearance: params
.appearance
.map(|appearance| appearance.map(state_thread_section_appearance)),
})
.await
.map_err(|err| thread_section_store_error(OPERATION, err))?
.ok_or_else(|| {
invalid_params(format!("thread section not found: {}", params.section_id))
})?;
Ok(Some(
ThreadSectionUpdateResponse {
section: api_thread_section(section),
}
.into(),
))
}
pub(crate) async fn thread_section_delete(
&self,
params: ThreadSectionDeleteParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
const OPERATION: &str = "threadSection/delete";
self.ensure_thread_sections_supported(OPERATION)?;
if params.section_id.trim().is_empty() {
return Err(invalid_params("sectionId must not be empty"));
}
if params.section_id == PINNED_THREAD_SECTION_ID {
return Err(invalid_params(
"the built-in pinned section cannot be deleted",
));
}
let deleted = self
.thread_store
.delete_thread_section(StoreDeleteThreadSectionParams {
section_id: params.section_id.clone(),
})
.await
.map_err(|err| thread_section_store_error(OPERATION, err))?;
if !deleted {
return Err(invalid_params(format!(
"thread section not found: {}",
params.section_id
)));
}
Ok(Some(ThreadSectionDeleteResponse {}.into()))
}
fn ensure_thread_sections_supported(
&self,
operation: &'static str,
) -> Result<(), JSONRPCErrorError> {
if self.thread_store.supports_thread_sections() {
Ok(())
} else {
Err(unsupported_thread_section_operation(operation))
}
}
}
fn validate_thread_section_appearance(
appearance: &ThreadSectionAppearance,
) -> Result<(), JSONRPCErrorError> {
for (field, value) in [
("icon", appearance.icon.as_ref()),
("color", appearance.color.as_ref()),
] {
if value.is_some_and(|value| value.len() > MAX_THREAD_SECTION_APPEARANCE_FIELD_BYTES) {
return Err(invalid_params(format!(
"section appearance {field} must not exceed {MAX_THREAD_SECTION_APPEARANCE_FIELD_BYTES} bytes"
)));
}
}
Ok(())
}
fn api_thread_section(section: StoredThreadSection) -> ThreadSection {
ThreadSection {
id: section.id,
name: section.name,
appearance: section
.appearance
.map(|appearance| ThreadSectionAppearance {
icon: appearance.icon,
color: appearance.color,
}),
}
}
fn state_thread_section_appearance(
appearance: ThreadSectionAppearance,
) -> codex_state::ThreadSectionAppearance {
codex_state::ThreadSectionAppearance {
icon: appearance.icon,
color: appearance.color,
}
}
fn unsupported_thread_section_operation(operation: &'static str) -> JSONRPCErrorError {
method_not_found(format!("{operation} is unavailable without sqlite state"))
}
fn thread_section_store_error(
operation: &'static str,
error: ThreadStoreError,
) -> JSONRPCErrorError {
match error {
ThreadStoreError::Unsupported { .. } => unsupported_thread_section_operation(operation),
ThreadStoreError::InvalidRequest { message } => invalid_params(message),
error @ (ThreadStoreError::ThreadNotFound { .. }
| ThreadStoreError::Conflict { .. }
| ThreadStoreError::Retryable { .. }
| ThreadStoreError::OutcomeUnknown { .. }
| ThreadStoreError::Internal { .. }) => {
let action = operation
.strip_prefix("threadSection/")
.unwrap_or(operation);
internal_error(format!("failed to {action} thread section: {error}"))
}
}
}

View File

@@ -0,0 +1,300 @@
use super::*;
#[cfg(test)]
use chrono::DateTime;
#[cfg(test)]
use chrono::Utc;
use codex_protocol::config_types::MultiAgentMode;
#[cfg(test)]
pub(crate) async fn read_summary_from_rollout(
path: &Path,
fallback_provider: &str,
) -> std::io::Result<ConversationSummary> {
let head = read_head_for_summary(path).await?;
let Some(first) = head.first() else {
return Err(IoError::other(format!(
"rollout at {} is empty",
path.display()
)));
};
let session_meta_line =
serde_json::from_value::<SessionMetaLine>(first.clone()).map_err(|_| {
IoError::other(format!(
"rollout at {} does not start with session metadata",
path.display()
))
})?;
let SessionMetaLine {
meta: session_meta,
git,
} = session_meta_line;
let mut session_meta = session_meta;
session_meta.source = with_thread_spawn_agent_metadata(
session_meta.source.clone(),
session_meta.agent_nickname.clone(),
session_meta.agent_role.clone(),
);
let created_at = if session_meta.timestamp.is_empty() {
None
} else {
Some(session_meta.timestamp.as_str())
};
let updated_at = read_updated_at(path, created_at).await;
if let Some(summary) = extract_conversation_summary(
path.to_path_buf(),
&head,
&session_meta,
git.as_ref(),
fallback_provider,
updated_at.clone(),
) {
return Ok(summary);
}
let timestamp = if session_meta.timestamp.is_empty() {
None
} else {
Some(session_meta.timestamp.clone())
};
let model_provider = session_meta
.model_provider
.clone()
.unwrap_or_else(|| fallback_provider.to_string());
let git_info = git.as_ref().map(map_git_info);
let updated_at = updated_at.or_else(|| timestamp.clone());
Ok(ConversationSummary {
conversation_id: session_meta.id,
timestamp,
updated_at,
path: path.to_path_buf(),
preview: String::new(),
model_provider,
cwd: session_meta.cwd,
cli_version: session_meta.cli_version,
source: session_meta.source,
git_info,
})
}
#[cfg(test)]
fn extract_conversation_summary(
path: PathBuf,
head: &[serde_json::Value],
session_meta: &SessionMeta,
git: Option<&CoreGitInfo>,
fallback_provider: &str,
updated_at: Option<String>,
) -> Option<ConversationSummary> {
let preview = head
.iter()
.filter_map(|value| serde_json::from_value::<ResponseItem>(value.clone()).ok())
.find_map(|item| match codex_core::parse_turn_item(&item) {
Some(TurnItem::UserMessage(user)) => Some(user.message()),
_ => None,
})?;
let preview = strip_user_message_prefix(preview.as_str());
let timestamp = if session_meta.timestamp.is_empty() {
None
} else {
Some(session_meta.timestamp.clone())
};
let conversation_id = session_meta.id;
let model_provider = session_meta
.model_provider
.clone()
.unwrap_or_else(|| fallback_provider.to_string());
let git_info = git.map(map_git_info);
let updated_at = updated_at.or_else(|| timestamp.clone());
Some(ConversationSummary {
conversation_id,
timestamp,
updated_at,
path,
preview: preview.to_string(),
model_provider,
cwd: session_meta.cwd.clone(),
cli_version: session_meta.cli_version.clone(),
source: session_meta.source.clone(),
git_info,
})
}
#[cfg(test)]
fn map_git_info(git_info: &CoreGitInfo) -> ConversationGitInfo {
ConversationGitInfo {
sha: git_info.commit_hash.as_ref().map(|sha| sha.0.clone()),
branch: git_info.branch.clone(),
origin_url: git_info.repository_url.clone().map(String::from),
}
}
pub(super) fn with_thread_spawn_agent_metadata(
source: codex_protocol::protocol::SessionSource,
agent_nickname: Option<String>,
agent_role: Option<String>,
) -> codex_protocol::protocol::SessionSource {
if agent_nickname.is_none() && agent_role.is_none() {
return source;
}
match source {
codex_protocol::protocol::SessionSource::SubAgent(
codex_protocol::protocol::SubAgentSource::ThreadSpawn {
parent_thread_id,
depth,
agent_path,
agent_nickname: existing_agent_nickname,
agent_role: existing_agent_role,
},
) => codex_protocol::protocol::SessionSource::SubAgent(
codex_protocol::protocol::SubAgentSource::ThreadSpawn {
parent_thread_id,
depth,
agent_path,
agent_nickname: agent_nickname.or(existing_agent_nickname),
agent_role: agent_role.or(existing_agent_role),
},
),
_ => source,
}
}
pub(crate) fn thread_response_active_permission_profile(
active_permission_profile: Option<codex_protocol::models::ActivePermissionProfile>,
) -> Option<codex_app_server_protocol::ActivePermissionProfile> {
active_permission_profile.map(Into::into)
}
pub(crate) fn thread_settings_from_config_snapshot(
config_snapshot: &ThreadConfigSnapshot,
) -> ThreadSettings {
ThreadSettings {
disabled_plugin_ids: config_snapshot.disabled_plugin_ids.clone(),
cwd: config_snapshot.cwd().clone(),
approval_policy: config_snapshot.approval_policy.into(),
approvals_reviewer: config_snapshot.approvals_reviewer.into(),
sandbox_policy: config_snapshot.sandbox_policy().into(),
active_permission_profile: thread_response_active_permission_profile(
config_snapshot.active_permission_profile.clone(),
),
model: config_snapshot.model.clone(),
model_provider: config_snapshot.model_provider_id.clone(),
service_tier: config_snapshot.service_tier.clone(),
effort: config_snapshot.reasoning_effort.clone(),
summary: config_snapshot.reasoning_summary,
collaboration_mode: config_snapshot.collaboration_mode.clone(),
multi_agent_mode: MultiAgentMode::ExplicitRequestOnly,
personality: config_snapshot.personality,
}
}
#[cfg(test)]
fn parse_datetime(timestamp: Option<&str>) -> Option<DateTime<Utc>> {
timestamp.and_then(|ts| {
chrono::DateTime::parse_from_rfc3339(ts)
.ok()
.map(|dt| dt.with_timezone(&chrono::Utc))
})
}
#[cfg(test)]
async fn read_updated_at(path: &Path, created_at: Option<&str>) -> Option<String> {
let updated_at = tokio::fs::metadata(path)
.await
.ok()
.and_then(|meta| meta.modified().ok())
.map(|modified| {
let updated_at: DateTime<Utc> = modified.into();
updated_at.to_rfc3339_opts(SecondsFormat::Millis, true)
});
updated_at.or_else(|| created_at.map(str::to_string))
}
pub(super) fn thread_started_notification(mut thread: Thread) -> ThreadStartedNotification {
thread.turns.clear();
ThreadStartedNotification { thread }
}
#[cfg(test)]
pub(crate) fn summary_to_thread(
summary: ConversationSummary,
fallback_cwd: &AbsolutePathBuf,
) -> Thread {
let ConversationSummary {
conversation_id,
path,
preview,
timestamp,
updated_at,
model_provider,
cwd,
cli_version,
source,
git_info,
} = summary;
let created_at = parse_datetime(timestamp.as_deref());
let updated_at = parse_datetime(updated_at.as_deref()).or(created_at);
let git_info = git_info.map(|info| ApiGitInfo {
sha: info.sha,
branch: info.branch,
origin_url: info.origin_url,
});
let cwd =
AbsolutePathBuf::relative_to_current_dir(path_utils::normalize_for_native_workdir(cwd))
.unwrap_or_else(|err| {
warn!(
conversation_id = %conversation_id,
path = %path.display(),
"failed to normalize thread cwd while summarizing thread: {err}"
);
fallback_cwd.clone()
});
let thread_id = conversation_id.to_string();
Thread {
originator: None,
environments: None,
id: thread_id.clone(),
extra: None,
session_id: thread_id,
forked_from_id: None,
parent_thread_id: None,
preview,
ephemeral: false,
section: None,
section_entered_at: None,
project_id: None,
history_mode: ThreadHistoryMode::Legacy,
model_provider,
created_at: created_at.map(|dt| dt.timestamp()).unwrap_or(0),
model: None,
reasoning_effort: None,
updated_at: updated_at.map(|dt| dt.timestamp()).unwrap_or(0),
recency_at: updated_at.map(|dt| dt.timestamp()),
status: ThreadStatus::NotLoaded,
path: (!path.as_os_str().is_empty()).then_some(path),
cwd,
cli_version,
agent_nickname: source.get_nickname(),
agent_role: source.get_agent_role(),
source: source.into(),
can_accept_direct_input: None,
thread_source: None,
git_info,
name: None,
daybreak_enabled: None,
turns: Vec::new(),
}
}
#[cfg(test)]
#[path = "thread_summary_tests.rs"]
mod thread_summary_tests;

View File

@@ -0,0 +1,70 @@
use super::*;
use anyhow::Result;
use codex_protocol::protocol::USER_MESSAGE_BEGIN;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::path::PathBuf;
#[test]
fn extract_conversation_summary_prefers_plain_user_messages() -> Result<()> {
let conversation_id = ThreadId::from_string("3f941c35-29b3-493b-b0a4-e25800d9aeb0")?;
let timestamp = Some("2025-09-05T16:53:11.850Z".to_string());
let path = PathBuf::from("rollout.jsonl");
let head = vec![
json!({
"session_id": conversation_id.to_string(),
"id": conversation_id.to_string(),
"timestamp": timestamp,
"cwd": "/",
"originator": "codex",
"cli_version": "0.0.0",
"model_provider": "test-provider"
}),
json!({
"type": "message",
"role": "user",
"content": [{
"type": "input_text",
"text": "# AGENTS.md instructions for project\n\n<INSTRUCTIONS>\n<AGENTS.md contents>\n</INSTRUCTIONS>".to_string(),
}],
}),
json!({
"type": "message",
"role": "user",
"content": [{
"type": "input_text",
"text": format!("<prior context> {USER_MESSAGE_BEGIN}Count to 5"),
}],
}),
];
let session_meta = serde_json::from_value::<SessionMeta>(head[0].clone())?;
let summary = extract_conversation_summary(
path.clone(),
&head,
&session_meta,
/*git*/ None,
"test-provider",
timestamp.clone(),
)
.expect("summary");
let expected = ConversationSummary {
conversation_id,
timestamp: timestamp.clone(),
updated_at: timestamp,
path,
preview: "Count to 5".to_string(),
model_provider: "test-provider".to_string(),
cwd: PathBuf::from("/"),
cli_version: "0.0.0".to_string(),
source: codex_protocol::protocol::SessionSource::VSCode,
git_info: None,
};
assert_eq!(summary, expected);
Ok(())
}

View File

@@ -0,0 +1,201 @@
//! Replays persisted token usage snapshots when a client attaches to an existing thread.
//!
//! The message processor decides when replay is allowed and preserves JSON-RPC response
//! ordering. This module owns notification construction and the attribution rules that
//! map the latest persisted `TokenCount` back to a v2 turn id.
//!
//! Rollout histories can contain explicit turn ids or generated turn ids. When explicit
//! ids do not match the rebuilt thread, replay falls back to the active turn position at
//! the time the `TokenCount` was persisted so the notification still targets the
//! corresponding rebuilt turn.
use std::sync::Arc;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadHistoryBuilder;
use codex_app_server_protocol::ThreadTokenUsage;
use codex_app_server_protocol::ThreadTokenUsageUpdatedNotification;
use codex_app_server_protocol::Turn;
use codex_app_server_protocol::TurnStatus;
use codex_core::CodexThread;
use codex_protocol::ThreadId;
use codex_protocol::protocol::EventMsg;
use codex_rollout::RolloutItem;
use crate::outgoing_message::ConnectionId;
use crate::outgoing_message::OutgoingMessageSender;
/// Sends a restored token usage update to the connection that attached to a thread.
///
/// This is lifecycle replay rather than a model event: the rollout already contains
/// the original `TokenCount`, and emitting through `send_event` here would duplicate
/// persisted usage records. Keeping replay connection-scoped also avoids
/// surprising other subscribers with a historical usage update while they may be
/// rendering live turn events.
pub(super) async fn send_thread_token_usage_update_to_connection(
outgoing: &Arc<OutgoingMessageSender>,
connection_id: ConnectionId,
thread_id: ThreadId,
conversation: &CodexThread,
token_usage_turn_id: String,
) {
if token_usage_turn_id.is_empty() {
return;
}
let Some(info) = conversation.token_usage_info().await else {
return;
};
let notification = ThreadTokenUsageUpdatedNotification {
thread_id: thread_id.to_string(),
turn_id: token_usage_turn_id,
token_usage: ThreadTokenUsage::from(info),
};
outgoing
.send_server_notification_to_connections(
&[connection_id],
ServerNotification::ThreadTokenUsageUpdated(notification),
)
.await;
}
pub(super) fn restored_token_usage_turn_id(
rollout_items: &[RolloutItem],
turns: &[Turn],
) -> String {
latest_token_usage_turn_id_from_rollout_items(rollout_items, turns)
.unwrap_or_else(|| latest_token_usage_turn_id(turns))
}
/// Identifies the turn that was active when the latest `TokenCount` record appeared.
///
/// The id is preferred when it still appears in the rebuilt thread. The position is a
/// fallback for histories whose implicit turn ids are regenerated during reconstruction.
fn latest_token_usage_turn_id_from_rollout_items(
rollout_items: &[RolloutItem],
turns: &[Turn],
) -> Option<String> {
let token_count_index = rollout_items
.iter()
.rposition(|item| matches!(item, RolloutItem::EventMsg(EventMsg::TokenCount(_))))?;
let mut builder = ThreadHistoryBuilder::new();
for item in &rollout_items[..token_count_index] {
builder.handle_rollout_item(item);
}
if turns.is_empty() {
return builder.active_turn_id_if_explicit();
}
let active_turn_id = builder.active_turn_id()?;
if turns.iter().any(|turn| turn.id == active_turn_id) {
Some(active_turn_id.to_string())
} else {
builder
.active_turn_position()
.and_then(|position| turns.get(position))
.map(|turn| turn.id.clone())
}
}
/// Chooses a fallback turn id that should own a replayed token usage update.
///
/// Normal replay derives the owner from the rollout position of the latest
/// `TokenCount` event. This fallback only preserves a stable wire shape for
/// unusual histories where that rollout information cannot be read.
fn latest_token_usage_turn_id(turns: &[Turn]) -> String {
turns
.iter()
.rev()
.find(|turn| matches!(turn.status, TurnStatus::Completed | TurnStatus::Failed))
.or_else(|| turns.last())
.map(|turn| turn.id.clone())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use codex_app_server_protocol::build_turns_from_rollout_items;
use codex_protocol::protocol::AgentMessageEvent;
use codex_protocol::protocol::TokenCountEvent;
use codex_protocol::protocol::UserMessageEvent;
use pretty_assertions::assert_eq;
#[test]
fn replay_attribution_uses_already_loaded_history() {
let rollout_items = token_usage_history();
let turns = build_turns_from_rollout_items(&rollout_items);
assert_eq!(
latest_token_usage_turn_id_from_rollout_items(&rollout_items, turns.as_slice()),
Some(turns[0].id.clone())
);
}
#[test]
fn replay_attribution_falls_back_to_rebuilt_turn_position() {
let rollout_items = token_usage_history();
let mut turns = build_turns_from_rollout_items(&rollout_items);
turns[0].id = "rebuilt-turn-id".to_string();
assert_eq!(
latest_token_usage_turn_id_from_rollout_items(&rollout_items, turns.as_slice()),
Some("rebuilt-turn-id".to_string())
);
}
#[test]
fn replay_attribution_rejects_suffix_generated_turn_ids() {
let rollout_items = token_usage_history();
assert_eq!(
latest_token_usage_turn_id_from_rollout_items(&rollout_items, /*turns*/ &[]),
None
);
}
#[test]
fn replay_attribution_uses_latest_token_count_and_ignores_tail_turn() {
let mut rollout_items = token_usage_history();
rollout_items.extend(token_usage_history());
let turns = build_turns_from_rollout_items(&rollout_items);
assert_eq!(
latest_token_usage_turn_id_from_rollout_items(&rollout_items, turns.as_slice()),
Some(turns[2].id.clone())
);
}
fn token_usage_history() -> Vec<RolloutItem> {
vec![
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
client_id: None,
message: "first turn".to_string(),
images: None,
local_images: Vec::new(),
text_elements: Vec::new(),
..Default::default()
})),
RolloutItem::EventMsg(EventMsg::AgentMessage(AgentMessageEvent {
moderation: None,
message: "first answer".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
})),
RolloutItem::EventMsg(EventMsg::TokenCount(TokenCountEvent {
info: None,
rate_limits: None,
})),
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
client_id: None,
message: "second turn".to_string(),
images: None,
local_images: Vec::new(),
text_elements: Vec::new(),
..Default::default()
})),
]
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,427 @@
use super::*;
#[cfg(target_os = "windows")]
use anyhow::Context as _;
use codex_protocol::sandbox::SandboxType;
use codex_utils_path_uri::PathUri;
#[derive(Clone)]
pub(crate) struct WindowsSandboxRequestProcessor {
outgoing: Arc<OutgoingMessageSender>,
config: Arc<Config>,
config_manager: ConfigManager,
#[cfg(target_os = "windows")]
registration_refresh: Arc<tokio::sync::OnceCell<()>>,
}
impl WindowsSandboxRequestProcessor {
pub(crate) fn new(
outgoing: Arc<OutgoingMessageSender>,
config: Arc<Config>,
config_manager: ConfigManager,
) -> Self {
codex_core::windows_sandbox::log_windows_sandbox_startup(&config);
Self {
outgoing,
config,
config_manager,
#[cfg(target_os = "windows")]
registration_refresh: Arc::default(),
}
}
pub(crate) async fn windows_sandbox_readiness(
&self,
request_id: &ConnectionRequestId,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
#[cfg(target_os = "windows")]
if codex_windows_sandbox::registered_core_requested()
&& self.config.effective_local_windows_sandbox_type() != SandboxType::WindowsMxc
&& matches!(
WindowsSandboxLevel::from_config(&self.config),
WindowsSandboxLevel::Elevated
)
&& !codex_login::is_workload_identity_selected()
{
let processor = self.clone();
let request_id = request_id.clone();
// Deployment must not hold up unrelated RPCs in the serial dispatcher.
tokio::spawn(async move {
// Coalesce readiness requests. A failed refresh leaves manual setup available.
processor.registration_refresh.get_or_init(|| async {
let config = Arc::clone(&processor.config);
let result = tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
if !codex_windows_sandbox::registered_core_needs_refresh(&config.codex_home)? {
return Ok(());
}
let env_map = std::env::vars().collect();
let policy = config.permissions.effective_permission_profile();
let (settings, listeners) = match config.permissions.network.as_ref() {
Some(network) => network.windows_sandbox_proxy_listeners()?,
None => (
codex_windows_sandbox::WindowsSandboxProvisioningSettings::from_environment(&policy, &env_map),
codex_windows_sandbox::WindowsSandboxProxyListeners::from_environment(&policy, &env_map),
),
};
codex_windows_sandbox::refresh_registered_core_via_service(
&config.codex_home, settings, listeners,
)?;
Ok(())
}).await.map_err(anyhow::Error::from).and_then(std::convert::identity);
if let Err(error) = result {
warn!("Registered Core startup refresh requires manual setup: {error:#}");
}
}).await;
processor
.outgoing
.send_response(
request_id,
determine_windows_sandbox_readiness(&processor.config),
)
.await;
});
return Ok(None);
}
#[cfg(not(target_os = "windows"))]
let _ = request_id;
Ok(Some(
determine_windows_sandbox_readiness(&self.config).into(),
))
}
pub(crate) async fn windows_sandbox_setup_start(
&self,
request_id: &ConnectionRequestId,
params: WindowsSandboxSetupStartParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.windows_sandbox_setup_start_inner(request_id, params)
.await
.map(|()| None)
}
async fn windows_sandbox_setup_start_inner(
&self,
request_id: &ConnectionRequestId,
params: WindowsSandboxSetupStartParams,
) -> Result<(), JSONRPCErrorError> {
// Validate requirements before acknowledging setup so callers do not get a
// `started` response for a Windows sandbox mode that cannot be persisted.
let (config, command_cwd) = load_setup_config(
&self.config_manager,
self.config.cwd.as_path(),
params.cwd.map(PathBuf::from),
)
.await
.map_err(|err| config_load_error(&err))?;
let setup_mode = resolve_allowed_windows_sandbox_setup_mode(
config.config_layer_stack.requirements(),
params.mode,
)?;
// Provisioning installs native Windows filesystem permissions. Validate
// this boundary before acknowledging that setup has started.
let workspace_roots = config
.effective_workspace_roots()
.iter()
.map(PathUri::to_abs_path)
.collect::<std::io::Result<Vec<_>>>()
.map_err(|err| {
invalid_request(format!(
"workspace roots are not native to this host: {err}"
))
})?;
self.outgoing
.send_response(
request_id.clone(),
WindowsSandboxSetupStartResponse { started: true },
)
.await;
let outgoing = Arc::clone(&self.outgoing);
let connection_id = request_id.connection_id;
tokio::spawn(async move {
let setup_request = WindowsSandboxSetupRequest {
mode: setup_mode,
permission_profile: config.permissions.effective_permission_profile(),
workspace_roots,
command_cwd,
env_map: std::env::vars().collect(),
codex_home: config.codex_home.to_path_buf(),
};
let setup_result = async {
// Workload identity is process-local, so use the existing helper path with
// the caller's resolved configuration instead of loading auth in the service.
#[cfg(target_os = "windows")]
if setup_mode == CoreWindowsSandboxSetupMode::Elevated
&& (codex_windows_sandbox::registered_core_requested()
|| config.features.enabled(Feature::WindowsSandboxService))
&& !codex_login::is_workload_identity_selected()
{
let provisioning = match config
.permissions
.network
.as_ref()
.map_or_else(
|| {
Ok((
codex_windows_sandbox::WindowsSandboxProvisioningSettings::from_environment(
&setup_request.permission_profile,
&setup_request.env_map,
),
codex_windows_sandbox::WindowsSandboxProxyListeners::from_environment(
&setup_request.permission_profile,
&setup_request.env_map,
),
))
},
codex_core::config::NetworkProxySpec::windows_sandbox_proxy_listeners,
)
{
Ok(provisioning) => Some(provisioning),
Err(error) => {
if codex_windows_sandbox::registered_core_requested() {
return Err(error).context("registered Core requires service-compatible proxy settings");
}
warn!(
"Windows sandbox service does not support the configured proxy listeners; falling back to elevated setup: {error}"
);
None
}
};
if let Some((settings, listeners)) = provisioning {
let service_setup_request = setup_request.clone();
let service_setup_start = Instant::now();
tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
if matches!(
&service_setup_request.permission_profile,
codex_protocol::models::PermissionProfile::Disabled
) {
// Only registered Core needs service provisioning for full access;
// legacy setup keeps using the shared setup path below.
if !codex_windows_sandbox::registered_core_requested() {
return Ok(());
}
} else {
let Ok(permissions) = codex_windows_sandbox::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
&service_setup_request.permission_profile,
&service_setup_request.workspace_roots,
) else {
anyhow::ensure!(!codex_windows_sandbox::registered_core_requested(),
"registered Core requires a service-compatible sandbox policy");
// The existing setup path can still succeed for completed
// provisioning without resolving the current profile.
return Ok(());
};
permissions.validate_elevated_filesystem_policy(
&service_setup_request.command_cwd,
)?;
}
if codex_windows_sandbox::registered_core_requested() {
codex_windows_sandbox::start_windows_sandbox_service_for_setup()?;
}
// The shared setup path below handles helper fallback and
// refreshes workspace ACLs after provisioning.
codex_windows_sandbox::provision_windows_sandbox_via_service(
&service_setup_request.codex_home,
settings,
listeners,
)?;
Ok(())
})
.await
.map_err(|error| {
anyhow::anyhow!(
"Windows sandbox service provisioning task failed: {error}"
)
})
.and_then(std::convert::identity)
.inspect_err(|error| {
codex_core::windows_sandbox::emit_windows_sandbox_setup_failure_metrics(
setup_mode,
service_setup_start.elapsed(),
error,
);
})?;
}
}
codex_core::windows_sandbox::run_windows_sandbox_setup(setup_request).await
}
.await;
let notification = WindowsSandboxSetupCompletedNotification {
mode: match setup_mode {
CoreWindowsSandboxSetupMode::Elevated => WindowsSandboxSetupMode::Elevated,
CoreWindowsSandboxSetupMode::Unelevated => WindowsSandboxSetupMode::Unelevated,
},
success: setup_result.is_ok(),
error: setup_result.err().map(|err| err.to_string()),
};
outgoing
.send_server_notification_to_connections(
&[connection_id],
ServerNotification::WindowsSandboxSetupCompleted(notification),
)
.await;
});
Ok(())
}
}
async fn load_setup_config(
manager: &ConfigManager,
fallback_cwd: &std::path::Path,
requested_cwd: Option<PathBuf>,
) -> std::io::Result<(Config, PathBuf)> {
// Setup without a project must not grant writes to the app's install directory.
let workspace_roots = requested_cwd.is_none().then(Vec::new);
let cwd = requested_cwd.unwrap_or_else(|| fallback_cwd.to_path_buf());
let config = manager
.load_for_cwd(
/*request_overrides*/ None,
ConfigOverrides {
cwd: Some(cwd.clone()),
workspace_roots,
..Default::default()
},
Some(cwd.clone()),
)
.await?;
Ok((config, cwd))
}
#[cfg(test)]
#[path = "windows_sandbox_setup_config_tests.rs"]
mod setup_config_tests;
/// Resolves the requested API mode after checking that managed requirements allow it.
fn resolve_allowed_windows_sandbox_setup_mode(
requirements: &codex_config::ConfigRequirements,
requested_mode: WindowsSandboxSetupMode,
) -> Result<CoreWindowsSandboxSetupMode, JSONRPCErrorError> {
let (setup_mode, config_mode) = match requested_mode {
WindowsSandboxSetupMode::Elevated => (
CoreWindowsSandboxSetupMode::Elevated,
codex_config::types::WindowsSandboxModeToml::Elevated,
),
WindowsSandboxSetupMode::Unelevated => (
CoreWindowsSandboxSetupMode::Unelevated,
codex_config::types::WindowsSandboxModeToml::Unelevated,
),
};
requirements
.windows_sandbox_mode
.can_set(&Some(config_mode))
.map_err(|err| invalid_request(format!("invalid Windows sandbox setup mode: {err}")))?;
Ok(setup_mode)
}
fn determine_windows_sandbox_readiness(config: &Config) -> WindowsSandboxReadinessResponse {
if !cfg!(windows) {
return WindowsSandboxReadinessResponse {
status: WindowsSandboxReadiness::NotConfigured,
};
}
if config.effective_local_windows_sandbox_type() == SandboxType::WindowsMxc {
return WindowsSandboxReadinessResponse {
status: WindowsSandboxReadiness::Ready,
};
}
determine_windows_sandbox_readiness_from_state(
WindowsSandboxLevel::from_config(config),
sandbox_setup_is_complete(config.codex_home.as_path()),
)
}
fn determine_windows_sandbox_readiness_from_state(
windows_sandbox_level: WindowsSandboxLevel,
sandbox_setup_is_complete: bool,
) -> WindowsSandboxReadinessResponse {
let status = match windows_sandbox_level {
WindowsSandboxLevel::Disabled => WindowsSandboxReadiness::NotConfigured,
WindowsSandboxLevel::RestrictedToken => WindowsSandboxReadiness::Ready,
WindowsSandboxLevel::Elevated => {
if sandbox_setup_is_complete {
WindowsSandboxReadiness::Ready
} else {
WindowsSandboxReadiness::UpdateRequired
}
}
};
WindowsSandboxReadinessResponse { status }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error_code::INVALID_REQUEST_ERROR_CODE;
use codex_config::ConfigRequirements;
use codex_config::Constrained;
use codex_config::ConstrainedWithSource;
use codex_config::types::WindowsSandboxModeToml;
#[test]
fn resolve_allowed_windows_sandbox_setup_mode_rejects_disallowed_mode() {
let requirements = ConfigRequirements {
windows_sandbox_mode: ConstrainedWithSource::new(
Constrained::allow_only(Some(WindowsSandboxModeToml::Elevated)),
/*source*/ None,
),
..Default::default()
};
let err = resolve_allowed_windows_sandbox_setup_mode(
&requirements,
WindowsSandboxSetupMode::Unelevated,
)
.expect_err("unelevated setup should be rejected");
assert_eq!(err.code, INVALID_REQUEST_ERROR_CODE);
assert!(
err.message.contains("invalid Windows sandbox setup mode"),
"{err:?}"
);
}
#[test]
fn determine_windows_sandbox_readiness_reports_not_configured_when_disabled() {
let response = determine_windows_sandbox_readiness_from_state(
WindowsSandboxLevel::Disabled,
/*sandbox_setup_is_complete*/ false,
);
assert_eq!(response.status, WindowsSandboxReadiness::NotConfigured);
}
#[test]
fn determine_windows_sandbox_readiness_reports_ready_for_unelevated_mode() {
let response = determine_windows_sandbox_readiness_from_state(
WindowsSandboxLevel::RestrictedToken,
/*sandbox_setup_is_complete*/ false,
);
assert_eq!(response.status, WindowsSandboxReadiness::Ready);
}
#[test]
fn determine_windows_sandbox_readiness_reports_ready_for_complete_elevated_mode() {
let response = determine_windows_sandbox_readiness_from_state(
WindowsSandboxLevel::Elevated,
/*sandbox_setup_is_complete*/ true,
);
assert_eq!(response.status, WindowsSandboxReadiness::Ready);
}
#[test]
fn determine_windows_sandbox_readiness_reports_update_required_when_elevated_setup_is_stale() {
let response = determine_windows_sandbox_readiness_from_state(
WindowsSandboxLevel::Elevated,
/*sandbox_setup_is_complete*/ false,
);
assert_eq!(response.status, WindowsSandboxReadiness::UpdateRequired);
}
}

View File

@@ -0,0 +1,42 @@
//! Exercise the setup RPC's real configuration loading without changing Windows accounts or ACLs.
use super::ConfigManager;
use super::load_setup_config;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn omitted_cwd_does_not_make_the_server_directory_a_workspace() -> anyhow::Result<()> {
let home = tempfile::tempdir()?;
let install = tempfile::tempdir()?;
let manager = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf());
let (config, command_cwd) =
load_setup_config(&manager, install.path(), /*requested_cwd*/ None).await?;
assert_eq!(
(command_cwd, config.effective_workspace_roots()),
(install.path().to_path_buf(), Vec::new()),
);
Ok(())
}
#[tokio::test]
async fn explicit_cwd_remains_the_setup_workspace() -> anyhow::Result<()> {
let home = tempfile::tempdir()?;
let install = tempfile::tempdir()?;
let project = tempfile::tempdir()?;
let manager = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf());
let (config, command_cwd) =
load_setup_config(&manager, install.path(), Some(project.path().to_path_buf())).await?;
let expected = AbsolutePathBuf::from_absolute_path(project.path())?;
assert_eq!(
(command_cwd, config.effective_workspace_roots()),
(
project.path().to_path_buf(),
vec![PathUri::from_abs_path(&expected)],
),
);
Ok(())
}