aKode fase 2b-1 (WIP): rimossi cloud-config, apps MCP ChatGPT, upload file, connectors-extension, rate limits backend; plugin remoti in corso (test non ancora compilanti)
Some checks failed
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled

This commit is contained in:
Andrea
2026-11-09 13:55:36 +01:00
parent 137106bf17
commit e4209e2755
166 changed files with 155 additions and 31558 deletions

View File

@@ -7,9 +7,7 @@ use crate::auth_mode::auth_mode_to_api;
use crate::external_auth::ExternalAuthBridge;
use crate::model_catalog::ModelCatalog;
use crate::outgoing_message::AccountNotification;
use chrono::DateTime;
use codex_app_server_protocol::DesktopOnboardingEntrypoint;
use codex_app_server_protocol::GetAccountRateLimitsParams;
use codex_login::LoginOnboardingEntrypoint;
use codex_login::login_with_bedrock_access_keys;
use codex_mcp::ema_auth_scope;
@@ -17,13 +15,11 @@ use codex_model_provider::is_supported_amazon_bedrock_region;
use codex_otel::auth_storage::AuthStorageOriginator;
use codex_rmcp_client::EnterpriseOAuthCredentialGuard;
mod backend_client;
mod bedrock_gov_cloud;
mod bedrock_setup;
mod enterprise_login;
mod gateway_oauth;
mod gcp_setup;
mod rate_limit_resets;
mod security_setup;
mod workspace_routing;
mod workspace_switching;
@@ -34,10 +30,6 @@ pub(crate) use gcp_setup::handle_gcp_setup;
// Duration before a browser ChatGPT login attempt is abandoned.
const LOGIN_CHATGPT_TIMEOUT: Duration = Duration::from_secs(10 * 60);
const ACCOUNT_TOKEN_USAGE_FETCH_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
const THREAD_USAGE_FETCH_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 60);
const ACCOUNT_WORKSPACE_MESSAGES_FETCH_TIMEOUT: Duration =
Duration::from_millis(/*millis*/ 1000);
// Packaged clients use this together with the OAuth client ID override for staging login.
const LOGIN_ISSUER_OVERRIDE_ENV_VAR: &str = "CODEX_APP_SERVER_LOGIN_ISSUER";
// The development success-page redirect remains debug-only.
@@ -205,41 +197,6 @@ impl AccountRequestProcessor {
.map(|response| Some(response.into()))
}
pub(crate) async fn get_account_rate_limits(
&self,
params: Option<GetAccountRateLimitsParams>,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.get_account_rate_limits_response(params.unwrap_or_default())
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn get_account_token_usage(
&self,
params: Option<GetAccountTokenUsageParams>,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.get_account_token_usage_response(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn get_workspace_messages(
&self,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.get_workspace_messages_response()
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn send_add_credits_nudge_email(
&self,
params: SendAddCreditsNudgeEmailParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.send_add_credits_nudge_email_response(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn cancel_active_login(&self) {
self.cancel_gateway_login();
self.enterprise_login.cancel(/*login_id*/ None).await;
@@ -1169,376 +1126,6 @@ impl AccountRequestProcessor {
Ok(response)
}
async fn get_account_rate_limits_response(
&self,
params: GetAccountRateLimitsParams,
) -> Result<GetAccountRateLimitsResponse, 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 to read rate limits",
));
};
if !auth.uses_codex_backend() {
return Err(invalid_request(
"chatgpt authentication required to read rate limits",
));
}
let client = self.backend_client(&auth, http_client_factory).await?;
let usage_request = async {
if params.supports_luna_reserve
&& auth.auth_mode() == codex_protocol::auth::AuthMode::Chatgpt
&& !auth.is_fedramp_account()
{
client.get_rate_limits_with_luna_reserve().await
} else {
client.get_rate_limits_with_reset_credits().await
}
};
let (response, detailed_rate_limit_reset_credits) = tokio::join!(usage_request, async {
if params.exclude_reset_credit_details {
None
} else {
Self::detailed_rate_limit_reset_credits(&client).await
}
},);
let response = response
.map_err(|err| internal_error(format!("failed to fetch codex rate limits: {err}")))?;
if response.rate_limits.is_empty() {
return Err(internal_error(
"failed to fetch codex rate limits: no snapshots returned",
));
}
let rate_limits_by_limit_id: HashMap<_, _> = response
.rate_limits
.iter()
.cloned()
.map(|snapshot| {
let limit_id = snapshot
.limit_id
.clone()
.unwrap_or_else(|| "codex".to_string());
(limit_id, snapshot)
})
.collect();
let rate_limits = response
.rate_limits
.iter()
.find(|snapshot| snapshot.limit_id.as_deref() == Some("codex"))
.cloned()
.unwrap_or_else(|| response.rate_limits[0].clone());
let rate_limit_reset_credits = detailed_rate_limit_reset_credits.or_else(|| {
response
.rate_limit_reset_credits
.map(|summary| RateLimitResetCreditsSummary {
available_count: summary.available_count,
credits: None,
})
});
// Match desktop's account readiness check before exposing account-bound CTA content.
// Normal rate limits remain available when older backends omit identity or banner data.
// Login can change while the backend read is in flight.
let active_auth = self.auth_manager.auth().await;
let matches_active_account = active_auth.is_some_and(|auth| {
!auth.is_fedramp_account()
&& response.account_id.is_some()
&& response.account_id == auth.get_account_id()
&& response.user_id.is_some()
&& response.user_id == auth.get_chatgpt_user_id()
});
let rate_limit_upsell = response
.rate_limit_upsell
.filter(|_| matches_active_account);
Ok(GetAccountRateLimitsResponse {
ordinary_usage_allowed: response
.ordinary_usage_allowed
.filter(|_| matches_active_account),
rate_limits: rate_limits.into(),
rate_limits_by_limit_id: Some(
rate_limits_by_limit_id
.into_iter()
.map(|(limit_id, snapshot)| (limit_id, snapshot.into()))
.collect(),
),
rate_limit_reset_credits,
account_id: response.account_id,
rate_limit_upsell,
})
}
async fn get_account_token_usage_response(
&self,
params: Option<GetAccountTokenUsageParams>,
) -> Result<GetAccountTokenUsageResponse, JSONRPCErrorError> {
let thread_id = params
.and_then(|params| params.thread_id)
.map(|thread_id| {
ThreadId::from_string(&thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))
})
.transpose()?;
let Some((auth, http_client_factory)) =
self.auth_manager.auth_with_http_client_factory().await
else {
return Err(invalid_request(
"codex account authentication required to read token usage",
));
};
if !auth.uses_codex_backend() {
return Err(invalid_request(
"chatgpt authentication required to read token usage",
));
}
let client = self.backend_client(&auth, http_client_factory).await?;
if let Some(thread_id) = thread_id {
let thread_id = thread_id.to_string();
let usage = tokio::time::timeout(
THREAD_USAGE_FETCH_TIMEOUT,
client.get_thread_usage(&thread_id),
)
.await
.map_err(|_| internal_error("thread usage fetch timed out"))?;
let thread_usage = match usage {
Ok(usage) => Some(codex_app_server_protocol::ThreadUsage {
thread_id: usage.thread_id,
estimated_usage_credits_micros: usage.estimated_usage_credits_micros,
estimated_usage_usd_micros: usage.estimated_usage_usd_micros,
native_usage_usd_micros: usage.native_usage_usd_micros,
groups: usage
.groups
.into_iter()
.map(
|group| codex_app_server_protocol::ThreadUsageBreakdownGroup {
model: group.model,
reasoning_effort: group.reasoning_effort,
speed: group.speed,
estimated_usage_credits_micros: group
.estimated_usage_credits_micros,
net_new_input_tokens: group.net_new_input_tokens,
cached_input_tokens: group.cached_input_tokens,
input_tokens: group.input_tokens,
output_tokens: group.output_tokens,
total_tokens: group.total_tokens,
},
)
.collect(),
}),
Err(err)
if matches!(err.status().map(|status| status.as_u16()), Some(403 | 404)) =>
{
None
}
Err(err) => {
return Err(internal_error(format!(
"failed to fetch thread usage: {err}"
)));
}
};
return Ok(GetAccountTokenUsageResponse {
summary: AccountTokenUsageSummary {
lifetime_tokens: None,
peak_daily_tokens: None,
longest_running_turn_sec: None,
current_streak_days: None,
longest_streak_days: None,
},
daily_usage_buckets: None,
thread_usage,
});
}
let profile = tokio::time::timeout(
ACCOUNT_TOKEN_USAGE_FETCH_TIMEOUT,
client.get_token_usage_profile(),
)
.await
.map_err(|_| internal_error("token usage profile fetch timed out"))?
.map_err(|err| internal_error(format!("failed to fetch token usage profile: {err}")))?;
Ok(Self::account_token_usage_response(profile))
}
async fn get_workspace_messages_response(
&self,
) -> Result<GetWorkspaceMessagesResponse, 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 to read workspace messages",
));
};
if !auth.uses_codex_backend() {
return Err(invalid_request(
"chatgpt authentication required to read workspace messages",
));
}
let client = self.backend_client(&auth, http_client_factory).await?;
let messages = tokio::time::timeout(
ACCOUNT_WORKSPACE_MESSAGES_FETCH_TIMEOUT,
client.list_workspace_messages(),
)
.await
.map_err(|_| internal_error("workspace messages fetch timed out"))?;
match messages {
Ok(messages) => {
Self::workspace_messages_response(messages, /*feature_enabled*/ true)
}
Err(err) if workspace_messages_feature_disabled(&err) => {
Self::workspace_messages_response(
BackendWorkspaceMessagesResponse {
messages: Vec::new(),
},
/*feature_enabled*/ false,
)
}
Err(err) => Err(internal_error(format!(
"failed to fetch workspace messages: {err}"
))),
}
}
fn account_token_usage_response(profile: TokenUsageProfile) -> GetAccountTokenUsageResponse {
let stats = profile.stats;
GetAccountTokenUsageResponse {
summary: AccountTokenUsageSummary {
lifetime_tokens: stats.lifetime_tokens,
peak_daily_tokens: stats.peak_daily_tokens,
longest_running_turn_sec: stats.longest_running_turn_sec,
current_streak_days: stats.current_streak_days,
longest_streak_days: stats.longest_streak_days,
},
daily_usage_buckets: stats.daily_usage_buckets.map(|buckets| {
buckets
.into_iter()
.map(|bucket| AccountTokenUsageDailyBucket {
start_date: bucket.start_date,
tokens: bucket.tokens,
})
.collect()
}),
thread_usage: None,
}
}
fn workspace_messages_response(
messages: BackendWorkspaceMessagesResponse,
feature_enabled: bool,
) -> Result<GetWorkspaceMessagesResponse, JSONRPCErrorError> {
Ok(GetWorkspaceMessagesResponse {
feature_enabled,
messages: messages
.messages
.into_iter()
.map(workspace_message_from_backend)
.collect::<Result<Vec<_>, _>>()?,
})
}
async fn send_add_credits_nudge_email_response(
&self,
params: SendAddCreditsNudgeEmailParams,
) -> Result<SendAddCreditsNudgeEmailResponse, JSONRPCErrorError> {
self.send_add_credits_nudge_email_inner(params)
.await
.map(|status| SendAddCreditsNudgeEmailResponse { status })
}
async fn send_add_credits_nudge_email_inner(
&self,
params: SendAddCreditsNudgeEmailParams,
) -> Result<AddCreditsNudgeEmailStatus, 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 to notify workspace owner",
));
};
if !auth.uses_codex_backend() {
return Err(invalid_request(
"chatgpt authentication required to notify workspace owner",
));
}
let client = self.backend_client(&auth, http_client_factory).await?;
match client
.send_add_credits_nudge_email(Self::backend_credit_type(params.credit_type))
.await
{
Ok(()) => Ok(AddCreditsNudgeEmailStatus::Sent),
Err(err) if err.status().is_some_and(|status| status.as_u16() == 429) => {
Ok(AddCreditsNudgeEmailStatus::CooldownActive)
}
Err(err) => Err(internal_error(format!(
"failed to notify workspace owner: {err}"
))),
}
}
fn backend_credit_type(value: AddCreditsNudgeCreditType) -> BackendAddCreditsNudgeCreditType {
match value {
AddCreditsNudgeCreditType::Credits => BackendAddCreditsNudgeCreditType::Credits,
AddCreditsNudgeCreditType::UsageLimit => BackendAddCreditsNudgeCreditType::UsageLimit,
}
}
}
fn workspace_message_from_backend(
message: BackendWorkspaceMessage,
) -> Result<WorkspaceMessage, JSONRPCErrorError> {
Ok(WorkspaceMessage {
message_id: message.message_id,
message_type: workspace_message_type_from_backend(message.message_type),
message_body: message.message_body,
created_at: workspace_message_timestamp_from_backend(message.created_at)?,
archived_at: workspace_message_timestamp_from_backend(message.archived_at)?,
})
}
fn workspace_message_timestamp_from_backend(
timestamp: Option<String>,
) -> Result<Option<i64>, JSONRPCErrorError> {
timestamp
.map(|timestamp| {
DateTime::parse_from_rfc3339(&timestamp)
.map(|timestamp| timestamp.timestamp())
.map_err(|err| {
internal_error(format!(
"failed to parse workspace message timestamp `{timestamp}`: {err}"
))
})
})
.transpose()
}
fn workspace_message_type_from_backend(
message_type: BackendWorkspaceMessageType,
) -> WorkspaceMessageType {
match message_type {
BackendWorkspaceMessageType::Headline => WorkspaceMessageType::Headline,
BackendWorkspaceMessageType::Announcement => WorkspaceMessageType::Announcement,
BackendWorkspaceMessageType::Unknown => WorkspaceMessageType::Unknown,
}
}
fn workspace_messages_feature_disabled(err: &BackendRequestError) -> bool {
err.status().is_some_and(|status| status.as_u16() == 404)
}
/// Remove account credentials using the current account's policy, even during startup recovery.
@@ -1616,98 +1203,3 @@ pub(crate) async fn clear_account_configuration(
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use codex_backend_client::TokenUsageProfileDailyBucket;
use codex_backend_client::TokenUsageProfileStats;
use http::StatusCode;
use pretty_assertions::assert_eq;
#[test]
fn account_token_usage_response_maps_profile_stats_and_daily_buckets() {
let response = AccountRequestProcessor::account_token_usage_response(TokenUsageProfile {
stats: TokenUsageProfileStats {
lifetime_tokens: Some(123),
peak_daily_tokens: Some(45),
longest_running_turn_sec: Some(67),
current_streak_days: Some(8),
longest_streak_days: Some(9),
daily_usage_buckets: Some(vec![TokenUsageProfileDailyBucket {
start_date: "2026-05-29".to_string(),
tokens: 10,
}]),
},
});
assert_eq!(
response,
GetAccountTokenUsageResponse {
summary: AccountTokenUsageSummary {
lifetime_tokens: Some(123),
peak_daily_tokens: Some(45),
longest_running_turn_sec: Some(67),
current_streak_days: Some(8),
longest_streak_days: Some(9),
},
daily_usage_buckets: Some(vec![AccountTokenUsageDailyBucket {
start_date: "2026-05-29".to_string(),
tokens: 10,
}]),
thread_usage: None,
}
);
}
#[test]
fn workspace_messages_response_maps_backend_messages() {
let response = AccountRequestProcessor::workspace_messages_response(
BackendWorkspaceMessagesResponse {
messages: vec![BackendWorkspaceMessage {
message_id: "headline-id".to_string(),
message_type: BackendWorkspaceMessageType::Headline,
message_body: "Headline body".to_string(),
created_at: Some("2026-06-14T00:00:00Z".to_string()),
archived_at: Some("2026-06-15T00:00:00Z".to_string()),
}],
},
/*feature_enabled*/ true,
)
.expect("workspace message timestamps should parse");
assert_eq!(
response,
GetWorkspaceMessagesResponse {
feature_enabled: true,
messages: vec![WorkspaceMessage {
message_id: "headline-id".to_string(),
message_type: WorkspaceMessageType::Headline,
message_body: "Headline body".to_string(),
created_at: Some(1_781_395_200),
archived_at: Some(1_781_481_600),
}],
}
);
}
#[test]
fn workspace_messages_feature_disabled_only_for_not_found() {
let cases = [
(StatusCode::NOT_FOUND, true),
(StatusCode::UNAUTHORIZED, false),
(StatusCode::FORBIDDEN, false),
];
for (status, expected) in cases {
let err = BackendRequestError::UnexpectedStatus {
method: "GET".to_string(),
url: "https://example.test/api/codex/workspace-messages".to_string(),
status,
content_type: "application/json".to_string(),
body: "{}".to_string(),
identity_error_code: None,
};
assert_eq!(workspace_messages_feature_disabled(&err), expected);
}
}
}

View File

@@ -1,31 +0,0 @@
//! 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

@@ -1,169 +0,0 @@
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

@@ -1,497 +0,0 @@
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

@@ -1,293 +0,0 @@
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

@@ -1,149 +0,0 @@
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

@@ -1,108 +0,0 @@
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

@@ -1,8 +1,8 @@
use super::apps_processor::APP_READ_MAX_IDS;
use super::config_processor::reload_user_config;
use super::*;
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use crate::error_code::method_not_found;
use codex_analytics::PluginInstallSource;
use codex_app_server_protocol::PluginAvailability;
use codex_app_server_protocol::PluginSharePrincipalRole;
@@ -1831,78 +1831,15 @@ impl PluginRequestProcessor {
);
}
/// ChatGPT apps never need auth in aKode: the hosted apps MCP server is never used.
async fn plugin_apps_needing_auth_for_install(
&self,
config: &Config,
auth: Option<&CodexAuth>,
plugin_id: &str,
plugin_app_declarations: &[codex_plugin::AppDeclaration],
_config: &Config,
_auth: Option<&CodexAuth>,
_plugin_id: &str,
_plugin_app_declarations: &[codex_plugin::AppDeclaration],
) -> Vec<AppSummary> {
if plugin_app_declarations.is_empty()
|| !config
.features
.apps_enabled_for_auth(auth.is_some_and(CodexAuth::is_chatgpt_auth))
{
return Vec::new();
}
let plugin_apps =
codex_plugin::app_connector_ids_from_declarations(plugin_app_declarations);
let app_category_by_id = plugin_app_declarations
.iter()
.filter_map(|app| {
app.category
.as_ref()
.map(|category| (app.connector_id.0.clone(), category.clone()))
})
.collect();
let environment_manager = self.thread_manager.environment_manager();
let (app_summaries, accessible_connectors_result) = tokio::join!(
load_plugin_app_summaries(
&self.thread_manager,
config,
auth,
&plugin_apps,
&app_category_by_id
),
connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager(
config,
/*force_refetch*/ true,
Arc::clone(&environment_manager),
self.thread_manager.mcp_manager(),
),
);
let (accessible_connectors, codex_apps_ready) = match accessible_connectors_result {
Ok(status) => (status.connectors, status.codex_apps_ready),
Err(err) => {
warn!(
plugin = plugin_id,
"failed to load accessible apps after plugin install: {err:#}"
);
(
connectors::list_cached_accessible_connectors_from_mcp_tools(config, auth)
.unwrap_or_default(),
false,
)
}
};
if !codex_apps_ready {
warn!(
plugin = plugin_id,
"codex_apps MCP not ready after plugin install; skipping appsNeedingAuth check"
);
return Vec::new();
}
let accessible_ids = accessible_connectors
.iter()
.map(|connector| connector.id.as_str())
.collect::<HashSet<_>>();
app_summaries
.into_iter()
.filter(|app| !accessible_ids.contains(app.id.as_str()))
.collect()
Vec::new()
}
async fn start_plugin_mcp_oauth_logins(
@@ -2182,79 +2119,25 @@ impl PluginRequestProcessor {
}
}
/// Summarizes plugin app declarations locally; aKode never fetches ChatGPT app metadata.
async fn load_plugin_app_summaries(
thread_manager: &ThreadManager,
config: &Config,
auth: Option<&CodexAuth>,
_thread_manager: &ThreadManager,
_config: &Config,
_auth: Option<&CodexAuth>,
plugin_apps: &[codex_plugin::AppConnectorId],
app_category_by_id: &HashMap<String, String>,
) -> Vec<AppSummary> {
let mut seen_app_ids = HashSet::new();
let app_ids = plugin_apps
plugin_apps
.iter()
.map(|app| app.0.clone())
.filter(|app_id| seen_app_ids.insert(app_id.clone()))
.collect::<Vec<_>>();
let mut metadata_by_id = HashMap::new();
if let Some(auth) = auth.filter(|auth| {
config
.features
.apps_enabled_for_auth(auth.uses_codex_backend())
}) {
metadata_by_id.extend(
codex_connectors::ConnectorMetadataStore::new(
config.chatgpt_base_url.clone(),
auth.get_account_id(),
auth.get_chatgpt_user_id(),
auth.is_workspace_account(),
)
.fresh_records(&app_ids, /*include_tools*/ false),
);
let runtime = thread_manager.runtime_auth_for_config(config);
for app_ids in app_ids.chunks(APP_READ_MAX_IDS) {
let runtime = match &runtime {
Ok(runtime) => runtime.as_ref(),
Err(error) => {
warn!("failed to initialize app metadata authentication: {error}");
break;
}
};
match connectors::read_connector_metadata(
config, auth, runtime, app_ids, /*include_tools*/ false,
)
.await
{
Ok(result) => metadata_by_id.extend(
result
.apps
.into_iter()
.map(|metadata| (metadata.id.clone(), metadata)),
),
Err(err) => {
warn!("failed to load app metadata for plugin: {err:#}");
break;
}
}
}
}
app_ids
.into_iter()
.map(|app_id| {
let (name, description) = metadata_by_id
.remove(&app_id)
.map(|metadata| (metadata.name, metadata.description))
.unwrap_or_else(|| (app_id.clone(), None));
let category = app_category_by_id.get(&app_id).cloned();
AppSummary {
install_url: Some(codex_connectors::metadata::connector_install_url(
&name, &app_id,
)),
id: app_id,
name,
description,
category,
}
.map(|app_id| AppSummary {
install_url: None,
name: app_id.clone(),
description: None,
category: app_category_by_id.get(&app_id).cloned(),
id: app_id,
})
.collect()
}
@@ -2425,6 +2308,7 @@ fn remote_plugin_detail_to_info(
fn remote_plugin_catalog_error_type(err: &RemotePluginCatalogError) -> &'static str {
match err {
RemotePluginCatalogError::Unavailable => "remote_catalog_unavailable",
RemotePluginCatalogError::AuthRequired => "remote_catalog_auth_required",
RemotePluginCatalogError::UnsupportedAuthMode => "remote_catalog_unsupported_auth_mode",
RemotePluginCatalogError::AuthToken(_) => "remote_catalog_auth_token",
@@ -2459,6 +2343,7 @@ fn remote_plugin_catalog_error_type(err: &RemotePluginCatalogError) -> &'static
fn remote_plugin_bundle_install_error_type(err: &RemotePluginBundleInstallError) -> &'static str {
match err {
RemotePluginBundleInstallError::Unavailable => "remote_bundle_unavailable",
RemotePluginBundleInstallError::MissingReleaseVersion { .. } => {
"remote_bundle_missing_release_version"
}
@@ -2499,6 +2384,7 @@ fn remote_plugin_catalog_error_to_jsonrpc(
) -> JSONRPCErrorError {
let message = format!("{context}: {err}");
match &err {
RemotePluginCatalogError::Unavailable => method_not_found(message),
RemotePluginCatalogError::AuthRequired | RemotePluginCatalogError::UnsupportedAuthMode => {
invalid_request(message)
}

View File

@@ -26,7 +26,6 @@ pub(super) struct ListenerTaskContext {
pub(super) thread_watch_manager: ThreadWatchManager,
pub(super) codex_home: PathBuf,
pub(super) skills_watcher: Arc<SkillsWatcher>,
pub(super) turn_cost_worker: Option<crate::turn_cost_worker::TurnCostWorkerHandle>,
}
struct UnloadingState {
@@ -500,7 +499,6 @@ async fn start_listener(
pending_thread_unloads,
thread_watch_manager,
codex_home,
turn_cost_worker,
..
} = listener_task_context;
let outgoing_for_task = Arc::clone(&outgoing);
@@ -538,15 +536,6 @@ async fn start_listener(
}
};
if let Some(worker) = &turn_cost_worker {
worker.observe_event(
conversation_id,
config.as_ref(),
&event,
|| conversation.session_telemetry(),
);
}
// Track the event before emitting any typed translations
// so thread-local state such as raw event opt-in stays
// synchronized with the conversation.
@@ -751,7 +740,6 @@ async fn start_listener(
drop(conversation);
drop(config);
drop(thread_manager);
drop(turn_cost_worker);
if shutdown_complete {
drained_tx.send_replace(true);

View File

@@ -90,7 +90,6 @@ async fn listener_shutdown_releases_runtime_and_preserves_other_subscribers(
/*state_db*/ None,
/*log_db*/ None,
skills_watcher.clone(),
/*turn_cost_worker*/ None,
Vec::new(),
Arc::new(SampleResponseRegistry::default()),
);

View File

@@ -518,7 +518,6 @@ pub(crate) struct ThreadRequestProcessor {
pub(super) background_tasks: TaskTracker,
pub(super) sample_responses: Arc<crate::thread_sample::SampleResponseRegistry>,
pub(super) skills_watcher: Arc<SkillsWatcher>,
pub(super) turn_cost_worker: Option<crate::turn_cost_worker::TurnCostWorkerHandle>,
pub(super) initial_config_warnings: Arc<Vec<ConfigWarningNotification>>,
}
@@ -557,7 +556,6 @@ impl ThreadRequestProcessor {
state_db: Option<StateDbHandle>,
log_db: Option<LogDbLayer>,
skills_watcher: Arc<SkillsWatcher>,
turn_cost_worker: Option<crate::turn_cost_worker::TurnCostWorkerHandle>,
initial_config_warnings: Vec<ConfigWarningNotification>,
sample_responses: Arc<crate::thread_sample::SampleResponseRegistry>,
) -> Self {
@@ -579,7 +577,6 @@ impl ThreadRequestProcessor {
background_tasks: TaskTracker::new(),
sample_responses,
skills_watcher,
turn_cost_worker,
initial_config_warnings: Arc::new(initial_config_warnings),
}
}
@@ -1231,7 +1228,6 @@ impl ThreadRequestProcessor {
thread_watch_manager: self.thread_watch_manager.clone(),
codex_home: self.config.codex_home.to_path_buf(),
skills_watcher: Arc::clone(&self.skills_watcher),
turn_cost_worker: self.turn_cost_worker.clone(),
}
}
@@ -1361,7 +1357,6 @@ impl ThreadRequestProcessor {
thread_watch_manager: self.thread_watch_manager.clone(),
codex_home: self.config.codex_home.to_path_buf(),
skills_watcher: Arc::clone(&self.skills_watcher),
turn_cost_worker: self.turn_cost_worker.clone(),
};
let request_trace = request_context.request_trace();
let config_manager = self.config_manager.clone();

View File

@@ -89,7 +89,6 @@ pub(crate) struct TurnRequestProcessor {
thread_state_manager: ThreadStateManager,
thread_watch_manager: ThreadWatchManager,
skills_watcher: Arc<SkillsWatcher>,
turn_cost_worker: Option<crate::turn_cost_worker::TurnCostWorkerHandle>,
}
fn map_additional_context(
@@ -147,7 +146,6 @@ impl TurnRequestProcessor {
thread_state_manager: ThreadStateManager,
thread_watch_manager: ThreadWatchManager,
skills_watcher: Arc<SkillsWatcher>,
turn_cost_worker: Option<crate::turn_cost_worker::TurnCostWorkerHandle>,
) -> Self {
Self {
thread_manager,
@@ -159,7 +157,6 @@ impl TurnRequestProcessor {
thread_state_manager,
thread_watch_manager,
skills_watcher,
turn_cost_worker,
}
}
@@ -1543,7 +1540,6 @@ impl TurnRequestProcessor {
thread_watch_manager: self.thread_watch_manager.clone(),
codex_home: self.config.codex_home.to_path_buf(),
skills_watcher: Arc::clone(&self.skills_watcher),
turn_cost_worker: self.turn_cost_worker.clone(),
}
}