返回 CodeWhale
route_billing.rs
根目录 / crates / engine / src / route_billing.rs
1 //! Route-aware billing presentation.
2 //!
3 //! Model pricing and the way a user pays for a route are different facts.
4 //! The same model can be metered through an API key or covered by an OAuth /
5 //! token-plan subscription. Keep that decision in one small module so TUI
6 //! surfaces do not infer dollars from a model id alone.
7 //!
8 //! Display rule (TUI-DOG-010):
9 //! - dollars only for metered routes with a real priced usage basis and
10 //! positive accrued spend;
11 //! - OAuth/token-plan routes show a quota label, or a real used % when one
12 //! was supplied by the provider;
13 //! - unknown stays unknown — never `$0.00` and never an estimate-as-spend.
14
15 use crate::pricing::{UnpricedReason, format_cost_amount};
16 use codewhale_config::ProviderKind;
17 use codewhale_config::pricing::CostCurrency;
18 use codewhale_localization::{Locale, MessageId, tr};
19 use codewhale_runtime::config::{Config, ProviderConfig, ProviderIdentity};
20
21 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
22 pub enum BillingPresentation {
23 /// Per-token API usage may be rendered as a currency estimate.
24 Metered,
25 /// Account/subscription quota is the truthful owner; dollar estimates are
26 /// intentionally hidden unless the provider later exposes real spend.
27 Subscription(&'static str),
28 /// The route is local or otherwise has no provider bill.
29 Local,
30 /// Billing basis is not known; never invent dollars or a fake zero.
31 Unknown,
32 }
33
34 /// Truthful chip for session/footer/sidebar usage surfaces.
35 #[derive(Debug, Clone, PartialEq)]
36 pub enum UsageChip {
37 /// Positive accrued spend on a metered route with real pricing.
38 Money(String),
39 /// Authoritatively priced portion of a mixed/legacy session whose complete
40 /// spend is unknown. The amount remains visible without being called a
41 /// total.
42 PricedSubtotal {
43 amount: String,
44 legacy: bool,
45 reasons: Vec<UnpricedReason>,
46 },
47 /// Subscription / OAuth allowance. `used_pct` is only set when the
48 /// provider supplied a real percentage.
49 Allowance {
50 label: &'static str,
51 used_pct: Option<f32>,
52 },
53 Local,
54 Unknown(Vec<UnpricedReason>),
55 /// Metered route with pricing, but nothing spent yet — omit the chip
56 /// rather than rendering `$0.00` / `<$0.0001`.
57 Hidden,
58 }
59
60 impl BillingPresentation {
61 #[must_use]
62 pub const fn shows_money(self) -> bool {
63 matches!(self, Self::Metered)
64 }
65
66 #[must_use]
67 pub const fn label(self) -> Option<&'static str> {
68 match self {
69 Self::Metered => None,
70 Self::Subscription(label) => Some(label),
71 Self::Local => Some("local"),
72 Self::Unknown => Some("unknown"),
73 }
74 }
75 }
76
77 /// Serializable mirror of [`BillingPresentation`] for crossing the child →
78 /// parent mailbox boundary. `BillingPresentation` borrows a `&'static str`
79 /// label, which serde cannot deserialize, so the token-usage envelope carries
80 /// this owned form instead. Conversion back recognizes only the labels
81 /// [`for_route`] itself produces; an unrecognized free-text label fails
82 /// closed to `Unknown` rather than inventing a quota claim.
83 ///
84 /// **Not on the production child path.** The wired child receipt is
85 /// [`crate::cost_status::EffectiveRouteEnvelope`], which carries the same
86 /// classification as a `RouteBillingMode` plus the billing surface, endpoint
87 /// fingerprint and dispatch instant, and is emitted by all three real
88 /// producers (`review`, `verify`, `rlm`) and by the sub-agent mailbox. This
89 /// owned-label mirror is retained only as the executable record of the
90 /// serialization contract; gate it with the tests so it cannot rot into a
91 /// second, drifting provenance channel.
92 #[cfg(any(test, feature = "test-support"))]
93 #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
94 #[serde(tag = "kind", rename_all = "snake_case")]
95 pub enum ChildBillingProvenance {
96 Metered,
97 Subscription { label: String },
98 Local,
99 Unknown,
100 }
101
102 #[cfg(any(test, feature = "test-support"))]
103 impl From<BillingPresentation> for ChildBillingProvenance {
104 fn from(billing: BillingPresentation) -> Self {
105 match billing {
106 BillingPresentation::Metered => Self::Metered,
107 BillingPresentation::Subscription(label) => Self::Subscription {
108 label: label.to_string(),
109 },
110 BillingPresentation::Local => Self::Local,
111 BillingPresentation::Unknown => Self::Unknown,
112 }
113 }
114 }
115
116 #[cfg(any(test, feature = "test-support"))]
117 impl ChildBillingProvenance {
118 /// Convert back to the presentation form consumed by pricing.
119 #[must_use]
120 pub fn as_billing_presentation(&self) -> BillingPresentation {
121 match self {
122 Self::Metered => BillingPresentation::Metered,
123 Self::Local => BillingPresentation::Local,
124 Self::Unknown => BillingPresentation::Unknown,
125 Self::Subscription { label } => static_subscription_label(label).map_or(
126 BillingPresentation::Unknown,
127 BillingPresentation::Subscription,
128 ),
129 }
130 }
131 }
132
133 /// The subscription labels [`for_route`] can emit, mapped back to their
134 /// static form. Anything else is not a label this process vouches for.
135 #[cfg(any(test, feature = "test-support"))]
136 fn static_subscription_label(label: &str) -> Option<&'static str> {
137 Some(match label {
138 "ChatGPT plan allowance" => "ChatGPT plan allowance",
139 "Codex OAuth quota" => "Codex OAuth quota",
140 "OpenCode Go quota" => "OpenCode Go quota",
141 "Z.ai Coding Plan quota" => "Z.ai Coding Plan quota",
142 "MiMo token plan" => "MiMo token plan",
143 "Kimi Code quota" => "Kimi Code quota",
144 "MiniMax Token Plan quota" => "MiniMax Token Plan quota",
145 "Grok OAuth quota" => "Grok OAuth quota",
146 "Claude OAuth quota" => "Claude OAuth quota",
147 "StepFun Step Plan quota" => "StepFun Step Plan quota",
148 "Alibaba Token Plan" => "Alibaba Token Plan",
149 "Alibaba Coding Plan" => "Alibaba Coding Plan",
150 "Volcengine Coding Plan" => "Volcengine Coding Plan",
151 _ => return None,
152 })
153 }
154
155 /// Immutable, non-secret receipt of the route a request was dispatched on.
156 ///
157 /// This is what a child/non-active route must be billed from. Re-reading an
158 /// ambient `Config` for a non-active provider is unsound: `apply_env_overrides`
159 /// merges provider endpoint variables (`MOONSHOT_BASE_URL`, `KIMI_BASE_URL`,
160 /// …) into the **active** provider's table only, so a cross-provider child's
161 /// config entry does not describe the endpoint its client was built with.
162 ///
163 /// Test-only: the production dispatch path captures a full
164 /// [`DispatchedReceipt`] at the client-freeze boundary and classifies with
165 /// [`for_dispatched_receipt`]. This pair exists so route-resolution tests can
166 /// assert that the pre-dispatch and receipt answers cannot disagree.
167 #[cfg(any(test, feature = "test-support"))]
168 #[derive(Debug, Clone, Copy)]
169 pub struct DispatchedRoute<'a> {
170 /// Provider the dispatched client is bound to.
171 pub provider: ProviderKind,
172 /// Base URL the dispatched client will call, verbatim.
173 pub base_url: &'a str,
174 }
175
176 /// A fully captured, `Config`-free billing receipt.
177 ///
178 /// This is what [`for_dispatched_receipt`] consumes. Every field is captured
179 /// at dispatch; nothing here can be re-derived later.
180 #[derive(Debug, Clone, Copy)]
181 pub struct DispatchedReceipt<'a> {
182 /// Provider the dispatched client was bound to.
183 pub provider: ProviderKind,
184 /// Non-secret identity key that selected this route's table — the
185 /// `[providers.<name>]` key for a named custom route, the provider's own
186 /// key otherwise.
187 ///
188 /// `None` means the identity was not captured. For a named custom route
189 /// that is fatal to any product claim: without it there is no way to say
190 /// *which* custom vendor ran, and the classifier fails closed rather than
191 /// reading whichever custom table happens to be selected now.
192 pub identity: Option<&'a str>,
193 /// Base URL the dispatched client called, verbatim.
194 pub base_url: &'a str,
195 /// Product truth captured when this client was built.
196 pub product: RouteProduct,
197 }
198
199 /// Immutable, non-secret product truth for one route, captured at the moment
200 /// its client was built.
201 ///
202 /// Several providers are *credential-shaped* rather than endpoint-shaped: the
203 /// same host sells both a metered and a subscription product, and only the
204 /// credential (or an operator-declared pay mode) separates them. That fact
205 /// cannot be recovered later from an ambient `Config` — the session may have
206 /// switched provider, custom table, or key since — so it has to travel with
207 /// the receipt.
208 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
209 pub enum RouteProduct {
210 /// No product fact was captured. Credential-shaped providers must fail
211 /// closed on this: an uncaptured product is not a licence to guess.
212 #[default]
213 Unproven,
214 /// The route's credential/pay mode is subscription-backed, with this
215 /// user-facing quota label.
216 Subscription(&'static str),
217 /// The route bills per token.
218 Metered,
219 }
220
221 /// Resolve how a provider route should present usage, from the endpoint that
222 /// route resolves to right now.
223 ///
224 /// The endpoint is resolved exactly once, through the same identity-aware
225 /// [`Config::base_url_for_route`] the client is built from, and is then judged
226 /// by the same exact-product rules a dispatch receipt gets. There is no
227 /// separate "ambient" reading of a provider's table: a config entry with no
228 /// `base_url` still resolves to a real endpoint (an imported Kimi token
229 /// resolves to the Kimi Code membership host), and classifying from the raw
230 /// table field would call that route metered and invent dollars against a
231 /// membership quota.
232 ///
233 /// This is the pre-dispatch answer — for a turn that already ran, bill from
234 /// its receipt with [`crate::route_billing::for_dispatched_receipt`] instead.
235 #[must_use]
236 pub fn for_route(config: &Config, identity: &ProviderIdentity) -> BillingPresentation {
237 let base_url = config.base_url_for_route(identity);
238 for_route_with_endpoint(config, identity, &base_url)
239 }
240
241 /// Capture billing from the concrete endpoint the client will dispatch on.
242 /// Candidate-selected endpoints can differ from the ambient config default;
243 /// credentials cannot turn a gateway endpoint into an official plan receipt.
244 #[must_use]
245 pub fn for_route_with_endpoint(
246 config: &Config,
247 identity: &ProviderIdentity,
248 base_url: &str,
249 ) -> BillingPresentation {
250 if config.verify_provider_identity(identity).is_err() {
251 return BillingPresentation::Unknown;
252 }
253 classify(
254 identity.provider,
255 Some(identity.key.as_str()),
256 base_url,
257 capture_product(config, identity),
258 )
259 }
260
261 /// Capture the immutable product facts for `provider` from the config its
262 /// client is being built from, **at dispatch time**.
263 ///
264 /// Call this while the config still describes the route being dispatched. The
265 /// result is what travels on [`crate::route_billing::DispatchedReceipt::product`];
266 /// nothing downstream
267 /// may re-derive it.
268 #[must_use]
269 pub fn capture_product(config: &Config, identity: &ProviderIdentity) -> RouteProduct {
270 if config.verify_provider_identity(identity).is_err() {
271 return RouteProduct::Unproven;
272 }
273 let provider = identity.provider;
274 let provider_config = config.provider_config_for(identity);
275 match provider {
276 ProviderKind::OpenaiCodex => {
277 if codewhale_runtime::oauth::official_chatgpt_registration(config).is_ok() {
278 RouteProduct::Subscription("ChatGPT plan allowance")
279 } else {
280 RouteProduct::Unproven
281 }
282 }
283 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic => {
284 match minimax_credential_product(config, identity, provider_config) {
285 CredentialProduct::Plan => RouteProduct::Subscription("MiniMax Token Plan quota"),
286 CredentialProduct::PayAsYouGo => RouteProduct::Metered,
287 CredentialProduct::Unprovable => RouteProduct::Unproven,
288 }
289 }
290 ProviderKind::Csdn => match csdn_credential_product(provider_config) {
291 CredentialProduct::Plan => RouteProduct::Subscription("CSDN Coding Plan quota"),
292 CredentialProduct::PayAsYouGo => RouteProduct::Metered,
293 CredentialProduct::Unprovable => RouteProduct::Unproven,
294 },
295 ProviderKind::XiaomiMimo => {
296 if xiaomi_is_explicit_pay_as_you_go(provider_config) {
297 RouteProduct::Metered
298 } else {
299 RouteProduct::Subscription("MiMo token plan")
300 }
301 }
302 ProviderKind::Xai => {
303 if provider_config.is_some_and(uses_xai_oauth)
304 && codewhale_runtime::oauth::credentials_valid(
305 codewhale_runtime::oauth::OAuthProvider::Xai,
306 config,
307 )
308 {
309 RouteProduct::Subscription("Grok OAuth quota")
310 } else {
311 RouteProduct::Metered
312 }
313 }
314 ProviderKind::Anthropic => {
315 if provider_config.is_some_and(uses_anthropic_oauth) {
316 RouteProduct::Subscription("Claude OAuth quota")
317 } else {
318 RouteProduct::Metered
319 }
320 }
321 ProviderKind::Custom => match provider_config {
322 Some(entry) if !custom_billing_unknown(entry) => RouteProduct::Metered,
323 // No table, or a table with no declared pay mode: a custom vendor
324 // that has not told us how it bills.
325 _ => RouteProduct::Unproven,
326 },
327 // Endpoint-shaped and flat-rate providers need no credential fact.
328 _ => RouteProduct::Unproven,
329 }
330 }
331
332 /// Resolve billing for a route from its dispatch-time receipt.
333 ///
334 /// Deliberately takes no `Config`: after dispatch there is no sound ambient
335 /// state to consult. The session can have switched provider, custom table, or
336 /// credential since the request went out, so every fact this needs must
337 /// already be on the receipt. A receipt that does not name a product fails
338 /// closed to [`BillingPresentation::Unknown`] rather than inventing one.
339 /// Classify a receipt with no `Config` in reach at all.
340 ///
341 /// This is the entry point every post-dispatch caller must use. Because it
342 /// takes no config, a provider switch, a `/provider` change, or a different
343 /// custom table being selected after dispatch cannot retro-bill the turn onto
344 /// another route.
345 #[must_use]
346 pub fn for_dispatched_receipt(receipt: DispatchedReceipt<'_>) -> BillingPresentation {
347 classify(
348 receipt.provider,
349 receipt.identity,
350 receipt.base_url,
351 receipt.product,
352 )
353 }
354
355 /// Convenience wrapper for callers that still hold the route's own
356 /// **dispatch-time** config and have not captured a receipt yet.
357 ///
358 /// Sound only while `config` still describes the dispatched route. Anything
359 /// that runs after the turn has already completed must capture a
360 /// [`DispatchedReceipt`] at dispatch and use [`for_dispatched_receipt`].
361 #[cfg(any(test, feature = "test-support"))]
362 #[must_use]
363 pub fn for_dispatched_route(config: &Config, route: DispatchedRoute<'_>) -> BillingPresentation {
364 let identity = config
365 .active_provider_identity()
366 .ok()
367 .filter(|id| id.provider == route.provider)
368 .or_else(|| config.builtin_provider_identity(route.provider).ok());
369 identity
370 .as_ref()
371 .map_or(BillingPresentation::Unknown, |identity| {
372 for_route_with_endpoint(config, identity, route.base_url)
373 })
374 }
375
376 /// The one classifier, pure in its inputs.
377 ///
378 /// `base_url` is the single resolved endpoint for this route and `product` is
379 /// the captured credential truth. There is no `Config` parameter on purpose:
380 /// this cannot read a provider table, a custom entry, or an active selection,
381 /// so a pre-dispatch answer and a receipt answer cannot drift apart and a
382 /// post-dispatch provider switch cannot retro-bill a turn onto another route.
383 fn classify(
384 provider: ProviderKind,
385 identity: Option<&str>,
386 base_url: &str,
387 product: RouteProduct,
388 ) -> BillingPresentation {
389 match provider {
390 ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm => {
391 BillingPresentation::Local
392 }
393 // The official public API accepts both API keys and ChatGPT grants.
394 // Only the plan provider plus verified dispatch-time grant can claim
395 // allowance; neither a shared host nor a provider name is proof.
396 ProviderKind::OpenaiCodex if crate::pricing::is_official_chatgpt_api(base_url) => {
397 match product {
398 RouteProduct::Subscription("ChatGPT plan allowance") => {
399 BillingPresentation::Subscription("ChatGPT plan allowance")
400 }
401 _ => BillingPresentation::Unknown,
402 }
403 }
404 // Keep legacy backend receipts interpretable for persisted history.
405 ProviderKind::OpenaiCodex if crate::pricing::is_chatgpt_codex_backend(base_url) => {
406 BillingPresentation::Subscription("Codex OAuth quota")
407 }
408 ProviderKind::OpenaiCodex => BillingPresentation::Unknown,
409 ProviderKind::OpencodeGo => BillingPresentation::Subscription("OpenCode Go quota"),
410 // StepFun already reduces an endpoint to a non-secret billing surface
411 // and fails closed on anything it does not recognize.
412 ProviderKind::Stepfun => stepfun_billing_for_endpoint(Some(base_url)),
413 // Z.ai's dedicated Coding endpoint is the GLM Coding Plan route. Its
414 // quota is subscription-backed, so a public API price estimate is not
415 // truthful spend and must not appear as dollars in the UI. A
416 // credentials-only `[providers.zai]` entry still resolves to that
417 // endpoint, because it is also CodeWhale's Z.ai default.
418 ProviderKind::Zai if base_url.trim().is_empty() => BillingPresentation::Unknown,
419 ProviderKind::Zai if is_zai_coding_plan_endpoint(base_url) => {
420 BillingPresentation::Subscription("Z.ai Coding Plan quota")
421 }
422 ProviderKind::Zai => endpoint_shaped_payg_billing(provider, base_url),
423 ProviderKind::XiaomiMimo => product_billing(product),
424
425 // Moonshot's direct platform is pay-as-you-go metered. Only the exact
426 // Kimi Code membership endpoint bills against subscription quota.
427 //
428 // The endpoint must name one of the two known products outright. A
429 // neighboring Kimi-hosted path, a gateway host, or a shipped default
430 // reached for a route we cannot otherwise explain must not inherit
431 // Moonshot's metered price list.
432 //
433 // Reading the resolved endpoint (not the provider table's `base_url`)
434 // is what makes the imported-token membership route truthful: a Kimi
435 // Code token with no `base_url` in its table still resolves to
436 // api.kimi.com/coding/v1, and calling that metered would put invented
437 // dollars against a membership quota.
438 ProviderKind::Moonshot
439 if codewhale_runtime::config::moonshot_base_url_is_exact_kimi_code(base_url) =>
440 {
441 BillingPresentation::Subscription("Kimi Code quota")
442 }
443 ProviderKind::Moonshot
444 if codewhale_runtime::config::moonshot_base_url_is_exact_direct_platform(base_url) =>
445 {
446 BillingPresentation::Metered
447 }
448 ProviderKind::Moonshot => BillingPresentation::Unknown,
449 // Both MiniMax dialects (`[providers.minimax]` chat-completions and
450 // `[providers.minimax_anthropic]` Messages) are reachable with the
451 // same MINIMAX_API_KEY and sell the same PAYG/Token Plan duality over
452 // the same endpoints, so the wire protocol must not change the billing
453 // story and the endpoint cannot settle it either. Only the credential
454 // product can, and when that is unprovable the route is Unknown.
455 // A MiniMax gateway sells its own product on its own terms, and the
456 // PAYG/Token Plan duality only describes MiniMax's own hosts. Settle
457 // the endpoint first: anything off the supported direct routes is
458 // Unknown no matter what credential was captured.
459 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic
460 if !minimax_base_url_is_supported_direct(base_url) =>
461 {
462 BillingPresentation::Unknown
463 }
464 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic => product_billing(product),
465 // CSDN 星图 sells the Coding Plan (`glm_for_coding`) and metered
466 // marketplace models over the same endpoint; the URL proves only that
467 // the route is first-party, so the captured product decides. Anything
468 // off the supported direct endpoint is Unknown no matter what was
469 // captured.
470 ProviderKind::Csdn
471 if !codewhale_config::provider::is_exact_csdn_platform_route(
472 codewhale_config::ProviderKind::Csdn,
473 base_url,
474 ) =>
475 {
476 BillingPresentation::Unknown
477 }
478 ProviderKind::Csdn => product_billing(product),
479 ProviderKind::Xai | ProviderKind::Anthropic => product_billing(product),
480 // A named custom route is billed from the identity and endpoint it
481 // dispatched on. Without an identity there is no vendor to name, and
482 // without an endpoint there is no route at all — either way the honest
483 // answer is Unknown rather than whatever the active custom table says.
484 ProviderKind::Custom
485 if identity.is_none_or(|key| key.trim().is_empty()) || base_url.trim().is_empty() =>
486 {
487 BillingPresentation::Unknown
488 }
489 ProviderKind::Custom => product_billing(product),
490 // These providers are endpoint-shaped — but
491 // only on an endpoint we actually recognize. A first-party or
492 // aggregator provider pointed at an unrecognized host is not evidence
493 // that the host sells that provider's price list, so it must not fall
494 // through to metered per-token dollars on the strength of a provider
495 // name (#4318).
496 // Keep this match exhaustive: onboarding a provider requires an
497 // explicit billing decision and the default-route audit below.
498 ProviderKind::Deepseek
499 | ProviderKind::DeepseekAnthropic
500 | ProviderKind::NvidiaNim
501 | ProviderKind::Openai
502 | ProviderKind::Atlascloud
503 | ProviderKind::WanjieArk
504 | ProviderKind::Volcengine
505 | ProviderKind::Openrouter
506 | ProviderKind::Orcarouter
507 | ProviderKind::Novita
508 | ProviderKind::Fireworks
509 | ProviderKind::Siliconflow
510 | ProviderKind::SiliconflowCN
511 | ProviderKind::Arcee
512 | ProviderKind::OllamaCloud
513 | ProviderKind::Huggingface
514 | ProviderKind::Modelscope
515 | ProviderKind::Together
516 | ProviderKind::Qianfan
517 | ProviderKind::Openmodel
518 | ProviderKind::Deepinfra
519 | ProviderKind::Sakana
520 | ProviderKind::LongCat
521 | ProviderKind::OpencodeZen
522 | ProviderKind::Meta
523 | ProviderKind::Mistral
524 | ProviderKind::Google
525 | ProviderKind::Antigravity
526 | ProviderKind::Telecomjs
527 | ProviderKind::Edenai
528 | ProviderKind::Zenmux
529 | ProviderKind::Concentrate
530 | ProviderKind::Codewhale
531 | ProviderKind::ModelstudioTokenPlan
532 | ProviderKind::ModelstudioTokenPlanAnthropic
533 | ProviderKind::ModelstudioCodingPlan
534 | ProviderKind::ModelstudioCodingPlanAnthropic => {
535 endpoint_shaped_payg_billing(provider, base_url)
536 }
537 }
538 }
539
540 /// Metered only when the resolved endpoint reduces to a known money surface.
541 /// An unclassified endpoint is Unknown, never metered-by-provider-name.
542 fn endpoint_shaped_payg_billing(provider: ProviderKind, base_url: &str) -> BillingPresentation {
543 use crate::pricing::EndpointMetering;
544
545 let surface = crate::pricing::billing_surface_for_route(provider, Some(base_url));
546 match crate::pricing::endpoint_metering_for_billing_surface(surface) {
547 EndpointMetering::Money => BillingPresentation::Metered,
548 EndpointMetering::LocalNoBill => BillingPresentation::Local,
549 EndpointMetering::ExactSubscription => BillingPresentation::Subscription(match surface {
550 Some(crate::pricing::MODELSTUDIO_TOKEN_PLAN_BILLING_SURFACE) => "Alibaba Token Plan",
551 Some(crate::pricing::MODELSTUDIO_CODING_PLAN_BILLING_SURFACE) => "Alibaba Coding Plan",
552 Some(crate::pricing::VOLCENGINE_CODING_PLAN_BILLING_SURFACE) => {
553 "Volcengine Coding Plan"
554 }
555 _ => "provider plan",
556 }),
557 EndpointMetering::Unknown => BillingPresentation::Unknown,
558 }
559 }
560
561 /// Billing presentation for callers that hold a provider and the concrete base
562 /// URL but **not** the app [`Config`] — background helpers (compaction,
563 /// purge) that run off a bare client.
564 ///
565 /// Everything decidable from provider identity plus a classified endpoint is
566 /// decided; everything that depends on credentials or an auth mode CodeWhale
567 /// cannot see from here stays [`BillingPresentation::Unknown`]. In particular a
568 /// local, custom, or plan endpoint is never allowed to fall through to metered
569 /// per-token dollars on the strength of a provider name (#4318).
570 ///
571 /// This is exactly a receipt with no identity and no captured product, so it
572 /// runs through the one [`classify`] path rather than keeping a second,
573 /// drift-prone copy of the endpoint rules: an uncaptured product makes every
574 /// credential-shaped provider Unknown, and a missing identity makes every
575 /// named custom route Unknown.
576 #[must_use]
577 pub fn for_endpoint_without_config(
578 provider: ProviderKind,
579 base_url: Option<&str>,
580 ) -> BillingPresentation {
581 classify(
582 provider,
583 None,
584 base_url.unwrap_or_default(),
585 RouteProduct::Unproven,
586 )
587 }
588
589 /// Immutable billing surface captured when a foreground/child request is
590 /// dispatched. Endpoint classification owns ordinary providers; MiniMax and
591 /// OAuth-on-the-same-host providers require the saved route mode as additional
592 /// evidence and otherwise fail closed.
593 #[must_use]
594 pub fn billing_surface_for_dispatch(
595 config: Option<&Config>,
596 identity: &ProviderIdentity,
597 base_url: Option<&str>,
598 ) -> Option<&'static str> {
599 let provider = identity.provider;
600 if let Some(config) = config {
601 if config.verify_provider_identity(identity).is_err() {
602 return None;
603 }
604 let billing = base_url.map_or_else(
605 || for_route(config, identity),
606 |endpoint| for_route_with_endpoint(config, identity, endpoint),
607 );
608 match billing {
609 BillingPresentation::Subscription(_) => {
610 return Some(match provider {
611 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic => {
612 crate::pricing::MINIMAX_TOKEN_PLAN_BILLING_SURFACE
613 }
614 ProviderKind::Csdn => crate::pricing::CSDN_CODING_PLAN_BILLING_SURFACE,
615 ProviderKind::OpenaiCodex
616 | ProviderKind::OpencodeGo
617 | ProviderKind::Anthropic
618 | ProviderKind::Xai => crate::pricing::OAUTH_SUBSCRIPTION_BILLING_SURFACE,
619 _ => crate::pricing::billing_surface_for_route(provider, base_url)
620 .unwrap_or(crate::pricing::UNCLASSIFIED_BILLING_SURFACE),
621 });
622 }
623 BillingPresentation::Metered
624 if matches!(
625 provider,
626 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic
627 ) =>
628 {
629 return Some(crate::pricing::MINIMAX_PAYG_BILLING_SURFACE);
630 }
631 BillingPresentation::Metered if provider == ProviderKind::Csdn => {
632 return Some(crate::pricing::CSDN_PAYG_BILLING_SURFACE);
633 }
634 BillingPresentation::Local => return Some(crate::pricing::LOCAL_BILLING_SURFACE),
635 BillingPresentation::Unknown | BillingPresentation::Metered => {}
636 }
637 }
638 crate::pricing::billing_surface_for_route(provider, base_url)
639 }
640
641 /// Credential-shaped providers answer from the captured product and nothing
642 /// else. An uncaptured product is Unknown: no invented dollars, no invented
643 /// quota label.
644 fn product_billing(product: RouteProduct) -> BillingPresentation {
645 match product {
646 RouteProduct::Subscription(label) => BillingPresentation::Subscription(label),
647 RouteProduct::Metered => BillingPresentation::Metered,
648 RouteProduct::Unproven => BillingPresentation::Unknown,
649 }
650 }
651
652 // MiniMax's own hosted routes, for both wire dialects. Single-sourced in
653 // `config` so billing classification and request shaping cannot disagree about
654 // which hosts are first-party.
655 use codewhale_runtime::config::minimax_base_url_is_supported_direct;
656
657 /// StepFun already reduces an endpoint to a non-secret billing surface and
658 /// fails closed on anything it does not recognize, so the resolved endpoint
659 /// and a dispatch receipt use the same reduction unchanged.
660 fn stepfun_billing_for_endpoint(base_url: Option<&str>) -> BillingPresentation {
661 match crate::pricing::billing_surface_for_route(ProviderKind::Stepfun, base_url) {
662 Some(crate::pricing::STEPFUN_PAYG_BILLING_SURFACE) => BillingPresentation::Metered,
663 Some(crate::pricing::STEPFUN_PLAN_BILLING_SURFACE) => {
664 BillingPresentation::Subscription("StepFun Step Plan quota")
665 }
666 _ => BillingPresentation::Unknown,
667 }
668 }
669
670 fn is_zai_coding_plan_endpoint(base_url: &str) -> bool {
671 base_url
672 .trim()
673 .trim_end_matches('/')
674 .ends_with("/api/coding/paas/v4")
675 }
676
677 /// Billing for a child route. Billing is never guessed from provider
678 /// identity:
679 ///
680 /// - `child_provenance` — the child's own route truth, classified by
681 /// [`for_dispatched_route`] from the immutable endpoint receipt captured
682 /// when its client was built, and carried on the usage envelope — always
683 /// wins.
684 /// - Without provenance, a child on the parent's provider runs the parent's
685 /// exact route (review/verify/rlm children reuse the session client), so
686 /// it inherits `parent_billing`.
687 /// - Without provenance, a cross-provider child fails closed: local routes
688 /// stay `Local`; everything else is `Unknown` — no invented dollars and no
689 /// invented subscription labels.
690 ///
691 /// **Superseded by [`for_child_route_receipt`].** Retained for the
692 /// subagent-routing path and its existing coverage, which compare first-party
693 /// providers whose identity key is the provider string itself. It must not be
694 /// used where a named custom route can appear: every custom route maps to
695 /// `ProviderKind::Custom`, so the enum comparison below cannot tell custom
696 /// vendor A from custom vendor B.
697 ///
698 /// Unknown is deliberately not a subscription label (#4318). A provider that
699 /// *can* be subscription-billed is not evidence that this child turn *was*,
700 /// and because non-metered routes are excused from money coverage, that guess
701 /// would quietly remove real spend from `/cost`'s denominator instead of
702 /// reporting it as missing.
703 #[must_use]
704 #[cfg(any(test, feature = "test-support"))]
705 pub fn for_child_route(
706 parent_provider: ProviderKind,
707 parent_billing: BillingPresentation,
708 child_provider: ProviderKind,
709 child_provenance: Option<BillingPresentation>,
710 ) -> BillingPresentation {
711 if let Some(provenance) = child_provenance {
712 return provenance;
713 }
714 if child_provider == parent_provider {
715 return parent_billing;
716 }
717 match child_provider {
718 // No provider bill exists for a local runtime under any configuration.
719 ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm => {
720 BillingPresentation::Local
721 }
722 _ => BillingPresentation::Unknown,
723 }
724 }
725
726 /// Identity-aware child billing, from the parent's frozen receipt.
727 ///
728 /// **Not on the production child path**, for the same reason as
729 /// [`ChildBillingProvenance`]: `tui::tool_routing` bills a child from the
730 /// child's own [`crate::cost_status::EffectiveRouteEnvelope`], rehydrated from
731 /// the complete `child_*` metadata its producer emits, and an incomplete
732 /// payload fails closed to Unknown rather than inheriting anything (see
733 /// `legacy_child_usage_metadata_fails_closed_without_parent_route_fallback`).
734 /// The identity-comparison rule below is therefore structurally unreachable —
735 /// nothing inherits — and is kept with the tests as the record of it.
736 #[cfg(any(test, feature = "test-support"))]
737 #[must_use]
738 pub fn for_child_route_receipt(
739 parent: ChildParentRoute<'_>,
740 child: ChildRouteClaim<'_>,
741 child_provenance: Option<BillingPresentation>,
742 ) -> BillingPresentation {
743 if let Some(provenance) = child_provenance {
744 return provenance;
745 }
746 // A child that claims no route at all ran in-process on the parent's own
747 // client (review/verify/rlm critics reuse the session client), so the
748 // parent's frozen receipt *is* its receipt. This is inheritance from an
749 // immutable capture, not from live session state.
750 if !child.named {
751 return parent.billing;
752 }
753 // Same-route inheritance requires the *whole* route to match, not just the
754 // provider enum. Every named custom route maps to `ProviderKind::Custom`,
755 // so an enum comparison would let a child on custom vendor A inherit the
756 // parent's product label from custom vendor B.
757 if child.provider == Some(parent.provider)
758 && child.identity.is_some_and(|key| key == parent.identity)
759 {
760 return parent.billing;
761 }
762 // A child that named a provider string this build cannot parse names no
763 // route we can vouch for. That is not a licence to inherit: Unknown.
764 match child.provider {
765 Some(ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm) => {
766 BillingPresentation::Local
767 }
768 _ => BillingPresentation::Unknown,
769 }
770 }
771
772 /// Non-secret route facts a child tool must publish alongside its token usage.
773 ///
774 /// Emitted from the child's own dispatched client, so the parent consumer never
775 /// has to infer which route ran. Keys are pinned by
776 /// `child_route_metadata_round_trips_through_the_consumer` so a producer and
777 /// the reader in `tui::tool_routing` cannot drift apart.
778 ///
779 /// `product` is left [`RouteProduct::Unproven`] when the child has no
780 /// route-scoped `Config` in reach: that classifies credential-shaped providers
781 /// as Unknown, which is the honest answer rather than a guess. A child running
782 /// the parent's exact route is recognized by identity and inherits the
783 /// parent's frozen receipt instead.
784 /// Currently exercised only by
785 /// `child_route_metadata_round_trips_through_the_consumer`: no tool producer
786 /// emits the keys yet, and the reader in `tui::tool_routing` treats them as
787 /// optional. The pairing lives here so a producer and that reader cannot drift
788 /// apart when one is wired up.
789 #[cfg(any(test, feature = "test-support"))]
790 #[must_use]
791 pub fn child_route_metadata(
792 provider: ProviderKind,
793 identity: &str,
794 base_url: &str,
795 product: RouteProduct,
796 ) -> serde_json::Value {
797 let billing = for_dispatched_receipt(DispatchedReceipt {
798 provider,
799 identity: Some(identity),
800 base_url,
801 product,
802 });
803 serde_json::json!({
804 "child_provider": provider.as_str(),
805 "child_provider_identity": identity,
806 "child_billing": ChildBillingProvenance::from(billing),
807 })
808 }
809
810 /// The parent turn's frozen receipt, as the only inheritance basis a child may
811 /// use.
812 ///
813 /// Deliberately not `app.billing_presentation`: that chip is live session
814 /// state, rewritten on every `/provider` switch, so reading it when a child's
815 /// usage envelope arrives bills the child against whatever route the session
816 /// points at *now*.
817 #[cfg(any(test, feature = "test-support"))]
818 #[derive(Debug, Clone, Copy)]
819 pub struct ChildParentRoute<'a> {
820 pub provider: ProviderKind,
821 /// The parent turn's captured identity key.
822 pub identity: &'a str,
823 /// Billing classified from the parent turn's dispatch receipt.
824 pub billing: BillingPresentation,
825 }
826
827 /// What a child claims about its own route.
828 ///
829 /// `named` distinguishes the two very different silences:
830 ///
831 /// - `named: false` — the child published no route at all, which means it ran
832 /// on the parent's own client. Inheriting the parent's frozen receipt is
833 /// correct.
834 /// - `named: true` with `provider: None` — the child published a provider
835 /// string this build cannot parse. It named *some* route, just not one we
836 /// recognize, so inheritance would be a guess: Unknown.
837 #[cfg(any(test, feature = "test-support"))]
838 #[derive(Debug, Clone, Copy, Default)]
839 pub struct ChildRouteClaim<'a> {
840 /// Whether the child published any route string at all.
841 pub named: bool,
842 pub provider: Option<ProviderKind>,
843 pub identity: Option<&'a str>,
844 }
845
846 /// Whether this route may show a dollar amount for the given model.
847 ///
848 /// Requires both a metered billing presentation and an authoritative priced
849 /// basis for the model. OAuth/token-plan routes always return false even when
850 /// the same model id is priced on a public API route.
851 #[cfg(any(test, feature = "test-support"))]
852 #[must_use]
853 pub fn has_priced_metered_basis(
854 billing: BillingPresentation,
855 provider: ProviderKind,
856 model: &str,
857 ) -> bool {
858 billing.shows_money()
859 && if provider == ProviderKind::Stepfun {
860 crate::pricing::has_pricing_for_billing_surface(
861 provider,
862 model,
863 Some(crate::pricing::STEPFUN_PAYG_BILLING_SURFACE),
864 )
865 } else {
866 crate::pricing::has_pricing_for_provider(provider, model)
867 }
868 }
869
870 /// Build the truthful usage chip for session surfaces.
871 ///
872 /// `used_pct` is only honored for subscription/OAuth routes and must come from
873 /// a provider-supplied allowance reading — never from a local estimate.
874 #[must_use]
875 pub fn usage_chip(
876 billing: BillingPresentation,
877 provider: ProviderKind,
878 model: &str,
879 displayed_cost: f64,
880 currency: CostCurrency,
881 used_pct: Option<f32>,
882 ) -> UsageChip {
883 match billing {
884 BillingPresentation::Local => UsageChip::Local,
885 BillingPresentation::Unknown => {
886 UsageChip::Unknown(vec![UnpricedReason::UnknownBillingBasis])
887 }
888 BillingPresentation::Subscription(label) => UsageChip::Allowance {
889 label,
890 used_pct: used_pct.filter(|pct| pct.is_finite() && *pct >= 0.0),
891 },
892 BillingPresentation::Metered => {
893 let surface = (provider == ProviderKind::Stepfun)
894 .then_some(crate::pricing::STEPFUN_PAYG_BILLING_SURFACE);
895 let audit = if surface.is_some() {
896 crate::pricing::audit_turn_cost_for_route_at(
897 provider,
898 model,
899 surface,
900 &codewhale_models::Usage::default(),
901 chrono::Utc::now(),
902 )
903 } else {
904 crate::pricing::audit_turn_cost_for_provider_at(
905 provider,
906 model,
907 &codewhale_models::Usage::default(),
908 chrono::Utc::now(),
909 )
910 };
911 if !audit.is_priced_in(currency) {
912 UsageChip::Unknown(vec![
913 audit
914 .unpriced_reason
915 .unwrap_or(UnpricedReason::UnsupportedCurrency),
916 ])
917 } else if displayed_cost.is_finite() && displayed_cost > 0.0 {
918 UsageChip::Money(format_cost_amount(displayed_cost, currency))
919 } else {
920 UsageChip::Hidden
921 }
922 }
923 }
924 }
925
926 /// Compact footer/header chip text. `None` means omit the chip.
927 #[must_use]
928 pub fn format_usage_chip(chip: &UsageChip, locale: Locale) -> Option<String> {
929 match chip {
930 UsageChip::Money(amount) => Some(amount.clone()),
931 // The glance shows confirmed money only. When part of the session has
932 // no authoritative price, the confirmed dollars still stand on their
933 // own; the cost report, not this line, explains what is missing.
934 UsageChip::PricedSubtotal { amount, .. } => Some(amount.clone()),
935 UsageChip::Allowance { label, used_pct } => Some(match used_pct {
936 Some(pct) => tr(locale, MessageId::CostChipAllowancePercent)
937 .replace("{plan}", label)
938 .replace("{percent}", &format!("{pct:.0}")),
939 None => tr(locale, MessageId::CostChipAllowance).replace("{plan}", label),
940 }),
941 UsageChip::Local => Some(tr(locale, MessageId::CostChipLocal).into_owned()),
942 // Nothing confirmed to show: an unpriced session has no dollars, and
943 // inventing a label for their absence is the noise this replaced.
944 UsageChip::Unknown(_) => None,
945 UsageChip::Hidden => None,
946 }
947 }
948
949 fn custom_billing_unknown(config: &ProviderConfig) -> bool {
950 // A custom OpenAI-compatible endpoint with no explicit pay mode and no
951 // priced catalog is treated as unknown rather than inventing metered
952 // dollars from a borrowed model id.
953 let mode = auth_mode(config);
954 !mode.as_deref().is_some_and(|mode| {
955 matches!(
956 mode,
957 "api_key"
958 | "api"
959 | "key"
960 | "keyring"
961 | "payg"
962 | "paygo"
963 | "pay_as_you_go"
964 | "metered"
965 | "standard"
966 )
967 })
968 }
969
970 fn normalized(value: &str) -> String {
971 value.trim().to_ascii_lowercase().replace(['-', ' '], "_")
972 }
973
974 fn auth_mode(config: &ProviderConfig) -> Option<String> {
975 config
976 .auth_mode
977 .as_deref()
978 .or(config.mode.as_deref())
979 .map(normalized)
980 }
981
982 fn uses_xai_oauth(config: &ProviderConfig) -> bool {
983 auth_mode(config).is_some_and(|mode| codewhale_runtime::oauth::auth_mode_uses_xai_oauth(&mode))
984 }
985
986 fn uses_anthropic_oauth(config: &ProviderConfig) -> bool {
987 auth_mode(config).is_some_and(|mode| {
988 matches!(
989 mode.as_str(),
990 "oauth"
991 | "anthropic_oauth"
992 | "claude_oauth"
993 | "claude_cli"
994 | "claude_code"
995 | "max"
996 | "subscription"
997 )
998 })
999 }
1000
1001 /// What immutable, non-secret provenance can prove about the credential
1002 /// product behind a dual-product route.
1003 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1004 enum CredentialProduct {
1005 /// A subscription / token-plan product is proven.
1006 Plan,
1007 /// An ordinary metered (pay-as-you-go) product is proven.
1008 PayAsYouGo,
1009 /// Neither can be proven from route/auth provenance. Classification must
1010 /// fail closed rather than default to metered dollars.
1011 Unprovable,
1012 }
1013
1014 /// MiniMax sells both a pay-as-you-go API and a Token Plan subscription over
1015 /// the *same* endpoints and the same `MINIMAX_API_KEY`, so the product can
1016 /// only come from an explicit pay mode or the credential's own product prefix.
1017 ///
1018 /// A key held in the Codewhale secret store / OS keyring is deliberately not
1019 /// probed: classification must never be a reason to open secret storage. When
1020 /// no product marker is visible the route is `Unprovable`, and [`for_route`]
1021 /// reports Unknown instead of inventing pay-as-you-go dollars.
1022 fn minimax_credential_product(
1023 config: &Config,
1024 identity: &ProviderIdentity,
1025 provider_config: Option<&ProviderConfig>,
1026 ) -> CredentialProduct {
1027 // An explicit operator-set pay mode is the strongest non-secret
1028 // provenance available: the operator has told us how the account bills,
1029 // and it wins over key shape in both directions. An unrecognized mode is
1030 // not a product claim.
1031 if let Some(mode) = provider_config
1032 .and_then(|config| config.mode.as_deref())
1033 .filter(|mode| !mode.trim().is_empty())
1034 .map(normalized)
1035 {
1036 return match mode.as_str() {
1037 // `subscription_plan` is the spelling the cost lane's operator
1038 // docs and tests used; keep it recognized so an explicit operator
1039 // declaration is never silently discarded as "unprovable".
1040 "token_plan" | "tokenplan" | "plan" | "subscription" | "subscription_plan" => {
1041 CredentialProduct::Plan
1042 }
1043 "pay_as_you_go" | "payg" | "paygo" | "pay_as_go" | "metered" | "standard" | "api"
1044 | "api_key" | "default" => CredentialProduct::PayAsYouGo,
1045 _ => CredentialProduct::Unprovable,
1046 };
1047 }
1048 match visible_minimax_credential_is_plan_shaped(config, identity, provider_config) {
1049 Some(true) => CredentialProduct::Plan,
1050 Some(false) => CredentialProduct::PayAsYouGo,
1051 None => CredentialProduct::Unprovable,
1052 }
1053 }
1054
1055 /// CSDN 星图 sells the Coding Plan and metered marketplace models over the
1056 /// same `ai.csdn.net/api/model/v1` endpoint and `CSDN_API_KEY` slot, so the
1057 /// product comes from an explicit saved pay mode or the routed model:
1058 /// `glm_for_coding` is the Coding Plan's dedicated model id — the route the
1059 /// plan sells — while every other model on the platform endpoint is ordinary
1060 /// metered marketplace access. An explicit operator-set mode wins over the
1061 /// model in both directions; an unrecognized mode is not a product claim.
1062 fn csdn_credential_product(provider_config: Option<&ProviderConfig>) -> CredentialProduct {
1063 if let Some(mode) = provider_config
1064 .and_then(|config| config.mode.as_deref())
1065 .filter(|mode| !mode.trim().is_empty())
1066 .map(normalized)
1067 {
1068 return match mode.as_str() {
1069 "coding_plan" | "codingplan" | "plan" | "subscription" | "subscription_plan" => {
1070 CredentialProduct::Plan
1071 }
1072 "pay_as_you_go" | "payg" | "paygo" | "pay_as_go" | "metered" | "standard" | "api"
1073 | "api_key" | "default" => CredentialProduct::PayAsYouGo,
1074 _ => CredentialProduct::Unprovable,
1075 };
1076 }
1077 // No table at all still resolves to the plan model: `glm_for_coding` is
1078 // the shipped default for the `csdn` route.
1079 let model = provider_config
1080 .and_then(|entry| entry.model.as_deref())
1081 .map(str::trim)
1082 .filter(|model| !model.is_empty())
1083 .unwrap_or(codewhale_config::descriptors::defaults::DEFAULT_CSDN_MODEL);
1084 if model.eq_ignore_ascii_case(codewhale_config::descriptors::defaults::DEFAULT_CSDN_MODEL) {
1085 CredentialProduct::Plan
1086 } else {
1087 CredentialProduct::PayAsYouGo
1088 }
1089 }
1090
1091 /// Whether a MiniMax credential is visible in non-secret-store provenance,
1092 /// and if so whether it carries the Token Plan (`sk-cp…`) product prefix.
1093 ///
1094 /// Only the product marker is returned — the credential value never leaves
1095 /// this function, nothing is logged, and the secret store is never opened.
1096 /// `None` means "no visible credential", which is the honest answer for a
1097 /// key resolved from the keyring, from an OAuth/command source, or from
1098 /// nowhere at all.
1099 fn visible_minimax_credential_is_plan_shaped(
1100 config: &Config,
1101 identity: &ProviderIdentity,
1102 provider_config: Option<&ProviderConfig>,
1103 ) -> Option<bool> {
1104 let is_plan_shaped = |key: &str| key.trim_start().starts_with("sk-cp");
1105 // 1. An explicit `[providers.minimax*] api_key` is file-owned route truth.
1106 if let Some(key) = provider_config
1107 .and_then(|config| config.api_key.as_deref())
1108 .filter(|key| {
1109 codewhale_config::classify_config_api_key_value(key)
1110 == codewhale_config::ConfigApiKeyValueKind::Literal
1111 })
1112 .map(str::trim)
1113 {
1114 return Some(is_plan_shaped(key));
1115 }
1116 // 2. `api_key_env = "…"` binds one variable to this route by name, so the
1117 // binding itself is config-owned provenance even though the value is
1118 // ambient.
1119 if let Some(value) = provider_config
1120 .and_then(|config| config.api_key_env.as_deref())
1121 .map(str::trim)
1122 .filter(|name| !name.is_empty())
1123 .and_then(|name| std::env::var(name).ok())
1124 .filter(|value| !value.trim().is_empty())
1125 {
1126 return Some(is_plan_shaped(&value));
1127 }
1128 // 3. Ambient `MINIMAX_API_KEY` only describes the route when the route is
1129 // still an official MiniMax endpoint. Credential resolution refuses to
1130 // send ambient provider keys to a custom host, so on a custom endpoint
1131 // the exported key proves nothing about what this route bills.
1132 if config.provider_uses_custom_endpoint(identity) {
1133 return None;
1134 }
1135 std::env::var("MINIMAX_API_KEY")
1136 .ok()
1137 .filter(|key| !key.trim().is_empty())
1138 .map(|key| is_plan_shaped(&key))
1139 }
1140
1141 fn xiaomi_is_explicit_pay_as_you_go(config: Option<&ProviderConfig>) -> bool {
1142 if let Some(mode) = std::env::var("XIAOMI_MIMO_MODE")
1143 .ok()
1144 .filter(|mode| !mode.trim().is_empty())
1145 .map(|mode| normalized(&mode))
1146 {
1147 return matches!(
1148 mode.as_str(),
1149 "standard" | "default" | "payg" | "paygo" | "pay_as_you_go" | "pay_as_go"
1150 );
1151 }
1152 if let Some(base_url) = std::env::var("XIAOMI_MIMO_BASE_URL")
1153 .ok()
1154 .filter(|base_url| !base_url.trim().is_empty())
1155 {
1156 return !base_url.to_ascii_lowercase().contains("token-plan-");
1157 }
1158 let token_plan_env = ["XIAOMI_MIMO_TOKEN_PLAN_API_KEY", "MIMO_TOKEN_PLAN_API_KEY"]
1159 .iter()
1160 .any(|name| std::env::var(name).is_ok_and(|value| !value.trim().is_empty()));
1161 let standard_env = ["XIAOMI_MIMO_API_KEY", "XIAOMI_API_KEY", "MIMO_API_KEY"]
1162 .iter()
1163 .any(|name| std::env::var(name).is_ok_and(|value| !value.trim().is_empty()));
1164 if standard_env && !token_plan_env {
1165 return true;
1166 }
1167 let Some(config) = config else {
1168 // The shipped MiMo default is a token-plan endpoint.
1169 return false;
1170 };
1171 if let Some(mode) = config
1172 .mode
1173 .as_deref()
1174 .filter(|mode| !mode.trim().is_empty())
1175 .map(normalized)
1176 {
1177 return matches!(
1178 mode.as_str(),
1179 "pay_as_you_go" | "payg" | "paygo" | "api" | "standard" | "default"
1180 );
1181 }
1182 if let Some(api_key) = config.api_key.as_deref().filter(|key| {
1183 codewhale_config::classify_config_api_key_value(key)
1184 == codewhale_config::ConfigApiKeyValueKind::Literal
1185 }) {
1186 return !api_key.trim_start().starts_with("tp-");
1187 }
1188 config.base_url.as_deref().is_some_and(|base_url| {
1189 let lower = base_url.to_ascii_lowercase();
1190 !lower.contains("token-plan-") && !lower.contains("token_plan_")
1191 })
1192 }
1193
1194 #[cfg(test)]
1195 mod tests {
1196 use super::*;
1197 use codewhale_config::pricing::CostCurrency;
1198 use codewhale_models::Usage;
1199
1200 fn config_with(provider: ProviderKind, provider_config: ProviderConfig) -> Config {
1201 let mut config = Config::default();
1202 *config
1203 .provider_config_for_mut(&config.test_identity_for_kind(provider))
1204 .unwrap() = provider_config;
1205 config
1206 }
1207
1208 /// Clear every variable that could otherwise supply a Moonshot endpoint,
1209 /// so the resolver has to answer from the config alone.
1210 fn moonshot_endpoint_env_lock() -> [crate::test_support::EnvVarGuard; 4] {
1211 [
1212 crate::test_support::EnvVarGuard::remove("CODEWHALE_BASE_URL"),
1213 crate::test_support::EnvVarGuard::remove("DEEPSEEK_BASE_URL"),
1214 crate::test_support::EnvVarGuard::remove("MOONSHOT_BASE_URL"),
1215 crate::test_support::EnvVarGuard::remove("KIMI_BASE_URL"),
1216 ]
1217 }
1218
1219 #[test]
1220 fn imported_token_moonshot_without_table_base_url_bills_membership_quota() {
1221 let _lock = crate::test_support::lock_test_env();
1222 let _env = moonshot_endpoint_env_lock();
1223 // An imported Kimi Code token with no `base_url` in its table. The
1224 // table field is empty, but the route still resolves to the exact
1225 // membership endpoint, so classifying from the raw field would call a
1226 // membership quota metered and invent dollars against it.
1227 let config = config_with(
1228 ProviderKind::Moonshot,
1229 ProviderConfig {
1230 auth_mode: Some("kimi_oauth".to_string()),
1231 ..ProviderConfig::default()
1232 },
1233 );
1234 assert_eq!(
1235 config.base_url_for_route(&config.test_identity_for_kind(ProviderKind::Moonshot)),
1236 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL
1237 );
1238
1239 let billing = for_route(
1240 &config,
1241 &(config).test_identity_for_kind(ProviderKind::Moonshot),
1242 );
1243 assert_eq!(
1244 billing,
1245 BillingPresentation::Subscription("Kimi Code quota")
1246 );
1247 assert!(!billing.shows_money());
1248
1249 let chip = usage_chip(
1250 billing,
1251 ProviderKind::Moonshot,
1252 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_MODEL,
1253 12.34,
1254 CostCurrency::Usd,
1255 None,
1256 );
1257 assert!(!matches!(chip, UsageChip::Money(_)));
1258 assert_eq!(
1259 format_usage_chip(&chip, codewhale_localization::Locale::En).as_deref(),
1260 Some("usage: Kimi Code quota")
1261 );
1262 // The label names the membership product, never the credential import
1263 // mechanism, and never a dollar figure.
1264 assert!(
1265 !format_usage_chip(&chip, codewhale_localization::Locale::En)
1266 .unwrap_or_default()
1267 .contains("OAuth")
1268 );
1269 assert!(
1270 !format_usage_chip(&chip, codewhale_localization::Locale::En)
1271 .unwrap_or_default()
1272 .contains("imported token")
1273 );
1274 assert!(
1275 !format_usage_chip(&chip, codewhale_localization::Locale::En)
1276 .unwrap_or_default()
1277 .contains('$')
1278 );
1279 }
1280
1281 #[test]
1282 fn turn_complete_kimi_code_receipt_accrues_no_dollars() {
1283 let _lock = crate::test_support::lock_test_env();
1284 let _env = moonshot_endpoint_env_lock();
1285 // Pins the exact decision the `EngineEvent::TurnComplete` arm makes:
1286 // classify from the event's immutable `base_url` receipt, then accrue
1287 // only when the result shows money. The ambient config deliberately
1288 // points at a *different* provider to prove the arm cannot re-resolve
1289 // its way onto another route's price list.
1290 let mut config = config_with(
1291 ProviderKind::Deepseek,
1292 ProviderConfig {
1293 api_key: Some("sk-session-deepseek".to_string()),
1294 ..ProviderConfig::default()
1295 },
1296 );
1297 config.provider = Some("deepseek".to_string());
1298
1299 let billing = for_dispatched_route(
1300 &config,
1301 DispatchedRoute {
1302 provider: ProviderKind::Moonshot,
1303 base_url: "https://api.kimi.com/coding/v1",
1304 },
1305 );
1306 assert_eq!(
1307 billing,
1308 BillingPresentation::Subscription("Kimi Code quota")
1309 );
1310 // `shows_money()` is the gate guarding `accrue_session_cost_estimate`.
1311 assert!(!billing.shows_money());
1312
1313 // A missing receipt must not fall back to the session's metered route.
1314 let no_receipt = for_dispatched_route(
1315 &config,
1316 DispatchedRoute {
1317 provider: ProviderKind::Moonshot,
1318 base_url: "",
1319 },
1320 );
1321 assert_eq!(no_receipt, BillingPresentation::Unknown);
1322 assert!(!no_receipt.shows_money());
1323 }
1324
1325 #[test]
1326 fn moonshot_ambient_and_dispatch_billing_agree_on_the_resolved_endpoint() {
1327 let _lock = crate::test_support::lock_test_env();
1328 let _env = moonshot_endpoint_env_lock();
1329 let cases = [
1330 // (table base_url, auth_mode, expected)
1331 (
1332 None,
1333 Some("kimi_oauth"),
1334 BillingPresentation::Subscription("Kimi Code quota"),
1335 ),
1336 (None, None, BillingPresentation::Metered),
1337 (
1338 Some("https://api.kimi.com/coding/v1"),
1339 None,
1340 BillingPresentation::Subscription("Kimi Code quota"),
1341 ),
1342 (
1343 Some("https://api.moonshot.ai/v1"),
1344 None,
1345 BillingPresentation::Metered,
1346 ),
1347 (
1348 Some("https://proxy.example.test/v1"),
1349 None,
1350 BillingPresentation::Unknown,
1351 ),
1352 ];
1353 for (base_url, auth_mode, expected) in cases {
1354 let config = config_with(
1355 ProviderKind::Moonshot,
1356 ProviderConfig {
1357 base_url: base_url.map(str::to_string),
1358 auth_mode: auth_mode.map(str::to_string),
1359 ..ProviderConfig::default()
1360 },
1361 );
1362 let resolved =
1363 config.base_url_for_route(&config.test_identity_for_kind(ProviderKind::Moonshot));
1364 let ambient = for_route(
1365 &config,
1366 &(config).test_identity_for_kind(ProviderKind::Moonshot),
1367 );
1368 let dispatched = for_dispatched_route(
1369 &config,
1370 DispatchedRoute {
1371 provider: ProviderKind::Moonshot,
1372 base_url: &resolved,
1373 },
1374 );
1375 assert_eq!(ambient, expected, "{base_url:?}/{auth_mode:?}");
1376 assert_eq!(
1377 ambient, dispatched,
1378 "{base_url:?}/{auth_mode:?} resolved to {resolved}: the pre-dispatch and \
1379 receipt classifications must not be able to disagree"
1380 );
1381 }
1382 }
1383
1384 #[test]
1385 fn moonshot_custom_gateway_is_unknown_not_metered() {
1386 let _lock = crate::test_support::lock_test_env();
1387 let _env = moonshot_endpoint_env_lock();
1388 // A Moonshot-compatible gateway sells its own product on its own
1389 // terms. Inheriting Moonshot's metered price list would invent
1390 // dollars; inheriting a membership label would invent a quota.
1391 for base_url in [
1392 "https://proxy.example.test/v1",
1393 "https://gateway.internal.test/moonshot/v1",
1394 ] {
1395 let config = config_with(
1396 ProviderKind::Moonshot,
1397 ProviderConfig {
1398 base_url: Some(base_url.to_string()),
1399 ..ProviderConfig::default()
1400 },
1401 );
1402 let billing = for_route(
1403 &config,
1404 &(config).test_identity_for_kind(ProviderKind::Moonshot),
1405 );
1406 assert_eq!(
1407 billing,
1408 BillingPresentation::Unknown,
1409 "{base_url} must not inherit a Moonshot product"
1410 );
1411 assert!(!billing.shows_money());
1412 let chip = usage_chip(
1413 billing,
1414 ProviderKind::Moonshot,
1415 "kimi-k2.7-code",
1416 12.34,
1417 CostCurrency::Usd,
1418 None,
1419 );
1420 assert!(!matches!(chip, UsageChip::Money(_)));
1421 assert!(
1422 !format_usage_chip(&chip, codewhale_localization::Locale::En)
1423 .unwrap_or_default()
1424 .contains('$')
1425 );
1426 }
1427 }
1428
1429 #[test]
1430 fn moonshot_direct_platform_stays_metered_with_priced_model() {
1431 let config = config_with(
1432 ProviderKind::Moonshot,
1433 ProviderConfig {
1434 base_url: Some("https://api.moonshot.ai/v1".to_string()),
1435 ..ProviderConfig::default()
1436 },
1437 );
1438 let billing = for_route(
1439 &config,
1440 &(config).test_identity_for_kind(ProviderKind::Moonshot),
1441 );
1442 assert_eq!(billing, BillingPresentation::Metered);
1443 assert!(billing.shows_money());
1444 let chip = usage_chip(
1445 billing,
1446 ProviderKind::Moonshot,
1447 "kimi-k2.7-code",
1448 0.42,
1449 CostCurrency::Usd,
1450 None,
1451 );
1452 assert!(matches!(chip, UsageChip::Money(_)));
1453 assert!(
1454 format_usage_chip(&chip, codewhale_localization::Locale::En)
1455 .unwrap_or_default()
1456 .contains('$')
1457 );
1458 }
1459
1460 #[test]
1461 fn moonshot_exact_kimi_code_endpoint_is_subscription_quota() {
1462 let config = config_with(
1463 ProviderKind::Moonshot,
1464 ProviderConfig {
1465 base_url: Some("https://api.kimi.com/coding/v1".to_string()),
1466 ..ProviderConfig::default()
1467 },
1468 );
1469 let billing = for_route(
1470 &config,
1471 &(config).test_identity_for_kind(ProviderKind::Moonshot),
1472 );
1473 assert_eq!(
1474 billing,
1475 BillingPresentation::Subscription("Kimi Code quota")
1476 );
1477 assert!(!billing.shows_money());
1478 // `kimi-k2.7-code` is priced on the metered route; the subscription
1479 // classification must still win over the priced row.
1480 let chip = usage_chip(
1481 billing,
1482 ProviderKind::Moonshot,
1483 "kimi-k2.7-code",
1484 12.34,
1485 CostCurrency::Usd,
1486 None,
1487 );
1488 assert!(!matches!(chip, UsageChip::Money(_)));
1489 assert_eq!(
1490 chip,
1491 UsageChip::Allowance {
1492 label: "Kimi Code quota",
1493 used_pct: None,
1494 }
1495 );
1496 assert!(
1497 !format_usage_chip(&chip, codewhale_localization::Locale::En)
1498 .unwrap_or_default()
1499 .contains('$')
1500 );
1501 }
1502
1503 #[test]
1504 fn moonshot_neighboring_kimi_paths_are_unknown_not_metered() {
1505 let _lock = crate::test_support::lock_test_env();
1506 let _env = moonshot_endpoint_env_lock();
1507 // A Kimi-hosted path that is not the exact membership endpoint names
1508 // no product we can stand behind. It must claim neither the Kimi Code
1509 // quota nor Moonshot's metered price list — the pre-dispatch and
1510 // receipt answers are the same fail-closed Unknown.
1511 for base_url in [
1512 "https://api.kimi.com/coding/v2",
1513 "https://api.kimi.com/v1",
1514 "https://api.kimi.com/coding/v1/preview",
1515 ] {
1516 let config = config_with(
1517 ProviderKind::Moonshot,
1518 ProviderConfig {
1519 base_url: Some(base_url.to_string()),
1520 ..ProviderConfig::default()
1521 },
1522 );
1523 let billing = for_route(
1524 &config,
1525 &(config).test_identity_for_kind(ProviderKind::Moonshot),
1526 );
1527 assert_eq!(
1528 billing,
1529 BillingPresentation::Unknown,
1530 "{base_url} must claim neither Kimi Code quota nor metered dollars"
1531 );
1532 assert!(!billing.shows_money());
1533 assert_eq!(
1534 billing,
1535 for_dispatched_route(
1536 &config,
1537 DispatchedRoute {
1538 provider: ProviderKind::Moonshot,
1539 base_url,
1540 },
1541 )
1542 );
1543 }
1544 }
1545
1546 /// The second release blocker. `apply_env_overrides` merges
1547 /// `MOONSHOT_BASE_URL`/`KIMI_BASE_URL` into the ACTIVE provider's table
1548 /// only, so a Moonshot child spawned from (say) a DeepSeek session has an
1549 /// empty `[providers.moonshot]` entry no matter what the operator
1550 /// exported. Re-reading that config calls a membership route metered;
1551 /// the dispatch receipt — the endpoint the child's client was actually
1552 /// built with — tells the truth.
1553 #[test]
1554 fn dispatched_moonshot_receipt_owns_billing_over_any_later_config_state() {
1555 let _lock = crate::test_support::lock_test_env();
1556 // Env-only endpoint selection: nothing is in the provider table.
1557 let _generic = crate::test_support::EnvVarGuard::remove("CODEWHALE_BASE_URL");
1558 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_BASE_URL");
1559 let _moonshot = crate::test_support::EnvVarGuard::remove("MOONSHOT_BASE_URL");
1560 let _kimi = crate::test_support::EnvVarGuard::set(
1561 "KIMI_BASE_URL",
1562 "https://api.kimi.com/coding/v1",
1563 );
1564 let config = config_with(ProviderKind::Moonshot, ProviderConfig::default());
1565
1566 // The pre-dispatch answer resolves the same env-selected endpoint
1567 // instead of reading the empty provider table — that blind spot is
1568 // what let an imported-token membership route look metered.
1569 assert_eq!(
1570 for_route(
1571 &config,
1572 &(config).test_identity_for_kind(ProviderKind::Moonshot)
1573 ),
1574 BillingPresentation::Subscription("Kimi Code quota")
1575 );
1576
1577 // A receipt still wins outright. A turn dispatched on the direct
1578 // platform bills metered even though the config resolves to the
1579 // membership host now.
1580 assert_eq!(
1581 for_dispatched_route(
1582 &config,
1583 DispatchedRoute {
1584 provider: ProviderKind::Moonshot,
1585 base_url: "https://api.moonshot.ai/v1",
1586 },
1587 ),
1588 BillingPresentation::Metered,
1589 "the endpoint the turn actually dispatched to owns its billing"
1590 );
1591 assert_eq!(
1592 for_dispatched_route(
1593 &config,
1594 DispatchedRoute {
1595 provider: ProviderKind::Moonshot,
1596 base_url: "https://api.kimi.com/coding/v1",
1597 },
1598 ),
1599 BillingPresentation::Subscription("Kimi Code quota")
1600 );
1601 }
1602
1603 /// A dispatched endpoint must NAME a known product. The exact direct
1604 /// platform is metered; a gateway host, a neighboring Kimi path, and a
1605 /// blank receipt are all ambiguous and fail closed.
1606 #[test]
1607 fn dispatched_moonshot_endpoint_must_name_a_known_product() {
1608 assert_eq!(
1609 for_dispatched_route(
1610 &Config::default(),
1611 DispatchedRoute {
1612 provider: ProviderKind::Moonshot,
1613 base_url: "https://api.moonshot.ai/v1",
1614 },
1615 ),
1616 BillingPresentation::Metered
1617 );
1618 for ambiguous in [
1619 "",
1620 " ",
1621 "https://api.kimi.com/v1",
1622 "https://api.kimi.com/coding/v1/preview",
1623 "https://gateway.internal.example/v1",
1624 ] {
1625 let billing = for_dispatched_route(
1626 &Config::default(),
1627 DispatchedRoute {
1628 provider: ProviderKind::Moonshot,
1629 base_url: ambiguous,
1630 },
1631 );
1632 assert_eq!(
1633 billing,
1634 BillingPresentation::Unknown,
1635 "{ambiguous:?} names no Moonshot product"
1636 );
1637 assert!(!billing.shows_money());
1638 }
1639 }
1640
1641 #[test]
1642 fn chatgpt_plan_never_claims_api_dollars() {
1643 let billing = for_dispatched_receipt(DispatchedReceipt {
1644 provider: ProviderKind::OpenaiCodex,
1645 identity: Some("openai_codex"),
1646 base_url: "https://api.openai.com/v1",
1647 product: RouteProduct::Subscription("ChatGPT plan allowance"),
1648 });
1649 assert_eq!(
1650 billing,
1651 BillingPresentation::Subscription("ChatGPT plan allowance")
1652 );
1653 let chip = usage_chip(
1654 billing,
1655 ProviderKind::OpenaiCodex,
1656 "gpt-5.5",
1657 12.34,
1658 CostCurrency::Usd,
1659 None,
1660 );
1661 assert_eq!(
1662 format_usage_chip(&chip, codewhale_localization::Locale::En).as_deref(),
1663 Some("usage: ChatGPT plan allowance")
1664 );
1665 assert!(
1666 !format_usage_chip(&chip, codewhale_localization::Locale::En)
1667 .unwrap_or_default()
1668 .contains('$')
1669 );
1670 }
1671
1672 #[test]
1673 fn chatgpt_plan_requires_captured_official_grant_and_endpoint() {
1674 let receipt = DispatchedReceipt {
1675 provider: ProviderKind::OpenaiCodex,
1676 identity: Some("openai_codex"),
1677 base_url: "https://api.openai.com/v1",
1678 product: RouteProduct::Subscription("ChatGPT plan allowance"),
1679 };
1680 for product in [
1681 RouteProduct::Unproven,
1682 RouteProduct::Metered,
1683 RouteProduct::Subscription("Codex OAuth quota"),
1684 ] {
1685 assert_eq!(
1686 for_dispatched_receipt(DispatchedReceipt { product, ..receipt }),
1687 BillingPresentation::Unknown,
1688 "{product:?} is not an official ChatGPT grant"
1689 );
1690 }
1691 for endpoint in [
1692 "https://gateway.example/v1",
1693 "https://api.openai.com.example.net/v1",
1694 "https://api.openai.com/v1/preview",
1695 "https://api.openai.com/v1?billing=plan",
1696 "https://api.openai.com/v1#plan",
1697 "https://user:secret@api.openai.com/v1",
1698 "http://api.openai.com/v1",
1699 "",
1700 ] {
1701 assert_eq!(
1702 for_dispatched_receipt(DispatchedReceipt {
1703 base_url: endpoint,
1704 ..receipt
1705 }),
1706 BillingPresentation::Unknown,
1707 "{endpoint} is not the official plan endpoint"
1708 );
1709 }
1710 assert_eq!(
1711 for_dispatched_receipt(DispatchedReceipt {
1712 provider: ProviderKind::Openai,
1713 identity: Some("openai"),
1714 ..receipt
1715 }),
1716 BillingPresentation::Metered,
1717 "API-key provider must not inherit ChatGPT plan allowance"
1718 );
1719 assert_eq!(
1720 for_dispatched_receipt(receipt),
1721 BillingPresentation::Subscription("ChatGPT plan allowance"),
1722 "receipt interpretation needs no ambient config or credentials"
1723 );
1724 }
1725
1726 #[test]
1727 fn chatgpt_plan_without_owned_grant_stays_unknown() {
1728 let config = Config::default();
1729 assert_eq!(
1730 for_route_with_endpoint(
1731 &config,
1732 &(config).test_identity_for_kind(ProviderKind::OpenaiCodex),
1733 "https://api.openai.com/v1"
1734 ),
1735 BillingPresentation::Unknown
1736 );
1737 assert_eq!(
1738 for_endpoint_without_config(
1739 ProviderKind::OpenaiCodex,
1740 Some("https://api.openai.com/v1")
1741 ),
1742 BillingPresentation::Unknown
1743 );
1744 assert_eq!(
1745 billing_surface_for_dispatch(
1746 Some(&config),
1747 &(config).test_identity_for_kind(ProviderKind::OpenaiCodex),
1748 Some("https://api.openai.com/v1")
1749 ),
1750 Some(crate::pricing::UNCLASSIFIED_BILLING_SURFACE)
1751 );
1752 }
1753
1754 #[test]
1755 fn xai_api_key_fallback_is_metered_when_external_oauth_is_unavailable() {
1756 let _lock = crate::test_support::lock_test_env();
1757 let temp = tempfile::tempdir().expect("xAI billing fixture");
1758 let grok_path = temp.path().join("external-grok-auth.json");
1759 std::fs::write(&grok_path, "must-never-be-read").expect("external trap");
1760 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", temp.path());
1761 let _grok = crate::test_support::EnvVarGuard::set("GROK_AUTH_PATH", &grok_path);
1762
1763 let config = config_with(
1764 ProviderKind::Xai,
1765 ProviderConfig {
1766 auth_mode: Some("oauth".to_string()),
1767 api_key: Some("xai-api-key".to_string()),
1768 ..ProviderConfig::default()
1769 },
1770 );
1771 codewhale_runtime::external_credentials::reset_side_effect_trap();
1772 assert_eq!(
1773 for_route(&config, &(config).test_identity_for_kind(ProviderKind::Xai)),
1774 BillingPresentation::Metered
1775 );
1776 assert_eq!(
1777 codewhale_runtime::external_credentials::side_effect_trap_counts(),
1778 (0, 0)
1779 );
1780 assert_eq!(
1781 std::fs::read_to_string(grok_path).expect("external trap unchanged"),
1782 "must-never-be-read"
1783 );
1784 }
1785
1786 #[test]
1787 fn opencode_go_quota_never_claims_token_dollars() {
1788 let billing = for_route(
1789 &Config::default(),
1790 &(Config::default()).test_identity_for_kind(ProviderKind::OpencodeGo),
1791 );
1792 assert_eq!(
1793 billing,
1794 BillingPresentation::Subscription("OpenCode Go quota")
1795 );
1796 let chip = usage_chip(
1797 billing,
1798 ProviderKind::OpencodeGo,
1799 "deepseek-v4-pro",
1800 12.34,
1801 CostCurrency::Usd,
1802 None,
1803 );
1804 assert!(
1805 !format_usage_chip(&chip, codewhale_localization::Locale::En)
1806 .unwrap_or_default()
1807 .contains('$')
1808 );
1809 assert_eq!(
1810 for_child_route(
1811 ProviderKind::Deepseek,
1812 BillingPresentation::Metered,
1813 ProviderKind::OpencodeGo,
1814 None,
1815 ),
1816 BillingPresentation::Unknown,
1817 "provider identity alone must not claim OpenCode Go quota"
1818 );
1819 assert_eq!(
1820 for_child_route(
1821 ProviderKind::Deepseek,
1822 BillingPresentation::Metered,
1823 ProviderKind::OpencodeGo,
1824 Some(BillingPresentation::Subscription("OpenCode Go quota")),
1825 ),
1826 BillingPresentation::Subscription("OpenCode Go quota"),
1827 "the child's own route truth is what may claim the quota"
1828 );
1829 }
1830
1831 #[test]
1832 fn zai_coding_plan_endpoint_never_claims_api_dollars() {
1833 let config = config_with(
1834 ProviderKind::Zai,
1835 ProviderConfig {
1836 base_url: Some("https://api.z.ai/api/coding/paas/v4".to_string()),
1837 ..ProviderConfig::default()
1838 },
1839 );
1840 let billing = for_route(&config, &(config).test_identity_for_kind(ProviderKind::Zai));
1841 assert_eq!(
1842 billing,
1843 BillingPresentation::Subscription("Z.ai Coding Plan quota")
1844 );
1845 let chip = usage_chip(
1846 billing,
1847 ProviderKind::Zai,
1848 "glm-5.2",
1849 0.05,
1850 CostCurrency::Usd,
1851 None,
1852 );
1853 assert!(
1854 !format_usage_chip(&chip, codewhale_localization::Locale::En)
1855 .unwrap_or_default()
1856 .contains('$')
1857 );
1858 }
1859
1860 #[test]
1861 fn zai_default_coding_endpoint_never_claims_api_dollars() {
1862 // The route resolves its shipped default, so the ambient generic
1863 // endpoint override has to be locked out for the assertion to be
1864 // about the default at all.
1865 let _lock = crate::test_support::lock_test_env();
1866 let _generic = crate::test_support::EnvVarGuard::remove("CODEWHALE_BASE_URL");
1867 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_BASE_URL");
1868 let config = config_with(ProviderKind::Zai, ProviderConfig::default());
1869 assert_eq!(
1870 for_route(&config, &(config).test_identity_for_kind(ProviderKind::Zai)),
1871 BillingPresentation::Subscription("Z.ai Coding Plan quota")
1872 );
1873 }
1874
1875 #[test]
1876 fn stepfun_payg_shows_money_but_step_plan_stays_subscription_billed() {
1877 // Same reason as the Z.ai default test: the PAYG half asserts against
1878 // StepFun's shipped default endpoint.
1879 let _lock = crate::test_support::lock_test_env();
1880 let _generic = crate::test_support::EnvVarGuard::remove("CODEWHALE_BASE_URL");
1881 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_BASE_URL");
1882 let payg_billing = for_route(
1883 &Config::default(),
1884 &(Config::default()).test_identity_for_kind(ProviderKind::Stepfun),
1885 );
1886 assert_eq!(payg_billing, BillingPresentation::Metered);
1887 let payg_chip = usage_chip(
1888 payg_billing,
1889 ProviderKind::Stepfun,
1890 "step-5-preview",
1891 0.42,
1892 CostCurrency::Usd,
1893 None,
1894 );
1895 assert_eq!(
1896 format_usage_chip(&payg_chip, codewhale_localization::Locale::En).as_deref(),
1897 Some("$0.42")
1898 );
1899 let unpriced_ga_chip = usage_chip(
1900 payg_billing,
1901 ProviderKind::Stepfun,
1902 codewhale_config::descriptors::defaults::DEFAULT_STEPFUN_MODEL,
1903 0.0,
1904 CostCurrency::Usd,
1905 None,
1906 );
1907 assert_eq!(
1908 format_usage_chip(&unpriced_ga_chip, codewhale_localization::Locale::En),
1909 None
1910 );
1911
1912 let plan_config = config_with(
1913 ProviderKind::Stepfun,
1914 ProviderConfig {
1915 base_url: Some("https://api.stepfun.ai/step_plan/v1".to_string()),
1916 ..ProviderConfig::default()
1917 },
1918 );
1919 let plan_billing = for_route(
1920 &plan_config,
1921 &(plan_config).test_identity_for_kind(ProviderKind::Stepfun),
1922 );
1923 assert_eq!(
1924 plan_billing,
1925 BillingPresentation::Subscription("StepFun Step Plan quota")
1926 );
1927 let plan_chip = usage_chip(
1928 plan_billing,
1929 ProviderKind::Stepfun,
1930 codewhale_config::descriptors::defaults::DEFAULT_STEPFUN_MODEL,
1931 0.42,
1932 CostCurrency::Usd,
1933 None,
1934 );
1935 assert!(
1936 !format_usage_chip(&plan_chip, codewhale_localization::Locale::En)
1937 .unwrap_or_default()
1938 .contains('$')
1939 );
1940
1941 assert_eq!(
1942 for_child_route(
1943 ProviderKind::Deepseek,
1944 BillingPresentation::Metered,
1945 ProviderKind::Stepfun,
1946 None,
1947 ),
1948 BillingPresentation::Unknown
1949 );
1950 }
1951
1952 /// A dual-mode child provider with no dispatch config is *unknown*, not a
1953 /// subscription. It still never shows dollars, but the distinction is what
1954 /// keeps its spend inside `/cost`'s coverage denominator instead of being
1955 /// excused as quota-billed (#4318).
1956 #[test]
1957 fn routed_zai_child_never_claims_api_dollars_without_full_route_config() {
1958 let billing = for_child_route(
1959 ProviderKind::Deepseek,
1960 BillingPresentation::Metered,
1961 ProviderKind::Zai,
1962 None,
1963 );
1964 assert_eq!(
1965 billing,
1966 BillingPresentation::Unknown,
1967 "without the child's route truth, fail closed instead of guessing a quota"
1968 );
1969 assert!(!billing.shows_money());
1970 assert_eq!(billing.label(), Some("unknown"));
1971 }
1972
1973 /// Child-route billing for each shape a child can take. Without the
1974 /// child's own provenance, only a local runtime is exactly non-metered;
1975 /// every other cross-provider child fails closed to Unknown, and Unknown
1976 /// (unlike a subscription label) keeps the turn inside `/cost`'s money
1977 /// coverage denominator instead of excusing it as quota-billed (#4318).
1978 #[test]
1979 fn child_route_billing_fails_closed_for_every_ambiguous_provider() {
1980 use crate::pricing::UnpricedReason;
1981
1982 let usage = codewhale_models::Usage {
1983 input_tokens: 10_000,
1984 output_tokens: 1_000,
1985 ..Default::default()
1986 };
1987 let now = chrono::Utc::now();
1988
1989 // Nothing about a provider name — not an aggregator, not a first-party
1990 // PAYG API, not an OAuth-only broker — is evidence of what this child
1991 // turn billed. Every one of them is Unknown without provenance, and
1992 // the cost audit counts them toward money coverage rather than
1993 // excusing them.
1994 for provider in [
1995 ProviderKind::Openrouter,
1996 ProviderKind::Openai,
1997 ProviderKind::Zai,
1998 ProviderKind::Moonshot,
1999 ProviderKind::Anthropic,
2000 ProviderKind::XiaomiMimo,
2001 ProviderKind::Xai,
2002 ProviderKind::Minimax,
2003 ProviderKind::MinimaxAnthropic,
2004 ProviderKind::Stepfun,
2005 ProviderKind::Custom,
2006 ProviderKind::OpenaiCodex,
2007 ProviderKind::OpencodeGo,
2008 ] {
2009 let billing = for_child_route(
2010 ProviderKind::Deepseek,
2011 BillingPresentation::Metered,
2012 provider,
2013 None,
2014 );
2015 assert_eq!(billing, BillingPresentation::Unknown, "{provider:?}");
2016 assert!(!billing.shows_money(), "{provider:?}");
2017 let audit = crate::pricing::audit_turn_cost_for_route(
2018 provider,
2019 "some-model",
2020 None,
2021 &usage,
2022 now,
2023 billing,
2024 );
2025 assert_eq!(
2026 audit.unpriced_reason,
2027 Some(UnpricedReason::UnknownBillingBasis),
2028 "{provider:?}"
2029 );
2030 assert!(
2031 audit.counts_toward_money_coverage(),
2032 "{provider:?} must stay in the coverage denominator"
2033 );
2034 }
2035
2036 // A local runtime has no provider bill under any configuration, so it
2037 // is exactly non-metered and is excluded from money coverage.
2038 for provider in [
2039 ProviderKind::Ollama,
2040 ProviderKind::Sglang,
2041 ProviderKind::Vllm,
2042 ] {
2043 let billing = for_child_route(
2044 ProviderKind::Deepseek,
2045 BillingPresentation::Metered,
2046 provider,
2047 None,
2048 );
2049 assert_eq!(billing, BillingPresentation::Local, "{provider:?}");
2050 let audit = crate::pricing::audit_turn_cost_for_route(
2051 provider,
2052 "some-model",
2053 None,
2054 &usage,
2055 now,
2056 billing,
2057 );
2058 assert_eq!(
2059 audit.unpriced_reason,
2060 Some(UnpricedReason::NotMoneyMetered),
2061 "{provider:?}"
2062 );
2063 assert!(!audit.counts_toward_money_coverage(), "{provider:?}");
2064 }
2065
2066 // A child on the parent's own provider ran the parent's exact route,
2067 // so it inherits the parent's frozen billing — the one inheritance
2068 // that is a fact rather than a guess.
2069 assert_eq!(
2070 for_child_route(
2071 ProviderKind::Deepseek,
2072 BillingPresentation::Metered,
2073 ProviderKind::Deepseek,
2074 None,
2075 ),
2076 BillingPresentation::Metered
2077 );
2078
2079 // The child's own captured provenance is the only thing that prices
2080 // (or excuses) the route.
2081 assert_eq!(
2082 for_child_route(
2083 ProviderKind::Deepseek,
2084 BillingPresentation::Metered,
2085 ProviderKind::Openrouter,
2086 Some(BillingPresentation::Metered),
2087 ),
2088 BillingPresentation::Metered
2089 );
2090 assert_eq!(
2091 for_child_route(
2092 ProviderKind::Deepseek,
2093 BillingPresentation::Metered,
2094 ProviderKind::Anthropic,
2095 Some(BillingPresentation::Subscription("Claude OAuth quota")),
2096 ),
2097 BillingPresentation::Subscription("Claude OAuth quota")
2098 );
2099 }
2100
2101 #[test]
2102 fn oauth_allowance_percent_is_shown_when_provider_supplies_it() {
2103 let chip = usage_chip(
2104 BillingPresentation::Subscription("Grok OAuth quota"),
2105 ProviderKind::Xai,
2106 "grok-4",
2107 0.0,
2108 CostCurrency::Usd,
2109 Some(37.0),
2110 );
2111 assert_eq!(
2112 format_usage_chip(&chip, codewhale_localization::Locale::En).as_deref(),
2113 Some("usage: Grok OAuth quota · 37%")
2114 );
2115 }
2116
2117 #[test]
2118 fn api_key_metered_shows_dollars_only_with_priced_positive_spend() {
2119 let billing = BillingPresentation::Metered;
2120 assert!(has_priced_metered_basis(
2121 billing,
2122 ProviderKind::Deepseek,
2123 "deepseek-v4-flash"
2124 ));
2125 let spent = usage_chip(
2126 billing,
2127 ProviderKind::Deepseek,
2128 "deepseek-v4-flash",
2129 0.42,
2130 CostCurrency::Usd,
2131 None,
2132 );
2133 assert_eq!(
2134 format_usage_chip(&spent, codewhale_localization::Locale::En).as_deref(),
2135 Some("$0.42")
2136 );
2137
2138 let zero = usage_chip(
2139 billing,
2140 ProviderKind::Deepseek,
2141 "deepseek-v4-flash",
2142 0.0,
2143 CostCurrency::Usd,
2144 None,
2145 );
2146 assert_eq!(zero, UsageChip::Hidden);
2147 assert!(format_usage_chip(&zero, codewhale_localization::Locale::En).is_none());
2148 assert!(
2149 !format_usage_chip(&zero, codewhale_localization::Locale::En)
2150 .unwrap_or_default()
2151 .contains('$')
2152 );
2153 }
2154
2155 #[test]
2156 fn local_free_routes_never_show_dollars() {
2157 assert_eq!(
2158 for_route(
2159 &Config::default(),
2160 &(Config::default()).test_identity_for_kind(ProviderKind::Ollama)
2161 ),
2162 BillingPresentation::Local
2163 );
2164 let chip = usage_chip(
2165 BillingPresentation::Local,
2166 ProviderKind::Ollama,
2167 "llama3.2",
2168 9.99,
2169 CostCurrency::Usd,
2170 None,
2171 );
2172 assert_eq!(
2173 format_usage_chip(&chip, codewhale_localization::Locale::En).as_deref(),
2174 Some("cost: local")
2175 );
2176 assert!(
2177 !format_usage_chip(&chip, codewhale_localization::Locale::En)
2178 .unwrap_or_default()
2179 .contains('$')
2180 );
2181 }
2182
2183 #[test]
2184 fn ollama_cloud_is_unknown_and_counts_as_possible_spend() {
2185 let config = {
2186 let __cw_config_init_0_0 = Some("ollama-cloud".to_string());
2187 let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig {
2188 ollama_cloud: codewhale_runtime::config::ProviderConfig {
2189 api_key: Some("cloud-key".to_string()),
2190 ..Default::default()
2191 },
2192 ..Default::default()
2193 });
2194 let mut __cw_config_init_0_value: Config = Default::default();
2195 __cw_config_init_0_value.provider = __cw_config_init_0_0;
2196 __cw_config_init_0_value.providers = __cw_config_init_0_1;
2197 __cw_config_init_0_value
2198 };
2199 let billing = for_route(
2200 &config,
2201 &(config).test_identity_for_kind(ProviderKind::OllamaCloud),
2202 );
2203 assert_eq!(billing, BillingPresentation::Unknown);
2204 assert!(!billing.shows_money());
2205
2206 let audit = crate::pricing::audit_turn_cost_for_route(
2207 ProviderKind::OllamaCloud,
2208 codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_CLOUD_MODEL,
2209 Some(crate::pricing::UNCLASSIFIED_BILLING_SURFACE),
2210 &Usage {
2211 input_tokens: 1_000,
2212 output_tokens: 100,
2213 ..Usage::default()
2214 },
2215 chrono::Utc::now(),
2216 billing,
2217 );
2218 assert_eq!(
2219 audit.unpriced_reason,
2220 Some(crate::pricing::UnpricedReason::UnknownBillingBasis)
2221 );
2222 assert!(audit.counts_toward_money_coverage());
2223 }
2224
2225 #[test]
2226 fn unknown_is_unknown_not_zero_dollars() {
2227 let chip = usage_chip(
2228 BillingPresentation::Metered,
2229 ProviderKind::NvidiaNim,
2230 "deepseek-ai/deepseek-v4-pro",
2231 0.0,
2232 CostCurrency::Usd,
2233 None,
2234 );
2235 assert_eq!(chip, UsageChip::Unknown(vec![UnpricedReason::NoPricingRow]));
2236 assert_eq!(
2237 format_usage_chip(&chip, codewhale_localization::Locale::En),
2238 None,
2239 "an unpriced turn shows no money"
2240 );
2241
2242 let unknown_billing = usage_chip(
2243 BillingPresentation::Unknown,
2244 ProviderKind::Custom,
2245 "anything",
2246 1.23,
2247 CostCurrency::Usd,
2248 None,
2249 );
2250 assert_eq!(
2251 unknown_billing,
2252 UsageChip::Unknown(vec![UnpricedReason::UnknownBillingBasis])
2253 );
2254 assert_eq!(
2255 format_usage_chip(&unknown_billing, codewhale_localization::Locale::En),
2256 None
2257 );
2258 }
2259
2260 #[test]
2261 fn xai_oauth_and_api_key_routes_stay_distinct() {
2262 let _lock = crate::test_support::lock_test_env();
2263 let temp = tempfile::tempdir().expect("xAI owned credential fixture");
2264 let owned_home = temp
2265 .path()
2266 .canonicalize()
2267 .expect("canonical xAI owned credential fixture");
2268 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &owned_home);
2269 let owned_path = owned_home.join("credentials/xai-auth.json");
2270 std::fs::create_dir_all(owned_path.parent().expect("owned credential parent"))
2271 .expect("create owned credential directory");
2272 #[cfg(windows)]
2273 codewhale_runtime::external_credentials::secure_codewhale_owned_windows_path(
2274 owned_path.parent().expect("owned credential parent"),
2275 true,
2276 )
2277 .expect("secure owned credential directory");
2278 let scope = format!(
2279 "{}::{}",
2280 codewhale_runtime::oauth::XAI_OIDC_ISSUER,
2281 codewhale_runtime::oauth::GROK_OIDC_CLIENT_ID
2282 );
2283 std::fs::write(
2284 &owned_path,
2285 serde_json::json!({
2286 scope: {
2287 "key": crate::test_support::future_test_jwt("billing"),
2288 "auth_mode": "oidc"
2289 }
2290 })
2291 .to_string(),
2292 )
2293 .expect("write Codewhale-owned xAI credential");
2294 #[cfg(unix)]
2295 {
2296 use std::os::unix::fs::PermissionsExt as _;
2297 std::fs::set_permissions(&owned_path, std::fs::Permissions::from_mode(0o600))
2298 .expect("secure owned credential file");
2299 }
2300 #[cfg(windows)]
2301 codewhale_runtime::external_credentials::secure_codewhale_owned_windows_path(
2302 &owned_path,
2303 false,
2304 )
2305 .expect("secure owned credential file");
2306 let oauth = config_with(
2307 ProviderKind::Xai,
2308 ProviderConfig {
2309 auth_mode: Some("grok-oauth".to_string()),
2310 ..ProviderConfig::default()
2311 },
2312 );
2313 let api = config_with(
2314 ProviderKind::Xai,
2315 ProviderConfig {
2316 auth_mode: Some("api-key".to_string()),
2317 ..ProviderConfig::default()
2318 },
2319 );
2320 assert!(
2321 !for_route(&oauth, &(oauth).test_identity_for_kind(ProviderKind::Xai)).shows_money()
2322 );
2323 assert!(for_route(&api, &(api).test_identity_for_kind(ProviderKind::Xai)).shows_money());
2324 }
2325
2326 #[test]
2327 fn future_claude_oauth_does_not_inherit_anthropic_api_prices() {
2328 let oauth = config_with(
2329 ProviderKind::Anthropic,
2330 ProviderConfig {
2331 auth_mode: Some("claude-code".to_string()),
2332 ..ProviderConfig::default()
2333 },
2334 );
2335 assert_eq!(
2336 for_route(
2337 &oauth,
2338 &(oauth).test_identity_for_kind(ProviderKind::Anthropic)
2339 )
2340 .label(),
2341 Some("Claude OAuth quota")
2342 );
2343 }
2344
2345 #[test]
2346 fn xiaomi_defaults_to_token_plan_but_explicit_payg_is_metered() {
2347 let _lock = crate::test_support::lock_test_env();
2348 let _mode = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_MODE");
2349 let _base = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_BASE_URL");
2350 let _token = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_TOKEN_PLAN_API_KEY");
2351 let _token_alias = crate::test_support::EnvVarGuard::remove("MIMO_TOKEN_PLAN_API_KEY");
2352 let _standard_a = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_API_KEY");
2353 let _standard_b = crate::test_support::EnvVarGuard::remove("XIAOMI_API_KEY");
2354 let _standard_c = crate::test_support::EnvVarGuard::remove("MIMO_API_KEY");
2355 assert!(
2356 !for_route(
2357 &Config::default(),
2358 &(Config::default()).test_identity_for_kind(ProviderKind::XiaomiMimo)
2359 )
2360 .shows_money()
2361 );
2362 let payg = config_with(
2363 ProviderKind::XiaomiMimo,
2364 ProviderConfig {
2365 mode: Some("pay-as-you-go".to_string()),
2366 ..ProviderConfig::default()
2367 },
2368 );
2369 assert!(
2370 for_route(
2371 &payg,
2372 &(payg).test_identity_for_kind(ProviderKind::XiaomiMimo)
2373 )
2374 .shows_money()
2375 );
2376 let standard_key = config_with(
2377 ProviderKind::XiaomiMimo,
2378 ProviderConfig {
2379 api_key: Some("sk-standard".to_string()),
2380 ..ProviderConfig::default()
2381 },
2382 );
2383 assert!(
2384 for_route(
2385 &standard_key,
2386 &(standard_key).test_identity_for_kind(ProviderKind::XiaomiMimo)
2387 )
2388 .shows_money()
2389 );
2390 }
2391
2392 #[test]
2393 fn minimax_requires_an_explicit_saved_billing_mode() {
2394 let _lock = crate::test_support::lock_test_env();
2395 let _env = minimax_env_guard();
2396 for provider in [ProviderKind::Minimax, ProviderKind::MinimaxAnthropic] {
2397 assert_eq!(
2398 for_route(
2399 &Config::default(),
2400 &(Config::default()).test_identity_for_kind(provider)
2401 ),
2402 BillingPresentation::Unknown
2403 );
2404 assert_eq!(
2405 for_endpoint_without_config(provider, Some(provider.provider().default_base_url())),
2406 BillingPresentation::Unknown
2407 );
2408
2409 let payg = config_with(
2410 provider,
2411 ProviderConfig {
2412 mode: Some("pay-as-you-go".to_string()),
2413 ..ProviderConfig::default()
2414 },
2415 );
2416 assert_eq!(
2417 for_route(&payg, &(payg).test_identity_for_kind(provider)),
2418 BillingPresentation::Metered
2419 );
2420 assert_eq!(
2421 billing_surface_for_dispatch(
2422 Some(&payg),
2423 &(payg).test_identity_for_kind(provider),
2424 Some(provider.provider().default_base_url())
2425 ),
2426 Some(crate::pricing::MINIMAX_PAYG_BILLING_SURFACE)
2427 );
2428
2429 let plan = config_with(
2430 provider,
2431 ProviderConfig {
2432 mode: Some("subscription-plan".to_string()),
2433 ..ProviderConfig::default()
2434 },
2435 );
2436 assert_eq!(
2437 for_route(&plan, &(plan).test_identity_for_kind(provider)),
2438 // The product's own name, not a generic "subscription plan":
2439 // MiniMax sells PAYG and Token Plan over the same endpoint.
2440 BillingPresentation::Subscription("MiniMax Token Plan quota")
2441 );
2442 assert_eq!(
2443 billing_surface_for_dispatch(
2444 Some(&plan),
2445 &(plan).test_identity_for_kind(provider),
2446 Some(provider.provider().default_base_url())
2447 ),
2448 Some(crate::pricing::MINIMAX_TOKEN_PLAN_BILLING_SURFACE)
2449 );
2450 }
2451 }
2452
2453 #[test]
2454 fn unknown_cross_provider_oauth_capable_child_never_invents_dollars() {
2455 assert!(
2456 !for_child_route(
2457 ProviderKind::Deepseek,
2458 BillingPresentation::Metered,
2459 ProviderKind::Xai,
2460 None,
2461 )
2462 .shows_money()
2463 );
2464 // Identity alone no longer claims metered dollars either: without the
2465 // child's own route truth a cross-provider child fails closed.
2466 assert!(
2467 !for_child_route(
2468 ProviderKind::Deepseek,
2469 BillingPresentation::Metered,
2470 ProviderKind::Openrouter,
2471 None,
2472 )
2473 .shows_money()
2474 );
2475 // Unknown, not an invented "provider quota" subscription.
2476 assert_eq!(
2477 for_child_route(
2478 ProviderKind::Deepseek,
2479 BillingPresentation::Metered,
2480 ProviderKind::Xai,
2481 None,
2482 ),
2483 BillingPresentation::Unknown
2484 );
2485 // The child's own metered provenance is what prices the route.
2486 assert!(
2487 for_child_route(
2488 ProviderKind::Deepseek,
2489 BillingPresentation::Metered,
2490 ProviderKind::Openrouter,
2491 Some(BillingPresentation::Metered),
2492 )
2493 .shows_money()
2494 );
2495 }
2496
2497 #[test]
2498 fn standard_mimo_env_key_uses_metered_presentation() {
2499 let _lock = crate::test_support::lock_test_env();
2500 let _mode = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_MODE");
2501 let _base = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_BASE_URL");
2502 let _token = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_TOKEN_PLAN_API_KEY");
2503 let _token_alias = crate::test_support::EnvVarGuard::remove("MIMO_TOKEN_PLAN_API_KEY");
2504 let _standard_a = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_API_KEY");
2505 let _standard_b = crate::test_support::EnvVarGuard::remove("XIAOMI_API_KEY");
2506 let _standard = crate::test_support::EnvVarGuard::set("MIMO_API_KEY", "sk-metered");
2507
2508 assert!(
2509 for_route(
2510 &Config::default(),
2511 &(Config::default()).test_identity_for_kind(ProviderKind::XiaomiMimo)
2512 )
2513 .shows_money()
2514 );
2515 }
2516
2517 #[test]
2518 fn custom_without_pay_mode_stays_unknown() {
2519 let mut config = Config::from_saved_document(
2520 r#"provider = "acme"
2521 [providers.acme]
2522 kind = "openai-compatible"
2523 base_url = "https://acme.example.test/v1"
2524 model = "fixture-model"
2525 "#,
2526 None,
2527 )
2528 .unwrap();
2529 let identity = config.active_provider_identity().unwrap();
2530 assert_eq!(for_route(&config, &identity), BillingPresentation::Unknown);
2531 config.provider_config_for_mut(&identity).unwrap().auth_mode = Some("api-key".into());
2532 assert_eq!(for_route(&config, &identity), BillingPresentation::Metered);
2533 }
2534
2535 #[test]
2536 fn dispatched_endpoint_shaped_routes_classify_from_the_receipt() {
2537 let config = Config::default();
2538 // StepFun: plan endpoint, PAYG endpoint, unrecognized host.
2539 assert_eq!(
2540 for_dispatched_route(
2541 &config,
2542 DispatchedRoute {
2543 provider: ProviderKind::Stepfun,
2544 base_url: "https://api.stepfun.ai/step_plan/v1",
2545 },
2546 ),
2547 BillingPresentation::Subscription("StepFun Step Plan quota")
2548 );
2549 assert_eq!(
2550 for_dispatched_route(
2551 &config,
2552 DispatchedRoute {
2553 provider: ProviderKind::Stepfun,
2554 base_url: codewhale_config::descriptors::defaults::DEFAULT_STEPFUN_BASE_URL,
2555 },
2556 ),
2557 BillingPresentation::Metered
2558 );
2559 assert_eq!(
2560 for_dispatched_route(
2561 &config,
2562 DispatchedRoute {
2563 provider: ProviderKind::Stepfun,
2564 base_url: "https://gateway.internal.example/v1",
2565 },
2566 ),
2567 BillingPresentation::Unknown
2568 );
2569 // Z.ai: the Coding Plan path is quota-billed; a blank receipt is not
2570 // an excuse to fall back to the plan default.
2571 assert_eq!(
2572 for_dispatched_route(
2573 &config,
2574 DispatchedRoute {
2575 provider: ProviderKind::Zai,
2576 base_url: "https://api.z.ai/api/coding/paas/v4",
2577 },
2578 ),
2579 BillingPresentation::Subscription("Z.ai Coding Plan quota")
2580 );
2581 assert_eq!(
2582 for_dispatched_route(
2583 &config,
2584 DispatchedRoute {
2585 provider: ProviderKind::Zai,
2586 base_url: "",
2587 },
2588 ),
2589 BillingPresentation::Unknown
2590 );
2591 // Identity-owned routes are unchanged by the receipt.
2592 assert_eq!(
2593 for_dispatched_route(
2594 &config,
2595 DispatchedRoute {
2596 provider: ProviderKind::Ollama,
2597 base_url: "http://localhost:11434/v1",
2598 },
2599 ),
2600 BillingPresentation::Local
2601 );
2602 assert_eq!(
2603 for_dispatched_route(
2604 &config,
2605 DispatchedRoute {
2606 provider: ProviderKind::OpenaiCodex,
2607 base_url: "https://chatgpt.com/backend-api/codex",
2608 },
2609 ),
2610 BillingPresentation::Subscription("Codex OAuth quota")
2611 );
2612 // The OAuth token pointed anywhere else proves no Codex quota.
2613 for elsewhere in [
2614 "https://codex-gateway.example.com/backend-api",
2615 "https://chatgpt.com.example.net/backend-api",
2616 "http://chatgpt.com/backend-api",
2617 "https://chatgpt.com/v1",
2618 "",
2619 ] {
2620 assert_eq!(
2621 for_dispatched_route(
2622 &config,
2623 DispatchedRoute {
2624 provider: ProviderKind::OpenaiCodex,
2625 base_url: elsewhere,
2626 },
2627 ),
2628 BillingPresentation::Unknown,
2629 "{elsewhere:?}"
2630 );
2631 // The persisted billing surface agrees: a custom endpoint is not
2632 // an OAuth subscription that would drop out of money coverage.
2633 if !elsewhere.is_empty() {
2634 assert_eq!(
2635 billing_surface_for_dispatch(
2636 None,
2637 &Config::default().test_identity_for_kind(ProviderKind::OpenaiCodex),
2638 Some(elsewhere)
2639 ),
2640 Some(crate::pricing::UNCLASSIFIED_BILLING_SURFACE),
2641 "{elsewhere:?}"
2642 );
2643 }
2644 }
2645 assert_eq!(
2646 billing_surface_for_dispatch(
2647 None,
2648 &Config::default().test_identity_for_kind(ProviderKind::OpenaiCodex),
2649 Some("https://chatgpt.com/backend-api/codex")
2650 ),
2651 Some(crate::pricing::OAUTH_SUBSCRIPTION_BILLING_SURFACE)
2652 );
2653 }
2654
2655 #[test]
2656 fn minimax_defaults_to_pay_as_you_go_metered() {
2657 let _lock = crate::test_support::lock_test_env();
2658 let _key = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");
2659 let config = config_with(
2660 ProviderKind::Minimax,
2661 ProviderConfig {
2662 base_url: Some("https://api.minimax.io/v1".to_string()),
2663 api_key: Some("sk-test-payg-key".to_string()),
2664 ..ProviderConfig::default()
2665 },
2666 );
2667 let billing = for_route(
2668 &config,
2669 &(config).test_identity_for_kind(ProviderKind::Minimax),
2670 );
2671 assert_eq!(billing, BillingPresentation::Metered);
2672 assert!(billing.shows_money());
2673 let chip = usage_chip(
2674 billing,
2675 ProviderKind::Minimax,
2676 "MiniMax-M3",
2677 0.42,
2678 CostCurrency::Usd,
2679 None,
2680 );
2681 assert!(matches!(chip, UsageChip::Money(_)));
2682 assert!(
2683 format_usage_chip(&chip, codewhale_localization::Locale::En)
2684 .unwrap_or_default()
2685 .contains('$')
2686 );
2687 }
2688
2689 #[test]
2690 fn minimax_explicit_token_plan_mode_is_subscription_quota() {
2691 let _lock = crate::test_support::lock_test_env();
2692 let _key = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");
2693 let config = config_with(
2694 ProviderKind::Minimax,
2695 ProviderConfig {
2696 mode: Some("token-plan".to_string()),
2697 api_key: Some("sk-test-payg-key".to_string()),
2698 ..ProviderConfig::default()
2699 },
2700 );
2701 let billing = for_route(
2702 &config,
2703 &(config).test_identity_for_kind(ProviderKind::Minimax),
2704 );
2705 assert_eq!(
2706 billing,
2707 BillingPresentation::Subscription("MiniMax Token Plan quota")
2708 );
2709 assert!(!billing.shows_money());
2710 // `MiniMax-M3` is priced on the metered route; the subscription
2711 // classification must still win over the priced row.
2712 let chip = usage_chip(
2713 billing,
2714 ProviderKind::Minimax,
2715 "MiniMax-M3",
2716 12.34,
2717 CostCurrency::Usd,
2718 None,
2719 );
2720 assert!(!matches!(chip, UsageChip::Money(_)));
2721 assert!(
2722 !format_usage_chip(&chip, codewhale_localization::Locale::En)
2723 .unwrap_or_default()
2724 .contains('$')
2725 );
2726 }
2727
2728 #[test]
2729 fn minimax_sk_cp_config_key_is_subscription_quota() {
2730 let _lock = crate::test_support::lock_test_env();
2731 let _key = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");
2732 let config = config_with(
2733 ProviderKind::Minimax,
2734 ProviderConfig {
2735 api_key: Some("sk-cp-test-token-plan-key".to_string()),
2736 ..ProviderConfig::default()
2737 },
2738 );
2739 let billing = for_route(
2740 &config,
2741 &(config).test_identity_for_kind(ProviderKind::Minimax),
2742 );
2743 assert_eq!(
2744 billing,
2745 BillingPresentation::Subscription("MiniMax Token Plan quota")
2746 );
2747 assert!(!billing.shows_money());
2748 }
2749
2750 /// The Anthropic-dialect MiniMax route is the same product behind a
2751 /// different wire protocol: same MINIMAX_API_KEY, same PAYG/Token Plan
2752 /// duality. Classifying only the chat-completions dialect would show
2753 /// invented dollars for a Token Plan key on `[providers.minimax_anthropic]`.
2754 #[test]
2755 fn minimax_anthropic_dialect_shares_the_token_plan_classification() {
2756 let _lock = crate::test_support::lock_test_env();
2757 let _key = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");
2758
2759 let plan = config_with(
2760 ProviderKind::MinimaxAnthropic,
2761 ProviderConfig {
2762 api_key: Some("sk-cp-test-token-plan-key".to_string()),
2763 ..ProviderConfig::default()
2764 },
2765 );
2766 let plan_billing = for_route(
2767 &plan,
2768 &(plan).test_identity_for_kind(ProviderKind::MinimaxAnthropic),
2769 );
2770 assert_eq!(
2771 plan_billing,
2772 BillingPresentation::Subscription("MiniMax Token Plan quota")
2773 );
2774 assert!(!plan_billing.shows_money());
2775
2776 let explicit_plan = config_with(
2777 ProviderKind::MinimaxAnthropic,
2778 ProviderConfig {
2779 mode: Some("token-plan".to_string()),
2780 api_key: Some("sk-test-payg-key".to_string()),
2781 ..ProviderConfig::default()
2782 },
2783 );
2784 assert_eq!(
2785 for_route(
2786 &explicit_plan,
2787 &(explicit_plan).test_identity_for_kind(ProviderKind::MinimaxAnthropic)
2788 ),
2789 BillingPresentation::Subscription("MiniMax Token Plan quota")
2790 );
2791
2792 // Pay-as-you-go on the same dialect stays metered.
2793 let payg = config_with(
2794 ProviderKind::MinimaxAnthropic,
2795 ProviderConfig {
2796 api_key: Some("sk-test-payg-key".to_string()),
2797 ..ProviderConfig::default()
2798 },
2799 );
2800 let payg_billing = for_route(
2801 &payg,
2802 &(payg).test_identity_for_kind(ProviderKind::MinimaxAnthropic),
2803 );
2804 assert_eq!(payg_billing, BillingPresentation::Metered);
2805 assert!(payg_billing.shows_money());
2806 }
2807
2808 #[test]
2809 fn minimax_sk_cp_env_key_is_subscription_quota() {
2810 let _lock = crate::test_support::lock_test_env();
2811 let _key =
2812 crate::test_support::EnvVarGuard::set("MINIMAX_API_KEY", "sk-cp-test-token-plan-key");
2813 let config = config_with(ProviderKind::Minimax, ProviderConfig::default());
2814 assert_eq!(
2815 for_route(
2816 &config,
2817 &(config).test_identity_for_kind(ProviderKind::Minimax)
2818 ),
2819 BillingPresentation::Subscription("MiniMax Token Plan quota")
2820 );
2821 }
2822
2823 #[test]
2824 fn minimax_explicit_pay_as_you_go_wins_over_sk_cp_key() {
2825 let _lock = crate::test_support::lock_test_env();
2826 let _key = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");
2827 for mode in ["pay-as-you-go", "payg", "metered"] {
2828 let config = config_with(
2829 ProviderKind::Minimax,
2830 ProviderConfig {
2831 mode: Some(mode.to_string()),
2832 api_key: Some("sk-cp-test-token-plan-key".to_string()),
2833 ..ProviderConfig::default()
2834 },
2835 );
2836 let billing = for_route(
2837 &config,
2838 &(config).test_identity_for_kind(ProviderKind::Minimax),
2839 );
2840 assert_eq!(
2841 billing,
2842 BillingPresentation::Metered,
2843 "explicit mode {mode} must win over the sk-cp key shape"
2844 );
2845 assert!(billing.shows_money());
2846 }
2847 }
2848
2849 /// Clear the only ambient variable `minimax_credential_product` reads, so
2850 /// a developer's real shell cannot decide a billing regression's outcome.
2851 fn minimax_env_guard() -> crate::test_support::EnvVarGuard {
2852 crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY")
2853 }
2854
2855 /// The release blocker: a MiniMax key saved through `codewhale auth set`
2856 /// lives in the secret store, so neither the config table nor
2857 /// `MINIMAX_API_KEY` carries a product marker. Classification must not
2858 /// open the secret store to find out, and must not silently call the
2859 /// route pay-as-you-go — a Token Plan account would then accrue invented
2860 /// dollars on every benchmark receipt.
2861 #[test]
2862 fn minimax_keyring_or_opaque_credential_is_unclassified_not_metered() {
2863 let _lock = crate::test_support::lock_test_env();
2864 let _env = minimax_env_guard();
2865 for provider in [ProviderKind::Minimax, ProviderKind::MinimaxAnthropic] {
2866 // No credential visible at all (keyring/OAuth/command-sourced).
2867 let opaque = config_with(provider, ProviderConfig::default());
2868 assert_eq!(
2869 for_route(&opaque, &(opaque).test_identity_for_kind(provider)),
2870 BillingPresentation::Unknown,
2871 "{provider:?} must not claim pay-as-you-go it cannot prove"
2872 );
2873 // The legacy keyring placeholder is not a credential and carries
2874 // no product prefix.
2875 for sentinel in [codewhale_config::API_KEYRING_SENTINEL, " __KEYRING__ "] {
2876 let sentinel = config_with(
2877 provider,
2878 ProviderConfig {
2879 api_key: Some(sentinel.to_string()),
2880 ..ProviderConfig::default()
2881 },
2882 );
2883 assert_eq!(
2884 for_route(&sentinel, &(sentinel).test_identity_for_kind(provider)),
2885 BillingPresentation::Unknown,
2886 "{provider:?} keyring sentinel is not a pay-as-you-go proof"
2887 );
2888 }
2889 let chip = usage_chip(
2890 for_route(&opaque, &(opaque).test_identity_for_kind(provider)),
2891 provider,
2892 "MiniMax-M3",
2893 12.34,
2894 CostCurrency::Usd,
2895 None,
2896 );
2897 assert_eq!(
2898 chip,
2899 UsageChip::Unknown(vec![UnpricedReason::UnknownBillingBasis])
2900 );
2901 assert!(
2902 !format_usage_chip(&chip, codewhale_localization::Locale::En)
2903 .unwrap_or_default()
2904 .contains('$')
2905 );
2906 }
2907 }
2908
2909 /// Provenance-by-source, both dialects: config value, route-bound
2910 /// `api_key_env`, and ambient `MINIMAX_API_KEY` are each sufficient to
2911 /// prove a product, and each proves it the same way.
2912 #[test]
2913 fn minimax_credential_provenance_classifies_both_dialects_identically() {
2914 let _lock = crate::test_support::lock_test_env();
2915 let _env = minimax_env_guard();
2916 for provider in [ProviderKind::Minimax, ProviderKind::MinimaxAnthropic] {
2917 // 1. Config-owned key.
2918 for (key, expected) in [
2919 (
2920 "sk-cp-plan-key",
2921 BillingPresentation::Subscription("MiniMax Token Plan quota"),
2922 ),
2923 ("sk-payg-key", BillingPresentation::Metered),
2924 ] {
2925 let config = config_with(
2926 provider,
2927 ProviderConfig {
2928 api_key: Some(key.to_string()),
2929 ..ProviderConfig::default()
2930 },
2931 );
2932 assert_eq!(
2933 for_route(&config, &(config).test_identity_for_kind(provider)),
2934 expected,
2935 "{provider:?} {key}"
2936 );
2937 }
2938
2939 // 2. Route-bound `api_key_env`: the binding is config-owned even
2940 // though the value is ambient.
2941 for (key, expected) in [
2942 (
2943 "sk-cp-plan-key",
2944 BillingPresentation::Subscription("MiniMax Token Plan quota"),
2945 ),
2946 ("sk-payg-key", BillingPresentation::Metered),
2947 ] {
2948 let _bound =
2949 crate::test_support::EnvVarGuard::set("CW_TEST_MINIMAX_BOUND_KEY", key);
2950 let config = config_with(
2951 provider,
2952 ProviderConfig {
2953 api_key_env: Some("CW_TEST_MINIMAX_BOUND_KEY".to_string()),
2954 ..ProviderConfig::default()
2955 },
2956 );
2957 assert_eq!(
2958 for_route(&config, &(config).test_identity_for_kind(provider)),
2959 expected,
2960 "{provider:?} api_key_env {key}"
2961 );
2962 }
2963
2964 // 3. Ambient provider environment on an official endpoint.
2965 for (key, expected) in [
2966 (
2967 "sk-cp-plan-key",
2968 BillingPresentation::Subscription("MiniMax Token Plan quota"),
2969 ),
2970 ("sk-payg-key", BillingPresentation::Metered),
2971 ] {
2972 let _ambient = crate::test_support::EnvVarGuard::set("MINIMAX_API_KEY", key);
2973 let config = config_with(provider, ProviderConfig::default());
2974 assert_eq!(
2975 for_route(&config, &(config).test_identity_for_kind(provider)),
2976 expected,
2977 "{provider:?} MINIMAX_API_KEY {key}"
2978 );
2979 }
2980 }
2981 }
2982
2983 /// Ambient provider credentials are never sent to a custom host, so an
2984 /// exported `MINIMAX_API_KEY` proves nothing about what a gateway route
2985 /// bills. That route is Unknown, not metered-by-default.
2986 #[test]
2987 fn minimax_ambient_key_does_not_classify_a_custom_endpoint() {
2988 let _lock = crate::test_support::lock_test_env();
2989 let _env = minimax_env_guard();
2990 let _ambient = crate::test_support::EnvVarGuard::set("MINIMAX_API_KEY", "sk-payg-key");
2991 let config = config_with(
2992 ProviderKind::Minimax,
2993 ProviderConfig {
2994 base_url: Some("https://gateway.internal.example/v1".to_string()),
2995 ..ProviderConfig::default()
2996 },
2997 );
2998 assert_eq!(
2999 for_route(
3000 &config,
3001 &(config).test_identity_for_kind(ProviderKind::Minimax)
3002 ),
3003 BillingPresentation::Unknown
3004 );
3005 }
3006
3007 /// An operator pay mode we do not recognize is not a product claim.
3008 #[test]
3009 fn minimax_unrecognized_pay_mode_is_unclassified() {
3010 let _lock = crate::test_support::lock_test_env();
3011 let _env = minimax_env_guard();
3012 let config = config_with(
3013 ProviderKind::Minimax,
3014 ProviderConfig {
3015 mode: Some("enterprise-committed-spend".to_string()),
3016 api_key: Some("sk-cp-plan-key".to_string()),
3017 ..ProviderConfig::default()
3018 },
3019 );
3020 assert_eq!(
3021 for_route(
3022 &config,
3023 &(config).test_identity_for_kind(ProviderKind::Minimax)
3024 ),
3025 BillingPresentation::Unknown
3026 );
3027 }
3028
3029 /// MiniMax billing is credential-shaped, not endpoint-shaped: a dispatch
3030 /// receipt pointing at the shipped default URL still cannot invent a
3031 /// product.
3032 #[test]
3033 fn dispatched_minimax_default_endpoint_does_not_invent_a_product() {
3034 let _lock = crate::test_support::lock_test_env();
3035 let _env = minimax_env_guard();
3036 let config = config_with(ProviderKind::Minimax, ProviderConfig::default());
3037 assert_eq!(
3038 for_dispatched_route(
3039 &config,
3040 DispatchedRoute {
3041 provider: ProviderKind::Minimax,
3042 base_url: "https://api.minimax.io/v1",
3043 },
3044 ),
3045 BillingPresentation::Unknown
3046 );
3047 }
3048
3049 #[test]
3050 fn same_provider_child_without_provenance_inherits_parent_billing() {
3051 assert_eq!(
3052 for_child_route(
3053 ProviderKind::Moonshot,
3054 BillingPresentation::Subscription("Kimi Code quota"),
3055 ProviderKind::Moonshot,
3056 None,
3057 ),
3058 BillingPresentation::Subscription("Kimi Code quota")
3059 );
3060 assert_eq!(
3061 for_child_route(
3062 ProviderKind::Minimax,
3063 BillingPresentation::Metered,
3064 ProviderKind::Minimax,
3065 None,
3066 ),
3067 BillingPresentation::Metered
3068 );
3069 }
3070
3071 #[test]
3072 fn cross_provider_child_without_provenance_fails_closed_unknown() {
3073 // Moonshot and MiniMax both run metered AND subscription routes, so
3074 // identity alone must never guess either direction.
3075 for child in [ProviderKind::Moonshot, ProviderKind::Minimax] {
3076 assert_eq!(
3077 for_child_route(
3078 ProviderKind::Deepseek,
3079 BillingPresentation::Metered,
3080 child,
3081 None,
3082 ),
3083 BillingPresentation::Unknown,
3084 "{child:?} identity must not guess subscription or metered billing"
3085 );
3086 }
3087 // Local routes are the one identity-derived fact that stays truthful.
3088 for child in [
3089 ProviderKind::Ollama,
3090 ProviderKind::Sglang,
3091 ProviderKind::Vllm,
3092 ] {
3093 assert_eq!(
3094 for_child_route(
3095 ProviderKind::Deepseek,
3096 BillingPresentation::Metered,
3097 child,
3098 None,
3099 ),
3100 BillingPresentation::Local
3101 );
3102 }
3103 }
3104
3105 #[test]
3106 fn child_provenance_wins_over_parent_route_and_provider_identity() {
3107 // Direct-platform Moonshot child under a Kimi Code membership
3108 // parent: the child's own metered truth must price the route.
3109 assert_eq!(
3110 for_child_route(
3111 ProviderKind::Moonshot,
3112 BillingPresentation::Subscription("Kimi Code quota"),
3113 ProviderKind::Moonshot,
3114 Some(BillingPresentation::Metered),
3115 ),
3116 BillingPresentation::Metered
3117 );
3118 // Membership Moonshot child under a metered parent: quota wins.
3119 assert_eq!(
3120 for_child_route(
3121 ProviderKind::Deepseek,
3122 BillingPresentation::Metered,
3123 ProviderKind::Moonshot,
3124 Some(BillingPresentation::Subscription("Kimi Code quota")),
3125 ),
3126 BillingPresentation::Subscription("Kimi Code quota")
3127 );
3128 // MiniMax Token Plan provenance never invents dollars; metered
3129 // provenance is allowed to accrue.
3130 assert!(
3131 !for_child_route(
3132 ProviderKind::Deepseek,
3133 BillingPresentation::Metered,
3134 ProviderKind::Minimax,
3135 Some(BillingPresentation::Subscription(
3136 "MiniMax Token Plan quota"
3137 )),
3138 )
3139 .shows_money()
3140 );
3141 assert!(
3142 for_child_route(
3143 ProviderKind::Deepseek,
3144 BillingPresentation::Metered,
3145 ProviderKind::Minimax,
3146 Some(BillingPresentation::Metered),
3147 )
3148 .shows_money()
3149 );
3150 }
3151
3152 #[test]
3153 fn child_billing_provenance_round_trips_through_serde() {
3154 for billing in [
3155 BillingPresentation::Metered,
3156 BillingPresentation::Subscription("ChatGPT plan allowance"),
3157 BillingPresentation::Subscription("Kimi Code quota"),
3158 BillingPresentation::Subscription("MiniMax Token Plan quota"),
3159 BillingPresentation::Local,
3160 BillingPresentation::Unknown,
3161 ] {
3162 let provenance = ChildBillingProvenance::from(billing);
3163 let json = serde_json::to_string(&provenance).expect("serialize provenance");
3164 let back: ChildBillingProvenance =
3165 serde_json::from_str(&json).expect("deserialize provenance");
3166 assert_eq!(back.as_billing_presentation(), billing);
3167 }
3168 // An unrecognized free-text label fails closed rather than
3169 // inventing a quota claim.
3170 assert_eq!(
3171 ChildBillingProvenance::Subscription {
3172 label: "free lunch".to_string(),
3173 }
3174 .as_billing_presentation(),
3175 BillingPresentation::Unknown
3176 );
3177 }
3178
3179 /// Two named custom routes are the same `ProviderKind::Custom`. Identity,
3180 /// not the enum, decides whether a child may inherit the parent's product.
3181 #[test]
3182 fn custom_siblings_do_not_inherit_each_others_product() {
3183 let parent = ChildParentRoute {
3184 provider: ProviderKind::Custom,
3185 identity: "gateway-a",
3186 billing: BillingPresentation::Metered,
3187 };
3188
3189 // Same vendor: inheritance is sound.
3190 assert_eq!(
3191 for_child_route_receipt(
3192 parent,
3193 ChildRouteClaim {
3194 named: true,
3195 provider: Some(ProviderKind::Custom),
3196 identity: Some("gateway-a"),
3197 },
3198 None,
3199 ),
3200 BillingPresentation::Metered
3201 );
3202
3203 // Sibling vendor on the same enum: must not borrow gateway-a's product.
3204 assert_eq!(
3205 for_child_route_receipt(
3206 parent,
3207 ChildRouteClaim {
3208 named: true,
3209 provider: Some(ProviderKind::Custom),
3210 identity: Some("gateway-b"),
3211 },
3212 None,
3213 ),
3214 BillingPresentation::Unknown
3215 );
3216 }
3217
3218 /// A child that names an unparseable provider named *some* route, just not
3219 /// one this build knows. That is never a licence to inherit.
3220 #[test]
3221 fn unparseable_child_provider_is_unknown_not_inherited() {
3222 let parent = ChildParentRoute {
3223 provider: ProviderKind::Anthropic,
3224 identity: "anthropic",
3225 billing: BillingPresentation::Subscription("Claude OAuth quota"),
3226 };
3227 assert_eq!(
3228 for_child_route_receipt(
3229 parent,
3230 ChildRouteClaim {
3231 named: true,
3232 provider: None,
3233 identity: Some("some-future-vendor"),
3234 },
3235 None,
3236 ),
3237 BillingPresentation::Unknown
3238 );
3239 // But a child that claims nothing ran the parent's own client.
3240 assert_eq!(
3241 for_child_route_receipt(parent, ChildRouteClaim::default(), None),
3242 BillingPresentation::Subscription("Claude OAuth quota")
3243 );
3244 }
3245
3246 /// The producer's metadata keys are exactly the ones the consumer reads.
3247 /// Pins the wire contract that previously had a reader and no producer.
3248 #[test]
3249 fn child_route_metadata_round_trips_through_the_consumer() {
3250 let metadata = child_route_metadata(
3251 ProviderKind::Ollama,
3252 "ollama",
3253 "http://localhost:11434/v1",
3254 RouteProduct::Unproven,
3255 );
3256
3257 assert_eq!(metadata["child_provider"], "ollama");
3258 assert_eq!(metadata["child_provider_identity"], "ollama");
3259 let provenance: ChildBillingProvenance =
3260 serde_json::from_value(metadata["child_billing"].clone())
3261 .expect("child_billing must deserialize with the consumer's type");
3262 assert_eq!(
3263 provenance.as_billing_presentation(),
3264 BillingPresentation::Local
3265 );
3266 }
3267
3268 /// A dispatched-route classification survives the child → parent mailbox
3269 /// boundary and still beats provider identity at the consumer.
3270 #[test]
3271 fn dispatched_receipt_survives_the_child_provenance_boundary() {
3272 let _lock = crate::test_support::lock_test_env();
3273 let _kimi = crate::test_support::EnvVarGuard::set(
3274 "KIMI_BASE_URL",
3275 "https://api.kimi.com/coding/v1",
3276 );
3277 let config = config_with(ProviderKind::Moonshot, ProviderConfig::default());
3278 let dispatched = for_dispatched_route(
3279 &config,
3280 DispatchedRoute {
3281 provider: ProviderKind::Moonshot,
3282 base_url: "https://api.kimi.com/coding/v1",
3283 },
3284 );
3285 let wire = serde_json::to_string(&ChildBillingProvenance::from(dispatched))
3286 .expect("serialize dispatch receipt");
3287 let back: ChildBillingProvenance =
3288 serde_json::from_str(&wire).expect("deserialize dispatch receipt");
3289 let billing = for_child_route(
3290 ProviderKind::Deepseek,
3291 BillingPresentation::Metered,
3292 ProviderKind::Moonshot,
3293 Some(back.as_billing_presentation()),
3294 );
3295 assert_eq!(
3296 billing,
3297 BillingPresentation::Subscription("Kimi Code quota")
3298 );
3299 assert!(!billing.shows_money());
3300 }
3301
3302 /// Every provider env contract that can move a default route's endpoint.
3303 /// The audit below pins shipped defaults, so these must not leak in.
3304 const BASE_URL_ENV_VARS: &[&str] = &[
3305 "CODEWHALE_BASE_URL",
3306 "DEEPSEEK_BASE_URL",
3307 "NIM_BASE_URL",
3308 "NVIDIA_BASE_URL",
3309 "NVIDIA_NIM_BASE_URL",
3310 "OPENAI_BASE_URL",
3311 "ATLASCLOUD_BASE_URL",
3312 "OPENROUTER_BASE_URL",
3313 "ORCAROUTER_BASE_URL",
3314 "MIMO_BASE_URL",
3315 "XIAOMI_MIMO_BASE_URL",
3316 "WANJIE_ARK_BASE_URL",
3317 "WANJIE_BASE_URL",
3318 "WANJIE_MAAS_BASE_URL",
3319 "VOLCENGINE_BASE_URL",
3320 "VOLCENGINE_ARK_BASE_URL",
3321 "ARK_BASE_URL",
3322 "NOVITA_BASE_URL",
3323 "FIREWORKS_BASE_URL",
3324 "SILICONFLOW_BASE_URL",
3325 "ARCEE_BASE_URL",
3326 "MOONSHOT_BASE_URL",
3327 "KIMI_BASE_URL",
3328 "SGLANG_BASE_URL",
3329 "VLLM_BASE_URL",
3330 "OLLAMA_BASE_URL",
3331 "OLLAMA_CLOUD_BASE_URL",
3332 "HF_BASE_URL",
3333 "HUGGINGFACE_BASE_URL",
3334 "META_MODEL_API_BASE_URL",
3335 "MODEL_API_BASE_URL",
3336 "MISTRAL_BASE_URL",
3337 "XAI_BASE_URL",
3338 "GEMINI_BASE_URL",
3339 "GOOGLE_BASE_URL",
3340 "TELECOMJS_BASE_URL",
3341 "EDENAI_BASE_URL",
3342 "CONCENTRATE_BASE_URL",
3343 "MODELSTUDIO_TOKEN_PLAN_BASE_URL",
3344 "MODELSTUDIO_CODING_PLAN_BASE_URL",
3345 "OPENCODE_GO_BASE_URL",
3346 "OPENCODE_ZEN_BASE_URL",
3347 ];
3348
3349 /// The shipped default-route billing decision for every runnable provider.
3350 /// Onboarding or re-defaulting a provider must update this table and the
3351 /// audit artifact (`docs/PROVIDERS.md` billing column) deliberately.
3352 const DEFAULT_ROUTE_BILLING_AUDIT: &[(ProviderKind, BillingPresentation)] = &[
3353 (ProviderKind::Deepseek, BillingPresentation::Metered),
3354 (
3355 ProviderKind::DeepseekAnthropic,
3356 BillingPresentation::Metered,
3357 ),
3358 (ProviderKind::NvidiaNim, BillingPresentation::Metered),
3359 (ProviderKind::Openai, BillingPresentation::Metered),
3360 (ProviderKind::Atlascloud, BillingPresentation::Metered),
3361 (ProviderKind::WanjieArk, BillingPresentation::Metered),
3362 (
3363 ProviderKind::Volcengine,
3364 BillingPresentation::Subscription("Volcengine Coding Plan"),
3365 ),
3366 (ProviderKind::Openrouter, BillingPresentation::Metered),
3367 (ProviderKind::Orcarouter, BillingPresentation::Metered),
3368 (
3369 ProviderKind::XiaomiMimo,
3370 BillingPresentation::Subscription("MiMo token plan"),
3371 ),
3372 (ProviderKind::Novita, BillingPresentation::Metered),
3373 (ProviderKind::Fireworks, BillingPresentation::Metered),
3374 (ProviderKind::Siliconflow, BillingPresentation::Metered),
3375 (ProviderKind::Arcee, BillingPresentation::Metered),
3376 (ProviderKind::SiliconflowCN, BillingPresentation::Metered),
3377 (ProviderKind::Moonshot, BillingPresentation::Metered),
3378 (ProviderKind::Sglang, BillingPresentation::Local),
3379 (ProviderKind::Vllm, BillingPresentation::Local),
3380 (ProviderKind::Ollama, BillingPresentation::Local),
3381 (ProviderKind::OllamaCloud, BillingPresentation::Unknown),
3382 (ProviderKind::Huggingface, BillingPresentation::Metered),
3383 (ProviderKind::Modelscope, BillingPresentation::Metered),
3384 (ProviderKind::Together, BillingPresentation::Metered),
3385 (ProviderKind::Qianfan, BillingPresentation::Metered),
3386 (ProviderKind::OpenaiCodex, BillingPresentation::Unknown),
3387 (ProviderKind::Anthropic, BillingPresentation::Metered),
3388 (ProviderKind::Openmodel, BillingPresentation::Metered),
3389 (
3390 ProviderKind::Zai,
3391 BillingPresentation::Subscription("Z.ai Coding Plan quota"),
3392 ),
3393 (ProviderKind::Stepfun, BillingPresentation::Metered),
3394 (ProviderKind::Minimax, BillingPresentation::Unknown),
3395 (ProviderKind::MinimaxAnthropic, BillingPresentation::Unknown),
3396 (ProviderKind::Deepinfra, BillingPresentation::Metered),
3397 (ProviderKind::Sakana, BillingPresentation::Metered),
3398 (ProviderKind::LongCat, BillingPresentation::Metered),
3399 (
3400 ProviderKind::OpencodeGo,
3401 BillingPresentation::Subscription("OpenCode Go quota"),
3402 ),
3403 (ProviderKind::OpencodeZen, BillingPresentation::Metered),
3404 (ProviderKind::Meta, BillingPresentation::Metered),
3405 (ProviderKind::Xai, BillingPresentation::Metered),
3406 (ProviderKind::Mistral, BillingPresentation::Metered),
3407 (ProviderKind::Telecomjs, BillingPresentation::Metered),
3408 (
3409 ProviderKind::ModelstudioTokenPlan,
3410 BillingPresentation::Subscription("Alibaba Token Plan"),
3411 ),
3412 (
3413 ProviderKind::ModelstudioTokenPlanAnthropic,
3414 BillingPresentation::Subscription("Alibaba Token Plan"),
3415 ),
3416 (
3417 ProviderKind::ModelstudioCodingPlan,
3418 BillingPresentation::Subscription("Alibaba Coding Plan"),
3419 ),
3420 (
3421 ProviderKind::ModelstudioCodingPlanAnthropic,
3422 BillingPresentation::Subscription("Alibaba Coding Plan"),
3423 ),
3424 // Retired identity: never selectable or runnable. A tombstone cannot
3425 // prove a billing product; retain its row so the audit stays exhaustive.
3426 (ProviderKind::Antigravity, BillingPresentation::Unknown),
3427 (ProviderKind::Google, BillingPresentation::Metered),
3428 (ProviderKind::Edenai, BillingPresentation::Metered),
3429 (ProviderKind::Zenmux, BillingPresentation::Metered),
3430 (
3431 ProviderKind::Csdn,
3432 BillingPresentation::Subscription("CSDN Coding Plan quota"),
3433 ),
3434 (ProviderKind::Concentrate, BillingPresentation::Metered),
3435 (ProviderKind::Codewhale, BillingPresentation::Metered),
3436 (ProviderKind::Custom, BillingPresentation::Unknown),
3437 ];
3438
3439 /// Default-route billing is a deliberate, audited decision for every
3440 /// provider `ProviderKind::all()` exposes — 51 rows covering the primary
3441 /// route and every dialect/plan-variant alternate identity.
3442 #[test]
3443 fn default_route_billing_audit_covers_every_provider() {
3444 let _lock = crate::test_support::lock_test_env();
3445 let _env: Vec<_> = BASE_URL_ENV_VARS
3446 .iter()
3447 .copied()
3448 .map(crate::test_support::EnvVarGuard::remove)
3449 .collect();
3450 // Credential shape also steers MiniMax's default product; the audit
3451 // pins the no-credential answer.
3452 let _minimax = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");
3453
3454 let audited: Vec<_> = DEFAULT_ROUTE_BILLING_AUDIT
3455 .iter()
3456 .map(|(provider, _)| provider)
3457 .collect();
3458 for (index, provider) in audited.iter().enumerate() {
3459 assert!(
3460 !audited[..index].contains(provider),
3461 "duplicate audit row for {provider:?}"
3462 );
3463 }
3464 for provider in ProviderKind::all() {
3465 assert!(
3466 audited.contains(&provider),
3467 "{provider:?} is missing from DEFAULT_ROUTE_BILLING_AUDIT"
3468 );
3469 }
3470 assert_eq!(
3471 DEFAULT_ROUTE_BILLING_AUDIT.len(),
3472 52,
3473 "the audit covers every provider identity, primary and alternate"
3474 );
3475
3476 let mut config = Config::default();
3477 config
3478 .providers
3479 .get_or_insert_with(Default::default)
3480 .custom
3481 .insert(
3482 "custom".into(),
3483 codewhale_runtime::config::ProviderConfig {
3484 kind: Some("openai-compatible".into()),
3485 base_url: Some("http://localhost:1234/v1".into()),
3486 model: Some("fixture-model".into()),
3487 ..Default::default()
3488 },
3489 );
3490 for (provider, expected) in DEFAULT_ROUTE_BILLING_AUDIT {
3491 let mut scoped = config.clone();
3492 scoped.provider = Some(provider.as_str().into());
3493 let identity = scoped.active_provider_identity().unwrap();
3494 let actual = for_route(&scoped, &identity);
3495 assert_eq!(
3496 &actual, expected,
3497 "{provider:?} default route billing changed; update the audit deliberately"
3498 );
3499 }
3500 }
3501 }
3502
3502 lines RUST