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

@@ -1,175 +0,0 @@
use codex_app_server_protocol::AppBranding as ApiAppBranding;
use codex_app_server_protocol::AppInfo as ApiAppInfo;
use codex_app_server_protocol::AppMetadata as ApiAppMetadata;
use codex_app_server_protocol::AppReview as ApiAppReview;
use codex_app_server_protocol::AppScreenshot as ApiAppScreenshot;
use codex_app_server_protocol::AppToolSummary as ApiAppToolSummary;
use codex_app_server_protocol::ConnectorMetadata as ApiConnectorMetadata;
use codex_connectors::AppBranding;
use codex_connectors::AppInfo;
use codex_connectors::AppMetadata;
use codex_connectors::AppReview;
use codex_connectors::AppScreenshot;
use codex_connectors::ConnectorMetadata;
use codex_connectors::ConnectorToolSummary;
use codex_connectors::metadata::connector_install_url;
/// Converts connector-domain app metadata owned by `codex-connectors` into the app-server wire
/// type owned by `codex-app-server-protocol`.
///
/// The types stay separate so app-server protocol ownership does not leak into the connector
/// domain crate. Because this crate owns neither type, Rust's orphan rules require an explicit
/// conversion function instead of a `From` implementation.
pub(crate) fn app_info_to_api(app: AppInfo) -> ApiAppInfo {
let AppInfo {
id,
name,
description,
logo_url,
logo_url_dark,
icon_assets,
icon_dark_assets,
distribution_channel,
branding,
app_metadata,
labels,
install_url,
is_accessible,
is_enabled,
plugin_display_names,
} = app;
ApiAppInfo {
id,
name,
description,
logo_url,
logo_url_dark,
icon_assets,
icon_dark_assets,
distribution_channel,
branding: branding.map(app_branding_to_api),
app_metadata: app_metadata.map(app_metadata_to_api),
labels,
install_url,
is_accessible,
is_enabled,
plugin_display_names,
}
}
/// Converts metadata-only connector data into the app-server wire type.
///
/// Keeping this separate from app_info_to_api makes it impossible for app/read to accidentally
/// expose full runtime tool state from the broader app/list path.
pub(crate) fn connector_metadata_to_api(metadata: ConnectorMetadata) -> ApiConnectorMetadata {
let ConnectorMetadata {
id,
name,
description,
icon_url,
icon_url_dark,
distribution_channel,
tool_summaries,
} = metadata;
let install_url = Some(connector_install_url(&name, &id));
ApiConnectorMetadata {
id,
name,
description,
icon_url,
icon_url_dark,
distribution_channel,
install_url,
plugin_display_names: Vec::new(),
tool_summaries: tool_summaries.map(|tools| {
tools
.into_iter()
.map(|tool| {
let ConnectorToolSummary {
name,
title,
description,
is_enabled,
disabled_reason,
is_read_only,
} = tool;
ApiAppToolSummary {
name,
title,
description,
is_enabled,
disabled_reason,
is_read_only,
}
})
.collect()
}),
}
}
fn app_branding_to_api(branding: AppBranding) -> ApiAppBranding {
let AppBranding {
category,
developer,
website,
privacy_policy,
terms_of_service,
is_discoverable_app,
} = branding;
ApiAppBranding {
category,
developer,
website,
privacy_policy,
terms_of_service,
is_discoverable_app,
}
}
fn app_review_to_api(review: AppReview) -> ApiAppReview {
let AppReview { status } = review;
ApiAppReview { status }
}
fn app_screenshot_to_api(screenshot: AppScreenshot) -> ApiAppScreenshot {
let AppScreenshot {
url,
file_id,
user_prompt,
} = screenshot;
ApiAppScreenshot {
url,
file_id,
user_prompt,
}
}
fn app_metadata_to_api(metadata: AppMetadata) -> ApiAppMetadata {
let AppMetadata {
review,
categories,
sub_categories,
seo_description,
screenshots,
developer,
version,
version_id,
version_notes,
first_party_requires_install,
show_in_composer_when_unlinked,
} = metadata;
ApiAppMetadata {
review: review.map(app_review_to_api),
categories,
sub_categories,
seo_description,
screenshots: screenshots
.map(|screenshots| screenshots.into_iter().map(app_screenshot_to_api).collect()),
developer,
version,
version_id,
version_notes,
first_party_requires_install,
show_in_composer_when_unlinked,
}
}

View File

@@ -28,7 +28,7 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() -
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(200))
.expect(2)
.expect(1)
.mount(&server)
.await;
let home = tempdir()?;
@@ -44,28 +44,15 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() -
.build()
.await?;
config.chatgpt_base_url = server.uri();
let cloud_endpoint = format!("{}/api/codex/config/bundle", server.uri());
let policy = EmbeddedNetworkPolicy::load(&overrides).await;
let bootstrap_auth = policy.bind_bootstrap_auth(config.auth_config());
let bootstrap = bootstrap_auth
.auth_route_config
.http_client_factory()
.build_client(&cloud_endpoint, ClientRouteClass::Auth)?;
let application = policy
.bind(config.http_client_factory())
.build_client(&server.uri(), ClientRouteClass::Other)?;
assert!(bootstrap.get(&cloud_endpoint).send().await.is_err());
assert!(application.get(server.uri()).send().await.is_err());
policy.activate(&mut config);
let caller_factory = config.http_client_factory();
let caller_client = caller_factory.build_client(&server.uri(), ClientRouteClass::Other)?;
let worktree_bootstrap = policy.clone().bind_bootstrap_auth(config.auth_config());
let worktree_client = worktree_bootstrap
.auth_route_config
.http_client_factory()
.build_client(&cloud_endpoint, ClientRouteClass::Auth)?;
assert!(caller_client.get(server.uri()).send().await.is_err());
assert!(worktree_client.get(&cloud_endpoint).send().await.is_err());
assert!(
caller_factory
.network_policy()
@@ -86,29 +73,17 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() -
std::fs::remove_file(&requirements)?;
let unrestricted = manager.refresh_application_network_policy().await?;
let unrelated_endpoint = format!("{}/not-the-config-endpoint", server.uri()).parse()?;
assert_eq!(
bootstrap_auth
.auth_route_config
.http_client_factory()
.network_policy()
.acquire(&unrelated_endpoint)
.map(|_| ()),
Err(NetworkPolicyDenied::Destination),
);
caller_client.get(server.uri()).send().await?;
worktree_client.get(&cloud_endpoint).send().await?;
assert!(
caller_factory
.network_policy()
.acquire_for_unsupported_sdk()
.is_ok()
);
assert_eq!(server.received_requests().await.unwrap().len(), 2);
assert_eq!(server.received_requests().await.unwrap().len(), 1);
std::fs::write(&requirements, "[malformed")?;
assert!(manager.refresh_application_network_policy().await.is_err());
assert!(caller_client.get(server.uri()).send().await.is_err());
assert!(worktree_client.get(&cloud_endpoint).send().await.is_err());
assert!(
caller_factory
.network_policy()

View File

@@ -1,243 +0,0 @@
use codex_core::config::Config;
use codex_features::Feature;
use codex_features::RuntimeAuthMode;
use codex_http_client::HttpClient;
use codex_http_client::HttpClientFactory;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::default_client::RESIDENCY_HEADER_NAME;
use codex_login::default_client::create_client_with_chatgpt_cookies;
use codex_login::default_client::default_headers;
use codex_runtime_agent_instance::RuntimeAuthManager;
use std::sync::Arc;
use anyhow::Context;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::sync::LazyLock;
use std::sync::Mutex;
use std::time::Duration;
const OAI_PRODUCT_SKU_HEADER: &str = "OAI-Product-Sku";
const CODEX_PRODUCT_SKU: &str = "codex";
struct CachedChatGptClient {
factory: HttpClientFactory,
residency: Option<Vec<u8>>,
client: HttpClient,
}
static CHATGPT_CLIENT: LazyLock<Mutex<Option<CachedChatGptClient>>> =
LazyLock::new(|| Mutex::new(None));
/// Reuse the client and cookies without changing the caller's captured account policy.
fn chatgpt_client(factory: HttpClientFactory) -> HttpClient {
let residency = default_headers()
.get(RESIDENCY_HEADER_NAME)
.map(|value| value.as_bytes().to_vec());
let mut cached = CHATGPT_CLIENT
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(cached_client) = cached.as_ref()
&& cached_client.factory == factory
&& cached_client.residency == residency
{
return cached_client.client.clone();
}
let client = create_client_with_chatgpt_cookies(&factory);
*cached = Some(CachedChatGptClient {
factory,
residency,
client: client.clone(),
});
client
}
/// Make a GET request to the ChatGPT backend API.
#[cfg(test)]
pub(crate) async fn chatgpt_get_request<T: DeserializeOwned>(
config: &Config,
path: String,
) -> anyhow::Result<T> {
let mut config = config.clone();
let (auth, runtime) = standalone_auth(&mut config).await?;
chatgpt_get_request_with_timeout(
&config,
&auth,
runtime.as_ref(),
path,
/*timeout*/ None,
)
.await
}
pub(crate) async fn standalone_auth(
config: &mut Config,
) -> anyhow::Result<(
CodexAuth,
Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
)> {
// Standalone commands create one owner. Freeze the caller's account policy before loading
// credentials; this temporary manager does not own later account changes.
config.application_network_policy = config
.application_network_policy
.clone()
.for_current_account();
if config.features.enabled(Feature::RuntimeAgentInstances) {
codex_model_provider::validate_runtime_destination(Some(&config.chatgpt_base_url))?;
}
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?;
let runtime = if config.features.enabled(Feature::RuntimeAgentInstances)
&& codex_runtime_agent_instance::is_openai_api_url(&config.chatgpt_base_url)
{
let installation_id = codex_core::resolve_installation_id(&config.codex_home).await?;
codex_core::build_runtime_auth_manager(config, auth_manager.clone(), &installation_id)
.map(|runtime| (runtime, config.runtime_auth_mode))
} else {
None
};
let auth = auth_manager
.auth()
.await
.ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?;
Ok((auth, runtime))
}
pub(crate) async fn chatgpt_get_request_with_timeout<T: DeserializeOwned>(
config: &Config,
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
path: String,
timeout: Option<Duration>,
) -> anyhow::Result<T> {
let chatgpt_base_url = &config.chatgpt_base_url;
anyhow::ensure!(
auth.uses_codex_backend(),
"ChatGPT backend requests require Codex backend auth"
);
anyhow::ensure!(
auth.get_account_id().is_some(),
"ChatGPT account ID not available, please re-run `codex login`"
);
let url = format!(
"{}/{}",
chatgpt_base_url.trim_end_matches('/'),
path.trim_start_matches('/')
);
let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?;
let mut request = client
.get(&url)
.headers(default_headers())
.headers(
request_auth
.auth
.apply_auth_headers(Default::default())
.await?,
)
.header(OAI_PRODUCT_SKU_HEADER, CODEX_PRODUCT_SKU)
.header("Content-Type", "application/json");
if let Some(timeout) = timeout {
request = request.timeout(timeout);
}
let response = request.send().await.context("Failed to send request")?;
if response.status().is_success() {
let result: T = response
.json()
.await
.context("Failed to parse JSON response")?;
Ok(result)
} else {
let status = response.status();
let body = response.text().await.unwrap_or_default();
anyhow::bail!("Request failed with status {status}: {body}")
}
}
/// Make a POST request to the ChatGPT backend API with an already-captured auth identity.
///
/// Callers must capture `auth` and `config.application_network_policy` together and preserve
/// that snapshot rather than reacquiring either while the request is in flight.
pub(crate) async fn chatgpt_post_request_with_timeout<
TResponse: DeserializeOwned,
TRequest: Serialize + ?Sized,
>(
config: &Config,
auth: &CodexAuth,
path: String,
body: &TRequest,
timeout: Duration,
product_sku: &str,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
) -> anyhow::Result<TResponse> {
anyhow::ensure!(
auth.uses_codex_backend(),
"ChatGPT backend requests require Codex backend auth"
);
anyhow::ensure!(
auth.get_account_id().is_some(),
"ChatGPT account ID not available, please re-run codex login"
);
let url = format!(
"{}/{}",
config.chatgpt_base_url.trim_end_matches('/'),
path.trim_start_matches('/')
);
let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?;
let response = client
.post(&url)
.headers(default_headers())
.headers(
request_auth
.auth
.apply_auth_headers(Default::default())
.await?,
)
.header(OAI_PRODUCT_SKU_HEADER, product_sku)
.header("Content-Type", "application/json")
.timeout(timeout)
.json(body)
.send()
.await
.context("Failed to send request")?;
if response.status().is_success() {
response
.json()
.await
.context("Failed to parse JSON response")
} else {
let status = response.status();
let body = response.text().await.unwrap_or_default();
anyhow::bail!("Request failed with status {status}: {body}")
}
}
/// Keep request credentials and the transport bound to the same account snapshot.
async fn prepare_client_auth(
config: &Config,
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
url: &str,
) -> anyhow::Result<(HttpClient, codex_model_provider::ResolvedProviderAuth)> {
if runtime.is_some() {
codex_model_provider::validate_runtime_destination(Some(url))?;
}
let resolved = codex_model_provider::auth_provider_for_request(
auth,
runtime,
/*headers*/ &Default::default(),
)
.await?;
let factory = resolved.bind_http_client_factory(config.http_client_factory())?;
let client = chatgpt_client(factory);
Ok((client, resolved))
}
#[cfg(test)]
#[path = "chatgpt_client_runtime_auth_tests.rs"]
mod runtime_auth_tests;

View File

@@ -1,321 +0,0 @@
//! Test captured ChatGPT credentials and runtime proofs on helper requests.
use super::*;
use base64::Engine;
use codex_features::RuntimeAuthMode;
use codex_runtime_agent_instance::AgentHostAuthorization;
use codex_runtime_agent_instance::RuntimeAuthManager;
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
use codex_runtime_agent_instance::RuntimeRole;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::HashSet;
use std::sync::Arc;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::path;
#[tokio::test]
async fn helpers_use_captured_auth_and_strip_cross_origin_proofs() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let redirected = MockServer::start().await;
Mock::given(path("/"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
.expect(1)
.mount(&redirected)
.await;
Mock::given(path("/agent/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-chatgpt", "agent_host_id": "host-a",
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "workspace-a"},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(path("/data"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
.expect(2)
.mount(&server)
.await;
Mock::given(path("/redirect"))
.respond_with(ResponseTemplate::new(307).insert_header("location", redirected.uri()))
.expect(1)
.mount(&server)
.await;
Mock::given(path("/ps/apps/batch"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"apps": [{"id": "calendar", "name": "Calendar", "description": "Calendar metadata"}],
})))
.expect(1).mount(&server).await;
let home = tempfile::TempDir::new().unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = server.uri();
let token = actor_token();
let auth = CodexAuth::from_external_chatgpt_tokens(
&token,
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let runtime = (
Arc::new(RuntimeAuthManager::new(
AuthManager::from_auth_for_testing(auth.clone()),
AgentHostAuthorization::InstallationId {
installation_id: uuid::Uuid::nil(),
},
RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/agent/register", server.uri()).parse().unwrap(),
)),
mode,
);
// No saved auth exists: these helpers must use the supplied snapshot, not reload auth.
let get: serde_json::Value = chatgpt_get_request_with_timeout(
&config,
&auth,
Some(&runtime),
"data".into(),
/*timeout*/ None,
)
.await
.unwrap();
let post: serde_json::Value = chatgpt_post_request_with_timeout(
&config,
&auth,
"data".into(),
&json!({}),
Duration::from_secs(10),
"codex",
Some(&runtime),
)
.await
.unwrap();
let metadata = crate::chatgpt_connectors::read_connector_metadata(
&config,
&auth,
Some(&runtime),
&["calendar".into()],
/*include_tools*/ false,
)
.await
.unwrap();
assert_eq!(metadata.apps.len(), 1);
assert_eq!(metadata.apps[0].name, "Calendar");
assert!(metadata.missing_app_ids.is_empty());
assert_eq!(get, json!({"ok": true}));
assert_eq!(post, get);
let redirected_result = chatgpt_get_request_with_timeout::<serde_json::Value>(
&config,
&auth,
Some(&runtime),
"redirect".into(),
/*timeout*/ None,
)
.await
.unwrap();
assert_eq!(redirected_result, get);
let forwarded = redirected.received_requests().await.unwrap();
assert_eq!(forwarded.len(), 1);
assert!(!forwarded[0].headers.contains_key("authorization"));
assert!(
!forwarded[0]
.headers
.contains_key("x-openai-agent-assertion")
);
redirected.verify().await;
let requests = server.received_requests().await.unwrap();
let metadata_request = requests
.iter()
.find(|request| request.url.path() == "/ps/apps/batch")
.unwrap();
assert_eq!(
metadata_request.headers["authorization"],
format!("Bearer {token}")
);
assert!(
!metadata_request
.headers
.contains_key("x-openai-agent-assertion")
);
let proofs: HashSet<_> = requests
.iter()
.filter(|r| !matches!(r.url.path(), "/agent/register" | "/ps/apps/batch"))
.map(|r| {
assert_eq!(r.headers["chatgpt-account-id"], "workspace-a");
let authorization = r.headers["authorization"].to_str().unwrap();
match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(authorization, format!("Bearer {token}"));
r.headers["x-openai-agent-assertion"].to_str().unwrap()
}
RuntimeAuthMode::AssertionOnly => {
assert!(!r.headers.contains_key("x-openai-agent-assertion"));
authorization.strip_prefix("AgentAssertion ").unwrap()
}
}
})
.collect();
assert_eq!(proofs.len(), 3);
server.verify().await;
}
}
fn actor_token() -> String {
let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json!({
"iss": "https://auth.openai.com/", "session_id": "login-a",
"https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "workspace-a"},
}).to_string());
format!("header.{claims}.signature")
}
#[tokio::test]
async fn standalone_apply_keeps_custom_backend_auth_when_runtime_feature_is_enabled() {
let server = MockServer::start().await;
let token = actor_token();
Mock::given(path("/task"))
.and(wiremock::matchers::header(
"authorization",
format!("Bearer {token}"),
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
.expect(1)
.mount(&server)
.await;
let home = tempfile::TempDir::new().unwrap();
codex_login::auth::login_with_chatgpt_auth_tokens(
home.path(),
&token,
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = server.uri();
config
.features
.enable(Feature::RuntimeAgentInstances)
.unwrap();
let response: serde_json::Value = chatgpt_get_request(&config, "task".into()).await.unwrap();
assert_eq!(response, json!({"ok": true}));
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 1);
assert!(!requests[0].headers.contains_key("x-openai-agent-assertion"));
server.verify().await;
}
#[tokio::test]
async fn connector_requests_reject_unsupported_openai_destinations() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
for base_url in [
"http://chatgpt.com",
"https://future.openai.com/backend-api",
] {
let home = tempfile::TempDir::new().unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = base_url.to_string();
config.features.enable(Feature::Apps).unwrap();
let auth = CodexAuth::from_external_chatgpt_tokens(
&actor_token(),
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let runtime = (
Arc::new(RuntimeAuthManager::for_chatgpt(
AuthManager::from_auth_for_testing(auth.clone()),
uuid::Uuid::nil().to_string(),
base_url.to_string(),
RuntimeRegistrationMetadata {
harness: Some("codex".to_string()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
)),
mode,
);
// Keep a broken validation path from sending the test credential to the network.
let controller = codex_http_client::NetworkPolicyController::default();
config.application_network_policy = controller.policy();
assert!(controller.publish(
config.application_network_policy.revision(),
codex_http_client::DestinationPolicy::Restricted {
allowed_hosts: Default::default(),
},
));
let directory_error = crate::chatgpt_connectors::list_all_connectors_with_options(
&config,
Some(&auth),
Some(&runtime),
/*force_refetch*/ true,
&[],
)
.await
.expect_err("reject unsupported directory destination");
let metadata_error = crate::chatgpt_connectors::read_connector_metadata(
&config,
&auth,
Some(&runtime),
&["calendar".to_string()],
/*include_tools*/ false,
)
.await
.err()
.expect("reject unsupported metadata destination");
for error in [directory_error, metadata_error] {
assert!(
matches!(
error
.downcast_ref::<codex_protocol::error::CodexErr>()
.map(codex_protocol::error::CodexErr::details),
Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_))
),
"{base_url} ({mode:?}): {error:#}",
);
}
}
}
}
#[tokio::test]
async fn standalone_apply_rejects_unsupported_openai_destination() {
let home = tempfile::TempDir::new().unwrap();
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
config.chatgpt_base_url = "https://future.openai.com/backend-api".into();
config
.features
.enable(Feature::RuntimeAgentInstances)
.unwrap();
let error = chatgpt_get_request::<serde_json::Value>(&config, "task".into())
.await
.unwrap_err();
assert!(matches!(
error
.downcast_ref::<codex_protocol::error::CodexErr>()
.map(codex_protocol::error::CodexErr::details),
Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_))
));
}

View File

@@ -1,525 +0,0 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::time::Duration;
mod chatgpt_client;
use self::chatgpt_client::chatgpt_get_request_with_timeout;
use self::chatgpt_client::chatgpt_post_request_with_timeout;
use codex_connectors::AppInfo;
use codex_connectors::AppToolPolicyEvaluator;
use codex_connectors::ConnectorDirectoryCacheContext;
use codex_connectors::ConnectorDirectoryCacheKey;
use codex_connectors::ConnectorMetadata;
use codex_connectors::ConnectorMetadataStore;
use codex_connectors::ConnectorToolSummary;
use codex_connectors::DirectoryListResponse;
use codex_connectors::merge::merge_connectors;
use codex_connectors::merge::merge_plugin_connectors;
use codex_core::config::Config;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status;
pub use codex_core::connectors::list_cached_accessible_connectors_from_mcp_tools;
use codex_features::RuntimeAuthMode;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_plugin::AppConnectorId;
use codex_runtime_agent_instance::RuntimeAuthManager;
use serde::Deserialize;
use serde::Serialize;
use std::sync::Arc;
const DIRECTORY_CONNECTORS_TIMEOUT: Duration = Duration::from_secs(60);
const CONNECTOR_METADATA_TIMEOUT: Duration = Duration::from_secs(60);
const DEFAULT_APPS_PRODUCT_SKU: &str = "codex";
async fn apps_enabled(config: &Config) -> anyhow::Result<bool> {
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?;
let auth = auth_manager.auth().await;
Ok(config
.features
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)))
}
pub async fn list_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>> {
if !apps_enabled(config).await? {
return Ok(Vec::new());
}
let (connectors_result, accessible_result) = tokio::join!(
list_all_connectors(config),
list_accessible_connectors_from_mcp_tools(config),
);
let connectors = connectors_result?;
let accessible = accessible_result?;
Ok(
AppToolPolicyEvaluator::new(&config.config_layer_stack).apply_app_enabled_state(
merge_connectors_with_accessible(
connectors, accessible, /*all_connectors_loaded*/ true,
),
),
)
}
pub async fn list_all_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>> {
if !apps_enabled(config).await? {
return Ok(Vec::new());
}
let mut config = config.clone();
let (auth, runtime) = self::chatgpt_client::standalone_auth(&mut config).await?;
list_all_connectors_with_options(
&config,
Some(&auth),
runtime.as_ref(),
/*force_refetch*/ false,
&[],
)
.await
}
pub fn list_cached_all_connectors(
config: &Config,
auth: Option<&CodexAuth>,
plugin_apps: &[AppConnectorId],
) -> Option<Vec<AppInfo>> {
if !config
.features
.apps_enabled_for_auth(auth.is_some_and(CodexAuth::uses_codex_backend))
{
return Some(Vec::new());
}
let auth = auth?;
let cache_context = connector_directory_cache_context(config, auth);
let connectors = codex_connectors::cached_directory_connectors(&cache_context)?;
Some(merge_directory_and_plugin_connectors(
connectors.to_vec(),
plugin_apps,
))
}
pub async fn list_all_connectors_with_options(
config: &Config,
auth: Option<&CodexAuth>,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
force_refetch: bool,
plugin_apps: &[AppConnectorId],
) -> anyhow::Result<Vec<AppInfo>> {
if !config
.features
.apps_enabled_for_auth(auth.is_some_and(CodexAuth::uses_codex_backend))
{
return Ok(Vec::new());
}
let auth = auth.ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?;
let runtime = codex_model_provider::runtime_auth_for_url(runtime, &config.chatgpt_base_url)?;
let cache_context = connector_directory_cache_context(config, auth);
let connectors = codex_connectors::list_all_connectors_with_options(
cache_context,
auth.is_workspace_account(),
force_refetch,
|path| async move {
chatgpt_get_request_with_timeout::<DirectoryListResponse>(
config,
auth,
runtime,
path,
Some(DIRECTORY_CONNECTORS_TIMEOUT),
)
.await
},
)
.await?;
Ok(merge_directory_and_plugin_connectors(
connectors,
plugin_apps,
))
}
pub struct ConnectorMetadataReadResult {
pub apps: Vec<ConnectorMetadata>,
pub missing_app_ids: Vec<String>,
}
/// Reads display metadata without loading MCP connector tools or runtime state.
///
/// The store is created before awaiting the backend request, so a response that arrives after an
/// account or backend change can only commit to the scope under which it was requested.
/// Capture `auth` and `config.application_network_policy` together using
/// `AuthManager::auth_with_http_client_factory` so the request retains that account's policy.
pub async fn read_connector_metadata(
config: &Config,
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
app_ids: &[String],
include_tools: bool,
) -> anyhow::Result<ConnectorMetadataReadResult> {
anyhow::ensure!(
auth.uses_codex_backend(),
"ChatGPT backend requests require Codex backend auth"
);
anyhow::ensure!(
auth.get_account_id().is_some(),
"ChatGPT account ID not available, please re-run codex login"
);
let runtime = codex_model_provider::runtime_auth_for_url(runtime, &config.chatgpt_base_url)?;
let store = ConnectorMetadataStore::new(
config.chatgpt_base_url.clone(),
auth.get_account_id(),
auth.get_chatgpt_user_id(),
auth.is_workspace_account(),
);
let mut metadata_by_id = store.fresh_records(app_ids, include_tools);
let missing_ids = app_ids
.iter()
.filter(|app_id| !metadata_by_id.contains_key(app_id.as_str()))
.cloned()
.collect::<Vec<_>>();
if !missing_ids.is_empty() {
let product_sku = config
.apps_mcp_product_sku
.as_deref()
.unwrap_or(DEFAULT_APPS_PRODUCT_SKU);
let response: GetAppsResponse = chatgpt_post_request_with_timeout(
config,
auth,
"/ps/apps/batch".to_string(),
&GetAppsRequest {
app_ids: &missing_ids,
include_tools,
},
CONNECTOR_METADATA_TIMEOUT,
product_sku,
runtime,
)
.await?;
let mut requested_ids = missing_ids.iter().cloned().collect::<HashSet<_>>();
let fetched = response
.apps
.into_iter()
.map(batch_app_to_metadata)
.filter(|metadata| requested_ids.remove(&metadata.id))
.collect::<Vec<_>>();
store.commit(&fetched);
metadata_by_id.extend(
fetched
.into_iter()
.map(|metadata| (metadata.id.clone(), metadata)),
);
}
let mut apps = Vec::new();
let mut missing_app_ids = Vec::new();
for app_id in app_ids {
if let Some(mut metadata) = metadata_by_id.remove(app_id) {
if !include_tools {
metadata.tool_summaries = None;
}
apps.push(metadata);
} else {
missing_app_ids.push(app_id.clone());
}
}
Ok(ConnectorMetadataReadResult {
apps,
missing_app_ids,
})
}
#[derive(Serialize)]
struct GetAppsRequest<'a> {
app_ids: &'a [String],
include_tools: bool,
}
#[derive(Deserialize)]
struct GetAppsResponse {
apps: Vec<BatchApp>,
}
/// The explicit metadata-only projection of Plugin Service's public app response.
///
/// Serde ignores all other backend fields, including full actions, model descriptions, and
/// runtime state.
#[derive(Deserialize)]
struct BatchApp {
id: String,
name: String,
description: Option<String>,
icon_url: Option<String>,
#[serde(default, rename = "icon_dark_url", alias = "icon_url_dark")]
icon_url_dark: Option<String>,
#[serde(default)]
distribution_channel: Option<String>,
#[serde(default)]
tools: Option<Vec<BatchAppToolSummary>>,
}
#[derive(Deserialize)]
struct BatchAppToolSummary {
name: String,
title: Option<String>,
description: String,
#[serde(default)]
is_enabled: Option<bool>,
#[serde(default)]
disabled_reason: Option<String>,
#[serde(default)]
is_read_only: bool,
}
fn batch_app_to_metadata(app: BatchApp) -> ConnectorMetadata {
let BatchApp {
id,
name,
description,
icon_url,
icon_url_dark,
distribution_channel,
tools,
} = app;
ConnectorMetadata {
id,
name,
description,
icon_url,
icon_url_dark,
distribution_channel,
tool_summaries: tools.map(|tools| {
tools
.into_iter()
.map(|tool| {
let BatchAppToolSummary {
name,
title,
description,
is_enabled,
disabled_reason,
is_read_only,
} = tool;
ConnectorToolSummary {
name,
title,
description,
is_enabled: is_enabled.unwrap_or(true),
disabled_reason,
is_read_only,
}
})
.collect()
}),
}
}
fn connector_directory_cache_context(
config: &Config,
auth: &CodexAuth,
) -> ConnectorDirectoryCacheContext {
ConnectorDirectoryCacheContext::new(
config.codex_home.to_path_buf(),
ConnectorDirectoryCacheKey::new(
config.chatgpt_base_url.clone(),
auth.get_account_id(),
auth.get_chatgpt_user_id(),
auth.is_workspace_account(),
),
)
}
fn merge_directory_and_plugin_connectors(
connectors: Vec<AppInfo>,
plugin_apps: &[AppConnectorId],
) -> Vec<AppInfo> {
merge_plugin_connectors(
connectors,
plugin_apps
.iter()
.map(|connector_id| connector_id.0.clone()),
)
}
pub fn connectors_for_plugin_apps(
connectors: Vec<AppInfo>,
plugin_apps: &[AppConnectorId],
) -> Vec<AppInfo> {
let connectors = merge_plugin_connectors(
connectors,
plugin_apps
.iter()
.map(|connector_id| connector_id.0.clone()),
);
let mut connectors_by_id = connectors
.into_iter()
.map(|connector| (connector.id.clone(), connector))
.collect::<HashMap<_, _>>();
plugin_apps
.iter()
.filter_map(|connector_id| connectors_by_id.remove(connector_id.0.as_str()))
.collect()
}
pub fn merge_connectors_with_accessible(
connectors: Vec<AppInfo>,
accessible_connectors: Vec<AppInfo>,
all_connectors_loaded: bool,
) -> Vec<AppInfo> {
let accessible_connectors = if all_connectors_loaded {
let connector_ids: HashSet<&str> = connectors
.iter()
.map(|connector| connector.id.as_str())
.collect();
accessible_connectors
.into_iter()
.filter(|connector| connector_ids.contains(connector.id.as_str()))
.collect()
} else {
accessible_connectors
};
merge_connectors(connectors, accessible_connectors)
}
#[cfg(test)]
mod tests {
use super::*;
use codex_connectors::metadata::connector_install_url;
use codex_plugin::AppConnectorId;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn batch_app_accepts_missing_optional_metadata() {
let app = serde_json::from_value::<BatchApp>(json!({
"id": "alpha",
"name": "Alpha",
"description": "Alpha description",
"icon_url": null,
"tools": [{
"name": "search",
"title": "Search",
"description": "Search Alpha",
}],
}))
.expect("valid legacy batch app");
assert_eq!(
batch_app_to_metadata(app),
ConnectorMetadata {
id: "alpha".to_string(),
name: "Alpha".to_string(),
description: Some("Alpha description".to_string()),
icon_url: None,
icon_url_dark: None,
distribution_channel: None,
tool_summaries: Some(vec![ConnectorToolSummary {
name: "search".to_string(),
title: Some("Search".to_string()),
description: "Search Alpha".to_string(),
is_enabled: true,
disabled_reason: None,
is_read_only: false,
}]),
}
);
}
fn app(id: &str) -> AppInfo {
AppInfo {
id: id.to_string(),
name: id.to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: None,
is_accessible: false,
is_enabled: true,
plugin_display_names: Vec::new(),
}
}
fn merged_app(id: &str, is_accessible: bool) -> AppInfo {
AppInfo {
id: id.to_string(),
name: id.to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: Some(connector_install_url(id, id)),
is_accessible,
is_enabled: true,
plugin_display_names: Vec::new(),
}
}
#[test]
fn excludes_accessible_connectors_not_in_all_when_all_loaded() {
let merged = merge_connectors_with_accessible(
vec![app("alpha")],
vec![app("alpha"), app("beta")],
/*all_connectors_loaded*/ true,
);
assert_eq!(merged, vec![merged_app("alpha", /*is_accessible*/ true)]);
}
#[test]
fn keeps_accessible_connectors_not_in_all_while_all_loading() {
let merged = merge_connectors_with_accessible(
vec![app("alpha")],
vec![app("alpha"), app("beta")],
/*all_connectors_loaded*/ false,
);
assert_eq!(
merged,
vec![
merged_app("alpha", /*is_accessible*/ true),
merged_app("beta", /*is_accessible*/ true)
]
);
}
#[test]
fn connectors_for_plugin_apps_returns_only_requested_plugin_apps() {
let connectors = connectors_for_plugin_apps(
vec![app("alpha"), app("beta")],
&[
AppConnectorId("gmail".to_string()),
AppConnectorId("alpha".to_string()),
AppConnectorId("gmail".to_string()),
],
);
assert_eq!(
connectors,
vec![merged_app("gmail", /*is_accessible*/ false), app("alpha")]
);
}
#[test]
fn connectors_for_plugin_apps_preserves_formerly_disallowed_plugin_apps() {
let connector_id = "asdk_app_6938a94a61d881918ef32cb999ff937c";
let connectors =
connectors_for_plugin_apps(Vec::new(), &[AppConnectorId(connector_id.to_string())]);
assert_eq!(
connectors,
vec![merged_app(connector_id, /*is_accessible*/ false)]
);
}
}

View File

@@ -1,6 +1,5 @@
use codex_app_server_protocol::ModelProviderError;
use codex_arg0::Arg0DispatchPaths;
use codex_cloud_config::managed_config_bundle_loader;
use codex_config::CloudConfigBundleLoader;
use codex_config::ConfigLayerStack;
use codex_config::LoaderOverrides;
@@ -191,37 +190,14 @@ impl ConfigManager {
Ok(())
}
/// aKode never fetches managed config bundles from a remote service, so an
/// auth change only resets any previously installed loader.
pub(crate) fn update_managed_config_loader(
&self,
auth_manager: Arc<AuthManager>,
config: &Config,
_auth_manager: Arc<AuthManager>,
_config: &Config,
) {
// Keep config-server settings and their refresh worker when only
// ChatGPT/API-key credentials change.
if self
.current_managed_config_loader()
.config_server()
.is_some()
{
self.revoke_mcp_ema();
return;
}
let loader = managed_config_bundle_loader(
auth_manager,
config.chatgpt_base_url.clone(),
self.codex_home.clone(),
config
.http_client_factory()
.with_network_policy(self.local_network_policy.policy()),
config.config_layer_stack.requirements_toml(),
);
if let Ok(mut guard) = self.cloud_config_bundle.write() {
guard.retire_ema_policy();
*guard = loader;
} else {
warn!("failed to update cloud config bundle loader");
}
self.revoke_mcp_ema();
self.clear_chatgpt_config_loader();
}
pub(crate) fn clear_chatgpt_config_loader(&self) {

View File

@@ -18,7 +18,6 @@ use codex_extension_api::ExtensionWarning;
use codex_extension_api::TurnStartAdmission;
use codex_goal_extension::GoalExtensionConfig;
use codex_goal_extension::GoalService;
use codex_http_client::HttpClientFactory;
use codex_login::AuthManager;
use codex_protocol::ThreadId;
use codex_protocol::protocol::Event;
@@ -42,8 +41,6 @@ pub(crate) struct ThreadExtensionDependencies {
pub(crate) environment_manager: Arc<EnvironmentManager>,
pub(crate) executor_skill_provider: Arc<dyn codex_skills_extension::SkillProvider>,
pub(crate) cloud_skill_provider: Option<Arc<dyn codex_skills_extension::SkillProvider>>,
pub(crate) git_attribution_base_url: String,
pub(crate) http_client_factory: HttpClientFactory,
/// Process-scoped queue shared by idle dispatch and app-server requests.
pub(crate) queue_service: Option<Arc<QueuedItemService>>,
pub(crate) turn_start_admission: Option<Arc<dyn TurnStartAdmission>>,
@@ -64,8 +61,6 @@ pub(crate) fn thread_extensions(
environment_manager,
executor_skill_provider,
cloud_skill_provider,
git_attribution_base_url,
http_client_factory,
queue_service,
turn_start_admission,
} = dependencies;
@@ -98,15 +93,9 @@ pub(crate) fn thread_extensions(
},
);
}
codex_git_attribution::install(
&mut builder,
auth_manager.clone(),
git_attribution_base_url,
http_client_factory,
);
codex_git_attribution::install(&mut builder);
codex_guardian_v2::install(&mut builder, thread_manager);
codex_memories_extension::install(&mut builder, codex_otel::global());
codex_mcp_extension::install(&mut builder);
codex_mcp_extension::install_plugins(&mut builder, environment_manager);
codex_web_search_extension::install(&mut builder, auth_manager.clone());
codex_image_generation_extension::install(&mut builder, auth_manager, |config: &Config| {

View File

@@ -67,35 +67,6 @@ impl EmbeddedNetworkPolicy {
pub fn bind_config(&self, config: &mut Config) {
config.application_network_policy = self.effective.policy();
}
/// Limits cloud discovery and each authentication request to their exact local-policy endpoints.
pub fn bind_bootstrap_auth(
&self,
mut auth: codex_login::AuthConfig,
) -> codex_login::AuthConfig {
let factory = auth
.auth_route_config
.http_client_factory()
.clone()
.with_network_policy(self.local.policy());
let endpoint = codex_backend_client::Client::new(
auth.chatgpt_base_url
.as_deref()
.unwrap_or("https://chatgpt.com/backend-api/"),
factory.clone(),
)
.config_bundle_url();
auth.auth_route_config = codex_login::AuthRouteConfig::from_http_client_factory(
factory.clone().with_network_policy(
self.local
.policy()
.restrict_to_endpoints(endpoint.parse().into_iter().collect()),
),
)
.with_local_bootstrap_factory(factory)
.with_application_network_policy(self.effective.policy());
auth
}
}
pub(super) async fn configure(

View File

@@ -1,10 +1,7 @@
//! Embedded startup preserves caller configuration and bootstrap access across authentication.
use super::EmbeddedNetworkPolicy;
use super::configure;
use crate::config_manager::ConfigManager;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_arg0::Arg0DispatchPaths;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
@@ -12,138 +9,12 @@ use codex_config::NoopThreadConfigLoader;
use codex_core::config::ConfigBuilder;
use codex_core::config::ConfigOverrides;
use codex_core::config::set_project_trust_level;
use codex_http_client::DestinationPolicy;
use codex_http_client::HttpClientFactory;
use codex_http_client::NetworkPermit;
use codex_http_client::NetworkPolicyDenied;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::ExternalAuth;
use codex_login::ExternalAuthFuture;
use codex_login::ExternalAuthRefreshContext;
use codex_model_provider::DEFAULT_CHATGPT_BASE_URL;
use codex_protocol::config_types::TrustLevel;
use pretty_assertions::assert_eq;
use std::sync::Arc;
struct BootstrapExternalAuth(CodexAuth);
impl ExternalAuth for BootstrapExternalAuth {
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
Box::pin(async { Ok(self.0.clone()) })
}
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
self.resolve()
}
}
#[tokio::test]
async fn bootstrap_discovery_survives_identity_installation_but_account_access_is_revoked()
-> anyhow::Result<()> {
let home = tempfile::tempdir()?;
let overrides = LoaderOverrides::without_managed_config_for_tests();
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.loader_overrides(overrides.clone())
.build()
.await?;
let policy = EmbeddedNetworkPolicy::load(&overrides).await;
let auth_config = policy.bind_bootstrap_auth(config.auth_config());
let bootstrap = auth_config.auth_route_config.http_client_factory().clone();
let bundle_url =
codex_backend_client::Client::new(config.chatgpt_base_url.clone(), bootstrap.clone())
.config_bundle_url()
.parse()?;
let content_url = "https://chatgpt.com/backend-api/codex/responses".parse()?;
let manager = AuthManager::new(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::Ephemeral,
/*forced_chatgpt_workspace_id*/ None,
Some(config.chatgpt_base_url.clone()),
AuthKeyringBackendKind::default(),
auth_config.auth_route_config,
)
.await;
assert!(manager.auth_cached().is_none());
bootstrap.network_policy().acquire(&bundle_url)?;
let mut previous_access: Option<(HttpClientFactory, NetworkPermit)> = None;
for identity in ["bootstrap-account-one", "bootstrap-account-two"] {
let token = format!(
"e30.{}.signature",
URL_SAFE_NO_PAD.encode(serde_json::to_vec(&serde_json::json!({
"sub": "bootstrap-user",
"https://api.openai.com/auth": {
"chatgpt_user_id": "bootstrap-user",
"chatgpt_account_id": identity,
},
}))?),
);
let auth = CodexAuth::from_external_chatgpt_tokens(&token, identity, Some("enterprise"))?;
manager
.set_external_auth(Arc::new(BootstrapExternalAuth(auth)))
.await?;
if let Some((client, permit)) = previous_access.take() {
assert_eq!(permit.check(), Err(NetworkPolicyDenied::Revoked));
assert_eq!(
client.network_policy().acquire(&content_url).err(),
Some(NetworkPolicyDenied::Revoked)
);
}
// Discovery must remain possible after both initial login and a workspace change.
bootstrap.network_policy().acquire(&bundle_url)?;
assert_eq!(
bootstrap.network_policy().acquire(&content_url).err(),
Some(NetworkPolicyDenied::Destination)
);
assert_eq!(
manager
.application_network_policy()
.acquire(&content_url)
.err(),
Some(NetworkPolicyDenied::Unavailable)
);
assert!(policy.effective.publish(
policy.effective.policy().revision(),
DestinationPolicy::Unrestricted,
));
let client = manager.http_client_factory();
let permit = client.network_policy().acquire(&content_url)?;
previous_access = Some((client, permit));
}
let (client, permit) = previous_access.expect("the last identity has active account access");
manager.clear_external_auth();
assert_eq!(permit.check(), Err(NetworkPolicyDenied::Revoked));
assert_eq!(
client.network_policy().acquire(&content_url).err(),
Some(NetworkPolicyDenied::Revoked)
);
assert_eq!(
manager
.application_network_policy()
.acquire(&content_url)
.err(),
Some(NetworkPolicyDenied::Unavailable)
);
bootstrap.network_policy().acquire(&bundle_url)?;
// Losing local requirements must still close the bootstrap route.
policy.local.unavailable(policy.local.policy().revision());
assert_eq!(
bootstrap.network_policy().acquire(&bundle_url).err(),
Some(NetworkPolicyDenied::Unavailable)
);
Ok(())
}
#[tokio::test]
async fn startup_reloads_the_callers_selected_project() -> anyhow::Result<()> {
let temp = tempfile::tempdir()?;

View File

@@ -99,13 +99,11 @@ pub use codex_agent_message_board_host::delete_agent_message_boards;
pub use codex_agent_message_board_host::install_agent_message_board;
mod analytics_utils;
mod app_info;
mod app_server_tracing;
mod attestation;
mod auth_mode;
mod bespoke_event_handling;
#[doc(hidden)]
pub mod chatgpt_connectors;
mod code_mode_host;
mod codex_home_metrics;
mod command_exec;
@@ -155,7 +153,6 @@ mod thread_state;
mod thread_status;
mod transport;
mod turn_admission;
mod turn_cost_worker;
mod user_verification;
mod user_verification_response;

View File

@@ -560,8 +560,6 @@ enabled = false
goal_service: Arc::new(codex_goal_extension::GoalService::new()),
environment_manager: Arc::clone(&environment_manager),
executor_skill_provider: Arc::clone(&executor_skill_provider),
git_attribution_base_url: good_config.chatgpt_base_url.clone(),
http_client_factory: good_config.http_client_factory(),
queue_service: None,
turn_start_admission: None,
},

View File

@@ -26,7 +26,6 @@ use crate::outgoing_message::RequestContext;
use crate::plugin_config_reload;
use crate::plugin_config_reload::PluginStartupConfig;
use crate::request_processors::AccountRequestProcessor;
use crate::request_processors::AppsRequestProcessor;
use crate::request_processors::CatalogRequestProcessor;
use crate::request_processors::CommandExecRequestProcessor;
use crate::request_processors::ConfigRequestProcessor;
@@ -61,7 +60,6 @@ use crate::thread_state::ConnectionCapabilities;
use crate::thread_state::ThreadStateManager;
use crate::transport::AppServerTransport;
use crate::transport::RemoteControlHandle;
use crate::turn_cost_worker::TurnCostWorker;
use codex_analytics::AnalyticsEventsClient;
use codex_analytics::AppServerRpcTransport;
use codex_app_server_protocol::ClientNotification;
@@ -155,10 +153,8 @@ pub(crate) struct MessageProcessor {
outgoing: Arc<OutgoingMessageSender>,
startup_warnings: StartupWarnings,
models_refresh_worker: ModelsRefreshWorker,
turn_cost_worker: Option<TurnCostWorker>,
skills_watcher: Arc<SkillsWatcher>,
account_processor: Arc<AccountRequestProcessor>,
apps_processor: AppsRequestProcessor,
catalog_processor: CatalogRequestProcessor,
command_exec_processor: CommandExecRequestProcessor,
process_exec_processor: ProcessExecRequestProcessor,
@@ -400,8 +396,6 @@ impl MessageProcessor {
environment_manager: Arc::clone(&environment_manager_for_extensions),
executor_skill_provider: Arc::clone(&executor_skill_provider),
cloud_skill_provider: cloud_skill_provider.clone(),
git_attribution_base_url: config.chatgpt_base_url.clone(),
http_client_factory: config.http_client_factory(),
queue_service: queue_service.clone(),
turn_start_admission: Some(Arc::clone(&turn_start_admission)),
},
@@ -440,11 +434,6 @@ impl MessageProcessor {
Arc::clone(&thread_manager),
));
let models_refresh_worker = crate::models_refresh_worker::spawn(&model_catalog);
let turn_cost_worker = TurnCostWorker::spawn(
Arc::clone(&config),
Arc::clone(&auth_manager),
runtime_auth.map(|runtime| (runtime, config.runtime_auth_mode)),
);
thread_manager
.plugins_manager()
.set_analytics_events_client(analytics_events_client.clone());
@@ -458,7 +447,6 @@ impl MessageProcessor {
let thread_watch_manager =
crate::thread_status::ThreadWatchManager::new_with_outgoing(outgoing.clone());
let thread_list_state_permit = Arc::new(Semaphore::new(/*permits*/ 1));
let app_list_shutdown_token = CancellationToken::new();
let request_serialization_queues = RequestSerializationQueues::default();
let config_processor = ConfigRequestProcessor::new(
outgoing.clone(),
@@ -483,12 +471,6 @@ impl MessageProcessor {
config_manager.clone(),
Arc::clone(&model_catalog),
);
let apps_processor = AppsRequestProcessor::new(
Arc::clone(&thread_manager),
outgoing.clone(),
config_manager.clone(),
app_list_shutdown_token,
);
let catalog_processor = CatalogRequestProcessor::new(
outgoing.clone(),
Arc::clone(&skills_watcher),
@@ -574,7 +556,6 @@ impl MessageProcessor {
state_db.clone(),
log_db,
Arc::clone(&skills_watcher),
turn_cost_worker.as_ref().map(TurnCostWorker::handle),
config_warnings.clone(),
sample_responses,
);
@@ -588,7 +569,6 @@ impl MessageProcessor {
thread_state_manager,
thread_watch_manager,
Arc::clone(&skills_watcher),
turn_cost_worker.as_ref().map(TurnCostWorker::handle),
);
if let Some(startup_config) = plugin_startup_tasks {
let reload_config = match startup_config {
@@ -650,10 +630,8 @@ impl MessageProcessor {
config: config_warnings,
},
models_refresh_worker,
turn_cost_worker,
skills_watcher,
account_processor,
apps_processor,
catalog_processor,
command_exec_processor,
process_exec_processor,
@@ -681,7 +659,6 @@ impl MessageProcessor {
pub(crate) fn clear_runtime_references(&self) {
self.account_processor.clear_external_auth();
self.apps_processor.shutdown();
self.models_refresh_worker.shutdown();
self.skills_watcher.shutdown();
}
@@ -915,9 +892,6 @@ impl MessageProcessor {
pub(crate) async fn drain_background_tasks(&self) {
self.models_refresh_worker.shutdown();
if let Some(worker) = &self.turn_cost_worker {
worker.shutdown();
}
self.thread_processor.drain_background_tasks().await;
}
@@ -1706,15 +1680,22 @@ impl MessageProcessor {
ClientRequest::PluginShareDelete { params, .. } => {
self.plugin_processor.plugin_share_delete(params).await
}
ClientRequest::AppsRead { params, .. } => self.apps_processor.apps_read(params).await,
ClientRequest::AppsList { params, .. } => {
self.apps_processor.apps_list(&request_id, params).await
// ChatGPT apps/connectors are not available in aKode.
ClientRequest::AppsRead { .. } => Err(method_not_found(
"ChatGPT apps are not available in aKode",
)),
ClientRequest::AppsList { .. } => Ok(Some(
codex_app_server_protocol::AppsListResponse {
data: Vec::new(),
next_cursor: None,
}
.into(),
)),
ClientRequest::AppsInstalled { .. } => {
Ok(Some(
codex_app_server_protocol::AppsInstalledResponse { apps: Vec::new() }.into(),
))
}
ClientRequest::AppsInstalled { params, .. } => self
.apps_processor
.apps_installed(params)
.await
.map(|response| Some(response.into())),
ClientRequest::SkillsConfigWrite { params, .. } => {
self.catalog_processor.skills_config_write(params).await
}
@@ -1948,25 +1929,13 @@ impl MessageProcessor {
.await
.into(),
)),
ClientRequest::GetAccountRateLimits { params, .. } => {
self.account_processor.get_account_rate_limits(params).await
}
ClientRequest::ConsumeAccountRateLimitResetCredit { params, .. } => {
self.account_processor
.consume_account_rate_limit_reset_credit(params)
.await
}
ClientRequest::GetAccountTokenUsage { params, .. } => {
self.account_processor.get_account_token_usage(params).await
}
ClientRequest::GetWorkspaceMessages { .. } => {
self.account_processor.get_workspace_messages().await
}
ClientRequest::SendAddCreditsNudgeEmail { params, .. } => {
self.account_processor
.send_add_credits_nudge_email(params)
.await
}
ClientRequest::GetAccountRateLimits { .. }
| ClientRequest::ConsumeAccountRateLimitResetCredit { .. }
| ClientRequest::GetAccountTokenUsage { .. }
| ClientRequest::GetWorkspaceMessages { .. }
| ClientRequest::SendAddCreditsNudgeEmail { .. } => Err(method_not_found(
"ChatGPT usage, credits and workspace messages are not available in aKode",
)),
ClientRequest::GitDiffToRemote { params, .. } => {
self.git_processor.git_diff_to_remote(params).await
}

View File

@@ -1,5 +1,4 @@
use crate::bespoke_event_handling::apply_bespoke_event_handling;
use crate::chatgpt_connectors as connectors;
use crate::command_exec::CommandExecManager;
use crate::command_exec::StartCommandExecParams;
use crate::config_manager::ConfigManager;
@@ -22,23 +21,12 @@ use codex_analytics::InputError;
use codex_analytics::TurnSteerRequestError;
use codex_app_server_protocol::Account;
use codex_app_server_protocol::AccountLoginCompletedNotification;
use codex_app_server_protocol::AccountTokenUsageDailyBucket;
use codex_app_server_protocol::AccountTokenUsageSummary;
use codex_app_server_protocol::AccountUpdatedNotification;
use codex_app_server_protocol::AddCreditsNudgeCreditType;
use codex_app_server_protocol::AddCreditsNudgeEmailStatus;
use codex_app_server_protocol::AdditionalContextEntry;
use codex_app_server_protocol::AdditionalContextKind;
use codex_app_server_protocol::AppListUpdatedNotification;
use codex_app_server_protocol::AppSummary;
use codex_app_server_protocol::AppTemplateSummary;
use codex_app_server_protocol::AppTemplateUnavailableReason;
use codex_app_server_protocol::AppsInstalledParams;
use codex_app_server_protocol::AppsInstalledResponse;
use codex_app_server_protocol::AppsListParams;
use codex_app_server_protocol::AppsListResponse;
use codex_app_server_protocol::AppsReadParams;
use codex_app_server_protocol::AppsReadResponse;
use codex_app_server_protocol::AskForApproval;
use codex_app_server_protocol::AuthMode;
use codex_app_server_protocol::CancelLoginAccountParams;
@@ -55,9 +43,6 @@ use codex_app_server_protocol::CommandExecResizeParams;
use codex_app_server_protocol::CommandExecTerminateParams;
use codex_app_server_protocol::CommandExecWriteParams;
use codex_app_server_protocol::ConfigWarningNotification;
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome;
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditParams;
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse;
use codex_app_server_protocol::ConversationGitInfo;
use codex_app_server_protocol::ConversationSummary;
use codex_app_server_protocol::DeprecationNoticeNotification;
@@ -79,15 +64,11 @@ use codex_app_server_protocol::ExperimentalFeatureStage as ApiExperimentalFeatur
use codex_app_server_protocol::FeedbackUploadParams;
use codex_app_server_protocol::FeedbackUploadResponse;
use codex_app_server_protocol::GetAccountParams;
use codex_app_server_protocol::GetAccountRateLimitsResponse;
use codex_app_server_protocol::GetAccountResponse;
use codex_app_server_protocol::GetAccountTokenUsageParams;
use codex_app_server_protocol::GetAccountTokenUsageResponse;
use codex_app_server_protocol::GetAuthStatusParams;
use codex_app_server_protocol::GetAuthStatusResponse;
use codex_app_server_protocol::GetConversationSummaryParams;
use codex_app_server_protocol::GetConversationSummaryResponse;
use codex_app_server_protocol::GetWorkspaceMessagesResponse;
use codex_app_server_protocol::GitDiffToRemoteParams;
use codex_app_server_protocol::GitDiffToRemoteResponse;
use codex_app_server_protocol::GitInfo as ApiGitInfo;
@@ -97,7 +78,6 @@ use codex_app_server_protocol::HooksListParams;
use codex_app_server_protocol::HooksListResponse;
use codex_app_server_protocol::InitializeParams;
use codex_app_server_protocol::InitializeResponse;
use codex_app_server_protocol::InstalledApp;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::ListMcpServerStatusParams;
use codex_app_server_protocol::ListMcpServerStatusResponse;
@@ -169,17 +149,11 @@ use codex_app_server_protocol::PluginSource;
use codex_app_server_protocol::PluginSummary;
use codex_app_server_protocol::PluginUninstallParams;
use codex_app_server_protocol::PluginUninstallResponse;
use codex_app_server_protocol::RateLimitResetCredit;
use codex_app_server_protocol::RateLimitResetCreditStatus;
use codex_app_server_protocol::RateLimitResetCreditsSummary;
use codex_app_server_protocol::RateLimitResetType;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ReviewStartParams;
use codex_app_server_protocol::ReviewStartResponse;
use codex_app_server_protocol::ReviewTarget as ApiReviewTarget;
use codex_app_server_protocol::SandboxMode;
use codex_app_server_protocol::SendAddCreditsNudgeEmailParams;
use codex_app_server_protocol::SendAddCreditsNudgeEmailResponse;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::SkillSummary;
use codex_app_server_protocol::SkillsConfigWriteParams;
@@ -316,29 +290,16 @@ use codex_app_server_protocol::WindowsSandboxSetupCompletedNotification;
use codex_app_server_protocol::WindowsSandboxSetupMode;
use codex_app_server_protocol::WindowsSandboxSetupStartParams;
use codex_app_server_protocol::WindowsSandboxSetupStartResponse;
use codex_app_server_protocol::WorkspaceMessage;
use codex_app_server_protocol::WorkspaceMessageType;
use codex_arg0::Arg0DispatchPaths;
use codex_backend_client::AddCreditsNudgeCreditType as BackendAddCreditsNudgeCreditType;
use codex_backend_client::Client as BackendClient;
use codex_backend_client::CodexWorkspaceMessage as BackendWorkspaceMessage;
use codex_backend_client::CodexWorkspaceMessageType as BackendWorkspaceMessageType;
use codex_backend_client::CodexWorkspaceMessagesResponse as BackendWorkspaceMessagesResponse;
use codex_backend_client::ConsumeRateLimitResetCreditCode as BackendConsumeRateLimitResetCreditCode;
use codex_backend_client::RateLimitResetCreditDetails as BackendRateLimitResetCreditDetails;
use codex_backend_client::RateLimitResetCreditsDetails as BackendRateLimitResetCreditsDetails;
use codex_backend_client::RequestError as BackendRequestError;
use codex_backend_client::TokenUsageProfile;
use codex_config::CloudConfigBundleLoadError;
use codex_config::CloudConfigBundleLoadErrorCode;
use codex_config::ConfigLayerStack;
use codex_config::loader::project_trust_key;
use codex_config::types::McpServerTransportConfig;
use codex_connectors::AppInfo;
use codex_core::CodexThread;
use codex_core::CodexThreadSettingsOverrides;
use codex_core::ForkSnapshot;
use codex_core::McpManager;
use codex_core::NewThread;
use codex_core::NotSubmittedReason;
#[cfg(test)]
@@ -356,7 +317,6 @@ use codex_core::config::ConfigOverrides;
use codex_core::config::NetworkProxyAuditMetadata;
use codex_core::config::edit::ConfigEdit;
use codex_core::config::edit::ConfigEditsBuilder;
use codex_core::connectors::AccessibleConnectorsStatus;
use codex_core::exec::ExecCapturePolicy;
use codex_core::exec::ExecExpiration;
use codex_core::exec::ExecParams;
@@ -376,7 +336,6 @@ use codex_core_plugins::PluginInstallError as CorePluginInstallError;
use codex_core_plugins::PluginInstallRequest;
use codex_core_plugins::PluginReadRequest;
use codex_core_plugins::PluginUninstallError as CorePluginUninstallError;
use codex_core_plugins::PluginsManager;
use codex_core_plugins::loader::load_plugin_apps;
use codex_core_plugins::manifest::PluginManifestInterface;
use codex_core_plugins::marketplace::MarketplaceError;
@@ -525,7 +484,6 @@ use tokio::sync::broadcast;
use tokio::sync::oneshot;
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
use tokio_util::sync::DropGuard;
use tokio_util::task::TaskTracker;
use toml::Value as TomlValue;
use tracing::Instrument;
@@ -538,7 +496,6 @@ use uuid::Uuid;
use codex_app_server_protocol::ServerRequest;
pub(crate) mod account_processor;
mod apps_processor;
mod bedrock_auth;
mod catalog_processor;
mod command_exec_processor;
@@ -580,7 +537,6 @@ mod turn_processor;
mod windows_sandbox_processor;
pub(crate) use account_processor::AccountRequestProcessor;
pub(crate) use apps_processor::AppsRequestProcessor;
pub(crate) use catalog_processor::CatalogRequestProcessor;
pub(crate) use command_exec_processor::CommandExecRequestProcessor;
pub(crate) use config_processor::ConfigRequestProcessor;

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(),
}
}

View File

@@ -1,555 +0,0 @@
use codex_backend_client::ApiKeyTurnCost;
use codex_backend_client::ApiKeyTurnCostStatus;
use codex_backend_client::Client as BackendClient;
use codex_backend_client::RequestError;
use codex_config::types::OtelExporterKind;
use codex_core::config::Config;
use codex_features::RuntimeAuthMode;
use codex_login::AuthManager;
use codex_model_provider::SharedModelProvider;
use codex_otel::SessionTelemetry;
use codex_protocol::ThreadId;
use codex_protocol::auth::AuthMode;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_runtime_agent_instance::RuntimeAuthManager;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::warn;
const POLL_INTERVAL: Duration = Duration::from_secs(150);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
const OBSERVATION_CHANNEL_CAPACITY: usize = 16_384;
const MAX_TRACKED_TURNS: usize = 4_096;
const MAX_QUERY_TURNS: usize = 100;
const MAX_TRACKED_RESPONSES_PER_TURN: usize = 4_096;
const MAX_STALLED_POLL_ATTEMPTS: u8 = 5;
pub(crate) struct TurnCostWorker {
handle: TurnCostWorkerHandle,
shutdown: CancellationToken,
_task: JoinHandle<()>,
}
#[derive(Clone)]
pub(crate) struct TurnCostWorkerHandle {
sender: mpsc::Sender<TurnCostObservation>,
backend: TurnCostBackend,
config: Arc<Config>,
}
enum TurnCostObservationKind {
Started {
session_telemetry: Box<SessionTelemetry>,
},
ResponseCompleted {
response_id: String,
},
Finished {
interrupted: bool,
},
}
struct TurnCostObservation {
thread_id: ThreadId,
turn_id: String,
kind: TurnCostObservationKind,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum TurnCostStatus {
Running,
Completed,
Interrupted,
}
struct TurnCostEntry {
thread_id: ThreadId,
session_telemetry: SessionTelemetry,
expected_response_ids: HashSet<String>,
status: TurnCostStatus,
next_poll_at: Instant,
attempt_count: u8,
}
struct WorkerRuntime {
config: Arc<Config>,
backend: TurnCostBackend,
turns: HashMap<String, TurnCostEntry>,
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
}
#[derive(Clone)]
enum TurnCostBackend {
OpenAi(Arc<AuthManager>),
ModelProvider(SharedModelProvider),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BackendAvailability {
AwaitingAuthChange,
RetryProbe,
Ready,
Disabled,
}
impl TurnCostWorker {
pub(crate) fn spawn(
config: Arc<Config>,
auth_manager: Arc<AuthManager>,
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
) -> Option<Self> {
let has_otel_log_exporter = matches!(
config.otel.exporter,
OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. }
);
let has_otel_metrics_exporter = matches!(
config.otel.metrics_exporter,
OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. }
);
if !(has_otel_log_exporter || has_otel_metrics_exporter)
|| config.model_provider.is_amazon_bedrock()
{
return None;
}
let is_openai = config.model_provider.is_openai();
let backend = if is_openai {
TurnCostBackend::OpenAi(Arc::clone(&auth_manager))
} else {
TurnCostBackend::ModelProvider(
codex_model_provider::ProviderAuthContext {
credentials: Arc::clone(&auth_manager),
runtime_auth: runtime_auth.clone(),
}
.model_provider(config.model_provider.clone()),
)
};
let (sender, receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY);
let shutdown = CancellationToken::new();
let runtime = WorkerRuntime {
config: Arc::clone(&config),
backend: backend.clone(),
turns: HashMap::new(),
runtime_auth,
};
let worker_shutdown = shutdown.clone();
let task = tokio::spawn(async move {
runtime.run(receiver, worker_shutdown).await;
});
Some(Self {
handle: TurnCostWorkerHandle {
sender,
backend,
config,
},
shutdown,
_task: task,
})
}
pub(crate) fn handle(&self) -> TurnCostWorkerHandle {
self.handle.clone()
}
pub(crate) fn shutdown(&self) {
self.shutdown.cancel();
}
}
impl Drop for TurnCostWorker {
fn drop(&mut self) {
self.shutdown();
}
}
impl TurnCostWorkerHandle {
pub(crate) fn observe_event(
&self,
thread_id: ThreadId,
thread_config: &Config,
event: &Event,
session_telemetry: impl FnOnce() -> SessionTelemetry,
) {
if thread_config.model_provider != self.config.model_provider {
return;
}
if let TurnCostBackend::OpenAi(auth_manager) = &self.backend {
let Some(auth) = auth_manager.auth_cached() else {
return;
};
if !auth.is_api_key_auth() && !auth.is_chatgpt_auth() {
return;
}
}
let kind = match &event.msg {
EventMsg::TurnStarted(_) => TurnCostObservationKind::Started {
session_telemetry: Box::new(session_telemetry()),
},
EventMsg::RawResponseCompleted(event) => TurnCostObservationKind::ResponseCompleted {
response_id: event.response_id.clone(),
},
EventMsg::TurnComplete(_) => TurnCostObservationKind::Finished { interrupted: false },
EventMsg::TurnAborted(_) => TurnCostObservationKind::Finished { interrupted: true },
_ => return,
};
let _ = self.sender.try_send(TurnCostObservation {
thread_id,
turn_id: event.id.clone(),
kind,
});
}
}
impl WorkerRuntime {
async fn run(self, receiver: mpsc::Receiver<TurnCostObservation>, shutdown: CancellationToken) {
let auth_changes = match &self.backend {
TurnCostBackend::OpenAi(auth_manager) => Some(auth_manager.auth_change_receiver()),
TurnCostBackend::ModelProvider(_) => None,
};
let backend_availability = self.probe_backend().await;
self.run_with_backend_availability(receiver, shutdown, auth_changes, backend_availability)
.await;
}
async fn run_with_backend_availability(
mut self,
mut receiver: mpsc::Receiver<TurnCostObservation>,
shutdown: CancellationToken,
mut auth_changes: Option<tokio::sync::watch::Receiver<u64>>,
mut backend_availability: BackendAvailability,
) {
let mut ticker = tokio::time::interval(POLL_INTERVAL);
ticker.tick().await;
loop {
tokio::select! {
biased;
_ = shutdown.cancelled() => break,
changed = async {
match auth_changes.as_mut() {
Some(auth_changes) => auth_changes.changed().await,
None => std::future::pending().await,
}
} => {
if changed.is_err() {
break;
}
// Cost telemetry is best effort: auth changes may drop pending turns.
// Callers can query the cost API directly to reconcile missing telemetry.
self.turns.clear();
while receiver.try_recv().is_ok() {}
backend_availability = self.probe_backend().await;
}
observation = receiver.recv() => {
let Some(observation) = observation else {
break;
};
if !matches!(
backend_availability,
BackendAvailability::Ready | BackendAvailability::RetryProbe
) {
continue;
}
self.record_observation(observation);
}
_ = ticker.tick() => {
match backend_availability {
BackendAvailability::Ready => self.poll_due().await,
BackendAvailability::RetryProbe => {
backend_availability = self.probe_backend().await;
}
BackendAvailability::AwaitingAuthChange
| BackendAvailability::Disabled => {}
}
}
}
}
}
async fn probe_backend(&self) -> BackendAvailability {
let probe_turn_ids = [uuid::Uuid::new_v4().to_string()];
match tokio::time::timeout(REQUEST_TIMEOUT, self.query_turn_costs(&probe_turn_ids)).await {
Ok(Ok(Some(_))) => BackendAvailability::Ready,
Ok(Ok(None)) => match self.backend {
TurnCostBackend::OpenAi(_) => BackendAvailability::AwaitingAuthChange,
TurnCostBackend::ModelProvider(_) => BackendAvailability::Disabled,
},
Ok(Err(error)) => match error.status().map(|status| status.as_u16()) {
Some(401 | 403) if matches!(self.backend, TurnCostBackend::OpenAi(_)) => {
tracing::debug!(
status = error.status().map(|status| status.as_u16()),
"turn cost worker waiting for auth change after backend availability check"
);
BackendAvailability::AwaitingAuthChange
}
Some(401 | 403 | 429) => BackendAvailability::RetryProbe,
Some(400..=499) => {
tracing::debug!(
status = error.status().map(|status| status.as_u16()),
"turn cost worker disabled by backend availability check"
);
BackendAvailability::Disabled
}
_ => {
tracing::debug!(
status = error.status().map(|status| status.as_u16()),
"turn cost worker backend availability check failed temporarily"
);
BackendAvailability::RetryProbe
}
},
Err(_) => {
tracing::debug!(
"turn cost worker backend availability check timed out; will retry"
);
BackendAvailability::RetryProbe
}
}
}
fn record_observation(&mut self, observation: TurnCostObservation) {
match observation.kind {
TurnCostObservationKind::Started { session_telemetry } => {
if self.turns.len() < MAX_TRACKED_TURNS {
self.turns
.entry(observation.turn_id)
.or_insert(TurnCostEntry {
thread_id: observation.thread_id,
session_telemetry: *session_telemetry,
expected_response_ids: HashSet::new(),
status: TurnCostStatus::Running,
next_poll_at: Instant::now(),
attempt_count: 0,
});
}
}
TurnCostObservationKind::ResponseCompleted { response_id } => {
if let Some(entry) = self.turns.get_mut(&observation.turn_id)
&& entry.status == TurnCostStatus::Running
{
if entry.expected_response_ids.len() >= MAX_TRACKED_RESPONSES_PER_TURN {
self.turns.remove(&observation.turn_id);
return;
}
entry.expected_response_ids.insert(response_id);
}
}
TurnCostObservationKind::Finished { interrupted } => {
let Some(entry) = self.turns.get_mut(&observation.turn_id) else {
return;
};
if entry.status != TurnCostStatus::Running {
return;
}
entry.status = if interrupted {
TurnCostStatus::Interrupted
} else {
TurnCostStatus::Completed
};
entry.next_poll_at = Instant::now();
}
}
}
async fn poll_due(&mut self) {
let now = Instant::now();
let due_turn_ids: Vec<String> = self
.turns
.iter()
.filter(|(_, entry)| {
entry.status != TurnCostStatus::Running && entry.next_poll_at <= now
})
.take(MAX_QUERY_TURNS)
.map(|(turn_id, _)| turn_id.clone())
.collect();
if !due_turn_ids.is_empty() {
self.poll_entries(&due_turn_ids).await;
}
}
async fn poll_entries(&mut self, turn_ids: &[String]) {
let costs =
match tokio::time::timeout(REQUEST_TIMEOUT, self.query_turn_costs(turn_ids)).await {
Ok(Ok(Some(costs))) => costs,
Ok(Ok(None)) => return,
Ok(Err(error)) => {
warn!(
status = error.status().map(|status| status.as_u16()),
"failed to query turn costs"
);
self.retry_entries(turn_ids);
return;
}
Err(_) => {
warn!("timed out querying turn costs");
self.retry_entries(turn_ids);
return;
}
};
let costs_by_turn: HashMap<String, ApiKeyTurnCost> = costs
.into_iter()
.map(|cost| (cost.turn_id.clone(), cost))
.collect();
for turn_id in turn_ids {
let Some(cost) = costs_by_turn.get(turn_id) else {
self.retry_entry(turn_id);
continue;
};
self.process_turn_cost(turn_id, cost);
}
}
async fn query_turn_costs(
&self,
turn_ids: &[String],
) -> Result<Option<Vec<ApiKeyTurnCost>>, RequestError> {
match &self.backend {
TurnCostBackend::OpenAi(auth_manager) => {
let Some((auth, captured_factory)) =
auth_manager.auth_with_http_client_factory().await
else {
return Ok(None);
};
let http_client_factory = self
.config
.http_client_factory()
.with_network_policy(captured_factory.network_policy().clone());
if auth.is_chatgpt_auth() {
return self
.query_chatgpt_turn_costs(&auth, http_client_factory, turn_ids)
.await
.map(Some);
}
if !auth.is_api_key_auth() {
return Ok(None);
}
let provider = self
.config
.model_provider
.to_api_provider(Some(AuthMode::ApiKey))
.map_err(|error| RequestError::Other(error.into()))?;
let client = BackendClient::from_auth_with_runtime(
self.config.chatgpt_backend_url().resolve(&auth),
&auth,
http_client_factory,
self.runtime_auth.as_ref(),
&provider.headers,
)
.await
.map_err(RequestError::Other)?;
client
.query_api_key_turn_costs(turn_ids, &provider.headers)
.await
.map(Some)
}
TurnCostBackend::ModelProvider(model_provider) => {
let http_client_factory = self.config.http_client_factory().with_network_policy(
self.config
.application_network_policy
.clone()
.for_current_account(),
);
if model_provider.info().requires_openai_auth {
let Some(auth) = model_provider.auth().await else {
return Ok(None);
};
if !auth.is_api_key_auth() {
return Ok(None);
}
}
let resolved = codex_model_provider::resolve_request(
model_provider.as_ref(),
/*scope*/ None,
/*routing*/ None,
http_client_factory,
)
.await
.map_err(|error| RequestError::Other(error.into()))?;
let provider = resolved.api_provider;
let endpoint = provider.url_for_path("analytics/codex/turn-costs");
let client =
BackendClient::new(provider.base_url.clone(), resolved.http_client_factory)
.with_auth_provider(resolved.api_auth)
.map_err(RequestError::Other)?;
client
.query_api_key_turn_costs_at(&endpoint, turn_ids, &provider.headers)
.await
.map(Some)
}
}
}
fn process_turn_cost(&mut self, turn_id: &str, cost: &ApiKeyTurnCost) {
if cost.status != ApiKeyTurnCostStatus::Priced {
self.retry_entry(turn_id);
return;
}
let response_count = cost
.responses
.as_ref()
.map(|responses| responses.len() as u64)
.or(cost.event_count);
let (Some(total_usd), Some(response_count)) = (cost.total_usd.as_deref(), response_count)
else {
self.retry_entry(turn_id);
return;
};
let Some(entry) = self.turns.get(turn_id) else {
return;
};
if response_count < entry.expected_response_ids.len() as u64 {
self.retry_entry(turn_id);
return;
}
let mut session_telemetry = entry.session_telemetry.clone();
if let Some(model) = cost.model.as_deref() {
session_telemetry = session_telemetry.with_model(model, model);
}
let Some(entry) = self.turns.remove(turn_id) else {
return;
};
session_telemetry.record_turn_cost(
turn_id,
total_usd,
entry.status == TurnCostStatus::Interrupted,
cost.speed.as_deref(),
cost.reasoning_effort.as_deref(),
);
}
fn retry_entries(&mut self, turn_ids: &[String]) {
for turn_id in turn_ids {
self.retry_entry(turn_id);
}
}
fn retry_entry(&mut self, turn_id: &str) {
let Some(entry) = self.turns.get_mut(turn_id) else {
return;
};
entry.attempt_count = entry.attempt_count.saturating_add(1);
if entry.attempt_count >= MAX_STALLED_POLL_ATTEMPTS {
warn!(
thread_id = %entry.thread_id,
turn_id,
attempts = MAX_STALLED_POLL_ATTEMPTS,
"dropping turn cost event after repeated unsuccessful polls"
);
self.turns.remove(turn_id);
return;
}
entry.next_poll_at = Instant::now() + POLL_INTERVAL;
}
}
#[path = "turn_cost_worker_chatgpt.rs"]
mod chatgpt;
#[cfg(test)]
#[path = "turn_cost_worker_tests.rs"]
mod tests;

View File

@@ -1,86 +0,0 @@
//! Adapts workspace-visible SiWC estimates to the shared turn-cost emission path.
//! Emit only nonnegative, visible amounts covering every observed completed response;
//! missing amounts/settlement data must never be interpreted as a zero-cost turn.
use super::ApiKeyTurnCost;
use super::ApiKeyTurnCostStatus;
use super::BackendClient;
use super::RequestError;
use super::WorkerRuntime;
use codex_login::CodexAuth;
use std::collections::BTreeMap;
impl WorkerRuntime {
pub(super) async fn query_chatgpt_turn_costs(
&self,
auth: &CodexAuth,
http_client_factory: codex_http_client::HttpClientFactory,
turn_ids: &[String],
) -> Result<Vec<ApiKeyTurnCost>, RequestError> {
let mut threads: BTreeMap<String, Vec<String>> = BTreeMap::new();
for turn_id in turn_ids {
// Availability probes use an untracked, random thread/turn pair.
let thread_id = self
.turns
.get(turn_id)
.map(|entry| entry.thread_id)
.unwrap_or_default();
threads
.entry(thread_id.to_string())
.or_default()
.push(turn_id.clone());
}
let client = BackendClient::from_auth_with_runtime(
self.config.chatgpt_base_url.clone(),
auth,
http_client_factory,
self.runtime_auth.as_ref(),
/*headers*/ &Default::default(),
)
.await
.map_err(RequestError::Other)?;
let costs = client.query_chatgpt_turn_costs(&threads).await?;
let mut settled_costs = Vec::new();
for thread in costs {
let Some(requested_turns) = threads.get(&thread.thread_id) else {
continue;
};
for cost in thread.turns {
if !requested_turns.contains(&cost.turn_id) {
continue;
}
let Some(entry) = self.turns.get(&cost.turn_id) else {
continue;
};
let (Some(micros), Some(settled_ids)) =
(cost.estimated_usage_usd_micros, cost.settled_response_ids)
else {
continue;
};
// Missing/hidden dollars are not zero. A projection can appear before
// all responses settle, so require every locally observed response.
if micros < 0
|| entry.expected_response_ids.is_empty()
|| !entry
.expected_response_ids
.iter()
.all(|id| settled_ids.contains(id))
{
continue;
}
// Reuse the existing emission path without a floating-point conversion.
settled_costs.push(ApiKeyTurnCost {
turn_id: cost.turn_id,
status: ApiKeyTurnCostStatus::Priced,
total_usd: Some(format!("{}.{:06}", micros / 1_000_000, micros % 1_000_000)),
event_count: Some(settled_ids.len() as u64),
responses: None,
model: cost.model,
speed: None,
reasoning_effort: None,
});
}
}
Ok(settled_costs)
}
}

View File

@@ -1,73 +0,0 @@
//! Checks unusable SiWC estimates and exact conversion; public app-server/OTLP coverage lives in turn_cost_otel.
use super::*;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use test_case::test_case;
#[test_case(json!(null), json!(["resp-one", "resp-two"]), None; "hidden or incomplete amount")]
#[test_case(json!(-1), json!(["resp-one", "resp-two"]), None; "negative amount")]
#[test_case(json!(1), json!(null), None; "missing settlement")]
#[test_case(json!(1), json!([]), None; "unsettled")]
#[test_case(json!(1), json!(["unrelated"]), None; "wrong response")]
#[test_case(json!(1), json!(["resp-one"]), None; "only one response settled")]
#[test_case(json!(0), json!(["resp-one", "resp-two"]), Some("0.000000"); "zero")]
#[test_case(json!(i64::MAX), json!(["resp-one", "resp-two"]), Some("9223372036854.775807"); "integer precision")]
#[tokio::test]
async fn chatgpt_cost_requires_visible_amount_and_matching_settlement(
micros: Value,
settled_ids: Value,
expected: Option<&str>,
) {
let server = MockServer::start().await;
let mut runtime = test_runtime(
&server,
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
)
.await;
let thread_id = ThreadId::new();
runtime.turns.insert(
"turn-1".to_string(),
TurnCostEntry {
thread_id,
session_telemetry: test_session_telemetry(thread_id),
expected_response_ids: HashSet::from(["resp-one".to_string(), "resp-two".to_string()]),
status: TurnCostStatus::Completed,
next_poll_at: Instant::now(),
attempt_count: 0,
},
);
Mock::given(method("POST"))
.and(path("/api/codex/usage/thread-estimates/query"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!({"threads": [{
"thread_id": thread_id, "turns": [{"turn_id": "turn-1",
"estimated_usage_usd_micros": micros, "settled_response_ids": settled_ids}]
}]})),
)
.expect(1)
.mount(&server)
.await;
let costs = runtime
.query_turn_costs(&["turn-1".to_string()])
.await
.expect("query")
.expect("SiWC enabled");
assert_eq!(
costs,
expected
.map(|amount| ApiKeyTurnCost {
turn_id: "turn-1".to_string(),
status: ApiKeyTurnCostStatus::Priced,
total_usd: Some(amount.to_string()),
event_count: Some(2),
responses: None,
model: None,
speed: None,
reasoning_effort: None,
})
.into_iter()
.collect::<Vec<_>>()
);
}

View File

@@ -1,124 +0,0 @@
//! Exercise runtime-authenticated turn-cost requests through OpenAI and provider aliases.
use super::*;
use codex_features::RuntimeAuthMode;
use codex_runtime_agent_instance::AgentHostAuthorization;
use codex_runtime_agent_instance::RuntimeAuthManager;
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
use codex_runtime_agent_instance::RuntimeRole;
use pretty_assertions::assert_eq;
use test_case::test_case;
use wiremock::matchers::body_partial_json;
#[test_case(false; "default OpenAI provider")]
#[test_case(true; "OpenAI alias")]
#[tokio::test]
async fn turn_costs_register_with_requested_organization(openai_alias: bool) {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let registration = if openai_alias {
ResponseTemplate::new(200).set_body_json(serde_json::json!({
"runtime_agent_instance_id": "runtime-telemetry", "agent_host_id": "host-a",
"actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-a", "project_id": null},
}))
} else {
// Inspect registration without sending a request to the real OpenAI destination.
ResponseTemplate::new(403)
};
Mock::given(path("/agent/register"))
.and(body_partial_json(serde_json::json!({
"actor_auth": {"organization_id": "org-a"},
})))
.respond_with(registration)
.expect(1)
.mount(&server)
.await;
Mock::given(path(TURN_COST_PATH))
.and(header("openai-organization", "org-a"))
.respond_with(
ResponseTemplate::new(200).set_body_json(serde_json::json!({"turns": []})),
)
.expect(if openai_alias { 2 } else { 0 })
.mount(&server)
.await;
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a"));
let mut worker = test_runtime(&server, credentials.clone()).await;
let owner = Arc::new(RuntimeAuthManager::new(
credentials.clone(),
AgentHostAuthorization::InstallationId {
installation_id: uuid::Uuid::nil(),
},
RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/agent/register", server.uri()).parse().unwrap(),
));
let mut info = codex_model_provider_info::ModelProviderInfo::create_openai_provider(Some(
format!("{}/v1", server.uri()),
));
info.name = "OpenAI alias".to_string();
info.http_headers = Some(HashMap::from([(
"OpenAI-Organization".to_string(),
"org-a".into(),
)]));
if openai_alias {
worker.backend = TurnCostBackend::ModelProvider(
codex_model_provider::test_support::runtime_model_provider(
info,
credentials,
(owner, mode),
),
);
} else {
let config = Arc::make_mut(&mut worker.config);
config.model_provider = info;
config.chatgpt_base_url = "https://chatgpt.com".to_string();
worker.runtime_auth = Some((owner, mode));
worker
.query_turn_costs(&[])
.await
.expect_err("registration denial must stop the cost request");
server.verify().await;
continue;
}
for _ in 0..2 {
assert!(
worker
.query_turn_costs(&[])
.await
.unwrap()
.unwrap()
.is_empty()
);
}
let requests = server.received_requests().await.unwrap();
let proofs: Vec<_> = requests
.iter()
.filter(|r| r.url.path() != "/agent/register")
.map(|r| {
let authorization = r.headers["authorization"].to_str().unwrap();
match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(authorization, "Bearer key-a");
r.headers["x-openai-agent-assertion"]
.to_str()
.unwrap()
.to_owned()
}
RuntimeAuthMode::AssertionOnly => {
assert!(!r.headers.contains_key("x-openai-agent-assertion"));
authorization
.strip_prefix("AgentAssertion ")
.unwrap()
.to_owned()
}
}
})
.collect();
assert_eq!(proofs.len(), 2);
assert_eq!(proofs.iter().collect::<HashSet<_>>().len(), 2);
server.verify().await;
}
}

View File

@@ -1,507 +0,0 @@
use super::*;
use codex_backend_client::ApiKeyResponseCost;
use codex_core::config::ConfigBuilder;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::CodexAuth;
use codex_login::login_with_api_key;
use codex_model_provider::create_model_provider;
use codex_model_provider_info::ModelProviderInfo;
use codex_otel::TelemetryAuthMode;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::TurnStartedEvent;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use test_case::test_case;
use tokio::time::timeout;
use tracing::instrument::WithSubscriber;
use tracing_subscriber::layer::SubscriberExt;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
const TURN_COST_PATH: &str = "/v1/analytics/codex/turn-costs";
#[path = "turn_cost_worker_chatgpt_tests.rs"]
mod chatgpt;
#[tokio::test]
async fn worker_starts_with_otlp_metrics_exporter_without_log_exporter() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(TURN_COST_PATH))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"turns": []
})))
.expect(1)
.mount(&server)
.await;
let codex_home = TempDir::new().expect("temporary Codex home");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("test config");
config.chatgpt_base_url = server.uri();
config.otel.exporter = OtelExporterKind::None;
config.otel.metrics_exporter = OtelExporterKind::OtlpGrpc {
endpoint: server.uri(),
headers: HashMap::new(),
tls: None,
};
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test"));
let worker = TurnCostWorker::spawn(Arc::new(config), auth_manager, /*runtime_auth*/ None)
.expect("OTLP metrics exporter should enable turn-cost collection");
wait_for_request_count(&server, /*expected*/ 1).await;
worker.shutdown();
server.verify().await;
}
#[tokio::test]
async fn handle_observes_only_matching_model_provider() {
let codex_home = TempDir::new().expect("temporary Codex home");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("test config");
let model_provider = ModelProviderInfo {
name: "provider-a".to_string(),
base_url: Some("https://provider-a.example/v1".to_string()),
..Default::default()
};
config.model_provider = model_provider.clone();
let config = Arc::new(config);
let (sender, mut receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY);
let handle = TurnCostWorkerHandle {
sender,
backend: TurnCostBackend::ModelProvider(create_model_provider(
model_provider.clone(),
/*auth_manager*/ None,
)),
config: Arc::clone(&config),
};
let thread_id = ThreadId::new();
let event = Event {
id: "turn-1".to_string(),
msg: EventMsg::TurnStarted(TurnStartedEvent {
turn_attribution: None,
turn_id: "turn-1".to_string(),
root_turn_id: None,
trace_id: None,
started_at: None,
model_context_window: None,
collaboration_mode_kind: Default::default(),
}),
};
let mut mismatched_config = config.as_ref().clone();
mismatched_config.model_provider = ModelProviderInfo {
base_url: Some("https://provider-b.example/v1".to_string()),
..model_provider
};
handle.observe_event(thread_id, &mismatched_config, &event, || {
panic!("telemetry should not be captured for a mismatched provider")
});
assert!(receiver.try_recv().is_err());
handle.observe_event(thread_id, config.as_ref(), &event, || {
test_session_telemetry(thread_id)
});
let observation = receiver.recv().await.expect("matching observation");
assert_eq!(observation.thread_id, thread_id);
assert_eq!(observation.turn_id, "turn-1");
assert!(matches!(
observation.kind,
TurnCostObservationKind::Started { .. }
));
}
#[tokio::test]
async fn worker_waits_for_late_api_key_login() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(TURN_COST_PATH))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"turns": []
})))
.expect(1)
.mount(&server)
.await;
let auth_home = TempDir::new().expect("temporary auth home");
let auth_manager = auth_manager_at(auth_home.path()).await;
let runtime = test_runtime(&server, Arc::clone(&auth_manager)).await;
let (_sender, receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY);
let shutdown = CancellationToken::new();
let mut task = tokio::spawn(runtime.run(receiver, shutdown.clone()));
assert!(
timeout(Duration::from_millis(/*millis*/ 50), &mut task)
.await
.is_err(),
"worker exited while waiting for login"
);
login_with_api_key(
auth_home.path(),
"sk-test",
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)
.expect("write API-key auth");
assert!(auth_manager.reload().await);
wait_for_request_count(&server, /*expected*/ 1).await;
shutdown.cancel();
task.await.expect("worker task");
server.verify().await;
}
#[tokio::test]
async fn custom_provider_auth_failure_retries_without_auth_changes() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/analytics/codex/turn-costs"))
.and(header("authorization", "Bearer sk-old"))
.respond_with(ResponseTemplate::new(401))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/analytics/codex/turn-costs"))
.and(header("authorization", "Bearer sk-new-token"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"turns": []
})))
.expect(1)
.mount(&server)
.await;
let provider_auth_home = TempDir::new().expect("temporary provider auth home");
login_with_api_key(
provider_auth_home.path(),
"sk-old",
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)
.expect("write initial provider auth");
let provider_auth_manager = auth_manager_at(provider_auth_home.path()).await;
let codex_home = TempDir::new().expect("temporary Codex home");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("test config");
config.model_provider = ModelProviderInfo {
name: "custom-provider".to_string(),
base_url: Some(server.uri()),
requires_openai_auth: true,
..Default::default()
};
let backend = TurnCostBackend::ModelProvider(create_model_provider(
config.model_provider.clone(),
Some(Arc::clone(&provider_auth_manager)),
));
let runtime = WorkerRuntime {
config: Arc::new(config),
backend,
turns: HashMap::new(),
runtime_auth: None,
};
assert_eq!(
runtime.probe_backend().await,
BackendAvailability::RetryProbe
);
login_with_api_key(
provider_auth_home.path(),
"sk-new-token",
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)
.expect("update provider auth");
provider_auth_manager.reload().await;
assert_eq!(runtime.probe_backend().await, BackendAvailability::Ready);
server.verify().await;
}
#[tokio::test]
async fn custom_provider_does_not_send_chatgpt_auth_for_turn_costs() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/analytics/codex/turn-costs"))
.respond_with(ResponseTemplate::new(500))
.mount(&server)
.await;
let auth_manager =
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
let codex_home = TempDir::new().expect("temporary Codex home");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("test config");
config.model_provider = ModelProviderInfo {
name: "custom-provider".to_string(),
base_url: Some(server.uri()),
requires_openai_auth: true,
..Default::default()
};
let backend = TurnCostBackend::ModelProvider(create_model_provider(
config.model_provider.clone(),
Some(Arc::clone(&auth_manager)),
));
let runtime = WorkerRuntime {
config: Arc::new(config),
backend,
turns: HashMap::new(),
runtime_auth: None,
};
assert_eq!(runtime.probe_backend().await, BackendAvailability::Disabled);
let requests = server.received_requests().await.expect("received requests");
assert!(requests.is_empty());
}
#[tokio::test]
async fn transient_probe_failure_keeps_worker_alive() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(TURN_COST_PATH))
.respond_with(ResponseTemplate::new(500).set_body_string("temporary failure"))
.expect(1)
.mount(&server)
.await;
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test"));
let runtime = test_runtime(&server, Arc::clone(&auth_manager)).await;
let backend_availability = runtime.probe_backend().await;
assert_eq!(backend_availability, BackendAvailability::RetryProbe);
let (_sender, receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY);
let shutdown = CancellationToken::new();
let auth_changes = Some(auth_manager.auth_change_receiver());
let mut task = tokio::spawn(runtime.run_with_backend_availability(
receiver,
shutdown.clone(),
auth_changes,
backend_availability,
));
assert!(
timeout(Duration::from_millis(/*millis*/ 50), &mut task)
.await
.is_err(),
"worker exited after a transient probe failure"
);
shutdown.cancel();
task.await.expect("worker task");
server.verify().await;
}
#[tokio::test]
async fn priced_cost_uses_telemetry_captured_before_thread_removal() {
let server = MockServer::start().await;
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test"));
let mut runtime = test_runtime(&server, auth_manager).await;
let thread_id = ThreadId::new();
let turn_id = "turn-1";
runtime.record_observation(TurnCostObservation {
thread_id,
turn_id: turn_id.to_string(),
kind: TurnCostObservationKind::Started {
session_telemetry: Box::new(test_session_telemetry(thread_id)),
},
});
runtime.record_observation(TurnCostObservation {
thread_id,
turn_id: turn_id.to_string(),
kind: TurnCostObservationKind::ResponseCompleted {
response_id: "resp-one".to_string(),
},
});
runtime.record_observation(TurnCostObservation {
thread_id,
turn_id: turn_id.to_string(),
kind: TurnCostObservationKind::Finished { interrupted: false },
});
runtime.process_turn_cost(
turn_id,
&ApiKeyTurnCost {
turn_id: turn_id.to_string(),
status: ApiKeyTurnCostStatus::Priced,
total_usd: Some("1.25".to_string()),
event_count: Some(1),
responses: None,
model: Some("gpt-5.6".to_string()),
speed: Some("fast".to_string()),
reasoning_effort: Some("high".to_string()),
},
);
assert_eq!(runtime.turns.len(), 0);
}
#[tokio::test]
async fn priced_cost_waits_for_every_response_when_response_costs_are_available() {
let server = MockServer::start().await;
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test"));
let mut runtime = test_runtime(&server, auth_manager).await;
let thread_id = ThreadId::new();
let turn_id = "turn-1";
runtime.turns.insert(
turn_id.to_string(),
TurnCostEntry {
thread_id,
session_telemetry: test_session_telemetry(thread_id),
expected_response_ids: HashSet::from(["resp-one".to_string(), "resp-two".to_string()]),
status: TurnCostStatus::Completed,
next_poll_at: Instant::now(),
attempt_count: 0,
},
);
let mut cost = ApiKeyTurnCost {
turn_id: turn_id.to_string(),
status: ApiKeyTurnCostStatus::Priced,
total_usd: Some("1.25".to_string()),
event_count: Some(2),
responses: Some(vec![ApiKeyResponseCost {
response_id: "resp-one".to_string(),
total_usd: "1.25".to_string(),
}]),
model: Some("gpt-5.6".to_string()),
speed: Some("fast".to_string()),
reasoning_effort: Some("high".to_string()),
};
runtime.process_turn_cost(turn_id, &cost);
let entry = runtime.turns.get(turn_id).expect("turn remains tracked");
assert_eq!(entry.attempt_count, 1);
cost.event_count = None;
cost.responses
.as_mut()
.expect("response costs")
.push(ApiKeyResponseCost {
response_id: "resp-two".to_string(),
total_usd: "0.50".to_string(),
});
runtime.process_turn_cost(turn_id, &cost);
assert_eq!(runtime.turns.len(), 0);
}
async fn test_runtime(server: &MockServer, auth_manager: Arc<AuthManager>) -> WorkerRuntime {
let codex_home = TempDir::new().expect("temporary Codex home");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("test config");
config.chatgpt_base_url = server.uri();
let backend = TurnCostBackend::OpenAi(Arc::clone(&auth_manager));
WorkerRuntime {
config: Arc::new(config),
backend,
turns: HashMap::new(),
runtime_auth: None,
}
}
async fn auth_manager_at(codex_home: &std::path::Path) -> Arc<AuthManager> {
Arc::new(
AuthManager::new(
codex_home.to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::default(),
codex_login::test_support::transport_default_auth_route_config(),
)
.await,
)
}
fn test_session_telemetry(thread_id: ThreadId) -> SessionTelemetry {
SessionTelemetry::new(
thread_id,
"gpt-5.6",
"gpt-5.6",
/*account_id*/ None,
/*account_email*/ None,
Some(TelemetryAuthMode::ApiKey),
"test".to_string(),
/*log_user_prompts*/ false,
"test".to_string(),
SessionSource::Cli,
)
}
async fn wait_for_request_count(server: &MockServer, expected: usize) {
timeout(Duration::from_secs(/*secs*/ 15), async {
loop {
let requests = server.received_requests().await.unwrap_or_default();
if requests.len() >= expected {
break;
}
tokio::task::yield_now().await;
}
})
.await
.expect("timed out waiting for turn-cost request");
}
#[test_case(500; "HTTP failure")]
#[test_case(200; "decode failure")]
#[tokio::test]
async fn turn_cost_failures_do_not_log_response_bodies(status: u16) {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(TURN_COST_PATH))
.respond_with(
ResponseTemplate::new(status).set_body_string("private-workspace-response-marker"),
)
.expect(2)
.mount(&server)
.await;
let mut runtime = test_runtime(
&server,
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test")),
)
.await;
let capture = tempfile::NamedTempFile::new().expect("log capture");
let subscriber = tracing_subscriber::fmt()
.with_ansi(false)
.with_max_level(tracing::Level::DEBUG)
.with_writer(Arc::new(capture.reopen().expect("log writer")))
.finish();
// A parallel test can first register this callsite without a subscriber.
// Keep two dispatchers alive so it cannot globally disable our log capture.
let _parallel_dispatch = tracing::Dispatch::new(
tracing_subscriber::registry().with(tracing_subscriber::filter::LevelFilter::OFF),
);
async {
assert_eq!(
runtime.probe_backend().await,
BackendAvailability::RetryProbe
);
runtime.poll_entries(&["turn-1".to_string()]).await;
}
.with_subscriber(subscriber)
.await;
let logs = std::fs::read_to_string(capture.path()).expect("captured logs");
assert!(logs.contains("backend availability check failed temporarily"));
assert!(logs.contains("failed to query turn costs"));
assert!(!logs.contains("private-workspace-response-marker"));
server.verify().await;
}
#[path = "turn_cost_worker_runtime_auth_tests.rs"]
mod runtime_auth;