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
34 changes: 25 additions & 9 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ impl AppState {
config.upstream_url(Provider::Anthropic),
);
upstream_urls.insert(Provider::Minimax, config.upstream_url(Provider::Minimax));
upstream_urls.insert(Provider::Opencode, config.upstream_url(Provider::Opencode));

// Build key mappings for both static and OAuth keys
let mut key_mappings: BTreeMap<String, ResolvedKey> = BTreeMap::new();
Expand Down Expand Up @@ -1021,16 +1022,20 @@ async fn maybe_translate_response(
None => return Ok(response),
};

let is_streaming = stream_requested
|| response
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.is_some_and(|ct| ct.contains("text/event-stream"));
let upstream_is_sse = response
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.is_some_and(|ct| ct.contains("text/event-stream"));

debug!(format = ?format, is_streaming, "maybe_translate_response: translating response");
debug!(
format = ?format,
stream_requested,
upstream_is_sse,
"maybe_translate_response: translating response"
);

if is_streaming {
if stream_requested {
let (parts, body) = response.into_parts();
let translated_body = match format {
crate::oauth::ResponseFormat::ResponsesApi => {
Expand All @@ -1056,9 +1061,20 @@ async fn maybe_translate_response(

match format {
crate::oauth::ResponseFormat::ResponsesApi => {
match crate::translate::responses_to_chat_completion(&body_bytes) {
let translated = if upstream_is_sse {
crate::translate::responses_sse_to_chat_completion(&body_bytes)
} else {
crate::translate::responses_to_chat_completion(&body_bytes)
};

match translated {
Ok(translated) => {
parts.headers.remove("content-type");
parts.headers.remove("content-length");
parts.headers.insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("application/json"),
);
Ok(Response::from_parts(parts, Body::from(translated)))
}
Err(e) => {
Expand Down
53 changes: 53 additions & 0 deletions src/app/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -996,6 +996,59 @@ async fn test_openai_and_openrouter_keys_map_to_distinct_real_keys() {
assert_eq!(openrouter_resp.status(), StatusCode::OK);
}

#[tokio::test]
async fn test_opencode_key_uses_zen_upstream() {
let mock_server = MockServer::start().await;

Mock::given(method("POST"))
.and(path("/v1/chat/completions"))
.and(header("authorization", "Bearer sk-opencode-real"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"provider": "opencode"
})))
.mount(&mock_server)
.await;

let mut key_map = BTreeMap::new();
key_map.insert(
"vk-opencode".to_string(),
ResolvedKey {
source: KeySource::Static {
real_key: "sk-opencode-real".to_string(),
},
provider: Provider::Opencode,
},
);

let mut upstream_urls = BTreeMap::new();
upstream_urls.insert(Provider::Opencode, mock_server.uri());

let app = build_router(AppState {
key_manager: Arc::new(KeyManager::new(key_map)),
dlp_scanner: Arc::new(DlpScanner::new(&[], false).unwrap()),
proxy_client: Arc::new(ProxyClient::with_upstream_urls(
upstream_urls,
"2023-06-01".to_string(),
)),
oauth_registry: Arc::new(OAuthRegistry::new(Default::default())),
email_enabled: false,
email_policy: None,
email_accounts: Arc::new(BTreeMap::new()),
email_service: Arc::new(EmailService::mock_disabled()),
stats: Arc::new(Stats::new(None)),
});

let req = Request::builder()
.method("POST")
.uri("/v1/chat/completions")
.header("authorization", "Bearer vk-opencode")
.header("content-type", "application/json")
.body(Body::from("{}"))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}

// ========== DLP Redaction Tests ==========

fn make_app_with_redact(upstream_url: &str) -> axum::Router {
Expand Down
11 changes: 11 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub enum Provider {
Openrouter,
Anthropic,
Minimax,
Opencode,
}

impl Provider {
Expand All @@ -21,6 +22,7 @@ impl Provider {
Provider::Openrouter => "https://openrouter.ai/api",
Provider::Anthropic => "https://api.anthropic.com",
Provider::Minimax => "https://api.minimax.io",
Provider::Opencode => "https://opencode.ai/zen",
}
}
}
Expand Down Expand Up @@ -82,6 +84,10 @@ pub struct UpstreamConfig {
pub anthropic_version: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub minimax_base_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub opencode_zen_base_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub opencode_go_base_url: Option<String>,
}

fn default_anthropic_version() -> String {
Expand Down Expand Up @@ -445,6 +451,11 @@ impl Config {
.minimax_base_url
.clone()
.unwrap_or_else(|| Provider::Minimax.default_base_url().to_string()),
Provider::Opencode => self
.upstream
.opencode_zen_base_url
.clone()
.unwrap_or_else(|| Provider::Opencode.default_base_url().to_string()),
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl ProxyClient {

// Inject the real API key based on provider
match provider {
Provider::Openai | Provider::Openrouter | Provider::Minimax => {
Provider::Openai | Provider::Openrouter | Provider::Minimax | Provider::Opencode => {
req_headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", real_key))
Expand Down
Loading
Loading