A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
//! Qoder's native custom-provider schema (`settings.json.providers`).
//! 供应商卡片存在供应商表里(同 Kimi):「添加」把卡片写进所选版本的 `providers`,
//! 「默认」是 `model.name`(`auto` 是 Qoder 官方自动选模,其余是 `<供应商>/<模型>`)。
//! 账号的运行权限仍归 Qoder 管:这里只改本地配置,不碰登录态。
use crate::{
error::AppError,
jsonc_document::JsoncDocument,
qoder_config::{self, QoderEdition},
};
use indexmap::IndexMap;
use serde_json::{json, Value};
use std::{
collections::HashSet,
fs,
path::{Path, PathBuf},
};
/// Qoder 官方自动选模。
pub(crate) const AUTO_MODEL: &str = "auto";
fn settings_path(edition: QoderEdition) -> PathBuf {
qoder_config::data_dir(edition).join("settings.json")
}
fn read(path: &Path) -> Result<JsoncDocument, AppError> {
let text = match fs::read_to_string(path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => "{}".into(),
Err(error) => return Err(AppError::io(path, error)),
};
let document = JsoncDocument::parse(text.trim_start_matches('\u{feff}'))?;
for field in ["providers", "model"] {
if document.root_key_count(field)? > 1 {
return Err(AppError::Config(format!(
"Qoder settings contain duplicate '{field}' keys"
)));
}
if document
.value()
.get(field)
.is_some_and(|value| !value.is_object())
{
return Err(AppError::Config(format!(
"Qoder '{field}' must be an object"
)));
}
}
if let Some(providers) = document.value().get("providers").and_then(Value::as_object) {
for provider in providers.values() {
if !provider.is_object()
|| provider
.get("models")
.is_some_and(|models| !models.is_array())
{
return Err(AppError::Config(
"Qoder providers must be objects with an optional model array".into(),
));
}
if provider
.get("models")
.and_then(Value::as_array)
.is_some_and(|models| {
models
.iter()
.any(|model| !model.get("model").is_some_and(Value::is_string))
})
{
return Err(AppError::Config(
"Each Qoder model must declare a string model ID".into(),
));
}
}
}
Ok(document)
}
fn lock(edition: QoderEdition) -> Result<std::sync::MutexGuard<'static, ()>, AppError> {
qoder_config::settings_write_lock(edition)
.lock()
.map_err(|error| AppError::Message(error.to_string()))
}
fn providers_in(document: &Value) -> IndexMap<String, Value> {
document
.get("providers")
.and_then(Value::as_object)
.map(|providers| {
providers
.iter()
.map(|(id, provider)| (id.clone(), provider.clone()))
.collect()
})
.unwrap_or_default()
}
fn current_model_in(document: &Value) -> String {
document
.pointer("/model/name")
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.unwrap_or(AUTO_MODEL)
.into()
}
/// 所选版本 settings.json 里的自带供应商(按文件顺序)。
pub(crate) fn providers(edition: QoderEdition) -> Result<IndexMap<String, Value>, AppError> {
let _guard = lock(edition)?;
Ok(providers_in(read(&settings_path(edition))?.value()))
}
/// 所选版本的默认模型(`model.name`,没写时是 `auto`)。
pub(crate) fn current_model(edition: QoderEdition) -> Result<String, AppError> {
let _guard = lock(edition)?;
Ok(current_model_in(read(&settings_path(edition))?.value()))
}
/// 默认模型属于哪家自带供应商:供应商 ID 不含 `/`,所以按第一个 `/` 切。
pub(crate) fn model_owner(model: &str) -> Option<&str> {
model
.split_once('/')
.map(|(id, _)| id)
.filter(|id| !id.is_empty())
}
/// 保序改写所选版本的 settings.json,再提交库;提交失败时把文件还回去。
pub(crate) fn change_and_commit<T>(
edition: QoderEdition,
change: impl FnOnce(&mut Value) -> Result<(), AppError>,
commit: impl FnOnce() -> Result<T, AppError>,
) -> Result<T, AppError> {
let _guard = lock(edition)?;
change_file_and_commit(&settings_path(edition), change, commit)
}
fn change_file_and_commit<T>(
path: &Path,
change: impl FnOnce(&mut Value) -> Result<(), AppError>,
commit: impl FnOnce() -> Result<T, AppError>,
) -> Result<T, AppError> {
crate::mcode_config::write_and_commit(
path,
|| {
let mut document = read(path)?;
let mut next = document.value().clone();
change(&mut next)?;
qoder_config::write_settings(path, &mut document, &mut next)
},
commit,
)
}
/// 写入(或替换)一家供应商。默认模型指着它、但改完后它已经没有那个模型时,
/// 改指向它的默认模型,免得 Qoder 启动时找不到模型。
pub(crate) fn put_provider_in(
document: &mut Value,
id: &str,
provider: Value,
) -> Result<(), AppError> {
if document.get("providers").is_none() {
document["providers"] = json!({});
}
let current = current_model_in(document);
let default = default_model(&provider)
.ok_or_else(|| AppError::InvalidInput("Add a Qoder model first".into()))?
.to_string();
let lost_default = current
.strip_prefix(&format!("{id}/"))
.is_some_and(|model| !has_model(&provider, model));
document["providers"][id] = provider;
if lost_default {
set_model_in(document, &format!("{id}/{default}"))?;
}
Ok(())
}
/// 从 settings.json 拿掉一家供应商;默认模型指着它时拒绝(先把别的设为默认)。
pub(crate) fn remove_provider_in(document: &mut Value, id: &str) -> Result<(), AppError> {
if model_owner(¤t_model_in(document)) == Some(id) {
return Err(AppError::localized(
"qoder.provider.defaultCannotRemove",
"这家是 Qoder 的默认模型,先把别的设为默认再移除",
"This provider holds Qoder's default model. Set another default before removing it",
));
}
if let Some(providers) = document.get_mut("providers").and_then(Value::as_object_mut) {
providers.remove(id);
}
Ok(())
}
/// 改默认模型:`auto` 或 settings.json 里已有的 `<供应商>/<模型>`。
pub(crate) fn set_model(edition: QoderEdition, model: &str) -> Result<(), AppError> {
change_and_commit(edition, |document| set_model_in(document, model), || Ok(()))
}
pub(crate) fn set_model_in(document: &mut Value, model: &str) -> Result<(), AppError> {
if model != AUTO_MODEL && model != current_model_in(document) {
let (id, model_id) = model
.split_once('/')
.ok_or_else(|| AppError::InvalidInput("Select an available Qoder model".into()))?;
let provider = document
.get("providers")
.and_then(|providers| providers.get(id))
.ok_or_else(|| {
AppError::InvalidInput("Add this provider to Qoder before using its model".into())
})?;
validate_provider(id, provider)?;
if !has_model(provider, model_id) {
return Err(AppError::InvalidInput(
"Qoder model is no longer configured; refresh the provider list".into(),
));
}
}
if document.get("model").is_none() {
document["model"] = json!({});
}
document["model"]["name"] = json!(model);
Ok(())
}
/// 供应商的默认模型:`model`,没写时取模型列表的第一个。
pub(crate) fn default_model(provider: &Value) -> Option<&str> {
provider
.get("model")
.and_then(Value::as_str)
.filter(|value| !value.trim().is_empty())
.or_else(|| {
provider
.get("models")?
.as_array()?
.first()?
.get("model")?
.as_str()
})
}
pub(crate) fn has_model(provider: &Value, id: &str) -> bool {
provider.get("model").and_then(Value::as_str) == Some(id)
|| provider
.get("models")
.and_then(Value::as_array)
.is_some_and(|models| {
models
.iter()
.any(|model| model.get("model").and_then(Value::as_str) == Some(id))
})
}
pub fn validate_provider(id: &str, provider: &Value) -> Result<(), AppError> {
let invalid = |message: &str| AppError::InvalidInput(message.into());
if id.is_empty()
|| !id.starts_with(|character: char| character.is_ascii_alphanumeric())
|| !id.chars().all(|character| {
character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-')
})
|| matches!(id, "qoder" | "constructor" | "prototype")
{
return Err(invalid("Provider ID must start with a letter or digit and contain only letters, digits, '.', '_' or '-'; reserved IDs are not allowed"));
}
let object = provider
.as_object()
.ok_or_else(|| invalid("Qoder provider must be an object"))?;
for (field, options) in [
(
"type",
&["openai-compatible", "alibaba", "aliyun-bailian"][..],
),
("protocol", &["openai", "openai-responses", "anthropic"][..]),
("authType", &["bearer", "api-key"][..]),
] {
if object
.get(field)
.is_some_and(|value| !value.as_str().is_some_and(|value| options.contains(&value)))
{
return Err(invalid(&format!("Select a supported Qoder {field}")));
}
}
let url = object
.get("baseUrl")
.and_then(Value::as_str)
.and_then(|value| url::Url::parse(value).ok());
if !url.is_some_and(|url| {
matches!(url.scheme(), "http" | "https")
&& url.host_str().is_some()
&& url.username().is_empty()
&& url.password().is_none()
&& url.query().is_none()
&& url.fragment().is_none()
}) {
return Err(invalid(
"Enter an HTTP(S) base URL without credentials, query parameters or a fragment",
));
}
let key = object
.get("apiKey")
.and_then(Value::as_str)
.ok_or_else(|| {
invalid(
"Enter an API key, an environment reference, or an empty key for a local service",
)
})?;
if key.chars().any(char::is_control)
|| (matches!(
object.get("type").and_then(Value::as_str),
Some("alibaba" | "aliyun-bailian")
) && key.trim().is_empty())
{
return Err(invalid("Enter a valid API key"));
}
for field in [
"image",
"contextWindow",
"maxOutputTokens",
"temperature",
"top_p",
"topP",
"top_k",
"topK",
"thinking",
"reasoning",
"generation",
"preserve_thinking",
"preserveThinking",
] {
if object.contains_key(field) {
return Err(invalid(&format!("Qoder does not support provider-level '{field}'; configure model capabilities and token limits on each model")));
}
}
let mut ids = HashSet::new();
if let Some(models) = object.get("models") {
for model in models
.as_array()
.ok_or_else(|| invalid("Qoder models must be an array"))?
{
let model_object = model
.as_object()
.ok_or_else(|| invalid("Each Qoder model must be an object"))?;
let id = model
.get("model")
.and_then(Value::as_str)
.filter(|value| {
!value.trim().is_empty()
&& value.trim() == *value
&& !value.chars().any(char::is_control)
})
.ok_or_else(|| invalid("Enter a model ID"))?;
if !ids.insert(id) {
return Err(invalid("Model IDs must be unique within a provider"));
}
for field in ["contextWindow", "maxOutputTokens"] {
if model_object.get(field).is_some_and(|value| {
!value
.as_u64()
.is_some_and(|value| value > 0 && value <= 9_007_199_254_740_991)
}) {
return Err(invalid("Model token limits must be positive integers"));
}
}
for field in [
"maxTokens",
"temperature",
"top_p",
"topP",
"top_k",
"topK",
"thinking",
"reasoning",
"generation",
"preserve_thinking",
"preserveThinking",
] {
if model_object.contains_key(field) {
return Err(invalid(&format!("Qoder does not support model-level '{field}'; use maxOutputTokens and capabilities instead")));
}
}
if let Some(capabilities) = model.get("capabilities") {
let capabilities = capabilities
.as_object()
.ok_or_else(|| invalid("Model capabilities must be an object"))?;
for field in ["tools", "vision", "cacheControl"] {
if capabilities
.get(field)
.is_some_and(|value| !value.is_boolean())
{
return Err(invalid("Model capability switches must be boolean"));
}
}
if let Some(thinking) = capabilities.get("thinking") {
let thinking = thinking
.as_object()
.ok_or_else(|| invalid("Thinking capabilities must be an object"))?;
if !thinking
.get("modes")
.and_then(Value::as_array)
.is_some_and(|modes| {
modes
.iter()
.all(|mode| matches!(mode.as_str(), Some("enabled" | "adaptive")))
})
{
return Err(invalid("Choose valid thinking modes: enabled or adaptive"));
}
}
}
}
}
if default_model(provider)
.is_none_or(|model| model.trim().is_empty() || model.chars().any(char::is_control))
{
return Err(invalid(
"Add at least one model or specify a default model ID",
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn provider() -> Value {
json!({"displayName":"Example","protocol":"openai-responses","baseUrl":"https://example.test/v1","apiKey":"${EXAMPLE_API_KEY}","model":"vendor/model-one","models":[{"model":"vendor/model-one","contextWindow":128000,"maxOutputTokens":8192,"capabilities":{"tools":true,"vision":false,"thinking":{"modes":[]}},"customNativeOption":"keep"}],"routing":{"summary":"vendor/model-one"}})
}
#[test]
fn qoder_models_write_native_providers_and_select_models_preserving_jsonc() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("settings.json");
fs::write(&path, "{\n // native settings\n \"model\": {\"name\": \"auto\", \"reasoningEffort\": \"high\"},\n \"mcpServers\": {\"local\": {\"command\": \"node\"}},\n \"skills\": {\"custom\": true},\n \"modelConfigs\": {\"customModels\": [{\"provider\":\"legacy\"}]},\n \"providers\": {\"other\": {\"model\":\"native\",\"apiKey\":\"untouched\"}}\n}\n").unwrap();
let before = read(&path).unwrap().value().clone();
validate_provider("example", &provider()).unwrap();
change_file_and_commit(
&path,
|document| {
put_provider_in(document, "example", provider())?;
set_model_in(document, "example/vendor/model-one")
},
|| Ok(()),
)
.unwrap();
let source = fs::read_to_string(&path).unwrap();
assert!(source.contains("// native settings"));
let saved = read(&path).unwrap();
assert_eq!(current_model_in(saved.value()), "example/vendor/model-one");
for field in ["mcpServers", "skills", "modelConfigs"] {
assert_eq!(saved.value()[field], before[field]);
}
assert_eq!(
saved.value()["providers"]["other"],
before["providers"]["other"]
);
assert_eq!(saved.value()["model"]["reasoningEffort"], "high");
assert_eq!(saved.value()["providers"]["example"], provider());
assert_eq!(
providers_in(saved.value()).keys().collect::<Vec<_>>(),
["other", "example"]
);
}
#[test]
fn qoder_settings_survive_failed_commits_and_invalid_files() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("settings.json");
let original =
json!({"providers":{"example":provider()},"model":{"name":"example/vendor/model-one"}})
.to_string();
fs::write(&path, &original).unwrap();
// 默认模型指着的供应商不能移除
assert!(change_file_and_commit(
&path,
|document| remove_provider_in(document, "example"),
|| Ok(())
)
.is_err());
// 库提交失败时文件还原
assert!(change_file_and_commit(
&path,
|document| set_model_in(document, AUTO_MODEL),
|| Err::<(), _>(AppError::Message("db".into()))
)
.is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), original);
for malformed in [
"broken JSON",
"{\"providers\":[]}",
"{\"model\":null}",
"{\"providers\":{},\"providers\":{}}",
] {
fs::write(&path, malformed).unwrap();
assert!(change_file_and_commit(&path, |_| Ok(()), || Ok(())).is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), malformed);
}
}
#[test]
fn qoder_native_model_validation_rejects_unusable_settings() {
for (field, value) in [
("protocol", json!("gemini")),
("authType", json!("custom")),
("baseUrl", json!("https://user:[email protected]/v1")),
("baseUrl", json!("https://example.test/v1?key=secret")),
("models", json!([{"model":"same"},{"model":"same"}])),
("models", json!([{"model":"model","contextWindow":1.5}])),
("models", json!([{"model":"model","maxOutputTokens":0}])),
(
"models",
json!([{"model":"model","thinking":{"modes":["enabled"]}}]),
),
] {
let mut invalid = provider();
invalid[field] = value;
assert!(validate_provider("example", &invalid).is_err(), "{field}");
}
for id in ["qoder", "constructor", "../outside", "bad/id", ""] {
assert!(validate_provider(id, &provider()).is_err());
}
let mut local = provider();
local["apiKey"] = json!("");
validate_provider("local", &local).unwrap();
}
#[test]
fn qoder_editing_active_model_keeps_default_model_valid() {
let mut document = json!({"providers":{"example":provider()},"model":{"name":"example/vendor/model-one","reasoningEffort":"high"}});
let mut edited = provider();
edited["model"] = json!("model-two");
edited["models"] = json!([{"model":"model-two"}]);
put_provider_in(&mut document, "example", edited).unwrap();
assert_eq!(document["model"]["name"], "example/model-two");
assert_eq!(document["model"]["reasoningEffort"], "high");
let before = document.clone();
assert!(set_model_in(&mut document, "missing/model").is_err());
assert_eq!(document, before);
}
}