mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-11-20 07:52:52 +08:00
feat(codex): write third-party routes as the built-in openai provider
Codex 0.167 makes a thread read-only when its recorded model_provider differs from the current one, so switching between the official route (built-in openai) and a third-party route (custom table) split session history in two. When unified session history is off and a ChatGPT login is on disk after the write, route third parties the same way as the official route: no model_provider, top-level openai_base_url pointing at the local proxy, so every thread stays in the openai bucket. The proxy swaps in the third-party key and strips the ChatGPT identity. Keep the custom table when there is no login, when unified history is on, or when the row carries client settings the built-in provider cannot express (request/stream retries, stream idle timeout, remote compaction capability). The contract records the new shape so existing proxy users are rewritten once on attach. Direct mode is unchanged.
This commit is contained in:
@@ -3534,10 +3534,19 @@ mod mode_tests {
|
||||
assert!(!official_contract.contains("sk-relay"));
|
||||
assert_eq!(auth(), native_auth);
|
||||
|
||||
// 本机有 ChatGPT 登录:第三方路由也写成内置 openai(和官方路由同一个会话组),
|
||||
// 之前的 custom 表仍是休眠形态,第三方的 Key 不进客户端文件。
|
||||
ProviderService::switch(&state, AppType::Codex, "relay").expect("route back");
|
||||
let third_party = fs::read_to_string(&config_path).unwrap();
|
||||
assert!(third_party.contains(PROXY_TOKEN_PLACEHOLDER));
|
||||
assert!(!third_party.contains("openai_base_url"), "{third_party}");
|
||||
let doc: toml::Table = toml::from_str(&third_party).unwrap();
|
||||
assert!(doc.get("model_provider").is_none(), "{third_party}");
|
||||
assert_eq!(doc["openai_base_url"].as_str(), Some(base_url));
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["experimental_bearer_token"].as_str(),
|
||||
Some(PROXY_TOKEN_PLACEHOLDER)
|
||||
);
|
||||
assert!(!third_party.contains("sk-relay"), "{third_party}");
|
||||
assert_eq!(auth(), native_auth);
|
||||
exit(&state, &AppType::Codex).await.expect("exit");
|
||||
assert_eq!(auth(), native_auth);
|
||||
assert!(!state
|
||||
@@ -4206,20 +4215,73 @@ model_provider = "c"
|
||||
|
||||
enter(&state, &AppType::Codex, false).await.expect("enter");
|
||||
assert_eq!(codex_login_file(), Some(chatgpt_login("acct")));
|
||||
assert_eq!(
|
||||
codex_doc()["model_providers"]["custom"]["requires_openai_auth"].as_bool(),
|
||||
Some(true)
|
||||
);
|
||||
// 还回来的登录算数:第三方路由也写成内置 openai,会话和官方同组。
|
||||
let doc = codex_doc();
|
||||
assert!(doc.get("model_provider").is_none(), "{}", codex_text());
|
||||
assert!(doc["openai_base_url"]
|
||||
.as_str()
|
||||
.is_some_and(|url| url.starts_with("http://127.0.0.1:")));
|
||||
|
||||
// 只还一次:在 Codex 里登出后换路由,不会又被登上。
|
||||
// 只还一次:在 Codex 里登出后换路由,不会又被登上;没有登录就退回 custom 表。
|
||||
fs::remove_file(codex_auth_path()).unwrap();
|
||||
set_route(&state, &AppType::Codex, "b")
|
||||
.await
|
||||
.expect("route b");
|
||||
assert_eq!(codex_login_file(), None);
|
||||
let doc = codex_doc();
|
||||
assert_eq!(doc["model_provider"].as_str(), Some("custom"));
|
||||
assert!(doc.get("openai_base_url").is_none(), "{}", codex_text());
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["requires_openai_auth"].as_bool(),
|
||||
Some(false)
|
||||
);
|
||||
exit(&state, &AppType::Codex).await.expect("exit");
|
||||
}
|
||||
|
||||
/// 有登录也仍写 custom 表的两种情况:统一会话历史开着(本来全在 custom 组),行里写了
|
||||
/// 内置 openai 表达不了的客户端设置(流空闲超时等,Codex 只认 provider 表上的)。
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn codex_third_party_route_keeps_the_custom_table_when_openai_cannot_carry_it() {
|
||||
let slow = Provider::with_id(
|
||||
"slow".to_string(),
|
||||
"Slow".to_string(),
|
||||
json!({
|
||||
"auth": { "OPENAI_API_KEY": "sk-slow" },
|
||||
"config": "model_provider = \"custom\"\nmodel = \"m\"\n\n[model_providers.custom]\nname = \"slow\"\nbase_url = \"https://slow.example/v1\"\nwire_api = \"responses\"\nstream_idle_timeout_ms = 900000\n"
|
||||
}),
|
||||
None,
|
||||
);
|
||||
let [a, _] = codex_a_b();
|
||||
for (unified, route) in [(true, "a"), (false, "slow")] {
|
||||
let _home = Home::new();
|
||||
crate::settings::update_settings(crate::settings::AppSettings {
|
||||
preserve_codex_official_auth_on_switch: true,
|
||||
unify_codex_session_history: unified,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
seed_codex("", Some(&chatgpt_login("acct")));
|
||||
let state = state_with(AppType::Codex, &[a.clone(), slow.clone()], route).await;
|
||||
ProviderService::switch(&state, AppType::Codex, route).expect("direct");
|
||||
enter(&state, &AppType::Codex, false).await.expect("enter");
|
||||
let doc = codex_doc();
|
||||
assert_eq!(
|
||||
doc.get("model_provider").and_then(|v| v.as_str()),
|
||||
Some("custom"),
|
||||
"unified={unified}: {}",
|
||||
codex_text()
|
||||
);
|
||||
assert!(doc.get("openai_base_url").is_none(), "{}", codex_text());
|
||||
let table = &doc["model_providers"]["custom"];
|
||||
assert_eq!(table["requires_openai_auth"].as_bool(), Some(true));
|
||||
if route == "slow" {
|
||||
assert_eq!(table["stream_idle_timeout_ms"].as_integer(), Some(900000));
|
||||
}
|
||||
exit(&state, &AppType::Codex).await.expect("exit");
|
||||
}
|
||||
}
|
||||
|
||||
fn codex_login_on_disk() -> Value {
|
||||
crate::config::read_json_file(&codex_auth_path()).unwrap()
|
||||
}
|
||||
|
||||
@@ -565,6 +565,12 @@ pub(crate) struct Planned {
|
||||
official_logins: Vec<Value>,
|
||||
/// 目录里的官方行取自哪个登录的官方列表:拿写锁后和实际的目标登录核对。
|
||||
native_identity: Option<String>,
|
||||
/// 代理的第三方路由可以和官方路由一样写成内置 openai(不写选路,顶层 `openai_base_url`
|
||||
/// 指向本地代理)时的代理地址。写入时盘上有登录才这样写,否则仍写 custom 表:内置 openai
|
||||
/// 没有登录会卡在登录页。这样路由 / 聚合模式下换哪一家,新会话都记在 `openai` 组,
|
||||
/// Codex 0.167 起不会因为 provider 不一致把另一组会话变成只读。代理负责把请求带着的
|
||||
/// ChatGPT 身份剥掉、换上第三方的 Key。
|
||||
openai_route: Option<String>,
|
||||
/// 代理契约(直连时也算,没有用处)。
|
||||
pub contract: Contract,
|
||||
}
|
||||
@@ -598,6 +604,7 @@ pub(crate) fn plan(
|
||||
|
||||
let official = provider.is_some_and(is_official);
|
||||
let managed_login = prepared.target_login.as_ref().map(|(_, auth)| auth.clone());
|
||||
let mut openai_route = None;
|
||||
let (route, stamp, auth) = match (target, &projection) {
|
||||
(Target::Direct(None), _) | (_, None) => (RouteWrite::Default, None, AuthGoal::KeepNative),
|
||||
(Target::Direct(Some(provider)), Some(projection)) => {
|
||||
@@ -655,6 +662,24 @@ pub(crate) fn plan(
|
||||
// compaction preference. Preserve the existing UI's OpenAI-name
|
||||
// toggle and Codex's explicit override (including "unsupported").
|
||||
let mut proxy_table = proxy_route_table(ROUTE_ID, base_url, false);
|
||||
// 写完后盘上有登录时,改成和官方路由一样的写法(见 `Planned::openai_route`)。
|
||||
// 行里写了内置 openai 表达不了的客户端设置时仍写 custom 表,统一会话历史开着时
|
||||
// 本来就全在 custom 组。
|
||||
let client_owned = match &projection.route {
|
||||
Route::Custom { table, .. } => {
|
||||
PROXY_KEPT_CLIENT_KEYS
|
||||
.iter()
|
||||
.any(|key| table.contains_key(key))
|
||||
|| table
|
||||
.get("capabilities")
|
||||
.and_then(|capabilities| capabilities.get("remote_compaction"))
|
||||
.is_some()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if !client_owned && !crate::settings::unify_codex_session_history() {
|
||||
openai_route = Some(base_url.to_string());
|
||||
}
|
||||
if let Route::Custom { table, .. } = &projection.route {
|
||||
if table.get("name").and_then(Item::as_str) == Some("OpenAI") {
|
||||
proxy_table.insert("name", toml_edit::value("OpenAI"));
|
||||
@@ -756,10 +781,12 @@ pub(crate) fn plan(
|
||||
catalog.as_deref(),
|
||||
prepared,
|
||||
official_login.as_deref(),
|
||||
openai_route.is_some(),
|
||||
);
|
||||
Ok(Planned {
|
||||
config,
|
||||
stamp,
|
||||
openai_route,
|
||||
catalog,
|
||||
auth,
|
||||
leaving_official,
|
||||
@@ -1006,6 +1033,7 @@ fn contract_of(
|
||||
catalog: Option<&[u8]>,
|
||||
prepared: &Prepared,
|
||||
official_login: Option<&str>,
|
||||
openai_route: bool,
|
||||
) -> Contract {
|
||||
let base_url = match target {
|
||||
Target::Proxy { base_url, .. } => *base_url,
|
||||
@@ -1037,7 +1065,7 @@ fn contract_of(
|
||||
.iter()
|
||||
.map(|(path, value)| serde_json::json!([path.join("."), value_text(value)]))
|
||||
.collect();
|
||||
let parts = serde_json::json!({
|
||||
let mut parts = serde_json::json!({
|
||||
"app": "codex",
|
||||
"version": CONTRACT_VERSION,
|
||||
"url": base_url,
|
||||
@@ -1050,6 +1078,10 @@ fn contract_of(
|
||||
"managed": prepared.target_login.as_ref().map(|(account, _)| account),
|
||||
"login": official_login,
|
||||
});
|
||||
// 第三方路由按登录写成内置 openai:和以前只写 custom 表的契约区分开,升级后接上时重写一次。
|
||||
if openai_route {
|
||||
parts["openai_route"] = Value::Bool(true);
|
||||
}
|
||||
let key = digest(Some(
|
||||
&serde_json::to_vec(&parts).expect("contract parts serialize"),
|
||||
))
|
||||
@@ -1220,6 +1252,12 @@ pub(crate) fn run_with_edits(
|
||||
}
|
||||
};
|
||||
let mut config = planned.config;
|
||||
if let Some(base_url) = planned.openai_route.filter(|_| login) {
|
||||
config.route = RouteWrite::OfficialProxy {
|
||||
base_url,
|
||||
unified: false,
|
||||
};
|
||||
}
|
||||
if let (Some(kind), RouteWrite::Custom(table)) = (planned.stamp, &mut config.route) {
|
||||
if matches!(kind, RouteAuth::Bearer | RouteAuth::EnvKey) {
|
||||
table.insert(
|
||||
|
||||
Reference in New Issue
Block a user