diff --git a/Cargo.lock b/Cargo.lock index a9698b26..7be656f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3763,7 +3763,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.90.0" +version = "0.91.0" dependencies = [ "serde", "serde_json", @@ -3774,7 +3774,7 @@ dependencies = [ [[package]] name = "tw-bedrock" -version = "0.90.0" +version = "0.91.0" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -3795,7 +3795,7 @@ dependencies = [ [[package]] name = "tw-breaker" -version = "0.90.0" +version = "0.91.0" dependencies = [ "serde", "serde_json", @@ -3803,7 +3803,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.90.0" +version = "0.91.0" dependencies = [ "blake3", "libc", @@ -3829,7 +3829,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.90.0" +version = "0.91.0" dependencies = [ "axum", "base64 0.22.1", @@ -3875,7 +3875,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.90.0" +version = "0.91.0" dependencies = [ "memchr", "serde", @@ -3884,7 +3884,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.90.0" +version = "0.91.0" dependencies = [ "chrono", "serde", @@ -3898,7 +3898,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.90.0" +version = "0.91.0" dependencies = [ "arc-swap", "async-stream", @@ -3950,7 +3950,7 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.90.0" +version = "0.91.0" dependencies = [ "aho-corasick", "base64 0.22.1", @@ -3971,7 +3971,7 @@ dependencies = [ [[package]] name = "tw-handover" -version = "0.90.0" +version = "0.91.0" dependencies = [ "libc", "serde", @@ -3984,7 +3984,7 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.90.0" +version = "0.91.0" dependencies = [ "serde", "serde_json", @@ -3998,7 +3998,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.90.0" +version = "0.91.0" dependencies = [ "tokio", "tracing", @@ -4007,7 +4007,7 @@ dependencies = [ [[package]] name = "tw-pack" -version = "0.90.0" +version = "0.91.0" dependencies = [ "age", "blake3", @@ -4031,7 +4031,7 @@ dependencies = [ [[package]] name = "tw-plugin" -version = "0.90.0" +version = "0.91.0" dependencies = [ "libc", "rand 0.10.2", @@ -4047,7 +4047,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.90.0" +version = "0.91.0" dependencies = [ "arc-swap", "flate2", @@ -4060,14 +4060,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.90.0" +version = "0.91.0" dependencies = [ "thiserror 2.0.20", ] [[package]] name = "tw-store" -version = "0.90.0" +version = "0.91.0" dependencies = [ "blake3", "bytes", @@ -4087,7 +4087,7 @@ dependencies = [ [[package]] name = "tw-sync" -version = "0.90.0" +version = "0.91.0" dependencies = [ "age", "axum", @@ -4115,7 +4115,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.90.0" +version = "0.91.0" dependencies = [ "serde", "serde_json", @@ -4124,7 +4124,7 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.90.0" +version = "0.91.0" dependencies = [ "libc", "notify", @@ -4135,7 +4135,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.90.0" +version = "0.91.0" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -4145,7 +4145,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.90.0" +version = "0.91.0" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index 067b591e..52d6498c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,7 @@ categories = ["network-programming", "web-programming::http-server"] # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.90.0" +version = "0.91.0" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index c0281367..1291675e 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -4023,6 +4023,10 @@ pub struct ProxyTest { pub struct AliasInput { pub name: String, pub models: Vec, + /// Hide target original names in client discovery only. Omission preserves an + /// existing alias's setting; new aliases default to false. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hide_originals: Option, } /// 新建或保存一个别名(`POST /aliases`、`PUT /aliases/{name}`)。保存时名字可以改: @@ -4050,6 +4054,9 @@ pub struct AliasModel { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct AliasView { pub name: String, + /// Hide original model names from client discovery without changing access. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub hide_originals: bool, /// 按书写顺序 pub models: Vec, /// 每家能服务它的上游实际发出的名称,按配置里的顺序。停用的上游不在里面;没有清单 @@ -4086,6 +4093,10 @@ pub struct AliasSuggestion { #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct AliasesView { + /// This Core understands hide_originals. Absent/false on older servers; + /// clients must not offer the setting there. + #[serde(default)] + pub hide_originals_supported: bool, /// 按书写顺序 pub aliases: Vec, /// 同一个模型在不同上游上叫不同名称的几组。**只认 Claude**:各家清单里的名称归一之后 @@ -4123,6 +4134,10 @@ pub struct AliasPreview { /// 规则同 [`AliasesView::suggestions`]。列表里已经有的名称、已经有列表里某个名称的 /// 上游不在里面 pub same_model: Vec, + /// Original names hidden by this alias in an unrestricted client catalog. + /// Actual client lists still apply protocol, availability and key permissions. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub hidden_originals: Vec, } /// 一条写着这个名称的规则。 @@ -4305,6 +4320,10 @@ pub struct KnownModel { pub alias: Option>, /// 列出了这个模型名的别名,按别名表的顺序。别名自己这一项是空的 pub aliases: Vec, + /// Available aliases that hide this original name in an unrestricted client + /// catalog. Admins still receive the complete directory and original IDs. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub hidden_by: Vec, } /// 聚合类端点的时间窗(`GET /summary`、`/latency`)。**缺省是「今天」而不是 @@ -7179,6 +7198,28 @@ pub struct PluginRunView { #[cfg(test)] mod tests { + #[test] + fn alias_discovery_fields_are_additive_and_keep_omission_distinct_from_false() { + let omitted: AliasInput = + serde_json::from_str(r#"{"name":"short","models":["raw"]}"#).unwrap(); + assert_eq!(omitted.hide_originals, None); + let clear: AliasInput = + serde_json::from_str(r#"{"name":"short","models":["raw"],"hide_originals":false}"#) + .unwrap(); + assert_eq!(clear.hide_originals, Some(false)); + assert!( + serde_json::to_value(&omitted) + .unwrap() + .get("hide_originals") + .is_none() + ); + let old: AliasesView = serde_json::from_str(r#"{"aliases":[],"suggestions":[]}"#).unwrap(); + assert!(!old.hide_originals_supported); + let known: KnownModel = + serde_json::from_str(r#"{"id":"raw","providers":[],"aliases":[]}"#).unwrap(); + assert!(known.hidden_by.is_empty()); + } + /// 手动加入例外的请求带着原值:调试输出里不能有它 #[test] fn an_exception_request_does_not_print_its_value() { diff --git a/crates/tw-config/src/aliases.rs b/crates/tw-config/src/aliases.rs index da9eb168..3fe5d5b1 100644 --- a/crates/tw-config/src/aliases.rs +++ b/crates/tw-config/src/aliases.rs @@ -22,10 +22,12 @@ use serde::ser::SerializeMap; use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// 一个别名:它的名字,和它在各家上游叫什么(有序)。 -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Alias { pub name: String, pub models: Vec, + /// 只从客户端模型列表隐藏目标原名;不改变权限、准入或上游清单。 + pub hide_originals: bool, } /// 整张别名表,按书写顺序。 @@ -62,6 +64,21 @@ impl Serialize for Aliases { fn serialize(&self, s: S) -> Result { let mut m = s.serialize_map(Some(self.0.len()))?; for a in &self.0 { + if a.hide_originals { + #[derive(Serialize)] + struct Expanded<'a> { + models: &'a [String], + hide_originals: bool, + } + m.serialize_entry( + &a.name, + &Expanded { + models: &a.models, + hide_originals: true, + }, + )?; + continue; + } match a.models.as_slice() { [one] => m.serialize_entry(&a.name, one)?, many => m.serialize_entry(&a.name, many)?, @@ -86,8 +103,19 @@ impl<'de> Deserialize<'de> for Aliases { // **重名不在这里拒**:这里拒的话说出来的是解析器的话,而校验那一句 // 带码、说得出是哪个别名(`config.alias_duplicate`) let mut out = Vec::new(); - while let Some((name, Models(models))) = map.next_entry::()? { - out.push(Alias { name, models }); + while let Some((name, definition)) = map.next_entry::()? { + let (models, hide_originals) = match definition { + Definition::Simple(Models(models)) => (models, false), + Definition::Expanded(Expanded { + models: Models(models), + hide_originals, + }) => (models, hide_originals), + }; + out.push(Alias { + name, + models, + hide_originals, + }); } Ok(Aliases(out)) } @@ -96,6 +124,71 @@ impl<'de> Deserialize<'de> for Aliases { } } +enum Definition { + Simple(Models), + Expanded(Expanded), +} + +impl<'de> Deserialize<'de> for Definition { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> Visitor<'de> for V { + type Value = Definition; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a model name, a list of model names, or {models, hide_originals}") + } + fn visit_map>(self, map: A) -> Result { + Expanded::deserialize(de::value::MapAccessDeserializer::new(map)) + .map(Definition::Expanded) + } + fn visit_seq>(self, seq: A) -> Result { + Models::deserialize(de::value::SeqAccessDeserializer::new(seq)) + .map(Definition::Simple) + } + fn visit_unit(self) -> Result { + Ok(Definition::Simple(Models(Vec::new()))) + } + fn visit_str(self, v: &str) -> Result { + Models::deserialize(de::value::StrDeserializer::::new(v)).map(Definition::Simple) + } + fn visit_string(self, v: String) -> Result { + Models::deserialize(de::value::StringDeserializer::::new(v)) + .map(Definition::Simple) + } + fn visit_bool(self, v: bool) -> Result { + Models::deserialize(de::value::BoolDeserializer::::new(v)) + .map(Definition::Simple) + } + fn visit_i64(self, v: i64) -> Result { + Models::deserialize(de::value::I64Deserializer::::new(v)).map(Definition::Simple) + } + fn visit_u64(self, v: u64) -> Result { + Models::deserialize(de::value::U64Deserializer::::new(v)).map(Definition::Simple) + } + fn visit_i128(self, v: i128) -> Result { + Models::deserialize(de::value::I128Deserializer::::new(v)) + .map(Definition::Simple) + } + fn visit_u128(self, v: u128) -> Result { + Models::deserialize(de::value::U128Deserializer::::new(v)) + .map(Definition::Simple) + } + fn visit_f64(self, v: f64) -> Result { + Models::deserialize(de::value::F64Deserializer::::new(v)).map(Definition::Simple) + } + } + d.deserialize_any(V) + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Expanded { + models: Models, + #[serde(default)] + hide_originals: bool, +} + /// 一个别名的值:一个名称,或者一组名称。 struct Models(Vec); @@ -157,6 +250,26 @@ impl<'de> Deserialize<'de> for Models { mod tests { use super::*; + #[test] + fn expanded_definition_preserves_policy_and_rejects_unknown_fields() { + let a: Aliases = serde_yaml_ng::from_str( + "short: {models: [raw-a, raw-b], hide_originals: true}\nlegacy: raw-c\n", + ) + .unwrap(); + assert!(a[0].hide_originals); + assert!(!a[1].hide_originals); + let text = serde_yaml_ng::to_string(&a).unwrap(); + assert!(text.contains("hide_originals: true")); + assert!(text.contains("legacy: raw-c")); + assert_eq!(serde_yaml_ng::from_str::(&text).unwrap(), a); + let plain: Aliases = serde_yaml_ng::from_str("short: {models: raw-a}").unwrap(); + assert_eq!(serde_yaml_ng::to_string(&plain).unwrap(), "short: raw-a\n"); + let err = serde_yaml_ng::from_str::("short: {models: raw-a, hide_original: true}") + .unwrap_err() + .to_string(); + assert!(err.contains("unknown field `hide_original`"), "{err}"); + } + const TABLE: &str = "\ deepseek-v4.1: DeepSeek-v4.1-flash claude-sonnet-5: @@ -170,6 +283,7 @@ a-model: [x] Alias { name: name.into(), models: models.iter().map(|m| m.to_string()).collect(), + hide_originals: false, } } @@ -244,7 +358,7 @@ a-model: [x] let e = serde_yaml_ng::from_str::("x: {a: b}\n") .unwrap_err() .to_string(); - assert!(e.contains("a model name or a list of model names"), "{e}"); + assert!(e.contains("unknown field `a`"), "{e}"); let e = serde_yaml_ng::from_str::("[a, b]\n") .unwrap_err() .to_string(); diff --git a/crates/tw-config/src/edit.rs b/crates/tw-config/src/edit.rs index a1ae2847..bcbb767b 100644 --- a/crates/tw-config/src/edit.rs +++ b/crates/tw-config/src/edit.rs @@ -520,7 +520,7 @@ const ALIASES: &str = "aliases"; /// —— 名字可以不同,那是改名,**位置不变**;引用它的地方由调用方跟着改 /// ([`crate::refs::rename_alias`])。 /// -/// 一个模型写成字符串,几个写成列表。模型没变就不碰它的值(原来写成 `[a]` 的照旧)。 +/// 默认一个模型写成字符串、几个写成列表;隐藏原名时写对象。模型和展示策略没变就不碰原值。 /// 表是块式的时候只动这一项;表写成了行内(`aliases: {a: b}`)、或者空着,整张表换成 /// 块式。 pub fn upsert_alias( @@ -536,7 +536,7 @@ pub fn upsert_alias( let doc = parse(text)?; let mut table = alias_table(&doc); let taken = table.iter().position(|(k, _)| *k == alias.name); - let value = alias_value(&alias.models); + let value = alias_value(alias); let (index, changed) = match current { None => { if taken.is_some() { @@ -563,7 +563,13 @@ pub fn upsert_alias( name: alias.name.clone(), }); } - let changed = models_of(&table[index].1).as_deref() != Some(alias.models.as_slice()); + let changed = models_of(&table[index].1).as_deref() != Some(alias.models.as_slice()) + || table[index] + .1 + .get("hide_originals") + .and_then(Value::as_bool) + .unwrap_or(false) + != alias.hide_originals; table[index].0 = alias.name.clone(); if changed { table[index].1 = value.clone(); @@ -804,8 +810,22 @@ fn key_string(k: &Value) -> Option { } /// 一个模型写成字符串,几个写成列表 —— 和 `Aliases` 写回去的样子一样 -fn alias_value(models: &[String]) -> Value { - match models { +fn alias_value(alias: &crate::Alias) -> Value { + let models = &alias.models; + if alias.hide_originals { + return Value::Mapping( + [ + ( + Value::String("models".into()), + Value::Sequence(models.iter().cloned().map(Value::String).collect()), + ), + (Value::String("hide_originals".into()), Value::Bool(true)), + ] + .into_iter() + .collect(), + ); + } + match models.as_slice() { [one] => Value::String(one.clone()), many => Value::Sequence(many.iter().cloned().map(Value::String).collect()), } @@ -817,6 +837,7 @@ fn models_of(v: &Value) -> Option> { Value::String(s) => Some(vec![s.clone()]), Value::Sequence(xs) => xs.iter().map(|x| x.as_str().map(str::to_string)).collect(), Value::Null => Some(Vec::new()), + Value::Mapping(_) => v.get("models").and_then(models_of), _ => None, } } @@ -1224,6 +1245,7 @@ providers: crate::Alias { name: name.into(), models: models.iter().map(|m| m.to_string()).collect(), + hide_originals: false, } } @@ -1239,6 +1261,22 @@ aliases: routes: [] "; + #[test] + fn alias_policy_changes_rename_and_noop_preserve_other_text() { + let text = "version: 1\naliases:\n short: {models: [raw], hide_originals: true} # keep\n other: original # untouched\n"; + let mut a = alias("short", &["raw"]); + a.hide_originals = true; + assert_eq!(upsert_alias(text, Some("short"), &a).unwrap(), text); + a.name = "renamed".into(); + let renamed = upsert_alias(text, Some("short"), &a).unwrap(); + assert!(aliases_of(&renamed)[0].hide_originals); + assert!(renamed.contains("other: original # untouched")); + a.hide_originals = false; + let cleared = upsert_alias(&renamed, Some("renamed"), &a).unwrap(); + assert!(!aliases_of(&cleared)[0].hide_originals); + assert!(cleared.contains("other: original # untouched")); + } + fn aliases_of(text: &str) -> Vec { crate::try_parse(&format!("{text}listen:\n control:\n key: c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00\nclients:\n - name: default\n key: tw-a\n")) .unwrap_or_else(|e| panic!("{e}\n{text}")) diff --git a/crates/tw-config/src/refs.rs b/crates/tw-config/src/refs.rs index 88601475..f4022833 100644 --- a/crates/tw-config/src/refs.rs +++ b/crates/tw-config/src/refs.rs @@ -825,6 +825,7 @@ routes: let renamed = crate::Alias { name: "claude-sonnet".into(), models: vec!["claude-sonnet-5".into(), "anthropic/claude-sonnet-5".into()], + hide_originals: false, }; let text = edit::upsert_alias(ALIASED, Some("sonnet"), &renamed).unwrap(); let (out, done) = rename_alias(&text, &c, "sonnet", &renamed).unwrap(); @@ -869,6 +870,7 @@ routes: let renamed = crate::Alias { name: "sonnet".into(), models: vec!["claude-sonnet-5".into(), "anthropic/claude-sonnet-5".into()], + hide_originals: false, }; let edited = edit::upsert_alias(&text, Some("claude-sonnet-5"), &renamed).unwrap(); let (out, done) = rename_alias(&edited, &c, "claude-sonnet-5", &renamed).unwrap(); @@ -898,6 +900,7 @@ routes: let narrowed = crate::Alias { name: "sonnet".into(), models: vec!["anthropic/claude-sonnet-5".into()], + hide_originals: false, }; let edited = edit::upsert_alias(&text, Some("claude-sonnet-5"), &narrowed).unwrap(); let (out, done) = rename_alias(&edited, &c, "claude-sonnet-5", &narrowed).unwrap(); diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index 8101efca..99ea4ba6 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -2012,10 +2012,12 @@ groups: crate::Alias { name: "x".into(), models: vec!["a".into()], + hide_originals: false, }, crate::Alias { name: "x".into(), models: vec!["b".into()], + hide_originals: false, }, ]); assert_eq!( diff --git a/crates/tw-config/tests/manual.rs b/crates/tw-config/tests/manual.rs index e6fa2f35..1280c5d7 100644 --- a/crates/tw-config/tests/manual.rs +++ b/crates/tw-config/tests/manual.rs @@ -178,8 +178,8 @@ pub enum Kind { Objs(&'static str), /// 键 → 对象,见那一节 ObjMap(T2, &'static str), - /// 键 → 一个字符串或一组字符串 - OneOrManyMap(T2), + /// 别名 → 字符串、列表或带展示选项的对象 + AliasMap, /// 一个字符串,或者一组对象(见那一节) StrOrObjs(&'static str), /// 一个列表,每一项是字符串或者对象(见那一节) @@ -307,12 +307,11 @@ fn kind(k: &Kind, l: Lang) -> String { Kind::ObjMap(key, p) => { format!("{} {} → {}", pick("map of", "映射:"), key.get(l), link(p)) } - Kind::OneOrManyMap(key) => format!( - "{} {} → {}", - pick("map of", "映射:"), - key.get(l), - pick("string or list of strings", "字符串或字符串列表") - ), + Kind::AliasMap => pick( + "map of alias → string, list of strings or object", + "映射:别名 → 字符串、字符串列表或对象", + ) + .to_string(), Kind::StrOrObjs(p) => format!( "{} {}", pick("string, or list of", "字符串,或对象列表,见"), diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index f442d607..7f8b0c7e 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -259,11 +259,11 @@ pub fn sections() -> Vec
{ ), row( "aliases", - Kind::OneOrManyMap(t("alias", "别名")), + Kind::AliasMap, Def::Is("{}"), t( - "Model aliases: one name for the same model across upstreams, mapped to the name each upstream uses, in order. A request for an alias goes to any upstream offering one of the listed names, under the first of them it offers. An alias cannot list another alias.", - "模型别名:同一个模型在各上游的名称合用一个名字,按顺序列出各上游的名称。请求别名时,提供其中任一名称的上游都能服务,发给它的是列表中它提供的第一个名称。别名不能列出别的别名。", + "Model aliases: one name for the same model across upstreams, mapped to the name each upstream uses, in order. A request for an alias goes to any upstream offering one of the listed names, under the first of them it offers. An alias cannot list another alias. The object form accepts `models` and `hide_originals` (default false); hiding only affects client discovery, not access.", + "模型别名:同一个模型在各上游的名称合用一个名字,按顺序列出各上游的名称。请求别名时,提供其中任一名称的上游都能服务,发给它的是列表中它提供的第一个名称。别名不能列出别的别名。对象写法接受 `models` 和 `hide_originals`(默认 false);隐藏只影响客户端列表,不改变访问权限。", ), ), row( diff --git a/crates/tw-control/src/aliases.rs b/crates/tw-control/src/aliases.rs index cd1823a2..198eaa5d 100644 --- a/crates/tw-control/src/aliases.rs +++ b/crates/tw-control/src/aliases.rs @@ -59,6 +59,7 @@ async fn list(State(s): State) -> Json { .unwrap_or_default(); tw_api::AliasView { name: a.name.clone(), + hide_originals: a.hide_originals, models: a .models .iter() @@ -80,6 +81,7 @@ async fn list(State(s): State) -> Json { }) .collect(); Json(tw_api::AliasesView { + hide_originals_supported: true, aliases, suggestions: suggestions(&lists, &cfg.aliases), }) @@ -114,7 +116,11 @@ async fn preview( let cfg = s.config(); let catalog = s.gateway.catalog.load(); let lists = lists(&s, &cfg); - let draft = draft(&req.alias); + let previous = req + .original + .as_deref() + .and_then(|name| cfg.aliases.find(name)); + let draft = draft(&req.alias, previous.is_some_and(|a| a.hide_originals)); let mut problems = Vec::new(); if let Err(m) = crate::resources::checked_name(&req.alias.name, edit::ALIAS) { problems.push(m); @@ -144,9 +150,9 @@ async fn preview( problems.push(e.msg()); } - // 「存了之后」:这张表里只有这一个别名就够 resolve 用 —— 重名的时候也不会认错 + // 用完整候选表重建展示目录,避免编辑/改名后沿用旧别名的可用性。 let mut with = (*cfg).clone(); - with.aliases = tw_config::Aliases(vec![draft.clone()]); + with.aliases = table; let listed = |m: &String| draft.models.contains(m); let reached: HashSet<&str> = lists .iter() @@ -169,9 +175,30 @@ async fn preview( // 准入就会拒掉的话,列表里的每个名称都算没有上游提供:没有清单的上游当作有,也 // 轮不到它(见 `served_by`) let admitted = admitted(&with, &catalog, &draft); + let served_by = served_by(&with, &catalog, &draft); + let sources: Vec<_> = lists + .iter() + .map(|(provider, models)| tw_engine::ProviderModels { + provider: provider.clone(), + protocol: String::new(), + known: true, + models: models.clone(), + }) + .collect(); + let preview_catalog = tw_engine::Catalog::build(&sources).with_aliases( + with.aliases + .iter() + .map(|a| (a.name.as_str(), a.models.as_slice())), + ); + let allowed = preview_catalog.resolve_allowed(None, None); + let hidden_originals = tw_gateway::discovery::hidden_originals(&with, &allowed) + .into_iter() + .filter(|(_, names)| names.contains(&draft.name)) + .map(|(name, _)| name) + .collect(); Json(tw_api::AliasPreview { problems, - served_by: served_by(&with, &catalog, &draft), + served_by, unserved: draft .models .iter() @@ -180,6 +207,7 @@ async fn preview( .collect(), shadows: shadows(&lists, &draft), same_model, + hidden_originals, }) } @@ -192,7 +220,7 @@ async fn create( let version = s .cfg .transform(req.base_version.as_deref(), Origin::Ui, |text, _| { - let a = to_alias(&req.alias)?; + let a = to_alias(&req.alias, false)?; Ok(edit::upsert_alias(text, None, &a)?) }) .await @@ -212,7 +240,10 @@ async fn update( if !cfg.aliases.contains(&name) { return Err(not_found(&name)); } - let a = to_alias(&req.alias)?; + let a = to_alias( + &req.alias, + cfg.aliases.find(&name).is_some_and(|a| a.hide_originals), + )?; let out = edit::upsert_alias(text, Some(&name), &a)?; if a.name == name { return Ok(out); @@ -253,7 +284,7 @@ async fn delete_alias( /// 交过来的别名,模型名去掉首尾空白、去掉重复(顺序不变)。**不在这里挡空的**: /// 那一句由校验说(`config.alias_blank_model`),和手改配置时说的一样 -fn draft(input: &tw_api::AliasInput) -> tw_config::Alias { +fn draft(input: &tw_api::AliasInput, previous_hide_originals: bool) -> tw_config::Alias { let mut models: Vec = Vec::new(); for m in input.models.iter().map(|m| m.trim()) { if !models.iter().any(|x| x == m) { @@ -263,12 +294,16 @@ fn draft(input: &tw_api::AliasInput) -> tw_config::Alias { tw_config::Alias { name: input.name.clone(), models, + hide_originals: input.hide_originals.unwrap_or(previous_hide_originals), } } -fn to_alias(input: &tw_api::AliasInput) -> Result { +fn to_alias( + input: &tw_api::AliasInput, + previous_hide_originals: bool, +) -> Result { crate::resources::checked_name(&input.name, edit::ALIAS).map_err(crate::resources::invalid)?; - Ok(draft(input)) + Ok(draft(input, previous_hide_originals)) } fn usage_view(r: AliasRefs, requests_24h: u64) -> tw_api::AliasUsage { @@ -690,6 +725,7 @@ mod tests { tw_config::Alias { name: name.into(), models: models.iter().map(|m| m.to_string()).collect(), + hide_originals: false, } } diff --git a/crates/tw-control/src/routes.rs b/crates/tw-control/src/routes.rs index dd2bdd00..377d8081 100644 --- a/crates/tw-control/src/routes.rs +++ b/crates/tw-control/src/routes.rs @@ -737,7 +737,7 @@ fn to_group(input: &tw_api::GroupInput, cfg: &tw_config::Config) -> Result) -> Json> { Json(known(&s.config(), &s.gateway.catalog.load())) @@ -751,6 +751,7 @@ async fn known_models(State(s): State) -> Json Vec { + let hidden = tw_gateway::discovery::hidden_originals(cfg, &catalog.resolve_allowed(None, None)); let mut out: Vec = catalog .all() .into_iter() @@ -760,6 +761,7 @@ fn known(cfg: &tw_config::Config, catalog: &tw_engine::Catalog) -> Vec Vec( .collect() } -fn names(catalog: &tw_engine::Catalog, allow: Option<&[String]>) -> Vec { - catalog.resolve_allowed( +fn names( + cfg: &tw_config::Config, + catalog: &tw_engine::Catalog, + allow: Option<&[String]>, +) -> Vec { + crate::discovery::models( + cfg, + catalog, Some(&crate::client_api::slugs( crate::client_api::ClientApi::OpenaiResponses.servable_by(true), )), @@ -291,7 +297,7 @@ pub(crate) async fn list( 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 listed = names(&rt.config, &catalog, allow.as_deref()); let mut providers = BTreeMap::new(); for name in &listed { for (provider, _) in candidates(&rt, &catalog, name) { @@ -342,7 +348,7 @@ pub(crate) async fn list( allow = current_allow; let catalog = state.catalog.load(); let book = state.pricing.load(); - let models: Vec<_> = names(&catalog, allow.as_deref()) + let models: Vec<_> = names(&rt.config, &catalog, allow.as_deref()) .iter() .map(|name| project(name, &candidates(&rt, &catalog, name), &book, &upstreams)) .collect(); diff --git a/crates/tw-gateway/src/discovery.rs b/crates/tw-gateway/src/discovery.rs new file mode 100644 index 00000000..075bd508 --- /dev/null +++ b/crates/tw-gateway/src/discovery.rs @@ -0,0 +1,130 @@ +//! Client model-list presentation. Never use this filter for admission or routing. + +use std::collections::{BTreeMap, BTreeSet}; + +/// Original names replaced in this already-authorized, protocol-filtered list. +/// An unavailable/inaccessible alias cannot hide another usable name. Alias +/// identities always win, including aliases sharing a target or their own name. +pub fn hidden_originals( + cfg: &tw_config::Config, + allowed: &[String], +) -> BTreeMap> { + let allowed: BTreeSet<&str> = allowed.iter().map(String::as_str).collect(); + let mut hidden: BTreeMap> = BTreeMap::new(); + for alias in cfg + .aliases + .iter() + .filter(|a| a.hide_originals && allowed.contains(a.name.as_str())) + { + for original in &alias.models { + if allowed.contains(original.as_str()) && !cfg.aliases.contains(original) { + hidden + .entry(original.clone()) + .or_default() + .push(alias.name.clone()); + } + } + } + hidden +} + +/// Discovery is a view of existing permissions, not a replacement for them. +pub fn models( + cfg: &tw_config::Config, + catalog: &tw_engine::Catalog, + protocols: Option<&[&str]>, + allow: Option<&[String]>, +) -> Vec { + let allowed = catalog.resolve_allowed(protocols, allow); + let hidden = hidden_originals(cfg, &allowed); + allowed + .into_iter() + .filter(|name| !hidden.contains_key(name)) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use tw_engine::{Catalog, ProviderModels}; + + fn cfg(text: &str) -> tw_config::Config { + tw_config::Config { + aliases: serde_yaml_ng::from_str(text).unwrap(), + ..Default::default() + } + } + fn catalog(cfg: &tw_config::Config) -> Catalog { + Catalog::build(&[ + ProviderModels { + provider: "a".into(), + protocol: "anthropic".into(), + known: true, + models: vec!["raw-a".into(), "raw-b".into(), "other".into()], + }, + ProviderModels { + provider: "b".into(), + protocol: "openai-responses".into(), + known: true, + models: vec!["raw-c".into()], + }, + ]) + .with_aliases( + cfg.aliases + .iter() + .map(|a| (a.name.as_str(), a.models.as_slice())), + ) + } + #[test] + fn discovery_filters_only_exact_originals_and_keeps_admission_and_inventory() { + let cfg = cfg( + "short: {models: [raw-a, raw-b], hide_originals: true}\nother-alias: raw-a\nghost: {models: [missing], hide_originals: true}", + ); + let c = catalog(&cfg); + assert_eq!( + models(&cfg, &c, None, None), + ["other", "other-alias", "raw-c", "short"] + ); + assert!(c.admits("raw-a", None, None)); + assert_eq!(c.offers("a", "raw-a"), Some(true)); + assert!(models(&cfg, &c, None, Some(&[])).is_empty()); + assert_eq!( + models(&cfg, &c, Some(&["openai-responses"]), None), + ["raw-c"] + ); + assert_eq!(models(&cfg, &c, None, Some(&["short".into()])), ["short"]); + // A target grant inherits aliases, but never grants the other targets. + assert_eq!( + models(&cfg, &c, None, Some(&["raw-a".into()])), + ["other-alias", "short"] + ); + assert!(!c.admits("raw-b", None, Some(&["raw-a".into()]))); + } + #[test] + fn shared_targets_restore_only_after_last_hiding_alias_is_disabled_or_deleted() { + let mut cfg = cfg( + "a: {models: [raw-a], hide_originals: true}\nb: {models: [raw-a], hide_originals: true}", + ); + assert_eq!( + hidden_originals(&cfg, &catalog(&cfg).resolve_allowed(None, None))["raw-a"], + ["a", "b"] + ); + cfg.aliases.0.remove(0); + assert!(!models(&cfg, &catalog(&cfg), None, None).contains(&"raw-a".into())); + cfg.aliases.0[0].hide_originals = false; + assert!(models(&cfg, &catalog(&cfg), None, None).contains(&"raw-a".into())); + } + #[test] + fn alias_identity_and_unavailable_aliases_cannot_hide_names() { + let cfg = cfg( + "raw-a: {models: [raw-a, raw-b], hide_originals: true}\nshort: {models: [raw-c], hide_originals: true}", + ); + let c = catalog(&cfg); + assert!(models(&cfg, &c, None, None).contains(&"raw-a".into())); + // Apply only to aliases present in the current authorized/protocol list. + assert!(hidden_originals(&cfg, &["raw-c".into()]).is_empty()); + assert!(!models(&cfg, &c, Some(&["anthropic"]), None).contains(&"short".into())); + assert!(Catalog::default().resolve_allowed(None, None).is_empty()); + assert!(models(&cfg, &Catalog::default(), None, None).is_empty()); + } +} diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 394c1bdc..9e2c643f 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -21,6 +21,7 @@ pub mod clientprobe; mod codex_catalog; pub mod content; pub mod count; +pub mod discovery; pub mod effort_memory; pub mod egress; pub mod ending; diff --git a/crates/tw-gateway/src/server/listing.rs b/crates/tw-gateway/src/server/listing.rs index a7114708..16e333d0 100644 --- a/crates/tw-gateway/src/server/listing.rs +++ b/crates/tw-gateway/src/server/listing.rs @@ -155,7 +155,12 @@ pub(super) async fn list_models( .and_then(|c| c.allow.clone()); let shape = ListingShape::of(uri.path(), &headers, position); let catalog = state.catalog.load(); - let models = catalog.resolve_allowed(Some(&shape.protocols()), allow.as_deref()); + let models = crate::discovery::models( + &rt.config, + &catalog, + Some(&shape.protocols()), + allow.as_deref(), + ); let book = state.pricing.load(); let objects: Vec<_> = models diff --git a/crates/tw-gateway/tests/alias_catalog.rs b/crates/tw-gateway/tests/alias_catalog.rs index 5426c9ba..7a25bfd4 100644 --- a/crates/tw-gateway/tests/alias_catalog.rs +++ b/crates/tw-gateway/tests/alias_catalog.rs @@ -348,3 +348,53 @@ async fn a_phase_two_rename_is_admitted_as_written_even_when_an_alias_has_its_na "{body}" ); } + +#[tokio::test] +async fn hiding_originals_changes_all_public_lists_but_not_raw_requests_or_lookup() { + let mut cfg = setup( + vec![ + client("all", None, None), + client("alias-only", Some(&["sonnet"]), None), + client("none", Some(&[]), None), + ], + "", + ) + .await; + cfg.aliases.0[0].hide_originals = true; + let gw = serve(cfg).await; + let names = listed(gw, "all").await; + assert!(names.contains(&"sonnet".into())); + assert!(!names.contains(&"claude-sonnet-4-5".into())); + assert!(!names.contains(&"anthropic/claude-sonnet-4-5".into())); + assert_eq!(listed(gw, "alias-only").await, ["sonnet"]); + assert!(listed(gw, "none").await.is_empty()); + let (_, anthropic) = get_json(gw, "all", "/v1/models", true).await; + assert!( + !anthropic["data"] + .as_array() + .unwrap() + .iter() + .any(|m| m["id"] == "claude-sonnet-4-5") + ); + let (status, gemini) = get_json(gw, "all", "/v1beta/models", false).await; + assert_eq!(status, 200); + assert!( + !gemini["models"] + .as_array() + .unwrap() + .iter() + .any(|m| m["name"] == "models/claude-sonnet-4-5") + ); + assert_eq!( + get_json(gw, "all", "/v1/models/claude-sonnet-4-5", false) + .await + .0, + 200 + ); + let (status, answer) = ask(gw, "all", "claude-sonnet-4-5").await; + assert_eq!(status, 200, "{answer}"); + assert_eq!(answer["sent"], "claude-sonnet-4-5"); + let (status, denied) = ask(gw, "alias-only", "claude-sonnet-4-5").await; + assert_eq!(status, 400, "{denied}"); + assert!(message(&denied).contains("claude-sonnet-4-5")); +} diff --git a/crates/tw-gateway/tests/codex_catalog.rs b/crates/tw-gateway/tests/codex_catalog.rs index f2ab0673..2268b5a0 100644 --- a/crates/tw-gateway/tests/codex_catalog.rs +++ b/crates/tw-gateway/tests/codex_catalog.rs @@ -459,3 +459,28 @@ async fn oversized_projected_catalog_is_rejected_instead_of_truncated() { let (_, gw) = serve(config(vec![p])).await; assert_eq!(request(gw).send().await.unwrap().status(), 413); } + +#[tokio::test] +async fn alias_discovery_policy_reloads_over_cached_metadata_and_is_key_scoped() { + let up = Upstream::new(json!({"models":[native("raw")]})); + let addr = up.serve().await; + let mut cfg = config(vec![provider("native", addr, &["raw"])]); + cfg.aliases = serde_yaml_ng::from_str("coding: raw").unwrap(); + let (state, gw) = serve(cfg.clone()).await; + assert_eq!(slugs(&catalog(gw).await), ["coding", "raw"]); + cfg.aliases.0[0].hide_originals = true; + state.reload(cfg.clone()).unwrap(); + assert_eq!(slugs(&catalog(gw).await), ["coding"]); + assert_eq!( + up.requests.lock().unwrap().len(), + 1, + "reuse metadata, not the old discovery result" + ); + cfg.clients[0].allow = Some(vec![]); + state.reload(cfg.clone()).unwrap(); + assert!(slugs(&catalog(gw).await).is_empty()); + cfg.clients[0].allow = None; + cfg.aliases.0.clear(); + state.reload(cfg).unwrap(); + assert_eq!(slugs(&catalog(gw).await), ["raw"]); +} diff --git a/crates/tw-gateway/tests/plugins_request.rs b/crates/tw-gateway/tests/plugins_request.rs index 09474718..8fd68c44 100644 --- a/crates/tw-gateway/tests/plugins_request.rs +++ b/crates/tw-gateway/tests/plugins_request.rs @@ -516,6 +516,7 @@ async fn a_plugin_renaming_to_an_alias_sends_each_upstream_its_own_name() { aliases: tw_config::Aliases(vec![tw_config::Alias { name: "sonnet".into(), models: vec!["claude-sonnet-5".into(), "anthropic/claude-sonnet-5".into()], + hide_originals: false, }]), ..config() }, @@ -566,10 +567,12 @@ async fn a_plugin_renaming_to_an_alias_inherits_the_keys_allow_like_a_request_fo tw_config::Alias { name: "sonnet".into(), models: vec!["claude-sonnet-5".into()], + hide_originals: false, }, tw_config::Alias { name: "opus".into(), models: vec!["claude-opus-5".into()], + hide_originals: false, }, ]), ..config() diff --git a/crates/tw-pack/src/model/items.rs b/crates/tw-pack/src/model/items.rs index 8fcb73ad..0bbe7b20 100644 --- a/crates/tw-pack/src/model/items.rs +++ b/crates/tw-pack/src/model/items.rs @@ -68,9 +68,11 @@ pub(crate) fn of_config( let id = ItemId::new(ItemKind::Alias, &a.name); put( id, - one(Json::Array( - a.models.iter().cloned().map(Json::String).collect(), - )), + one(if a.hide_originals { + serde_json::json!({ "models": a.models, "hide_originals": true }) + } else { + Json::Array(a.models.iter().cloned().map(Json::String).collect()) + }), ); } for g in &cfg.groups { @@ -382,22 +384,22 @@ where typed_mapping::(Yaml::Mapping(m)).map_err(|e| shape(id, e)) } -/// 别名的模型列表 -pub(crate) fn alias_models( +/// 别名的模型及展示策略,兼容旧快照里的模型数组。 +pub(crate) fn alias_definition( id: &ItemId, units: &BTreeMap, -) -> Result, ModelError> { - match units.get(unit::ALL) { - Some(Json::Array(a)) => a - .iter() - .map(|m| { - m.as_str() - .map(str::to_string) - .ok_or_else(|| shape(id, "a model is not a string")) - }) - .collect(), - _ => Err(shape(id, "unit `all` is not a list of models")), - } +) -> Result { + let value = units + .get(unit::ALL) + .ok_or_else(|| shape(id, "unit `all` is missing"))?; + let aliases: tw_config::Aliases = + serde_json::from_value(serde_json::json!({ id.name.clone(): value })) + .map_err(|e| shape(id, e))?; + aliases + .0 + .into_iter() + .next() + .ok_or_else(|| shape(id, "alias definition is missing")) } /// 顺序项目里的名字 diff --git a/crates/tw-pack/src/model/tests.rs b/crates/tw-pack/src/model/tests.rs index d326bfa7..c22e82db 100644 --- a/crates/tw-pack/src/model/tests.rs +++ b/crates/tw-pack/src/model/tests.rs @@ -1128,3 +1128,45 @@ fn a_plugin_refers_to_the_upstreams_its_scope_names() { let script = String::from_utf8(out.plugins["scoped"].script.clone()).unwrap(); assert!(script.contains("relay (2)"), "{script}"); } + +#[test] +fn alias_visibility_survives_pack_normalization_and_reconstruction() { + let text = rich().replace( + "fast: [claude-haiku, gpt-mini]", + "fast: {models: [claude-haiku, gpt-mini], hide_originals: true}", + ); + let source = pack(&text); + let model = snap(&source); + let rebuilt = mat(&pack(&rich()), &model); + let cfg = tw_config::try_parse(&rebuilt.config_yaml).unwrap(); + assert!(cfg.aliases.find("fast").unwrap().hide_originals); + assert_eq!(snap(&rebuilt), model); + let exported = crate::export::export_with( + &source, + crate::export::Options { + scope: None, + secrets: false, + client_prefs: None, + origin: PackOrigin::Ui, + }, + &Fake::new(), + ) + .unwrap(); + assert!( + serde_yaml_ng::from_str::(&exported.pack.config_yaml) + .unwrap() + .aliases[0] + .hide_originals + ); + let mut renamed = model; + rename(&mut renamed, &id(ItemKind::Alias, "fast"), "quick"); + let landed = mat(&pack(&rich()), &renamed); + assert!( + tw_config::try_parse(&landed.config_yaml) + .unwrap() + .aliases + .find("quick") + .unwrap() + .hide_originals + ); +} diff --git a/crates/tw-pack/src/model/write.rs b/crates/tw-pack/src/model/write.rs index 793ef2d6..d5b3182d 100644 --- a/crates/tw-pack/src/model/write.rs +++ b/crates/tw-pack/src/model/write.rs @@ -18,7 +18,7 @@ use tw_config::{Config, Plugin}; use tw_yaml::Step; use super::items::{ - alias_models, approved_source, global_path, order_names, provider_mapping, rule_name, + alias_definition, approved_source, global_path, order_names, provider_mapping, rule_name, sha256_hex, whole_mapping, }; use super::json::{key, to_yaml, unflatten}; @@ -541,10 +541,7 @@ fn upsert( plugins: &BTreeMap, ) -> Result { if id.kind == ItemKind::Alias { - let alias = tw_config::Alias { - name: id.name.clone(), - models: alias_models(id, &item.units)?, - }; + let alias = alias_definition(id, &item.units)?; let current = exists.then_some(id.name.as_str()); return Ok(edit::upsert_alias(text, current, &alias)?); } @@ -770,11 +767,18 @@ fn rebuild( cfg.aliases.iter().map(|a| a.name.clone()).collect(), ) { let id = ItemId::new(ItemKind::Alias, n.clone()); - let models = alias_models(&id, &target.items[&id].units)?; - let v = match models.as_slice() { - [one] => Yaml::String(one.clone()), - many => Yaml::Sequence(many.iter().cloned().map(Yaml::String).collect()), - }; + let alias = alias_definition(&id, &target.items[&id].units)?; + let mut value = serde_yaml_ng::to_value(tw_config::Aliases(vec![alias])).map_err(|e| { + ModelError::Shape { + item: id.to_string(), + detail: e.to_string(), + } + })?; + let v = value + .as_mapping_mut() + .expect("aliases serialize as a map") + .remove(key(&n)) + .expect("the serialized alias is present"); aliases.insert(key(&n), v); } if !aliases.is_empty() { diff --git a/docs/config.md b/docs/config.md index 17f07674..6549bcb6 100644 --- a/docs/config.md +++ b/docs/config.md @@ -205,7 +205,7 @@ means. | `security` | object, [`security`](#cfg-security) | — | The three guards. All of them start in `observe`, so out of the box nothing is changed or refused. | | `retention` | object, [`retention`](#cfg-retention) | — | How long request logs are kept. | | `failover` | object, [`failover`](#cfg-failover) | — | How long an upstream is set aside after it fails, and how long the start of a stream is awaited. | -| `aliases` | map of alias → string or list of strings | `{}` | Model aliases: one name for the same model across upstreams, mapped to the name each upstream uses, in order. A request for an alias goes to any upstream offering one of the listed names, under the first of them it offers. An alias cannot list another alias. | +| `aliases` | map of alias → string, list of strings or object | `{}` | Model aliases: one name for the same model across upstreams, mapped to the name each upstream uses, in order. A request for an alias goes to any upstream offering one of the listed names, under the first of them it offers. An alias cannot list another alias. The object form accepts `models` and `hide_originals` (default false); hiding only affects client discovery, not access. | | `groups` | list of [`groups[]`](#cfg-groups) | `[]` | Strategy groups: several upstreams behind one name, with a way to pick among them. | | `routes` | list of [`routes[]`](#cfg-routes) | `[]` | Routes. Without any, requests fail over across all upstreams in the order they are declared. | | `default_route` | string | — | The route for keys that do not name one. Unset: the route named `default`, or the built-in failover when there is none. | @@ -1452,11 +1452,29 @@ aliases: - anthropic/claude-sonnet-5 ``` +To hide the mapped original names from client model lists, use the object form: + +```yaml +aliases: + coding: + models: [provider-model-2026] + hide_originals: true # optional; defaults to false +``` + +`models` accepts the same string or list forms as a simple alias. The option +only changes discovery (`/v1/models`, Gemini lists and `/codex/models`); +original-name requests and single-model lookups keep their existing permissions +and routing. Filtering runs after protocol, availability and key permissions: +only a usable, visible alias can hide its exact targets. Alias identities stay +visible, and shared targets remain hidden until the last effective hiding alias +is disabled or removed. Changes reload live; clients may cache their picker and +need a model-list refresh. Admin inventories and permission editors stay complete. + - An upstream serves an alias when it offers one of the listed names within its `models_only`, and receives the first such name in the list. Every upstream that serves an alias takes part in failover for it. - `GET /v1/models` lists aliases next to the upstream models, and the - original names stay available. + original names stay available unless hidden from the list as above. - An alias takes precedence over an upstream model of the same name: a request for `claude-sonnet-5` above goes only to upstreams offering one of the three names. List an upstream's own name when it should keep serving it. diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index ce244df6..8ac96c21 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -114,7 +114,7 @@ twcore config set /listen/gateway/port 8790 --int | `security` | 对象,见 [`security`](#cfg-security) | — | 三项防护。出厂时都处在 `observe`,不改变、不拒绝任何请求。 | | `retention` | 对象,见 [`retention`](#cfg-retention) | — | 请求日志保留多久。 | | `failover` | 对象,见 [`failover`](#cfg-failover) | — | 上游失败后停用多久,以及流式回答的开头最多等多久。 | -| `aliases` | 映射: 别名 → 字符串或字符串列表 | `{}` | 模型别名:同一个模型在各上游的名称合用一个名字,按顺序列出各上游的名称。请求别名时,提供其中任一名称的上游都能服务,发给它的是列表中它提供的第一个名称。别名不能列出别的别名。 | +| `aliases` | 映射:别名 → 字符串、字符串列表或对象 | `{}` | 模型别名:同一个模型在各上游的名称合用一个名字,按顺序列出各上游的名称。请求别名时,提供其中任一名称的上游都能服务,发给它的是列表中它提供的第一个名称。别名不能列出别的别名。对象写法接受 `models` 和 `hide_originals`(默认 false);隐藏只影响客户端列表,不改变访问权限。 | | `groups` | 对象列表,见 [`groups[]`](#cfg-groups) | `[]` | 策略组:多个上游合用一个名字,并规定如何在其中选择。 | | `routes` | 对象列表,见 [`routes[]`](#cfg-routes) | `[]` | 路由。一条都不写时,请求按上游的声明顺序故障转移。 | | `default_route` | 字符串 | — | 未指定路由的密钥走哪条路由。不写:名为 `default` 的路由;没有这条路由时走内置的故障转移。 | @@ -1091,8 +1091,19 @@ aliases: - anthropic/claude-sonnet-5 ``` +要从客户端模型列表隐藏对应的上游原名,使用对象写法: + +```yaml +aliases: + coding: + models: [provider-model-2026] + hide_originals: true # 可选,默认 false +``` + +`models` 和简单写法一样接受字符串或列表。此选项只影响模型发现(`/v1/models`、Gemini 列表和 `/codex/models`);原名请求、单模型查询仍沿用原有权限和路由。先按协议、可用性和密钥权限筛选,再由可用且可见的别名精确隐藏目标原名。别名身份始终保留;多个别名共享目标时,最后一个有效隐藏来源关闭或删除后才恢复原名。修改会热加载;客户端可能缓存模型菜单,需要刷新模型列表。管理目录和权限编辑始终保留完整清单。 + - 上游在 `models_only` 范围内提供列出的任一名称,就能服务这个别名,收到的是列表里它提供的第一个名称。能服务同一别名的上游互为备用。 -- `GET /v1/models` 在上游模型旁一并列出别名,原来的名称照常可用。 +- `GET /v1/models` 默认在上游模型旁一并列出别名;上面的选项可隐藏原名,原名调用照常可用。 - 别名优先于同名的上游模型:上例中请求 `claude-sonnet-5` 只会发给提供这三个名称之一的上游。要让某家上游继续用自己的同名模型提供服务,把它的名称列进去。 - 密钥的 `allow` 和规则的 `when.model` 写上游模型名时,对列有这个名称的别名同样有效;写别名时只对别名有效。 - 上游答的是发给它的那个模型时,回答里的模型名写成客户端请求的名称;答的是别的模型,原样转发。 diff --git a/release-notes/0.91.0.md b/release-notes/0.91.0.md new file mode 100644 index 00000000..d8afba67 --- /dev/null +++ b/release-notes/0.91.0.md @@ -0,0 +1,7 @@ +Model aliases can now optionally hide their mapped original names from client model lists. Enable `hide_originals: true` on an alias, or use the matching setting in ThinkWatch Lite. Existing aliases keep showing both names by default. + +The shared discovery policy covers OpenAI and Anthropic model lists, Gemini model lists and the native Codex catalog. It applies after existing protocol, availability and gateway-key permissions. Original names remain callable and single-model lookups keep working with their existing permissions and routing. Administrative inventories, upstream targets and request history remain complete. + +Changes take effect through configuration hot reload. Clients may cache their model pickers and need a list refresh. Shared targets reappear only after the last effective hiding alias is disabled or removed. Alias edits, renames and configuration packs preserve the setting; older clients that omit it while editing keep the stored value. + +The control-plane protocol remains 58 and the request-store schema remains 28. No database migration is required. The extended alias object format requires this Core version or later.