mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Expose gateway spend in app-server account rate limits (#65193)
## Why Clients need to show the spend and cap for the account behind a thread's model provider. The existing ChatGPT usage read cannot provide those figures for a gateway account. ## What changed - Route `account/rateLimits/read` through the provider's configured `usage_url` using the provider's credentials. An optional `threadId` selects a loaded thread's provider for the account-wide read. Omitting it selects the default provider. - Return `usageUnavailable` for a thread whose provider has neither a usage endpoint nor first-party authentication. Surface gateway errors without falling back to ChatGPT usage. - Report monthly gateway spend in `individualLimit` as exact USD decimal strings, with `limit: "unlimited"` for uncapped accounts. Use `spendControlReached` for the gateway's cap status. Spend snapshots identify their unit as `usd` or `credit`, with omitted units defaulting to `credit` for compatibility. ## Testing Add integration coverage for thread-specific provider selection, gateway usage taking precedence over ChatGPT without fallback, and reuse of an existing gateway OAuth session without interactive login. GitOrigin-RevId: e6ec9d83eecc3084fcc98e72e2c031bd3e53a2cd
This commit is contained in:
+8
-1
@@ -1778,7 +1778,7 @@
|
||||
"type": "object"
|
||||
},
|
||||
"GetAccountRateLimitsParams": {
|
||||
"description": "Usage-read capabilities of the requesting client, never inferred from its experiment arm.",
|
||||
"description": "Provider selection and client capabilities for an account rate-limit read.",
|
||||
"properties": {
|
||||
"excludeResetCreditDetails": {
|
||||
"description": "Skip the separate reset-credit detail lookup for background usage polls. The usage response still includes the available count; omitted/false preserves detailed reads.",
|
||||
@@ -1787,6 +1787,13 @@
|
||||
"supportsLunaReserve": {
|
||||
"description": "The client supports automatic Luna Reserve fallback. For eligible ChatGPT CLI users, allow the backend to record experiment exposure after ordinary usage is blocked.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"threadId": {
|
||||
"description": "Use the loaded thread's provider for this account-wide read. Omit for the default provider.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
|
||||
@@ -4345,9 +4345,11 @@
|
||||
"SpendControlLimitSnapshot": {
|
||||
"properties": {
|
||||
"limit": {
|
||||
"description": "Decimal amount, or \"unlimited\" when the provider has no spend cap.",
|
||||
"type": "string"
|
||||
},
|
||||
"remainingPercent": {
|
||||
"description": "For an unlimited cap this is 100 for compatibility. Ignore it for display and warnings.",
|
||||
"format": "int32",
|
||||
"type": "integer"
|
||||
},
|
||||
@@ -4355,6 +4357,15 @@
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"unit": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/SpendControlUnit"
|
||||
}
|
||||
],
|
||||
"default": "credit",
|
||||
"description": "Unit of `used` and any numeric `limit`. Older servers omit this for credits."
|
||||
},
|
||||
"used": {
|
||||
"type": "string"
|
||||
}
|
||||
@@ -4367,6 +4378,13 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"SpendControlUnit": {
|
||||
"enum": [
|
||||
"credit",
|
||||
"usd"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"StrictReviewRequiredNotification": {
|
||||
"properties": {
|
||||
"startedAtMs": {
|
||||
|
||||
+26
-1
@@ -13909,7 +13909,7 @@
|
||||
"type": "object"
|
||||
},
|
||||
"GetAccountRateLimitsParams": {
|
||||
"description": "Usage-read capabilities of the requesting client, never inferred from its experiment arm.",
|
||||
"description": "Provider selection and client capabilities for an account rate-limit read.",
|
||||
"properties": {
|
||||
"excludeResetCreditDetails": {
|
||||
"description": "Skip the separate reset-credit detail lookup for background usage polls. The usage response still includes the available count; omitted/false preserves detailed reads.",
|
||||
@@ -13918,6 +13918,13 @@
|
||||
"supportsLunaReserve": {
|
||||
"description": "The client supports automatic Luna Reserve fallback. For eligible ChatGPT CLI users, allow the backend to record experiment exposure after ordinary usage is blocked.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"threadId": {
|
||||
"description": "Use the loaded thread's provider for this account-wide read. Omit for the default provider.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
@@ -22815,9 +22822,11 @@
|
||||
"SpendControlLimitSnapshot": {
|
||||
"properties": {
|
||||
"limit": {
|
||||
"description": "Decimal amount, or \"unlimited\" when the provider has no spend cap.",
|
||||
"type": "string"
|
||||
},
|
||||
"remainingPercent": {
|
||||
"description": "For an unlimited cap this is 100 for compatibility. Ignore it for display and warnings.",
|
||||
"format": "int32",
|
||||
"type": "integer"
|
||||
},
|
||||
@@ -22825,6 +22834,15 @@
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"unit": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/v2/SpendControlUnit"
|
||||
}
|
||||
],
|
||||
"default": "credit",
|
||||
"description": "Unit of `used` and any numeric `limit`. Older servers omit this for credits."
|
||||
},
|
||||
"used": {
|
||||
"type": "string"
|
||||
}
|
||||
@@ -22837,6 +22855,13 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"SpendControlUnit": {
|
||||
"enum": [
|
||||
"credit",
|
||||
"usd"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"StartupGatewayOAuthChangedNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Browser handoff on the dedicated `--startup-oauth` connection.",
|
||||
|
||||
+26
-1
@@ -9680,7 +9680,7 @@
|
||||
"type": "object"
|
||||
},
|
||||
"GetAccountRateLimitsParams": {
|
||||
"description": "Usage-read capabilities of the requesting client, never inferred from its experiment arm.",
|
||||
"description": "Provider selection and client capabilities for an account rate-limit read.",
|
||||
"properties": {
|
||||
"excludeResetCreditDetails": {
|
||||
"description": "Skip the separate reset-credit detail lookup for background usage polls. The usage response still includes the available count; omitted/false preserves detailed reads.",
|
||||
@@ -9689,6 +9689,13 @@
|
||||
"supportsLunaReserve": {
|
||||
"description": "The client supports automatic Luna Reserve fallback. For eligible ChatGPT CLI users, allow the backend to record experiment exposure after ordinary usage is blocked.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"threadId": {
|
||||
"description": "Use the loaded thread's provider for this account-wide read. Omit for the default provider.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
@@ -20437,9 +20444,11 @@
|
||||
"SpendControlLimitSnapshot": {
|
||||
"properties": {
|
||||
"limit": {
|
||||
"description": "Decimal amount, or \"unlimited\" when the provider has no spend cap.",
|
||||
"type": "string"
|
||||
},
|
||||
"remainingPercent": {
|
||||
"description": "For an unlimited cap this is 100 for compatibility. Ignore it for display and warnings.",
|
||||
"format": "int32",
|
||||
"type": "integer"
|
||||
},
|
||||
@@ -20447,6 +20456,15 @@
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"unit": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/SpendControlUnit"
|
||||
}
|
||||
],
|
||||
"default": "credit",
|
||||
"description": "Unit of `used` and any numeric `limit`. Older servers omit this for credits."
|
||||
},
|
||||
"used": {
|
||||
"type": "string"
|
||||
}
|
||||
@@ -20459,6 +20477,13 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"SpendControlUnit": {
|
||||
"enum": [
|
||||
"credit",
|
||||
"usd"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"StartupGatewayOAuthChangedNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Browser handoff on the dedicated `--startup-oauth` connection.",
|
||||
|
||||
+18
@@ -177,9 +177,11 @@
|
||||
"SpendControlLimitSnapshot": {
|
||||
"properties": {
|
||||
"limit": {
|
||||
"description": "Decimal amount, or \"unlimited\" when the provider has no spend cap.",
|
||||
"type": "string"
|
||||
},
|
||||
"remainingPercent": {
|
||||
"description": "For an unlimited cap this is 100 for compatibility. Ignore it for display and warnings.",
|
||||
"format": "int32",
|
||||
"type": "integer"
|
||||
},
|
||||
@@ -187,6 +189,15 @@
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"unit": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/SpendControlUnit"
|
||||
}
|
||||
],
|
||||
"default": "credit",
|
||||
"description": "Unit of `used` and any numeric `limit`. Older servers omit this for credits."
|
||||
},
|
||||
"used": {
|
||||
"type": "string"
|
||||
}
|
||||
@@ -198,6 +209,13 @@
|
||||
"used"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"SpendControlUnit": {
|
||||
"enum": [
|
||||
"credit",
|
||||
"usd"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"description": "Sparse rolling rate-limit update.\n\nClients should merge available values into the most recent `account/rateLimits/read` response or refetch that snapshot. Nullable account metadata may be unavailable in a rolling update and does not clear a previously observed value.",
|
||||
|
||||
+18
@@ -263,9 +263,11 @@
|
||||
"SpendControlLimitSnapshot": {
|
||||
"properties": {
|
||||
"limit": {
|
||||
"description": "Decimal amount, or \"unlimited\" when the provider has no spend cap.",
|
||||
"type": "string"
|
||||
},
|
||||
"remainingPercent": {
|
||||
"description": "For an unlimited cap this is 100 for compatibility. Ignore it for display and warnings.",
|
||||
"format": "int32",
|
||||
"type": "integer"
|
||||
},
|
||||
@@ -273,6 +275,15 @@
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"unit": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/SpendControlUnit"
|
||||
}
|
||||
],
|
||||
"default": "credit",
|
||||
"description": "Unit of `used` and any numeric `limit`. Older servers omit this for credits."
|
||||
},
|
||||
"used": {
|
||||
"type": "string"
|
||||
}
|
||||
@@ -284,6 +295,13 @@
|
||||
"used"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"SpendControlUnit": {
|
||||
"enum": [
|
||||
"credit",
|
||||
"usd"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
|
||||
+8
-1
@@ -10,7 +10,7 @@
|
||||
],
|
||||
"definitions": {
|
||||
"GetAccountRateLimitsParams": {
|
||||
"description": "Usage-read capabilities of the requesting client, never inferred from its experiment arm.",
|
||||
"description": "Provider selection and client capabilities for an account rate-limit read.",
|
||||
"properties": {
|
||||
"excludeResetCreditDetails": {
|
||||
"description": "Skip the separate reset-credit detail lookup for background usage polls. The usage response still includes the available count; omitted/false preserves detailed reads.",
|
||||
@@ -19,6 +19,13 @@
|
||||
"supportsLunaReserve": {
|
||||
"description": "The client supports automatic Luna Reserve fallback. For eligible ChatGPT CLI users, allow the backend to record experiment exposure after ordinary usage is blocked.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"threadId": {
|
||||
"description": "Use the loaded thread's provider for this account-wide read. Omit for the default provider.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
+5
-1
@@ -3,9 +3,13 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Usage-read capabilities of the requesting client, never inferred from its experiment arm.
|
||||
* Provider selection and client capabilities for an account rate-limit read.
|
||||
*/
|
||||
export type GetAccountRateLimitsParams = {
|
||||
/**
|
||||
* Use the loaded thread's provider for this account-wide read. Omit for the default provider.
|
||||
*/
|
||||
threadId?: string | null,
|
||||
/**
|
||||
* The client supports automatic Luna Reserve fallback. For eligible ChatGPT CLI users,
|
||||
* allow the backend to record experiment exposure after ordinary usage is blocked.
|
||||
|
||||
+14
-1
@@ -1,5 +1,18 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { SpendControlUnit } from "./SpendControlUnit";
|
||||
|
||||
export type SpendControlLimitSnapshot = { limit: string, used: string, remainingPercent: number, resetsAt: number, };
|
||||
export type SpendControlLimitSnapshot = {
|
||||
/**
|
||||
* Unit of `used` and any numeric `limit`. Older servers omit this for credits.
|
||||
*/
|
||||
unit: SpendControlUnit,
|
||||
/**
|
||||
* Decimal amount, or "unlimited" when the provider has no spend cap.
|
||||
*/
|
||||
limit: string, used: string,
|
||||
/**
|
||||
* For an unlimited cap this is 100 for compatibility. Ignore it for display and warnings.
|
||||
*/
|
||||
remainingPercent: number, resetsAt: number, };
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type SpendControlUnit = "credit" | "usd";
|
||||
@@ -514,6 +514,7 @@ export type { SkillsListParams } from "./SkillsListParams";
|
||||
export type { SkillsListResponse } from "./SkillsListResponse";
|
||||
export type { SortDirection } from "./SortDirection";
|
||||
export type { SpendControlLimitSnapshot } from "./SpendControlLimitSnapshot";
|
||||
export type { SpendControlUnit } from "./SpendControlUnit";
|
||||
export type { StartupGatewayOAuthChangedNotification } from "./StartupGatewayOAuthChangedNotification";
|
||||
export type { StrictReviewRequiredNotification } from "./StrictReviewRequiredNotification";
|
||||
export type { SubAgentActivityKind } from "./SubAgentActivityKind";
|
||||
|
||||
@@ -11,6 +11,7 @@ use codex_protocol::protocol::RateLimitReachedType as CoreRateLimitReachedType;
|
||||
use codex_protocol::protocol::RateLimitSnapshot as CoreRateLimitSnapshot;
|
||||
use codex_protocol::protocol::RateLimitWindow as CoreRateLimitWindow;
|
||||
use codex_protocol::protocol::SpendControlLimitSnapshot as CoreSpendControlLimitSnapshot;
|
||||
pub use codex_protocol::protocol::SpendControlUnit;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
@@ -348,11 +349,14 @@ impl fmt::Debug for ChatgptAuthTokensRefreshResponse {
|
||||
}
|
||||
}
|
||||
|
||||
/// Usage-read capabilities of the requesting client, never inferred from its experiment arm.
|
||||
/// Provider selection and client capabilities for an account rate-limit read.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct GetAccountRateLimitsParams {
|
||||
/// Use the loaded thread's provider for this account-wide read. Omit for the default provider.
|
||||
#[ts(optional = nullable)]
|
||||
pub thread_id: Option<String>,
|
||||
/// The client supports automatic Luna Reserve fallback. For eligible ChatGPT CLI users,
|
||||
/// allow the backend to record experiment exposure after ordinary usage is blocked.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
@@ -954,8 +958,13 @@ impl From<CoreCreditsSnapshot> for CreditsSnapshot {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct SpendControlLimitSnapshot {
|
||||
/// Unit of `used` and any numeric `limit`. Older servers omit this for credits.
|
||||
#[serde(default)]
|
||||
pub unit: SpendControlUnit,
|
||||
/// Decimal amount, or "unlimited" when the provider has no spend cap.
|
||||
pub limit: String,
|
||||
pub used: String,
|
||||
/// For an unlimited cap this is 100 for compatibility. Ignore it for display and warnings.
|
||||
pub remaining_percent: i32,
|
||||
#[ts(type = "number")]
|
||||
pub resets_at: i64,
|
||||
@@ -964,6 +973,7 @@ pub struct SpendControlLimitSnapshot {
|
||||
impl From<CoreSpendControlLimitSnapshot> for SpendControlLimitSnapshot {
|
||||
fn from(value: CoreSpendControlLimitSnapshot) -> Self {
|
||||
Self {
|
||||
unit: value.unit,
|
||||
limit: value.limit,
|
||||
used: value.used,
|
||||
remaining_percent: value.remaining_percent,
|
||||
|
||||
@@ -922,6 +922,39 @@ If the read reports `configServerLogin`, keep the connection open.
|
||||
only after validating the requirements. Older clients can still use the
|
||||
one-shot command before and after sign-in.
|
||||
|
||||
# Provider spend in account usage reads
|
||||
|
||||
Set `model_providers.<id>.usage_url` to the full URL of a trusted gateway's
|
||||
`GET /v1/usage/me` endpoint. By default, `account/rateLimits/read` uses the
|
||||
current non-project configuration. Pass `threadId` to select a loaded thread's
|
||||
provider, including any thread-specific provider definition. The returned
|
||||
limits are shared by the provider account across threads.
|
||||
|
||||
A provider with `usage_url` uses its own credentials and skips ChatGPT usage
|
||||
and reset credits. Provider errors never fall back to a different account.
|
||||
A first-party thread reads ChatGPT account limits.
|
||||
|
||||
If the thread's provider has neither `usage_url` nor first-party authentication, the
|
||||
request fails with code `-32600` and `error.data.reason` set to
|
||||
`"usageUnavailable"`. Clients can hide usage for that thread and should not
|
||||
retry without `threadId`, which could return a different account's limits.
|
||||
Unknown threads and gateway request failures do not carry this reason. Omitting
|
||||
`threadId` or passing `null` preserves the existing account backend behavior
|
||||
when the default provider has no `usage_url`.
|
||||
|
||||
Monthly spend is in `rateLimits.individualLimit` and the corresponding
|
||||
`rateLimitsByLimitId` entry. The provider returns `unit: "usd"`, exact decimal
|
||||
strings for `used` and `limit`, an integer `remainingPercent`, and `resetsAt`
|
||||
in Unix seconds. A zero cap has 0% remaining. For an uncapped user, `limit`
|
||||
is `"unlimited"` and `remainingPercent` is 100 for compatibility. Clients
|
||||
should display the amount spent and skip percentage bars and threshold warnings
|
||||
for unlimited users. Rounded usage can leave 0% remaining before the cap is hit.
|
||||
Use `rateLimits.spendControlReached` (the gateway's `reached` flag) to check
|
||||
whether the cap has been reached. Both rolling windows stay null.
|
||||
|
||||
ChatGPT spend controls also carry `unit` (`"credit"` or `"usd"`). When an
|
||||
older server omits it, clients should assume `"credit"`.
|
||||
|
||||
# Item history anchors
|
||||
|
||||
Live notifications and turn history return the same `ThreadItem`. Each item has
|
||||
|
||||
@@ -17,6 +17,7 @@ use codex_login::LoginOnboardingEntrypoint;
|
||||
use codex_login::login_with_bedrock_access_keys;
|
||||
use codex_mcp::ema_auth_scope;
|
||||
use codex_model_provider::is_supported_amazon_bedrock_region;
|
||||
use codex_model_provider::provider_uses_first_party_auth_path;
|
||||
use codex_otel::auth_storage::AuthStorageOriginator;
|
||||
use codex_rmcp_client::EnterpriseOAuthCredentialGuard;
|
||||
|
||||
@@ -28,6 +29,7 @@ mod gateway_oauth;
|
||||
mod gcp_setup;
|
||||
mod rate_limit_resets;
|
||||
mod security_setup;
|
||||
mod usage;
|
||||
mod voice_settings;
|
||||
mod workspace_routing;
|
||||
mod workspace_switching;
|
||||
@@ -1210,6 +1212,42 @@ impl AccountRequestProcessor {
|
||||
&self,
|
||||
params: GetAccountRateLimitsParams,
|
||||
) -> Result<GetAccountRateLimitsResponse, JSONRPCErrorError> {
|
||||
if let Some(thread_id) = params.thread_id.as_deref() {
|
||||
let thread_id = ThreadId::from_string(thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
|
||||
let thread = self
|
||||
.thread_manager
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
|
||||
let config = thread.config().await;
|
||||
self.config_manager
|
||||
.check_thread_model_provider(&config)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
if config.model_provider.usage_url.is_some() {
|
||||
return usage::read(&config, Arc::clone(&self.auth_manager)).await;
|
||||
}
|
||||
if !provider_uses_first_party_auth_path(&config.model_provider) {
|
||||
let mut error = invalid_request(format!(
|
||||
"usage is unavailable for model provider `{}`",
|
||||
config.model_provider_id
|
||||
));
|
||||
error.data = Some(serde_json::json!({ "reason": "usageUnavailable" }));
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
|
||||
// Thread overrides select the provider, but must not redirect ChatGPT account credentials.
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
if params.thread_id.is_none() && config.model_provider.usage_url.is_some() {
|
||||
return usage::read(&config, Arc::clone(&self.auth_manager)).await;
|
||||
}
|
||||
|
||||
let Some((auth, http_client_factory)) =
|
||||
self.auth_manager.auth_with_http_client_factory().await
|
||||
else {
|
||||
@@ -1224,7 +1262,9 @@ impl AccountRequestProcessor {
|
||||
));
|
||||
}
|
||||
|
||||
let client = self.backend_client(&auth, http_client_factory).await?;
|
||||
let client = self
|
||||
.backend_client_for_config(&config, &auth, http_client_factory)
|
||||
.await?;
|
||||
|
||||
let usage_request = async {
|
||||
if params.supports_luna_reserve
|
||||
|
||||
@@ -13,9 +13,21 @@ impl AccountRequestProcessor {
|
||||
) -> BoxFuture<'a, Result<BackendClient, JSONRPCErrorError>> {
|
||||
Box::pin(async move {
|
||||
let config = self.load_latest_config().await;
|
||||
self.backend_client_for_config(&config, auth, http_client_factory)
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn backend_client_for_config<'a>(
|
||||
&'a self,
|
||||
config: &'a Config,
|
||||
auth: &'a CodexAuth,
|
||||
http_client_factory: codex_http_client::HttpClientFactory,
|
||||
) -> BoxFuture<'a, Result<BackendClient, JSONRPCErrorError>> {
|
||||
Box::pin(async move {
|
||||
let runtime = self
|
||||
.thread_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.runtime_auth_for_config(config)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
BackendClient::from_auth_with_runtime(
|
||||
config.chatgpt_base_url.clone(),
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Map provider spend to account rate limits.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::RateLimitSnapshot;
|
||||
use codex_app_server_protocol::SpendControlLimitSnapshot;
|
||||
use codex_app_server_protocol::SpendControlUnit;
|
||||
|
||||
pub(super) async fn read(
|
||||
config: &Config,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
) -> Result<GetAccountRateLimitsResponse, JSONRPCErrorError> {
|
||||
let spend = codex_model_provider::read_provider_usage(
|
||||
&config.model_provider,
|
||||
auth_manager,
|
||||
config.http_client_factory(),
|
||||
)
|
||||
.await
|
||||
.map_err(internal_error)?;
|
||||
let limit_id = config.model_provider_id.clone();
|
||||
let snapshot = RateLimitSnapshot {
|
||||
limit_id: Some(limit_id.clone()),
|
||||
limit_name: Some(config.model_provider.name.clone()),
|
||||
normal_model_slug: None,
|
||||
primary: None,
|
||||
secondary: None,
|
||||
credits: None,
|
||||
individual_limit: Some(SpendControlLimitSnapshot {
|
||||
unit: SpendControlUnit::Usd,
|
||||
limit: spend.limit_usd.unwrap_or_else(|| "unlimited".to_string()),
|
||||
used: spend.used_usd,
|
||||
remaining_percent: 100 - spend.used_percent.unwrap_or(0),
|
||||
resets_at: spend.resets_at,
|
||||
}),
|
||||
spend_control_reached: Some(spend.reached),
|
||||
plan_type: None,
|
||||
rate_limit_reached_type: None,
|
||||
};
|
||||
Ok(GetAccountRateLimitsResponse {
|
||||
rate_limits: snapshot.clone(),
|
||||
rate_limits_by_limit_id: Some(HashMap::from([(limit_id, snapshot)])),
|
||||
ordinary_usage_allowed: None,
|
||||
rate_limit_reset_credits: None,
|
||||
account_id: None,
|
||||
rate_limit_upsell: None,
|
||||
})
|
||||
}
|
||||
@@ -872,3 +872,114 @@ async fn selected_gateway_read_notifies_matching_providers() -> Result<()> {
|
||||
assert!(oauth.received_requests().await.unwrap().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_usage_uses_existing_oauth_session_without_interactive_login() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let gateway = MockServer::start().await;
|
||||
let url = gateway.uri();
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
r#"
|
||||
model_provider = "gateway"
|
||||
[model_providers.gateway]
|
||||
name = "Test gateway"
|
||||
base_url = "{url}/v1"
|
||||
usage_url = "{url}/v1/usage/me"
|
||||
[model_providers.gateway.gateway_oauth]
|
||||
authorization_url = "{url}/authorize"
|
||||
token_url = "{url}/token"
|
||||
client_id = "usage-test"
|
||||
credentials_store = "file"
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/v1/usage/me"))
|
||||
.and(wiremock::matchers::header(
|
||||
"authorization",
|
||||
"Bearer gateway-access",
|
||||
))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(/*s*/ 200).set_body_json(serde_json::json!({
|
||||
"reached": false,
|
||||
"usage_periods": [{
|
||||
"period": "month",
|
||||
"period_start": 1793491200,
|
||||
"period_end": 1796083200,
|
||||
"current_usage_amount": {"amount": "8.95", "unit": "usd"},
|
||||
"effective_usage_limit": {"amount": "10.00", "unit": "usd"}
|
||||
}]
|
||||
})),
|
||||
)
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&gateway)
|
||||
.await;
|
||||
let mut server = gateway_server(home.path()).await?;
|
||||
let request = server.send_get_account_rate_limits_request().await?;
|
||||
let error = timeout(
|
||||
TIMEOUT,
|
||||
server.read_stream_until_error_message(RequestId::Integer(request)),
|
||||
)
|
||||
.await??;
|
||||
assert!(error.error.message.contains("Sign in to the gateway"));
|
||||
assert!(
|
||||
gateway
|
||||
.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|req| !matches!(req.url.path(), "/authorize" | "/token" | "/v1/usage/me"))
|
||||
);
|
||||
|
||||
login_to_gateway(&mut server, &gateway).await?;
|
||||
let request = server.send_get_account_rate_limits_request().await?;
|
||||
let raw: serde_json::Value = timeout(TIMEOUT, server.read_response(request)).await??;
|
||||
assert!(raw.get("usage").is_none());
|
||||
let result: codex_app_server_protocol::GetAccountRateLimitsResponse =
|
||||
serde_json::from_value(raw)?;
|
||||
let started = server.start_thread(ThreadStartParams::default()).await?;
|
||||
let request = server
|
||||
.send_request(
|
||||
"account/rateLimits/read",
|
||||
Some(serde_json::json!({"threadId": started.thread.id})),
|
||||
)
|
||||
.await?;
|
||||
let scoped: codex_app_server_protocol::GetAccountRateLimitsResponse =
|
||||
timeout(TIMEOUT, server.read_response(request)).await??;
|
||||
assert_eq!(scoped, result);
|
||||
let snapshot = codex_app_server_protocol::RateLimitSnapshot {
|
||||
limit_id: Some("gateway".into()),
|
||||
limit_name: Some("Test gateway".into()),
|
||||
normal_model_slug: None,
|
||||
primary: None,
|
||||
secondary: None,
|
||||
credits: None,
|
||||
individual_limit: Some(codex_app_server_protocol::SpendControlLimitSnapshot {
|
||||
unit: codex_app_server_protocol::SpendControlUnit::Usd,
|
||||
limit: "10.00".into(),
|
||||
used: "8.95".into(),
|
||||
remaining_percent: 10,
|
||||
resets_at: 1796083200,
|
||||
}),
|
||||
spend_control_reached: Some(false),
|
||||
plan_type: None,
|
||||
rate_limit_reached_type: None,
|
||||
};
|
||||
assert_eq!(
|
||||
result,
|
||||
codex_app_server_protocol::GetAccountRateLimitsResponse {
|
||||
rate_limits: snapshot.clone(),
|
||||
rate_limits_by_limit_id: Some(std::collections::HashMap::from([(
|
||||
"gateway".into(),
|
||||
snapshot
|
||||
)])),
|
||||
ordinary_usage_allowed: None,
|
||||
rate_limit_reset_credits: None,
|
||||
account_id: None,
|
||||
rate_limit_upsell: None,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -141,6 +141,10 @@ base_url = "{}/v1"
|
||||
};
|
||||
for (method, params) in [
|
||||
("thread/resume", json!({"threadId": started.thread.id})),
|
||||
(
|
||||
"account/rateLimits/read",
|
||||
json!({"threadId": started.thread.id}),
|
||||
),
|
||||
(
|
||||
"thread/guardianReview",
|
||||
json!({"threadId": started.thread.id, "toolCall": {
|
||||
|
||||
@@ -22,10 +22,13 @@ use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::SendAddCreditsNudgeEmailParams;
|
||||
use codex_app_server_protocol::SendAddCreditsNudgeEmailResponse;
|
||||
use codex_app_server_protocol::SpendControlLimitSnapshot;
|
||||
use codex_app_server_protocol::SpendControlUnit;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_protocol::account::PlanType as AccountPlanType;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
use test_case::test_case;
|
||||
@@ -101,6 +104,7 @@ async fn get_account_rate_limits_requires_chatgpt_auth() -> Result<()> {
|
||||
}
|
||||
|
||||
#[test_case("enterprise_cbp_automation", AccountPlanType::EnterpriseCbpAutomation; "enterprise_automation")]
|
||||
#[test_case("ent26", AccountPlanType::Ent26; "enterprise_usd")]
|
||||
#[test_case("promax", AccountPlanType::ProMax; "pro_max")]
|
||||
#[test_case("edu_plus", AccountPlanType::EduPlus; "edu_plus")]
|
||||
#[test_case("edu_pro", AccountPlanType::EduPro; "edu_pro")]
|
||||
@@ -148,7 +152,7 @@ async fn get_account_rate_limits_returns_snapshot(
|
||||
"description": "View your usage.",
|
||||
"ctas": [{"action": "view_usage", "label": "View usage"}]
|
||||
});
|
||||
let response_body = json!({
|
||||
let mut response_body = json!({
|
||||
"account_id": "account-123",
|
||||
"user_id": "user-123",
|
||||
"rate_limit_upsell": banner,
|
||||
@@ -204,6 +208,12 @@ async fn get_account_rate_limits_returns_snapshot(
|
||||
],
|
||||
"rate_limit_reset_credits": { "available_count": 3 }
|
||||
});
|
||||
let expected_unit = if expected_plan == AccountPlanType::Ent26 {
|
||||
response_body["spend_control"]["individual_limit"]["unit"] = json!("usd");
|
||||
SpendControlUnit::Usd
|
||||
} else {
|
||||
SpendControlUnit::Credit
|
||||
};
|
||||
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/api/codex/usage"))
|
||||
@@ -283,6 +293,7 @@ async fn get_account_rate_limits_returns_snapshot(
|
||||
}),
|
||||
credits: None,
|
||||
individual_limit: Some(SpendControlLimitSnapshot {
|
||||
unit: expected_unit,
|
||||
limit: "25000".to_string(),
|
||||
used: "8000".to_string(),
|
||||
remaining_percent: 68,
|
||||
@@ -312,6 +323,7 @@ async fn get_account_rate_limits_returns_snapshot(
|
||||
}),
|
||||
credits: None,
|
||||
individual_limit: Some(SpendControlLimitSnapshot {
|
||||
unit: expected_unit,
|
||||
limit: "25000".to_string(),
|
||||
used: "8000".to_string(),
|
||||
remaining_percent: 68,
|
||||
@@ -1093,3 +1105,334 @@ async fn security_setup_requires_matching_saved_chatgpt_login(kind: &str) -> Res
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_account_rate_limits_selects_the_loaded_threads_provider() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
write_chatgpt_auth(
|
||||
home.path(),
|
||||
ChatGptAuthFixture::new("chatgpt-token")
|
||||
.account_id("account-123")
|
||||
.plan_type("pro"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
let account = MockServer::start().await;
|
||||
let gateway = MockServer::start().await;
|
||||
write_chatgpt_base_url(home.path(), &account.uri())?;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/api/codex/usage"))
|
||||
.and(header("authorization", "Bearer chatgpt-token"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"account_id": "account-123",
|
||||
"plan_type": "pro",
|
||||
"rate_limit": {
|
||||
"allowed": true, "limit_reached": false,
|
||||
"primary_window": {
|
||||
"used_percent": 42, "limit_window_seconds": 3600,
|
||||
"reset_after_seconds": 120, "reset_at": 1735689720
|
||||
}
|
||||
}
|
||||
})))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&account)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/thread-usage"))
|
||||
.and(header("authorization", "Bearer gateway-token"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"reached": false,
|
||||
"usage_periods": [{
|
||||
"period": "month", "period_start": 1793491200, "period_end": 1796083200,
|
||||
"current_usage_amount": {"amount": "12.00", "unit": "usd"},
|
||||
"effective_usage_limit": {"amount": "20.00", "unit": "usd"}
|
||||
}]
|
||||
})))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&gateway)
|
||||
.await;
|
||||
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(app_test_support::CLEARED_OPENAI_AUTH_ENV)
|
||||
.with_env_overrides(&[("GATEWAY_TEST_TOKEN", Some("gateway-token"))])
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
.await?;
|
||||
// The account client must not send ChatGPT credentials to a thread-supplied destination.
|
||||
let first_party = app
|
||||
.start_thread(ThreadStartParams {
|
||||
config: Some(HashMap::from([(
|
||||
"chatgpt_base_url".into(),
|
||||
json!(gateway.uri()),
|
||||
)])),
|
||||
..Default::default()
|
||||
})
|
||||
.await?
|
||||
.thread;
|
||||
// This provider definition exists only in the thread's configuration.
|
||||
let custom = app
|
||||
.start_thread(ThreadStartParams {
|
||||
model_provider: Some("custom".into()),
|
||||
config: Some(HashMap::from([(
|
||||
"model_providers.custom".into(),
|
||||
json!({
|
||||
"name": "Thread gateway",
|
||||
"base_url": format!("{}/v1", gateway.uri()),
|
||||
"usage_url": format!("{}/thread-usage", gateway.uri()),
|
||||
"env_key": "GATEWAY_TEST_TOKEN"
|
||||
}),
|
||||
)])),
|
||||
..Default::default()
|
||||
})
|
||||
.await?
|
||||
.thread;
|
||||
let unsupported = app
|
||||
.start_thread(ThreadStartParams {
|
||||
model_provider: Some("no-usage".into()),
|
||||
config: Some(HashMap::from([(
|
||||
"model_providers.no-usage".into(),
|
||||
json!({
|
||||
"name": "No usage",
|
||||
"base_url": format!("{}/v1", gateway.uri()),
|
||||
"env_key": "GATEWAY_TEST_TOKEN"
|
||||
}),
|
||||
)])),
|
||||
..Default::default()
|
||||
})
|
||||
.await?
|
||||
.thread;
|
||||
|
||||
let method = "account/rateLimits/read";
|
||||
let request = app
|
||||
.send_request(
|
||||
method,
|
||||
Some(json!({
|
||||
"threadId": null, "excludeResetCreditDetails": true
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
let global: GetAccountRateLimitsResponse = app.read_response(request).await?;
|
||||
assert_eq!(global.account_id.as_deref(), Some("account-123"));
|
||||
|
||||
let request = app
|
||||
.send_request(method, Some(json!({"threadId": custom.id})))
|
||||
.await?;
|
||||
let scoped: GetAccountRateLimitsResponse = app.read_response(request).await?;
|
||||
assert_eq!(scoped.rate_limits.limit_id.as_deref(), Some("custom"));
|
||||
assert_eq!(
|
||||
scoped.rate_limits.individual_limit,
|
||||
Some(SpendControlLimitSnapshot {
|
||||
unit: SpendControlUnit::Usd,
|
||||
limit: "20.00".into(),
|
||||
used: "12.00".into(),
|
||||
remaining_percent: 40,
|
||||
resets_at: 1796083200,
|
||||
})
|
||||
);
|
||||
|
||||
// Change the default, including the definition of the same provider id.
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
r#"
|
||||
chatgpt_base_url = "{backend}"
|
||||
model_provider = "custom"
|
||||
[model_providers.custom]
|
||||
name = "Global gateway"
|
||||
base_url = "{gateway}/v1"
|
||||
usage_url = "{gateway}/global-usage"
|
||||
env_key = "GATEWAY_TEST_TOKEN"
|
||||
"#,
|
||||
backend = account.uri(),
|
||||
gateway = gateway.uri()
|
||||
),
|
||||
)?;
|
||||
let request = app
|
||||
.send_request(
|
||||
method,
|
||||
Some(json!({
|
||||
"threadId": first_party.id, "excludeResetCreditDetails": true
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
let from_first_party: GetAccountRateLimitsResponse = app.read_response(request).await?;
|
||||
assert_eq!(from_first_party, global);
|
||||
let request = app
|
||||
.send_request(method, Some(json!({"threadId": custom.id})))
|
||||
.await?;
|
||||
let from_custom: GetAccountRateLimitsResponse = app.read_response(request).await?;
|
||||
assert_eq!(from_custom, scoped);
|
||||
|
||||
for (thread_id, message, expected_data) in [
|
||||
(
|
||||
unsupported.id.as_str(),
|
||||
"usage is unavailable",
|
||||
Some(json!({ "reason": "usageUnavailable" })),
|
||||
),
|
||||
("not-a-thread", "invalid thread id", None),
|
||||
(
|
||||
"00000000-0000-4000-8000-000000000001",
|
||||
"thread not found",
|
||||
None,
|
||||
),
|
||||
] {
|
||||
let request = app
|
||||
.send_request(method, Some(json!({"threadId": thread_id})))
|
||||
.await?;
|
||||
let error = app
|
||||
.read_stream_until_error_message(RequestId::Integer(request))
|
||||
.await?;
|
||||
assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE);
|
||||
assert_eq!(error.error.data, expected_data);
|
||||
assert!(
|
||||
error.error.message.contains(message),
|
||||
"{}",
|
||||
error.error.message
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
gateway
|
||||
.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|req| {
|
||||
!matches!(
|
||||
req.url.path(),
|
||||
"/global-usage" | "/api/codex/usage" | "/api/codex/rate-limit-reset-credits"
|
||||
)
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_usage_takes_precedence_over_chatgpt_and_never_falls_back() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
write_chatgpt_auth(
|
||||
home.path(),
|
||||
ChatGptAuthFixture::new("chatgpt-token")
|
||||
.account_id("account-123")
|
||||
.plan_type("pro"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
let account = MockServer::start().await;
|
||||
let provider = MockServer::start().await;
|
||||
let other = MockServer::start().await;
|
||||
let config_path = home.path().join("config.toml");
|
||||
write_chatgpt_base_url(home.path(), &account.uri())?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.without_auto_env()
|
||||
.with_env_overrides(app_test_support::CLEARED_OPENAI_AUTH_ENV)
|
||||
.with_env_overrides(&[("GATEWAY_TEST_TOKEN", Some("gateway-token"))])
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
.await?;
|
||||
let config = |endpoint: &str| {
|
||||
format!(
|
||||
r#"
|
||||
chatgpt_base_url = "{backend}"
|
||||
model_provider = "custom"
|
||||
[model_providers.custom]
|
||||
name = "Gateway"
|
||||
base_url = "{gateway}/v1"
|
||||
usage_url = "{gateway}/{endpoint}?key=private-query"
|
||||
env_key = "GATEWAY_TEST_TOKEN"
|
||||
query_params = {{ tenant = "sample" }}
|
||||
"#,
|
||||
backend = account.uri(),
|
||||
gateway = provider.uri()
|
||||
)
|
||||
};
|
||||
|
||||
for (endpoint, limit, reached) in [
|
||||
("spend", json!(null), false),
|
||||
("near-cap", json!({"amount": "12.35", "unit": "usd"}), false),
|
||||
("zero", json!({"amount": "0.00", "unit": "usd"}), true),
|
||||
] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/{endpoint}")))
|
||||
.and(wiremock::matchers::query_param("key", "private-query"))
|
||||
.and(wiremock::matchers::query_param("tenant", "sample"))
|
||||
.and(header("authorization", "Bearer gateway-token"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"reached": reached,
|
||||
"usage_periods": [{
|
||||
"period": "month", "period_start": 1793491200, "period_end": 1796083200,
|
||||
"current_usage_amount": {"amount": "12.3456789", "unit": "usd"},
|
||||
"effective_usage_limit": limit
|
||||
}]
|
||||
})))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&provider)
|
||||
.await;
|
||||
}
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/broken"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 403).set_body_string("private-response-body"))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&provider)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/redirect"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(/*s*/ 307)
|
||||
.insert_header("location", format!("{}/token", other.uri())),
|
||||
)
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&provider)
|
||||
.await;
|
||||
for (endpoint, limit, remaining_percent, reached) in [
|
||||
("spend", "unlimited", 100, false),
|
||||
("near-cap", "12.35", 0, false),
|
||||
("zero", "0.00", 0, true),
|
||||
] {
|
||||
std::fs::write(&config_path, config(endpoint))?;
|
||||
let request = app.send_get_account_rate_limits_request().await?;
|
||||
let response: GetAccountRateLimitsResponse =
|
||||
timeout(DEFAULT_READ_TIMEOUT, app.read_response(request)).await??;
|
||||
assert_eq!(
|
||||
response.rate_limits.individual_limit,
|
||||
Some(SpendControlLimitSnapshot {
|
||||
unit: SpendControlUnit::Usd,
|
||||
limit: limit.to_string(),
|
||||
used: "12.3456789".into(),
|
||||
remaining_percent,
|
||||
resets_at: 1796083200,
|
||||
})
|
||||
);
|
||||
assert_eq!(response.rate_limits.spend_control_reached, Some(reached));
|
||||
assert_eq!(response.rate_limits.primary, None);
|
||||
assert_eq!(response.account_id, None);
|
||||
}
|
||||
for endpoint in ["broken", "redirect"] {
|
||||
std::fs::write(&config_path, config(endpoint))?;
|
||||
let request = app.send_get_account_rate_limits_request().await?;
|
||||
let error: JSONRPCError = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
app.read_stream_until_error_message(RequestId::Integer(request)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(error.error.code, INTERNAL_ERROR_CODE);
|
||||
assert_eq!(error.error.data, None);
|
||||
assert!(!error.error.message.contains("private-"));
|
||||
assert!(!error.error.message.contains("gateway-token"));
|
||||
if endpoint == "broken" {
|
||||
assert!(error.error.message.contains("403"));
|
||||
}
|
||||
}
|
||||
assert!(other.received_requests().await.unwrap().is_empty());
|
||||
assert!(
|
||||
account
|
||||
.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|req| {
|
||||
!matches!(
|
||||
req.url.path(),
|
||||
"/api/codex/usage" | "/api/codex/rate-limit-reset-credits"
|
||||
)
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ use codex_protocol::protocol::RateLimitReachedType;
|
||||
use codex_protocol::protocol::RateLimitSnapshot;
|
||||
use codex_protocol::protocol::RateLimitWindow;
|
||||
use codex_protocol::protocol::SpendControlLimitSnapshot;
|
||||
use codex_protocol::protocol::SpendControlUnit;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use http::Method;
|
||||
use http::StatusCode;
|
||||
@@ -754,7 +755,7 @@ impl Client {
|
||||
let spend_control_reached = spend_control.as_ref().map(|details| details.reached);
|
||||
let individual_limit = spend_control
|
||||
.and_then(|details| details.individual_limit.flatten())
|
||||
.map(|details| Self::map_individual_limit(*details));
|
||||
.and_then(|details| Self::map_individual_limit(*details));
|
||||
RateLimitSnapshot {
|
||||
limit_id,
|
||||
limit_name,
|
||||
@@ -848,13 +849,20 @@ impl Client {
|
||||
|
||||
fn map_individual_limit(
|
||||
details: crate::types::SpendControlLimitDetails,
|
||||
) -> SpendControlLimitSnapshot {
|
||||
SpendControlLimitSnapshot {
|
||||
) -> Option<SpendControlLimitSnapshot> {
|
||||
let unit = match details.unit.as_deref() {
|
||||
None | Some("credit") => SpendControlUnit::Credit,
|
||||
Some("usd") => SpendControlUnit::Usd,
|
||||
// Keep the rest of the account snapshot without mislabeling an unknown unit.
|
||||
Some(_) => return None,
|
||||
};
|
||||
Some(SpendControlLimitSnapshot {
|
||||
unit,
|
||||
limit: details.limit,
|
||||
used: details.used,
|
||||
remaining_percent: details.remaining_percent,
|
||||
resets_at: i64::from(details.reset_at),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn map_plan_type(plan_type: crate::types::PlanType) -> AccountPlanType {
|
||||
@@ -993,6 +1001,7 @@ mod tests {
|
||||
individual_limit: Some(Some(Box::new(
|
||||
crate::types::SpendControlLimitDetails {
|
||||
source: None,
|
||||
unit: Some("usd".to_string()),
|
||||
limit: "25000".to_string(),
|
||||
used: "8000".to_string(),
|
||||
remaining: "17000".to_string(),
|
||||
@@ -1039,6 +1048,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
snapshots[0].individual_limit,
|
||||
Some(SpendControlLimitSnapshot {
|
||||
unit: SpendControlUnit::Usd,
|
||||
limit: "25000".to_string(),
|
||||
used: "8000".to_string(),
|
||||
remaining_percent: 68,
|
||||
|
||||
@@ -20,6 +20,8 @@ pub struct SpendControlLimitDetails {
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub source: Option<Option<String>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub unit: Option<String>,
|
||||
#[serde(rename = "limit")]
|
||||
pub limit: String,
|
||||
#[serde(rename = "used")]
|
||||
@@ -48,6 +50,7 @@ impl SpendControlLimitDetails {
|
||||
) -> SpendControlLimitDetails {
|
||||
SpendControlLimitDetails {
|
||||
source: None,
|
||||
unit: None,
|
||||
limit,
|
||||
used,
|
||||
remaining,
|
||||
|
||||
@@ -6,6 +6,7 @@ use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::CreditsSnapshot;
|
||||
use codex_protocol::protocol::RateLimitWindow;
|
||||
use codex_protocol::protocol::SpendControlLimitSnapshot;
|
||||
use codex_protocol::protocol::SpendControlUnit;
|
||||
use codex_protocol::protocol::TokenUsage;
|
||||
use codex_protocol::protocol::TokenUsageRecord;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -207,6 +208,7 @@ async fn set_rate_limits_carries_account_metadata_from_codex_to_codex_other() {
|
||||
balance: Some("50".to_string()),
|
||||
}),
|
||||
individual_limit: Some(SpendControlLimitSnapshot {
|
||||
unit: SpendControlUnit::Credit,
|
||||
limit: "25000".to_string(),
|
||||
used: "8000".to_string(),
|
||||
remaining_percent: 68,
|
||||
@@ -252,6 +254,7 @@ async fn set_rate_limits_carries_account_metadata_from_codex_to_codex_other() {
|
||||
balance: Some("50".to_string()),
|
||||
}),
|
||||
individual_limit: Some(SpendControlLimitSnapshot {
|
||||
unit: SpendControlUnit::Credit,
|
||||
limit: "25000".to_string(),
|
||||
used: "8000".to_string(),
|
||||
remaining_percent: 68,
|
||||
|
||||
@@ -2768,8 +2768,19 @@ pub struct CreditsSnapshot {
|
||||
pub balance: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/", rename_all = "camelCase")]
|
||||
pub enum SpendControlUnit {
|
||||
#[default]
|
||||
Credit,
|
||||
Usd,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
|
||||
pub struct SpendControlLimitSnapshot {
|
||||
#[serde(default)]
|
||||
pub unit: SpendControlUnit,
|
||||
pub limit: String,
|
||||
pub used: String,
|
||||
pub remaining_percent: i32,
|
||||
|
||||
@@ -867,6 +867,7 @@ pub(super) async fn fetch_account_rate_limits(
|
||||
.request_typed(ClientRequest::GetAccountRateLimits {
|
||||
request_id: request_id.clone(),
|
||||
params: Some(GetAccountRateLimitsParams {
|
||||
thread_id: None,
|
||||
supports_luna_reserve: true,
|
||||
exclude_reset_credit_details: origin == RateLimitRefreshOrigin::Periodic,
|
||||
}),
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::chatwidget::rate_limits::NUDGE_MODEL_SLUG;
|
||||
use crate::chatwidget::rate_limits::get_limits_duration;
|
||||
use crate::chatwidget::realtime::tests::activate_voice_for_thread;
|
||||
use codex_app_server_protocol::SpendControlLimitSnapshot;
|
||||
use codex_app_server_protocol::SpendControlUnit;
|
||||
use codex_app_server_protocol::ThreadUsage;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::Terminal;
|
||||
@@ -1214,6 +1215,7 @@ async fn rolling_rate_limit_snapshot_preserves_prior_individual_limit() {
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
let mut usage_limits = snapshot(/*percent*/ 10.0);
|
||||
usage_limits.individual_limit = Some(SpendControlLimitSnapshot {
|
||||
unit: SpendControlUnit::Credit,
|
||||
limit: "25000".to_string(),
|
||||
used: "8000".to_string(),
|
||||
remaining_percent: 68,
|
||||
|
||||
@@ -30,6 +30,7 @@ use codex_app_server_protocol::CreditsSnapshot;
|
||||
use codex_app_server_protocol::RateLimitSnapshot;
|
||||
use codex_app_server_protocol::RateLimitWindow;
|
||||
use codex_app_server_protocol::SpendControlLimitSnapshot;
|
||||
use codex_app_server_protocol::SpendControlUnit;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
@@ -1080,6 +1081,7 @@ async fn status_snapshot_includes_enterprise_monthly_credit_limit() {
|
||||
secondary: None,
|
||||
credits: None,
|
||||
individual_limit: Some(SpendControlLimitSnapshot {
|
||||
unit: SpendControlUnit::Credit,
|
||||
limit: "25000".to_string(),
|
||||
used: "8000".to_string(),
|
||||
remaining_percent: 68,
|
||||
|
||||
@@ -2033,6 +2033,13 @@ class GetAccountRateLimitsParams(BaseModel):
|
||||
description="The client supports automatic Luna Reserve fallback. For eligible ChatGPT CLI users, allow the backend to record experiment exposure after ordinary usage is blocked.",
|
||||
),
|
||||
] = None
|
||||
thread_id: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
alias="threadId",
|
||||
description="Use the loaded thread's provider for this account-wide read. Omit for the default provider.",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class GetAccountSecuritySetupResponse(BaseModel):
|
||||
@@ -5416,14 +5423,9 @@ class SortDirection(Enum):
|
||||
desc = "desc"
|
||||
|
||||
|
||||
class SpendControlLimitSnapshot(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
limit: str
|
||||
remaining_percent: Annotated[int, Field(alias="remainingPercent")]
|
||||
resets_at: Annotated[int, Field(alias="resetsAt")]
|
||||
used: str
|
||||
class SpendControlUnit(Enum):
|
||||
credit = "credit"
|
||||
usd = "usd"
|
||||
|
||||
|
||||
class StartupGatewayOAuthChangedNotification(BaseModel):
|
||||
@@ -10187,38 +10189,6 @@ class RateLimitResetCreditsSummary(BaseModel):
|
||||
] = None
|
||||
|
||||
|
||||
class RateLimitSnapshot(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
credits: CreditsSnapshot | None = None
|
||||
individual_limit: Annotated[
|
||||
SpendControlLimitSnapshot | None, Field(alias="individualLimit")
|
||||
] = None
|
||||
limit_id: Annotated[str | None, Field(alias="limitId")] = None
|
||||
limit_name: Annotated[str | None, Field(alias="limitName")] = None
|
||||
normal_model_slug: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
alias="normalModelSlug",
|
||||
description="Normal model whose display name and reasoning options describe this quota alias.",
|
||||
),
|
||||
] = None
|
||||
plan_type: Annotated[PlanType | None, Field(alias="planType")] = None
|
||||
primary: RateLimitWindow | None = None
|
||||
rate_limit_reached_type: Annotated[
|
||||
RateLimitReachedType | None, Field(alias="rateLimitReachedType")
|
||||
] = None
|
||||
secondary: RateLimitWindow | None = None
|
||||
spend_control_reached: Annotated[
|
||||
bool | None,
|
||||
Field(
|
||||
alias="spendControlReached",
|
||||
description="Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class RawResponseCompletedNotification(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
@@ -11014,6 +10984,30 @@ class SkillsListResponse(BaseModel):
|
||||
data: list[SkillsListEntry]
|
||||
|
||||
|
||||
class SpendControlLimitSnapshot(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
limit: Annotated[
|
||||
str, Field(description='Decimal amount, or "unlimited" when the provider has no spend cap.')
|
||||
]
|
||||
remaining_percent: Annotated[
|
||||
int,
|
||||
Field(
|
||||
alias="remainingPercent",
|
||||
description="For an unlimited cap this is 100 for compatibility. Ignore it for display and warnings.",
|
||||
),
|
||||
]
|
||||
resets_at: Annotated[int, Field(alias="resetsAt")]
|
||||
unit: Annotated[
|
||||
SpendControlUnit | None,
|
||||
Field(
|
||||
description="Unit of `used` and any numeric `limit`. Older servers omit this for credits."
|
||||
),
|
||||
] = "credit"
|
||||
used: str
|
||||
|
||||
|
||||
class ThreadSpawn(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
@@ -11909,13 +11903,6 @@ class WorkspaceMessage(BaseModel):
|
||||
message_type: Annotated[WorkspaceMessageType, Field(alias="messageType")]
|
||||
|
||||
|
||||
class AccountRateLimitsUpdatedNotification(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
rate_limits: Annotated[RateLimitSnapshot, Field(alias="rateLimits")]
|
||||
|
||||
|
||||
class AccountSession(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
@@ -12402,50 +12389,6 @@ class FunctionCallOutputBody(RootModel[str | list[FunctionCallOutputContentItem]
|
||||
root: str | list[FunctionCallOutputContentItem]
|
||||
|
||||
|
||||
class GetAccountRateLimitsResponse(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
account_id: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
alias="accountId",
|
||||
description="Account associated with this usage snapshot, when supplied by the backend.",
|
||||
),
|
||||
] = None
|
||||
ordinary_usage_allowed: Annotated[
|
||||
bool | None,
|
||||
Field(
|
||||
alias="ordinaryUsageAllowed",
|
||||
description="Backend permission for ordinary included usage, validated against the active account. Null means unavailable; clients must not infer recovery from percentages or reset times.",
|
||||
),
|
||||
] = None
|
||||
rate_limit_reset_credits: Annotated[
|
||||
RateLimitResetCreditsSummary | None, Field(alias="rateLimitResetCredits")
|
||||
] = None
|
||||
rate_limit_upsell: Annotated[
|
||||
Any | None,
|
||||
Field(
|
||||
alias="rateLimitUpsell",
|
||||
description="Optional backend-owned banner from the same usage read. Its nested keys retain the backend's snake_case contract; an absent banner leaves the client's existing UI unchanged.",
|
||||
),
|
||||
] = None
|
||||
rate_limits: Annotated[
|
||||
RateLimitSnapshot,
|
||||
Field(
|
||||
alias="rateLimits",
|
||||
description="Backward-compatible single-bucket view; mirrors the historical payload.",
|
||||
),
|
||||
]
|
||||
rate_limits_by_limit_id: Annotated[
|
||||
dict[str, Any] | None,
|
||||
Field(
|
||||
alias="rateLimitsByLimitId",
|
||||
description="Multi-bucket view keyed by metered `limit_id` (for example, `codex`).",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class GetAccountTokenUsageResponse(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
@@ -12628,6 +12571,38 @@ class PluginSummary(BaseModel):
|
||||
] = None
|
||||
|
||||
|
||||
class RateLimitSnapshot(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
credits: CreditsSnapshot | None = None
|
||||
individual_limit: Annotated[
|
||||
SpendControlLimitSnapshot | None, Field(alias="individualLimit")
|
||||
] = None
|
||||
limit_id: Annotated[str | None, Field(alias="limitId")] = None
|
||||
limit_name: Annotated[str | None, Field(alias="limitName")] = None
|
||||
normal_model_slug: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
alias="normalModelSlug",
|
||||
description="Normal model whose display name and reasoning options describe this quota alias.",
|
||||
),
|
||||
] = None
|
||||
plan_type: Annotated[PlanType | None, Field(alias="planType")] = None
|
||||
primary: RateLimitWindow | None = None
|
||||
rate_limit_reached_type: Annotated[
|
||||
RateLimitReachedType | None, Field(alias="rateLimitReachedType")
|
||||
] = None
|
||||
secondary: RateLimitWindow | None = None
|
||||
spend_control_reached: Annotated[
|
||||
bool | None,
|
||||
Field(
|
||||
alias="spendControlReached",
|
||||
description="Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class FunctionCallOutputResponseItem(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
@@ -12836,24 +12811,6 @@ class ItemFileChangePatchUpdatedServerNotification(BaseModel):
|
||||
params: FileChangePatchUpdatedNotification
|
||||
|
||||
|
||||
class AccountRateLimitsUpdatedServerNotification(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
emitted_at_ms: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
alias="emittedAtMs",
|
||||
description="Unix timestamp (in milliseconds) when app-server emitted this notification.",
|
||||
),
|
||||
] = None
|
||||
method: Annotated[
|
||||
Literal["account/rateLimits/updated"],
|
||||
Field(title="Account/rateLimits/updatedNotificationMethod"),
|
||||
]
|
||||
params: AccountRateLimitsUpdatedNotification
|
||||
|
||||
|
||||
class AppListUpdatedServerNotification(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
@@ -13261,6 +13218,13 @@ class TurnsPage(BaseModel):
|
||||
next_cursor: Annotated[str | None, Field(alias="nextCursor")] = None
|
||||
|
||||
|
||||
class AccountRateLimitsUpdatedNotification(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
rate_limits: Annotated[RateLimitSnapshot, Field(alias="rateLimits")]
|
||||
|
||||
|
||||
class AdditionalFileSystemPermissions(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
@@ -13455,6 +13419,50 @@ class ExternalAgentConfigImportParams(BaseModel):
|
||||
] = None
|
||||
|
||||
|
||||
class GetAccountRateLimitsResponse(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
account_id: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
alias="accountId",
|
||||
description="Account associated with this usage snapshot, when supplied by the backend.",
|
||||
),
|
||||
] = None
|
||||
ordinary_usage_allowed: Annotated[
|
||||
bool | None,
|
||||
Field(
|
||||
alias="ordinaryUsageAllowed",
|
||||
description="Backend permission for ordinary included usage, validated against the active account. Null means unavailable; clients must not infer recovery from percentages or reset times.",
|
||||
),
|
||||
] = None
|
||||
rate_limit_reset_credits: Annotated[
|
||||
RateLimitResetCreditsSummary | None, Field(alias="rateLimitResetCredits")
|
||||
] = None
|
||||
rate_limit_upsell: Annotated[
|
||||
Any | None,
|
||||
Field(
|
||||
alias="rateLimitUpsell",
|
||||
description="Optional backend-owned banner from the same usage read. Its nested keys retain the backend's snake_case contract; an absent banner leaves the client's existing UI unchanged.",
|
||||
),
|
||||
] = None
|
||||
rate_limits: Annotated[
|
||||
RateLimitSnapshot,
|
||||
Field(
|
||||
alias="rateLimits",
|
||||
description="Backward-compatible single-bucket view; mirrors the historical payload.",
|
||||
),
|
||||
]
|
||||
rate_limits_by_limit_id: Annotated[
|
||||
dict[str, Any] | None,
|
||||
Field(
|
||||
alias="rateLimitsByLimitId",
|
||||
description="Multi-bucket view keyed by metered `limit_id` (for example, `codex`).",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class ItemCompletedNotification(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
@@ -13655,6 +13663,24 @@ class ItemCompletedServerNotification(BaseModel):
|
||||
params: ItemCompletedNotification
|
||||
|
||||
|
||||
class AccountRateLimitsUpdatedServerNotification(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
emitted_at_ms: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
alias="emittedAtMs",
|
||||
description="Unix timestamp (in milliseconds) when app-server emitted this notification.",
|
||||
),
|
||||
] = None
|
||||
method: Annotated[
|
||||
Literal["account/rateLimits/updated"],
|
||||
Field(title="Account/rateLimits/updatedNotificationMethod"),
|
||||
]
|
||||
params: AccountRateLimitsUpdatedNotification
|
||||
|
||||
|
||||
class Thread(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
|
||||
Reference in New Issue
Block a user