mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-03 01:40:21 +08:00
fix(provider): 接入 Windsurf 模型拉取和格式转换
This commit is contained in:
@@ -14,7 +14,8 @@ pub use logic::{
|
||||
aggregate_models_for_cache, apply_model_filters, build_models_fetch_url,
|
||||
endpoint_supports_rust_models_fetch, extract_error_message, json_string_list,
|
||||
merge_upstream_metadata, parse_models_response, parse_models_response_page,
|
||||
preset_models_for_provider, provider_type_uses_preset_models, select_models_fetch_endpoint,
|
||||
parse_windsurf_model_configs_response, preset_models_for_provider,
|
||||
provider_type_uses_preset_models, select_models_fetch_endpoint,
|
||||
selected_models_fetch_endpoints, ModelFetchRunSummary, ModelsFetchPage, ModelsFetchSuccess,
|
||||
};
|
||||
pub use strategy::{
|
||||
@@ -25,5 +26,5 @@ pub use transport::{
|
||||
build_antigravity_fetch_available_models_plan, build_gemini_cli_load_code_assist_plan,
|
||||
build_kiro_list_available_models_plan, build_models_fetch_execution_plan,
|
||||
build_standard_models_fetch_execution_plan, build_vertex_models_fetch_execution_plan,
|
||||
ModelFetchTransportRuntime,
|
||||
build_windsurf_model_configs_execution_plan, ModelFetchTransportRuntime,
|
||||
};
|
||||
|
||||
@@ -166,6 +166,107 @@ pub fn parse_models_response_page(
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_windsurf_model_configs_response(
|
||||
body: &Value,
|
||||
updated_at_unix_secs: u64,
|
||||
) -> Result<(ModelsFetchSuccess, Value), String> {
|
||||
let configs = body
|
||||
.get("clientModelConfigs")
|
||||
.or_else(|| body.get("client_model_configs"))
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| {
|
||||
"windsurf model configs response is missing clientModelConfigs".to_string()
|
||||
})?;
|
||||
|
||||
let mut cached_models = Vec::new();
|
||||
let mut metadata_models = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for config in configs {
|
||||
let Some(model_id) =
|
||||
windsurf_model_config_string(config, &["modelUid", "model_uid", "id", "name"])
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !seen.insert(model_id.clone()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let label = windsurf_model_config_string(config, &["label", "displayName", "display_name"]);
|
||||
let provider = windsurf_model_config_string(config, &["provider"]);
|
||||
let supports_images = config
|
||||
.get("supportsImages")
|
||||
.or_else(|| config.get("supports_images"))
|
||||
.and_then(windsurf_json_bool);
|
||||
let credit_multiplier = config
|
||||
.get("creditMultiplier")
|
||||
.or_else(|| config.get("credit_multiplier"))
|
||||
.and_then(windsurf_json_f64);
|
||||
|
||||
let mut model = serde_json::Map::new();
|
||||
model.insert("id".to_string(), json!(model_id.clone()));
|
||||
model.insert("object".to_string(), json!("model"));
|
||||
model.insert("model_uid".to_string(), json!(model_id.clone()));
|
||||
model.insert(
|
||||
"display_name".to_string(),
|
||||
json!(label.as_deref().unwrap_or(model_id.as_str())),
|
||||
);
|
||||
model.insert(
|
||||
"owned_by".to_string(),
|
||||
json!(provider.as_deref().unwrap_or("windsurf")),
|
||||
);
|
||||
model.insert(
|
||||
"api_formats".to_string(),
|
||||
json!(["openai:chat", "openai:responses", "claude:messages"]),
|
||||
);
|
||||
if let Some(supports_images) = supports_images {
|
||||
model.insert("supports_images".to_string(), json!(supports_images));
|
||||
}
|
||||
if let Some(credit_multiplier) = credit_multiplier {
|
||||
model.insert("credit_multiplier".to_string(), json!(credit_multiplier));
|
||||
}
|
||||
cached_models.push(Value::Object(model));
|
||||
|
||||
let mut metadata_model = serde_json::Map::new();
|
||||
metadata_model.insert("model_uid".to_string(), json!(model_id));
|
||||
if let Some(label) = label {
|
||||
metadata_model.insert("label".to_string(), json!(label));
|
||||
}
|
||||
if let Some(provider) = provider {
|
||||
metadata_model.insert("provider".to_string(), json!(provider));
|
||||
}
|
||||
if let Some(supports_images) = supports_images {
|
||||
metadata_model.insert("supports_images".to_string(), json!(supports_images));
|
||||
}
|
||||
if let Some(credit_multiplier) = credit_multiplier {
|
||||
metadata_model.insert("credit_multiplier".to_string(), json!(credit_multiplier));
|
||||
}
|
||||
metadata_models.push(Value::Object(metadata_model));
|
||||
}
|
||||
|
||||
let mut windsurf_metadata = serde_json::Map::new();
|
||||
windsurf_metadata.insert("updated_at".to_string(), json!(updated_at_unix_secs));
|
||||
windsurf_metadata.insert(
|
||||
"allowed_models_count".to_string(),
|
||||
json!(metadata_models.len() as u64),
|
||||
);
|
||||
windsurf_metadata.insert("models".to_string(), Value::Array(metadata_models));
|
||||
if let Some(default_model_uid) = body
|
||||
.get("defaultOverrideModelConfig")
|
||||
.or_else(|| body.get("default_override_model_config"))
|
||||
.and_then(|config| windsurf_model_config_string(config, &["modelUid", "model_uid"]))
|
||||
{
|
||||
windsurf_metadata.insert("default_model_uid".to_string(), json!(default_model_uid));
|
||||
}
|
||||
|
||||
Ok((
|
||||
ModelsFetchSuccess {
|
||||
fetched_model_ids: collect_cached_model_ids(&cached_models),
|
||||
cached_models,
|
||||
},
|
||||
json!({ "windsurf": windsurf_metadata }),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn selected_models_fetch_endpoints(
|
||||
endpoints: &[StoredProviderCatalogEndpoint],
|
||||
key: &StoredProviderCatalogKey,
|
||||
@@ -561,6 +662,53 @@ fn model_id_from_openai_like_item(item: &Value) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
fn windsurf_model_config_string(value: &Value, fields: &[&str]) -> Option<String> {
|
||||
fields.iter().find_map(|field| {
|
||||
value
|
||||
.get(*field)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
})
|
||||
}
|
||||
|
||||
fn windsurf_json_bool(value: &Value) -> Option<bool> {
|
||||
match value {
|
||||
Value::Bool(value) => Some(*value),
|
||||
Value::String(text) => match text.trim().to_ascii_lowercase().as_str() {
|
||||
"true" | "1" => Some(true),
|
||||
"false" | "0" => Some(false),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn windsurf_json_f64(value: &Value) -> Option<f64> {
|
||||
match value {
|
||||
Value::Number(number) => number.as_f64(),
|
||||
Value::String(text) => text.trim().parse::<f64>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_cached_model_ids(models: &[Value]) -> Vec<String> {
|
||||
let mut ids = Vec::new();
|
||||
for model in models {
|
||||
let Some(model_id) = model
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
ids.push(model_id.to_string());
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
fn split_url_query(base_url: &str) -> (&str, Option<&str>) {
|
||||
let trimmed = base_url.trim();
|
||||
trimmed
|
||||
|
||||
@@ -16,11 +16,15 @@ use rsa::RsaPrivateKey;
|
||||
use serde_json::{json, Value};
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::logic::{extract_error_message, parse_models_response_page, preset_models_for_provider};
|
||||
use crate::logic::{
|
||||
extract_error_message, parse_models_response_page, parse_windsurf_model_configs_response,
|
||||
preset_models_for_provider,
|
||||
};
|
||||
use crate::transport::{
|
||||
build_antigravity_fetch_available_models_plan, build_gemini_cli_load_code_assist_plan,
|
||||
build_kiro_list_available_models_plan, build_standard_models_fetch_execution_plan,
|
||||
build_vertex_models_fetch_execution_plan, ModelFetchTransportRuntime,
|
||||
build_vertex_models_fetch_execution_plan, build_windsurf_model_configs_execution_plan,
|
||||
ModelFetchTransportRuntime,
|
||||
};
|
||||
|
||||
const ANTIGRAVITY_SANDBOX_BASE_URL: &str = "https://daily-cloudcode-pa.sandbox.googleapis.com";
|
||||
@@ -51,6 +55,7 @@ pub enum ModelFetchStrategyKind {
|
||||
Antigravity,
|
||||
GeminiCliPreset,
|
||||
Kiro,
|
||||
Windsurf,
|
||||
}
|
||||
|
||||
pub trait ModelFetchStrategy {
|
||||
@@ -136,6 +141,7 @@ fn select_model_fetch_strategy(
|
||||
let kind = match provider_type.as_str() {
|
||||
"antigravity" => ModelFetchStrategyKind::Antigravity,
|
||||
"vertex_ai" => ModelFetchStrategyKind::Vertex,
|
||||
"windsurf" => ModelFetchStrategyKind::Windsurf,
|
||||
_ => ModelFetchStrategyKind::StandardTransport,
|
||||
};
|
||||
Ok(SelectedModelFetchStrategy {
|
||||
@@ -176,6 +182,7 @@ async fn execute_model_fetch_strategy(
|
||||
.await
|
||||
}
|
||||
ModelFetchStrategyKind::Kiro => fetch_kiro_models(runtime, first_transport).await,
|
||||
ModelFetchStrategyKind::Windsurf => fetch_windsurf_models(runtime, first_transport).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,6 +373,25 @@ async fn fetch_kiro_models(
|
||||
Ok(build_success_outcome(models, metadata, true))
|
||||
}
|
||||
|
||||
async fn fetch_windsurf_models(
|
||||
runtime: &(impl ModelFetchTransportRuntime + ?Sized),
|
||||
transport: &GatewayProviderTransportSnapshot,
|
||||
) -> Result<ModelsFetchOutcome, String> {
|
||||
let plan = build_windsurf_model_configs_execution_plan(runtime, transport).await?;
|
||||
let result = runtime.execute_model_fetch_execution_plan(&plan).await?;
|
||||
if !(200..300).contains(&result.status_code) {
|
||||
return Err(execution_result_error_message(&result));
|
||||
}
|
||||
|
||||
let body_json = execution_result_json_body_allow_empty(&result)?;
|
||||
let (models, metadata) = parse_windsurf_model_configs_response(&body_json, now_unix_secs())?;
|
||||
Ok(build_success_outcome(
|
||||
models.cached_models,
|
||||
Some(metadata),
|
||||
true,
|
||||
))
|
||||
}
|
||||
|
||||
async fn fetch_vertex_models(
|
||||
runtime: &(impl ModelFetchTransportRuntime + ?Sized),
|
||||
transports: &[GatewayProviderTransportSnapshot],
|
||||
@@ -1413,6 +1439,22 @@ mod tests {
|
||||
transport
|
||||
}
|
||||
|
||||
fn sample_windsurf_transport() -> GatewayProviderTransportSnapshot {
|
||||
let mut transport = sample_custom_aiplatform_transport();
|
||||
transport.provider.provider_type = "windsurf".to_string();
|
||||
transport.provider.name = "Windsurf".to_string();
|
||||
transport.endpoint.api_format = "openai:chat".to_string();
|
||||
transport.endpoint.api_family = Some("openai".to_string());
|
||||
transport.endpoint.endpoint_kind = Some("chat".to_string());
|
||||
transport.endpoint.base_url = "https://server.codeium.com".to_string();
|
||||
transport.endpoint.custom_path = None;
|
||||
transport.key.auth_type = "oauth".to_string();
|
||||
transport.key.api_formats = Some(vec!["openai:chat".to_string()]);
|
||||
transport.key.decrypted_api_key = "devin-session-token$abc".to_string();
|
||||
transport.key.decrypted_auth_config = Some(r#"{"provider_type":"windsurf"}"#.to_string());
|
||||
transport
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strategy_selection_keeps_codex_on_standard_transport_fetch() {
|
||||
let strategy = select_model_fetch_strategy(&[sample_codex_transport()])
|
||||
@@ -1443,6 +1485,15 @@ mod tests {
|
||||
assert_eq!(strategy.kind(), ModelFetchStrategyKind::Kiro);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strategy_selection_uses_windsurf_model_configs_fetch() {
|
||||
let strategy = select_model_fetch_strategy(&[sample_windsurf_transport()])
|
||||
.expect("strategy should select");
|
||||
|
||||
assert_eq!(strategy.provider_id(), "windsurf");
|
||||
assert_eq!(strategy.kind(), ModelFetchStrategyKind::Windsurf);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_aiplatform_transport_uses_vertex_models_fetch_path_and_normalizes_chat_format()
|
||||
{
|
||||
@@ -1629,4 +1680,57 @@ mod tests {
|
||||
Some(&json!("auto"))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn windsurf_transport_fetches_cascade_model_configs() {
|
||||
let executed_urls = Arc::new(Mutex::new(Vec::new()));
|
||||
let runtime = TestRuntime {
|
||||
executed_urls: Arc::clone(&executed_urls),
|
||||
response_body: json!({
|
||||
"clientModelConfigs": [
|
||||
{
|
||||
"modelUid": "claude-sonnet-4-6",
|
||||
"label": "Claude Sonnet 4.6",
|
||||
"provider": "anthropic",
|
||||
"supportsImages": true,
|
||||
"creditMultiplier": 4
|
||||
},
|
||||
{
|
||||
"modelUid": "gpt-5.4",
|
||||
"label": "GPT-5.4",
|
||||
"provider": "openai"
|
||||
}
|
||||
],
|
||||
"defaultOverrideModelConfig": {
|
||||
"modelUid": "claude-sonnet-4-6"
|
||||
}
|
||||
}),
|
||||
};
|
||||
let outcome = fetch_models_from_transports(&runtime, &[sample_windsurf_transport()])
|
||||
.await
|
||||
.expect("models fetch should succeed");
|
||||
|
||||
let urls = executed_urls.lock().expect("executed_urls lock");
|
||||
assert_eq!(
|
||||
urls.as_slice(),
|
||||
&["https://server.codeium.com/exa.api_server_pb.ApiServerService/GetCascadeModelConfigs"]
|
||||
);
|
||||
assert_eq!(
|
||||
outcome.fetched_model_ids,
|
||||
vec!["claude-sonnet-4-6".to_string(), "gpt-5.4".to_string()]
|
||||
);
|
||||
assert_eq!(outcome.cached_models.len(), 2);
|
||||
assert_eq!(
|
||||
outcome.cached_models[0]["api_formats"],
|
||||
json!(["openai:chat", "openai:responses", "claude:messages"])
|
||||
);
|
||||
assert_eq!(
|
||||
outcome.upstream_metadata.as_ref().and_then(|value| {
|
||||
value
|
||||
.get("windsurf")
|
||||
.and_then(|value| value.get("allowed_models_count"))
|
||||
}),
|
||||
Some(&json!(2))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ use aether_provider_transport::kiro::{
|
||||
resolve_local_kiro_request_auth,
|
||||
};
|
||||
use aether_provider_transport::vertex::resolve_local_vertex_api_key_query_auth;
|
||||
use aether_provider_transport::windsurf::resolve_windsurf_cascade_auth;
|
||||
use aether_provider_transport::{
|
||||
apply_local_header_rules, resolve_transport_execution_timeouts, resolve_transport_profile,
|
||||
GatewayProviderTransportSnapshot, LocalResolvedOAuthRequestAuth,
|
||||
@@ -30,6 +31,10 @@ const CLAUDE_VERSION_HEADER: &str = "2023-06-01";
|
||||
const ANTIGRAVITY_FETCH_PROVIDER_API_FORMAT: &str = "antigravity:fetch_available_models";
|
||||
const GEMINI_CLI_LOAD_CODE_ASSIST_PROVIDER_API_FORMAT: &str = "gemini_cli:load_code_assist";
|
||||
const KIRO_LIST_AVAILABLE_MODELS_PROVIDER_API_FORMAT: &str = "kiro:list_available_models";
|
||||
const WINDSURF_MODEL_CONFIGS_PROVIDER_API_FORMAT: &str = "windsurf:model_configs";
|
||||
const WINDSURF_MODEL_CONFIGS_PATH: &str =
|
||||
"/exa.api_server_pb.ApiServerService/GetCascadeModelConfigs";
|
||||
const WINDSURF_IDE_VERSION: &str = "1.9600.41";
|
||||
|
||||
const BROWSER_FINGERPRINT_HEADERS: &[(&str, &str)] = &[
|
||||
(
|
||||
@@ -295,6 +300,60 @@ pub async fn build_kiro_list_available_models_plan(
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn build_windsurf_model_configs_execution_plan(
|
||||
runtime: &(impl ModelFetchTransportRuntime + ?Sized),
|
||||
transport: &GatewayProviderTransportSnapshot,
|
||||
) -> Result<ExecutionPlan, String> {
|
||||
let (_, auth_value) = resolve_windsurf_cascade_auth(transport)
|
||||
.or_else(|| resolve_local_openai_bearer_auth(transport))
|
||||
.ok_or_else(|| "Windsurf models fetch requires apiKey/sessionToken".to_string())?;
|
||||
let api_key = auth_secret_from_header_value(&auth_value);
|
||||
if api_key.is_empty() {
|
||||
return Err("Windsurf models fetch requires apiKey/sessionToken".to_string());
|
||||
}
|
||||
|
||||
let headers = BTreeMap::from([
|
||||
("content-type".to_string(), "application/json".to_string()),
|
||||
("accept".to_string(), "application/json".to_string()),
|
||||
("connect-protocol-version".to_string(), "1".to_string()),
|
||||
(
|
||||
"user-agent".to_string(),
|
||||
format!("windsurf/{WINDSURF_IDE_VERSION}"),
|
||||
),
|
||||
]);
|
||||
let headers = apply_fetch_header_rules(transport, headers, &[])?;
|
||||
let url = format!(
|
||||
"{}{}",
|
||||
transport.endpoint.base_url.trim_end_matches('/'),
|
||||
WINDSURF_MODEL_CONFIGS_PATH
|
||||
);
|
||||
|
||||
build_execution_plan(
|
||||
runtime,
|
||||
transport,
|
||||
ModelFetchExecutionPlanRequest {
|
||||
method: "POST".to_string(),
|
||||
url,
|
||||
headers,
|
||||
content_type: Some("application/json".to_string()),
|
||||
body: RequestBody::from_json(json!({
|
||||
"metadata": {
|
||||
"apiKey": api_key,
|
||||
"ideName": "windsurf",
|
||||
"ideVersion": WINDSURF_IDE_VERSION,
|
||||
"extensionName": "windsurf",
|
||||
"extensionVersion": WINDSURF_IDE_VERSION,
|
||||
"locale": "en",
|
||||
}
|
||||
})),
|
||||
client_api_format: "openai:chat".to_string(),
|
||||
provider_api_format: WINDSURF_MODEL_CONFIGS_PROVIDER_API_FORMAT.to_string(),
|
||||
model_name: Some("GetCascadeModelConfigs".to_string()),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn build_vertex_models_fetch_execution_plan(
|
||||
runtime: &(impl ModelFetchTransportRuntime + ?Sized),
|
||||
transport: &GatewayProviderTransportSnapshot,
|
||||
@@ -586,6 +645,16 @@ fn insert_non_empty_auth_header(
|
||||
headers.insert(name.to_string(), value.to_string());
|
||||
}
|
||||
|
||||
fn auth_secret_from_header_value(auth_value: &str) -> String {
|
||||
auth_value
|
||||
.trim()
|
||||
.strip_prefix("Bearer ")
|
||||
.or_else(|| auth_value.trim().strip_prefix("bearer "))
|
||||
.unwrap_or_else(|| auth_value.trim())
|
||||
.trim()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use aether_contracts::{ExecutionPlan, ExecutionResult, ProxySnapshot};
|
||||
|
||||
Reference in New Issue
Block a user