Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/jcode-base/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ pub mod protocol;
pub mod provider;
pub mod provider_activity;
pub mod provider_catalog;
pub mod provider_declared_models;
pub mod recent_session_index;
pub mod registry;
pub mod runtime_memory_log;
Expand Down
2 changes: 1 addition & 1 deletion crates/jcode-base/src/provider/catalog_routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1655,7 +1655,7 @@ mod tests {
std::fs::create_dir_all(&cache_dir).expect("create cache dir");
let cache = jcode_provider_openrouter::DiskCache {
cached_at: jcode_provider_openrouter::current_unix_secs().expect("current unix time"),
source_api_base: None,
source_api_base: Some(super::super::STANDARD_OPENROUTER_API_BASE.to_string()),
models: model_ids
.iter()
.map(|id| jcode_provider_openrouter::ModelInfo {
Expand Down
78 changes: 39 additions & 39 deletions crates/jcode-base/src/provider/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,37 +142,26 @@ pub fn stores_reasoning_content_for_context(provider_name: &str) -> bool {
// cached routes immediately while a background refresh updates the catalog.
pub(crate) const OPENAI_COMPATIBLE_PROFILE_CATALOG_SOFT_REFRESH_SECS: u64 = 15 * 60;

fn openai_compatible_profile_catalog_cache_is_stale(cached_at: u64, now: u64) -> bool {
/// Public OpenRouter API base. The `openrouter` cache namespace must have been
/// fetched from this endpoint for its catalog to be trusted as OpenRouter's.
pub(crate) const STANDARD_OPENROUTER_API_BASE: &str = "https://openrouter.ai/api/v1";

/// Whether a cached profile catalog has aged past the soft-refresh window.
///
/// Lives here rather than next to the cache reader so that
/// `provider_declared_models::cached_live_models_for_namespace` and the
/// `provider` tests can both reach it without a circular module dependency.
pub(crate) fn openai_compatible_profile_catalog_cache_is_stale(cached_at: u64, now: u64) -> bool {
now.saturating_sub(cached_at) >= OPENAI_COMPATIBLE_PROFILE_CATALOG_SOFT_REFRESH_SECS
}

pub(crate) fn cached_live_models_for_openai_compatible_profile(
resolved: &crate::provider_catalog::ResolvedOpenAiCompatibleProfile,
) -> Option<(Vec<String>, bool)> {
let cache = jcode_provider_openrouter::load_disk_cache_entry_for_namespace(&resolved.id)?;
let cache_is_stale = jcode_provider_openrouter::current_unix_secs()
.map(|now| openai_compatible_profile_catalog_cache_is_stale(cache.cached_at, now))
.unwrap_or(false);
let source_api_base = cache
.source_api_base
.as_deref()
.and_then(crate::provider_catalog::normalize_api_base)?;
let expected_api_base = crate::provider_catalog::normalize_api_base(&resolved.api_base)?;
if source_api_base != expected_api_base {
return None;
}

let models = cache
.models
.into_iter()
.map(|model| model.id.trim().to_string())
.filter(|model| !model.is_empty())
.collect::<Vec<_>>();
if models.is_empty() {
None
} else {
Some((models, cache_is_stale))
}
crate::provider_declared_models::cached_live_models_for_namespace(
&resolved.id,
&resolved.api_base,
)
}

fn direct_openai_compatible_profile_routes(
Expand All @@ -197,6 +186,22 @@ fn direct_openai_compatible_profile_routes(
(models, false)
};

// Models the user declared in config.toml under
// `[[providers.<name>.models]]` are an explicit statement about what this
// endpoint serves, so they are unioned into the fetched/static list instead
// of being replaced by it. Many gateways serve a model on chat completions
// while omitting it from `GET /models` (issue #1824, MiniMax
// `MiniMax-M3.1-Flash-Preview`), which otherwise makes the model unusable
// from the picker. Declared ids are appended after the fetched list, so
// existing entries and their ordering are untouched.
for model in
crate::provider_declared_models::config_declared_model_ids_for_profile(&resolved.id)
{
if !models.iter().any(|existing| existing == &model) {
models.push(model);
}
}

let provider = resolved.display_name.clone();
let api_method = format!("openai-compatible:{}", resolved.id);
let detail = if from_live_catalog {
Expand Down Expand Up @@ -245,26 +250,21 @@ fn standard_openrouter_profile_configured() -> bool {
}

fn configured_standard_openrouter_profile_routes() -> Vec<ModelRoute> {
let Some(cache) = jcode_provider_openrouter::load_disk_cache_entry_for_namespace("openrouter")
// Same validated read as every other consumer: a cache in the `openrouter`
// namespace that was fetched from a different endpoint is not evidence about
// the public OpenRouter catalog (issue #1824).
let Some((models, _cache_is_stale)) =
crate::provider_declared_models::cached_live_models_for_namespace(
"openrouter",
STANDARD_OPENROUTER_API_BASE,
)
else {
return Vec::new();
};

let source_matches_openrouter = cache
.source_api_base
.as_deref()
.and_then(crate::provider_catalog::normalize_api_base)
.map(|base| base.contains("openrouter.ai"))
.unwrap_or(false);
if !source_matches_openrouter {
return Vec::new();
}

let available = standard_openrouter_profile_configured();
cache
.models
models
.into_iter()
.map(|model| model.id.trim().to_string())
.filter(|model| is_listable_model_name(model))
.map(|model| build_openrouter_auto_route(&model, available, String::new()))
.collect()
Expand Down
26 changes: 18 additions & 8 deletions crates/jcode-base/src/provider/openrouter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
//! - re-exports of the pure catalog/cache types from
//! `jcode-provider-openrouter`.

use super::STANDARD_OPENROUTER_API_BASE as DEFAULT_API_BASE;
use crate::provider_catalog::{
OPENAI_COMPAT_PROFILE, is_safe_env_file_name, is_safe_env_key_name,
load_api_key_from_env_or_config, normalize_api_base, openai_compatible_profiles,
Expand All @@ -27,17 +28,28 @@ pub use jcode_provider_openrouter::{

/// Whether the standard OpenRouter public catalog (disk cache) lists a model.
///
/// Returns `None` when no fresh catalog cache exists (unknown), so callers can
/// Returns `None` when no usable catalog cache exists (unknown), so callers can
/// stay optimistic. Returns `Some(false)` for models OpenRouter definitively
/// does not serve (e.g. `openai/gpt-5.3-codex-spark`, a ChatGPT-subscription
/// exclusive), letting the model picker skip fabricated OpenRouter fallback
/// routes that would 400 with "not a valid model ID" at request time.
///
/// The cache is validated against the endpoint it was fetched from before it is
/// trusted. The `openrouter` namespace is written by the standard OpenRouter
/// refresh, but it is also the default namespace for a direct compatible runtime
/// that never set `JCODE_OPENROUTER_CACHE_NAMESPACE`, so another endpoint's
/// catalog can land there and silently decide the picker (issue #1824). Reading
/// through the shared validated cache reader keeps one validation discipline
/// instead of a second copy: a cache whose `source_api_base` does not match
/// [`DEFAULT_API_BASE`] reads as "unknown" (`None`) rather than as an
/// authoritative "OpenRouter does not serve this model".
pub fn standard_catalog_lists_model(model_id: &str) -> Option<bool> {
let cache = jcode_provider_openrouter::load_disk_cache_entry_for_namespace("openrouter")?;
if cache.models.is_empty() {
return None;
}
Some(cache.models.iter().any(|model| model.id == model_id))
let (models, _cache_is_stale) =
crate::provider_declared_models::cached_live_models_for_namespace(
"openrouter",
DEFAULT_API_BASE,
)?;
Some(models.iter().any(|model| model == model_id))
}

/// Schedule a background catalog refresh for a direct OpenAI-compatible
Expand Down Expand Up @@ -84,8 +96,6 @@ pub fn get_api_key() -> Option<String> {
load_api_key_from_env_or_config(&key_name, &env_file)
}

/// OpenRouter API base URL
const DEFAULT_API_BASE: &str = "https://openrouter.ai/api/v1";
const DEFAULT_API_KEY_NAME: &str = "OPENROUTER_API_KEY";
const DEFAULT_ENV_FILE: &str = "openrouter.env";
const OPENROUTER_TRANSPORT_STATE_ENV: &str = "JCODE_OPENROUTER_TRANSPORT_STATE";
Expand Down
1 change: 1 addition & 0 deletions crates/jcode-base/src/provider/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1141,6 +1141,7 @@ fn new_session_fork_reloads_changed_config_provider_and_model() {
}
include!("tests/auth_refresh.rs");
include!("tests/model_resolution.rs");
include!("tests/model_picker_config_models.rs");
include!("tests/issue_534_profile_preservation.rs");
include!("tests/fallback_failover.rs");
include!("tests/catalog_subscription.rs");
Expand Down
Loading