diff --git a/Cargo.lock b/Cargo.lock index 3fd56d9b..a9698b26 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1997,9 +1997,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.38.2" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" +checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3" dependencies = [ "cc", "pkg-config", @@ -2771,9 +2771,9 @@ dependencies = [ [[package]] name = "rusqlite" -version = "0.40.2" +version = "0.41.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" +checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594" dependencies = [ "bitflags", "fallible-iterator", @@ -3763,7 +3763,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.89.2" +version = "0.90.0" dependencies = [ "serde", "serde_json", @@ -3774,7 +3774,7 @@ dependencies = [ [[package]] name = "tw-bedrock" -version = "0.89.2" +version = "0.90.0" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -3795,7 +3795,7 @@ dependencies = [ [[package]] name = "tw-breaker" -version = "0.89.2" +version = "0.90.0" dependencies = [ "serde", "serde_json", @@ -3803,7 +3803,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.89.2" +version = "0.90.0" dependencies = [ "blake3", "libc", @@ -3829,7 +3829,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.89.2" +version = "0.90.0" dependencies = [ "axum", "base64 0.22.1", @@ -3875,7 +3875,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.89.2" +version = "0.90.0" dependencies = [ "memchr", "serde", @@ -3884,7 +3884,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.89.2" +version = "0.90.0" dependencies = [ "chrono", "serde", @@ -3898,7 +3898,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.89.2" +version = "0.90.0" dependencies = [ "arc-swap", "async-stream", @@ -3950,7 +3950,7 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.89.2" +version = "0.90.0" dependencies = [ "aho-corasick", "base64 0.22.1", @@ -3971,7 +3971,7 @@ dependencies = [ [[package]] name = "tw-handover" -version = "0.89.2" +version = "0.90.0" dependencies = [ "libc", "serde", @@ -3984,7 +3984,7 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.89.2" +version = "0.90.0" dependencies = [ "serde", "serde_json", @@ -3998,7 +3998,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.89.2" +version = "0.90.0" dependencies = [ "tokio", "tracing", @@ -4007,7 +4007,7 @@ dependencies = [ [[package]] name = "tw-pack" -version = "0.89.2" +version = "0.90.0" dependencies = [ "age", "blake3", @@ -4031,7 +4031,7 @@ dependencies = [ [[package]] name = "tw-plugin" -version = "0.89.2" +version = "0.90.0" dependencies = [ "libc", "rand 0.10.2", @@ -4047,7 +4047,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.89.2" +version = "0.90.0" dependencies = [ "arc-swap", "flate2", @@ -4060,14 +4060,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.89.2" +version = "0.90.0" dependencies = [ "thiserror 2.0.20", ] [[package]] name = "tw-store" -version = "0.89.2" +version = "0.90.0" dependencies = [ "blake3", "bytes", @@ -4087,7 +4087,7 @@ dependencies = [ [[package]] name = "tw-sync" -version = "0.89.2" +version = "0.90.0" dependencies = [ "age", "axum", @@ -4115,7 +4115,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.89.2" +version = "0.90.0" dependencies = [ "serde", "serde_json", @@ -4124,7 +4124,7 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.89.2" +version = "0.90.0" dependencies = [ "libc", "notify", @@ -4135,7 +4135,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.89.2" +version = "0.90.0" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -4145,7 +4145,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.89.2" +version = "0.90.0" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index dc8504c0..067b591e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,7 @@ categories = ["network-programming", "web-programming::http-server"] # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.89.2" +version = "0.90.0" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── @@ -104,7 +104,7 @@ serde_yaml_ng = "0.10" # 文件监听,只有 tw-watch 直接用 notify = "8" # 请求历史。bundled 是刻意的:零外部依赖,用户不必装 sqlite -rusqlite = { version = "0.40", features = ["bundled"] } +rusqlite = { version = "0.41", features = ["bundled"] } libc = "0.2" # 问 Windows 要它自己才知道的东西:网卡清单(tw-config 的 nics)、 # 一个 pid 在不在(twcore 的 proc)。**纯 Rust 的绑定**,不编译任何 C —— diff --git a/bin/twcore/Cargo.toml b/bin/twcore/Cargo.toml index 4c5b3f7c..9b633046 100644 --- a/bin/twcore/Cargo.toml +++ b/bin/twcore/Cargo.toml @@ -2,7 +2,8 @@ name = "twcore" version.workspace = true edition.workspace = true -rust-version.workspace = true +# rusqlite 0.41 (patched bundled SQLite) requires Rust 1.89. +rust-version = "1.89" license.workspace = true repository.workspace = true homepage.workspace = true diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index eab7bcfa..5cfa4c6a 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -320,6 +320,8 @@ gw.chatgpt.token_missing gw.chatgpt.token_not_json gw.chatgpt.token_status gw.chatgpt.token_unreachable +gw.codex_catalog.client_version +gw.codex_catalog.too_large gw.config.allow_from gw.config.http_client gw.config.no_upstreams diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index 96ac56d9..446c37e3 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -2,7 +2,8 @@ name = "tw-control" version.workspace = true edition.workspace = true -rust-version.workspace = true +# rusqlite 0.41 (patched bundled SQLite) requires Rust 1.89. +rust-version = "1.89" license.workspace = true repository.workspace = true homepage.workspace = true diff --git a/crates/tw-gateway/src/codex_catalog.rs b/crates/tw-gateway/src/codex_catalog.rs new file mode 100644 index 00000000..364b908e --- /dev/null +++ b/crates/tw-gateway/src/codex_catalog.rs @@ -0,0 +1,536 @@ +//! Codex's native model catalog, projected from the live gateway directory. +//! +//! Only upstream metadata is cached. Names, aliases, permissions and manual +//! capabilities are resolved again on every read, including conditional reads. +//! A version/credential-scoped upstream catalog preserves native instructions +//! and tools; ordinary API model lists use a conservative gateway profile. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use axum::extract::{ConnectInfo, RawQuery, State}; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use futures::{StreamExt, stream}; +use serde_json::{Value, json}; +use tw_config::{Provider, SpecSource}; +use tw_types::msg; + +use crate::error::GatewayError; +use crate::state::{AppState, Runtime}; + +const MAX_BYTES: usize = 1024 * 1024; +const MAX_CACHED: usize = 32; +const FETCH_TIMEOUT: Duration = Duration::from_secs(8); +const CACHE_TTL: Duration = Duration::from_secs(300); +type Models = Arc>; +type Cell = Arc>>; + +struct Cached { + expires: Instant, + models: Models, +} + +pub(crate) struct Cache { + entries: Mutex>, + fetches: tokio::sync::Semaphore, +} + +impl Default for Cache { + fn default() -> Self { + Self { + entries: Mutex::default(), + fetches: tokio::sync::Semaphore::new(4), + } + } +} + +impl Cache { + fn cell(&self, key: String) -> Cell { + let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); + if !entries.contains_key(&key) && entries.len() >= MAX_CACHED { + let oldest = entries + .iter() + .min_by_key(|(_, (used, _))| *used) + .map(|(k, _)| k.clone()); + if let Some(oldest) = oldest { + entries.remove(&oldest); + } + } + let (used, cell) = entries + .entry(key) + .or_insert_with(|| (Instant::now(), Default::default())); + *used = Instant::now(); + cell.clone() + } + + async fn get( + &self, + state: &AppState, + rt: &Runtime, + provider: &Provider, + version: &str, + ) -> Models { + let empty = || Arc::new(BTreeMap::new()); + let http = rt.clients.get(&provider.name).unwrap_or(&state.http); + let Ok(headers) = state.headers_for(provider, http).await else { + return empty(); + }; + let url = upstream_url(provider, version); + // Resolved credentials, not environment-variable spellings, partition + // access-dependent catalogs. No raw credential is retained in the key. + let identity = serde_json::to_vec(&( + &provider.name, + &url, + &headers, + crate::outbound::proxy_shape(&rt.config, provider), + )) + .expect("catalog identity is JSON"); + let cell = self.cell(blake3::hash(&identity).to_hex().to_string()); + let mut cached = cell.lock().await; + if let Some(entry) = cached.as_ref().filter(|c| c.expires > Instant::now()) { + return entry.models.clone(); + } + let Ok(_permit) = self.fetches.acquire().await else { + return empty(); + }; + let (models, ttl) = fetch(http, &url, &headers) + .await + .unwrap_or_else(|| (empty(), Duration::from_secs(30))); + *cached = (!ttl.is_zero()).then(|| Cached { + expires: Instant::now() + ttl, + models: models.clone(), + }); + models + } +} + +fn upstream_url(provider: &Provider, version: &str) -> String { + let query = format!("client_version={version}"); + if provider.effective_protocol() == Some(tw_config::Protocol::Chatgpt) { + return crate::forward::upstream_url(&provider.base_url, "/models", Some(&query)); + } + // OpenAI documents its native Codex catalog separately from its public + // models API. Only the actual official origin uses this credential target. + let official = reqwest::Url::parse(&provider.base_url).is_ok_and(|u| { + u.scheme() == "https" + && u.host_str() == Some("api.openai.com") + && u.port_or_known_default() == Some(443) + && matches!(u.path().trim_end_matches('/'), "" | "/v1") + }); + if official { + return crate::forward::upstream_url(crate::chatgpt::BASE_URL, "/models", Some(&query)); + } + crate::forward::upstream_url(&provider.base_url, "/v1/models", Some(&query)) +} + +async fn fetch( + http: &reqwest::Client, + url: &str, + headers: &[(String, String)], +) -> Option<(Models, Duration)> { + let mut response = crate::forward::apply_headers(http.get(url).timeout(FETCH_TIMEOUT), headers) + .send() + .await + .ok()?; + if !response.status().is_success() + || response + .content_length() + .is_some_and(|n| n > MAX_BYTES as u64) + { + return None; + } + let ttl = cache_ttl(response.headers()); + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.ok()? { + if body.len() + chunk.len() > MAX_BYTES { + return None; + } + body.extend_from_slice(&chunk); + } + let value: Value = serde_json::from_slice(&body).ok()?; + let mut models = BTreeMap::new(); + for model in value.get("models")?.as_array()? { + // A list of IDs is not a native Codex definition. Unknown fields in a + // valid definition survive unchanged, including version-specific tools. + if native(model) { + models + .entry(model["slug"].as_str()?.to_string()) + .or_insert_with(|| model.clone()); + } + } + Some((Arc::new(models), ttl)) +} + +fn cache_ttl(headers: &HeaderMap) -> Duration { + let mut ttl = CACHE_TTL; + for value in headers.get_all(header::CACHE_CONTROL) { + for directive in value.to_str().unwrap_or_default().split(',').map(str::trim) { + if directive.eq_ignore_ascii_case("no-store") + || directive.eq_ignore_ascii_case("no-cache") + { + return Duration::ZERO; + } + if let Some((key, value)) = directive.split_once('=') + && key.eq_ignore_ascii_case("max-age") + && let Ok(seconds) = value.trim().trim_matches('"').parse::() + { + ttl = ttl.min(Duration::from_secs(seconds)); + } + } + } + let age = headers + .get(header::AGE) + .and_then(|v| v.to_str().ok()?.parse::().ok()) + .unwrap_or_default(); + ttl.saturating_sub(Duration::from_secs(age)) +} + +fn native(model: &Value) -> bool { + model["slug"].as_str().is_some_and(|s| !s.trim().is_empty()) + && model["display_name"].is_string() + && model["supported_reasoning_levels"].is_array() + && model["shell_type"].is_string() + && model["truncation_policy"].is_object() + && (model["base_instructions"].is_string() || model["model_messages"].is_object()) +} + +fn version(query: Option<&str>) -> Result { + let values: Vec<_> = + reqwest::Url::parse(&format!("http://catalog/?{}", query.unwrap_or_default())) + .expect("a query appended to a fixed URL is valid") + .query_pairs() + .filter(|(key, _)| key == "client_version") + .map(|(_, v)| v.into_owned()) + .collect(); + if let [value] = values.as_slice() + && value.len() <= 32 + && value.split('.').count() == 3 + && value + .split('.') + .all(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) + { + return Ok(value.clone()); + } + Err(GatewayError::request( + msg!("gw.codex_catalog.client_version" => "The Codex catalog requires one client_version in major.minor.patch form."), + )) +} + +fn authorize( + state: &AppState, + peer: std::net::SocketAddr, + headers: &HeaderMap, + query: Option<&str>, +) -> Result<(Arc, Option>), GatewayError> { + loop { + let rt = state.runtime(); + let identity = state.identify(headers, query); + // identify reads the runtime itself. Retry if a reload separated that + // authentication from the source/permission snapshot used here. + if !Arc::ptr_eq(&rt, &state.runtime()) { + continue; + } + if !rt.allow.allows(peer.ip()) { + return Err(GatewayError::auth( + msg!("gw.auth.source_not_allowed", peer = peer.ip() => "{peer} is not among the allowed source addresses."), + )); + } + let (client, _) = identity?; + let allow = crate::models::key_allow(&rt.config, &client).map(<[_]>::to_vec); + return Ok((rt, allow)); + } +} + +fn candidates<'a>( + rt: &'a Runtime, + catalog: &'a tw_engine::Catalog, + name: &'a str, +) -> Vec<(&'a Provider, &'a str)> { + let available: Vec<_> = if catalog.alias(name).is_some() { + catalog + .served(name) + .iter() + .map(|(p, model)| (p.as_str(), model.as_str())) + .collect() + } else { + catalog + .providers_for(name) + .iter() + .map(|p| (p.as_str(), name)) + .collect() + }; + available + .into_iter() + .filter_map(|(p, model)| { + rt.config + .providers + .iter() + .find(|v| v.name == p && !v.disabled) + .map(|p| (p, model)) + }) + .collect() +} + +fn names(catalog: &tw_engine::Catalog, allow: Option<&[String]>) -> Vec { + catalog.resolve_allowed( + Some(&crate::client_api::slugs( + crate::client_api::ClientApi::OpenaiResponses.servable_by(true), + )), + allow, + ) +} + +pub(crate) async fn list( + State(state): State, + ConnectInfo(peer): ConnectInfo, + RawQuery(query): RawQuery, + headers: HeaderMap, +) -> Result { + let (mut rt, mut allow) = authorize(&state, peer, &headers, query.as_deref())?; + let version = version(query.as_deref())?; + let catalog = state.catalog.load_full(); + let listed = names(&catalog, allow.as_deref()); + let mut providers = BTreeMap::new(); + for name in &listed { + for (provider, _) in candidates(&rt, &catalog, name) { + if matches!( + provider.effective_protocol(), + Some( + tw_config::Protocol::OpenaiChat + | tw_config::Protocol::OpenaiResponses + | tw_config::Protocol::Chatgpt + ) + ) { + providers.insert(provider.name.clone(), provider.clone()); + } + } + } + let mut upstreams = HashMap::new(); + { + let requests: Vec<_> = providers + .into_values() + .map(|p| { + let state = state.clone(); + let rt = rt.clone(); + let version = version.clone(); + async move { + ( + p.name.clone(), + state.codex_catalogs.get(&state, &rt, &p, &version).await, + ) + } + }) + .collect(); + let mut requests = stream::iter(requests).buffer_unordered(4); + let deadline = tokio::time::Instant::now() + FETCH_TIMEOUT; + while let Ok(Some((provider, models))) = + tokio::time::timeout_at(deadline, requests.next()).await + { + upstreams.insert(provider, models); + } + } + // A permission/credential change during a slow metadata fetch must not + // return the old account's catalog, even as a 304. The next read can fetch + // fresh native metadata; this read uses the new runtime's generic profile. + let (current, current_allow) = authorize(&state, peer, &headers, query.as_deref())?; + if !Arc::ptr_eq(&rt, ¤t) { + upstreams.clear(); + } + rt = current; + allow = current_allow; + let catalog = state.catalog.load(); + let book = state.pricing.load(); + let models: Vec<_> = names(&catalog, allow.as_deref()) + .iter() + .map(|name| project(name, &candidates(&rt, &catalog, name), &book, &upstreams)) + .collect(); + let body = serde_json::to_vec(&json!({"models":models})).expect("catalog is JSON"); + if body.len() > MAX_BYTES { + return Err(GatewayError::too_large( + msg!("gw.codex_catalog.too_large" => "The Codex catalog exceeds 1 MiB. Reduce the models available to this gateway key."), + )); + } + let etag = format!("\"{}\"", blake3::hash(&body).to_hex()); + let unchanged = headers + .get_all(header::IF_NONE_MATCH) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(',')) + .map(str::trim) + .any(|v| v == "*" || v.strip_prefix("W/").unwrap_or(v) == etag); + let mut response = if unchanged { + StatusCode::NOT_MODIFIED.into_response() + } else { + ([(header::CONTENT_TYPE, "application/json")], body).into_response() + }; + response.headers_mut().insert( + header::ETAG, + HeaderValue::from_str(&etag).expect("hash is a header value"), + ); + response.headers_mut().insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, max-age=30, must-revalidate"), + ); + response.headers_mut().insert( + header::VARY, + HeaderValue::from_static("Authorization, X-API-Key, X-Goog-API-Key"), + ); + Ok(response) +} + +fn generic(name: &str) -> Value { + json!({ + "slug":name,"display_name":name,"description":"Available through ThinkWatch", + "base_instructions":"You are a coding assistant. Follow the user's instructions, inspect relevant files before editing, use the provided tools when needed, and report changes and verification clearly.", + "supported_reasoning_levels":[],"shell_type":"shell_command","visibility":"list", + "supported_in_api":true,"priority":0,"support_verbosity":false, + "truncation_policy":{"mode":"tokens","limit":10000}, + "experimental_supported_tools":[],"upgrade":null,"input_modalities":["text"], + "supports_search_tool":false,"node_repl_disabled":true, + "service_tiers":[],"additional_speed_tiers":[],"default_service_tier":null + }) +} + +fn pick(spec: Option>, native: Option) -> Option { + match spec { + Some(s) if s.source == SpecSource::Manual => Some(s.value), + _ => native.or(spec.map(|s| s.value)), + } +} + +fn project( + name: &str, + candidates: &[(&Provider, &str)], + book: &tw_pricing::PriceBook, + upstreams: &HashMap, +) -> Value { + let definitions: Vec<_> = candidates + .iter() + .map(|(p, model)| upstreams.get(&p.name).and_then(|models| models.get(*model))) + .collect(); + let native = definitions + .first() + .copied() + .flatten() + .filter(|first| definitions.iter().all(|v| v.is_some_and(|v| v == *first))); + let mut out = native.cloned().unwrap_or_else(|| generic(name)); + let mut contexts = Vec::new(); + let mut max_contexts = Vec::new(); + let mut reasoning = Vec::new(); + let mut images = Vec::new(); + for ((p, model), definition) in candidates.iter().zip(&definitions) { + let spec = p.model_spec(book, model); + contexts.push(pick( + spec.context_window, + definition.and_then(|d| d["context_window"].as_u64()), + )); + max_contexts.push(pick( + spec.context_window, + definition.and_then(|d| { + d["max_context_window"] + .as_u64() + .or_else(|| d["context_window"].as_u64()) + }), + )); + reasoning.push(pick( + spec.reasoning, + definition.map(|d| { + d["supported_reasoning_levels"] + .as_array() + .is_some_and(|v| !v.is_empty()) + }), + )); + images.push(pick( + spec.image_input, + definition + .and_then(|d| d["input_modalities"].as_array()) + .map(|v| v.iter().any(|v| v == "image")), + )); + } + let context = (!contexts.is_empty() && contexts.iter().all(Option::is_some)) + .then(|| contexts.iter().flatten().copied().min()) + .flatten(); + if let Some(context) = context { + out["context_window"] = json!(context); + out["max_context_window"] = json!( + max_contexts + .iter() + .flatten() + .copied() + .min() + .unwrap_or(context) + ); + } else if let Some(object) = out.as_object_mut() { + object.remove("context_window"); + object.remove("max_context_window"); + } + if reasoning.contains(&Some(false)) { + out["supported_reasoning_levels"] = json!([]); + out["default_reasoning_level"] = Value::Null; + } + if !images.is_empty() && images.iter().all(|v| *v == Some(true)) { + out["input_modalities"] = json!(["text", "image"]); + } else { + out["input_modalities"] = json!(["text"]); + out["supports_image_detail_original"] = json!(false); + } + if out["slug"] != name { + out["display_name"] = json!(name); + } + out["slug"] = json!(name); + out["supported_in_api"] = json!(true); + out["visibility"] = json!("list"); + out["upgrade"] = Value::Null; + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn catalog_cache_honors_upstream_controls_and_validates_the_client_version() { + let mut headers = HeaderMap::new(); + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, max-age=17"), + ); + assert_eq!(cache_ttl(&headers), Duration::from_secs(17)); + headers.insert(header::AGE, HeaderValue::from_static("10")); + assert_eq!(cache_ttl(&headers), Duration::from_secs(7)); + headers.append(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + assert_eq!(cache_ttl(&headers), Duration::ZERO); + assert_eq!(version(Some("client_version=0.166.0")).unwrap(), "0.166.0"); + for query in [ + "", + "client_version=invalid", + "client_version=1.2.3&client_version=1.2.4", + ] { + assert!(version(Some(query)).is_err()); + } + } + + #[test] + fn upstream_urls_select_native_openai_defaults_only_for_the_official_origin() { + let mut provider = Provider { + name: "test".into(), + base_url: "https://api.openai.com/v1/".into(), + protocol: Some(tw_config::Protocol::OpenaiResponses), + ..Default::default() + }; + assert_eq!( + upstream_url(&provider, "0.166.0"), + "https://chatgpt.com/backend-api/codex/models?client_version=0.166.0" + ); + provider.base_url = "https://relay.example/api.openai.com/v1".into(); + assert!(upstream_url(&provider, "0.166.0").starts_with("https://relay.example/")); + provider.base_url = "http://127.0.0.1:1234/codex".into(); + provider.protocol = Some(tw_config::Protocol::Chatgpt); + assert_eq!( + upstream_url(&provider, "0.166.0"), + "http://127.0.0.1:1234/codex/models?client_version=0.166.0" + ); + } +} diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 83150e6c..394c1bdc 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -18,6 +18,7 @@ pub mod cache_marks; pub mod chatgpt; pub mod client_api; pub mod clientprobe; +mod codex_catalog; pub mod content; pub mod count; pub mod effort_memory; diff --git a/crates/tw-gateway/src/oauth.rs b/crates/tw-gateway/src/oauth.rs index 623f4a0b..73ec8f67 100644 --- a/crates/tw-gateway/src/oauth.rs +++ b/crates/tw-gateway/src/oauth.rs @@ -762,6 +762,12 @@ async fn exchange(cfg: &OAuth, refresh: &str, http: &reqwest::Client) -> Result< mod tests { use super::*; + fn direct_client() -> reqwest::Client { + // These tests require a direct loopback connection refusal, regardless + // of the developer machine's native system proxy settings. + reqwest::Client::builder().no_proxy().build().unwrap() + } + fn cfg(endpoint: &str) -> OAuth { OAuth { access: None, @@ -780,7 +786,7 @@ mod tests { let c = Cache::new(); let mut o = cfg("http://127.0.0.1:1/nope"); o.access = Some("a-existing".into()); - let http = reqwest::Client::new(); + let http = direct_client(); let got = tokio::runtime::Runtime::new() .unwrap() .block_on(c.token("p", &o, &http)) @@ -792,7 +798,7 @@ mod tests { #[test] fn a_configured_access_token_is_used_until_its_lead_time_then_renewed() { let rt = tokio::runtime::Runtime::new().unwrap(); - let http = reqwest::Client::new(); + let http = direct_client(); let at = |secs: i64| { (chrono::Utc::now() + chrono::Duration::seconds(secs)) .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) @@ -863,7 +869,7 @@ mod tests { // **没有退避,一个坏掉的 token 端点会被每个请求敲一次。** let c = Cache::new(); let o = cfg("http://127.0.0.1:1/nope"); - let http = reqwest::Client::new(); + let http = direct_client(); let rt = tokio::runtime::Runtime::new().unwrap(); let first = rt.block_on(c.token("p", &o, &http)).unwrap_err(); assert!(matches!(first, OauthError::Http { .. }), "{first}"); diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index d9b605ad..996964ee 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -29,6 +29,7 @@ pub fn router(state: AppState) -> Router { .route("/api/hello", get(|| async {})) // **和准入共用同一个函数** —— 列表和准入不可能不一致。 .route("/v1/models", get(list_models)) + .route("/codex/models", get(crate::codex_catalog::list)) // **单点查询要走同一道准入**。不接这条的话它掉进 // fallback 直接透传上游 —— 一个被 `allow` 限制成只能用便宜 // 模型的 client,`GET /v1/models/claude-opus-4` 照样拿 200。 diff --git a/crates/tw-gateway/src/state.rs b/crates/tw-gateway/src/state.rs index bf8a4690..dd0f8de4 100644 --- a/crates/tw-gateway/src/state.rs +++ b/crates/tw-gateway/src/state.rs @@ -200,6 +200,8 @@ pub struct AppState { pub catalog: Arc>, /// 每个上游的模型清单,以及是什么时候、怎么来的。**跨重载存活** pub models: Arc, + /// Native Codex metadata only; live names and permissions are never cached. + pub(crate) codex_catalogs: Arc, /// 请求体和响应体往哪儿交。 /// /// **有界通道,满了就丢。**直接调用意味着文件 I/O 跑在转发那条路上 @@ -361,6 +363,7 @@ impl AppState { health, catalog: Arc::new(arc_swap::ArcSwap::from_pointee(Default::default())), models, + codex_catalogs: Default::default(), body_sink: Arc::new(std::sync::Mutex::new(None)), quotas: Arc::new(std::sync::Mutex::new(Default::default())), glm: Default::default(), diff --git a/crates/tw-gateway/tests/codex_catalog.rs b/crates/tw-gateway/tests/codex_catalog.rs new file mode 100644 index 00000000..f2ab0673 --- /dev/null +++ b/crates/tw-gateway/tests/codex_catalog.rs @@ -0,0 +1,461 @@ +//! Native discovery and its cache must follow the live gateway directory. + +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::extract::{OriginalUri, State}; +use axum::http::HeaderMap; +use axum::routing::get; +use axum::{Json, Router}; +use serde_json::{Value, json}; +use tw_config::{Client, Config, ModelSpec, Protocol, Provider}; +use tw_gateway::AppState; + +#[derive(Clone)] +struct Upstream { + body: Arc>, + requests: Arc>>, + control: &'static str, + gate: Option>, + started: Arc, +} + +impl Upstream { + fn new(body: Value) -> Self { + Self { + body: Arc::new(Mutex::new(body)), + requests: Default::default(), + control: "private, max-age=300", + gate: None, + started: Default::default(), + } + } + + async fn serve(&self) -> SocketAddr { + async fn models( + State(up): State, + OriginalUri(uri): OriginalUri, + headers: HeaderMap, + ) -> impl axum::response::IntoResponse { + up.requests.lock().unwrap().push(( + uri.to_string(), + headers + .get("authorization") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .into(), + )); + up.started.notify_one(); + if let Some(gate) = &up.gate { + gate.notified().await; + } + ( + [("cache-control", up.control)], + Json(up.body.lock().unwrap().clone()), + ) + } + let app = Router::new() + .route("/v1/models", get(models)) + .route("/models", get(models)) + .with_state(self.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + addr + } +} + +fn native(slug: &str) -> Value { + json!({ + "slug":slug,"display_name":"Native model","base_instructions":"Native coding instructions", + "supported_reasoning_levels":[{"effort":"high","description":"More reasoning"}], + "default_reasoning_level":"high","shell_type":"shell_command","visibility":"list", + "supported_in_api":true,"priority":0,"support_verbosity":false, + "truncation_policy":{"mode":"tokens","limit":10000}, + "experimental_supported_tools":["native_tool"],"upgrade":null, + "context_window":128000,"max_context_window":256000,"input_modalities":["text","image"], + "future_tool_setting":{"enabled":true} + }) +} + +fn provider(name: &str, addr: SocketAddr, models: &[&str]) -> Provider { + Provider { + name: name.into(), + base_url: format!("http://{addr}/v1"), + protocol: Some(Protocol::OpenaiResponses), + key: Some("upstream-test-key".into()), + models: models.iter().map(|s| (*s).into()).collect(), + ..Default::default() + } +} + +fn config(providers: Vec) -> Config { + Config { + providers, + clients: vec![Client { + name: "codex".into(), + key: "gateway-test-key".into(), + ..Default::default() + }], + ..Default::default() + } +} + +fn http() -> reqwest::Client { + reqwest::Client::builder().no_proxy().build().unwrap() +} + +async fn serve(config: Config) -> (AppState, SocketAddr) { + let state = AppState::new(config).unwrap(); + let addr = tw_gateway::serve(state.clone(), ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + (state, addr) +} + +fn request(addr: SocketAddr) -> reqwest::RequestBuilder { + http() + .get(format!("http://{addr}/codex/models?client_version=0.166.0")) + .bearer_auth("gateway-test-key") +} + +async fn catalog(addr: SocketAddr) -> Value { + request(addr) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap() +} + +fn slugs(body: &Value) -> Vec<&str> { + body["models"] + .as_array() + .unwrap() + .iter() + .map(|m| m["slug"].as_str().unwrap()) + .collect() +} + +#[tokio::test] +async fn native_metadata_is_version_scoped_and_uses_only_provider_credentials() { + let up = Upstream::new(json!({"models":[native("private-model")]})); + let addr = up.serve().await; + let mut cfg = config(vec![provider("native", addr, &["private-model"])]); + cfg.aliases = serde_yaml_ng::from_str("coding: private-model").unwrap(); + let (_, gw) = serve(cfg).await; + let body = catalog(gw).await; + assert_eq!(slugs(&body), ["coding", "private-model"]); + for m in body["models"].as_array().unwrap() { + assert_eq!(m["base_instructions"], "Native coding instructions"); + assert_eq!(m["experimental_supported_tools"], json!(["native_tool"])); + assert_eq!(m["future_tool_setting"]["enabled"], true); + assert_eq!(m["supported_reasoning_levels"][0]["effort"], "high"); + assert_eq!(m["input_modalities"], json!(["text", "image"])); + assert_eq!(m["context_window"], 128000); + assert_eq!(m["max_context_window"], 256000); + assert!(m["upgrade"].is_null()); + } + assert_eq!(body["models"][0]["display_name"], "coding"); + catalog(gw).await; + assert_eq!( + up.requests.lock().unwrap().len(), + 1, + "native metadata should be cached" + ); + let response = http() + .get(format!("http://{gw}/codex/models?client_version=0.165.0")) + .bearer_auth("gateway-test-key") + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let requests = up.requests.lock().unwrap(); + assert_eq!(requests.len(), 2); + assert_eq!( + requests[0], + ( + "/v1/models?client_version=0.166.0".into(), + "Bearer upstream-test-key".into() + ) + ); + assert!(requests[1].0.contains("0.165.0")); +} + +#[tokio::test] +async fn chatgpt_metadata_uses_the_actual_codex_version_instead_of_the_inventory_version() { + let up = Upstream::new(json!({"models":[native("one")]})); + let addr = up.serve().await; + let mut p = provider("account", addr, &["one"]); + p.base_url = format!("http://{addr}"); + p.protocol = Some(Protocol::Chatgpt); + let (_, gw) = serve(config(vec![p])).await; + assert_eq!( + catalog(gw).await["models"][0]["base_instructions"], + "Native coding instructions" + ); + assert_eq!( + up.requests.lock().unwrap()[0].0, + "/models?client_version=0.166.0" + ); +} + +#[tokio::test] +async fn ordinary_model_lists_get_a_generic_profile_and_standard_listing_is_unchanged() { + let up = Upstream::new(json!({"data":[{"id":"unknown-model"}]})); + let (_, gw) = serve(config(vec![provider( + "ordinary", + up.serve().await, + &["unknown-model"], + )])) + .await; + let body = catalog(gw).await; + let model = &body["models"][0]; + assert_eq!(model["slug"], "unknown-model"); + assert!(model["base_instructions"].is_string()); + assert!(model.get("context_window").is_none()); + assert_eq!(model["supported_reasoning_levels"], json!([])); + assert_eq!(model["input_modalities"], json!(["text"])); + let standard: Value = http() + .get(format!("http://{gw}/v1/models")) + .bearer_auth("gateway-test-key") + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(standard["data"][0]["id"], "unknown-model"); + assert!(standard.get("models").is_none()); +} + +#[tokio::test] +async fn live_reload_changes_names_aliases_permissions_and_specs_before_conditional_reads() { + let up = Upstream::new(json!({"models":[native("one"),native("two")]})); + let mut cfg = config(vec![provider("native", up.serve().await, &["one", "two"])]); + cfg.clients[0].allow = Some(vec!["one".into()]); + let (state, gw) = serve(cfg.clone()).await; + let first = request(gw).send().await.unwrap(); + let etag = first.headers()["etag"].clone(); + assert_eq!(slugs(&first.json::().await.unwrap()), ["one"]); + let unchanged = request(gw) + .header("if-none-match", etag.clone()) + .send() + .await + .unwrap(); + assert_eq!(unchanged.status(), 304); + assert!(unchanged.bytes().await.unwrap().is_empty()); + + cfg.providers[0].models.push("new".into()); + cfg.aliases = serde_yaml_ng::from_str("coding: two").unwrap(); + cfg.clients[0].allow = Some(vec!["coding".into(), "new".into()]); + cfg.providers[0].model_specs.insert( + "two".into(), + ModelSpec { + context_window: Some(64000), + reasoning: Some(false), + image_input: Some(false), + ..Default::default() + }, + ); + state.reload(cfg.clone()).unwrap(); + let changed = request(gw) + .header("if-none-match", etag.clone()) + .send() + .await + .unwrap(); + assert_eq!(changed.status(), 200); + let body: Value = changed.json().await.unwrap(); + assert_eq!(slugs(&body), ["coding", "new"]); + assert_eq!(body["models"][0]["context_window"], 64000); + assert_eq!(body["models"][0]["supported_reasoning_levels"], json!([])); + assert_eq!(body["models"][0]["input_modalities"], json!(["text"])); + assert_eq!( + up.requests.lock().unwrap().len(), + 1, + "reload must reapply policy over cached native metadata" + ); + cfg.clients[0].disabled = true; + state.reload(cfg).unwrap(); + assert_eq!( + request(gw) + .header("if-none-match", etag) + .send() + .await + .unwrap() + .status(), + 401 + ); +} + +#[tokio::test] +async fn provider_credential_changes_partition_native_metadata() { + let up = Upstream::new(json!({"models":[native("one")]})); + let mut cfg = config(vec![provider("native", up.serve().await, &["one"])]); + let (state, gw) = serve(cfg.clone()).await; + catalog(gw).await; + up.body.lock().unwrap()["models"][0]["base_instructions"] = json!("New account instructions"); + cfg.providers[0].key = Some("new-account-key".into()); + state.reload(cfg).unwrap(); + assert_eq!( + catalog(gw).await["models"][0]["base_instructions"], + "New account instructions" + ); + assert_eq!(up.requests.lock().unwrap()[1].1, "Bearer new-account-key"); +} + +#[tokio::test] +async fn no_store_and_concurrent_reads_obey_upstream_cache_controls() { + let mut up = Upstream::new(json!({"models":[native("one")]})); + up.control = "no-store"; + let (_, gw) = serve(config(vec![provider("native", up.serve().await, &["one"])])).await; + catalog(gw).await; + up.body.lock().unwrap()["models"][0]["base_instructions"] = json!("Fresh instructions"); + assert_eq!( + catalog(gw).await["models"][0]["base_instructions"], + "Fresh instructions" + ); + assert_eq!(up.requests.lock().unwrap().len(), 2); + + let up = Upstream::new(json!({"models":[native("one")]})); + let (_, gw) = serve(config(vec![provider("native", up.serve().await, &["one"])])).await; + let (a, b, c) = tokio::join!(catalog(gw), catalog(gw), catalog(gw)); + assert_eq!(a, b); + assert_eq!(b, c); + assert_eq!(up.requests.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn aliases_intersect_capabilities_across_all_candidates() { + let one = Upstream::new(json!({"models":[native("one")]})); + let two = Upstream::new(json!({"models":[native("two")]})); + let mut cfg = config(vec![ + provider("first", one.serve().await, &["one"]), + provider("second", two.serve().await, &["two"]), + ]); + cfg.aliases = serde_yaml_ng::from_str("coding: [one, two]").unwrap(); + cfg.providers[1].model_specs.insert( + "two".into(), + ModelSpec { + context_window: Some(32000), + image_input: Some(false), + reasoning: Some(false), + ..Default::default() + }, + ); + let (_, gw) = serve(cfg).await; + let body = catalog(gw).await; + let alias = &body["models"][0]; + assert_eq!(alias["slug"], "coding"); + assert_eq!(alias["context_window"], 32000); + assert_eq!(alias["supported_reasoning_levels"], json!([])); + assert_eq!(alias["input_modalities"], json!(["text"])); +} + +#[tokio::test] +async fn metadata_fetch_cannot_resurrect_permissions_or_an_old_account_during_reload() { + let mut up = Upstream::new(json!({"models":[native("one")]})); + let gate = Arc::new(tokio::sync::Notify::new()); + up.gate = Some(gate.clone()); + let mut cfg = config(vec![provider("native", up.serve().await, &["one"])]); + let (state, gw) = serve(cfg.clone()).await; + let pending = tokio::spawn(async move { catalog(gw).await }); + tokio::time::timeout(Duration::from_secs(3), up.started.notified()) + .await + .unwrap(); + cfg.providers[0].key = Some("different-account".into()); + cfg.providers[0].models = vec!["new".into()]; + cfg.clients[0].allow = Some(vec!["new".into()]); + state.reload(cfg).unwrap(); + gate.notify_one(); + let body = pending.await.unwrap(); + assert_eq!(slugs(&body), ["new"]); + assert_ne!( + body["models"][0]["base_instructions"], + "Native coding instructions" + ); +} + +#[tokio::test] +async fn invalid_versions_and_unauthorized_reads_never_reach_upstream() { + let up = Upstream::new(json!({"models":[native("one")]})); + let (_, gw) = serve(config(vec![provider("native", up.serve().await, &["one"])])).await; + for query in [ + "", + "client_version=nope", + "client_version=1.2.3&client_version=1.2.4", + ] { + let response = http() + .get(format!("http://{gw}/codex/models?{query}")) + .bearer_auth("gateway-test-key") + .send() + .await + .unwrap(); + assert_eq!(response.status(), 400); + } + assert_eq!( + http() + .get(format!("http://{gw}/codex/models?client_version=0.166.0")) + .header("if-none-match", "*") + .send() + .await + .unwrap() + .status(), + 401 + ); + assert!(up.requests.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn oversized_or_non_native_upstream_metadata_falls_back_to_a_bounded_profile() { + let mut model = native("one"); + model["base_instructions"] = json!("x".repeat(1024 * 1024)); + let up = Upstream::new(json!({"models":[model]})); + let (_, gw) = serve(config(vec![provider("native", up.serve().await, &["one"])])).await; + let body = catalog(gw).await; + assert!( + body["models"][0]["base_instructions"] + .as_str() + .unwrap() + .len() + < 1000 + ); + assert!(body["models"][0].get("context_window").is_none()); +} + +#[tokio::test] +async fn source_restrictions_apply_to_native_discovery() { + use tower::ServiceExt; + let state = AppState::new(config(vec![])).unwrap(); + let response = tw_gateway::server::router(state) + .oneshot( + axum::http::Request::builder() + .uri("/codex/models?client_version=0.166.0") + .header("authorization", "Bearer gateway-test-key") + .extension(axum::extract::ConnectInfo( + "203.0.113.10:12345".parse::().unwrap(), + )) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), 401); +} + +#[tokio::test] +async fn oversized_projected_catalog_is_rejected_instead_of_truncated() { + let mut p = Provider { + name: "local".into(), + base_url: "http://127.0.0.1:1".into(), + protocol: Some(Protocol::Anthropic), + ..Default::default() + }; + p.models = (0..2000).map(|i| format!("local-model-{i}")).collect(); + let (_, gw) = serve(config(vec![p])).await; + assert_eq!(request(gw).send().await.unwrap().status(), 413); +} diff --git a/crates/tw-gateway/tests/hotreload.rs b/crates/tw-gateway/tests/hotreload.rs index 4be11625..a31ff349 100644 --- a/crates/tw-gateway/tests/hotreload.rs +++ b/crates/tw-gateway/tests/hotreload.rs @@ -518,7 +518,12 @@ async fn changing_the_port_actually_moves_the_listener() { assert_eq!(primary(&state), Some(p1)); let at = |port: u16| async move { - reqwest::Client::new() + // A closed listener must cause a direct connection refusal, rather + // than an HTTP error generated by the machine's system proxy. + reqwest::Client::builder() + .no_proxy() + .build() + .unwrap() .post(format!("http://127.0.0.1:{port}/v1/messages")) .header("x-api-key", "tw-k") .timeout(Duration::from_secs(2)) diff --git a/crates/tw-store/Cargo.toml b/crates/tw-store/Cargo.toml index ec40258c..f8fbdc40 100644 --- a/crates/tw-store/Cargo.toml +++ b/crates/tw-store/Cargo.toml @@ -2,7 +2,8 @@ name = "tw-store" version.workspace = true edition.workspace = true -rust-version.workspace = true +# rusqlite 0.41 (patched bundled SQLite) requires Rust 1.89. +rust-version = "1.89" license.workspace = true repository.workspace = true homepage.workspace = true diff --git a/docs/codex-model-catalog.md b/docs/codex-model-catalog.md new file mode 100644 index 00000000..4aad2c62 --- /dev/null +++ b/docs/codex-model-catalog.md @@ -0,0 +1,90 @@ +# Codex remote model discovery + +[中文](codex-model-catalog.zh-CN.md) + +Core serves a native Codex catalog at +`GET /codex/models?client_version=`. It uses the same gateway +keys, allowed source addresses, model directory, aliases and key `allow` rules +as inference. The standard `/v1/models` endpoint keeps its OpenAI response shape. + +ThinkWatch Lite configures this connection when adopting Codex. For a manual +connection, use a provider like this in Codex's `config.toml`: + +```toml +model_provider = "thinkwatch" + +[features] +api_key_model_discovery = true + +[model_providers.thinkwatch] +name = "ThinkWatch" +base_url = "http://127.0.0.1:8788/v1" +model_catalog_url = "http://127.0.0.1:8788/codex/models" +wire_api = "responses" +env_key = "THINKWATCH_GATEWAY_KEY" +requires_openai_auth = false +supports_websockets = false +``` + +Use your gateway's actual address and set `THINKWATCH_GATEWAY_KEY` to an enabled +gateway key. Remove any effective `model_catalog_json` setting: that local file +takes precedence over the remote catalog. A selected profile can also override +the provider, local catalog or discovery feature. Lite handles the selected +default profile and restores its original fields when disconnected. Explicitly +selecting a different profile or passing command-line overrides can still change +which provider Codex uses. + +The connection is configured once. After that, changes to upstream models, +aliases, enabled ranges, manual model capabilities or key permissions are +projected on the next catalog request. Changes made through Lite or the control +API use the normal hot reload path; no model list is written to the Codex config. +The initial connection requires restarting Codex. Codex also maintains its own +model cache, so an already open picker may show its previous list until the +client refreshes it or restarts. This endpoint does not push updates to clients. + +## Native metadata and ordinary upstreams + +For Responses, Chat Completions and ChatGPT providers, Core requests metadata +with the requesting Codex `client_version`, using that provider's credentials +and configured proxy. The inbound gateway key is never forwarded. ChatGPT uses +its native models URL. Direct OpenAI API providers use OpenAI's documented native +Codex endpoint; other providers use their models endpoint. A full native +`models` entry retains its instructions, tools and unknown version-specific +fields. A standard OpenAI `data` list contains no native Codex instructions and +uses a generic coding profile instead. Core does not copy bundled OpenAI model +instructions onto unrelated providers. + +Only models already in the shared gateway directory are exposed. A native +catalog does not independently add models or grant inference access. Alias +names become the exposed slugs, with no migration target. If routing candidates +have different native definitions, Core uses the generic profile and intersects +their known capabilities. Explicit model specifications override native values; +native values take precedence over the price table. Unknown context windows +are omitted, and reasoning effort choices are only taken from native metadata. +Image input requires affirmative support from every candidate. + +## Cache and limits + +Only upstream native metadata is cached. Entries are isolated by the provider, +resolved credentials and headers, URL, client version and proxy configuration. +There are at most 32 cache entries and four concurrent metadata fetches. Fetches +have an eight-second deadline. Successful upstream cache lifetimes are capped at +five minutes, subtract `Age`, and honor `no-cache` and `no-store`; failed fetches +use a generic fallback and are retried after 30 seconds. Oversized or unavailable +upstream metadata also falls back to the generic profile. + +Gateway names, permissions and capabilities are rebuilt even on conditional +requests. Authentication happens before an ETag can yield `304`. A configuration +reload during a metadata fetch discards that fetch's native definitions before +projecting the current configuration. Responses are private, revalidate after +30 seconds and carry an ETag. Inference continues enforcing the current key and +model permissions independently of anything cached by Codex. + +The final native response is limited to 1 MiB, as required by Codex. A catalog +larger than that returns `413` instead of silently omitting models. Restrict the +models available to the gateway key to reduce its size. Missing, duplicate or +invalid `client_version` parameters return `400`. + +The remote catalog and generic profile have been checked with Codex CLI +0.166.0. See OpenAI's [catalog endpoint contract](https://developers.openai.com/codex/enterprise/roll-out-a-gateway#implement-the-catalog-endpoint) +for the client configuration and versioned schema requirements. diff --git a/docs/codex-model-catalog.zh-CN.md b/docs/codex-model-catalog.zh-CN.md new file mode 100644 index 00000000..c3009d2f --- /dev/null +++ b/docs/codex-model-catalog.zh-CN.md @@ -0,0 +1,66 @@ +# Codex 远程模型发现 + +[English](codex-model-catalog.md) + +Core 在 `GET /codex/models?client_version=` 提供 Codex 原生模型目录, +复用推理请求的网关密钥、来源地址限制、模型目录、别名和密钥 `allow` 范围。 +标准的 `/v1/models` 保持 OpenAI 响应格式。 + +ThinkWatch Lite 接管 Codex 时会配置这个地址。手动连接的例子: + +```toml +model_provider = "thinkwatch" + +[features] +api_key_model_discovery = true + +[model_providers.thinkwatch] +name = "ThinkWatch" +base_url = "http://127.0.0.1:8788/v1" +model_catalog_url = "http://127.0.0.1:8788/codex/models" +wire_api = "responses" +env_key = "THINKWATCH_GATEWAY_KEY" +requires_openai_auth = false +supports_websockets = false +``` + +地址改成网关的实际地址,环境变量 `THINKWATCH_GATEWAY_KEY` 设为已启用的网关密钥。 +移除生效的 `model_catalog_json`:本地目录文件会覆盖远程发现。选中的 profile 也可能覆盖 +provider、本地目录或发现开关。Lite 会处理默认选中的 profile,断开接管时恢复原字段。 +显式选择其他 profile 或传入命令行覆盖项仍会改变 Codex 使用的 provider。 + +连接只需配置一次。此后,上游模型、别名、启用范围、手动模型规格和密钥权限的变更, +都会在下一次目录请求里体现。Lite 和控制 API 的修改走正常热重载,无需向 Codex 配置 +写入模型列表。首次连接需要重启 Codex。Codex 自己也有模型缓存,已经打开的模型选择器 +可能在客户端刷新或重启之后才显示新列表;此接口不会向客户端推送更新。 + +## 原生元数据和普通上游 + +Core 向 Responses、Chat Completions 和 ChatGPT 上游获取元数据时,传入请求者的 +Codex `client_version`,使用该上游的凭据和代理,不转发入站网关密钥。ChatGPT 使用原生 +模型地址,直连 OpenAI API 时使用其文档指定的原生 Codex 接口,其他上游使用各自的模型接口。 +完整的原生 `models` 条目会保留指令、工具和 +版本特有的未知字段。标准 OpenAI `data` 列表没有原生指令,改用通用编程描述,不把 +OpenAI 内置模型的指令套到无关模型上。 + +只暴露共享网关目录中已经存在的模型,原生目录不会独立添加模型或授予推理权限。 +别名作为对外的 slug,不设置迁移目标。多个路由候选的原生定义不一致时,使用通用描述, +对已知能力取交集。手动模型规格优先于原生值,原生值优先于价目表。未知上下文窗口不填, +推理档位仅采用原生目录提供的选项,图片输入要求所有候选都明确支持。 + +## 缓存和限制 + +只缓存上游原生元数据。缓存按上游、解析后的凭据及请求头、地址、客户端版本和代理配置 +隔离,最多 32 项,同时最多四次元数据请求,获取期限为八秒。成功响应最多缓存五分钟, +扣除 `Age`,遵守 `no-cache` 和 `no-store`。获取失败时使用通用描述,30 秒后重试。 +上游元数据过大或不可用时也使用通用描述。 + +即使带条件请求头,网关也会重新生成名称、权限和能力,并在返回 `304` 前鉴权。获取元数据 +期间发生配置重载,会先丢弃旧配置的原生定义,再根据当前配置生成目录。响应使用私有缓存, +30 秒后重新验证,携带 ETag。推理接口独立检查当前密钥和模型权限,不依赖 Codex 的缓存。 + +最终目录限制为 Codex 要求的 1 MiB。超过时返回 `413`,不会静默漏掉部分模型;可缩小该 +网关密钥的模型范围。缺失、重复或格式错误的 `client_version` 返回 `400`。 + +远程目录和通用描述已用 Codex CLI 0.166.0 验证。客户端配置和版本化格式参见 +OpenAI 的[模型目录接口契约](https://developers.openai.com/codex/enterprise/roll-out-a-gateway#implement-the-catalog-endpoint)。 diff --git a/release-notes/0.90.0.md b/release-notes/0.90.0.md new file mode 100644 index 00000000..90f67f99 --- /dev/null +++ b/release-notes/0.90.0.md @@ -0,0 +1,11 @@ +Core now serves a native Codex model catalog at `GET /codex/models?client_version=`. Changes to upstream models, aliases, enabled ranges, manual capabilities and gateway-key permissions appear on the next catalog request through the existing hot reload path. The standard OpenAI `/v1/models` response stays unchanged. + +The catalog uses the same authentication, allowed source addresses and model permissions as inference. Version-matched upstream definitions retain their native instructions and tools when available. Ordinary upstreams use a conservative coding profile; aliases and routing candidates expose only capabilities they can support. Gateway credentials are never forwarded to upstream model endpoints. + +Upstream metadata has a bounded cache and fetch deadline. Live model names and permissions are rebuilt on every request, including conditional requests. Catalog responses are limited to 1 MiB and support private caching with ETags. Codex can retain its own picker cache, so changes appear when the client refreshes its catalog or restarts; the gateway does not push updates into an already open picker. + +ThinkWatch Lite 2026.11.7 configures remote discovery during Codex adoption. The initial connection updates client configuration once and requires a client restart. Subsequent model changes do not rewrite the client configuration. See [the setup and cache guide](https://github.com/ThinkWatchProject/ThinkWatch-Core/blob/main/docs/codex-model-catalog.md) for manual connections and profile behavior. + +The control-plane protocol remains 58 and the request-store schema remains 28. Existing configuration, request history and usage history are preserved. No configuration or database migration is required. + +Bundled SQLite is upgraded through rusqlite 0.41 to fix RUSTSEC-2026-0459 (CVE-2026-119375). The database format and request-store schema stay unchanged. Building the storage and Core binary crates now requires Rust 1.89 or later; shared client crates retain their existing declared minimum.