fix(provider): 接入 Windsurf 模型拉取和格式转换

This commit is contained in:
Entropy.Xu
2026-05-18 20:04:49 +08:00
parent 0a0a8b31c7
commit 9466d92a7a
9 changed files with 949 additions and 17 deletions

View File

@@ -26,7 +26,11 @@ use crate::ai_serving::transport::{
build_openai_image_headers, build_openai_image_upstream_url,
build_standard_provider_request_headers, openai_image_transport_unsupported_reason,
resolve_grok_session_auth, resolve_openai_image_auth, GrokHeaderInput,
ProviderOpenAiImageHeadersInput, StandardProviderRequestHeadersInput, GROK_CHAT_PATH,
build_windsurf_cascade_headers, build_windsurf_cascade_request_body,
build_windsurf_cascade_upstream_url, is_windsurf_provider_transport,
local_windsurf_request_transport_unsupported_reason_with_network,
ProviderOpenAiImageHeadersInput, StandardProviderRequestHeadersInput, WINDSURF_ENVELOPE_NAME,
GROK_CHAT_PATH,
};
use crate::ai_serving::{
build_openai_image_request_body_from_gemini_image_request, gemini_request_is_image_generation,
@@ -198,11 +202,18 @@ pub(crate) async fn resolve_local_standard_candidate_payload_parts(
return None;
}
if let Some(skip_reason) = crate::ai_serving::request_pair_transport_unsupported_reason(
transport,
spec_metadata.api_format,
provider_api_format,
) {
let is_windsurf_cascade =
provider_api_format == "openai:chat" && is_windsurf_provider_transport(transport);
let transport_unsupported_reason = if is_windsurf_cascade {
local_windsurf_request_transport_unsupported_reason_with_network(transport)
} else {
crate::ai_serving::request_pair_transport_unsupported_reason(
transport,
spec_metadata.api_format,
provider_api_format,
)
};
if let Some(skip_reason) = transport_unsupported_reason {
mark_skipped_local_standard_candidate(
state,
input,
@@ -321,7 +332,7 @@ pub(crate) async fn resolve_local_standard_candidate_payload_parts(
provider_api_format,
parts.uri.path(),
upstream_is_stream,
if is_kiro_claude_cli {
if is_kiro_claude_cli || is_windsurf_cascade {
None
} else {
transport.endpoint.body_rules.as_ref()
@@ -443,6 +454,24 @@ pub(crate) async fn resolve_local_standard_candidate_payload_parts(
)
.await;
}
if is_windsurf_cascade {
return build_windsurf_cross_format_payload_parts(
state,
parts,
trace_id,
body_json,
input,
attempt,
transport,
provider_api_format,
prepared_candidate.mapped_model,
prepared_candidate.auth_header,
prepared_candidate.auth_value,
provider_request_body,
upstream_is_stream,
)
.await;
}
let upstream_url = match crate::ai_serving::planner::standard::build_standard_upstream_url(
parts,
@@ -542,6 +571,121 @@ fn apply_transport_request_body_semantics(
)
}
#[allow(clippy::too_many_arguments)]
async fn build_windsurf_cross_format_payload_parts(
state: &AppState,
parts: &http::request::Parts,
trace_id: &str,
original_body_json: &serde_json::Value,
input: &LocalStandardDecisionInput,
attempt: &LocalStandardCandidateAttempt,
transport: &Arc<GatewayProviderTransportSnapshot>,
provider_api_format: &str,
mapped_model: String,
auth_header: String,
auth_value: String,
openai_chat_request_body: Value,
upstream_is_stream: bool,
) -> Option<LocalStandardCandidatePayloadParts> {
let candidate = &attempt.eligible.candidate;
let effective_headers = input.effective_headers(&parts.headers);
let provider_request_body = match build_windsurf_cascade_request_body(
&openai_chat_request_body,
&mapped_model,
&auth_value,
transport.endpoint.body_rules.as_ref(),
Some(effective_headers),
upstream_is_stream,
) {
Some(body) => body,
None => {
mark_skipped_local_standard_candidate_with_extra_data(
state,
input,
trace_id,
candidate,
attempt.candidate_index,
&attempt.candidate_id,
"provider_request_body_build_failed",
request_body_build_failure_extra_data(
&openai_chat_request_body,
provider_api_format,
provider_api_format,
),
)
.await;
return None;
}
};
let upstream_url = match build_windsurf_cascade_upstream_url(
transport.endpoint.base_url.as_str(),
parts.uri.query(),
) {
Some(url) => url,
None => {
mark_skipped_local_standard_candidate_with_failure_diagnostic(
state,
input,
trace_id,
candidate,
attempt.candidate_index,
&attempt.candidate_id,
"upstream_url_missing",
CandidateFailureDiagnostic::upstream_url_missing(
provider_api_format,
provider_api_format,
"standard_family_windsurf_url",
),
)
.await;
return None;
}
};
let provider_request_headers = match build_windsurf_cascade_headers(
effective_headers,
&provider_request_body,
original_body_json,
transport.endpoint.header_rules.as_ref(),
&auth_header,
&auth_value,
upstream_is_stream,
) {
Some(headers) => headers,
None => {
mark_skipped_local_standard_candidate_with_failure_diagnostic(
state,
input,
trace_id,
candidate,
attempt.candidate_index,
&attempt.candidate_id,
"transport_header_rules_apply_failed",
CandidateFailureDiagnostic::header_rules_apply_failed(
provider_api_format,
provider_api_format,
"standard_family_windsurf_headers",
),
)
.await;
return None;
}
};
Some(LocalStandardCandidatePayloadParts {
auth_header,
auth_value,
mapped_model,
provider_api_format: provider_api_format.to_string(),
provider_request_body,
provider_request_headers,
upstream_url,
upstream_is_stream,
envelope_name: Some(WINDSURF_ENVELOPE_NAME),
transport: Arc::clone(transport),
transport_profile: None,
})
}
async fn resolve_local_gemini_image_to_openai_image_candidate_payload_parts(
state: &AppState,
parts: &http::request::Parts,

View File

@@ -39,10 +39,13 @@ use crate::ai_serving::transport::kiro::{
use crate::ai_serving::transport::{
build_grok_browser_headers, build_grok_upstream_url, build_kiro_cross_format_upstream_url,
build_openai_image_headers, build_openai_image_upstream_url,
build_standard_provider_request_headers,
local_standard_transport_unsupported_reason_with_network,
build_standard_provider_request_headers, build_windsurf_cascade_headers,
build_windsurf_cascade_request_body, build_windsurf_cascade_upstream_url,
is_windsurf_provider_transport, local_standard_transport_unsupported_reason_with_network,
local_windsurf_request_transport_unsupported_reason_with_network,
openai_image_transport_unsupported_reason, resolve_openai_image_auth, GrokHeaderInput,
ProviderOpenAiImageHeadersInput, StandardProviderRequestHeadersInput, GROK_CHAT_PATH,
ProviderOpenAiImageHeadersInput, StandardProviderRequestHeadersInput, WINDSURF_ENVELOPE_NAME,
GROK_CHAT_PATH,
};
use crate::ai_serving::{
ai_local_execution_contract_for_formats, request_conversion_direct_auth,
@@ -128,6 +131,8 @@ pub(crate) async fn resolve_local_openai_responses_candidate_payload_parts(
)
.await;
}
let is_windsurf_cascade =
provider_api_format == "openai:chat" && is_windsurf_provider_transport(transport);
let same_format = api_format_alias_matches(provider_api_format, &client_api_format);
let conversion_kind = request_conversion_kind(spec_metadata.api_format, provider_api_format);
@@ -139,6 +144,8 @@ pub(crate) async fn resolve_local_openai_responses_candidate_payload_parts(
local_kiro_request_transport_unsupported_reason_with_network(transport)
} else if same_format {
local_standard_transport_unsupported_reason_with_network(transport, provider_api_format)
} else if is_windsurf_cascade {
local_windsurf_request_transport_unsupported_reason_with_network(transport)
} else {
match conversion_kind {
Some(_) if is_antigravity && provider_api_format == "gemini:generate_content" => None,
@@ -302,7 +309,7 @@ pub(crate) async fn resolve_local_openai_responses_candidate_payload_parts(
upstream_is_stream,
force_body_stream_field,
transport.provider.provider_type.as_str(),
if is_kiro_claude_cli {
if is_kiro_claude_cli || is_windsurf_cascade {
None
} else {
transport.endpoint.body_rules.as_ref()
@@ -319,7 +326,7 @@ pub(crate) async fn resolve_local_openai_responses_candidate_payload_parts(
force_body_stream_field,
transport.provider.provider_type.as_str(),
provider_api_format,
if is_kiro_claude_cli {
if is_kiro_claude_cli || is_windsurf_cascade {
None
} else {
transport.endpoint.body_rules.as_ref()
@@ -447,6 +454,27 @@ pub(crate) async fn resolve_local_openai_responses_candidate_payload_parts(
)
.await;
}
if is_windsurf_cascade {
return build_windsurf_openai_responses_payload_parts(
state,
parts,
trace_id,
body_json,
input,
eligible,
candidate_index,
candidate_id,
spec_metadata.api_format,
transport,
provider_api_format,
mapped_model,
auth_header,
auth_value,
provider_request_body,
upstream_is_stream,
)
.await;
}
let Some(upstream_url) = (if is_grok && is_grok_text_provider_api_format(provider_api_format) {
Some(build_grok_upstream_url(transport, GROK_CHAT_PATH))
@@ -619,6 +647,130 @@ pub(crate) async fn resolve_local_openai_responses_candidate_payload_parts(
})
}
#[allow(clippy::too_many_arguments)]
async fn build_windsurf_openai_responses_payload_parts(
state: &AppState,
parts: &http::request::Parts,
trace_id: &str,
original_body_json: &serde_json::Value,
input: &LocalOpenAiResponsesDecisionInput,
eligible: &EligibleLocalExecutionCandidate,
candidate_index: u32,
candidate_id: &str,
client_api_format: &str,
transport: &Arc<GatewayProviderTransportSnapshot>,
provider_api_format: &str,
mapped_model: String,
auth_header: String,
auth_value: String,
openai_chat_request_body: Value,
upstream_is_stream: bool,
) -> Option<LocalOpenAiResponsesCandidatePayloadParts> {
let candidate = &eligible.candidate;
let effective_headers = input.effective_headers(&parts.headers);
let provider_request_body = match build_windsurf_cascade_request_body(
&openai_chat_request_body,
&mapped_model,
&auth_value,
transport.endpoint.body_rules.as_ref(),
Some(effective_headers),
upstream_is_stream,
) {
Some(body) => body,
None => {
mark_skipped_local_openai_responses_candidate_with_failure_diagnostic(
state,
input,
trace_id,
candidate,
candidate_index,
candidate_id,
"provider_request_body_build_failed",
CandidateFailureDiagnostic::envelope_build_failed(
client_api_format,
provider_api_format,
"openai_responses_windsurf_cascade",
),
)
.await;
return None;
}
};
let upstream_url = match build_windsurf_cascade_upstream_url(
transport.endpoint.base_url.as_str(),
parts.uri.query(),
) {
Some(url) => url,
None => {
mark_skipped_local_openai_responses_candidate_with_failure_diagnostic(
state,
input,
trace_id,
candidate,
candidate_index,
candidate_id,
"upstream_url_missing",
CandidateFailureDiagnostic::upstream_url_missing(
client_api_format,
provider_api_format,
"openai_responses_windsurf_url",
),
)
.await;
return None;
}
};
let provider_request_headers = match build_windsurf_cascade_headers(
effective_headers,
&provider_request_body,
original_body_json,
transport.endpoint.header_rules.as_ref(),
&auth_header,
&auth_value,
upstream_is_stream,
) {
Some(headers) => headers,
None => {
mark_skipped_local_openai_responses_candidate_with_failure_diagnostic(
state,
input,
trace_id,
candidate,
candidate_index,
candidate_id,
"transport_header_rules_apply_failed",
CandidateFailureDiagnostic::header_rules_apply_failed(
client_api_format,
provider_api_format,
"openai_responses_windsurf_headers",
),
)
.await;
return None;
}
};
let (execution_strategy, conversion_mode) =
ai_local_execution_contract_for_formats(client_api_format, provider_api_format);
Some(LocalOpenAiResponsesCandidatePayloadParts {
auth_header,
auth_value,
mapped_model,
provider_api_format: provider_api_format.to_string(),
provider_request_body,
provider_request_headers,
upstream_url,
execution_strategy,
conversion_mode,
is_antigravity: false,
envelope_name: Some(WINDSURF_ENVELOPE_NAME),
upstream_is_stream,
transport: Arc::clone(transport),
transport_profile: None,
image_request_summary: None,
})
}
fn api_format_alias_matches(left: &str, right: &str) -> bool {
crate::ai_serving::api_format_alias_matches(left, right)
}

View File

@@ -426,6 +426,7 @@ mod tests {
keys: Arc<Mutex<Vec<StoredProviderCatalogKey>>>,
transports: Arc<HashMap<(String, String, String), GatewayProviderTransportSnapshot>>,
execution_results: Arc<Mutex<VecDeque<ExecutionResult>>>,
executed_plans: Arc<Mutex<Vec<ExecutionPlan>>>,
cached_models: Arc<Mutex<HashMap<(String, String), Vec<Value>>>>,
}
@@ -443,6 +444,7 @@ mod tests {
keys: Arc::new(Mutex::new(keys)),
transports: Arc::new(transports),
execution_results: Arc::new(Mutex::new(VecDeque::from(execution_results))),
executed_plans: Arc::new(Mutex::new(Vec::new())),
cached_models: Arc::new(Mutex::new(HashMap::new())),
}
}
@@ -482,8 +484,12 @@ mod tests {
async fn execute_model_fetch_execution_plan(
&self,
_plan: &ExecutionPlan,
plan: &ExecutionPlan,
) -> Result<ExecutionResult, String> {
self.executed_plans
.lock()
.expect("executed plans mutex")
.push(plan.clone());
self.execution_results
.lock()
.expect("execution result mutex")
@@ -910,6 +916,134 @@ mod tests {
);
}
#[tokio::test]
async fn model_fetch_fetches_windsurf_model_configs_and_persists_allowed_models() {
let provider = sample_provider("provider-windsurf", "windsurf");
let endpoint = StoredProviderCatalogEndpoint::new(
"endpoint-windsurf-chat".to_string(),
"provider-windsurf".to_string(),
"openai:chat".to_string(),
None,
None,
true,
)
.expect("endpoint should build")
.with_transport_fields(
"https://server.codeium.com".to_string(),
None,
None,
None,
None,
None,
None,
None,
)
.expect("endpoint transport should build");
let key = sample_key(
"key-windsurf",
"provider-windsurf",
"api_key",
&["openai:chat"],
);
let mut transport = sample_transport(
"windsurf",
"provider-windsurf",
"endpoint-windsurf-chat",
"key-windsurf",
"openai:chat",
"api_key",
Some(r#"{"provider_type":"windsurf"}"#),
);
transport.endpoint.base_url = "https://server.codeium.com".to_string();
transport.key.decrypted_api_key = "devin-session-token$abc".to_string();
let state = TestState::new(
vec![provider],
vec![endpoint],
vec![key],
HashMap::from([(
(
"provider-windsurf".to_string(),
"endpoint-windsurf-chat".to_string(),
"key-windsurf".to_string(),
),
transport,
)]),
vec![execution_result(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 summary = perform_model_fetch_once_with_state(&state)
.await
.expect("fetch should succeed");
assert_eq!(summary.succeeded, 1);
let plans = state.executed_plans.lock().expect("executed plans mutex");
assert_eq!(plans.len(), 1);
assert_eq!(
plans[0].url,
"https://server.codeium.com/exa.api_server_pb.ApiServerService/GetCascadeModelConfigs"
);
assert_eq!(plans[0].method, "POST");
assert_eq!(plans[0].provider_api_format, "windsurf:model_configs");
assert_eq!(
plans[0]
.body
.json_body
.as_ref()
.and_then(|body| body.get("metadata"))
.and_then(|metadata| metadata.get("apiKey")),
Some(&json!("devin-session-token$abc"))
);
drop(plans);
let updated = state.key("key-windsurf");
assert_eq!(
updated.allowed_models,
Some(json!(["claude-sonnet-4-6", "gpt-5.4"]))
);
assert_eq!(
updated
.upstream_metadata
.as_ref()
.and_then(|value| value.get("windsurf"))
.and_then(|value| value.get("allowed_models_count")),
Some(&json!(2))
);
assert_eq!(
updated
.upstream_metadata
.as_ref()
.and_then(|value| value.get("windsurf"))
.and_then(|value| value.get("default_model_uid")),
Some(&json!("claude-sonnet-4-6"))
);
let cached = state.cached_models.lock().expect("cache mutex");
let cached_models = cached
.get(&("provider-windsurf".to_string(), "key-windsurf".to_string()))
.expect("cached models should be written");
assert_eq!(
cached_models[0]["api_formats"],
json!(["openai:chat", "openai:responses", "claude:messages"])
);
}
#[tokio::test]
async fn model_fetch_failure_keeps_existing_allowed_models() {
let provider = sample_provider("provider-openai", "openai");

View File

@@ -242,6 +242,144 @@ async fn gateway_handles_admin_provider_query_models_fetches_upstream_for_select
execution_runtime_handle.abort();
}
#[tokio::test]
async fn gateway_handles_admin_provider_query_models_fetches_windsurf_model_configs() {
let execution_runtime_hits = Arc::new(Mutex::new(0usize));
let execution_runtime_hits_clone = Arc::clone(&execution_runtime_hits);
let execution_runtime = Router::new().route(
"/v1/execute/sync",
any(move |Json(plan): Json<ExecutionPlan>| {
let execution_runtime_hits_inner = Arc::clone(&execution_runtime_hits_clone);
async move {
*execution_runtime_hits_inner
.lock()
.expect("mutex should lock") += 1;
assert_eq!(plan.method, "POST");
assert_eq!(
plan.url,
"https://server.codeium.com/exa.api_server_pb.ApiServerService/GetCascadeModelConfigs"
);
assert_eq!(plan.client_api_format, "openai:chat");
assert_eq!(plan.provider_api_format, "windsurf:model_configs");
assert_eq!(plan.model_name.as_deref(), Some("GetCascadeModelConfigs"));
assert_eq!(
plan.headers.get("connect-protocol-version").map(String::as_str),
Some("1")
);
assert_eq!(
plan.body
.json_body
.as_ref()
.and_then(|body| body.get("metadata"))
.and_then(|metadata| metadata.get("apiKey")),
Some(&json!("devin-session-token$abc"))
);
Json(json!({
"request_id": "req-provider-query-windsurf",
"status_code": 200,
"headers": {
"content-type": "application/json"
},
"body": {
"json_body": {
"clientModelConfigs": [{
"modelUid": "claude-sonnet-4-6",
"label": "Claude Sonnet 4.6",
"provider": "anthropic",
"supportsImages": true,
"creditMultiplier": 4
}],
"defaultOverrideModelConfig": {
"modelUid": "claude-sonnet-4-6"
}
}
}
}))
}
}),
);
let (execution_runtime_url, execution_runtime_handle) = start_server(execution_runtime).await;
let mut provider = sample_provider("provider-windsurf", "Windsurf", 10);
provider.provider_type = "windsurf".to_string();
let mut windsurf_key = sample_key(
"key-windsurf-selected",
"provider-windsurf",
"openai:chat",
"devin-session-token$abc",
);
windsurf_key.auth_type = "oauth".to_string();
let provider_catalog_repository = Arc::new(InMemoryProviderCatalogReadRepository::seed(
vec![provider],
vec![StoredProviderCatalogEndpoint::new(
"endpoint-windsurf-chat".to_string(),
"provider-windsurf".to_string(),
"openai:chat".to_string(),
Some("chat".to_string()),
Some("primary".to_string()),
true,
)
.expect("endpoint should build")
.with_transport_fields(
"https://server.codeium.com".to_string(),
None,
None,
None,
None,
None,
None,
None,
)
.expect("endpoint transport should build")],
vec![windsurf_key],
));
let gateway = build_router_with_state(
build_state_with_execution_runtime_override(execution_runtime_url)
.with_data_state_for_tests(GatewayDataState::with_provider_transport_reader_for_tests(
provider_catalog_repository,
DEVELOPMENT_ENCRYPTION_KEY.to_string(),
)),
);
let (gateway_url, gateway_handle) = start_server(gateway).await;
let response = reqwest::Client::new()
.post(format!("{gateway_url}/api/admin/provider-query/models"))
.header(crate::constants::GATEWAY_HEADER, "rust-phase3b")
.header(TRUSTED_ADMIN_USER_ID_HEADER, "admin-user-123")
.header(TRUSTED_ADMIN_USER_ROLE_HEADER, "admin")
.header(TRUSTED_ADMIN_SESSION_ID_HEADER, "session-123")
.json(&json!({
"provider_id": "provider-windsurf",
"api_key_id": "key-windsurf-selected"
}))
.send()
.await
.expect("request should succeed");
assert_eq!(response.status(), StatusCode::OK);
let payload: serde_json::Value = response.json().await.expect("json body should parse");
assert_eq!(payload["success"], json!(true));
assert_eq!(payload["data"]["error"], serde_json::Value::Null);
assert_eq!(payload["data"]["from_cache"], json!(false));
let models = payload["data"]["models"]
.as_array()
.expect("models should be an array");
assert_eq!(models.len(), 1);
assert_eq!(models[0]["id"], json!("claude-sonnet-4-6"));
assert_eq!(
models[0]["api_formats"],
json!(["openai:chat", "openai:responses", "claude:messages"])
);
assert_eq!(
*execution_runtime_hits.lock().expect("mutex should lock"),
1
);
gateway_handle.abort();
execution_runtime_handle.abort();
}
#[tokio::test]
async fn gateway_handles_admin_provider_query_models_with_openai_responses_endpoint() {
let execution_runtime_hits = Arc::new(Mutex::new(0usize));

View File

@@ -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,
};

View File

@@ -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

View File

@@ -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))
);
}
}

View File

@@ -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};

View File

@@ -20,6 +20,11 @@ use crate::vertex::{
local_vertex_gemini_transport_unsupported_reason_with_network,
resolve_local_vertex_api_key_query_auth, VERTEX_API_KEY_QUERY_PARAM,
};
use crate::windsurf::{
is_windsurf_provider_transport,
local_windsurf_request_transport_unsupported_reason_with_network,
resolve_windsurf_cascade_auth,
};
use crate::GatewayProviderTransportSnapshot;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -122,6 +127,11 @@ pub fn request_conversion_transport_unsupported_reason(
if is_kiro_claude_messages_transport(transport, &transport.endpoint.api_format) {
return local_kiro_request_transport_unsupported_reason_with_network(transport);
}
if is_windsurf_provider_transport(transport)
&& normalize_api_format_alias(&transport.endpoint.api_format) == "openai:chat"
{
return local_windsurf_request_transport_unsupported_reason_with_network(transport);
}
match normalize_api_format_alias(&transport.endpoint.api_format).as_str() {
"openai:chat" => local_openai_chat_transport_unsupported_reason(transport),
@@ -202,6 +212,9 @@ fn request_direct_auth_for_provider_format(
provider_api_format: &str,
) -> Option<(String, String)> {
match normalize_api_format_alias(provider_api_format).as_str() {
"openai:chat" if is_windsurf_provider_transport(transport) => {
resolve_windsurf_cascade_auth(transport)
}
"openai:chat"
| "openai:responses"
| "openai:responses:compact"
@@ -623,6 +636,35 @@ mod tests {
));
}
#[test]
fn windsurf_openai_chat_anchor_supports_cross_format_conversion_via_cascade() {
let mut transport = transport_snapshot("windsurf", "openai:chat", "oauth", true, None);
transport.key.decrypted_api_key = "devin-session-token$abc".to_string();
transport.key.decrypted_auth_config = Some(r#"{"provider_type":"windsurf"}"#.to_string());
assert!(request_pair_allowed_for_transport(
&transport,
"claude:messages",
"openai:chat"
));
assert!(request_pair_allowed_for_transport(
&transport,
"openai:responses",
"openai:chat"
));
assert!(request_conversion_transport_supported(
&transport,
RequestConversionKind::ToOpenAIChat
));
assert_eq!(
request_conversion_direct_auth(&transport, RequestConversionKind::ToOpenAIChat),
Some((
"authorization".to_string(),
"Bearer devin-session-token$abc".to_string()
))
);
}
#[test]
fn candidate_common_transport_policy_checks_active_state_format_and_allowed_models() {
let mut transport = transport_snapshot("custom", "openai:chat", "bearer", true, None);