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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,10 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt");
/// `POST /providers/{name}/balance/refresh`(→ [`Balance`])马上读一次;没有余额可读是 404
/// (`control.balance_none`)。读失败的原因是 `gw.balance.*`。配置里的 `balance:` 写了不认识的
/// 取值时加载不了(`config.unknown_variant`,一键修复改回 `auto`)。照 45 写的界面不认这个事件。
///
/// **46 起看得出密钥是账号登录换来的**:[`ProviderView`] 多了 `signed_in`([`ZaiFamily`])。
/// Z.ai / BigModel 的账号登录在它写的上游上记下 `signed_in: zai | bigmodel`;重新登录照旧
/// 写上,在界面里保存时密钥没变就留着,换成了别的密钥就去掉。手填的密钥和别的上游是 null。
pub const CONTROL_API_VERSION: u32 = 46;

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -2256,6 +2260,9 @@ pub struct ProviderView {
/// 认不出是哪一种中转站),或者还没读完第一次。读到了、读失败了都报
/// [`Event::BalanceUpdated`]
pub balance: Option<Balance>,
/// 密钥是用哪一家的账号登录换来的(配置里的 `signed_in:`):`zai` / `bigmodel`。手填的
/// 密钥、别的上游、这一项出现之前登录的都是空。在界面里手动换掉密钥之后也是空
pub signed_in: Option<ZaiFamily>,
}

/// 一行请求头,配置里写的原样。
Expand Down
38 changes: 38 additions & 0 deletions crates/tw-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ impl Default for Provider {
max_concurrent: None,
disabled: false,
balance: BalanceSetting::Auto,
signed_in: None,
}
}
}
Expand Down Expand Up @@ -848,6 +849,43 @@ pub struct Provider {
/// 余额从哪儿读,见 [`BalanceSetting`]。不写就是 `auto`
#[serde(default, skip_serializing_if = "is_default")]
pub balance: BalanceSetting,
/// `key` 是用哪一家的账号登录换来的,见 [`SignedIn`]。只有账号登录写它,别的上游
/// 没有这一项
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signed_in: Option<SignedIn>,
}

/// 一家上游的 `key` 是用 Z.ai 还是 BigModel 的账号登录换来的。
///
/// **它只说密钥的来历,不改变任何行为**:转发、额度、余额都不看它。那类登录的终点是一把
/// 普通 API key,和手填的一模一样,不记下来的话,界面编辑这条上游时说不出它是「账号登录」
/// 得来的。重新登录照旧写上;在界面里手动换掉密钥时去掉 —— 那时的密钥已经不是登录得来的
/// 了。这一项出现之前写下的配置没有它
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SignedIn {
/// Z.ai(api.z.ai)
Zai,
/// BigModel(open.bigmodel.cn)
Bigmodel,
}

impl From<SignedIn> for tw_api::ZaiFamily {
fn from(s: SignedIn) -> Self {
match s {
SignedIn::Zai => Self::Zai,
SignedIn::Bigmodel => Self::Bigmodel,
}
}
}

impl From<tw_api::ZaiFamily> for SignedIn {
fn from(f: tw_api::ZaiFamily) -> Self {
match f {
tw_api::ZaiFamily::Zai => Self::Zai,
tw_api::ZaiFamily::Bigmodel => Self::Bigmodel,
}
}
}

/// 一家上游的余额从哪儿读。
Expand Down
47 changes: 47 additions & 0 deletions crates/tw-config/src/reload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,53 @@ routes:
);
}

/// 一家上游的 `signed_in:`:`zai`、`bigmodel` 读得进、原样写回去;不写(这一项出现之前
/// 的配置、手填的密钥)就是没有,写回去时也不写出来
#[test]
fn the_sign_in_mark_loads_and_round_trips() {
use crate::SignedIn as S;
let with = |extra: &str| {
format!(
"{GOOD}providers:\n - name: glm\n base_url: https://api.z.ai/api/anthropic\n protocol: anthropic\n key: id.secret\n{extra}"
)
};
for (value, want) in [("zai", S::Zai), ("bigmodel", S::Bigmodel)] {
let cfg = try_parse(&with(&format!(" signed_in: {value}\n")))
.unwrap_or_else(|e| panic!("{value}: {e}"));
assert_eq!(cfg.providers[0].signed_in, Some(want), "{value}");
// 和契约里的那个词一一对应
assert_eq!(tw_api::ZaiFamily::from(want).slug(), value);
assert_eq!(S::from(tw_api::ZaiFamily::from(want)), want);
let written = serde_yaml_ng::to_string(&cfg.providers[0]).unwrap();
assert!(
written.contains(&format!("signed_in: {value}")),
"{written}"
);
let back: crate::Provider = serde_yaml_ng::from_str(&written).unwrap();
assert_eq!(back.signed_in, Some(want));
}
let cfg = try_parse(&with("")).unwrap();
assert_eq!(cfg.providers[0].signed_in, None);
let written = serde_yaml_ng::to_string(&cfg.providers[0]).unwrap();
assert!(!written.contains("signed_in"), "{written}");
}

/// 不认识的取值:加载不了,说清楚写了什么、能写哪几个;一键修复删掉这一行
#[test]
fn an_unknown_sign_in_mark_is_refused_and_repaired_away() {
let text = format!(
"{GOOD}providers:\n - name: glm\n base_url: https://api.z.ai/api/anthropic\n key: id.secret\n signed_in: chatgpt\n"
);
let r = try_parse(&text).unwrap_err();
assert_eq!(r.message.code, "config.unknown_variant", "{r:?}");
assert_eq!(r.message.arg("field"), "providers[0].signed_in");
assert_eq!(r.message.arg("value"), "chatgpt");
assert_eq!(r.message.arg("expected"), "zai, bigmodel");
let fix = crate::repair::repair(&text).expect("一键修复改得了");
assert_eq!(fix.fixes[0].field, "providers[0].signed_in");
assert_eq!(try_parse(&fix.text).unwrap().providers[0].signed_in, None);
}

#[test]
fn the_display_form_reads_like_a_sentence_a_person_can_act_on() {
let bad = "version: 1\nclients:\n - name: c\n kye: tw-k\n";
Expand Down
12 changes: 12 additions & 0 deletions crates/tw-config/tests/manual/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ fn billings() -> Vec<&'static str> {
fn balance_settings() -> Vec<&'static str> {
super::fields::<BalanceSetting>()
}
fn signed_in() -> Vec<&'static str> {
super::fields::<SignedIn>()
}
fn proxy_kinds() -> Vec<&'static str> {
super::fields::<ProxyKind>()
}
Expand Down Expand Up @@ -663,6 +666,15 @@ pub fn sections() -> Vec<Section> {
"从哪里读这家上游的余额,用它自己的密钥、走它自己的代理:`openrouter`、`deepseek`、`moonshot`、`sub2api`、`newapi`(New API 和 One API)或 `thinkwatch`(ThinkWatch 企业网关)。`auto`:OpenRouter、DeepSeek、Moonshot 按 `base_url` 识别;其他地址(Anthropic、OpenAI、Gemini 的官方地址除外)询问一次它是不是 Sub2API、ThinkWatch 企业网关或 New API 中转站,结果只保存在内存中。`off`:不读余额。ChatGPT、Z.ai 账号和 Bedrock 不读余额,与这里写什么无关。",
),
),
row(
"signed_in",
Kind::Enum(signed_in),
Def::Unset,
t(
"Which account sign-in the `key` came from: `zai` (Z.ai) or `bigmodel` (BigModel). Signing in to the account in the desktop app writes it; replacing the key there removes it. It does not change how requests are sent. Unset: the key was written by hand.",
"`key` 来自哪一家的账号登录:`zai`(Z.ai)或 `bigmodel`(BigModel)。在桌面端登录账号时写入,在桌面端更换密钥时删除。不影响请求的发送方式。不写:密钥是手动填写的。",
),
),
],
},
Section {
Expand Down
2 changes: 2 additions & 0 deletions crates/tw-control/src/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,8 @@ async fn exchange_and_save(
});
// 重新登录:换掉凭据和账户 ID,其余设置(出站方式、模型范围、停用…)不动
p.key = None;
// 那是说 `key` 从 Z.ai 登录得来的记号,ChatGPT 账号没有 `key`
p.signed_in = None;
p.oauth = Some(oauth.clone());
let mut headers: Vec<tw_config::Header> = p
.headers
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,7 @@ fn provider_view(
max_concurrent: p.max_concurrent,
balance_setting: p.balance.into(),
balance: s.gateway.balance_of(p),
signed_in: p.signed_in.map(Into::into),
}
}

Expand Down
5 changes: 5 additions & 0 deletions crates/tw-control/src/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,10 @@ fn to_provider(
profile: nonblank(&a.profile),
region: nonblank(&a.region),
});
// 账号登录换来的密钥原样交回来,才还是登录换来的;换成了手填的,这个记号跟着去掉
let signed_in = existing
.filter(|e| key.is_some() && e.key == key)
.and_then(|e| e.signed_in);
let provider = tw_config::Provider {
name,
base_url,
Expand Down Expand Up @@ -542,6 +546,7 @@ fn to_provider(
max_concurrent: input.max_concurrent,
disabled: input.disabled,
balance: input.balance.map(Into::into).unwrap_or_default(),
signed_in,
};
// **保存和检测之前就说清楚凭据写法哪儿不对**,而不是等整份配置校验时
// 报一条指着 YAML 的错误
Expand Down
18 changes: 15 additions & 3 deletions crates/tw-control/src/zai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
//! **登录的终点是账号下一把普通 API key**,不是一对会过期的 OAuth 令牌。Coding Plan
//! 的额度跟着 key 走 —— Z.ai 自己的客户端就是这么用的:套餐的每个请求只带这把 key,
//! 没有第二种凭据。所以写进 config.yaml 的是 `key`,不是 `oauth`:不需要刷新、不需要
//! refresh token 轮换,[`tw_gateway::oauth`] 那一层完全不参与。
//! refresh token 轮换,[`tw_gateway::oauth`] 那一层完全不参与。这把 key 和手填的没有
//! 区别,所以同时写下 `signed_in: zai | bigmodel`,界面才认得出这条上游是账号登录
//! ([`tw_config::SignedIn`])。
//!
//! # 授权页上显示的是 Z.ai 自己的客户端
//!
Expand Down Expand Up @@ -87,6 +89,13 @@ impl Family {
fn default_name(&self) -> &'static str {
self.slug()
}
/// 写进上游的 `signed_in:`
fn signed_in(self) -> tw_config::SignedIn {
match self {
Self::Zai => tw_config::SignedIn::Zai,
Self::Bigmodel => tw_config::SignedIn::Bigmodel,
}
}
}

/// 登录要用的地址。**平时是它们的**,测试里换成本机的假服务器
Expand Down Expand Up @@ -603,8 +612,8 @@ fn pick_place(info: &Value) -> Option<(String, String)> {

/// 把登录得来的密钥写进 config.yaml。
///
/// **重新登录只换密钥**,出站方式、模型范围、停用状态这些都不动 —— 用户在上游页上
/// 调过的东西不该因为换一次密钥就回到默认值。
/// **重新登录只换密钥**(连同它来自哪一家的 `signed_in`),出站方式、模型范围、停用
/// 状态这些都不动 —— 用户在上游页上调过的东西不该因为换一次密钥就回到默认值。
async fn save(s: &ControlState, want: &Want, key: String) -> Result<String, Msg> {
let name = want.name.clone();
let proxy = want.proxy.clone();
Expand All @@ -631,6 +640,9 @@ async fn save(s: &ControlState, want: &Want, key: String) -> Result<String, Msg>
..Default::default()
});
p.key = Some(tw_config::Secret::new(key.clone()));
// 记下密钥是登录换来的、哪一家的:和手填的 key 一模一样,不记的话界面说不出
// 这条上游是账号登录
p.signed_in = Some(want.family.signed_in());
// 这类上游从不用 OAuth。上一次登录留下的(不该有)也一并清掉
p.oauth = None;
p.check_credential()
Expand Down
85 changes: 85 additions & 0 deletions crates/tw-control/tests/zai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,10 +329,28 @@ async fn a_login_writes_the_account_into_the_config_as_an_anthropic_upstream() {
"made-key.the-secret"
);
assert!(p.oauth.is_none(), "这类上游不用 OAuth,不该写 oauth 块");
// 记下密钥是哪一家的账号登录换来的:key 本身和手填的没有区别
assert_eq!(p.signed_in, Some(tw_config::SignedIn::Zai));
assert!(b.file().contains("signed_in: zai"), "{}", b.file());
// 计费是默认那档:订阅账号也按价目表算费用
assert_eq!(p.billing, tw_config::Billing::PerToken);
// 原有的上游一个都没动
assert!(b.file().contains("sk-relay"));
// 界面拿到的上游视图带着它;手填密钥的上游是 null
let (st, ov) = b.call("GET", "/overview", Value::Null).await;
assert_eq!(st, StatusCode::OK, "{ov}");
let view = |name: &str| {
ov["providers"]
.as_array()
.unwrap()
.iter()
.find(|p| p["name"] == name)
.cloned()
.unwrap()
};
assert_eq!(view("zai")["signed_in"], "zai");
assert_eq!(view("relay")["signed_in"], Value::Null);
assert!(view("relay").get("signed_in").is_some(), "null 也要写出来");

// 轮询凭据是我们自己生成的,不是平台回显的那个
let init_auth = b.zai.auth_of("/api/v1/oauth/cli/init").unwrap();
Expand Down Expand Up @@ -451,6 +469,8 @@ async fn signing_in_again_only_replaces_the_key() {
assert_eq!(p.models_only.as_deref(), Some(&["glm-4.6".to_string()][..]));
assert!(p.disabled);
assert_eq!(b.zai.hit("/api_keys:create"), 0, "已经有的 key 应当复用");
// 这一项出现之前登录的上游没有记号,重新登录之后有了
assert_eq!(p.signed_in, Some(tw_config::SignedIn::Zai));
}

#[tokio::test]
Expand Down Expand Up @@ -489,6 +509,7 @@ async fn bigmodel_signs_in_with_the_oauth_token_itself_and_may_get_a_key_without
assert_eq!(p.base_url, b.endpoints.bigmodel_upstream);
// secret 那一半没有时,BigModel 的 key 就是它自己
assert_eq!(p.key.as_ref().unwrap().resolve().unwrap(), "made-key");
assert_eq!(p.signed_in, Some(tw_config::SignedIn::Bigmodel));
// 它的业务接口直接认 OAuth 的 access token,**不带 `Bearer ` 前缀**
assert_eq!(
b.zai.auth_of("/api/biz/customer/getCustomerInfo").unwrap(),
Expand Down Expand Up @@ -550,3 +571,67 @@ async fn a_login_can_be_cancelled_and_a_new_one_replaces_the_old() {
let (st, _) = b.call("GET", &format!("/zai/login/{id}"), json!({})).await;
assert_eq!(st, StatusCode::NOT_FOUND, "旧的那次已经不在了");
}

// ---------------------------------------------------------------- 登录之后在界面里改

/// 登录写下的一条上游,`signed_in` 已经在了
fn signed_in_upstream(e: &Endpoints) -> String {
format!(
" - name: zai
base_url: {upstream}
protocol: anthropic
key: made-key.the-secret
signed_in: zai
",
upstream = e.zai_upstream
)
}

/// 编辑对话框交回来的整份定义
fn edited(b: &Bed, key: &str) -> Value {
json!({"provider": {
"name": "zai",
"base_url": b.endpoints.zai_upstream,
"protocol": "anthropic",
"key": key,
"proxy": "system",
"disabled": true,
}})
}

#[tokio::test]
async fn an_edit_that_keeps_the_signed_in_key_keeps_the_mark() {
let b = bed(signed_in_upstream).await;
let (st, v) = b
.call("PUT", "/providers/zai", edited(&b, "made-key.the-secret"))
.await;
assert_eq!(st, StatusCode::OK, "{v}");
let p = b.provider("zai").unwrap();
// 别的设置照改,密钥没变,它就还是登录换来的
assert_eq!(p.proxy, "system");
assert!(p.disabled);
assert_eq!(p.signed_in, Some(tw_config::SignedIn::Zai));
let (_, ov) = b.call("GET", "/overview", Value::Null).await;
assert_eq!(ov["providers"][1]["name"], "zai");
assert_eq!(ov["providers"][1]["signed_in"], "zai");
}

#[tokio::test]
async fn replacing_the_key_by_hand_drops_the_mark() {
let b = bed(signed_in_upstream).await;
let (st, v) = b
.call("PUT", "/providers/zai", edited(&b, "typed-by-hand.secret"))
.await;
assert_eq!(st, StatusCode::OK, "{v}");
let p = b.provider("zai").unwrap();
assert_eq!(
p.key.as_ref().unwrap().resolve().unwrap(),
"typed-by-hand.secret"
);
// 密钥已经不是登录换来的了
assert_eq!(p.signed_in, None);
assert!(!b.file().contains("signed_in"), "{}", b.file());
let (_, ov) = b.call("GET", "/overview", Value::Null).await;
assert_eq!(ov["providers"][1]["name"], "zai");
assert_eq!(ov["providers"][1]["signed_in"], Value::Null);
}
1 change: 1 addition & 0 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,7 @@ Upstreams: the APIs requests are forwarded to.
| `max_concurrent` | integer | — | Most requests sent to this upstream at the same time, from 1 to 1000. When it is full, a conversation that stays on it waits for a free slot and other requests go to the next upstream; see `failover.slot_wait_secs`. Unset: no limit. |
| `disabled` | bool | `false` | Take the upstream out of routing and out of the model list, and keep its configuration. |
| `balance` | `auto` \| `off` \| `openrouter` \| `deepseek` \| `moonshot` \| `sub2api` \| `newapi` \| `thinkwatch` | `auto` | Where the upstream's balance is read from, with its own key and proxy: `openrouter`, `deepseek`, `moonshot`, `sub2api`, `newapi` (New API and One API) or `thinkwatch` (a ThinkWatch Enterprise gateway). `auto`: recognized from `base_url` for OpenRouter, DeepSeek and Moonshot; any other address, except Anthropic's, OpenAI's and Gemini's own, is asked once whether it is a Sub2API, ThinkWatch Enterprise or New API relay, and the answer is kept in memory only. `off`: no balance. ChatGPT and Z.ai accounts and Bedrock have no balance whatever is written here. |
| `signed_in` | `zai` \| `bigmodel` | — | Which account sign-in the `key` came from: `zai` (Z.ai) or `bigmodel` (BigModel). Signing in to the account in the desktop app writes it; replacing the key there removes it. It does not change how requests are sent. Unset: the key was written by hand. |
<!-- /generated -->

A credential is one of four things: `key`, which goes in the header the
Expand Down
1 change: 1 addition & 0 deletions docs/config.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ clients:
| `max_concurrent` | 整数 | — | 同时发给这家的请求最多几个,取值 1 到 1000。满了的时候,留在这家的对话等空位,别的请求换下一家;等多久见 `failover.slot_wait_secs`。不写:不限。 |
| `disabled` | 布尔 | `false` | 不参与路由,模型也不出现在模型列表里;配置原样保留。 |
| `balance` | `auto` \| `off` \| `openrouter` \| `deepseek` \| `moonshot` \| `sub2api` \| `newapi` \| `thinkwatch` | `auto` | 从哪里读这家上游的余额,用它自己的密钥、走它自己的代理:`openrouter`、`deepseek`、`moonshot`、`sub2api`、`newapi`(New API 和 One API)或 `thinkwatch`(ThinkWatch 企业网关)。`auto`:OpenRouter、DeepSeek、Moonshot 按 `base_url` 识别;其他地址(Anthropic、OpenAI、Gemini 的官方地址除外)询问一次它是不是 Sub2API、ThinkWatch 企业网关或 New API 中转站,结果只保存在内存中。`off`:不读余额。ChatGPT、Z.ai 账号和 Bedrock 不读余额,与这里写什么无关。 |
| `signed_in` | `zai` \| `bigmodel` | — | `key` 来自哪一家的账号登录:`zai`(Z.ai)或 `bigmodel`(BigModel)。在桌面端登录账号时写入,在桌面端更换密钥时删除。不影响请求的发送方式。不写:密钥是手动填写的。 |
<!-- /generated -->

凭据有四种写法:`key`,放进协议规定的请求头;`oauth`,用 refresh token 换取 token;`aws`,Bedrock 上游签名请求用的访问密钥;`headers`,用于上游自有的鉴权方式。`headers` 可以和其余几种同时使用,但不能再设置已经承载凭据的那个请求头。
Expand Down
Loading