Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix: honor declared reasoning parameters on private Prime Inference routes (#3621)

Stu Caoa01c7923cfcb
diff --git a/crates/pa-core/src/models/mod.rs b/crates/pa-core/src/models/mod.rs
index ad2535b058..8ac717330a 100644
--- a/crates/pa-core/src/models/mod.rs
+++ b/crates/pa-core/src/models/mod.rs
@@ -41,9 +41,6 @@ pub use prime_inference::{
is_private_prime_inference_model, is_private_prime_inference_model_id,
private_prime_inference_models, PRIME_INFERENCE_BASE_URL,
};
-pub use prime_inference_catalog::{
- build_prime_inference_models, parse_prime_inference_model_catalog, PrimeInferenceCatalogEntry,
-};
pub use resolver::{
build_fallback_model, failover_candidates, find_exact_model_reference_match,
find_initial_model, find_preferred_default_model, resolve_cli_model,
diff --git a/crates/pa-core/src/models/prime_inference_catalog.rs b/crates/pa-core/src/models/prime_inference_catalog.rs
index ef5cb5945b..718c9d3766 100644
--- a/crates/pa-core/src/models/prime_inference_catalog.rs
+++ b/crates/pa-core/src/models/prime_inference_catalog.rs
@@ -1,327 +1,24 @@
-//! Prime Inference model catalog: parse, build, disk cache, and refresh.
+//! The Prime Inference `/models` fetch: the private-authorization flow's
+//! HTTP layer. The payload's parse and model build live in the catalog crate
+//! (`pa_models::prime_inference`), shared with the public routes.
use std::collections::HashMap;
-use pa_types::ai::{Model, ModelCompat, ModelCost, ModelInput};
-use pa_types::JsNumber;
-use serde::{Deserialize, Serialize};
-
-use super::prime_inference::{is_private_prime_inference_model_id, PRIME_INFERENCE_BASE_URL};
-
const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;
-const MIN_CATALOG_COVERAGE: f64 = 0.5;
-
-/// One parsed catalog entry (packages/ai `PrimeInferenceCatalogEntry`).
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", default)]
-pub struct PrimeInferenceCatalogEntry {
- pub id: String,
- pub name: Option<String>,
- pub input: f64,
- pub output: f64,
- pub cache_read: Option<f64>,
- pub cache_write: Option<f64>,
- pub context_window: Option<u64>,
- pub max_tokens: Option<u64>,
- pub vision: Option<bool>,
- pub reasoning: Option<bool>,
-}
-
-fn non_negative(value: &serde_json::Value) -> Option<f64> {
- value
- .as_f64()
- .filter(|number| number.is_finite() && *number >= 0.0)
-}
-
-fn positive_u64(value: &serde_json::Value) -> Option<u64> {
- value.as_u64().filter(|number| *number > 0)
-}
-
-fn strip_control(value: &str) -> String {
- value
- .chars()
- .filter(|c| !c.is_control() && !('\u{7f}'..='\u{9f}').contains(c))
- .collect::<String>()
- .trim()
- .to_string()
-}
-
-fn string_array(value: &serde_json::Value) -> Option<Vec<String>> {
- value.as_array().and_then(|items| {
- items
- .iter()
- .map(|item| item.as_str().map(str::to_string))
- .collect::<Option<Vec<String>>>()
- })
-}
-/// Parse the catalog payload; invalid entries drop out, duplicates fail.
+/// Fetch the live `/models` payload (timeout-capped, 2 MiB cap). `base_url`
+/// is the Prime Inference API base (production: [`super::prime_inference
+/// ::PRIME_INFERENCE_BASE_URL`]; tests pass a local server through the
+/// shared catalog's seam).
///
/// # Errors
///
-/// Human-readable error: no model array, duplicate ids, or empty while
-/// `allow_empty` is false.
-///
-/// # Panics
-///
-/// The `context_window.unwrap()` runs only when the specs guard proved the field present.
-pub fn parse_prime_inference_model_catalog(
- payload: &serde_json::Value,
- allow_empty: bool,
-) -> Result<Vec<PrimeInferenceCatalogEntry>, String> {
- let data = payload
- .get("data")
- .and_then(|data| data.as_array())
- .ok_or_else(|| "Invalid Prime Inference model catalog".to_string())?;
- let mut models = Vec::new();
- let mut seen = std::collections::HashSet::new();
- for item in data {
- let Some(id) = item.get("id").and_then(|id| id.as_str()) else {
- continue;
- };
- if id.is_empty() || id.len() > 1024 {
- continue;
- }
- if id
- .chars()
- .any(|c| c.is_control() || ('\u{7f}'..='\u{9f}').contains(&c))
- {
- continue;
- }
- if !seen.insert(id.to_string()) {
- return Err(format!("Duplicate Prime Inference model {id}"));
- }
- let pricing = item.get("pricing").cloned().unwrap_or_default();
- let Some(input) = non_negative(
- &pricing
- .get("input_usd_per_mtok")
- .cloned()
- .unwrap_or_default(),
- ) else {
- continue;
- };
- let Some(output) = non_negative(
- &pricing
- .get("output_usd_per_mtok")
- .cloned()
- .unwrap_or_default(),
- ) else {
- continue;
- };
- let name = item
- .get("display_name")
- .and_then(|name| name.as_str())
- .map(strip_control)
- .filter(|name| !name.is_empty());
- // Capability filtering (documented deviation from the TS parser,
- // which never reads this field): a model whose supported parameters
- // omit "tools" can never serve a turn, so it never enters the catalog;
- // entries without the field stay.
- let supported_parameters = string_array(
- item.get("supported_parameters")
- .unwrap_or(&serde_json::Value::Null),
- );
- if supported_parameters
- .is_some_and(|parameters| !parameters.iter().any(|parameter| parameter == "tools"))
- {
- continue;
- }
- let specs = item.get("specs").cloned().unwrap_or_default();
- let modalities = specs.get("modalities").cloned().unwrap_or_default();
- let input_modalities =
- string_array(modalities.get("input").unwrap_or(&serde_json::Value::Null));
- let output_modalities =
- string_array(modalities.get("output").unwrap_or(&serde_json::Value::Null));
- let context_window = positive_u64(
- specs
- .get("context_window")
- .unwrap_or(&serde_json::Value::Null),
- );
- let max_tokens = positive_u64(
- specs
- .get("max_output_tokens")
- .unwrap_or(&serde_json::Value::Null),
- );
- let reasoning = specs
- .get("supports_reasoning")
- .and_then(serde_json::Value::as_bool);
- let has_specs = context_window.is_some()
- && max_tokens.is_some()
- && reasoning.is_some()
- && input_modalities.is_some()
- && output_modalities.is_some();
- let entry = PrimeInferenceCatalogEntry {
- id: id.to_string(),
- name,
- input,
- output,
- cache_read: non_negative(
- &pricing
- .get("cache_read_usd_per_mtok")
- .cloned()
- .unwrap_or_default(),
- ),
- cache_write: non_negative(
- &pricing
- .get("cache_write_usd_per_mtok")
- .cloned()
- .unwrap_or_default(),
- ),
- context_window: if has_specs { context_window } else { None },
- max_tokens: if has_specs {
- max_tokens.map(|m| m.min(context_window.unwrap()))
- } else {
- None
- },
- vision: has_specs.then(|| {
- input_modalities
- .as_ref()
- .is_some_and(|m| m.iter().any(|modality| modality == "image"))
- }),
- reasoning: if has_specs { reasoning } else { None },
- };
- models.push(entry);
- }
- if models.is_empty() && !allow_empty {
- return Err("Prime Inference model catalog is empty".to_string());
- }
- Ok(models)
-}
-
-fn default_compat() -> ModelCompat {
- serde_json::from_value(serde_json::json!({
- "supportsStore": false,
- "supportsDeveloperRole": false,
- "supportsReasoningEffort": false,
- "maxTokensField": "max_tokens",
- "supportsStrictMode": false
- }))
- .expect("default compat serializes")
-}
-
-/// Build models from catalog entries over the bundled templates.
-#[must_use]
-pub fn build_prime_inference_models(
- bundled_models: &[Model],
- entries: &[PrimeInferenceCatalogEntry],
- include_private: bool,
-) -> Option<Vec<Model>> {
- build_prime_inference_models_with_minimum(bundled_models, entries, include_private, None)
-}
-
-/// Like [`build_prime_inference_models`] with an explicit coverage floor
-/// (`None` keeps the 50% default; `Some(0)` disables the check).
-pub fn build_prime_inference_models_with_minimum(
- bundled_models: &[Model],
- entries: &[PrimeInferenceCatalogEntry],
- include_private: bool,
- minimum_models: Option<usize>,
-) -> Option<Vec<Model>> {
- let bundled: HashMap<String, &Model> = bundled_models
- .iter()
- .map(|model| (model.id.to_lowercase(), model))
- .collect();
- let mut models = Vec::new();
- for entry in entries {
- if !include_private && is_private_prime_inference_model_id(&entry.id) {
- continue;
- }
- let template = bundled.get(&entry.id.to_lowercase());
- if template.is_none()
- && (entry.context_window.is_none()
- || entry.max_tokens.is_none()
- || entry.reasoning.is_none())
- {
- continue;
- }
- let template = template.map(|model| model as &Model);
- let context_window = entry
- .context_window
- .or_else(|| template.map(|t| t.context_window))
- .unwrap_or(0);
- let max_tokens = entry
- .max_tokens
- .or_else(|| template.map(|t| t.max_tokens))
- .unwrap_or(0)
- .min(context_window);
- let mut compat = template
- .and_then(|t| t.compat.clone())
- .unwrap_or_else(default_compat);
- let anthropic = entry.id.to_lowercase().starts_with("anthropic/");
- if anthropic {
- compat.raw.insert(
- "cacheControlFormat".to_string(),
- serde_json::Value::String("anthropic".to_string()),
- );
- }
- let cache_read = entry
- .cache_read
- .or_else(|| template.map(|t| t.cost.cache_read.0))
- .unwrap_or(if anthropic { entry.input * 0.1 } else { 0.0 });
- let cache_write = entry
- .cache_write
- .or_else(|| template.map(|t| t.cost.cache_write.0))
- .unwrap_or(if anthropic { entry.input * 1.25 } else { 0.0 });
- let vision = entry.vision.unwrap_or(false)
- || template.is_some_and(|t| t.input.contains(&ModelInput::Image));
- models.push(Model {
- id: entry.id.clone(),
- name: entry
- .name
- .clone()
- .or_else(|| template.map(|t| t.name.clone()))
- .unwrap_or_else(|| entry.id.clone()),
- api: "openai-completions".to_string(),
- provider: "prime-inference".to_string(),
- base_url: PRIME_INFERENCE_BASE_URL.to_string(),
- reasoning: entry
- .reasoning
- .or_else(|| template.map(|t| t.reasoning))
- .unwrap_or(false),
- thinking_level_map: template.and_then(|t| t.thinking_level_map.clone()),
- input: if vision {
- vec![ModelInput::Text, ModelInput::Image]
- } else {
- vec![ModelInput::Text]
- },
- cost: ModelCost {
- input: JsNumber::from(entry.input),
- output: JsNumber::from(entry.output),
- cache_read: JsNumber::from(cache_read),
- cache_write: JsNumber::from(cache_write),
- },
- context_window,
- max_tokens,
- // Catalog chain models stay capped: only explicit
- // configuration flips the flag.
- max_tokens_explicit: false,
- featured: template.and_then(|t| t.featured),
- headers: None,
- compat: Some(compat),
- });
- }
- let minimum = minimum_models
- .unwrap_or_else(|| ((bundled.len() as f64) * MIN_CATALOG_COVERAGE).ceil() as usize);
- let covered = models
- .iter()
- .filter(|model| bundled.contains_key(&model.id.to_lowercase()))
- .count();
- if covered >= minimum {
- Some(models)
- } else {
- None
- }
-}
-
-/// Fetch the live catalog (5s timeout, 2 MiB cap). `base_url` is the API
-/// base (production: [`PRIME_INFERENCE_BASE_URL`]; tests pass a local
-/// server through the shared catalog's seam).
+/// Human-readable error: the request failed, or the body is not JSON.
pub(crate) async fn fetch_prime_inference_model_catalog(
base_url: &str,
headers: Option<&HashMap<String, String>>,
timeout_ms: u64,
- allow_empty: bool,
-) -> Result<(serde_json::Value, Vec<PrimeInferenceCatalogEntry>), String> {
+) -> Result<serde_json::Value, String> {
let client = pa_ai::utils::tls::http_client_builder()
.timeout(std::time::Duration::from_millis(timeout_ms))
.build()
@@ -345,79 +42,5 @@ pub(crate) async fn fetch_prime_inference_model_catalog(
if bytes.len() > MAX_RESPONSE_BYTES {
return Err("Response is too large".to_string());
}
- let payload: serde_json::Value =
- serde_json::from_slice(&bytes).map_err(|error| error.to_string())?;
- let entries = parse_prime_inference_model_catalog(&payload, allow_empty)?;
- Ok((payload, entries))
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn bundled() -> Vec<Model> {
- vec![serde_json::from_value(serde_json::json!({
- "id": "z-ai/glm-5.3", "name": "GLM", "api": "openai-completions",
- "provider": "prime-inference", "baseUrl": PRIME_INFERENCE_BASE_URL,
- "reasoning": true, "input": ["text"],
- "cost": { "input": 1, "output": 2, "cacheRead": 0.1, "cacheWrite": 1.25 },
- "contextWindow": 128_000, "maxTokens": 8192, "featured": true,
- "compat": { "maxTokensField": "max_tokens" }
- }))
- .unwrap()]
- }
-
- #[test]
- fn parses_catalog_entries() {
- let payload = serde_json::json!({
- "data": [
- {
- "id": "z-ai/glm-5.3",
- "pricing": { "input_usd_per_mtok": 0.6, "output_usd_per_mtok": 2.2 },
- "specs": { "context_window": 200_000, "max_output_tokens": 16384,
- "supports_reasoning": true,
- "modalities": { "input": ["text"], "output": ["text"] } }
- },
- { "id": "bad", "pricing": {} },
- { "id": "internal/x", "pricing": { "input_usd_per_mtok": 0, "output_usd_per_mtok": 0 } }
- ]
- });
- let entries = parse_prime_inference_model_catalog(&payload, false).unwrap();
- assert_eq!(entries.len(), 2);
- assert_eq!(entries[0].context_window, Some(200_000));
- // Private ids parse but build() excludes them by default.
- let models = build_prime_inference_models(&bundled(), &entries, false).unwrap();
- assert!(models
- .iter()
- .all(|m| !is_private_prime_inference_model_id(&m.id)));
- }
-
- #[test]
- fn build_requires_minimum_coverage() {
- let payload = serde_json::json!({ "data": [
- { "id": "other/model", "pricing": { "input_usd_per_mtok": 1, "output_usd_per_mtok": 1 },
- "specs": { "context_window": 1000, "max_output_tokens": 500, "supports_reasoning": false,
- "modalities": { "input": ["text"], "output": ["text"] } } }
- ]});
- let entries = parse_prime_inference_model_catalog(&payload, false).unwrap();
- // 0/1 bundled coverage < 50% -> None.
- assert!(build_prime_inference_models(&bundled(), &entries, false).is_none());
- }
-
- #[test]
- fn entries_without_tool_support_are_filtered() {
- let payload = serde_json::json!({ "data": [
- { "id": "z-ai/glm-5.3",
- "pricing": { "input_usd_per_mtok": 0.6, "output_usd_per_mtok": 2.2 },
- "supported_parameters": ["max_tokens", "temperature", "tools", "tool_choice"] },
- { "id": "meta-llama/Llama-3.2-1B-Instruct",
- "pricing": { "input_usd_per_mtok": 0.1, "output_usd_per_mtok": 0.2 },
- "supported_parameters": ["max_tokens", "temperature", "top_p"] },
- { "id": "qwen/qwen3.8-max",
- "pricing": { "input_usd_per_mtok": 1, "output_usd_per_mtok": 4 } }
- ]});
- let entries = parse_prime_inference_model_catalog(&payload, false).unwrap();
- let ids: Vec<&str> = entries.iter().map(|entry| entry.id.as_str()).collect();
- assert_eq!(ids, vec!["z-ai/glm-5.3", "qwen/qwen3.8-max"]);
- }
+ serde_json::from_slice(&bytes).map_err(|error| error.to_string())
}
diff --git a/crates/pa-core/src/models/private_auth.rs b/crates/pa-core/src/models/private_auth.rs
index 2fde93bcec..b58241fdc2 100644
--- a/crates/pa-core/src/models/private_auth.rs
+++ b/crates/pa-core/src/models/private_auth.rs
@@ -9,10 +9,12 @@ use hmac::{Hmac, Mac};
use pa_types::ai::Model;
use sha2::Sha256;
+use serde_json::Value;
+
use super::prime_inference::is_private_prime_inference_model_id;
-use super::prime_inference_catalog::{
- build_prime_inference_models_with_minimum, fetch_prime_inference_model_catalog,
- parse_prime_inference_model_catalog, PrimeInferenceCatalogEntry,
+use super::prime_inference_catalog::fetch_prime_inference_model_catalog;
+use pa_models::prime_inference::{
+ build_prime_inference_models, parse_prime_inference_model_catalog, PrimeInferenceEntry,
};
const PRIVATE_PRIME_AUTHORIZATION_CACHE_FILE: &str = "prime-inference-private-models.json";
@@ -46,79 +48,125 @@ pub fn private_prime_authorization_fingerprint(api_key: &str, team_id: &str) ->
})
}
+/// The account's authorized private Prime Inference routes from a successful
+/// entitlement fetch: the models the registry serves, plus the raw `/models`
+/// wire items they were built from — the durable form the authorization cache
+/// stores, so a read rebuilds with the reasoning declarations intact.
+#[derive(Debug, Clone, Default)]
+pub struct AuthorizedPrivatePrimeInferenceModels {
+ pub models: Vec<Model>,
+ pub items: Vec<Value>,
+}
+
/// Fetch the team's authorized private models; 401/403 settle to empty.
/// `base_url` is the Prime Inference API base (the shared catalog's, so
/// hermetic tests aim the whole flow at a local server).
+///
+/// # Errors
+///
+/// Propagates the fetch's error, or the catalog parse's (an invalid payload).
pub async fn fetch_authorized_private_prime_inference_models(
base_url: &str,
api_key: &str,
team_headers: &HashMap<String, String>,
public_model_ids: &HashSet<String>,
timeout_ms: u64,
-) -> Result<Vec<Model>, String> {
+) -> Result<AuthorizedPrivatePrimeInferenceModels, String> {
if team_headers.get("X-Prime-Team-ID").is_none() {
- return Ok(Vec::new());
+ return Ok(AuthorizedPrivatePrimeInferenceModels::default());
}
let mut headers = team_headers.clone();
headers.insert("Authorization".to_string(), format!("Bearer {api_key}"));
- let fetch =
- fetch_prime_inference_model_catalog(base_url, Some(&headers), timeout_ms, true).await;
- let (payload, entries) = match fetch {
- Ok(result) => result,
+ let fetch = fetch_prime_inference_model_catalog(base_url, Some(&headers), timeout_ms).await;
+ let payload = match fetch {
+ Ok(payload) => payload,
Err(error) => {
// 401/403 mean "no entitlements", not a failure.
if error.contains("with status 401") || error.contains("with status 403") {
- return Ok(Vec::new());
+ return Ok(AuthorizedPrivatePrimeInferenceModels::default());
}
return Err(error);
}
};
+ // A malformed catalog is a failure, not an empty authorization: the
+ // registry's error path preserves the previous entitlements, while an
+ // empty success would wipe them and pin the wipe into the cache.
+ let data = payload
+ .get("data")
+ .and_then(|data| data.as_array())
+ .ok_or_else(|| "Invalid Prime Inference model catalog".to_string())?;
let public_ids: HashSet<String> = public_model_ids
.iter()
.map(|id| id.to_lowercase())
.collect();
+ let items = data
+ .iter()
+ .filter(|item| {
+ let Some(id) = item.get("id").and_then(|id| id.as_str()) else {
+ return false;
+ };
+ let lower = id.to_lowercase();
+ !public_ids.contains(&lower) && is_private_prime_inference_model_id(&lower)
+ })
+ .cloned()
+ .collect::<Vec<_>>();
+ let models = build_authorized_private_models(&items)?;
+ Ok(AuthorizedPrivatePrimeInferenceModels { models, items })
+}
+
+/// Build the registry's private models from the raw `/models` wire items: the
+/// parse and build are the catalog crate's, shared with the public routes, so
+/// a route's declared reasoning parameters rebuild into the model's compat and
+/// thinking-level map. An item the parser drops survives on a bundled
+/// template's entry.
+///
+/// # Errors
+///
+/// Propagates the catalog parse's error (an invalid item payload).
+fn build_authorized_private_models(items: &[Value]) -> Result<Vec<Model>, String> {
let bundled = super::prime_inference::private_prime_inference_models();
let bundled_by_id: HashMap<String, &Model> = bundled
.iter()
.map(|model| (model.id.to_lowercase(), model))
.collect();
- let entries_by_id: HashMap<String, &PrimeInferenceCatalogEntry> = entries
+ let parsed = parse_prime_inference_model_catalog(&serde_json::json!({ "data": items }), true)?;
+ let parsed_by_id: HashMap<String, &PrimeInferenceEntry> = parsed
.iter()
.map(|entry| (entry.id.to_lowercase(), entry))
.collect();
- let Some(data) = payload.get("data").and_then(|data| data.as_array()) else {
- return Ok(Vec::new());
- };
- let mut private_entries = Vec::new();
- for item in data {
- let Some(id) = item.get("id").and_then(|id| id.as_str()) else {
- continue;
- };
- let lower = id.to_lowercase();
- if public_ids.contains(&lower) || !is_private_prime_inference_model_id(&lower) {
- continue;
- }
- if let Some(parsed) = entries_by_id.get(&lower) {
- private_entries.push((*parsed).clone());
- } else if let Some(template) = bundled_by_id.get(&lower) {
- private_entries.push(PrimeInferenceCatalogEntry {
- id: id.to_string(),
- input: template.cost.input.0,
- output: template.cost.output.0,
- ..Default::default()
- });
- }
- }
- Ok(
- build_prime_inference_models_with_minimum(&bundled, &private_entries, true, Some(0))
- .unwrap_or_default(),
- )
+ let entries = items
+ .iter()
+ .filter_map(|item| {
+ let id = item.get("id").and_then(|id| id.as_str())?;
+ let lower = id.to_lowercase();
+ if !is_private_prime_inference_model_id(&lower) {
+ return None;
+ }
+ if let Some(parsed) = parsed_by_id.get(&lower) {
+ return Some((*parsed).clone());
+ }
+ bundled_by_id
+ .get(&lower)
+ .map(|template| PrimeInferenceEntry {
+ id: id.to_string(),
+ input: template.cost.input.0,
+ output: template.cost.output.0,
+ ..PrimeInferenceEntry::default()
+ })
+ })
+ .collect::<Vec<_>>();
+ Ok(build_prime_inference_models(&bundled, &entries, true, Some(0)).unwrap_or_default())
}
/// A cached authorization: fingerprint-scoped models with a refresh timestamp.
#[derive(Debug, Clone)]
pub struct PrivatePrimeAuthorizationCache {
pub fingerprint: String,
+ /// The raw `/models` wire items for the account's private routes — the
+ /// durable form this cache stores; a read rebuilds the models from them,
+ /// so the live reasoning declarations survive the round-trip.
+ pub items: Vec<Value>,
+ /// The models built from `items`: the registry's usable form.
pub models: Vec<Model>,
pub refreshed_at: u64,
}
@@ -247,21 +295,11 @@ fn parse_private_prime_authorization_cache(path: &Path) -> Option<PrivatePrimeAu
let parsed: serde_json::Value = serde_json::from_str(&content).ok()?;
let fingerprint = parsed.get("fingerprint")?.as_str()?.to_string();
let refreshed_at = parsed.get("refreshedAt")?.as_u64()?;
- let data = parsed.get("data")?.as_array()?;
- let entries = parse_prime_inference_model_catalog(&serde_json::json!({ "data": data }), true)
- .ok()?
- .into_iter()
- .filter(|entry| is_private_prime_inference_model_id(&entry.id))
- .collect::<Vec<_>>();
- let models = build_prime_inference_models_with_minimum(
- &super::prime_inference::private_prime_inference_models(),
- &entries,
- true,
- Some(0),
- )
- .unwrap_or_default();
+ let items = parsed.get("data")?.as_array()?.clone();
+ let models = build_authorized_private_models(&items).ok()?;
Some(PrivatePrimeAuthorizationCache {
fingerprint,
+ items,
models,
refreshed_at,
})
@@ -274,31 +312,9 @@ pub fn write_private_prime_authorization_cache(
models_json_path: &Path,
cache: &PrivatePrimeAuthorizationCache,
) {
- let data: Vec<serde_json::Value> = cache
- .models
- .iter()
- .map(|model| {
- serde_json::json!({
- "id": model.id,
- "display_name": model.name,
- "pricing": {
- "input_usd_per_mtok": model.cost.input.0,
- "output_usd_per_mtok": model.cost.output.0,
- "cache_read_usd_per_mtok": model.cost.cache_read.0,
- "cache_write_usd_per_mtok": model.cost.cache_write.0,
- },
- "specs": {
- "context_window": model.context_window,
- "max_output_tokens": model.max_tokens,
- "modalities": { "input": model.input.iter().map(|i| match i { pa_types::ai::ModelInput::Text => "text", pa_types::ai::ModelInput::Image => "image" }).collect::<Vec<_>>(), "output": ["text"] },
- "supports_reasoning": model.reasoning,
- }
- })
- })
- .collect();
let document = serde_json::json!({
"fingerprint": cache.fingerprint,
- "data": data,
+ "data": cache.items,
"refreshedAt": cache.refreshed_at,
});
let path = private_prime_authorization_cache_path(models_json_path);
@@ -322,10 +338,33 @@ pub fn is_offline_mode_enabled() -> bool {
mod tests {
use super::*;
+ /// One bundled private route's wire item (the durable cache form).
+ fn wire_item(model: &Model) -> serde_json::Value {
+ serde_json::json!({
+ "id": model.id,
+ "display_name": model.name,
+ "pricing": {
+ "input_usd_per_mtok": model.cost.input.0,
+ "output_usd_per_mtok": model.cost.output.0,
+ "cache_read_usd_per_mtok": model.cost.cache_read.0,
+ "cache_write_usd_per_mtok": model.cost.cache_write.0,
+ },
+ "specs": {
+ "context_window": model.context_window,
+ "max_output_tokens": model.max_tokens,
+ "supports_reasoning": model.reasoning,
+ "modalities": { "input": ["text"], "output": ["text"] },
+ },
+ })
+ }
+
fn cache(fingerprint: &str) -> PrivatePrimeAuthorizationCache {
+ let models = get_private_prime_inference_models();
+ let items = models.iter().map(wire_item).collect::<Vec<_>>();
PrivatePrimeAuthorizationCache {
fingerprint: fingerprint.to_string(),
- models: get_private_prime_inference_models(),
+ models,
+ items,
refreshed_at: 1,
}
}
@@ -479,4 +518,81 @@ mod tests {
"fingerprint-a"
);
}
+
+ /// The private-reasoning regression: the cache round-trips the raw wire
+ /// items, so a route declaring its reasoning parameters (the live
+ /// `internal/deepseek-v4.1-flash` shape) rebuilds with the declared
+ /// controls — a cache that stored only the built models' pricing and
+ /// specs would drop them, and the model would stop addressing reasoning.
+ #[test]
+ fn the_cache_rebuilds_declared_reasoning_controls_from_the_wire_items() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let models_json = dir.path().join("models.json");
+ write_private_prime_authorization_cache(
+ &models_json,
+ &PrivatePrimeAuthorizationCache {
+ fingerprint: "fingerprint-a".into(),
+ items: vec![serde_json::json!({
+ "id": "internal/deepseek-flash",
+ "display_name": "DeepSeek Flash (internal)",
+ "pricing": {
+ "input_usd_per_mtok": 0.0,
+ "output_usd_per_mtok": 0.0,
+ },
+ "specs": {
+ "context_window": 1_048_576,
+ "max_output_tokens": 131_072,
+ "supports_reasoning": true,
+ "modalities": { "input": ["text"], "output": ["text"] },
+ },
+ "supported_parameters": [
+ "max_tokens", "temperature", "tools", "tool_choice",
+ "reasoning", "reasoning_effort",
+ ],
+ "reasoning": {
+ "supported_efforts": ["none", "low", "high", "max"],
+ "default_effort": "high",
+ },
+ })],
+ models: Vec::new(),
+ refreshed_at: 1,
+ },
+ );
+ let cache = read_private_prime_authorization_cache(&models_json).expect("cache readable");
+ let model = cache
+ .models
+ .iter()
+ .find(|model| model.id == "internal/deepseek-flash")
+ .expect("the declared route rebuilds");
+ let compat = model
+ .compat
+ .as_ref()
+ .expect("the built route carries compat");
+ assert_eq!(
+ compat.raw.get("supportsReasoningEffort"),
+ Some(&serde_json::json!(true)),
+ "the declared reasoning_effort parameter must be addressable"
+ );
+ assert_eq!(compat.raw.get("thinkingFormat"), None);
+ let map = model
+ .thinking_level_map
+ .as_ref()
+ .expect("addressable levels");
+ assert_eq!(
+ map.get(&pa_types::ai::ModelThinkingLevel::High),
+ Some(&Some("high".into()))
+ );
+ assert_eq!(
+ map.get(&pa_types::ai::ModelThinkingLevel::Low),
+ Some(&Some("low".into()))
+ );
+ assert_eq!(
+ map.get(&pa_types::ai::ModelThinkingLevel::Max),
+ Some(&Some("max".into()))
+ );
+ assert_eq!(
+ map.get(&pa_types::ai::ModelThinkingLevel::Off),
+ Some(&Some("none".into()))
+ );
+ }
}
diff --git a/crates/pa-core/src/models/registry.rs b/crates/pa-core/src/models/registry.rs
index eb2a2c967a..3fc6a11c61 100644
--- a/crates/pa-core/src/models/registry.rs
+++ b/crates/pa-core/src/models/registry.rs
@@ -334,7 +334,7 @@ impl ModelRegistry {
let Some(PrivatePrimeAuthorizationCache {
fingerprint: cached_fingerprint,
models,
- refreshed_at: _,
+ ..
}) = read_private_prime_authorization_cache(&models_json_path)
else {
return;
@@ -652,6 +652,7 @@ impl ModelRegistry {
fingerprint: cached_fingerprint,
models,
refreshed_at,
+ ..
}) = cached
{
if cached_fingerprint == fingerprint {
@@ -690,9 +691,14 @@ impl ModelRegistry {
PRIVATE_MODEL_TIMEOUT_MS,
)
.await;
- if let Ok(models) = fetched {
- self.authorized_private_ids = models.iter().map(|model| model.id.clone()).collect();
- self.authorized_private_models.clone_from(&models);
+ if let Ok(authorized) = fetched {
+ self.authorized_private_ids = authorized
+ .models
+ .iter()
+ .map(|model| model.id.clone())
+ .collect();
+ self.authorized_private_models
+ .clone_from(&authorized.models);
self.authorized_team_id = Some(team_id);
self.load_models();
if let Some(cache_path) = self.models_json_path.clone() {
@@ -700,7 +706,8 @@ impl ModelRegistry {
&cache_path,
&PrivatePrimeAuthorizationCache {
fingerprint,
- models,
+ items: authorized.items,
+ models: authorized.models,
refreshed_at: now_millis(),
},
);
@@ -723,7 +730,7 @@ impl ModelRegistry {
cache_path: PathBuf,
) {
let public_ids = self.public_prime_inference_ids();
- let Ok(models) = fetch_authorized_private_prime_inference_models(
+ let Ok(authorized) = fetch_authorized_private_prime_inference_models(
self.catalog.prime_inference_base_url(),
&api_key,
&team_headers,
@@ -738,15 +745,21 @@ impl ModelRegistry {
if private_prime_authorization_fingerprint(&api_key, &team_id) != fingerprint {
return;
}
- self.authorized_private_ids = models.iter().map(|model| model.id.clone()).collect();
- self.authorized_private_models.clone_from(&models);
+ self.authorized_private_ids = authorized
+ .models
+ .iter()
+ .map(|model| model.id.clone())
+ .collect();
+ self.authorized_private_models
+ .clone_from(&authorized.models);
self.authorized_team_id = Some(team_id);
self.load_models();
write_private_prime_authorization_cache(
&cache_path,
&PrivatePrimeAuthorizationCache {
fingerprint,
- models,
+ items: authorized.items,
+ models: authorized.models,
refreshed_at: now_millis(),
},
);
diff --git a/crates/pa-daemon/src/model_catalog.rs b/crates/pa-daemon/src/model_catalog.rs
index 40d2fb6660..ab04ab8798 100644
--- a/crates/pa-daemon/src/model_catalog.rs
+++ b/crates/pa-daemon/src/model_catalog.rs
@@ -348,6 +348,35 @@ mod tests {
serde_json::to_string(&json!({"data": data})).unwrap()
}
+ /// A private entitlement payload whose route declares the live reasoning
+ /// parameters (`supported_parameters` with `reasoning`/`reasoning_effort`
+ /// plus the supported efforts) — the shape the internal `DeepSeek` routes
+ /// serve: reasoning arrives only when a request addresses it.
+ fn reasoning_private_payload(id: &str) -> String {
+ serde_json::to_string(&json!({
+ "data": [{
+ "id": id,
+ "display_name": id,
+ "pricing": {"input_usd_per_mtok": 1.0, "output_usd_per_mtok": 2.0},
+ "specs": {
+ "context_window": 200_000,
+ "max_output_tokens": 32_768,
+ "supports_reasoning": true,
+ "modalities": {"input": ["text"], "output": ["text"]},
+ },
+ "supported_parameters": [
+ "max_tokens", "temperature", "tools", "tool_choice",
+ "reasoning", "reasoning_effort",
+ ],
+ "reasoning": {
+ "supported_efforts": ["none", "low", "high", "max"],
+ "default_effort": "high",
+ },
+ }]
+ }))
+ .unwrap()
+ }
+
fn write_auth_json(agent_dir: &Path, api_key: &str, team_id: &str) {
std::fs::write(
agent_dir.join("auth.json"),
@@ -734,6 +763,116 @@ mod tests {
);
}
+ /// The private-route reasoning regression: a route that declares its
+ /// reasoning parameters (the live `internal/deepseek-v4.1-flash` shape)
+ /// must serve a model whose compat addresses them — the served catalog
+ /// reads the authorization cache back, so this pins the fetch build AND
+ /// the cache round-trip. Without the declared controls rebuilt into the
+ /// model, a thinking session sends no `reasoning_effort`, and a route
+ /// that only thinks when asked emits no thinking at all.
+ #[tokio::test]
+ async fn a_private_route_with_declared_reasoning_serves_addressable_levels() {
+ let answers = vec![
+ Answer::Raw(ok_json(&catalog_aggregate(&["probe-v1"]))),
+ Answer::Raw(ok_json(&pi_snapshot_payload("live/team-a-marker"))),
+ Answer::Raw(ok_json(&reasoning_private_payload(
+ "internal/team-a-private",
+ ))),
+ ];
+ let fixture = fixture(answers).await;
+
+ let served = get_model_catalog(&fixture.worker, "catalog-session").await;
+ assert_canonical_models_order(&served);
+ let model = served["models"]
+ .as_array()
+ .expect("models array")
+ .iter()
+ .find(|model| model["id"] == "internal/team-a-private")
+ .expect("the authorized private route");
+ assert_eq!(
+ model["compat"]["supportsReasoningEffort"], true,
+ "the declared reasoning_effort parameter must be addressable"
+ );
+ assert_eq!(model["thinkingLevelMap"]["high"], "high");
+ assert_eq!(model["thinkingLevelMap"]["low"], "low");
+ assert_eq!(model["thinkingLevelMap"]["max"], "max");
+ assert_eq!(model["thinkingLevelMap"]["off"], "none");
+ }
+
+ /// The malformed-entitlement regression: a 200 body without a `data`
+ /// array is a fetch failure, not an empty authorization — an empty
+ /// success would wipe the authorized private models and rewrite the
+ /// fingerprint cache with an empty set and a fresh TTL.
+ #[tokio::test]
+ async fn a_malformed_entitlement_payload_keeps_the_authorized_private_models() {
+ let fixture = fixture(create_phase_answers()).await;
+ // Age the on-disk authorization past its TTL so the next refresh
+ // refetches the entitlements in the background.
+ let cache_path = fixture
+ .agent_dir
+ .join("prime-inference-private-models.json");
+ let document: Value =
+ serde_json::from_str(&std::fs::read_to_string(&cache_path).expect("cache")).unwrap();
+ std::fs::write(
+ &cache_path,
+ serde_json::to_string(&json!({
+ "fingerprint": document["fingerprint"],
+ "data": document["data"],
+ "refreshedAt": 1u64,
+ }))
+ .unwrap(),
+ )
+ .expect("age the cache");
+ // The catalog chain stays hourly-gated from the create path; only the
+ // private entitlement fetch runs. Its answer is a held gate: the
+ // malformed body is released only after this test starts watching
+ // the cache, so the background refresh's write decision cannot slip
+ // in before the watch begins.
+ let (release, held) = gate();
+ fixture.server.push(held);
+ let requests_before = fixture.server.request_count();
+
+ let served = get_model_catalog(&fixture.worker, "catalog-session").await;
+ assert!(
+ has_model(&served, "internal/team-a-private"),
+ "the cached authorization serves instantly"
+ );
+ // The background entitlement fetch is recorded and parked on the
+ // gate; the deadline is on the request log, not a fixed wait.
+ let deadline = Instant::now() + Duration::from_secs(30);
+ while fixture.server.request_count() < requests_before + 1 {
+ assert!(
+ Instant::now() < deadline,
+ "the stale-cache background refresh never fetched: {:?}",
+ fixture.server.recorded_requests()
+ );
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ let aged_cache = std::fs::read_to_string(&cache_path).expect("cache");
+ // Release the malformed body. The empty-success bug applies the
+ // wipe and rewrites the cache the moment the refresh processes it;
+ // the bounded negative wait is the only way to prove the fixed
+ // path leaves the cache untouched.
+ let _ = release.send(ok_json(r#"{"data": {"not": "an array"}}"#));
+ let settle = Instant::now() + Duration::from_secs(2);
+ loop {
+ let cache = std::fs::read_to_string(&cache_path).expect("cache");
+ assert_eq!(
+ cache, aged_cache,
+ "a malformed entitlement payload must not rewrite the authorization cache"
+ );
+ if Instant::now() >= settle {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ let after = get_model_catalog(&fixture.worker, "catalog-session").await;
+ assert!(
+ has_model(&after, "internal/team-a-private"),
+ "a malformed entitlement payload must not wipe the authorized private models"
+ );
+ }
+
#[tokio::test]
async fn refresh_failure_keeps_the_last_good_catalog_and_stays_silent() {
let mut fixture = fixture(create_phase_answers()).await;
diff --git a/crates/pa-daemon/src/rlm_child_model.rs b/crates/pa-daemon/src/rlm_child_model.rs
index f37258e4fd..4a3ebc8d7c 100644
--- a/crates/pa-daemon/src/rlm_child_model.rs
+++ b/crates/pa-daemon/src/rlm_child_model.rs
@@ -447,15 +447,22 @@ mod tests {
&dir.path().join("models.json"),
&pa_core::models::PrivatePrimeAuthorizationCache {
fingerprint,
- models: vec![serde_json::from_value(json!({
- "id": "internal/glm-5.3-fast", "name": "GLM 5.3 Fast",
- "api": "openai-completions", "provider": "prime-inference",
- "baseUrl": "https://api.pinference.ai/api/v1",
- "reasoning": true, "input": ["text"],
- "cost": { "input": 0.42, "output": 2.1, "cacheRead": 0, "cacheWrite": 0 },
- "contextWindow": 400_000, "maxTokens": 131_072
- }))
- .unwrap()],
+ // The durable wire items (an `/models` payload shape): the
+ // read path parses and builds the model from them.
+ items: vec![json!({
+ "id": "internal/glm-5.3-fast",
+ "display_name": "GLM 5.3 Fast",
+ "pricing": {
+ "input_usd_per_mtok": 0.42, "output_usd_per_mtok": 2.1,
+ "cache_read_usd_per_mtok": 0.0, "cache_write_usd_per_mtok": 0.0,
+ },
+ "specs": {
+ "context_window": 400_000, "max_output_tokens": 131_072,
+ "supports_reasoning": true,
+ "modalities": { "input": ["text"], "output": ["text"] },
+ },
+ })],
+ models: Vec::new(),
refreshed_at: 1,
},
);