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

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

View File

@@ -0,0 +1,7 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "backend-client",
compile_data = glob(["tests/fixtures/**"]),
crate_name = "codex_backend_client",
)

View File

@@ -0,0 +1,39 @@
[package]
name = "codex-backend-client"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[lib]
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
anyhow = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
http = { workspace = true }
url = { workspace = true }
codex-backend-openapi-models = { path = "../codex-backend-openapi-models" }
codex-api = { workspace = true }
codex-features = { workspace = true }
codex-http-client = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-login = { workspace = true }
codex-model-provider = { workspace = true }
codex-runtime-agent-instance = { workspace = true }
codex-protocol = { workspace = true }
codex-response-debug-context = { workspace = true }
tokio = { workspace = true, features = ["time"] }
[dev-dependencies]
base64 = { workspace = true }
uuid = { workspace = true }
pretty_assertions = "1"
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,182 @@
//! Local analytics authentication, server plan discovery, and account/user identity checks.
//! Each new session fetches its plan once; token plan claims do not select reports.
use crate::Client;
use crate::RequestError;
use codex_features::RuntimeAuthMode;
use codex_http_client::HttpClientFactory;
use codex_login::AuthManager;
use codex_login::AuthManagerConfig;
use codex_login::CodexAuth;
use codex_protocol::account::PlanType;
use codex_runtime_agent_instance::RegistrationError;
use codex_runtime_agent_instance::RuntimeAuthError;
use codex_runtime_agent_instance::RuntimeAuthManager;
use codex_runtime_agent_instance::resolve_installation_id;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::sync::Arc;
/// Non-secret account metadata associated with an analytics session.
#[derive(Clone, Debug)]
pub struct AnalyticsAccount {
pub id: String,
pub email: Option<String>,
pub plan_type: Option<PlanType>,
}
/// A backend client bound to its initial ChatGPT account and user, with a server plan snapshot.
pub struct AnalyticsSession {
client: Client,
auth_manager: Arc<AuthManager>,
auth: CodexAuth,
account: AnalyticsAccount,
}
impl AnalyticsSession {
/// Load local ChatGPT credentials and the current server plan using the configured HTTP policy.
pub async fn from_config(
config: &impl AuthManagerConfig,
http_client_factory: HttpClientFactory,
runtime_auth_mode: Option<RuntimeAuthMode>,
) -> Result<Self, String> {
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false)
.await
.map_err(|_| {
"Couldn't load local sign-in. Sign in with ChatGPT and retry.".to_string()
})?;
let auth = auth_manager
.auth()
.await
.filter(CodexAuth::is_chatgpt_auth)
.ok_or("Sign in locally with ChatGPT to view Analytics.")?;
let (Some(id), Some(_)) = (auth.get_account_id(), auth.get_chatgpt_user_id()) else {
return Err("Analytics requires a ChatGPT account and user identity.".into());
};
let account = AnalyticsAccount {
id,
email: auth.get_account_email(),
plan_type: None,
};
let base_url = config.chatgpt_base_url();
let runtime_auth_mode = runtime_auth_mode
.filter(|_| codex_runtime_agent_instance::is_openai_api_url(&base_url));
let client = match runtime_auth_mode {
Some(mode) => {
let home = AbsolutePathBuf::from_absolute_path(config.codex_home())
.map_err(|_| "Couldn't initialize local Analytics authentication.")?;
let installation_id = resolve_installation_id(&home)
.await
.map_err(|_| "Couldn't initialize local Analytics authentication.")?;
let runtime = (
Arc::new(RuntimeAuthManager::for_codex(
Arc::clone(&auth_manager),
&base_url,
&installation_id,
)),
mode,
);
Client::from_auth_with_runtime_without_redirects(
&base_url,
&auth,
http_client_factory,
Some(&runtime),
/*headers*/ &Default::default(),
)
.await
.map_err(|error| {
match error.downcast_ref::<RuntimeAuthError>() {
Some(
RuntimeAuthError::RefreshFailed
| RuntimeAuthError::RefreshTokenFailed(_)
| RuntimeAuthError::Registration(RegistrationError::Rejected {
status: http::StatusCode::UNAUTHORIZED,
..
}),
) => "Sign in again to load Analytics.",
_ => "Couldn't authenticate the Analytics request.",
}
})?
}
None => Client::new_without_redirects(base_url, http_client_factory)
.with_auth_provider(codex_model_provider::auth_provider_from_auth_manager(
Arc::clone(&auth_manager),
&auth,
))
.map_err(|_| "Couldn't initialize local Analytics authentication.")?,
};
let mut session = Self {
client,
auth_manager,
auth,
account,
};
let accounts = session
.request(|client| async move { client.get_accounts_check().await })
.await;
// Preserve account-switch guidance even when it interrupts account discovery.
session.ensure_identity().await?;
let accounts = accounts.map_err(|error| {
if error.is_unauthorized() {
"Sign in again to load Analytics."
} else {
"Couldn't load account plan. Press R to retry Analytics."
}
})?;
session.account.plan_type = Some(
accounts
.accounts
.into_iter()
.find(|account| account.id == session.account.id)
.and_then(|account| account.plan_type)
.ok_or("Couldn't load account plan. Press R to retry Analytics.")?,
);
Ok(session)
}
/// Return the account metadata captured when this session was opened.
pub fn account(&self) -> &AnalyticsAccount {
&self.account
}
/// Reject responses or cached data after a local account or user change.
pub async fn ensure_identity(&self) -> Result<(), String> {
self.auth_manager.reload().await;
let current = self.auth_manager.auth().await;
if current.is_none_or(|auth| {
auth.get_account_id() != self.auth.get_account_id()
|| auth.get_chatgpt_user_id() != self.auth.get_chatgpt_user_id()
}) {
return Err("Account changed. Press R to refresh Analytics.".into());
}
Ok(())
}
/// Run an account-scoped request with bounded unauthorized recovery.
pub async fn request<T, F>(&self, request: impl Fn(Client) -> F) -> Result<T, RequestError>
where
F: std::future::Future<Output = Result<T, RequestError>>,
{
let mut recovery = self.auth_manager.unauthorized_recovery();
loop {
self.ensure_identity()
.await
.map_err(|error| RequestError::Other(anyhow::anyhow!(error)))?;
let result = request(self.client.clone()).await;
// Keep the original 401 when recovery fails so callers retain sign-in guidance.
if result.as_ref().is_err_and(RequestError::is_unauthorized)
&& recovery.has_next()
&& recovery.next().await.is_ok()
{
continue;
}
self.ensure_identity()
.await
.map_err(|error| RequestError::Other(anyhow::anyhow!(error)))?;
return result;
}
}
}
#[cfg(test)]
#[path = "analytics_session_tests.rs"]
mod tests;

View File

@@ -0,0 +1,114 @@
//! Authentication recovery preserves actionable status without changing the account scope.
use super::*;
use codex_http_client::OutboundProxyPolicy;
use codex_login::ExternalAuth;
use codex_login::ExternalAuthFuture;
use codex_login::ExternalAuthRefreshContext;
use codex_login::RefreshTokenError;
use codex_protocol::auth::RefreshTokenFailedError;
use codex_protocol::auth::RefreshTokenFailedReason;
use pretty_assertions::assert_eq;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
enum RefreshOutcome {
Accepted,
Rejected,
}
struct ExternalCredentials {
auth: CodexAuth,
outcome: RefreshOutcome,
refreshes: AtomicUsize,
}
impl ExternalAuth for ExternalCredentials {
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
Box::pin(async { Ok(self.auth.clone()) })
}
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
Box::pin(async {
self.refreshes.fetch_add(/*val*/ 1, Ordering::SeqCst);
match self.outcome {
RefreshOutcome::Accepted => Ok(self.auth.clone()),
RefreshOutcome::Rejected => Err(std::io::Error::other("refresh rejected")),
}
})
}
fn classify_error(&self, error: std::io::Error) -> RefreshTokenError {
RefreshTokenError::Permanent(RefreshTokenFailedError::new(
RefreshTokenFailedReason::Other,
error.to_string(),
))
}
}
#[tokio::test]
async fn failed_recovery_preserves_unauthorized_status() {
assert_unauthorized_after_recovery(RefreshOutcome::Rejected, /*expected_requests*/ 1).await;
}
#[tokio::test]
async fn persistent_unauthorized_stops_after_successful_recovery() {
assert_unauthorized_after_recovery(RefreshOutcome::Accepted, /*expected_requests*/ 2).await;
}
async fn assert_unauthorized_after_recovery(outcome: RefreshOutcome, expected_requests: u64) {
let auth = CodexAuth::from_external_chatgpt_tokens(
"e30.eyJleHAiOjQxMDI0NDQ4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X3VzZXJfaWQiOiJ1c2VyLWEifX0.test", "account-a", Some("plus"),
).unwrap();
let auth_manager = AuthManager::from_auth_for_testing(auth.clone());
let credentials = Arc::new(ExternalCredentials {
auth: auth.clone(),
outcome,
refreshes: AtomicUsize::new(/*v*/ 0),
});
auth_manager
.set_external_auth(credentials.clone())
.await
.unwrap();
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(/*s*/ 401))
.expect(expected_requests)
.mount(&server)
.await;
let client = Client::new_without_redirects(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.with_auth_provider(codex_model_provider::auth_provider_from_auth_manager(
Arc::clone(&auth_manager),
&auth,
))
.unwrap();
let session = AnalyticsSession {
account: AnalyticsAccount {
id: "account-a".into(),
email: None,
plan_type: auth.account_plan_type(),
},
client,
auth_manager,
auth,
};
let error = session
.request(|client| async move {
client
.get_account_analytics(crate::AnalyticsReport::Usage, "2026-09-01", "2026-09-07")
.await
})
.await
.unwrap_err();
assert_eq!(error.status().map(|status| status.as_u16()), Some(401));
session.ensure_identity().await.unwrap();
assert_eq!(credentials.refreshes.load(Ordering::SeqCst), 1);
server.verify().await;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,130 @@
//! Authenticated account analytics reads. Attribution and missing amounts remain unmodified.
use super::Client;
use super::PathStyle;
use super::RequestError;
use codex_backend_openapi_models::models::analytics as models;
use http::Method;
/// The bounded set of reports used by consumer and workspace Analytics views.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AnalyticsReport {
Usage,
EnterpriseTokens,
Credits,
WorkspaceCredits,
EnterpriseCredits { breakdown: &'static str },
Messages,
Plugins { limit: u8 },
Skills { limit: u8 },
}
/// Endpoint-specific backend contracts; normalization belongs to the consumer.
#[derive(Clone, Debug, PartialEq)]
pub enum AnalyticsResponse {
Usage(models::DailyProductSurfaceUsageResponse),
Credits(models::CreditUsageEventsResponse),
EnterpriseCredits(models::CurrentUserCreditUsageResponse),
Messages(models::DailyWorkspaceUsageCountResponse),
Plugins(models::PluginUsageMetricsResponse),
Skills(models::DailySkillUsageMetricsResponse),
}
impl Client {
/// Fetches one report for an inclusive UTC date range supplied by the caller.
pub async fn get_account_analytics(
&self,
report: AnalyticsReport,
start_date: &str,
end_date: &str,
) -> Result<AnalyticsResponse, RequestError> {
let route = match report {
AnalyticsReport::Usage => "usage/daily-token-usage-breakdown",
AnalyticsReport::Credits => "usage/credit-usage-events",
AnalyticsReport::WorkspaceCredits | AnalyticsReport::EnterpriseTokens => {
"usage/daily-workspace-user-token-usage-breakdown"
}
AnalyticsReport::EnterpriseCredits { .. } => "usage/daily-workspace-user-credit-usage",
AnalyticsReport::Messages => "analytics/daily-workspace-usage-counts",
AnalyticsReport::Plugins { .. } => "analytics/daily-plugin-usage-metrics",
AnalyticsReport::Skills { .. } => "analytics/daily-skill-usage-metrics",
};
let prefix = match self.path_style {
PathStyle::CodexApi => "api/codex",
PathStyle::ChatGptApi => "wham",
};
let mut url = url::Url::parse(&format!("{}/{prefix}/{route}", self.base_url))
.map_err(anyhow::Error::from)?;
if report != AnalyticsReport::Credits {
url.query_pairs_mut()
.append_pair("start_date", start_date)
.append_pair("end_date", end_date);
if let AnalyticsReport::EnterpriseCredits { breakdown } = report {
url.query_pairs_mut().append_pair("breakdown", breakdown);
} else {
url.query_pairs_mut().append_pair("group_by", "day");
}
}
if matches!(
report,
AnalyticsReport::Messages
| AnalyticsReport::Plugins { .. }
| AnalyticsReport::Skills { .. }
) {
url.query_pairs_mut().append_pair("workspace_user", "true");
}
match report {
AnalyticsReport::EnterpriseTokens => {
url.query_pairs_mut()
.append_pair("breakdown_by", "model")
.append_pair("modes", "codex")
.append_pair("modes", "work");
}
AnalyticsReport::Plugins { limit } => {
url.query_pairs_mut()
.append_pair("top_plugin_limit", &limit.to_string());
}
AnalyticsReport::Skills { limit } => {
url.query_pairs_mut()
.append_pair("top_skill_limit", &limit.to_string());
}
AnalyticsReport::Usage
| AnalyticsReport::Credits
| AnalyticsReport::WorkspaceCredits
| AnalyticsReport::EnterpriseCredits { .. }
| AnalyticsReport::Messages => {}
}
let request = self
.request(Method::GET, url.as_str())
.headers(self.headers().await?);
let (body, _) = self
.exec_request_detailed(request, "GET", url.as_str())
.await?;
// Do not include an untyped billing response in errors or diagnostics.
let response = match report {
AnalyticsReport::Usage
| AnalyticsReport::EnterpriseTokens
| AnalyticsReport::WorkspaceCredits => {
serde_json::from_str(&body).map(AnalyticsResponse::Usage)
}
AnalyticsReport::Credits => serde_json::from_str(&body).map(AnalyticsResponse::Credits),
AnalyticsReport::EnterpriseCredits { .. } => {
serde_json::from_str(&body).map(AnalyticsResponse::EnterpriseCredits)
}
AnalyticsReport::Messages => {
serde_json::from_str(&body).map(AnalyticsResponse::Messages)
}
AnalyticsReport::Plugins { .. } => {
serde_json::from_str(&body).map(AnalyticsResponse::Plugins)
}
AnalyticsReport::Skills { .. } => {
serde_json::from_str(&body).map(AnalyticsResponse::Skills)
}
};
response.map_err(|_| RequestError::Other(anyhow::anyhow!("Invalid analytics response.")))
}
}
#[cfg(test)]
#[path = "analytics_tests.rs"]
mod tests;

View File

@@ -0,0 +1,190 @@
//! HTTP contract coverage for account analytics report reads.
use super::*;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
#[tokio::test]
async fn account_analytics_uses_personal_daily_scope_and_plugin_contract() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/codex/analytics/daily-plugin-usage-metrics"))
.and(query_param("start_date", "2026-01-03"))
.and(query_param("end_date", "2026-01-09"))
.and(query_param("group_by", "day"))
.and(query_param("workspace_user", "true"))
.and(query_param("top_plugin_limit", "10"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"data": [{"date": "2026-01-03", "plugin_usage_overviews": [{
"plugin_id": null, "plugin_name": "example", "marketplace": null,
"display_name": "Example plugin", "invocation_counts": 12
}]}]
})))
.expect(/*r*/ 1)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let response = client
.get_account_analytics(
AnalyticsReport::Plugins { limit: 10 },
"2026-01-03",
"2026-01-09",
)
.await
.unwrap();
assert_eq!(
response,
AnalyticsResponse::Plugins(models::PluginUsageMetricsResponse {
data: vec![models::PluginUsageBucket {
date: "2026-01-03".into(),
plugin_usage_overviews: vec![models::PluginUsageOverview {
plugin_id: None,
plugin_name: "example".into(),
display_name: "Example plugin".into(),
marketplace: None,
invocation_counts: 12,
}],
}],
data_freshness_ts: None,
group_by: None,
})
);
}
#[tokio::test]
async fn account_analytics_preserves_signed_credit_events() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/wham/usage/credit-usage-events"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"data": [{"date": "2026-01-03", "product_surface": "cli", "credit_amount": -0.004}]
})))
.expect(/*r*/ 1)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.with_path_style(PathStyle::ChatGptApi);
let response = client
.get_account_analytics(AnalyticsReport::Credits, "2026-01-03", "2026-01-09")
.await
.unwrap();
assert_eq!(
response,
AnalyticsResponse::Credits(models::CreditUsageEventsResponse {
data: vec![models::CreditUsageEventBySurface {
date: "2026-01-03".into(),
product_surface: "cli".into(),
credit_amount: -0.004,
usage_id: None,
}],
})
);
}
#[tokio::test]
async fn account_analytics_rejects_another_reports_shape_without_logging_the_body() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/codex/analytics/daily-workspace-usage-counts"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"data": [{"date": "2026-01-03", "product_surface": "sensitive-value", "credit_amount": 10}]
})))
.expect(/*r*/ 1)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let error = client
.get_account_analytics(AnalyticsReport::Messages, "2026-01-03", "2026-01-09")
.await
.unwrap_err();
assert_eq!(error.to_string(), "Invalid analytics response.");
}
#[tokio::test]
async fn account_analytics_decodes_each_endpoint_and_accepts_new_string_values() {
for (report, route, body, expected) in [
(
AnalyticsReport::Usage,
"usage/daily-token-usage-breakdown",
json!({"data": [{"date": "2026-01-03", "product_surface_usage_values": {"future_surface": 1.0}}], "units": "future_unit"}),
AnalyticsResponse::Usage(models::DailyProductSurfaceUsageResponse {
data: vec![models::DailyProductSurfaceUsage {
date: "2026-01-03".into(),
product_surface_usage_values: [("future_surface".into(), 1.0)].into(),
..Default::default()
}],
units: Some("future_unit".into()),
..Default::default()
}),
),
(
AnalyticsReport::EnterpriseCredits { breakdown: "model" },
"usage/daily-workspace-user-credit-usage",
json!({"data": [], "series": [], "breakdown": "model"}),
AnalyticsResponse::EnterpriseCredits(models::CurrentUserCreditUsageResponse {
breakdown: "model".into(),
..Default::default()
}),
),
(
AnalyticsReport::Messages,
"analytics/daily-workspace-usage-counts",
json!({"data": []}),
AnalyticsResponse::Messages(models::DailyWorkspaceUsageCountResponse::default()),
),
(
AnalyticsReport::Skills { limit: 10 },
"analytics/daily-skill-usage-metrics",
json!({"data": []}),
AnalyticsResponse::Skills(models::DailySkillUsageMetricsResponse::default()),
),
(
AnalyticsReport::WorkspaceCredits,
"usage/daily-workspace-user-token-usage-breakdown",
json!({"data": []}),
AnalyticsResponse::Usage(models::DailyProductSurfaceUsageResponse::default()),
),
(
AnalyticsReport::EnterpriseTokens,
"usage/daily-workspace-user-token-usage-breakdown",
json!({"data": []}),
AnalyticsResponse::Usage(models::DailyProductSurfaceUsageResponse::default()),
),
] {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path(format!("/api/codex/{route}")))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(body))
.expect(/*r*/ 1)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
assert_eq!(
client
.get_account_analytics(report, "2026-01-03", "2026-01-09")
.await
.unwrap(),
expected
);
}
}

View File

@@ -0,0 +1,81 @@
//! Queries SiWC per-turn estimates using the client's Codex or WHAM route and auth.
//! Always request settled response IDs and retain thread/turn association and missing amounts.
use super::Client;
use super::PathStyle;
use super::RequestError;
use http::Method;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
/// Workspace-visible estimated cost and settled responses for a ChatGPT turn.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ChatgptTurnCost {
pub turn_id: String,
pub model: Option<String>,
pub estimated_usage_usd_micros: Option<i64>,
pub settled_response_ids: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ChatgptThreadTurnCosts {
pub thread_id: String,
pub turns: Vec<ChatgptTurnCost>,
}
#[derive(Serialize)]
struct ThreadTurnIds<'a> {
thread_id: &'a str,
turn_ids: &'a [String],
}
#[derive(Serialize)]
struct TurnCostsRequest<'a> {
threads: Vec<ThreadTurnIds<'a>>,
include_settled_response_ids: bool,
}
#[derive(Deserialize)]
struct TurnCostsResponse {
threads: Vec<ChatgptThreadTurnCosts>,
}
impl Client {
/// Queries per-turn estimates using the signed-in user's workspace permissions.
pub async fn query_chatgpt_turn_costs(
&self,
threads: &BTreeMap<String, Vec<String>>,
) -> Result<Vec<ChatgptThreadTurnCosts>, RequestError> {
let url = match self.path_style {
PathStyle::CodexApi => {
format!("{}/api/codex/usage/thread-estimates/query", self.base_url)
}
PathStyle::ChatGptApi => {
format!("{}/wham/usage/thread-estimates/query", self.base_url)
}
};
let request = self
.request(Method::POST, &url)
.headers(self.headers().await?)
.json(&TurnCostsRequest {
threads: threads
.iter()
.map(|(thread_id, turn_ids)| ThreadTurnIds {
thread_id,
turn_ids,
})
.collect(),
include_settled_response_ids: true,
});
let (body, content_type) = self.exec_request_detailed(request, "POST", &url).await?;
let response: TurnCostsResponse = self
.decode_json(&url, &content_type, &body)
.map_err(RequestError::Other)?;
Ok(response.threads)
}
}
#[cfg(test)]
#[path = "chatgpt_turn_cost_tests.rs"]
mod tests;

View File

@@ -0,0 +1,108 @@
//! Exercises both authenticated SiWC routes and preserves nullable/omitted estimate fields.
use super::*;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_login::CodexAuth;
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_json;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test]
async fn chatgpt_turn_costs_use_workspace_auth_and_chatgpt_path() {
check_query(
"/backend-api",
"/backend-api/wham/usage/thread-estimates/query",
)
.await;
}
#[tokio::test]
async fn chatgpt_turn_costs_use_workspace_auth_and_codex_path() {
check_query("", "/api/codex/usage/thread-estimates/query").await;
}
async fn check_query(base_path: &str, endpoint: &str) {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(endpoint))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.and(header("content-type", "application/json"))
.and(body_json(serde_json::json!({
"threads": [
{"thread_id": "thread-a", "turn_ids": ["turn-a"]},
{"thread_id": "thread-b", "turn_ids": ["turn-b", "turn-c"]}
],
"include_settled_response_ids": true
})))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"threads": [
{"thread_id": "thread-a", "turns": [{
"turn_id": "turn-a", "model": "gpt-5.6",
"estimated_usage_usd_micros": 1250001,
"settled_response_ids": ["resp-a", "resp-b"]
}]},
{"thread_id": "thread-b", "turns": [
{"turn_id": "turn-b", "estimated_usage_usd_micros": null,
"settled_response_ids": null},
{"turn_id": "turn-c", "estimated_usage_usd_micros": 0}
]}
]
})))
.expect(1)
.mount(&server)
.await;
let client = Client::from_auth(
format!("{}{base_path}", server.uri()),
&CodexAuth::create_dummy_chatgpt_auth_for_testing(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let result = client
.query_chatgpt_turn_costs(&BTreeMap::from([
("thread-a".to_string(), vec!["turn-a".to_string()]),
(
"thread-b".to_string(),
vec!["turn-b".to_string(), "turn-c".to_string()],
),
]))
.await
.expect("ChatGPT turn costs");
assert_eq!(
result,
vec![
ChatgptThreadTurnCosts {
thread_id: "thread-a".to_string(),
turns: vec![ChatgptTurnCost {
turn_id: "turn-a".to_string(),
model: Some("gpt-5.6".to_string()),
estimated_usage_usd_micros: Some(1250001),
settled_response_ids: Some(vec!["resp-a".to_string(), "resp-b".to_string()]),
}],
},
ChatgptThreadTurnCosts {
thread_id: "thread-b".to_string(),
turns: vec![
ChatgptTurnCost {
turn_id: "turn-b".to_string(),
model: None,
estimated_usage_usd_micros: None,
settled_response_ids: None,
},
ChatgptTurnCost {
turn_id: "turn-c".to_string(),
model: None,
estimated_usage_usd_micros: Some(0),
settled_response_ids: None,
},
],
},
]
);
server.verify().await;
}

View File

@@ -0,0 +1,87 @@
//! Seven-day allowance snapshots, preserving historical limits and unknown accounting.
use super::Client;
use super::PathStyle;
use super::RequestError;
use http::Method;
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PlanLimitHistory {
pub data_as_of: Option<String>,
pub coverage_start: Option<String>,
pub coverage_complete: bool,
#[serde(default = "approximate_by_default")]
pub approximate: bool,
pub boundary_tolerance_seconds: Option<u32>,
pub periods: Vec<PlanLimitPeriod>,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PlanLimitPeriod {
pub id: String,
pub window_minutes: u32,
pub plan_type: String,
pub starts_at: String,
pub ends_at: String,
pub accounting_complete: bool,
/// Hundredths of a percent of this period's historical allowance; null is unknown.
pub used_basis_points: Option<f64>,
pub breakdowns: Option<Vec<PlanLimitBreakdown>>,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PlanLimitDimension {
ThreadSource,
TurnTrigger,
Model,
Surface,
/// Additive server dimensions must not discard the supported breakdowns.
#[serde(other)]
Unknown,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PlanLimitBreakdown {
pub dimension: PlanLimitDimension,
pub rows: Vec<PlanLimitValue>,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PlanLimitValue {
pub key: String,
pub basis_points: f64,
}
fn approximate_by_default() -> bool {
true
}
impl Client {
/// Fetches seven days of snapshot history. An undeployed route has no report.
pub async fn get_plan_limit_history(&self) -> Result<Option<PlanLimitHistory>, RequestError> {
let prefix = match self.path_style {
PathStyle::CodexApi => "api/codex",
PathStyle::ChatGptApi => "wham",
};
let url = format!("{}/{prefix}/usage/plan_limit_history?days=7", self.base_url);
let request = self
.request(Method::GET, &url)
.headers(self.headers().await?);
let (body, _) = match self.exec_request_detailed(request, "GET", &url).await {
Ok(response) => response,
Err(error) if error.status().is_some_and(|status| status.as_u16() == 404) => {
return Ok(None);
}
Err(error) => return Err(error),
};
serde_json::from_str(&body)
.map(Some)
.map_err(|_| RequestError::Other(anyhow::anyhow!("Invalid plan history response.")))
}
}
#[cfg(test)]
#[path = "plan_history_tests.rs"]
mod tests;

View File

@@ -0,0 +1,51 @@
//! Plan history's undeployed route and wire defaults remain distinct from failures.
use super::*;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
#[tokio::test]
async fn plan_history_handles_unavailable_errors_and_approximation_default() {
let server = MockServer::start().await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
for status in [404, 503, 200] {
server.reset().await;
Mock::given(method("GET"))
.and(path("/api/codex/usage/plan_limit_history"))
.and(query_param("days", "7"))
.respond_with(ResponseTemplate::new(status).set_body_json(json!({
"data_as_of": null, "coverage_start": null, "coverage_complete": false,
"boundary_tolerance_seconds": null, "periods": []
})))
.expect(/*r*/ 1)
.mount(&server)
.await;
let response = client.get_plan_limit_history().await;
match status {
404 => assert_eq!(response.unwrap(), None),
503 => assert_eq!(response.unwrap_err().status().unwrap().as_u16(), status),
200 => assert_eq!(
response.unwrap(),
Some(PlanLimitHistory {
data_as_of: None,
coverage_start: None,
coverage_complete: false,
approximate: true,
boundary_tolerance_seconds: None,
periods: vec![],
})
),
_ => unreachable!(),
}
}
}

View File

@@ -0,0 +1,75 @@
//! Read-only profile statistics shared with the desktop account summary.
//! Optional fields retain absence; unknown invocation kinds do not invalidate other statistics.
use super::Client;
use super::RequestError;
use crate::TokenUsageProfileStats;
use http::Method;
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct AccountProfile {
pub profile: Option<ProfileIdentity>,
pub metadata: Option<ProfileMetadata>,
pub stats: ProfileStats,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct ProfileIdentity {
pub display_name: Option<String>,
pub username: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct ProfileMetadata {
pub stats_as_of: Option<String>,
pub stats_error: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct ProfileStats {
#[serde(flatten)]
pub tokens: TokenUsageProfileStats,
pub fast_mode_usage_percentage: Option<serde_json::Number>,
pub most_used_reasoning_effort: Option<String>,
pub most_used_reasoning_effort_percentage: Option<serde_json::Number>,
pub unique_skills_used: Option<u64>,
pub total_skills_used: Option<u64>,
pub total_threads: Option<u64>,
pub top_invocations: Option<Vec<ProfileInvocation>>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct ProfileInvocation {
#[serde(rename = "type")]
pub kind: ProfileInvocationKind,
pub plugin_name: Option<String>,
pub skill_name: Option<String>,
pub usage_count: Option<u64>,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProfileInvocationKind {
Plugin,
Skill,
#[serde(other)]
Unknown,
}
impl Client {
/// Read the full profile using the same route as account token usage.
pub async fn get_account_profile(&self) -> Result<AccountProfile, RequestError> {
let url = self.token_usage_profile_url();
let request = self
.request(Method::GET, &url)
.headers(self.headers().await?);
let (body, _) = self.exec_request_detailed(request, "GET", &url).await?;
serde_json::from_str(&body)
.map_err(|_| RequestError::Other(anyhow::anyhow!("Invalid account profile response.")))
}
}
#[cfg(test)]
#[path = "profile_tests.rs"]
mod tests;

View File

@@ -0,0 +1,126 @@
//! Full and partial profile decoding through the authenticated HTTP client.
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test]
async fn profile_keeps_missing_zero_and_future_invocations_distinct() {
let server = MockServer::start().await;
let client = Client::new(
server.uri(),
codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
);
let empty = AccountProfile {
profile: None,
metadata: None,
stats: ProfileStats {
tokens: TokenUsageProfileStats {
lifetime_tokens: None,
peak_daily_tokens: None,
longest_running_turn_sec: None,
current_streak_days: None,
longest_streak_days: None,
daily_usage_buckets: None,
},
fast_mode_usage_percentage: None,
most_used_reasoning_effort: None,
most_used_reasoning_effort_percentage: None,
unique_skills_used: None,
total_skills_used: None,
total_threads: None,
top_invocations: None,
},
};
let full = AccountProfile {
profile: Some(ProfileIdentity {
display_name: Some("Test user".into()),
username: Some("test.user".into()),
}),
metadata: Some(ProfileMetadata {
stats_as_of: Some("2026-09-09".into()),
stats_error: Some("partial upstream data".into()),
}),
stats: ProfileStats {
tokens: TokenUsageProfileStats {
lifetime_tokens: Some(142_300_000_000),
peak_daily_tokens: Some(7_000_000_000),
longest_running_turn_sec: Some(158_760),
current_streak_days: Some(158),
longest_streak_days: Some(160),
daily_usage_buckets: Some(vec![crate::TokenUsageProfileDailyBucket {
start_date: "2026-09-09".into(),
tokens: 42,
}]),
},
fast_mode_usage_percentage: serde_json::Number::from_f64(/*f*/ 37.5),
most_used_reasoning_effort: Some("high".into()),
most_used_reasoning_effort_percentage: Some(26.into()),
unique_skills_used: Some(147),
total_skills_used: Some(13_190),
total_threads: Some(0),
top_invocations: Some(vec![
ProfileInvocation {
kind: ProfileInvocationKind::Unknown,
plugin_name: None,
skill_name: None,
usage_count: None,
},
ProfileInvocation {
kind: ProfileInvocationKind::Skill,
plugin_name: None,
skill_name: Some("review".into()),
usage_count: Some(12),
},
ProfileInvocation {
kind: ProfileInvocationKind::Plugin,
plugin_name: Some("github".into()),
skill_name: None,
usage_count: Some(34),
},
]),
},
};
for (body, expected) in [
(json!({"stats":{}}), empty),
(
json!({
"profile":{"display_name":"Test user","username":"test.user"},
"metadata":{"stats_as_of":"2026-09-09","stats_error":"partial upstream data"},
"stats":{
"lifetime_tokens":142_300_000_000_i64,"peak_daily_tokens":7_000_000_000_i64,
"longest_running_turn_sec":158_760,"current_streak_days":158,"longest_streak_days":160,
"daily_usage_buckets":[{"start_date":"2026-09-09","tokens":42}],
"fast_mode_usage_percentage":37.5,"most_used_reasoning_effort":"high",
"most_used_reasoning_effort_percentage":26,"unique_skills_used":147,
"total_skills_used":13_190,"total_threads":0,
"top_invocations":[{"type":"future_kind"},{"type":"skill","skill_name":"review","usage_count":12},
{"type":"plugin","plugin_name":"github","usage_count":34}]
}
}),
full,
),
] {
Mock::given(method("GET"))
.and(path("/api/codex/profiles/me"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(body))
.expect(/*r*/ 1)
.mount(&server)
.await;
assert_eq!(client.get_account_profile().await.unwrap(), expected);
server.verify().await;
server.reset().await;
}
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_string("private invalid payload"))
.mount(&server)
.await;
let error = client.get_account_profile().await.unwrap_err().to_string();
assert_eq!(error, "Invalid account profile response.");
}

View File

@@ -0,0 +1,163 @@
//! Backend client operations for reading available rate-limit reset credits and consuming one.
use super::Client;
use super::PathStyle;
use crate::types::ConsumeRateLimitResetCreditResponse;
use crate::types::RateLimitResetCreditsDetails;
use crate::types::RateLimitStatusWithResetCredits;
use crate::types::RateLimitsWithResetCredits;
use anyhow::Result;
use http::Method;
use http::header::CONTENT_TYPE;
use http::header::HeaderValue;
use serde::Serialize;
#[derive(Serialize)]
struct ConsumeRateLimitResetCreditRequest<'a> {
redeem_request_id: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
credit_id: Option<&'a str>,
}
impl Client {
pub async fn get_rate_limits_with_reset_credits(&self) -> Result<RateLimitsWithResetCredits> {
self.get_rate_limits_for_usage(/*supports_luna_reserve*/ false)
.await
}
/// Opt in only for clients that can apply Reserve, not for passive account usage readers.
pub async fn get_rate_limits_with_luna_reserve(&self) -> Result<RateLimitsWithResetCredits> {
self.get_rate_limits_for_usage(/*supports_luna_reserve*/ true)
.await
}
async fn get_rate_limits_for_usage(
&self,
supports_luna_reserve: bool,
) -> Result<RateLimitsWithResetCredits> {
let payload = self.get_rate_limit_status(supports_luna_reserve).await?;
let ordinary_usage_allowed = payload
.rate_limits
.rate_limit
.as_ref()
.and_then(|limit| limit.as_deref())
.map(|limit| limit.allowed);
let mut rate_limits = Self::rate_limit_snapshots_from_payload(payload.rate_limits);
let plan_type = rate_limits.first().and_then(|snapshot| snapshot.plan_type);
rate_limits.extend(
payload
.additional_rate_limits
.into_iter()
.flatten()
.map(|limit| {
let mut snapshot =
Self::make_additional_rate_limit_snapshot(limit.details, plan_type);
snapshot.normal_model_slug = limit.normal_model_slug;
snapshot
}),
);
Ok(RateLimitsWithResetCredits {
rate_limits,
ordinary_usage_allowed,
rate_limit_reset_credits: payload.rate_limit_reset_credits,
account_id: payload.account_id,
user_id: payload.user_id,
rate_limit_upsell: payload.rate_limit_upsell,
})
}
async fn get_rate_limit_status(
&self,
supports_luna_reserve: bool,
) -> Result<RateLimitStatusWithResetCredits> {
let url = self.rate_limit_status_url();
let mut req = self
.request(Method::GET, &url)
.headers(self.headers().await?);
if supports_luna_reserve {
req = req.header("x-openai-codex-luna-reserve", HeaderValue::from_static("1"));
}
let (body, ct) = self.exec_request(req, "GET", &url).await?;
self.decode_json(&url, &ct, &body)
}
pub async fn list_rate_limit_reset_credits(&self) -> Result<RateLimitResetCreditsDetails> {
let url = self.rate_limit_reset_credits_url();
let req = self
.request(Method::GET, &url)
.headers(self.headers().await?);
let (body, ct) = self.exec_request(req, "GET", &url).await?;
self.decode_json(&url, &ct, &body)
}
pub async fn consume_rate_limit_reset_credit(
&self,
redeem_request_id: &str,
) -> Result<ConsumeRateLimitResetCreditResponse> {
self.consume_rate_limit_reset_credit_request(redeem_request_id, /*credit_id*/ None)
.await
}
pub async fn consume_rate_limit_reset_credit_by_id(
&self,
redeem_request_id: &str,
credit_id: &str,
) -> Result<ConsumeRateLimitResetCreditResponse> {
self.consume_rate_limit_reset_credit_request(redeem_request_id, Some(credit_id))
.await
}
async fn consume_rate_limit_reset_credit_request(
&self,
redeem_request_id: &str,
credit_id: Option<&str>,
) -> Result<ConsumeRateLimitResetCreditResponse> {
let url = self.consume_rate_limit_reset_credit_url();
let req = self
.request(Method::POST, &url)
.headers(self.headers().await?)
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.json(&ConsumeRateLimitResetCreditRequest {
redeem_request_id,
credit_id,
});
let (body, ct) = self.exec_request(req, "POST", &url).await?;
self.decode_json(&url, &ct, &body)
}
fn rate_limit_status_url(&self) -> String {
match self.path_style {
PathStyle::CodexApi => format!("{}/api/codex/usage", self.base_url),
PathStyle::ChatGptApi => format!("{}/wham/usage", self.base_url),
}
}
fn rate_limit_reset_credits_url(&self) -> String {
match self.path_style {
PathStyle::CodexApi => {
format!("{}/api/codex/rate-limit-reset-credits", self.base_url)
}
PathStyle::ChatGptApi => {
format!("{}/wham/rate-limit-reset-credits", self.base_url)
}
}
}
fn consume_rate_limit_reset_credit_url(&self) -> String {
match self.path_style {
PathStyle::CodexApi => {
format!(
"{}/api/codex/rate-limit-reset-credits/consume",
self.base_url
)
}
PathStyle::ChatGptApi => {
format!("{}/wham/rate-limit-reset-credits/consume", self.base_url)
}
}
}
}
#[cfg(test)]
#[path = "rate_limit_resets_tests.rs"]
mod tests;

View File

@@ -0,0 +1,189 @@
//! Usage permission and earned-reset payloads, including compatibility with older backends.
use super::*;
use crate::types::ConsumeRateLimitResetCreditCode;
use crate::types::RateLimitResetCreditDetails;
use crate::types::RateLimitResetCreditsDetails;
use crate::types::RateLimitResetCreditsSummary;
use codex_model_provider::ClientAuth;
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test]
async fn ordinary_usage_permission_comes_from_backend_not_display_percent() {
for (allowed, used_percent) in [(Some(true), 100), (Some(false), 0), (None, 0)] {
let server = MockServer::start().await;
let rate_limit = allowed.map(|allowed| {
serde_json::json!({
"allowed": allowed, "limit_reached": !allowed,
"primary_window": {"used_percent": used_percent, "limit_window_seconds": 300,
"reset_after_seconds": 60, "reset_at": 2000000000}
})
});
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"plan_type": "plus", "rate_limit": rate_limit
})))
.expect(1)
.mount(&server)
.await;
let response = test_client(&server.uri(), PathStyle::CodexApi)
.get_rate_limits_with_reset_credits()
.await
.unwrap();
assert_eq!(response.ordinary_usage_allowed, allowed);
}
}
#[test]
fn rate_limit_reset_contract_uses_expected_paths_and_payloads() {
assert_eq!(
test_client("https://example.test", PathStyle::CodexApi).rate_limit_status_url(),
"https://example.test/api/codex/usage"
);
assert_eq!(
test_client("https://example.test", PathStyle::CodexApi).rate_limit_reset_credits_url(),
"https://example.test/api/codex/rate-limit-reset-credits"
);
assert_eq!(
test_client("https://example.test", PathStyle::CodexApi)
.consume_rate_limit_reset_credit_url(),
"https://example.test/api/codex/rate-limit-reset-credits/consume"
);
assert_eq!(
test_client("https://chatgpt.com/backend-api", PathStyle::ChatGptApi)
.rate_limit_status_url(),
"https://chatgpt.com/backend-api/wham/usage"
);
assert_eq!(
test_client("https://chatgpt.com/backend-api", PathStyle::ChatGptApi)
.rate_limit_reset_credits_url(),
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits"
);
assert_eq!(
test_client("https://chatgpt.com/backend-api", PathStyle::ChatGptApi)
.consume_rate_limit_reset_credit_url(),
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits/consume"
);
assert_eq!(
serde_json::to_value(ConsumeRateLimitResetCreditRequest {
redeem_request_id: "redeem-123",
credit_id: None,
})
.unwrap(),
serde_json::json!({ "redeem_request_id": "redeem-123" })
);
assert_eq!(
serde_json::to_value(ConsumeRateLimitResetCreditRequest {
redeem_request_id: "redeem-456",
credit_id: Some("credit-123"),
})
.unwrap(),
serde_json::json!({
"redeem_request_id": "redeem-456",
"credit_id": "credit-123",
})
);
let status: RateLimitStatusWithResetCredits = serde_json::from_value(serde_json::json!({
"plan_type": "plus",
"rate_limit_reset_credits": { "available_count": 3 }
}))
.unwrap();
assert_eq!(
status.rate_limit_reset_credits,
Some(RateLimitResetCreditsSummary { available_count: 3 })
);
let details: RateLimitResetCreditsDetails = serde_json::from_value(serde_json::json!({
"credits": [
{
"id": "credit-1",
"reset_type": "codex_rate_limits",
"status": "available",
"granted_at": "2026-06-17T00:00:00Z",
"expires_at": "2026-07-17T00:00:00Z",
"redeem_started_at": null,
"redeemed_at": null,
"profile_image_url": "https://example.test/avatar.png",
"profile_user_id": "@friend",
"title": "Full reset (Weekly + 5 hr)",
"description": "Ready to redeem"
},
{
"id": "credit-2",
"reset_type": "codex_rate_limits",
"status": "available",
"granted_at": "2026-06-18T00:00:00Z",
"expires_at": null
}
],
"available_count": 2,
"total_earned_count": 4
}))
.unwrap();
assert_eq!(
details,
RateLimitResetCreditsDetails {
credits: vec![
RateLimitResetCreditDetails {
id: "credit-1".to_string(),
reset_type: "codex_rate_limits".to_string(),
status: "available".to_string(),
granted_at: "2026-06-17T00:00:00Z".to_string(),
expires_at: Some("2026-07-17T00:00:00Z".to_string()),
title: Some("Full reset (Weekly + 5 hr)".to_string()),
description: Some("Ready to redeem".to_string()),
},
RateLimitResetCreditDetails {
id: "credit-2".to_string(),
reset_type: "codex_rate_limits".to_string(),
status: "available".to_string(),
granted_at: "2026-06-18T00:00:00Z".to_string(),
expires_at: None,
title: None,
description: None,
},
],
available_count: 2,
}
);
let response: ConsumeRateLimitResetCreditResponse = serde_json::from_value(serde_json::json!({
"code": "reset",
"credit": { "id": "ignored-by-cli" },
"windows_reset": 2
}))
.unwrap();
assert_eq!(
response,
ConsumeRateLimitResetCreditResponse {
code: ConsumeRateLimitResetCreditCode::Reset,
windows_reset: 2,
}
);
}
fn test_client(base_url: &str, path_style: PathStyle) -> Client {
Client {
base_url: base_url.to_string(),
http: codex_http_client::RouteAwareClientPool::new(
codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
codex_http_client::ClientRouteClass::Api,
),
auth: ClientAuth::new(codex_model_provider::unauthenticated_auth_provider()),
user_agent: None,
chatgpt_account_id: None,
chatgpt_account_is_fedramp: false,
path_style,
config_server_base_url: None,
}
}

View File

@@ -0,0 +1,673 @@
//! Verify the backend client resolves a fresh runtime proof for each HTTP request.
use super::*;
use codex_features::RuntimeAuthMode;
use codex_http_client::DestinationPolicy;
use codex_http_client::NetworkPolicyController;
use codex_http_client::NetworkPolicyDenied;
use codex_http_client::OutboundProxyPolicy;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::AuthManager;
use codex_login::AuthRouteConfig;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
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 std::sync::Arc;
use uuid::Uuid;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn runtime_provider(
server: &MockServer,
credentials: Arc<AuthManager>,
mode: RuntimeAuthMode,
) -> (Arc<RuntimeAuthManager>, RuntimeAuthMode) {
(
Arc::new(RuntimeAuthManager::new(
credentials,
AgentHostAuthorization::InstallationId {
installation_id: Uuid::nil(),
},
RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/register", server.uri()).parse().unwrap(),
)),
mode,
)
}
#[tokio::test]
async fn account_runtime_auth_signs_each_request_and_strips_credentials_on_redirect() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let destination = MockServer::start().await;
Mock::given(path("/register"))
.respond_with(|request: &wiremock::Request| {
let body: serde_json::Value = request.body_json().unwrap();
let organization = body["actor_auth"]["organization_id"].as_str().unwrap_or("org-a");
ResponseTemplate::new(200).set_body_json(serde_json::json!({
"runtime_agent_instance_id": format!("runtime-{organization}"), "agent_host_id": "host-a",
"actor": {"kind": "platform", "user_id": "user-a", "organization_id": organization, "project_id": null},
}))
})
.expect(2).mount(&server).await;
Mock::given(method("GET"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(serde_json::json!({"accounts": [], "account_ordering": []})),
)
.expect(2)
.mount(&destination)
.await;
Mock::given(path("/turn-costs"))
.respond_with(
ResponseTemplate::new(200).set_body_json(serde_json::json!({"turns": []})),
)
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(307).insert_header("location", destination.uri()))
.expect(2)
.mount(&server)
.await;
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
let auth = CodexAuth::from_api_key("key-a");
let runtime = runtime_provider(
&server,
AuthManager::from_auth_for_testing(auth.clone()),
mode,
);
let client = Client::from_auth_with_selected_runtime(
server.uri(),
&auth,
factory,
Some(&runtime),
&HeaderMap::new(),
Client::new,
)
.await
.unwrap();
client.get_accounts_check().await.unwrap();
client.get_accounts_check().await.unwrap();
assert!(
client
.clone()
.with_chatgpt_account_id("different-workspace")
.get_accounts_check()
.await
.is_err()
);
let stale_headers = HeaderMap::from_iter([
(
HeaderName::from_static("openai-organization"),
HeaderValue::from_static("org-b"),
),
(
http::header::AUTHORIZATION,
HeaderValue::from_static("Bearer stale"),
),
(
HeaderName::from_static("x-openai-agent-assertion"),
HeaderValue::from_static("stale"),
),
]);
client
.query_api_key_turn_costs_at(
&format!("{}/turn-costs", server.uri()),
&[],
&stale_headers,
)
.await
.unwrap();
assert!(
client
.query_api_key_turn_costs_at(&destination.uri(), &[], &stale_headers)
.await
.is_err()
);
let redirected = destination.received_requests().await.unwrap();
assert_eq!(redirected.len(), 2);
for request in redirected {
assert!(!request.headers.contains_key("authorization"));
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
}
let requests = server.received_requests().await.unwrap();
let cost_request = requests
.iter()
.find(|request| request.url.path() == "/turn-costs")
.unwrap();
assert_eq!(cost_request.headers["openai-organization"], "org-b");
let proofs: Vec<_> = requests
.iter()
.filter(|r| r.url.path() != "/register")
.map(|request| {
let authorization = request.headers["authorization"].to_str().unwrap();
match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(authorization, "Bearer key-a");
request.headers["x-openai-agent-assertion"]
.to_str()
.unwrap()
}
RuntimeAuthMode::AssertionOnly => {
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
authorization.strip_prefix("AgentAssertion ").unwrap()
}
}
})
.collect();
assert_eq!(proofs.len(), 3);
assert_ne!(proofs[0], proofs[1]);
assert_ne!(proofs[1], proofs[2]);
assert_ne!(proofs[2], "stale");
}
}
#[tokio::test]
async fn client_registers_in_requested_organization_when_default_is_denied() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/register"))
.respond_with(|request: &wiremock::Request| {
let body: serde_json::Value = request.body_json().unwrap();
if body["actor_auth"]["organization_id"] != "org-b" {
return ResponseTemplate::new(403);
}
ResponseTemplate::new(200).set_body_json(serde_json::json!({
"runtime_agent_instance_id": "runtime-org-b",
"agent_host_id": "host-a",
"actor": {
"kind": "platform",
"user_id": "user-a",
"organization_id": "org-b",
"project_id": null,
},
}))
})
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/turn-costs"))
.respond_with(
ResponseTemplate::new(200).set_body_json(serde_json::json!({"turns": []})),
)
.expect(1)
.mount(&server)
.await;
let auth = CodexAuth::from_api_key("key-a");
let runtime = runtime_provider(
&server,
AuthManager::from_auth_for_testing(auth.clone()),
mode,
);
let headers = HeaderMap::from_iter([(
HeaderName::from_static("openai-organization"),
HeaderValue::from_static("org-b"),
)]);
for name in ["openai-organization", "openai-project"] {
let mut invalid_headers = headers.clone();
invalid_headers.insert(
HeaderName::from_static(name),
HeaderValue::from_bytes(b"\xff")
.expect("non-ASCII selector is a valid header value"),
);
assert!(
Client::from_auth_with_selected_runtime(
server.uri(),
&auth,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
Some(&runtime),
&invalid_headers,
Client::new,
)
.await
.is_err(),
"invalid selectors must not fall back to the default resource"
);
}
let client = Client::from_auth_with_selected_runtime(
server.uri(),
&auth,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
Some(&runtime),
&headers,
Client::new,
)
.await
.unwrap();
client
.query_api_key_turn_costs_at(&format!("{}/turn-costs", server.uri()), &[], &headers)
.await
.unwrap();
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 2);
assert_eq!(requests[1].url.path(), "/turn-costs");
assert_eq!(requests[1].headers["openai-organization"], "org-b");
let authorization = requests[1].headers["authorization"].to_str().unwrap();
match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(authorization, "Bearer key-a");
assert!(requests[1].headers.contains_key("x-openai-agent-assertion"));
}
RuntimeAuthMode::AssertionOnly => {
assert!(authorization.starts_with("AgentAssertion "));
assert!(!requests[1].headers.contains_key("x-openai-agent-assertion"));
}
}
server.verify().await;
}
}
#[tokio::test]
async fn authenticated_clients_without_redirects_return_the_redirect_response() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let destination = MockServer::start().await;
Mock::given(path("/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"runtime_agent_instance_id": "runtime-a", "agent_host_id": "host-a",
"actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-a", "project_id": null},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(307).insert_header("location", destination.uri()))
.expect(2)
.mount(&server)
.await;
let auth = CodexAuth::from_api_key("key-a");
let runtime = runtime_provider(
&server,
AuthManager::from_auth_for_testing(auth.clone()),
mode,
);
let custom_backend = Client::from_auth_with_runtime_without_redirects(
server.uri(),
&auth,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
Some(&runtime),
&HeaderMap::new(),
)
.await
.unwrap();
assert_eq!(
custom_backend
.get_accounts_check()
.await
.unwrap_err()
.status(),
Some(StatusCode::TEMPORARY_REDIRECT),
);
let client = Client::from_auth_with_selected_runtime(
server.uri(),
&auth,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
Some(&runtime),
&HeaderMap::new(),
Client::new_without_redirects,
)
.await
.unwrap();
let error = client.get_accounts_check().await.unwrap_err();
assert_eq!(error.status(), Some(StatusCode::TEMPORARY_REDIRECT));
assert!(destination.received_requests().await.unwrap().is_empty());
let requests = server.received_requests().await.unwrap();
let requests: Vec<_> = requests
.iter()
.filter(|request| request.method == Method::GET)
.collect();
assert_eq!(requests.len(), 2);
assert_eq!(requests[0].headers["authorization"], "Bearer key-a");
assert!(!requests[0].headers.contains_key("x-openai-agent-assertion"));
let request = requests[1];
let authorization = request.headers["authorization"].to_str().unwrap();
match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(authorization, "Bearer key-a");
assert!(request.headers.contains_key("x-openai-agent-assertion"));
}
RuntimeAuthMode::AssertionOnly => {
assert!(authorization.starts_with("AgentAssertion "));
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
}
}
server.verify().await;
}
}
#[tokio::test]
async fn unsupported_openai_backend_rejects_runtime_auth_before_registration() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let auth = CodexAuth::from_api_key("key-a");
let runtime = runtime_provider(
&server,
AuthManager::from_auth_for_testing(auth.clone()),
mode,
);
let result = Client::from_auth_with_runtime(
"https://future.openai.com/backend-api",
&auth,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
Some(&runtime),
&HeaderMap::new(),
)
.await;
let Err(error) = result else {
panic!("unsupported OpenAI backend accepted runtime auth");
};
assert!(matches!(
error.downcast_ref::<CodexErr>().map(CodexErr::details),
Some(CodexErrorDetails::UnsupportedOperation(_))
));
assert!(server.received_requests().await.unwrap().is_empty());
}
}
#[tokio::test]
async fn custom_backend_keeps_its_credential_without_registering_a_runtime() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
Mock::given(path("/turn-costs"))
.respond_with(
ResponseTemplate::new(200).set_body_json(serde_json::json!({"turns": []})),
)
.expect(1)
.mount(&server)
.await;
let auth = CodexAuth::from_api_key("custom-backend-key");
let runtime = runtime_provider(
&server,
AuthManager::from_auth_for_testing(auth.clone()),
mode,
);
let client = Client::from_auth_with_runtime(
server.uri(),
&auth,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
Some(&runtime),
&HeaderMap::new(),
)
.await
.unwrap();
client
.query_api_key_turn_costs_at(
&format!("{}/turn-costs", server.uri()),
&[],
&HeaderMap::new(),
)
.await
.unwrap();
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 1);
assert_eq!(
requests[0].headers["authorization"],
"Bearer custom-backend-key"
);
assert!(!requests[0].headers.contains_key("x-openai-agent-assertion"));
server.verify().await;
}
}
#[tokio::test]
async fn reusable_runtime_client_keeps_the_selected_accounts_transport_policy() {
let server = MockServer::start().await;
Mock::given(path("/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"runtime_agent_instance_id": "runtime-policy", "agent_host_id": "host-a",
"actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-a", "project_id": null},
})))
.expect(1).mount(&server).await;
Mock::given(path("/turn-costs"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"turns": []})))
.expect(2)
.mount(&server)
.await;
let controller = NetworkPolicyController::default();
let policy = controller.policy();
let home = tempfile::tempdir().unwrap();
codex_login::login_with_api_key(
home.path(),
"key-a",
AuthCredentialsStoreMode::Ephemeral,
AuthKeyringBackendKind::Direct,
)
.unwrap();
let credentials = Arc::new(
AuthManager::new(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::Ephemeral,
/*forced_chatgpt_workspace_id*/ None,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::Direct,
AuthRouteConfig::from_http_client_factory(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy.clone()),
),
)
.await,
);
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
let auth = credentials.auth().await.unwrap();
let runtime = runtime_provider(&server, credentials, RuntimeAuthMode::AssertionOnly);
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
let client = Client::from_auth_with_selected_runtime(
server.uri(),
&auth,
factory.clone(),
Some(&runtime),
&HeaderMap::new(),
Client::new,
)
.await
.unwrap();
let url = format!("{}/turn-costs", server.uri());
client
.query_api_key_turn_costs_at(&url, &[], &HeaderMap::new())
.await
.unwrap();
policy.invalidate();
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
let error = client
.query_api_key_turn_costs_at(&url, &[], &HeaderMap::new())
.await
.unwrap_err();
assert!(matches!(
error,
RequestError::Policy(NetworkPolicyDenied::Revoked)
));
let fresh = Client::from_auth_with_selected_runtime(
server.uri(),
&auth,
factory,
Some(&runtime),
&HeaderMap::new(),
Client::new,
)
.await
.unwrap();
fresh
.query_api_key_turn_costs_at(&url, &[], &HeaderMap::new())
.await
.unwrap();
policy.invalidate();
assert!(controller.publish(
policy.revision(),
DestinationPolicy::Restricted {
allowed_hosts: Default::default()
}
));
let selectors = HeaderMap::from_iter([(
HeaderName::from_static("openai-organization"),
HeaderValue::from_static("org-b"),
)]);
let error = fresh
.query_api_key_turn_costs_at(&url, &[], &selectors)
.await
.unwrap_err();
assert!(
matches!(
error,
RequestError::Policy(NetworkPolicyDenied::Destination)
),
"{error}"
);
server.verify().await;
}
struct RotatingAuth(std::sync::RwLock<CodexAuth>);
impl codex_login::ExternalAuth for RotatingAuth {
fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
Box::pin(async { Ok(self.0.read().unwrap().clone()) })
}
fn refresh(
&self,
_: codex_login::ExternalAuthRefreshContext,
) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
self.resolve()
}
}
#[tokio::test]
async fn reusable_runtime_client_refreshes_credentials_without_accepting_a_new_session() {
use base64::Engine;
let oauth = |session, token| {
let claims = serde_json::json!({
"iss": "https://auth.openai.com/", "session_id": session, "jti": token,
"https://api.openai.com/auth": {
"user_id": "user-a", "chatgpt_account_id": "workspace-a"
}
});
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string());
CodexAuth::from_external_chatgpt_tokens(
&format!("header.{payload}.signature"),
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap()
};
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
Mock::given(path("/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"runtime_agent_instance_id": "runtime-refresh", "agent_host_id": "host-a",
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "workspace-a"}
})))
.mount(&server)
.await;
Mock::given(path("/api/codex/usage"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"plan_type": "plus",
"rate_limit": {
"allowed": true, "limit_reached": false,
"primary_window": {
"used_percent": 0, "limit_window_seconds": 300,
"reset_after_seconds": 60, "reset_at": 2000000000
}
}
})))
.expect(2)
.mount(&server)
.await;
let initial = oauth("login-a", "initial");
let refreshed = oauth("login-a", "refreshed");
let credentials = AuthManager::from_auth_for_testing(initial.clone());
let source = Arc::new(RotatingAuth(std::sync::RwLock::new(initial.clone())));
credentials.set_external_auth(source.clone()).await.unwrap();
let runtime = runtime_provider(&server, credentials, mode);
let client = Client::from_auth_with_selected_runtime(
server.uri(),
&initial,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
Some(&runtime),
&HeaderMap::new(),
Client::new,
)
.await
.unwrap();
assert!(
client
.clone()
.with_bearer_token("replacement-bearer".into())
.is_err()
);
assert!(
client
.clone()
.with_auth_provider(Arc::new(codex_model_provider::BearerAuthProvider::new(
"replacement-provider".to_string(),
)))
.is_err()
);
client.get_rate_limits().await.unwrap();
*source.0.write().unwrap() = refreshed.clone();
client.get_rate_limits().await.unwrap();
let requests = server.received_requests().await.unwrap();
assert_eq!(
requests
.iter()
.filter(|r| r.url.path() == "/register")
.count(),
1
);
let requests: Vec<_> = requests
.iter()
.filter(|r| r.url.path() == "/api/codex/usage")
.collect();
assert_eq!(requests.len(), 2);
let mut proofs = Vec::new();
for (request, expected) in requests.iter().zip([initial, refreshed]) {
let authorization = request.headers["authorization"].to_str().unwrap();
let proof = match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(
authorization,
format!("Bearer {}", expected.get_token().unwrap())
);
request.headers["x-openai-agent-assertion"]
.to_str()
.unwrap()
}
RuntimeAuthMode::AssertionOnly => {
authorization.strip_prefix("AgentAssertion ").unwrap()
}
};
let claims: serde_json::Value = serde_json::from_slice(
&base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(proof.split('.').nth(2).unwrap())
.unwrap(),
)
.unwrap();
assert_eq!(claims["runtime_agent_instance"], "runtime-refresh");
proofs.push(proof);
}
assert_ne!(proofs[0], proofs[1]);
*source.0.write().unwrap() = oauth("another-login", "replacement");
assert!(client.get_rate_limits().await.is_err());
}
}

View File

@@ -0,0 +1,229 @@
//! Consumer task accounting: current allowance percentages and actual balance debits.
//! This contract is deliberately separate from enterprise estimated lifetime credits.
use super::Client;
use super::PathStyle;
use super::RequestError;
use http::Method;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashSet;
#[derive(Clone, Debug, Serialize)]
pub struct TaskUsageThread {
pub thread_id: String,
pub created_at: Option<String>,
pub descendant_thread_ids: Vec<String>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct TaskUsageResponse {
pub data_as_of: Option<String>,
pub threads: Vec<TaskUsage>,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TaskUsageStatus {
Available,
Partial,
Unavailable,
}
#[derive(Clone, Debug, Deserialize)]
pub struct TaskUsage {
pub thread_id: String,
pub data_status: TaskUsageStatus,
pub usage_source: String,
#[serde(flatten)]
pub amounts: TaskUsageAmounts,
pub groups: Vec<TaskUsageGroup>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct TaskUsageAmounts {
#[serde(default, deserialize_with = "percentage")]
pub five_hour_limit_percent: Option<f64>,
#[serde(default, deserialize_with = "percentage")]
pub weekly_limit_percent: Option<f64>,
pub balance_usage_credits: Option<TaskCredits>,
}
// Flattened Serde fields buffer arbitrary-precision JSON numbers as maps.
// Decode through Number so decimal percentages work with either serde_json configuration.
fn percentage<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<f64>, D::Error> {
Option::<serde_json::Number>::deserialize(deserializer)?
.map(|value| {
value
.as_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| serde::de::Error::custom("Invalid task percentage."))
})
.transpose()
}
#[derive(Clone, Debug, Deserialize)]
pub struct TaskUsageGroup {
pub product_experience: Option<String>,
pub model: Option<String>,
pub reasoning_effort: Option<String>,
pub speed: Option<String>,
#[serde(flatten)]
pub amounts: TaskUsageAmounts,
}
impl Client {
/// Queries disjoint tasks, including legacy descendants, without selecting a comparison plan.
pub async fn get_task_usage(
&self,
threads: &[TaskUsageThread],
) -> Result<TaskUsageResponse, RequestError> {
let mut ids = HashSet::new();
if threads.is_empty()
|| threads.len() > 100
|| threads.iter().any(|thread| {
std::iter::once(&thread.thread_id)
.chain(&thread.descendant_thread_ids)
.any(|id| id.trim().is_empty() || id.len() > 512 || !ids.insert(id.as_str()))
})
|| ids.len() > 1_000
{
return Err(RequestError::Other(anyhow::anyhow!(
"Expected at most 100 disjoint tasks and 1,000 thread IDs."
)));
}
let prefix = match self.path_style {
PathStyle::CodexApi => "api/codex",
PathStyle::ChatGptApi => "wham",
};
let url = format!("{}/{prefix}/usage/thread_usage/query_v2", self.base_url);
#[derive(Serialize)]
struct Query<'a> {
threads: &'a [TaskUsageThread],
}
let request = self
.request(Method::POST, &url)
.headers(self.headers().await?)
.json(&Query { threads });
let (body, _) = self.exec_request_detailed(request, "POST", &url).await?;
let response: TaskUsageResponse = serde_json::from_str(&body)
.map_err(|_| RequestError::Other(anyhow::anyhow!("Invalid task usage response.")))?;
let roots: HashSet<_> = threads
.iter()
.map(|thread| thread.thread_id.as_str())
.collect();
let mut seen = HashSet::new();
if response.threads.iter().any(|thread| {
!roots.contains(thread.thread_id.as_str())
|| !seen.insert(&thread.thread_id)
|| std::iter::once(&thread.amounts)
.chain(thread.groups.iter().map(|group| &group.amounts))
.any(|amounts| {
[
amounts.five_hour_limit_percent,
amounts.weekly_limit_percent,
]
.into_iter()
.flatten()
.any(|value| !value.is_finite())
})
}) {
return Err(RequestError::Other(anyhow::anyhow!(
"Invalid task usage response."
)));
}
Ok(response)
}
}
/// Decimal strings retain all backend digits for both rendering and sorting.
#[derive(Clone, Debug, Eq)]
pub struct TaskCredits(String);
impl TaskCredits {
pub fn as_str(&self) -> &str {
&self.0
}
fn parts(&self) -> (bool, i64, String) {
let (mantissa, exponent) = self.0.split_once(['e', 'E']).unwrap_or((&self.0, "0"));
let negative = mantissa.starts_with('-');
let unsigned = mantissa.trim_start_matches(['-', '+']);
let fraction = unsigned
.split_once('.')
.map_or(/*default*/ 0, |(_, fraction)| fraction.len());
let digits = unsigned.replace('.', "");
let digits = digits.trim_start_matches('0');
let power =
exponent.parse::<i64>().unwrap_or_default() - fraction as i64 + digits.len() as i64;
(negative && !digits.is_empty(), power, digits.to_string())
}
}
impl<'de> Deserialize<'de> for TaskCredits {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = String::deserialize(deserializer)?;
let mantissa = value
.split(['e', 'E'])
.next()
.unwrap_or_default()
.trim_start_matches(['-', '+']);
let exponent = value
.split_once(['e', 'E'])
.map_or("0", |(_, exponent)| exponent);
if value.len() > 128
|| mantissa.is_empty()
|| !mantissa.chars().any(|ch| ch.is_ascii_digit())
|| !mantissa.chars().all(|ch| ch.is_ascii_digit() || ch == '.')
|| value.parse::<f64>().is_err()
|| exponent.parse::<i32>().is_err()
{
return Err(serde::de::Error::custom("Invalid decimal credits."));
}
Ok(Self(value))
}
}
impl Ord for TaskCredits {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
let (negative, power, digits) = self.parts();
let (other_negative, other_power, other_digits) = other.parts();
let magnitude = match (digits.is_empty(), other_digits.is_empty()) {
(true, true) => std::cmp::Ordering::Equal,
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
(false, false) => power.cmp(&other_power).then_with(|| {
let width = digits.len().max(other_digits.len());
digits
.bytes()
.chain(std::iter::repeat(b'0'))
.take(width)
.cmp(
other_digits
.bytes()
.chain(std::iter::repeat(b'0'))
.take(width),
)
}),
};
other_negative.cmp(&negative).then(if negative {
magnitude.reverse()
} else {
magnitude
})
}
}
impl PartialOrd for TaskCredits {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for TaskCredits {
fn eq(&self, other: &Self) -> bool {
self.cmp(other).is_eq()
}
}
#[cfg(test)]
#[path = "task_usage_tests.rs"]
mod tests;

View File

@@ -0,0 +1,132 @@
//! Exact decimal preservation and sorting for consumer task credits.
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn credits_preserve_precision_and_order_signed_decimal_strings() {
let mut amounts: Vec<TaskCredits> = serde_json::from_value(json!([
"1.000000000000000002",
"-0.00025",
"0",
"1.000000000000000001",
"1e-20",
"-1E+3"
]))
.unwrap();
amounts.sort();
assert_eq!(
amounts.iter().map(TaskCredits::as_str).collect::<Vec<_>>(),
vec![
"-1E+3",
"-0.00025",
"0",
"1e-20",
"1.000000000000000001",
"1.000000000000000002"
]
);
for invalid in ["NaN", "inf", "1..0", "", "1e999999999999"] {
assert!(serde_json::from_value::<TaskCredits>(json!(invalid)).is_err());
}
}
#[tokio::test]
async fn task_queries_validate_request_groups_and_response_ownership() {
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
let server = MockServer::start().await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let query = TaskUsageThread {
thread_id: "root".into(),
created_at: None,
descendant_thread_ids: vec!["child".into()],
};
let task = json!({"thread_id":"root", "data_status":"available", "usage_source":"plan_and_credits",
"five_hour_limit_percent":150.0, "weekly_limit_percent":0.0,
"balance_usage_credits":"-0.000000000000000001", "groups":[{
"product_experience":"codex", "model":"gpt-5.5", "reasoning_effort":"high", "speed":"standard",
"five_hour_limit_percent":150.25, "weekly_limit_percent":0.125, "balance_usage_credits":"0"
}]});
for ids in [vec!["root"], vec!["other"], vec!["root", "root"]] {
server.reset().await;
let response = json!({"data_as_of":null, "threads":ids.iter().map(|id| {
let mut task=task.clone();task["thread_id"]=json!(id);task
}).collect::<Vec<_>>()});
Mock::given(method("POST"))
.and(path("/api/codex/usage/thread_usage/query_v2"))
.respond_with(move |request: &wiremock::Request| {
assert_eq!(
request.body_json::<serde_json::Value>().unwrap(),
json!({"threads":[{
"thread_id":"root", "created_at":null, "descendant_thread_ids":["child"]
}]})
);
ResponseTemplate::new(/*s*/ 200).set_body_json(&response)
})
.expect(/*r*/ 1)
.mount(&server)
.await;
let result = client.get_task_usage(std::slice::from_ref(&query)).await;
if ids == ["root"] {
let response = result.unwrap();
assert_eq!((response.data_as_of, response.threads.len()), (None, 1));
let row = &response.threads[0];
assert_eq!(
(
row.thread_id.as_str(),
row.data_status,
row.amounts.five_hour_limit_percent,
row.amounts.weekly_limit_percent,
row.amounts
.balance_usage_credits
.as_ref()
.map(TaskCredits::as_str)
),
(
"root",
TaskUsageStatus::Available,
Some(150.0),
Some(0.0),
Some("-0.000000000000000001")
)
);
assert_eq!(
(
row.groups[0].amounts.five_hour_limit_percent,
row.groups[0].amounts.weekly_limit_percent
),
(Some(150.25), Some(0.125))
);
} else {
assert!(
result
.unwrap_err()
.to_string()
.contains("Invalid task usage response.")
);
}
}
server.reset().await;
for queries in [
vec![],
vec![query.clone(), query.clone()],
vec![TaskUsageThread {
thread_id: "root".into(),
created_at: None,
descendant_thread_ids: (0..1_000).map(|n| format!("child-{n}")).collect(),
}],
] {
assert!(client.get_task_usage(&queries).await.is_err());
}
assert!(server.received_requests().await.unwrap().is_empty());
}

View File

@@ -0,0 +1,130 @@
//! Backend credit estimates and native-dollar usage for bounded batches of Codex threads.
use super::Client;
use super::PathStyle;
use super::RequestError;
use anyhow::anyhow;
use http::Method;
use http::header::CONTENT_TYPE;
use http::header::HeaderValue;
use serde::Deserialize;
use serde::Serialize;
/// Backend usage grouped by model, reasoning effort, and response speed.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct ThreadUsageBreakdownGroup {
pub model: Option<String>,
pub reasoning_effort: Option<String>,
pub speed: Option<String>,
pub estimated_usage_credits_micros: i64,
pub native_usage_usd_micros: Option<i64>,
pub net_new_input_tokens: Option<i64>,
pub cached_input_tokens: Option<i64>,
pub input_tokens: Option<i64>,
pub output_tokens: Option<i64>,
pub total_tokens: Option<i64>,
}
/// Backend usage totals expressed in integer millionths of their respective units.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct ThreadUsage {
pub thread_id: String,
pub estimated_usage_credits_micros: i64,
pub estimated_usage_usd_micros: Option<i64>,
pub native_usage_usd_micros: Option<i64>,
#[serde(default)]
pub groups: Vec<ThreadUsageBreakdownGroup>,
}
#[derive(Serialize)]
struct ThreadUsageQueryRequest<'a> {
thread_ids: &'a [&'a str],
}
#[derive(Deserialize)]
struct ThreadUsageQueryResponse {
threads: Vec<ThreadUsageEstimate>,
}
// Preserve unavailable rows until all returned IDs have been validated.
#[derive(Deserialize)]
struct ThreadUsageEstimate {
thread_id: String,
estimated_usage_credits_micros: Option<i64>,
estimated_usage_usd_micros: Option<i64>,
native_usage_usd_micros: Option<i64>,
groups: Option<Vec<ThreadUsageBreakdownGroup>>,
}
impl Client {
/// Reads authoritative estimated totals without maintaining a second usage ledger.
pub async fn get_thread_usage(&self, thread_id: &str) -> Result<ThreadUsage, RequestError> {
self.get_threads_usage(&[thread_id])
.await?
.into_iter()
.find(|usage| usage.thread_id == thread_id)
.ok_or_else(|| {
RequestError::from(anyhow!("thread usage response omitted requested thread"))
})
}
/// Reads at most 100 distinct threads; omitted results are unavailable, not zero.
pub async fn get_threads_usage(
&self,
thread_ids: &[&str],
) -> Result<Vec<ThreadUsage>, RequestError> {
let requested: std::collections::HashSet<_> = thread_ids.iter().copied().collect();
if thread_ids.is_empty() || thread_ids.len() > 100 || requested.len() != thread_ids.len() {
return Err(RequestError::from(anyhow!(
"expected 1–100 distinct thread IDs"
)));
}
let url = self.thread_usage_url();
let request = self
.request(Method::POST, &url)
.headers(self.headers().await?)
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.json(&ThreadUsageQueryRequest { thread_ids });
let (body, _) = self.exec_request_detailed(request, "POST", &url).await?;
let response: ThreadUsageQueryResponse = serde_json::from_str(&body)
.map_err(|_| RequestError::Other(anyhow!("Invalid thread usage response.")))?;
let mut seen = std::collections::HashSet::new();
if response
.threads
.iter()
.any(|row| !requested.contains(row.thread_id.as_str()) || !seen.insert(&row.thread_id))
{
return Err(RequestError::from(anyhow!(
"thread usage returned unexpected threads"
)));
}
Ok(response
.threads
.into_iter()
.filter_map(|row| {
Some(ThreadUsage {
thread_id: row.thread_id,
estimated_usage_credits_micros: row.estimated_usage_credits_micros?,
estimated_usage_usd_micros: row.estimated_usage_usd_micros,
native_usage_usd_micros: row.native_usage_usd_micros,
groups: row.groups.unwrap_or_default(),
})
})
.collect())
}
fn thread_usage_url(&self) -> String {
match self.path_style {
PathStyle::CodexApi => {
format!("{}/api/codex/usage/thread_usage/query", self.base_url)
}
PathStyle::ChatGptApi => {
format!("{}/wham/usage/thread_usage/query", self.base_url)
}
}
}
}
#[cfg(test)]
#[path = "thread_usage_tests.rs"]
mod tests;

View File

@@ -0,0 +1,363 @@
use super::*;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_json;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[test]
fn thread_usage_contract_uses_expected_paths_and_payload() {
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
assert_eq!(
Client::new("https://example.test", factory.clone()).thread_usage_url(),
"https://example.test/api/codex/usage/thread_usage/query"
);
assert_eq!(
Client::new("https://chatgpt.com/backend-api", factory).thread_usage_url(),
"https://chatgpt.com/backend-api/wham/usage/thread_usage/query"
);
assert_eq!(
serde_json::to_value(ThreadUsageQueryRequest {
thread_ids: &["thread-123"],
})
.expect("serialize thread usage request"),
json!({ "thread_ids": ["thread-123"] })
);
}
#[tokio::test]
async fn get_thread_usage_returns_requested_thread_totals() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/codex/usage/thread_usage/query"))
.and(body_json(json!({ "thread_ids": ["thread-123"] })))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"threads": [{
"thread_id": "thread-123",
"estimated_usage_credits_micros": 46_000_000,
"estimated_usage_usd_micros": 1_820_000,
"native_usage_usd_micros": 3_250_000,
"groups": [{
"model": "gpt-5.4",
"reasoning_effort": "high",
"speed": "fast",
"estimated_usage_credits_micros": 46_000_000,
"native_usage_usd_micros": 3_250_000,
"net_new_input_tokens": 80,
"cached_input_tokens": 20,
"input_tokens": 100,
"output_tokens": 40,
"total_tokens": 140
}]
}]
})))
.expect(/*r*/ 1)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
assert_eq!(
client
.get_thread_usage("thread-123")
.await
.expect("read thread usage"),
ThreadUsage {
thread_id: "thread-123".to_string(),
estimated_usage_credits_micros: 46_000_000,
estimated_usage_usd_micros: Some(1_820_000),
native_usage_usd_micros: Some(3_250_000),
groups: vec![ThreadUsageBreakdownGroup {
model: Some("gpt-5.4".to_string()),
reasoning_effort: Some("high".to_string()),
speed: Some("fast".to_string()),
estimated_usage_credits_micros: 46_000_000,
native_usage_usd_micros: Some(3_250_000),
net_new_input_tokens: Some(80),
cached_input_tokens: Some(20),
input_tokens: Some(100),
output_tokens: Some(40),
total_tokens: Some(140),
}],
}
);
}
#[tokio::test]
async fn get_thread_usage_accepts_credits_without_usd_estimate() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/codex/usage/thread_usage/query"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"threads": [{
"thread_id": "thread-123",
"estimated_usage_credits_micros": 46_000_000,
"estimated_usage_usd_micros": null
}]
})))
.expect(/*r*/ 1)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
assert_eq!(
client
.get_thread_usage("thread-123")
.await
.expect("read credits without a dollar estimate"),
ThreadUsage {
thread_id: "thread-123".to_string(),
estimated_usage_credits_micros: 46_000_000,
estimated_usage_usd_micros: None,
native_usage_usd_micros: None,
groups: Vec::new(),
}
);
}
#[tokio::test]
async fn get_thread_usage_rejects_totals_for_another_thread() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"threads": [{
"thread_id": "another-thread",
"estimated_usage_credits_micros": 1,
"estimated_usage_usd_micros": 1
}]
})))
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let error = client
.get_thread_usage("thread-123")
.await
.expect_err("reject usage for a different thread");
assert!(error.to_string().contains("unexpected threads"));
}
#[tokio::test]
async fn batch_usage_rejects_invalid_requests_before_http() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(/*s*/ 500))
.expect(/*r*/ 0)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let too_many = (0..101)
.map(|id| format!("thread-{id}"))
.collect::<Vec<_>>();
for ids in [
Vec::new(),
vec!["duplicate", "duplicate"],
too_many.iter().map(String::as_str).collect(),
] {
let error = client.get_threads_usage(&ids).await.unwrap_err();
assert!(error.to_string().contains("1–100 distinct thread IDs"));
}
}
#[tokio::test]
async fn batch_usage_rejects_duplicate_and_unrequested_response_rows() {
for returned in [["first", "first"], ["first", "unexpected"]] {
for second_amount in [Some(1), None] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(body_json(json!({"thread_ids": ["first", "second"]})))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"threads": returned.iter().enumerate().map(|(index, thread_id)| json!({
"thread_id": thread_id,
"estimated_usage_credits_micros": if index == 0 { Some(1) } else { second_amount }
})).collect::<Vec<_>>()
})))
.expect(/*r*/ 1)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let error = client
.get_threads_usage(&["first", "second"])
.await
.unwrap_err();
assert!(error.to_string().contains("unexpected threads"));
}
}
}
#[test]
fn thread_usage_preserves_unknown_and_zero_native_group_amounts() {
let usage: ThreadUsage = serde_json::from_value(json!({
"thread_id": "thread-123",
"estimated_usage_credits_micros": 0,
"native_usage_usd_micros": null,
"groups": [
{ "model": "legacy", "estimated_usage_credits_micros": 0 },
{
"model": "unknown",
"estimated_usage_credits_micros": 0,
"native_usage_usd_micros": null
},
{
"model": "zero",
"estimated_usage_credits_micros": 0,
"native_usage_usd_micros": 0
}
]
}))
.expect("decode native groups from legacy and current backend responses");
assert_eq!(
usage,
ThreadUsage {
thread_id: "thread-123".to_string(),
estimated_usage_credits_micros: 0,
estimated_usage_usd_micros: None,
native_usage_usd_micros: None,
groups: [("legacy", None), ("unknown", None), ("zero", Some(0))]
.into_iter()
.map(
|(model, native_usage_usd_micros)| ThreadUsageBreakdownGroup {
model: Some(model.to_string()),
reasoning_effort: None,
speed: None,
estimated_usage_credits_micros: 0,
native_usage_usd_micros,
net_new_input_tokens: None,
cached_input_tokens: None,
input_tokens: None,
output_tokens: None,
total_tokens: None,
}
)
.collect(),
}
);
}
#[tokio::test]
async fn get_threads_usage_preserves_native_amounts_and_absence() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/codex/usage/thread_usage/query"))
.and(body_json(json!({ "thread_ids": ["priced", "unknown"] })))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"threads": [
{
"thread_id": "priced",
"estimated_usage_credits_micros": 46_000_000,
"estimated_usage_usd_micros": 2_505_000,
"native_usage_usd_micros": 3_250_000,
"groups": [
{
"model": "test-model-a",
"reasoning_effort": "medium",
"speed": "standard",
"estimated_usage_credits_micros": 12_000_000,
"native_usage_usd_micros": 750_000
},
{
"model": "test-model-b",
"reasoning_effort": "high",
"speed": "fast",
"estimated_usage_credits_micros": 34_000_000,
"native_usage_usd_micros": 2_500_000
}
]
},
{
"thread_id": "unknown",
"estimated_usage_credits_micros": 7_000_000,
"groups": [{
"model": "legacy-model",
"estimated_usage_credits_micros": 7_000_000
}]
}
]
})))
.expect(/*r*/ 1)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
assert_eq!(
client
.get_threads_usage(&["priced", "unknown"])
.await
.expect("read native and legacy usage in one batch"),
vec![
ThreadUsage {
thread_id: "priced".to_string(),
estimated_usage_credits_micros: 46_000_000,
estimated_usage_usd_micros: Some(2_505_000),
native_usage_usd_micros: Some(3_250_000),
groups: vec![
ThreadUsageBreakdownGroup {
model: Some("test-model-a".to_string()),
reasoning_effort: Some("medium".to_string()),
speed: Some("standard".to_string()),
estimated_usage_credits_micros: 12_000_000,
native_usage_usd_micros: Some(750_000),
net_new_input_tokens: None,
cached_input_tokens: None,
input_tokens: None,
output_tokens: None,
total_tokens: None,
},
ThreadUsageBreakdownGroup {
model: Some("test-model-b".to_string()),
reasoning_effort: Some("high".to_string()),
speed: Some("fast".to_string()),
estimated_usage_credits_micros: 34_000_000,
native_usage_usd_micros: Some(2_500_000),
net_new_input_tokens: None,
cached_input_tokens: None,
input_tokens: None,
output_tokens: None,
total_tokens: None,
},
],
},
ThreadUsage {
thread_id: "unknown".to_string(),
estimated_usage_credits_micros: 7_000_000,
estimated_usage_usd_micros: None,
native_usage_usd_micros: None,
groups: vec![ThreadUsageBreakdownGroup {
model: Some("legacy-model".to_string()),
reasoning_effort: None,
speed: None,
estimated_usage_credits_micros: 7_000_000,
native_usage_usd_micros: None,
net_new_input_tokens: None,
cached_input_tokens: None,
input_tokens: None,
output_tokens: None,
total_tokens: None,
}],
},
]
);
}

View File

@@ -0,0 +1,247 @@
use super::Client;
use super::RequestError;
use codex_http_client::OPENAI_ORGANIZATION_HEADER;
use codex_http_client::OPENAI_PROJECT_HEADER;
use http::HeaderMap;
use http::Method;
use http::header::CONTENT_TYPE;
use http::header::HeaderValue;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ApiKeyTurnCostStatus {
Pending,
Priced,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ApiKeyResponseCost {
pub response_id: String,
pub total_usd: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ApiKeyTurnCost {
pub turn_id: String,
pub status: ApiKeyTurnCostStatus,
pub total_usd: Option<String>,
pub event_count: Option<u64>,
pub responses: Option<Vec<ApiKeyResponseCost>>,
pub model: Option<String>,
pub speed: Option<String>,
pub reasoning_effort: Option<String>,
}
#[derive(Serialize)]
struct ApiKeyTurnCostsRequest<'a> {
turn_ids: &'a [String],
}
#[derive(Deserialize)]
struct ApiKeyTurnCostsResponse {
turns: Vec<ApiKeyTurnCost>,
}
impl Client {
pub async fn query_api_key_turn_costs(
&self,
turn_ids: &[String],
provider_headers: &HeaderMap,
) -> Result<Vec<ApiKeyTurnCost>, RequestError> {
let mut url =
url::Url::parse(&self.base_url).map_err(|error| RequestError::Other(error.into()))?;
let analytics_host = match url.host_str() {
Some("chatgpt.com" | "chat.openai.com") => Some("api.chatgpt.com"),
Some("chatgpt-staging.com") => Some("api.chatgpt-staging.com"),
_ => None,
};
if let Some(host) = analytics_host {
url.set_host(Some(host))
.map_err(|error| RequestError::Other(error.into()))?;
}
url.set_path("/v1/analytics/codex/turn-costs");
url.set_query(None);
url.set_fragment(None);
let provider_scope_headers = provider_headers
.iter()
.filter(|(name, _)| {
[OPENAI_ORGANIZATION_HEADER, OPENAI_PROJECT_HEADER]
.iter()
.any(|allowed| name.as_str().eq_ignore_ascii_case(allowed))
})
.map(|(name, value)| (name.clone(), value.clone()))
.collect();
self.query_api_key_turn_costs_at(url.as_ref(), turn_ids, &provider_scope_headers)
.await
}
/// Queries an API-key turn-cost endpoint chosen by the caller, attaching
/// the supplied provider headers in addition to this client's auth.
pub async fn query_api_key_turn_costs_at(
&self,
url: &str,
turn_ids: &[String],
provider_headers: &HeaderMap,
) -> Result<Vec<ApiKeyTurnCost>, RequestError> {
let headers = self.headers_with(provider_headers.clone()).await?;
let request = self
.request(Method::POST, url)
.headers(headers)
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.json(&ApiKeyTurnCostsRequest { turn_ids });
let (body, content_type) = self.exec_request_detailed(request, "POST", url).await?;
let response: ApiKeyTurnCostsResponse = self
.decode_json(url, &content_type, &body)
.map_err(RequestError::Other)?;
Ok(response.turns)
}
}
#[cfg(test)]
mod tests {
use super::ApiKeyResponseCost;
use super::ApiKeyTurnCost;
use super::ApiKeyTurnCostStatus;
use super::Client;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_login::CodexAuth;
use http::HeaderMap;
use http::HeaderValue;
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_json;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test]
async fn api_key_turn_cost_queries_use_api_key_auth_and_provider_scope() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/analytics/codex/turn-costs"))
.and(header("authorization", "Bearer sk-test"))
.and(header("openai-organization", "org-test"))
.and(header("openai-project", "project-test"))
.and(body_json(serde_json::json!({
"turn_ids": ["turn-priced", "turn-response"]
})))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"turns": [
{
"turn_id": "turn-priced",
"status": "priced",
"total_usd": "1.2500000001",
"event_count": 2,
"model": "gpt-5.6",
"speed": "fast",
"reasoning_effort": "high"
},
{
"turn_id": "turn-response",
"status": "priced",
"total_usd": "0.5000000000",
"responses": [{
"response_id": "resp-one",
"total_usd": "0.5000000000"
}]
}
]
})))
.expect(1)
.mount(&server)
.await;
let auth = CodexAuth::from_api_key("sk-test");
let client = Client::from_auth(
format!("{}/backend-api", server.uri()),
&auth,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let mut provider_headers = HeaderMap::new();
provider_headers.insert("openai-organization", HeaderValue::from_static("org-test"));
provider_headers.insert("openai-project", HeaderValue::from_static("project-test"));
let costs = client
.query_api_key_turn_costs(
&["turn-priced".to_string(), "turn-response".to_string()],
&provider_headers,
)
.await
.expect("query API key turn costs");
assert_eq!(
costs,
vec![
ApiKeyTurnCost {
turn_id: "turn-priced".to_string(),
status: ApiKeyTurnCostStatus::Priced,
total_usd: Some("1.2500000001".to_string()),
event_count: Some(2),
responses: None,
model: Some("gpt-5.6".to_string()),
speed: Some("fast".to_string()),
reasoning_effort: Some("high".to_string()),
},
ApiKeyTurnCost {
turn_id: "turn-response".to_string(),
status: ApiKeyTurnCostStatus::Priced,
total_usd: Some("0.5000000000".to_string()),
event_count: None,
responses: Some(vec![ApiKeyResponseCost {
response_id: "resp-one".to_string(),
total_usd: "0.5000000000".to_string(),
}]),
model: None,
speed: None,
reasoning_effort: None,
},
]
);
}
#[tokio::test]
async fn custom_turn_cost_queries_apply_client_auth_after_provider_headers() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/analytics/codex/turn-costs"))
.and(header("authorization", "Bearer sk-test"))
.and(header("chatgpt-account-id", "account-test"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"turns": []
})))
.expect(1)
.mount(&server)
.await;
let auth = CodexAuth::from_api_key("sk-test");
let client = Client::from_auth(
server.uri(),
&auth,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.with_chatgpt_account_id("account-test");
let mut provider_headers = HeaderMap::new();
provider_headers.insert(
"authorization",
HeaderValue::from_static("Bearer provider-override"),
);
provider_headers.insert(
"chatgpt-account-id",
HeaderValue::from_static("provider-account-override"),
);
let costs = client
.query_api_key_turn_costs_at(
&format!("{}/analytics/codex/turn-costs", server.uri()),
&["turn-one".to_string()],
&provider_headers,
)
.await
.expect("query custom-provider turn costs");
assert_eq!(costs, Vec::new());
}
}

View File

@@ -0,0 +1,474 @@
use std::io::BufRead;
use std::io::Read;
use std::io::Write;
use std::net::TcpListener;
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
use base64::Engine;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_http_client::cache_system_proxy_route_for_test;
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
#[tokio::test]
async fn client_preserves_supplied_factory_and_typed_policy_denial() {
let controller = codex_http_client::NetworkPolicyController::default();
let client = Client::new(
"https://example.test",
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy)
.with_network_policy(controller.policy()),
);
assert_eq!(
client.http.outbound_proxy_policy(),
OutboundProxyPolicy::RespectSystemProxy
);
let denied = client.get_config_bundle().await;
assert!(matches!(denied, Err(RequestError::Policy(_))));
}
#[test]
fn list_tasks_url_omits_empty_query_and_encodes_all_parameters() {
let client = Client::new(
"https://example.test",
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
assert_eq!(
client
.list_tasks_url(
/*limit*/ None, /*task_filter*/ None, /*environment_id*/ None,
/*cursor*/ None,
)
.unwrap(),
"https://example.test/api/codex/tasks/list"
);
assert_eq!(
client
.list_tasks_url(
/*limit*/ Some(10),
/*task_filter*/ Some("mine / shared"),
/*environment_id*/ Some("env&one"),
/*cursor*/ Some("next=page"),
)
.unwrap(),
"https://example.test/api/codex/tasks/list?limit=10&task_filter=mine+%2F+shared&cursor=next%3Dpage&environment_id=env%26one"
);
}
#[tokio::test]
async fn migrated_requests_preserve_query_auth_and_json_body() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("HTTP listener should bind");
let address = listener
.local_addr()
.expect("HTTP listener should have an address");
let server = std::thread::spawn(move || {
let mut requests = Vec::new();
for body in [r#"{"items":[]}"#, r#"{"task":{"id":"task-created"}}"#] {
let (mut stream, _) = listener.accept().expect("HTTP listener should accept");
stream
.set_read_timeout(Some(Duration::from_secs(2)))
.expect("HTTP stream should get a read timeout");
let mut request = Vec::new();
let mut buffer = [0_u8; 4096];
loop {
let size = stream.read(&mut buffer).expect("HTTP request should read");
if size == 0 {
break;
}
request.extend_from_slice(&buffer[..size]);
let Some(headers_end) = request.windows(4).position(|part| part == b"\r\n\r\n")
else {
continue;
};
let headers = String::from_utf8_lossy(&request[..headers_end]);
let content_length = headers
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse::<usize>().ok())
.flatten()
})
.unwrap_or(0);
if request.len() >= headers_end + 4 + content_length {
break;
}
}
requests.push(String::from_utf8(request).expect("request should be UTF-8"));
write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
.expect("HTTP response should write");
}
requests
});
let client = Client::new(
format!("http://{address}"),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.with_auth_provider(Arc::new(codex_model_provider::BearerAuthProvider::new(
"request-token".to_string(),
)))
.unwrap();
let tasks = client
.list_tasks(
Some(10),
Some("mine / shared"),
Some("env&one"),
Some("next=page"),
)
.await
.expect("list request should succeed");
let task_id = client
.create_task(serde_json::json!({ "prompt": "hello" }))
.await
.expect("create request should succeed");
let requests = server.join().expect("HTTP server should finish");
assert_eq!(tasks, PaginatedListTaskListItem::new(Vec::new()));
assert_eq!(task_id, "task-created");
assert_eq!(requests.len(), 2);
assert!(requests[0].starts_with(
"GET /api/codex/tasks/list?limit=10&task_filter=mine+%2F+shared&cursor=next%3Dpage&environment_id=env%26one HTTP/1.1\r\n"
));
assert!(
requests[0]
.to_ascii_lowercase()
.contains("authorization: bearer request-token\r\n")
);
assert!(requests[1].starts_with("POST /api/codex/tasks HTTP/1.1\r\n"));
assert!(
requests[1]
.to_ascii_lowercase()
.contains("authorization: bearer request-token\r\n")
);
assert!(requests[1].ends_with(r#"{"prompt":"hello"}"#));
}
const BLOCKED_ORIGIN: &str = "http://127.0.0.1:0";
fn run_without_environment_proxies(test_name: &str) -> bool {
const CHILD: &str = "CODEX_BOOTSTRAP_PROXY_TEST_CHILD";
if std::env::var_os(CHILD).is_some() {
return false;
}
let mut command = Command::new(std::env::current_exe().expect("test executable"));
command.arg("--exact").arg(test_name).env(CHILD, "1");
for key in [
"HTTP_PROXY",
"http_proxy",
"HTTPS_PROXY",
"https_proxy",
"ALL_PROXY",
"all_proxy",
"NO_PROXY",
"no_proxy",
] {
command.env_remove(key);
}
let output = command.output().expect("run isolated proxy test");
assert!(
output.status.success(),
"{test_name} failed\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
true
}
fn fallback_client(base_url: &str) -> Client {
Client::new(
base_url,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault).with_system_proxy_fallback(),
)
.with_auth_provider(Arc::new(codex_model_provider::BearerAuthProvider::new(
"bootstrap-token".to_string(),
)))
.unwrap()
.with_chatgpt_account_id("workspace-123")
.with_user_agent("bootstrap-test")
}
#[tokio::test]
async fn bootstrap_gets_resolve_each_fallback_destination_and_preserve_headers() {
if run_without_environment_proxies(
"client::request_tests::bootstrap_gets_resolve_each_fallback_destination_and_preserve_headers",
) {
return;
}
for (base_suffix, api_prefix) in [("", "/api/codex"), ("/backend-api", "/wham")] {
let bundle_proxy = MockServer::start().await;
let accounts_proxy = MockServer::start().await;
let base_url = format!("{BLOCKED_ORIGIN}{base_suffix}");
let client = fallback_client(&base_url);
for (endpoint, proxy) in [
("config/bundle", &bundle_proxy),
("accounts/check", &accounts_proxy),
] {
let endpoint_path = format!("{base_suffix}{api_prefix}/{endpoint}");
cache_system_proxy_route_for_test(
&format!("{base_url}{api_prefix}/{endpoint}"),
proxy.uri(),
);
Mock::given(method("GET"))
.and(path(endpoint_path))
.and(header("authorization", "Bearer bootstrap-token"))
.and(header("chatgpt-account-id", "workspace-123"))
.and(header("user-agent", "bootstrap-test"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.expect(1)
.mount(proxy)
.await;
}
client.get_config_bundle().await.expect("cloud bundle");
client.get_accounts_check().await.expect("accounts check");
bundle_proxy.verify().await;
accounts_proxy.verify().await;
}
}
#[tokio::test]
async fn bootstrap_gets_keep_default_responses_without_proxy_retry() {
if run_without_environment_proxies(
"client::request_tests::bootstrap_gets_keep_default_responses_without_proxy_retry",
) {
return;
}
for status in [200, 401, 403, 407, 429, 503] {
let issuer = MockServer::start().await;
let proxy = MockServer::start().await;
for endpoint in ["config/bundle", "accounts/check"] {
cache_system_proxy_route_for_test(
&format!("{}/api/codex/{endpoint}", issuer.uri()),
proxy.uri(),
);
}
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(status).set_body_json(serde_json::json!({})))
.expect(2)
.mount(&issuer)
.await;
let client = fallback_client(&issuer.uri());
let bundle = client.get_config_bundle().await;
let accounts = client.get_accounts_check().await;
if status == 200 {
bundle.expect("default cloud route succeeds");
accounts.expect("default accounts route succeeds");
} else {
assert_eq!(
[
bundle.expect_err("cloud status error").status(),
accounts.expect_err("accounts status error").status(),
],
[Some(http::StatusCode::from_u16(status).expect("valid test status")); 2]
);
}
issuer.verify().await;
assert_eq!(proxy.received_requests().await.unwrap_or_default().len(), 0);
}
}
#[tokio::test]
async fn bootstrap_gets_honor_disabled_fallback() {
if run_without_environment_proxies(
"client::request_tests::bootstrap_gets_honor_disabled_fallback",
) {
return;
}
let proxy = MockServer::start().await;
let base_url = BLOCKED_ORIGIN;
for endpoint in ["config/bundle", "accounts/check"] {
cache_system_proxy_route_for_test(&format!("{base_url}/api/codex/{endpoint}"), proxy.uri());
}
let client = Client::new(
base_url,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
assert!(client.get_config_bundle().await.is_err());
assert!(client.get_accounts_check().await.is_err());
assert_eq!(proxy.received_requests().await.unwrap_or_default().len(), 0);
}
#[tokio::test]
async fn bootstrap_gets_preserve_network_policy_with_fallback_enabled() {
let issuer = MockServer::start().await;
let proxy = MockServer::start().await;
for endpoint in ["config/bundle", "accounts/check"] {
cache_system_proxy_route_for_test(
&format!("{}/api/codex/{endpoint}", issuer.uri()),
proxy.uri(),
);
}
let controller = codex_http_client::NetworkPolicyController::default();
let client = Client::new(
issuer.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_system_proxy_fallback()
.with_network_policy(controller.policy()),
);
assert!(matches!(
client.get_config_bundle().await,
Err(RequestError::Policy(_))
));
assert!(matches!(
client.get_accounts_check().await,
Err(RequestError::Policy(_))
));
assert_eq!(
issuer.received_requests().await.unwrap_or_default().len(),
0
);
assert_eq!(proxy.received_requests().await.unwrap_or_default().len(), 0);
}
#[tokio::test]
async fn bootstrap_gets_retry_post_connect_failure_with_system_proxy() {
if run_without_environment_proxies(
"client::request_tests::bootstrap_gets_retry_post_connect_failure_with_system_proxy",
) {
return;
}
for endpoint in ["accounts/check", "config/bundle"] {
let issuer = TcpListener::bind(("127.0.0.1", 0)).expect("bind dropping issuer");
let issuer_url = format!("http://{}", issuer.local_addr().expect("issuer address"));
let issuer_thread = std::thread::spawn(move || {
let (stream, _) = issuer.accept().expect("accept bootstrap GET");
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.expect("set read timeout");
let mut reader = std::io::BufReader::new(&stream);
let mut lines = Vec::new();
loop {
let mut line = String::new();
reader.read_line(&mut line).expect("read request headers");
if line == "\r\n" || line.is_empty() {
break;
}
lines.push(line);
}
stream
.shutdown(std::net::Shutdown::Both)
.expect("drop connection before response headers");
lines
});
let proxy = MockServer::start().await;
let endpoint_path = format!("/api/codex/{endpoint}");
cache_system_proxy_route_for_test(&format!("{issuer_url}{endpoint_path}"), proxy.uri());
Mock::given(method("GET"))
.and(path(&endpoint_path))
.and(header("authorization", "Bearer bootstrap-token"))
.and(header("chatgpt-account-id", "workspace-123"))
.and(header("user-agent", "bootstrap-test"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.expect(1)
.mount(&proxy)
.await;
let client = fallback_client(&issuer_url);
let result = client
.exec_bootstrap_get(&format!("{issuer_url}{endpoint_path}"))
.await;
let requests = issuer_thread.join().expect("dropping issuer finishes");
assert_eq!(requests[0], format!("GET {endpoint_path} HTTP/1.1\r\n"));
assert_eq!(
result.expect("retry the idempotent bootstrap GET through the permitted system route"),
("{}".to_string(), "application/json".to_string())
);
proxy.verify().await;
}
}
#[tokio::test]
async fn bootstrap_get_recovers_from_stalled_body_before_cloud_startup_timeout() {
if run_without_environment_proxies(
"client::request_tests::bootstrap_get_recovers_from_stalled_body_before_cloud_startup_timeout",
) {
return;
}
let issuer = TcpListener::bind(("127.0.0.1", 0)).expect("bind stalled issuer");
let issuer_url = format!("http://{}", issuer.local_addr().expect("issuer address"));
let (finish, finished) = std::sync::mpsc::channel();
let issuer_thread = std::thread::spawn(move || {
let (mut stream, _) = issuer.accept().expect("accept bootstrap GET");
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.expect("set read timeout");
let mut request = String::new();
std::io::BufReader::new(&stream)
.read_line(&mut request)
.expect("read request line");
stream
.write_all(
b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{",
)
.expect("send headers and incomplete body");
finished
.recv_timeout(Duration::from_secs(20))
.expect("proxy request finishes while issuer body is pending");
});
let proxy = MockServer::start().await;
cache_system_proxy_route_for_test(
&format!("{issuer_url}/api/codex/config/bundle"),
proxy.uri(),
);
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.expect(1)
.mount(&proxy)
.await;
let result = tokio::time::timeout(
Duration::from_secs(15),
fallback_client(&issuer_url).get_config_bundle(),
)
.await;
finish.send(()).expect("release stalled issuer");
issuer_thread.join().expect("issuer finishes");
result
.expect("proxy retry must fit inside the cloud startup budget")
.expect("cloud bundle via proxy");
proxy.verify().await;
}
#[tokio::test]
async fn identity_header_errors_preserve_credential_recovery() {
for (code, recoverable) in [
("invalid_agent_instance_assertion", false),
("token_expired", true),
] {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/codex/accounts/check"))
.respond_with(
ResponseTemplate::new(401)
.insert_header(
"x-error-json",
base64::engine::general_purpose::STANDARD
.encode(serde_json::json!({"error": {"code": code}}).to_string()),
)
.set_body_json(serde_json::json!({"detail": "Unauthorized"})),
)
.expect(1)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let error = client.get_accounts_check().await.unwrap_err();
assert_eq!(error.status(), Some(StatusCode::UNAUTHORIZED));
assert_eq!(error.is_unauthorized(), recoverable, "{code}");
server.verify().await;
}
}

View File

@@ -0,0 +1,64 @@
mod analytics_session;
mod client;
pub(crate) mod types;
pub use analytics_session::AnalyticsAccount;
pub use analytics_session::AnalyticsSession;
pub use client::AddCreditsNudgeCreditType;
pub use client::ChatgptThreadTurnCosts;
pub use client::ChatgptTurnCost;
pub use client::Client;
pub use client::RequestError;
pub use client::ThreadUsage;
pub use client::ThreadUsageBreakdownGroup;
pub use client::analytics::AnalyticsReport;
pub use client::analytics::AnalyticsResponse;
pub use client::profile::AccountProfile;
pub use client::profile::ProfileIdentity;
pub use client::profile::ProfileInvocation;
pub use client::profile::ProfileInvocationKind;
pub use client::profile::ProfileMetadata;
pub use client::profile::ProfileStats;
pub use client::turn_usage::ApiKeyResponseCost;
pub use client::turn_usage::ApiKeyTurnCost;
pub use client::turn_usage::ApiKeyTurnCostStatus;
pub use types::AccountEntry;
pub use types::AccountsCheckResponse;
pub use types::CodeTaskDetailsResponse;
pub use types::CodeTaskDetailsResponseExt;
pub use types::CodexUserSettingsResponse;
pub use types::CodexWorkspaceMessage;
pub use types::CodexWorkspaceMessageType;
pub use types::CodexWorkspaceMessagesResponse;
pub use types::ConfigBundleResponse;
pub use types::ConsumeRateLimitResetCreditCode;
pub use types::ConsumeRateLimitResetCreditResponse;
pub use types::DeliveredConfigToml;
pub use types::DeliveredManagedLayers;
pub use types::DeliveredRequirementsToml;
pub use types::DeliveredTomlFragment;
pub use types::PaginatedListTaskListItem;
pub use types::RateLimitResetCreditDetails;
pub use types::RateLimitResetCreditsDetails;
pub use types::RateLimitResetCreditsSummary;
pub use types::RateLimitsWithResetCredits;
pub use types::TaskListItem;
pub use types::TokenUsageProfile;
pub use types::TokenUsageProfileDailyBucket;
pub use types::TokenUsageProfileStats;
pub use types::TurnAttemptsSiblingTurnsResponse;
pub use client::plan_history::PlanLimitBreakdown;
pub use client::plan_history::PlanLimitDimension;
pub use client::plan_history::PlanLimitHistory;
pub use client::plan_history::PlanLimitPeriod;
pub use client::plan_history::PlanLimitValue;
pub use client::task_usage::TaskCredits;
pub use client::task_usage::TaskUsage;
pub use client::task_usage::TaskUsageAmounts;
pub use client::task_usage::TaskUsageGroup;
pub use client::task_usage::TaskUsageResponse;
pub use client::task_usage::TaskUsageStatus;
pub use client::task_usage::TaskUsageThread;
pub use codex_backend_openapi_models::models::analytics as analytics_models;

View File

@@ -0,0 +1,681 @@
pub use codex_backend_openapi_models::models::ConfigBundleResponse;
pub use codex_backend_openapi_models::models::CreditStatusDetails;
pub use codex_backend_openapi_models::models::DeliveredConfigToml;
pub use codex_backend_openapi_models::models::DeliveredManagedLayers;
pub use codex_backend_openapi_models::models::DeliveredRequirementsToml;
pub use codex_backend_openapi_models::models::DeliveredTomlFragment;
pub use codex_backend_openapi_models::models::PaginatedListTaskListItem;
pub use codex_backend_openapi_models::models::PlanType;
pub use codex_backend_openapi_models::models::RateLimitReachedKind;
pub use codex_backend_openapi_models::models::RateLimitStatusDetails;
pub use codex_backend_openapi_models::models::RateLimitStatusPayload;
pub use codex_backend_openapi_models::models::RateLimitWindowSnapshot;
pub use codex_backend_openapi_models::models::SpendControlLimitDetails;
pub use codex_backend_openapi_models::models::TaskListItem;
use codex_protocol::protocol::RateLimitSnapshot;
use serde::Deserialize;
use serde::de::Deserializer;
use serde_json::Value;
use std::collections::HashMap;
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct RateLimitResetCreditsSummary {
pub available_count: i64,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct RateLimitResetCreditsDetails {
pub credits: Vec<RateLimitResetCreditDetails>,
pub available_count: i64,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct RateLimitResetCreditDetails {
pub id: String,
pub reset_type: String,
pub status: String,
pub granted_at: String,
pub expires_at: Option<String>,
pub title: Option<String>,
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RateLimitsWithResetCredits {
pub rate_limits: Vec<RateLimitSnapshot>,
/// Backend decision for ordinary included usage; absence is not permission to recover.
pub ordinary_usage_allowed: Option<bool>,
pub rate_limit_reset_credits: Option<RateLimitResetCreditsSummary>,
pub account_id: Option<String>,
pub user_id: Option<String>,
pub rate_limit_upsell: Option<Value>,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub(crate) struct RateLimitStatusWithResetCredits {
#[serde(flatten)]
pub rate_limits: RateLimitStatusPayload,
// Capture the new optional metadata alongside the generated quota fields until the
// backend OpenAPI export includes it. This field owns additional_rate_limits on the wire.
pub additional_rate_limits: Option<Vec<AdditionalRateLimitWithNormalModel>>,
pub rate_limit_reset_credits: Option<RateLimitResetCreditsSummary>,
pub account_id: Option<String>,
pub user_id: Option<String>,
// Preserve the backend-owned banner contract without making optional UI data break usage.
pub rate_limit_upsell: Option<Value>,
}
/// Additional quota details plus the normal model whose picker metadata should be used.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub(crate) struct AdditionalRateLimitWithNormalModel {
#[serde(flatten)]
pub details: codex_backend_openapi_models::models::AdditionalRateLimitDetails,
pub normal_model_slug: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct CodexWorkspaceMessagesResponse {
#[serde(default)]
pub messages: Vec<CodexWorkspaceMessage>,
}
/// Authenticated Codex user settings used by CLI runtime policy.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
pub struct CodexUserSettingsResponse {
/// Server-computed effective commit-attribution policy.
///
/// Older backend responses omit this field, which safely defaults to disabled.
#[serde(default)]
pub commit_attribution_enabled: bool,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct CodexWorkspaceMessage {
pub message_id: String,
pub message_type: CodexWorkspaceMessageType,
pub message_body: String,
#[serde(default)]
pub created_at: Option<String>,
#[serde(default)]
pub archived_at: Option<String>,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ConsumeRateLimitResetCreditCode {
Reset,
NothingToReset,
NoCredit,
AlreadyRedeemed,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct ConsumeRateLimitResetCreditResponse {
pub code: ConsumeRateLimitResetCreditCode,
#[serde(default)]
pub windows_reset: i64,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CodexWorkspaceMessageType {
Headline,
Announcement,
#[serde(other)]
Unknown,
}
#[derive(Clone, Debug)]
pub struct AccountsCheckResponse {
pub accounts: Vec<AccountEntry>,
pub account_ordering: Vec<String>,
pub default_account_id: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct AccountEntry {
pub id: String,
pub can_access_with_session: Option<bool>,
pub sso_connection_name: Option<String>,
#[serde(default)]
pub is_deactivated: bool,
#[serde(default)]
pub is_fedramp_compliant_workspace: bool,
/// Current subscription reported by the accounts endpoint, independent of token claims.
#[serde(default)]
pub plan_type: Option<codex_protocol::account::PlanType>,
pub workspace_backend_origin: Option<String>,
pub account_routing_override: Option<String>,
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub profile_picture_url: Option<String>,
#[serde(default)]
pub structure: String,
}
#[derive(Deserialize)]
struct RawAccountsCheckResponse {
#[serde(default)]
accounts: RawAccounts,
#[serde(default)]
account_ordering: Vec<String>,
#[serde(default)]
default_account_id: Option<String>,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum RawAccounts {
List(Vec<AccountEntry>),
Map(HashMap<String, ChatGptAccountEntry>),
}
impl Default for RawAccounts {
fn default() -> Self {
Self::List(Vec::new())
}
}
#[derive(Deserialize)]
struct ChatGptAccountEntry {
account: ChatGptAccountInfo,
can_access_with_session: Option<bool>,
sso_connection_name: Option<String>,
}
#[derive(Deserialize)]
struct ChatGptAccountInfo {
account_id: Option<String>,
#[serde(default)]
is_deactivated: bool,
#[serde(default)]
is_fedramp_compliant_workspace: bool,
#[serde(default)]
plan_type: Option<codex_protocol::account::PlanType>,
#[serde(default)]
name: Option<String>,
#[serde(default)]
profile_picture_url: Option<String>,
#[serde(default)]
structure: String,
}
impl<'de> Deserialize<'de> for AccountsCheckResponse {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let raw = RawAccountsCheckResponse::deserialize(deserializer)?;
let accounts = match raw.accounts {
RawAccounts::List(accounts) => accounts,
RawAccounts::Map(mut accounts) => raw
.account_ordering
.iter()
.filter_map(|account_id| {
let entry = accounts.remove(account_id)?;
let account = entry.account;
Some(AccountEntry {
id: account.account_id?,
can_access_with_session: entry.can_access_with_session,
sso_connection_name: entry.sso_connection_name,
is_deactivated: account.is_deactivated,
is_fedramp_compliant_workspace: account.is_fedramp_compliant_workspace,
plan_type: account.plan_type,
workspace_backend_origin: None,
account_routing_override: None,
name: account.name,
profile_picture_url: account.profile_picture_url,
structure: account.structure,
})
})
.collect(),
};
Ok(Self {
accounts,
account_ordering: raw.account_ordering,
default_account_id: raw.default_account_id,
})
}
}
/// Hand-rolled models for the Cloud Tasks task-details response.
/// The generated OpenAPI models are pretty bad. This is a half-step
/// towards hand-rolling them.
#[derive(Clone, Debug, Deserialize)]
pub struct CodeTaskDetailsResponse {
#[serde(default)]
pub current_user_turn: Option<Turn>,
#[serde(default)]
pub current_assistant_turn: Option<Turn>,
#[serde(default)]
pub current_diff_task_turn: Option<Turn>,
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct Turn {
#[serde(default)]
pub id: Option<String>,
#[serde(default)]
pub attempt_placement: Option<i64>,
#[serde(default, rename = "turn_status")]
pub turn_status: Option<String>,
#[serde(default, deserialize_with = "deserialize_vec")]
pub sibling_turn_ids: Vec<String>,
#[serde(default, deserialize_with = "deserialize_vec")]
pub input_items: Vec<TurnItem>,
#[serde(default, deserialize_with = "deserialize_vec")]
pub output_items: Vec<TurnItem>,
#[serde(default)]
pub worklog: Option<Worklog>,
#[serde(default)]
pub error: Option<TurnError>,
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct TurnItem {
#[serde(rename = "type", default)]
pub kind: String,
#[serde(default)]
pub role: Option<String>,
#[serde(default, deserialize_with = "deserialize_vec")]
pub content: Vec<ContentFragment>,
#[serde(default)]
pub diff: Option<String>,
#[serde(default)]
pub output_diff: Option<DiffPayload>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
pub enum ContentFragment {
Structured(StructuredContent),
Text(String),
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct StructuredContent {
#[serde(rename = "content_type", default)]
pub content_type: Option<String>,
#[serde(default)]
pub text: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct DiffPayload {
#[serde(default)]
pub diff: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct Worklog {
#[serde(default, deserialize_with = "deserialize_vec")]
pub messages: Vec<WorklogMessage>,
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct WorklogMessage {
#[serde(default)]
pub author: Option<Author>,
#[serde(default)]
pub content: Option<WorklogContent>,
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct Author {
#[serde(default)]
pub role: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct WorklogContent {
#[serde(default)]
pub parts: Vec<ContentFragment>,
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct TurnError {
#[serde(default)]
pub code: Option<String>,
#[serde(default)]
pub message: Option<String>,
}
impl ContentFragment {
fn text(&self) -> Option<&str> {
match self {
ContentFragment::Structured(inner) => {
if inner
.content_type
.as_deref()
.map(|ct| ct.eq_ignore_ascii_case("text"))
.unwrap_or(false)
{
inner.text.as_deref().filter(|s| !s.is_empty())
} else {
None
}
}
ContentFragment::Text(raw) => {
if raw.trim().is_empty() {
None
} else {
Some(raw.as_str())
}
}
}
}
}
impl TurnItem {
fn text_values(&self) -> Vec<String> {
self.content
.iter()
.filter_map(|fragment| fragment.text().map(str::to_string))
.collect()
}
fn diff_text(&self) -> Option<String> {
if self.kind == "output_diff" {
if let Some(diff) = &self.diff
&& !diff.is_empty()
{
return Some(diff.clone());
}
} else if self.kind == "pr"
&& let Some(payload) = &self.output_diff
&& let Some(diff) = &payload.diff
&& !diff.is_empty()
{
return Some(diff.clone());
}
None
}
}
impl Turn {
fn unified_diff(&self) -> Option<String> {
self.output_items.iter().find_map(TurnItem::diff_text)
}
fn message_texts(&self) -> Vec<String> {
let mut out: Vec<String> = self
.output_items
.iter()
.filter(|item| item.kind == "message")
.flat_map(TurnItem::text_values)
.collect();
if let Some(log) = &self.worklog {
for message in &log.messages {
if message.is_assistant() {
out.extend(message.text_values());
}
}
}
out
}
fn user_prompt(&self) -> Option<String> {
let parts: Vec<String> = self
.input_items
.iter()
.filter(|item| item.kind == "message")
.filter(|item| {
item.role
.as_deref()
.map(|r| r.eq_ignore_ascii_case("user"))
.unwrap_or(true)
})
.flat_map(TurnItem::text_values)
.collect();
if parts.is_empty() {
None
} else {
Some(parts.join(
"
",
))
}
}
fn error_summary(&self) -> Option<String> {
self.error.as_ref().and_then(TurnError::summary)
}
}
impl WorklogMessage {
fn is_assistant(&self) -> bool {
self.author
.as_ref()
.and_then(|a| a.role.as_deref())
.map(|role| role.eq_ignore_ascii_case("assistant"))
.unwrap_or(false)
}
fn text_values(&self) -> Vec<String> {
self.content
.as_ref()
.map(|content| {
content
.parts
.iter()
.filter_map(|fragment| fragment.text().map(str::to_string))
.collect()
})
.unwrap_or_default()
}
}
impl TurnError {
fn summary(&self) -> Option<String> {
let code = self.code.as_deref().unwrap_or("");
let message = self.message.as_deref().unwrap_or("");
match (code.is_empty(), message.is_empty()) {
(true, true) => None,
(false, true) => Some(code.to_string()),
(true, false) => Some(message.to_string()),
(false, false) => Some(format!("{code}: {message}")),
}
}
}
pub trait CodeTaskDetailsResponseExt {
/// Attempt to extract a unified diff string from the assistant or diff turn.
fn unified_diff(&self) -> Option<String>;
/// Extract assistant text output messages (no diff) from current turns.
fn assistant_text_messages(&self) -> Vec<String>;
/// Extract the user's prompt text from the current user turn, when present.
fn user_text_prompt(&self) -> Option<String>;
/// Extract an assistant error message (if the turn failed and provided one).
fn assistant_error_message(&self) -> Option<String>;
}
impl CodeTaskDetailsResponseExt for CodeTaskDetailsResponse {
fn unified_diff(&self) -> Option<String> {
[
self.current_diff_task_turn.as_ref(),
self.current_assistant_turn.as_ref(),
]
.into_iter()
.flatten()
.find_map(Turn::unified_diff)
}
fn assistant_text_messages(&self) -> Vec<String> {
let mut out = Vec::new();
for turn in [
self.current_diff_task_turn.as_ref(),
self.current_assistant_turn.as_ref(),
]
.into_iter()
.flatten()
{
out.extend(turn.message_texts());
}
out
}
fn user_text_prompt(&self) -> Option<String> {
self.current_user_turn.as_ref().and_then(Turn::user_prompt)
}
fn assistant_error_message(&self) -> Option<String> {
self.current_assistant_turn
.as_ref()
.and_then(Turn::error_summary)
}
}
fn deserialize_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
Option::<Vec<T>>::deserialize(deserializer).map(Option::unwrap_or_default)
}
#[derive(Clone, Debug, Deserialize)]
pub struct TurnAttemptsSiblingTurnsResponse {
#[serde(default)]
pub sibling_turns: Vec<HashMap<String, Value>>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct TokenUsageProfile {
pub stats: TokenUsageProfileStats,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct TokenUsageProfileStats {
pub lifetime_tokens: Option<i64>,
pub peak_daily_tokens: Option<i64>,
pub longest_running_turn_sec: Option<i64>,
pub current_streak_days: Option<i64>,
pub longest_streak_days: Option<i64>,
pub daily_usage_buckets: Option<Vec<TokenUsageProfileDailyBucket>>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct TokenUsageProfileDailyBucket {
pub start_date: String,
pub tokens: i64,
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
fn fixture(name: &str) -> CodeTaskDetailsResponse {
let json = match name {
"diff" => include_str!("../tests/fixtures/task_details_with_diff.json"),
"error" => include_str!("../tests/fixtures/task_details_with_error.json"),
other => panic!("unknown fixture {other}"),
};
serde_json::from_str(json).expect("fixture should deserialize")
}
#[test]
fn unified_diff_prefers_current_diff_task_turn() {
let details = fixture("diff");
let diff = details.unified_diff().expect("diff present");
assert!(diff.contains("diff --git"));
}
#[test]
fn unified_diff_falls_back_to_pr_output_diff() {
let details = fixture("error");
let diff = details.unified_diff().expect("diff from pr output");
assert!(diff.contains("lib.rs"));
}
#[test]
fn assistant_text_messages_extracts_text_content() {
let details = fixture("diff");
let messages = details.assistant_text_messages();
assert_eq!(messages, vec!["Assistant response".to_string()]);
}
#[test]
fn user_text_prompt_joins_parts_with_spacing() {
let details = fixture("diff");
let prompt = details.user_text_prompt().expect("prompt present");
assert_eq!(
prompt,
"First line
Second line"
);
}
#[test]
fn assistant_error_message_combines_code_and_message() {
let details = fixture("error");
let msg = details
.assistant_error_message()
.expect("error should be present");
assert_eq!(msg, "APPLY_FAILED: Patch could not be applied");
}
#[test]
fn workspace_messages_response_deserializes_messages() {
let response: CodexWorkspaceMessagesResponse = serde_json::from_value(serde_json::json!({
"messages": [
{
"message_id": "headline-id",
"message_type": "headline",
"message_body": "Headline body",
"created_at": "2026-06-14T00:00:00Z",
"archived_at": null
},
{
"message_id": "announcement-id",
"message_type": "announcement",
"message_body": "Announcement body",
"created_at": "2026-06-14T01:00:00Z",
"archived_at": null
},
{
"message_id": "unknown-id",
"message_type": "unknown",
"message_body": "Unknown body"
}
]
}))
.expect("workspace messages response should deserialize");
assert_eq!(
response,
CodexWorkspaceMessagesResponse {
messages: vec![
CodexWorkspaceMessage {
message_id: "headline-id".to_string(),
message_type: CodexWorkspaceMessageType::Headline,
message_body: "Headline body".to_string(),
created_at: Some("2026-06-14T00:00:00Z".to_string()),
archived_at: None,
},
CodexWorkspaceMessage {
message_id: "announcement-id".to_string(),
message_type: CodexWorkspaceMessageType::Announcement,
message_body: "Announcement body".to_string(),
created_at: Some("2026-06-14T01:00:00Z".to_string()),
archived_at: None,
},
CodexWorkspaceMessage {
message_id: "unknown-id".to_string(),
message_type: CodexWorkspaceMessageType::Unknown,
message_body: "Unknown body".to_string(),
created_at: None,
archived_at: None,
},
],
}
);
}
}

View File

@@ -0,0 +1,38 @@
{
"task": {
"id": "task_123",
"title": "Refactor cloud task client",
"archived": false,
"external_pull_requests": []
},
"current_user_turn": {
"input_items": [
{
"type": "message",
"role": "user",
"content": [
{ "content_type": "text", "text": "First line" },
{ "content_type": "text", "text": "Second line" }
]
}
]
},
"current_assistant_turn": {
"output_items": [
{
"type": "message",
"content": [
{ "content_type": "text", "text": "Assistant response" }
]
}
]
},
"current_diff_task_turn": {
"output_items": [
{
"type": "output_diff",
"diff": "diff --git a/src/main.rs b/src/main.rs\n+fn main() { println!(\"hi\"); }\n"
}
]
}
}

View File

@@ -0,0 +1,22 @@
{
"task": {
"id": "task_456",
"title": "Investigate failure",
"archived": false,
"external_pull_requests": []
},
"current_assistant_turn": {
"output_items": [
{
"type": "pr",
"output_diff": {
"diff": "diff --git a/lib.rs b/lib.rs\n+pub fn hello() {}\n"
}
}
],
"error": {
"code": "APPLY_FAILED",
"message": "Patch could not be applied"
}
}
}