| 1 | //! System One decision API on the existing client (#6525). |
| 2 | //! |
| 3 | //! `[auto.router] kind = "decision"` asks a non-generative decision model |
| 4 | //! (TypeSafe's Jev) one typed Choice per turn. The wire is a plain JSON |
| 5 | //! `POST to the route’s decision endpoint` — not chat completions — served on two routes: |
| 6 | //! |
| 7 | //! * **OpenRouter** — `https://openrouter.ai/api/alpha/decisions` with the user's OpenRouter |
| 8 | //! key, built exactly like every other OpenRouter client. |
| 9 | //! * **TypeSafe direct** — `https://api.typesafe.ai/v1/systemone` with a |
| 10 | //! TypeSafe key. |
| 11 | //! |
| 12 | //! This is a child of `client` so it reuses the client's auth headers, TLS, |
| 13 | //! redaction and bounded retry plumbing; there is no second HTTP client. |
| 14 | //! |
| 15 | //! Known limits (written down so nobody assumes them): |
| 16 | //! * TypeSafe is **not** an [`ProviderKind`]: it serves no chat route, so it is |
| 17 | //! the decision router's own endpoint + key (`TYPESAFE_API_KEY`, the |
| 18 | //! `typesafe` secret-store slot, or `[providers.typesafe] api_key` / |
| 19 | //! `api_key_env`). Its tokens enter the shared usage ledger under a frozen |
| 20 | //! `custom` / `typesafe` route with unknown billing; reported cost is retained |
| 21 | //! on decision receipts. Unknown pricing is never interpreted as free. |
| 22 | //! * The routing call makes one attempt (no retry): it is bounded by the |
| 23 | //! router timeout, and a retried decision would arrive after the turn has |
| 24 | //! already fallen back. |
| 25 | //! * The router parses the `choice` answer shape; the shadow Decision Gate |
| 26 | //! (`crate::superfast`), whose questions ride the router's request when |
| 27 | //! `shadow_gate = true`, also reads `noul`. The transport strictly validates |
| 28 | //! Choice, Noul and fractional Score responses before either policy uses them. |
| 29 | |
| 30 | use std::collections::BTreeMap; |
| 31 | |
| 32 | use serde::Deserialize; |
| 33 | use serde_json::value::RawValue; |
| 34 | |
| 35 | use super::*; |
| 36 | use crate::model_routing::AutoRouterFailure; |
| 37 | |
| 38 | /// TypeSafe's direct API base (the `/systemone` path is appended). |
| 39 | pub const TYPESAFE_DEFAULT_BASE_URL: &str = "https://api.typesafe.ai/v1"; |
| 40 | /// Environment variable holding a TypeSafe API key. |
| 41 | pub const TYPESAFE_API_KEY_ENV: &str = "TYPESAFE_API_KEY"; |
| 42 | /// Secret-store slot and `[providers.<name>]` table name for the TypeSafe key. |
| 43 | pub const TYPESAFE_KEY_NAME: &str = "typesafe"; |
| 44 | /// Bound a non-generative decision response before allocating/decoding it. |
| 45 | const DECISION_RESPONSE_MAX_BYTES: usize = 256 * 1024; |
| 46 | const DECISION_REQUEST_MAX_BYTES: usize = 1024 * 1024; |
| 47 | |
| 48 | /// Which endpoint serves a decision router. |
| 49 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 50 | #[serde(rename_all = "snake_case")] |
| 51 | pub enum DecisionRouterRoute { |
| 52 | Openrouter, |
| 53 | Typesafe, |
| 54 | } |
| 55 | |
| 56 | impl DecisionRouterRoute { |
| 57 | /// Parse an `[auto.router] provider` value for a decision router. |
| 58 | #[must_use] |
| 59 | pub fn parse(provider: &str) -> Option<Self> { |
| 60 | let provider = provider.trim(); |
| 61 | if ProviderKind::parse(provider) == Some(ProviderKind::Openrouter) { |
| 62 | Some(Self::Openrouter) |
| 63 | } else if provider.eq_ignore_ascii_case(TYPESAFE_KEY_NAME) |
| 64 | || provider.eq_ignore_ascii_case("typesafe-ai") |
| 65 | { |
| 66 | Some(Self::Typesafe) |
| 67 | } else { |
| 68 | None |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | #[must_use] |
| 73 | pub fn as_str(self) -> &'static str { |
| 74 | match self { |
| 75 | Self::Openrouter => "openrouter", |
| 76 | Self::Typesafe => TYPESAFE_KEY_NAME, |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | #[must_use] |
| 81 | pub fn display_name(self) -> &'static str { |
| 82 | match self { |
| 83 | Self::Openrouter => "OpenRouter", |
| 84 | Self::Typesafe => "TypeSafe", |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /// Whether a credential for this route is present (never returns it). |
| 89 | #[must_use] |
| 90 | pub fn has_key(self, config: &Config) -> bool { |
| 91 | match self { |
| 92 | Self::Openrouter => config |
| 93 | .builtin_provider_identity(ProviderKind::Openrouter) |
| 94 | .is_ok_and(|identity| { |
| 95 | crate::provider_readiness::has_api_key_for(config, &identity) |
| 96 | }), |
| 97 | Self::Typesafe => typesafe_api_key(config).is_some(), |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// Resolve the TypeSafe key: environment, then the durable secret store, then |
| 103 | /// `[providers.typesafe] api_key` / `api_key_env`. |
| 104 | pub fn typesafe_api_key(config: &Config) -> Option<String> { |
| 105 | let non_empty = |value: String| (!value.trim().is_empty()).then(|| value.trim().to_string()); |
| 106 | if let Some(key) = std::env::var(TYPESAFE_API_KEY_ENV).ok().and_then(non_empty) { |
| 107 | return Some(key); |
| 108 | } |
| 109 | if let Some(key) = codewhale_runtime::config::credential_secret_store() |
| 110 | .and_then(|store| store.get(TYPESAFE_KEY_NAME).ok().flatten()) |
| 111 | .and_then(non_empty) |
| 112 | { |
| 113 | return Some(key); |
| 114 | } |
| 115 | let entry = config |
| 116 | .providers |
| 117 | .as_ref() |
| 118 | .and_then(|providers| providers.custom_provider_config(TYPESAFE_KEY_NAME))?; |
| 119 | entry.api_key.clone().and_then(non_empty).or_else(|| { |
| 120 | entry |
| 121 | .api_key_env |
| 122 | .as_deref() |
| 123 | .map(str::trim) |
| 124 | .filter(|name| !name.is_empty()) |
| 125 | .and_then(|name| std::env::var(name).ok()) |
| 126 | .and_then(non_empty) |
| 127 | }) |
| 128 | } |
| 129 | |
| 130 | /// A decoded System One response. Unknown fields are ignored. |
| 131 | #[derive(Debug, Clone)] |
| 132 | pub struct SystemOneResponse { |
| 133 | pub id: Option<String>, |
| 134 | pub model: Option<String>, |
| 135 | pub answers: BTreeMap<String, SystemOneAnswer>, |
| 136 | pub usage: Option<SystemOneUsage>, |
| 137 | /// Transport validation is separate from decoding so a rejected policy |
| 138 | /// answer still preserves the provider's usage/cost evidence. |
| 139 | pub answers_validated: Option<bool>, |
| 140 | } |
| 141 | |
| 142 | impl SystemOneResponse { |
| 143 | pub fn abstained_questions(&self, names: &[&str]) -> Vec<String> { |
| 144 | names |
| 145 | .iter() |
| 146 | .filter(|name| self.answers.get(**name).is_some_and(|a| a.abstained)) |
| 147 | .map(|name| (*name).to_string()) |
| 148 | .collect() |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | impl<'de> Deserialize<'de> for SystemOneResponse { |
| 153 | fn deserialize<D: serde::Deserializer<'de>>( |
| 154 | deserializer: D, |
| 155 | ) -> std::result::Result<Self, D::Error> { |
| 156 | #[derive(Deserialize)] |
| 157 | struct Envelope { |
| 158 | #[serde(default)] |
| 159 | id: Option<Box<RawValue>>, |
| 160 | #[serde(default)] |
| 161 | model: Option<Box<RawValue>>, |
| 162 | #[serde(default)] |
| 163 | answers: Option<Box<RawValue>>, |
| 164 | #[serde(default)] |
| 165 | usage: Option<Box<RawValue>>, |
| 166 | } |
| 167 | let wire = Envelope::deserialize(deserializer)?; |
| 168 | let text = |raw: Option<&RawValue>| { |
| 169 | raw.and_then(|raw| serde_json::from_str::<String>(raw.get()).ok()) |
| 170 | }; |
| 171 | let id = text(wire.id.as_deref()); |
| 172 | let model = text(wire.model.as_deref()); |
| 173 | let malformed_identity = |
| 174 | (wire.id.is_some() && id.is_none()) || (wire.model.is_some() && model.is_none()); |
| 175 | // Invalid policy fields must fail validation without discarding the |
| 176 | // separately reported billing evidence. Empty/default answers never |
| 177 | // satisfy the required question types or probabilities. |
| 178 | let answers: BTreeMap<String, Box<RawValue>> = wire |
| 179 | .answers |
| 180 | .and_then(|raw| serde_json::from_str(raw.get()).ok()) |
| 181 | .unwrap_or_default(); |
| 182 | Ok(Self { |
| 183 | id, |
| 184 | model, |
| 185 | answers: answers |
| 186 | .into_iter() |
| 187 | .map(|(key, raw)| (key, serde_json::from_str(raw.get()).unwrap_or_default())) |
| 188 | .collect(), |
| 189 | usage: wire |
| 190 | .usage |
| 191 | .and_then(|raw| serde_json::from_str(raw.get()).ok()), |
| 192 | answers_validated: malformed_identity.then_some(false), |
| 193 | }) |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | /// One answer. The `choice` and `noul` subsets are interpreted. |
| 198 | #[derive(Debug, Clone, Default, Deserialize)] |
| 199 | pub struct SystemOneAnswer { |
| 200 | #[serde(rename = "type", default)] |
| 201 | pub kind: String, |
| 202 | #[serde(default)] |
| 203 | pub choice: Option<String>, |
| 204 | /// A `noul` answer's probability; validated by its reader. |
| 205 | #[serde(default)] |
| 206 | pub noul: Option<f64>, |
| 207 | #[serde(default)] |
| 208 | pub score: Option<f64>, |
| 209 | #[serde(default)] |
| 210 | pub legend: BTreeMap<String, Value>, |
| 211 | #[serde(default)] |
| 212 | pub probabilities: BTreeMap<String, Option<f64>>, |
| 213 | #[serde(default)] |
| 214 | pub confidence: Option<f64>, |
| 215 | #[serde(default)] |
| 216 | pub abstained: bool, |
| 217 | } |
| 218 | |
| 219 | /// Provider usage. OpenRouter adds `cost`; the token-count casing differs |
| 220 | /// between surfaces, so both spellings are accepted. |
| 221 | #[derive(Debug, Clone)] |
| 222 | pub struct SystemOneUsage { |
| 223 | /// Kept verbatim so the receipt never re-renders a float. |
| 224 | pub cost: Option<Box<RawValue>>, |
| 225 | pub input_tokens: u32, |
| 226 | pub output_tokens: u32, |
| 227 | pub complete: bool, |
| 228 | } |
| 229 | |
| 230 | impl<'de> Deserialize<'de> for SystemOneUsage { |
| 231 | fn deserialize<D: serde::Deserializer<'de>>( |
| 232 | deserializer: D, |
| 233 | ) -> std::result::Result<Self, D::Error> { |
| 234 | let mut wire = BTreeMap::<String, Box<RawValue>>::deserialize(deserializer)?; |
| 235 | let count = |snake: &str, camel: &str| match (wire.get(snake), wire.get(camel)) { |
| 236 | (Some(raw), None) | (None, Some(raw)) => serde_json::from_str::<u32>(raw.get()).ok(), |
| 237 | // Missing, malformed or ambiguous counts cannot authorize policy |
| 238 | // or a priced subtotal; keep an independently valid raw cost. |
| 239 | _ => None, |
| 240 | }; |
| 241 | let input_tokens = count("input_tokens", "inputTokens"); |
| 242 | let output_tokens = count("output_tokens", "outputTokens"); |
| 243 | Ok(Self { |
| 244 | complete: input_tokens.is_some() && output_tokens.is_some(), |
| 245 | input_tokens: input_tokens.unwrap_or(0), |
| 246 | output_tokens: output_tokens.unwrap_or(0), |
| 247 | cost: wire.remove("cost"), |
| 248 | }) |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | impl SystemOneUsage { |
| 253 | /// The provider-reported cost as its verbatim JSON decimal, when it is a |
| 254 | /// finite, non-negative number. |
| 255 | #[must_use] |
| 256 | pub fn reported_cost(&self) -> Option<String> { |
| 257 | let raw = self.cost.as_ref()?.get().trim(); |
| 258 | let value: f64 = raw.parse().ok()?; |
| 259 | (raw.len() <= 128 && value.is_finite() && value >= 0.0).then(|| raw.to_string()) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | impl CodewhaleClient { |
| 264 | /// Build the client that serves `route`. |
| 265 | /// |
| 266 | /// OpenRouter is the ordinary OpenRouter client (its key, base URL, |
| 267 | /// attribution headers). TypeSafe re-points a clone of the active route's |
| 268 | /// client — keeping its retry, TLS and redaction policy — at the TypeSafe |
| 269 | /// endpoint with the TypeSafe key only. Its captured request budget and |
| 270 | /// remote-control ownership continue to apply to the one decision attempt. |
| 271 | pub fn for_decision_route( |
| 272 | config: &Config, |
| 273 | route: DecisionRouterRoute, |
| 274 | base_url_override: Option<&str>, |
| 275 | ) -> Result<Self> { |
| 276 | match route { |
| 277 | DecisionRouterRoute::Openrouter => { |
| 278 | let mut scoped = config.clone(); |
| 279 | scoped.provider = Some(ProviderKind::Openrouter.as_str().to_string()); |
| 280 | // The decision model id is not a chat route; it travels in the |
| 281 | // JSON body only. |
| 282 | scoped.default_text_model = None; |
| 283 | Self::new(&scoped) |
| 284 | } |
| 285 | DecisionRouterRoute::Typesafe => { |
| 286 | let key = typesafe_api_key(config).with_context(|| { |
| 287 | format!("TypeSafe API key not configured ({TYPESAFE_API_KEY_ENV})") |
| 288 | })?; |
| 289 | let base_url = base_url_override |
| 290 | .map(str::trim) |
| 291 | .filter(|url| !url.is_empty()) |
| 292 | .unwrap_or(TYPESAFE_DEFAULT_BASE_URL) |
| 293 | .trim_end_matches('/') |
| 294 | .to_string(); |
| 295 | validate_base_url_security(&base_url, false)?; |
| 296 | let mut client = Self::new(config)?; |
| 297 | let root_cert = capture_ssl_cert_file(); |
| 298 | client.http_client = Self::http_client_builder_with_auth_mode( |
| 299 | &key, |
| 300 | &HashMap::new(), |
| 301 | ProviderKind::Custom, |
| 302 | &base_url, |
| 303 | WireFormat::ChatCompletions, |
| 304 | false, |
| 305 | client.force_http1, |
| 306 | config, |
| 307 | AuthHeaderSurface::Inference, |
| 308 | root_cert.as_ref(), |
| 309 | )? |
| 310 | .build()?; |
| 311 | client.base_url = base_url; |
| 312 | client.http1_client = client.http_client.clone(); |
| 313 | // Repointing auth/URL must also replace the inherited chat |
| 314 | // route identity. No TypeSafe price/product is guessed. |
| 315 | client.api_provider = ProviderKind::Custom; |
| 316 | // The fixed decision authority owns this validated key/URL; |
| 317 | // ordinary route admission supplies only its exact identity. |
| 318 | let mut route_config = config.clone(); |
| 319 | route_config.provider = Some(TYPESAFE_KEY_NAME.into()); |
| 320 | route_config |
| 321 | .providers |
| 322 | .get_or_insert_with(codewhale_runtime::config::ProvidersConfig::default) |
| 323 | .custom |
| 324 | .insert( |
| 325 | TYPESAFE_KEY_NAME.into(), |
| 326 | codewhale_runtime::config::ProviderConfig { |
| 327 | kind: Some("openai-compatible".into()), |
| 328 | base_url: Some(client.base_url.clone()), |
| 329 | api_key: Some(key.clone()), |
| 330 | ..codewhale_runtime::config::ProviderConfig::default() |
| 331 | }, |
| 332 | ); |
| 333 | client.admitted_identity = route_config |
| 334 | .active_provider_identity() |
| 335 | .map_err(anyhow::Error::msg)?; |
| 336 | client.openrouter_vendor = None; |
| 337 | client.billing_surface = None; |
| 338 | client.billing_mode = crate::cost_status::RouteBillingMode::Unknown; |
| 339 | client.route_limits = None; |
| 340 | // `Self::new` froze the redaction set from the chat provider's |
| 341 | // secrets; the TypeSafe key is none of them, so add it before |
| 342 | // any decision body is built from untrusted context. |
| 343 | let mut secrets = client.model_bound_secret_values.as_ref().clone(); |
| 344 | push_model_bound_secret(&mut secrets, Some(&key)); |
| 345 | client.model_bound_secret_values = Arc::new(secrets); |
| 346 | client.api_key = key; |
| 347 | Ok(client) |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | /// `POST to the route’s decision endpoint` once, isolated like the Auto chat classifier: |
| 353 | /// no global retry banners or response cache; shared admission still applies. |
| 354 | /// |
| 355 | /// Only a failure class leaves this function — provider error bodies can |
| 356 | /// echo the prompt and must never reach receipts. |
| 357 | /// |
| 358 | /// The caller retains its isolated physical observations across cancellation, |
| 359 | /// including admission waits, HTTP refusal and response-body parsing. |
| 360 | pub async fn system_one_decide( |
| 361 | &self, |
| 362 | body: &Value, |
| 363 | observation: crate::llm_client::RequestRetryObservation, |
| 364 | ) -> std::result::Result<SystemOneResponse, AutoRouterFailure> { |
| 365 | crate::llm_client::observe_request_retries(Some(observation), async { |
| 366 | if serde_json::to_vec(body) |
| 367 | .map_or(true, |bytes| bytes.len() > DECISION_REQUEST_MAX_BYTES) |
| 368 | || !valid_decision_request(body) |
| 369 | { |
| 370 | return Err(AutoRouterFailure::NotRunnable); |
| 371 | } |
| 372 | let mut isolated = self.clone(); |
| 373 | isolated.isolated_request_state = true; |
| 374 | isolated.retry.max_retries = 0; |
| 375 | let _inference = isolated.acquire_remote_control_inference_permit().await; |
| 376 | let _permit = isolated.acquire_provider_request_permit().await; |
| 377 | let url = if isolated.api_provider == ProviderKind::Openrouter { |
| 378 | // The OpenRouter Decisions API is a sibling of /api/v1, so keep |
| 379 | // the configured origin/proxy prefix and replace only /v1. |
| 380 | let mut url = reqwest::Url::parse(&isolated.base_url) |
| 381 | .map_err(|_| AutoRouterFailure::NotRunnable)?; |
| 382 | let prefix = url.path().trim_end_matches('/').trim_end_matches("/v1"); |
| 383 | url.set_path(&format!("{prefix}/alpha/decisions")); |
| 384 | url.to_string() |
| 385 | } else { |
| 386 | api_url(&isolated.base_url, "systemone") |
| 387 | }; |
| 388 | let response = isolated |
| 389 | .send_json_with_retry(&url, body) |
| 390 | .await |
| 391 | .map_err(|error| router_failure_from_error(&error))?; |
| 392 | let text = bounded_provider_catalog_text(response, DECISION_RESPONSE_MAX_BYTES) |
| 393 | .await |
| 394 | .map_err(|error| match error { |
| 395 | CatalogRefreshError::Network => AutoRouterFailure::Transport, |
| 396 | _ => AutoRouterFailure::InvalidAnswer, |
| 397 | })?; |
| 398 | let mut response: SystemOneResponse = |
| 399 | serde_json::from_str(&text).map_err(|_| AutoRouterFailure::InvalidAnswer)?; |
| 400 | response.answers_validated = Some(valid_decision_response(body, &response)); |
| 401 | response.model = response.model.map(|model| { |
| 402 | self.redact_model_bound_text(&model) |
| 403 | .chars() |
| 404 | .take(128) |
| 405 | .collect() |
| 406 | }); |
| 407 | Ok(response) |
| 408 | }) |
| 409 | .await |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | fn valid_decision_request(body: &Value) -> bool { |
| 414 | let Some(questions) = body.get("questions").and_then(Value::as_object) else { |
| 415 | return false; |
| 416 | }; |
| 417 | let supported_value = |
| 418 | |value: &Value| matches!(value, Value::String(_) | Value::Object(_) | Value::Array(_)); |
| 419 | let model = body.get("model").and_then(Value::as_str); |
| 420 | model.is_some_and(|m| !m.trim().is_empty() && m.len() <= 256) |
| 421 | && body.get("state").is_some_and(|state| { |
| 422 | matches!(state, Value::String(_) | Value::Object(_) | Value::Array(_)) |
| 423 | }) |
| 424 | && !questions.is_empty() |
| 425 | && questions.len() <= 64 |
| 426 | && questions |
| 427 | .values() |
| 428 | .all(|q| match q.get("type").and_then(Value::as_str) { |
| 429 | Some("noul") => true, |
| 430 | Some("choice") => q |
| 431 | .get("criteria") |
| 432 | .and_then(Value::as_object) |
| 433 | .is_some_and(|c| { |
| 434 | !c.is_empty() |
| 435 | && c.len() <= 64 |
| 436 | && c.iter().all(|(name, v)| { |
| 437 | !name.trim().is_empty() |
| 438 | && name.len() <= 128 |
| 439 | && (v.is_null() || supported_value(v)) |
| 440 | }) |
| 441 | }), |
| 442 | Some("score") => q |
| 443 | .get("criteria") |
| 444 | .and_then(Value::as_array) |
| 445 | .is_some_and(|c| { |
| 446 | !c.is_empty() && c.len() <= 10 && c.iter().all(supported_value) |
| 447 | }), |
| 448 | _ => false, |
| 449 | }) |
| 450 | } |
| 451 | |
| 452 | fn valid_decision_response(body: &Value, response: &SystemOneResponse) -> bool { |
| 453 | let Some(questions) = body.get("questions").and_then(Value::as_object) else { |
| 454 | return false; |
| 455 | }; |
| 456 | response.answers_validated != Some(false) |
| 457 | && response |
| 458 | .model |
| 459 | .as_deref() |
| 460 | .is_some_and(|m| !m.trim().is_empty() && m.len() <= 256) |
| 461 | && response.usage.as_ref().is_some_and(|usage| usage.complete) |
| 462 | && response.answers.len() == questions.len() |
| 463 | && questions.iter().all(|(name, question)| { |
| 464 | let Some(answer) = response.answers.get(name) else { |
| 465 | return false; |
| 466 | }; |
| 467 | if Some(answer.kind.as_str()) != question.get("type").and_then(Value::as_str) { |
| 468 | return false; |
| 469 | } |
| 470 | match answer.kind.as_str() { |
| 471 | "noul" => answer |
| 472 | .noul |
| 473 | .is_some_and(|v| v.is_finite() && (0.0..=1.0).contains(&v)), |
| 474 | "choice" => { |
| 475 | let Some(criteria) = question.get("criteria").and_then(Value::as_object) else { |
| 476 | return false; |
| 477 | }; |
| 478 | let options = criteria.keys().map(String::as_str).collect::<Vec<_>>(); |
| 479 | crate::model_routing::validated_choice(Some(answer), &options).is_some() |
| 480 | } |
| 481 | "score" => { |
| 482 | let Some(criteria) = question.get("criteria").and_then(Value::as_array) else { |
| 483 | return false; |
| 484 | }; |
| 485 | if criteria.is_empty() || criteria.len() > 10 { |
| 486 | return false; |
| 487 | } |
| 488 | let Some(score) = answer.score else { |
| 489 | return false; |
| 490 | }; |
| 491 | if !score.is_finite() |
| 492 | || !(0.0..=(criteria.len() - 1) as f64).contains(&score) |
| 493 | || !answer |
| 494 | .confidence |
| 495 | .is_some_and(|v| v.is_finite() && (0.0..=1.0).contains(&v)) |
| 496 | || answer.legend.len() != criteria.len() |
| 497 | || answer.probabilities.len() != criteria.len() |
| 498 | { |
| 499 | return false; |
| 500 | } |
| 501 | let mut sum = 0.0; |
| 502 | let mut expected_score = 0.0; |
| 503 | for (level, criterion) in criteria.iter().enumerate() { |
| 504 | let key = level.to_string(); |
| 505 | let Some(Some(probability)) = answer.probabilities.get(&key) else { |
| 506 | return false; |
| 507 | }; |
| 508 | if answer.legend.get(&key) != Some(criterion) |
| 509 | || !probability.is_finite() |
| 510 | || !(0.0..=1.0).contains(probability) |
| 511 | { |
| 512 | return false; |
| 513 | } |
| 514 | sum += probability; |
| 515 | expected_score += level as f64 * probability; |
| 516 | } |
| 517 | (sum - 1.0).abs() <= 0.02 && (score - expected_score).abs() <= 0.02 |
| 518 | } |
| 519 | _ => false, |
| 520 | } |
| 521 | }) |
| 522 | } |
| 523 | |
| 524 | /// Collapse a client error into a non-secret failure class. The HTTP status |
| 525 | /// is kept where the error carries it; the body never is. |
| 526 | pub fn router_failure_from_error(error: &anyhow::Error) -> AutoRouterFailure { |
| 527 | let Some(error) = error.downcast_ref::<LlmError>() else { |
| 528 | return AutoRouterFailure::Transport; |
| 529 | }; |
| 530 | match error { |
| 531 | LlmError::RateLimited { .. } | LlmError::QuotaWindow { .. } => { |
| 532 | AutoRouterFailure::Http { status: 429 } |
| 533 | } |
| 534 | LlmError::ServerError { status, .. } | LlmError::InvalidRequest { status, .. } => { |
| 535 | AutoRouterFailure::Http { status: *status } |
| 536 | } |
| 537 | LlmError::AuthenticationError(_) => AutoRouterFailure::Http { status: 401 }, |
| 538 | LlmError::AuthorizationError(_) => AutoRouterFailure::Http { status: 403 }, |
| 539 | LlmError::QuotaExhausted(_) => AutoRouterFailure::QuotaExhausted, |
| 540 | LlmError::ModelError(_) |
| 541 | | LlmError::ContextLengthError(_) |
| 542 | | LlmError::ContentPolicyError(_) => AutoRouterFailure::Rejected, |
| 543 | LlmError::Other(message) => message |
| 544 | .strip_prefix("HTTP ") |
| 545 | .and_then(|rest| rest.split(':').next()) |
| 546 | .and_then(|status| status.trim().parse::<u16>().ok()) |
| 547 | .map_or(AutoRouterFailure::Transport, |status| { |
| 548 | AutoRouterFailure::Http { status } |
| 549 | }), |
| 550 | LlmError::NetworkError(_) |
| 551 | | LlmError::HeaderTimeout { .. } |
| 552 | | LlmError::ConnectError { .. } |
| 553 | | LlmError::Timeout(_) |
| 554 | | LlmError::ParseError(_) => AutoRouterFailure::Transport, |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | #[cfg(test)] |
| 559 | mod decisions_compatibility_tests { |
| 560 | use super::*; |
| 561 | |
| 562 | fn request() -> Value { |
| 563 | json!({"model":"typesafe/jev-1.13", "state":{"ticket":"charged twice"}, "questions": { |
| 564 | "intent": {"type":"choice", "criteria":{"billing":"money", "other":"anything else"}}, |
| 565 | "refund": {"type":"noul", "instructions":"Does it ask for a refund?"}, |
| 566 | "urgency": {"type":"score", "criteria":["Can wait", "Needs attention this week", "Needs attention today"]} |
| 567 | }}) |
| 568 | } |
| 569 | |
| 570 | fn response() -> Value { |
| 571 | json!({"id":"fixture-decision", "model":"typesafe/jev-1.13-20260917", "usage":{"input_tokens":287,"output_tokens":20,"cost":0.000012054}, "answers": { |
| 572 | "intent":{"type":"choice","choice":"billing","confidence":0.9,"probabilities":{"billing":0.9,"other":0.1}}, |
| 573 | "refund":{"type":"noul","noul":0.99}, |
| 574 | "urgency":{"type":"score","score":1.7,"confidence":0.9,"legend":{"0":"Can wait","1":"Needs attention this week","2":"Needs attention today"},"probabilities":{"0":0.1,"1":0.1,"2":0.8}} |
| 575 | }}) |
| 576 | } |
| 577 | |
| 578 | #[test] |
| 579 | fn all_documented_primitives_validate_without_rescaling_score() { |
| 580 | let decoded: SystemOneResponse = |
| 581 | serde_json::from_value(response()).expect("documented fixture"); |
| 582 | assert!(valid_decision_request(&request())); |
| 583 | assert!(valid_decision_response(&request(), &decoded)); |
| 584 | assert_eq!(decoded.answers["urgency"].score, Some(1.7)); |
| 585 | assert_eq!( |
| 586 | decoded.usage.expect("usage").reported_cost().as_deref(), |
| 587 | Some("0.000012054") |
| 588 | ); |
| 589 | } |
| 590 | |
| 591 | #[test] |
| 592 | fn wrong_types_unoffered_choices_scores_and_partial_shapes_are_rejected() { |
| 593 | let changes = [ |
| 594 | ("/answers/refund/noul", json!(1.01)), |
| 595 | ("/answers/refund/type", json!("score")), |
| 596 | ("/answers/intent/choice", json!("not-offered")), |
| 597 | ("/answers/intent/choice", json!("other")), |
| 598 | ("/answers/intent/confidence", json!(-0.1)), |
| 599 | ("/answers/intent/probabilities", json!({"billing":0.9})), |
| 600 | ( |
| 601 | "/answers/intent/probabilities", |
| 602 | json!({"billing":0.6,"other":0.6}), |
| 603 | ), |
| 604 | ("/answers/urgency/score", json!(2.01)), |
| 605 | ("/answers/urgency/score", json!(0.5)), |
| 606 | ("/answers/urgency/legend/1", json!("different rubric")), |
| 607 | ("/answers/urgency/probabilities/1", Value::Null), |
| 608 | ("/answers/urgency/confidence", json!(1.1)), |
| 609 | ("/model", Value::Null), |
| 610 | ("/usage", Value::Null), |
| 611 | ("/usage", json!({"input_tokens": 287, "cost":0.000012054})), |
| 612 | ("/answers", json!({})), |
| 613 | ]; |
| 614 | for (pointer, value) in changes { |
| 615 | let mut body = response(); |
| 616 | *body.pointer_mut(pointer).expect("fixture field") = value; |
| 617 | let decoded: SystemOneResponse = |
| 618 | serde_json::from_value(body).expect("structural decode"); |
| 619 | assert!( |
| 620 | !valid_decision_response(&request(), &decoded), |
| 621 | "accepted {pointer}" |
| 622 | ); |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | #[test] |
| 627 | fn non_finite_in_memory_answers_and_unbounded_request_shapes_are_rejected() { |
| 628 | let mut decoded: SystemOneResponse = serde_json::from_value(response()).expect("fixture"); |
| 629 | decoded.answers.get_mut("refund").expect("noul").noul = Some(f64::NAN); |
| 630 | assert!(!valid_decision_response(&request(), &decoded)); |
| 631 | let mut decoded: SystemOneResponse = serde_json::from_value(response()).expect("fixture"); |
| 632 | decoded.answers.get_mut("urgency").expect("score").score = Some(f64::INFINITY); |
| 633 | assert!(!valid_decision_response(&request(), &decoded)); |
| 634 | for shape in [ |
| 635 | json!({}), |
| 636 | json!({"model":"jev", "state":"hello", "questions":{}}), |
| 637 | json!({"model":"jev", "state":"hello", "questions":{"q":{"type":"score","criteria":vec!["level";11]}}}), |
| 638 | ] { |
| 639 | assert!(!valid_decision_request(&shape)); |
| 640 | } |
| 641 | } |
| 642 | #[tokio::test] |
| 643 | async fn decision_transport_preserves_typesafe_auth_and_shared_admission_before_dispatch() { |
| 644 | use wiremock::matchers::{header, method, path}; |
| 645 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 646 | let server = MockServer::start().await; |
| 647 | Mock::given(method("POST")) |
| 648 | .and(path("/v1/systemone")) |
| 649 | .and(header("authorization", "Bearer decision-fixture-key")) |
| 650 | .respond_with(ResponseTemplate::new(200).set_body_json(response())) |
| 651 | .expect(1) |
| 652 | .mount(&server) |
| 653 | .await; |
| 654 | let _lock = crate::test_support::lock_test_env(); |
| 655 | let home = tempfile::tempdir().expect("home"); |
| 656 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 657 | let _key = |
| 658 | crate::test_support::EnvVarGuard::set(TYPESAFE_API_KEY_ENV, "decision-fixture-key"); |
| 659 | let config = { |
| 660 | let __cw_config_init_0_0 = Some("deepseek".to_string()); |
| 661 | let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 662 | deepseek: codewhale_runtime::config::ProviderConfig { |
| 663 | api_key: Some("chat-fixture-key".into()), |
| 664 | max_concurrency: Some(1), |
| 665 | ..Default::default() |
| 666 | }, |
| 667 | ..Default::default() |
| 668 | }); |
| 669 | let mut __cw_config_init_0_value: Config = Default::default(); |
| 670 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 671 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 672 | __cw_config_init_0_value |
| 673 | }; |
| 674 | let base = format!("{}/v1", server.uri()); |
| 675 | let ticket = crate::test_support::env_scope_ticket(); |
| 676 | let client = tokio::task::spawn_blocking(move || { |
| 677 | let _membership = crate::test_support::join_env_scope(ticket); |
| 678 | CodewhaleClient::for_decision_route(&config, DecisionRouterRoute::Typesafe, Some(&base)) |
| 679 | }) |
| 680 | .await |
| 681 | .expect("worker") |
| 682 | .expect("client"); |
| 683 | assert_eq!(client.provider_request_concurrency_limit(), Some(1)); |
| 684 | assert!( |
| 685 | client.remote_control_inference_participant, |
| 686 | "the cloned budget must remain an attached inference participant" |
| 687 | ); |
| 688 | let clone = client.clone(); |
| 689 | let held = client |
| 690 | .acquire_provider_request_permit() |
| 691 | .await |
| 692 | .expect("shared permit"); |
| 693 | let observation = crate::llm_client::RequestRetryObservation::isolated(); |
| 694 | assert!( |
| 695 | tokio::time::timeout( |
| 696 | Duration::from_millis(30), |
| 697 | clone.system_one_decide(&request(), observation.clone()) |
| 698 | ) |
| 699 | .await |
| 700 | .is_err() |
| 701 | ); |
| 702 | assert!( |
| 703 | observation |
| 704 | .wire_observations |
| 705 | .drain() |
| 706 | .transmissions |
| 707 | .is_empty(), |
| 708 | "a queued request has no dispatched-spend marker" |
| 709 | ); |
| 710 | assert!( |
| 711 | server |
| 712 | .received_requests() |
| 713 | .await |
| 714 | .expect("requests") |
| 715 | .is_empty() |
| 716 | ); |
| 717 | drop(held); |
| 718 | let answer = client |
| 719 | .system_one_decide(&request(), observation.clone()) |
| 720 | .await |
| 721 | .expect("one admitted request"); |
| 722 | assert_eq!(observation.wire_observations.drain().transmissions.len(), 1); |
| 723 | assert_eq!(answer.answers_validated, Some(true)); |
| 724 | assert_eq!( |
| 725 | client |
| 726 | .effective_route_envelope("jev-latest", chrono::Utc::now()) |
| 727 | .provider_identity, |
| 728 | "typesafe" |
| 729 | ); |
| 730 | } |
| 731 | #[test] |
| 732 | fn decision_partial_usage_retains_raw_cost_but_cannot_authorize_policy() { |
| 733 | let mut body = response(); |
| 734 | body["usage"] = json!({"inputTokens": 287, "cost": 0.000012054}); |
| 735 | let decoded: SystemOneResponse = serde_json::from_value(body).expect("partial receipt"); |
| 736 | assert!(!valid_decision_response(&request(), &decoded)); |
| 737 | let usage = decoded.usage.expect("reported usage"); |
| 738 | assert!(!usage.complete); |
| 739 | assert_eq!(usage.input_tokens, 287); |
| 740 | assert_eq!(usage.reported_cost().as_deref(), Some("0.000012054")); |
| 741 | let route = crate::cost_status::decision_receipt_fixture("partial").route; |
| 742 | let mut body = response(); |
| 743 | body["usage"] = json!({"inputTokens": 287, "cost": 0.000012054}); |
| 744 | let response: SystemOneResponse = serde_json::from_value(body).expect("partial response"); |
| 745 | let batch = crate::model_routing::decision_usage_batch( |
| 746 | &route, |
| 747 | &response, |
| 748 | &crate::cost_status::NativeUsageSource::capture( |
| 749 | "partial", |
| 750 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 751 | ), |
| 752 | &crate::llm_client::OutboundWireObservationBatch::default(), |
| 753 | ); |
| 754 | assert_eq!(batch.records.len(), 1); |
| 755 | assert_eq!(batch.records[0].usage.usage.input_tokens, 287); |
| 756 | assert_eq!( |
| 757 | batch.records[0].settlement.as_ref().unwrap().coverage, |
| 758 | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 759 | ); |
| 760 | assert_eq!(batch.dropped_records, 0); |
| 761 | assert!(batch.drop_records.is_empty()); |
| 762 | let mut invalid = request(); |
| 763 | invalid["questions"]["urgency"]["criteria"] = json!([null]); |
| 764 | assert!(!valid_decision_request(&invalid)); |
| 765 | } |
| 766 | |
| 767 | #[test] |
| 768 | fn malformed_policy_fields_retain_independent_raw_cost() { |
| 769 | for (pointer, value) in [ |
| 770 | ("/answers/intent/choice", json!(17)), |
| 771 | ("/answers/intent/confidence", json!("high")), |
| 772 | ("/answers/refund", Value::Null), |
| 773 | ("/answers", json!([])), |
| 774 | ("/model", json!({"invalid":"model"})), |
| 775 | ("/id", json!([])), |
| 776 | ] { |
| 777 | let mut body = response(); |
| 778 | *body.pointer_mut(pointer).expect("fixture field") = value; |
| 779 | let decoded: SystemOneResponse = |
| 780 | serde_json::from_value(body).expect("billing envelope"); |
| 781 | assert!( |
| 782 | !valid_decision_response(&request(), &decoded), |
| 783 | "accepted {pointer}" |
| 784 | ); |
| 785 | let usage = decoded |
| 786 | .usage |
| 787 | .expect("independent usage survives rejected policy"); |
| 788 | assert!(usage.complete); |
| 789 | assert_eq!(usage.input_tokens, 287); |
| 790 | assert_eq!(usage.output_tokens, 20); |
| 791 | assert_eq!(usage.reported_cost().as_deref(), Some("0.000012054")); |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | #[test] |
| 796 | fn malformed_or_overflowed_counters_retain_cost_without_priced_usage() { |
| 797 | for counters in [ |
| 798 | json!({"input_tokens": u64::MAX, "output_tokens":20}), |
| 799 | json!({"input_tokens": -1, "output_tokens":20}), |
| 800 | json!({"input_tokens": "287", "output_tokens":20}), |
| 801 | json!({"input_tokens": 287, "inputTokens":287, "output_tokens":20}), |
| 802 | json!({"input_tokens": 287, "output_tokens":1.5}), |
| 803 | ] { |
| 804 | let mut body = response(); |
| 805 | body["usage"] = counters; |
| 806 | body["usage"]["cost"] = json!(0.000012054); |
| 807 | let decoded: SystemOneResponse = |
| 808 | serde_json::from_value(body).expect("billing envelope"); |
| 809 | assert!(!valid_decision_response(&request(), &decoded)); |
| 810 | let usage = decoded.usage.as_ref().expect("independent cost"); |
| 811 | assert!(!usage.complete); |
| 812 | assert_eq!(usage.reported_cost().as_deref(), Some("0.000012054")); |
| 813 | let route = crate::cost_status::decision_receipt_fixture("malformed-count").route; |
| 814 | let batch = crate::model_routing::decision_usage_batch( |
| 815 | &route, |
| 816 | &decoded, |
| 817 | &crate::cost_status::NativeUsageSource::capture( |
| 818 | "malformed-count", |
| 819 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 820 | ), |
| 821 | &crate::llm_client::OutboundWireObservationBatch::default(), |
| 822 | ); |
| 823 | assert_eq!(batch.records.len(), 1); |
| 824 | assert_eq!( |
| 825 | batch.records[0].usage.usage.input_tokens, |
| 826 | usage.input_tokens |
| 827 | ); |
| 828 | assert_eq!( |
| 829 | batch.records[0].usage.usage.output_tokens, |
| 830 | usage.output_tokens |
| 831 | ); |
| 832 | assert!(matches!( |
| 833 | batch.records[0].settlement.as_ref().unwrap().coverage, |
| 834 | crate::llm_client::ProviderUsageCoverage::Missing |
| 835 | | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 836 | )); |
| 837 | assert_eq!(batch.dropped_records, 0); |
| 838 | assert!(batch.drop_records.is_empty()); |
| 839 | } |
| 840 | } |
| 841 | } |
| 842 |