feat(byok): add external API for local apps

This commit is contained in:
leokun committed 2026-09-28 19:06:50 +08:00
1 parent 2068ab2051
commit 9a8fde279c
26 files changed
+2920 -74

No files matched your search

+379
View File
@@ -0,0 +1,379 @@
//! Forwards matching HTTP protocols without projecting provider messages.
use std::time::Duration;
use async_stream::try_stream;
use axum::{
body::Body,
http::{header, HeaderMap, StatusCode},
response::Response,
};
use bytes::Bytes;
use eventsource_stream::Eventsource;
use futures_util::StreamExt;
use serde_json::Value;
use tokio_stream::wrappers::ReceiverStream;
use crate::{
model::{ModelConfig, NewLlmCall, Usage},
network::NetworkClients,
provider::{custom_headers, CallRecorder, FinishReason},
store::Store,
Error, Result,
};
use super::protocol::Protocol;
#[derive(Clone)]
pub struct NativeForwarder {
store: Store,
clients: NetworkClients,
request_timeout: Duration,
stream_idle_timeout: Duration,
}
impl NativeForwarder {
pub fn new(
store: Store,
clients: NetworkClients,
request_timeout: Duration,
stream_idle_timeout: Duration,
) -> Self {
Self {
store,
clients,
request_timeout,
stream_idle_timeout,
}
}
pub(super) async fn forward(
&self,
protocol: Protocol,
incoming_headers: &HeaderMap,
mut body: Value,
model: &ModelConfig,
) -> Result<Response> {
let call_id = format!("external-api:{}", uuid::Uuid::new_v4());
let request_url = model.request_url()?;
let new_call = NewLlmCall {
call_id: call_id.clone(),
run_id: call_id.clone(),
conversation_id: call_id.clone(),
provider_call_index: 0,
model_hash: model.model_hash.clone(),
provider_type: model.provider_type(),
provider_url: request_url.clone(),
request_type: model.provider_type(),
request_url: request_url.clone(),
model_id: model.model_id.clone(),
display_name: model.display_name.clone(),
reasoning_effort: model.reasoning_effort.clone(),
fast: false,
message_count: body
.get("messages")
.or_else(|| body.get("input"))
.and_then(Value::as_array)
.map_or(1, Vec::len),
tool_count: body
.get("tools")
.and_then(Value::as_array)
.map_or(0, Vec::len),
detailed: false,
};
body["model"] = Value::String(model.model_id.clone());
let mut upstream_headers = HeaderMap::new();
for (name, value) in incoming_headers {
if !matches!(
name.as_str(),
"authorization"
| "x-api-key"
| "host"
| "content-length"
| "content-type"
| "connection"
| "transfer-encoding"
| "accept-encoding"
| "cookie"
| "proxy-authorization"
| "proxy-authenticate"
| "te"
| "trailer"
| "upgrade"
) {
upstream_headers.append(name, value.clone());
}
}
if model.custom_headers_enabled {
upstream_headers.extend(custom_headers(&model.custom_headers, &call_id)?);
}
match protocol {
Protocol::Messages => {
upstream_headers.insert(
"x-api-key",
model.api_key.parse().map_err(|error| {
Error::Config(format!("invalid API key header: {error}"))
})?,
);
if !upstream_headers.contains_key("anthropic-version") {
upstream_headers.insert("anthropic-version", "2023-06-01".parse().unwrap());
}
}
Protocol::Chat | Protocol::Responses => {
upstream_headers.insert(
header::AUTHORIZATION,
format!("Bearer {}", model.api_key)
.parse()
.map_err(|error| {
Error::Config(format!("invalid API key header: {error}"))
})?,
);
}
}
let logged_headers = upstream_headers
.iter()
.filter(|(name, _)| !crate::model::is_sensitive_header(name.as_str()))
.filter_map(|(name, value)| {
value
.to_str()
.ok()
.map(|value| (name.as_str().to_owned(), Value::String(value.to_owned())))
})
.collect::<serde_json::Map<_, _>>();
let client = self.clients.provider_client(self.request_timeout).await?;
let recorder = CallRecorder::start(self.store.clone(), new_call).await?;
recorder
.request(Value::Object(logged_headers), &body)
.await?;
let response = match client
.post(&request_url)
.headers(upstream_headers)
.json(&body)
.send()
.await
{
Ok(response) => response,
Err(error) => {
let error = Error::Http(error);
recorder.failed(&error).await?;
return Err(error);
}
};
let status = response.status();
recorder.response_headers(status.as_u16()).await?;
let headers = response.headers().clone();
let stream = body.get("stream").and_then(Value::as_bool).unwrap_or(false);
if stream && status.is_success() {
Ok(self.stream_response(protocol, response, recorder, status, &headers))
} else {
let bytes = match response.bytes().await {
Ok(bytes) => bytes,
Err(error) => {
let error = Error::Http(error);
recorder.failed(&error).await?;
return Err(error);
}
};
recorder.response_chunk(&bytes).await?;
if status.is_success() {
if let Ok(value) = serde_json::from_slice::<Value>(&bytes) {
let summary = NativeSummary::from_value(protocol, &value);
if let Some(usage) = summary.usage {
recorder.usage(usage).await?;
}
if let Some(message) = summary.failure {
recorder.failed(&Error::Provider(message)).await?;
} else {
recorder
.completed(summary.finish.unwrap_or(FinishReason::Stop))
.await?;
}
} else {
recorder.completed(FinishReason::Stop).await?;
}
} else {
recorder
.failed(&Error::Provider(format!("upstream returned {status}")))
.await?;
}
Ok(build_response(status, &headers, Body::from(bytes)))
}
}
fn stream_response(
&self,
protocol: Protocol,
response: reqwest::Response,
recorder: CallRecorder,
status: StatusCode,
headers: &HeaderMap,
) -> Response {
let idle_timeout = self.stream_idle_timeout;
let output = try_stream! {
let _cancel = recorder.cancel_on_drop();
let (sender, receiver) = tokio::sync::mpsc::channel::<Bytes>(8);
let observer = tokio::spawn(observe_events(protocol, receiver));
let mut upstream = response.bytes_stream();
loop {
let next = tokio::time::timeout(idle_timeout, upstream.next()).await;
let chunk = match next {
Ok(Some(Ok(chunk))) => chunk,
Ok(None) => break,
Ok(Some(Err(error))) => {
let error = Error::Http(error);
recorder.failed(&error).await?;
Err::<Bytes, Error>(error)?
}
Err(_) => {
let error = Error::Provider("native upstream stream idle timeout".into());
recorder.failed(&error).await?;
Err::<Bytes, Error>(error)?
}
};
recorder.response_chunk(&chunk).await?;
let _ = sender.send(chunk.clone()).await;
yield chunk;
}
drop(sender);
if let Ok(summary) = observer.await {
if let Some(usage) = summary.usage { recorder.usage(usage).await?; }
if let Some(message) = summary.failure {
recorder.failed(&Error::Provider(message)).await?;
} else {
recorder.completed(summary.finish.unwrap_or(FinishReason::Stop)).await?;
}
} else {
recorder.completed(FinishReason::Stop).await?;
}
};
let output = output.map(|result: Result<Bytes>| result);
build_response(status, headers, Body::from_stream(output))
}
}
fn build_response(status: StatusCode, headers: &HeaderMap, body: Body) -> Response {
let mut response = Response::new(body);
*response.status_mut() = status;
for (name, value) in headers {
if !matches!(
name.as_str(),
"content-length" | "content-encoding" | "transfer-encoding" | "connection"
) {
response.headers_mut().append(name, value.clone());
}
}
response
}
#[derive(Default)]
struct NativeSummary {
usage: Option<Usage>,
finish: Option<FinishReason>,
failure: Option<String>,
}
impl NativeSummary {
fn from_value(protocol: Protocol, value: &Value) -> Self {
let mut summary = Self::default();
summary.observe(protocol, value);
summary
}
fn observe(&mut self, protocol: Protocol, value: &Value) {
if matches!(
value.get("type").and_then(Value::as_str),
Some("error" | "response.failed")
) || value.get("error").is_some_and(|error| !error.is_null())
{
self.failure = Some(
value
.pointer("/error/message")
.or_else(|| value.pointer("/response/error/message"))
.or_else(|| value.get("message"))
.and_then(Value::as_str)
.unwrap_or("upstream error event")
.to_owned(),
);
}
let usage = match protocol {
Protocol::Chat => value.get("usage"),
Protocol::Responses => value
.pointer("/response/usage")
.or_else(|| value.get("usage")),
Protocol::Messages => value
.pointer("/message/usage")
.or_else(|| value.get("usage")),
}
.filter(|usage| !usage.is_null())
.map(|usage| crate::provider::native_usage(protocol.provider_type(), usage));
if let Some(usage) = usage {
let current = self.usage.get_or_insert_default();
for (target, incoming) in [
(&mut current.input_tokens, usage.input_tokens),
(
&mut current.context_input_tokens,
usage.context_input_tokens,
),
(&mut current.output_tokens, usage.output_tokens),
(&mut current.total_tokens, usage.total_tokens),
(&mut current.cache_read_tokens, usage.cache_read_tokens),
(&mut current.cache_write_tokens, usage.cache_write_tokens),
(&mut current.reasoning_tokens, usage.reasoning_tokens),
] {
if incoming.is_some() {
*target = incoming;
}
}
}
let reason = match protocol {
Protocol::Chat => value
.pointer("/choices/0/finish_reason")
.and_then(Value::as_str),
Protocol::Responses => value
.pointer("/response/incomplete_details/reason")
.and_then(Value::as_str),
Protocol::Messages => value
.pointer("/delta/stop_reason")
.or_else(|| value.get("stop_reason"))
.and_then(Value::as_str),
};
self.finish = match reason {
Some("tool_calls" | "tool_use") => Some(FinishReason::ToolUse),
Some("length" | "max_tokens" | "max_output_tokens") => Some(FinishReason::Length),
Some(_) => Some(FinishReason::Stop),
None => self.finish,
};
if matches!(protocol, Protocol::Responses)
&& (value.pointer("/item/type").and_then(Value::as_str) == Some("function_call")
|| value
.pointer("/response/output")
.and_then(Value::as_array)
.is_some_and(|items| {
items.iter().any(|item| {
item.get("type").and_then(Value::as_str) == Some("function_call")
})
}))
{
self.finish = Some(FinishReason::ToolUse);
}
}
}
async fn observe_events(
protocol: Protocol,
receiver: tokio::sync::mpsc::Receiver<Bytes>,
) -> NativeSummary {
let source = ReceiverStream::new(receiver)
.map(Ok::<_, Error>)
.eventsource();
futures_util::pin_mut!(source);
let mut summary = NativeSummary::default();
while let Some(event) = source.next().await {
let Ok(event) = event else {
break;
};
if let Ok(value) = serde_json::from_str::<Value>(&event.data) {
summary.observe(protocol, &value);
}
}
summary
}
+201
View File
@@ -0,0 +1,201 @@
//! External OpenAI and Anthropic compatible API.
mod direct;
mod models;
mod output;
mod protocol;
use std::sync::Arc;
use axum::{
extract::State,
http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
};
use serde_json::{json, Value};
use tokio_util::sync::CancellationToken;
use crate::{
model::ModelInvocation, plugin::PluginRegistry, provider::Provider, store::Store, Error,
};
use self::protocol::Protocol;
pub use direct::NativeForwarder;
#[derive(Clone)]
struct ApiState {
store: Store,
plugins: PluginRegistry,
provider: Arc<dyn Provider>,
native: Option<NativeForwarder>,
}
pub fn router(
store: Store,
plugins: PluginRegistry,
provider: Arc<dyn Provider>,
native: Option<NativeForwarder>,
) -> Router {
Router::new()
.route("/byok/v1/models", get(list_models))
.route("/byok/v1/chat/completions", post(chat))
.route("/byok/v1/responses", post(responses))
.route("/byok/v1/messages", post(messages))
.with_state(ApiState {
store,
plugins,
provider,
native,
})
}
fn api_error(status: StatusCode, message: impl std::fmt::Display) -> Response {
(status, Json(json!({"error":{"message":message.to_string(),"type":if status.is_client_error() { "invalid_request_error" } else { "server_error" }}}))).into_response()
}
async fn authorized(
state: &ApiState,
headers: &HeaderMap,
) -> std::result::Result<(), Box<Response>> {
let settings = state
.store
.external_api_settings()
.await
.map_err(|error| Box::new(api_error(StatusCode::INTERNAL_SERVER_ERROR, error)))?;
if !settings.enabled {
return Err(Box::new(api_error(
StatusCode::FORBIDDEN,
"external API is disabled",
)));
}
let supplied = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.or_else(|| {
headers
.get("x-api-key")
.and_then(|value| value.to_str().ok())
})
.unwrap_or_default();
if supplied.is_empty() || !constant_time_eq(supplied.as_bytes(), settings.api_key.as_bytes()) {
return Err(Box::new(api_error(
StatusCode::UNAUTHORIZED,
"invalid API key",
)));
}
Ok(())
}
fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
if left.len() != right.len() {
return false;
}
let difference = left
.iter()
.zip(right)
.fold(0_u8, |difference, (left, right)| {
difference | (left ^ right)
});
difference == 0
}
async fn list_models(State(state): State<ApiState>, headers: HeaderMap) -> Response {
if let Err(error) = authorized(&state, &headers).await {
return *error;
}
match models::list(&state.store, &state.plugins).await {
Ok(models) => Json(models::response(&models)).into_response(),
Err(error) => api_error(StatusCode::CONFLICT, error),
}
}
async fn chat(
State(state): State<ApiState>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Response {
generate(state, headers, body, Protocol::Chat).await
}
async fn responses(
State(state): State<ApiState>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Response {
generate(state, headers, body, Protocol::Responses).await
}
async fn messages(
State(state): State<ApiState>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Response {
generate(state, headers, body, Protocol::Messages).await
}
async fn generate(
state: ApiState,
headers: HeaderMap,
body: Value,
protocol: Protocol,
) -> Response {
if let Err(error) = authorized(&state, &headers).await {
return *error;
}
let Some(public_model_id) = body
.get("model")
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
else {
return api_error(StatusCode::BAD_REQUEST, "model is required");
};
let models = match models::list(&state.store, &state.plugins).await {
Ok(models) => models,
Err(error) => return api_error(StatusCode::CONFLICT, error),
};
let Some(model) = models
.iter()
.find(|model| model.public_id == public_model_id)
else {
return api_error(StatusCode::NOT_FOUND, "model not found");
};
if let Some(native) = &state.native {
match state.store.model(&model.internal_id).await {
Ok(Some(config)) if protocol.provider_type() == config.provider_type() => {
return match native.forward(protocol, &headers, body, &config).await {
Ok(response) => response,
Err(error) => api_error(StatusCode::BAD_GATEWAY, error),
};
}
Ok(_) => {}
Err(error) => return api_error(StatusCode::INTERNAL_SERVER_ERROR, error),
}
}
let parsed = match protocol::parse(protocol, &body) {
Ok(parsed) => parsed,
Err(error) => return api_error(StatusCode::BAD_REQUEST, error),
};
let id = format!("external-api:{}", uuid::Uuid::new_v4());
let mut request = parsed.request;
request.model.model_id = model.internal_id.clone();
let invocation = ModelInvocation {
call_id: id.clone(),
run_id: id.clone(),
conversation_id: id.clone(),
provider_call_index: 0,
request,
};
let cancellation = CancellationToken::new();
let stream = state.provider.stream(invocation, cancellation.clone());
if parsed.stream {
output::streamed(protocol, stream, cancellation, id, parsed.public_model_id)
} else {
match output::complete(protocol, stream, &id, &parsed.public_model_id).await {
Ok(response) => response.into_response(),
Err(Error::Protocol(message)) => api_error(StatusCode::BAD_REQUEST, message),
Err(error) => api_error(StatusCode::BAD_GATEWAY, error),
}
}
}
+66
View File
@@ -0,0 +1,66 @@
use std::collections::HashSet;
use serde_json::{json, Value};
use crate::{plugin::PluginRegistry, store::Store, Result};
#[derive(Clone)]
pub(super) struct ListedModel {
pub public_id: String,
pub internal_id: String,
pub display_name: String,
}
pub(super) async fn list(store: &Store, plugins: &PluginRegistry) -> Result<Vec<ListedModel>> {
let mut models = Vec::new();
let mut ids = HashSet::new();
let mut configured = store.models().await?;
configured.sort_by(|left, right| {
left.sort_order
.cmp(&right.sort_order)
.then_with(|| left.display_name.cmp(&right.display_name))
.then_with(|| left.model_hash.cmp(&right.model_hash))
});
for model in configured {
let group = model
.group_name
.as_deref()
.filter(|value| !value.trim().is_empty())
.map(str::to_owned)
.unwrap_or_else(|| {
url::Url::parse(&model.base_url)
.ok()
.and_then(|url| url.host_str().map(str::to_owned))
.unwrap_or_else(|| model.base_url.clone())
});
let public_id = format!("{group}/{}", model.model_id);
if ids.insert(public_id.clone()) {
models.push(ListedModel {
public_id,
internal_id: model.model_hash,
display_name: model.display_name,
});
}
}
for model in plugins.configured_models().await {
let public_id = format!(
"plugin:{}:{}/{}",
model.plugin_id, model.provider_id, model.model_id
);
if ids.insert(public_id.clone()) {
models.push(ListedModel {
public_id,
internal_id: model.id,
display_name: model.display_name,
});
}
}
Ok(models)
}
pub(super) fn response(models: &[ListedModel]) -> Value {
json!({"object":"list","data":models.iter().map(|model| json!({
"id":model.public_id,"object":"model","created":0,"owned_by":"cursor-byok",
"name":model.display_name
})).collect::<Vec<_>>()})
}
+444
View File
@@ -0,0 +1,444 @@
use std::{
collections::{BTreeMap, HashSet},
convert::Infallible,
};
use axum::{
response::{
sse::{Event, KeepAlive, Sse},
IntoResponse, Response,
},
Json,
};
use futures_util::StreamExt;
use serde_json::{json, Value};
use tokio_util::sync::CancellationToken;
use crate::{
model::Usage,
provider::{FinishReason, ModelEvent, ProviderStream},
Error, Result,
};
use super::protocol::Protocol;
#[derive(Default)]
struct ToolOutput {
id: String,
name: String,
arguments: String,
}
#[derive(Default)]
struct Output {
text: String,
thinking: String,
tools: BTreeMap<usize, ToolOutput>,
usage: Option<Usage>,
finish: Option<FinishReason>,
}
impl Output {
fn update(&mut self, event: &ModelEvent) {
match event {
ModelEvent::TextDelta(delta) => self.text.push_str(delta),
ModelEvent::ThinkingDelta(delta) => self.thinking.push_str(delta),
ModelEvent::ToolCallStart {
index,
call_id,
name,
} => {
self.tools.insert(
*index,
ToolOutput {
id: call_id.clone(),
name: name.clone(),
arguments: String::new(),
},
);
}
ModelEvent::ToolCallArgumentsDelta { index, delta } => {
if let Some(tool) = self.tools.get_mut(index) {
tool.arguments.push_str(delta);
}
}
ModelEvent::Usage(usage) => self.usage = Some(*usage),
ModelEvent::Done(reason) => self.finish = Some(*reason),
_ => {}
}
}
fn json(&self, protocol: Protocol, id: &str, model: &str) -> Value {
let usage = self.usage_json(protocol);
let finish = match self.finish.unwrap_or(FinishReason::Stop) {
FinishReason::Stop => "stop",
FinishReason::Length => "length",
FinishReason::ToolUse => "tool_calls",
};
match protocol {
Protocol::Chat => json!({"id":id,"object":"chat.completion","created":0,"model":model,
"choices":[{"index":0,"message":{"role":"assistant","content":self.text,
"tool_calls":self.tools.values().map(|tool| json!({"id":tool.id,"type":"function",
"function":{"name":tool.name,"arguments":tool.arguments}})).collect::<Vec<_>>()},"finish_reason":finish}],
"usage":usage}),
Protocol::Responses => {
let mut items = Vec::new();
if !self.text.is_empty() {
items.push(json!({"id":format!("msg_{id}"),"type":"message","status":"completed",
"role":"assistant","content":[{"type":"output_text","text":self.text,"annotations":[]}]}));
}
items.extend(self.tools.values().map(|tool| json!({"type":"function_call","id":format!("fc_{}",tool.id),
"call_id":tool.id,"name":tool.name,"arguments":tool.arguments,"status":"completed"})));
json!({"id":id,"object":"response","created_at":0,"status":"completed","model":model,
"output":items,"output_text":self.text,
"usage":usage})
}
Protocol::Messages => {
let mut content = Vec::new();
if !self.text.is_empty() {
content.push(json!({"type":"text","text":self.text}));
}
content.extend(self.tools.values().map(|tool| {
json!({"type":"tool_use","id":tool.id,"name":tool.name,
"input":serde_json::from_str::<Value>(&tool.arguments).unwrap_or(json!({}))})
}));
json!({"id":id,"type":"message","role":"assistant","model":model,"content":content,
"stop_reason":if self.tools.is_empty() { match self.finish { Some(FinishReason::Length) => "max_tokens", _ => "end_turn" } } else { "tool_use" },
"stop_sequence":null,"usage":usage})
}
}
}
fn usage_json(&self, protocol: Protocol) -> Value {
let usage = self.usage.unwrap_or_default();
let input = usage
.context_input_tokens
.or(usage.input_tokens)
.unwrap_or(0);
let output = usage.output_tokens.unwrap_or(0);
match protocol {
Protocol::Chat => {
let mut value = json!({"prompt_tokens":input,"completion_tokens":output,
"total_tokens":usage.total_tokens.unwrap_or(input.saturating_add(output))});
if let Some(cached) = usage.cache_read_tokens {
value["prompt_tokens_details"] = json!({"cached_tokens":cached});
}
if let Some(reasoning) = usage.reasoning_tokens {
value["completion_tokens_details"] = json!({"reasoning_tokens":reasoning});
}
value
}
Protocol::Responses => {
let mut value = json!({"input_tokens":input,"output_tokens":output,
"total_tokens":usage.total_tokens.unwrap_or(input.saturating_add(output))});
if let Some(cached) = usage.cache_read_tokens {
value["input_tokens_details"] = json!({"cached_tokens":cached});
}
if let Some(reasoning) = usage.reasoning_tokens {
value["output_tokens_details"] = json!({"reasoning_tokens":reasoning});
}
value
}
Protocol::Messages => {
let uncached =
usage
.context_input_tokens
.map_or(usage.input_tokens.unwrap_or(0), |total| {
total
.saturating_sub(usage.cache_read_tokens.unwrap_or(0))
.saturating_sub(usage.cache_write_tokens.unwrap_or(0))
});
let mut value = json!({"input_tokens":uncached,"output_tokens":output});
if let Some(cached) = usage.cache_read_tokens {
value["cache_read_input_tokens"] = json!(cached);
}
if let Some(written) = usage.cache_write_tokens {
value["cache_creation_input_tokens"] = json!(written);
}
value
}
}
}
}
pub(super) async fn complete(
protocol: Protocol,
mut stream: ProviderStream,
id: &str,
model: &str,
) -> Result<Json<Value>> {
let mut output = Output::default();
while let Some(event) = stream.next().await {
output.update(&event?);
}
if output.finish.is_none() {
return Err(Error::Provider(
"model stream ended without completion".into(),
));
}
Ok(Json(output.json(protocol, id, model)))
}
struct CancelOnDrop(CancellationToken);
impl Drop for CancelOnDrop {
fn drop(&mut self) {
self.0.cancel();
}
}
pub(super) fn streamed(
protocol: Protocol,
mut provider: ProviderStream,
cancellation: CancellationToken,
id: String,
model: String,
) -> Response {
let events = async_stream::stream! {
let _cancel = CancelOnDrop(cancellation);
let mut output = Output::default();
if matches!(protocol, Protocol::Chat) {
yield Ok::<Event, Infallible>(Event::default().data(chat_chunk(&id, &model, json!({"role":"assistant"}), Value::Null).to_string()));
} else if matches!(protocol, Protocol::Responses) {
yield Ok(Event::default().event("response.created").data(json!({"type":"response.created","response":{"id":id,"status":"in_progress","model":model}}).to_string()));
yield Ok(Event::default().event("response.in_progress").data(json!({"type":"response.in_progress","response":{"id":id,"status":"in_progress","model":model}}).to_string()));
} else {
yield Ok(Event::default().event("message_start").data(json!({"type":"message_start","message":{"id":id,"type":"message","role":"assistant","model":model,"content":[],"usage":{"input_tokens":0,"output_tokens":0}}}).to_string()));
}
let mut text_started = false;
let mut text_closed = false;
let mut closed_tools = HashSet::new();
while let Some(result) = provider.next().await {
match result {
Ok(event) => {
if matches!(event, ModelEvent::TextDelta(_)) && !text_started && !matches!(protocol, Protocol::Chat) {
for (name, value) in stream_events(protocol, &ModelEvent::TextStart, &id, &model, &output, &mut text_started) {
yield Ok(Event::default().event(name).data(value.to_string()));
}
}
if matches!(event, ModelEvent::Done(_)) {
if text_started && !text_closed {
for (name, value) in stream_events(protocol, &ModelEvent::TextEnd, &id, &model, &output, &mut text_started) {
yield Ok(Event::default().event(name).data(value.to_string()));
}
}
for index in output.tools.keys().filter(|index| !closed_tools.contains(*index)).copied().collect::<Vec<_>>() {
for (name, value) in stream_events(protocol, &ModelEvent::ToolCallEnd { index }, &id, &model, &output, &mut text_started) {
yield Ok(Event::default().event(name).data(value.to_string()));
}
}
}
output.update(&event);
for (name, value) in stream_events(protocol, &event, &id, &model, &output, &mut text_started) {
yield Ok(Event::default().event(name).data(value.to_string()));
}
if matches!(event, ModelEvent::TextEnd | ModelEvent::Done(_)) {
text_closed = true;
}
if let ModelEvent::ToolCallEnd { index } = event {
closed_tools.insert(index);
}
}
Err(error) => {
yield Ok(Event::default().event("error").data(json!({"error":{"message":error.to_string(),"type":"upstream_error"}}).to_string()));
return;
}
}
}
if output.finish.is_some() && matches!(protocol, Protocol::Chat) {
yield Ok(Event::default().data("[DONE]"));
}
};
Sse::new(events)
.keep_alive(KeepAlive::default())
.into_response()
}
fn chat_chunk(id: &str, model: &str, delta: Value, finish: Value) -> Value {
json!({"id":id,"object":"chat.completion.chunk","created":0,"model":model,
"choices":[{"index":0,"delta":delta,"finish_reason":finish}]})
}
fn stream_events(
protocol: Protocol,
event: &ModelEvent,
id: &str,
model: &str,
output: &Output,
text_started: &mut bool,
) -> Vec<(&'static str, Value)> {
match protocol {
Protocol::Chat => match event {
ModelEvent::TextDelta(delta) => vec![(
"message",
chat_chunk(id, model, json!({"content":delta}), Value::Null),
)],
ModelEvent::ToolCallStart {
index,
call_id,
name,
} => vec![(
"message",
chat_chunk(
id,
model,
json!({"tool_calls":[{"index":index,"id":call_id,"type":"function","function":{"name":name,"arguments":""}}]}),
Value::Null,
),
)],
ModelEvent::ToolCallArgumentsDelta { index, delta } => vec![(
"message",
chat_chunk(
id,
model,
json!({"tool_calls":[{"index":index,"function":{"arguments":delta}}]}),
Value::Null,
),
)],
ModelEvent::Done(reason) => {
let finish = match reason {
FinishReason::Stop => "stop",
FinishReason::Length => "length",
FinishReason::ToolUse => "tool_calls",
};
let mut events = vec![("message", chat_chunk(id, model, json!({}), json!(finish)))];
if output.usage.is_some() {
events.push((
"message",
json!({"id":id,"object":"chat.completion.chunk","created":0,"model":model,
"choices":[],"usage":output.usage_json(protocol)}),
));
}
events
}
_ => Vec::new(),
},
Protocol::Responses => match event {
ModelEvent::TextStart if !*text_started => {
*text_started = true;
vec![
(
"response.output_item.added",
json!({"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":format!("msg_{id}"),"status":"in_progress","role":"assistant","content":[]}}),
),
(
"response.content_part.added",
json!({"type":"response.content_part.added","output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}),
),
]
}
ModelEvent::TextDelta(delta) => vec![(
"response.output_text.delta",
json!({"type":"response.output_text.delta","delta":delta,"output_index":0,"content_index":0}),
)],
ModelEvent::TextEnd if *text_started => vec![
(
"response.output_text.done",
json!({"type":"response.output_text.done","text":output.text,"output_index":0,"content_index":0}),
),
(
"response.content_part.done",
json!({"type":"response.content_part.done","output_index":0,"content_index":0,"part":{"type":"output_text","text":output.text,"annotations":[]}}),
),
(
"response.output_item.done",
json!({"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":format!("msg_{id}"),"status":"completed","role":"assistant","content":[{"type":"output_text","text":output.text,"annotations":[]}]}}),
),
],
ModelEvent::ToolCallStart {
index,
call_id,
name,
} => vec![(
"response.output_item.added",
json!({"type":"response.output_item.added","output_index":index + usize::from(*text_started),"item":{"type":"function_call","id":format!("fc_{call_id}"),"call_id":call_id,"name":name,"arguments":"","status":"in_progress"}}),
)],
ModelEvent::ToolCallArgumentsDelta { index, delta } => vec![(
"response.function_call_arguments.delta",
json!({"type":"response.function_call_arguments.delta","output_index":index + usize::from(*text_started),"delta":delta}),
)],
ModelEvent::ToolCallEnd { index } => {
let tool = output.tools.get(index);
let arguments = tool.map(|tool| tool.arguments.as_str()).unwrap_or_default();
let call_id = tool.map(|tool| tool.id.as_str()).unwrap_or_default();
vec![
(
"response.function_call_arguments.done",
json!({"type":"response.function_call_arguments.done","output_index":index + usize::from(*text_started),"arguments":arguments}),
),
(
"response.output_item.done",
json!({"type":"response.output_item.done","output_index":index + usize::from(*text_started),"item":{"type":"function_call","id":format!("fc_{call_id}"),"call_id":call_id,"name":tool.map(|tool| tool.name.as_str()).unwrap_or("tool"),"arguments":arguments,"status":"completed"}}),
),
]
}
ModelEvent::Done(_) => vec![(
"response.completed",
json!({"type":"response.completed","response":output.json(protocol,id,model)}),
)],
_ => Vec::new(),
},
Protocol::Messages => match event {
ModelEvent::TextStart => {
if *text_started {
Vec::new()
} else {
*text_started = true;
vec![(
"content_block_start",
json!({"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}),
)]
}
}
ModelEvent::TextDelta(delta) => {
let mut events = Vec::new();
if !*text_started {
*text_started = true;
events.push(("content_block_start",json!({"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}})));
}
events.push(("content_block_delta",json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":delta}})));
events
}
ModelEvent::TextEnd => {
if *text_started {
vec![(
"content_block_stop",
json!({"type":"content_block_stop","index":0}),
)]
} else {
Vec::new()
}
}
ModelEvent::ToolCallStart {
index,
call_id,
name,
} => vec![(
"content_block_start",
json!({"type":"content_block_start","index":index + usize::from(*text_started),"content_block":{"type":"tool_use","id":call_id,"name":name,"input":{}}}),
)],
ModelEvent::ToolCallArgumentsDelta { index, delta } => vec![(
"content_block_delta",
json!({"type":"content_block_delta","index":index + usize::from(*text_started),"delta":{"type":"input_json_delta","partial_json":delta}}),
)],
ModelEvent::ToolCallEnd { index } => vec![(
"content_block_stop",
json!({"type":"content_block_stop","index":index + usize::from(*text_started)}),
)],
ModelEvent::Done(reason) => {
let stop = match reason {
FinishReason::Stop => "end_turn",
FinishReason::Length => "max_tokens",
FinishReason::ToolUse => "tool_use",
};
vec![
(
"message_delta",
json!({"type":"message_delta","delta":{"stop_reason":stop,"stop_sequence":null},"usage":output.usage_json(protocol)}),
),
("message_stop", json!({"type":"message_stop"})),
]
}
_ => Vec::new(),
},
}
}
+471
View File
@@ -0,0 +1,471 @@
use base64::Engine;
use serde_json::Value;
use crate::{
model::{
ContentPart, ModelRequest, ModelSpec, ProjectedContent, ProjectedMessage, PromptSpec,
ProviderType, Role, ToolCallContent, ToolDefinition, ToolResultContent,
},
Error, Result,
};
#[derive(Clone, Copy, Debug)]
pub(super) enum Protocol {
Chat,
Responses,
Messages,
}
impl Protocol {
pub(super) fn provider_type(self) -> ProviderType {
match self {
Self::Chat => ProviderType::OpenAiChat,
Self::Responses => ProviderType::OpenAiResponses,
Self::Messages => ProviderType::Anthropic,
}
}
}
pub(super) struct ParsedRequest {
pub public_model_id: String,
pub request: ModelRequest,
pub stream: bool,
}
pub(super) fn parse(protocol: Protocol, body: &Value) -> Result<ParsedRequest> {
let public_model_id = required_string(body, "model")?.to_owned();
let stream = body.get("stream").and_then(Value::as_bool).unwrap_or(false);
let mut prompt = PromptSpec {
instructions: String::new(),
tools: Vec::new(),
};
let mut history = Vec::new();
let mut model = ModelSpec::new(&public_model_id);
match protocol {
Protocol::Chat => {
parse_chat_messages(body.get("messages"), &mut prompt, &mut history)?;
parse_tools(body.get("tools"), protocol, &mut prompt)?;
model.max_output_tokens = body
.get("max_completion_tokens")
.or_else(|| body.get("max_tokens"))
.and_then(Value::as_u64);
}
Protocol::Responses => {
prompt.instructions = body
.get("instructions")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
match body.get("input") {
Some(Value::String(text)) => history.push(text_message(0, Role::User, text)),
Some(input) => parse_responses_input(input, &mut history)?,
None => return Err(Error::Protocol("input is required".into())),
}
parse_tools(body.get("tools"), protocol, &mut prompt)?;
model.max_output_tokens = body.get("max_output_tokens").and_then(Value::as_u64);
}
Protocol::Messages => {
prompt.instructions = text_content(body.get("system")).unwrap_or_default();
parse_anthropic_messages(body.get("messages"), &mut history)?;
parse_tools(body.get("tools"), protocol, &mut prompt)?;
model.max_output_tokens = body.get("max_tokens").and_then(Value::as_u64);
}
}
if history.is_empty() {
return Err(Error::Protocol(
"at least one input message is required".into(),
));
}
Ok(ParsedRequest {
public_model_id,
request: ModelRequest {
prompt,
model,
history,
},
stream,
})
}
fn required_string<'a>(value: &'a Value, field: &str) -> Result<&'a str> {
value
.get(field)
.and_then(Value::as_str)
.filter(|text| !text.is_empty())
.ok_or_else(|| Error::Protocol(format!("{field} is required")))
}
fn text_message(index: usize, role: Role, text: &str) -> ProjectedMessage {
ProjectedMessage {
message_id: format!("external:{index}"),
role,
content: ProjectedContent::Parts(vec![ContentPart::Text { text: text.into() }]),
}
}
fn text_content(value: Option<&Value>) -> Option<String> {
match value? {
Value::String(text) => Some(text.clone()),
Value::Array(parts) => Some(
parts
.iter()
.filter_map(|part| {
part.as_str()
.or_else(|| part.get("text").and_then(Value::as_str))
})
.collect::<Vec<_>>()
.join("\n"),
),
_ => None,
}
}
fn parse_parts(value: Option<&Value>) -> Result<Vec<ContentPart>> {
let value = value.ok_or_else(|| Error::Protocol("message content is required".into()))?;
if let Some(text) = value.as_str() {
return Ok(vec![ContentPart::Text { text: text.into() }]);
}
let array = value
.as_array()
.ok_or_else(|| Error::Protocol("message content must be text or an array".into()))?;
array
.iter()
.map(|part| {
let kind = part.get("type").and_then(Value::as_str).unwrap_or("text");
match kind {
"text" | "input_text" | "output_text" => Ok(ContentPart::Text {
text: required_string(part, "text")?.into(),
}),
"image_url" | "input_image" | "image" => {
let url = part
.pointer("/image_url/url")
.or_else(|| part.get("image_url"))
.or_else(|| part.pointer("/source/data"))
.and_then(Value::as_str)
.ok_or_else(|| Error::Protocol("image data URL is required".into()))?;
let data_url = if url.starts_with("data:") {
url.to_owned()
} else if let Some(mime) =
part.pointer("/source/media_type").and_then(Value::as_str)
{
format!("data:{mime};base64,{url}")
} else {
return Err(Error::Protocol(
"only base64 image data URLs are supported".into(),
));
};
let (prefix, encoded) = data_url
.split_once(',')
.ok_or_else(|| Error::Protocol("invalid image data URL".into()))?;
let mime_type = prefix
.strip_prefix("data:")
.and_then(|prefix| prefix.strip_suffix(";base64"))
.ok_or_else(|| Error::Protocol("invalid image data URL".into()))?;
let data = base64::engine::general_purpose::STANDARD
.decode(encoded)
.map_err(|_| Error::Protocol("invalid base64 image".into()))?;
Ok(ContentPart::Image {
mime_type: mime_type.into(),
data,
})
}
_ => Err(Error::Protocol(format!("unsupported content type: {kind}"))),
}
})
.collect()
}
fn parse_chat_messages(
value: Option<&Value>,
prompt: &mut PromptSpec,
history: &mut Vec<ProjectedMessage>,
) -> Result<()> {
let messages = value
.and_then(Value::as_array)
.ok_or_else(|| Error::Protocol("messages must be an array".into()))?;
for (index, message) in messages.iter().enumerate() {
let role = required_string(message, "role")?;
match role {
"system" | "developer" => {
if !history.is_empty() {
return Err(Error::Protocol(
"system messages must precede conversation messages".into(),
));
}
let text = text_content(message.get("content"))
.ok_or_else(|| Error::Protocol("system content must be text".into()))?;
if !prompt.instructions.is_empty() {
prompt.instructions.push('\n');
}
prompt.instructions.push_str(&text);
}
"user" => history.push(ProjectedMessage {
message_id: format!("external:{index}"),
role: Role::User,
content: ProjectedContent::Parts(parse_parts(message.get("content"))?),
}),
"assistant" => {
let text = text_content(message.get("content")).unwrap_or_default();
let calls = message
.get("tool_calls")
.and_then(Value::as_array)
.map(|calls| {
calls
.iter()
.enumerate()
.map(|(index, call)| {
let function = call.get("function").ok_or_else(|| {
Error::Protocol("tool function is required".into())
})?;
let arguments = required_string(function, "arguments")?;
Ok(ToolCallContent {
index,
call_id: required_string(call, "id")?.into(),
name: required_string(function, "name")?.into(),
arguments: serde_json::from_str(arguments)?,
})
})
.collect::<Result<Vec<_>>>()
})
.transpose()?
.unwrap_or_default();
history.push(ProjectedMessage {
message_id: format!("external:{index}"),
role: Role::Assistant,
content: ProjectedContent::Assistant {
text,
thinking: String::new(),
replay_state: None,
calls,
},
});
}
"tool" => history.push(ProjectedMessage {
message_id: format!("external:{index}"),
role: Role::Tool,
content: ProjectedContent::ToolResult(ToolResultContent {
call_id: required_string(message, "tool_call_id")?.into(),
name: message
.get("name")
.and_then(Value::as_str)
.map(str::to_owned)
.or_else(|| {
tool_name(
history,
message
.get("tool_call_id")
.and_then(Value::as_str)
.unwrap_or_default(),
)
})
.unwrap_or_else(|| "tool".into()),
content: text_content(message.get("content")).unwrap_or_default(),
is_error: false,
image: None,
provider_parts: Vec::new(),
}),
}),
_ => return Err(Error::Protocol(format!("unsupported role: {role}"))),
}
}
Ok(())
}
fn parse_responses_input(value: &Value, history: &mut Vec<ProjectedMessage>) -> Result<()> {
let items = value
.as_array()
.ok_or_else(|| Error::Protocol("input must be text or an array".into()))?;
for (index, item) in items.iter().enumerate() {
match item.get("type").and_then(Value::as_str) {
Some("function_call_output") => history.push(ProjectedMessage {
message_id: format!("external:{index}"),
role: Role::Tool,
content: ProjectedContent::ToolResult(ToolResultContent {
call_id: required_string(item, "call_id")?.into(),
name: tool_name(history, required_string(item, "call_id")?)
.unwrap_or_else(|| "tool".into()),
content: text_content(item.get("output")).unwrap_or_default(),
is_error: false,
image: None,
provider_parts: Vec::new(),
}),
}),
Some("function_call") => history.push(ProjectedMessage {
message_id: format!("external:{index}"),
role: Role::Assistant,
content: ProjectedContent::Assistant {
text: String::new(),
thinking: String::new(),
replay_state: None,
calls: vec![ToolCallContent {
index: 0,
call_id: required_string(item, "call_id")?.into(),
name: required_string(item, "name")?.into(),
arguments: serde_json::from_str(required_string(item, "arguments")?)?,
}],
},
}),
_ => {
let role = item.get("role").and_then(Value::as_str).unwrap_or("user");
let role = match role {
"user" => Role::User,
"assistant" => Role::Assistant,
_ => return Err(Error::Protocol(format!("unsupported role: {role}"))),
};
history.push(ProjectedMessage {
message_id: format!("external:{index}"),
role,
content: ProjectedContent::Parts(parse_parts(item.get("content"))?),
});
}
}
}
Ok(())
}
fn parse_anthropic_messages(
value: Option<&Value>,
history: &mut Vec<ProjectedMessage>,
) -> Result<()> {
let messages = value
.and_then(Value::as_array)
.ok_or_else(|| Error::Protocol("messages must be an array".into()))?;
for (index, message) in messages.iter().enumerate() {
let role = required_string(message, "role")?;
let content = message
.get("content")
.ok_or_else(|| Error::Protocol("content is required".into()))?;
if let Some(blocks) = content.as_array() {
let mut text_parts = Vec::new();
let mut calls = Vec::new();
for (block_index, block) in blocks.iter().enumerate() {
match block.get("type").and_then(Value::as_str) {
Some("tool_use") => calls.push(ToolCallContent {
index: calls.len(),
call_id: required_string(block, "id")?.into(),
name: required_string(block, "name")?.into(),
arguments: block
.get("input")
.cloned()
.unwrap_or(Value::Object(Default::default())),
}),
Some("tool_result") => {
if role != "user" {
return Err(Error::Protocol(
"tool_result must be in a user message".into(),
));
}
if !text_parts.is_empty() {
history.push(ProjectedMessage {
message_id: format!("external:{index}:{block_index}:text"),
role: Role::User,
content: ProjectedContent::Parts(std::mem::take(&mut text_parts)),
});
}
let call_id = required_string(block, "tool_use_id")?;
history.push(ProjectedMessage {
message_id: format!("external:{index}:{block_index}:tool"),
role: Role::Tool,
content: ProjectedContent::ToolResult(ToolResultContent {
call_id: call_id.into(),
name: tool_name(history, call_id).unwrap_or_else(|| "tool".into()),
content: text_content(block.get("content")).unwrap_or_default(),
is_error: block
.get("is_error")
.and_then(Value::as_bool)
.unwrap_or(false),
image: None,
provider_parts: Vec::new(),
}),
});
}
_ => text_parts.extend(parse_parts(Some(&Value::Array(vec![block.clone()])))?),
}
}
if role == "assistant" {
let text = text_parts
.iter()
.filter_map(|part| {
if let ContentPart::Text { text } = part {
Some(text.as_str())
} else {
None
}
})
.collect::<Vec<_>>()
.join("");
history.push(ProjectedMessage {
message_id: format!("external:{index}"),
role: Role::Assistant,
content: ProjectedContent::Assistant {
text,
thinking: String::new(),
replay_state: None,
calls,
},
});
} else if !text_parts.is_empty() {
history.push(ProjectedMessage {
message_id: format!("external:{index}"),
role: Role::User,
content: ProjectedContent::Parts(text_parts),
});
}
} else {
let role = match role {
"user" => Role::User,
"assistant" => Role::Assistant,
_ => return Err(Error::Protocol(format!("unsupported role: {role}"))),
};
history.push(ProjectedMessage {
message_id: format!("external:{index}"),
role,
content: ProjectedContent::Parts(parse_parts(Some(content))?),
});
}
}
Ok(())
}
fn parse_tools(value: Option<&Value>, protocol: Protocol, prompt: &mut PromptSpec) -> Result<()> {
let Some(value) = value else {
return Ok(());
};
let tools = value
.as_array()
.ok_or_else(|| Error::Protocol("tools must be an array".into()))?;
for tool in tools {
let function = if matches!(protocol, Protocol::Chat) {
tool.get("function").unwrap_or(tool)
} else {
tool
};
prompt.tools.push(ToolDefinition {
name: required_string(function, "name")?.into(),
description: function
.get("description")
.and_then(Value::as_str)
.unwrap_or_default()
.into(),
parameters: function
.get("parameters")
.or_else(|| function.get("input_schema"))
.cloned()
.unwrap_or(serde_json::json!({"type":"object","properties":{}})),
});
}
Ok(())
}
fn tool_name(history: &[ProjectedMessage], call_id: &str) -> Option<String> {
history
.iter()
.rev()
.find_map(|message| match &message.content {
ProjectedContent::Assistant { calls, .. } => calls
.iter()
.find(|call| call.call_id == call_id)
.map(|call| call.name.clone()),
_ => None,
})
}
+1
View File
@@ -1,5 +1,6 @@
//! Exposes the HTTP and Connect API layer.
pub mod byok;
pub mod cursor;
mod router;
+12 -1
View File
@@ -52,6 +52,17 @@ impl App {
config.provider_request_timeout,
config.provider_stream_idle_timeout,
));
let byok = api::byok::router(
store.clone(),
plugins.clone(),
provider.clone(),
Some(api::byok::NativeForwarder::new(
store.clone(),
clients.clone(),
config.provider_request_timeout,
config.provider_stream_idle_timeout,
)),
);
let registry = TransportRegistry::with_plugins(
store.clone(),
provider.clone(),
@@ -69,7 +80,7 @@ impl App {
config.app_version.clone(),
)?;
let harness = control.cursor_harness().clone();
let mut router = api::router(registry.clone(), clients)?;
let mut router = api::router(registry.clone(), clients)?.merge(byok);
router = match &config.console {
Some(ConsoleSource::Directory(directory)) => {
router.merge(control::web_router(control.clone(), directory))
+4
View File
@@ -196,6 +196,10 @@ pub fn api_router(service: ControlService) -> Router {
"/__byok-api__/api/settings/ports",
get(settings::get_ports).put(settings::update_ports),
)
.route(
"/__byok-api__/api/settings/external-api",
get(settings::get_external_api).put(settings::update_external_api),
)
.route(
"/__byok-api__/api/settings/storage/statistics",
get(settings::get_storage).delete(settings::clear_storage),
+30 -7
View File
@@ -28,8 +28,8 @@ use crate::{
plugin::{PluginDescriptor, PluginRegistry, PluginRuntime, PluginRuntimeStatus},
provider::{is_valid_response_event, ModelEvent, Provider},
store::{
CommitSettings, DesktopSettings, PortSettings, ProxySettings, ProxySettingsInput,
StatisticsStorage, Store, TabSettings, TokenPricingSettings,
CommitSettings, DesktopSettings, ExternalApiSettings, PortSettings, ProxySettings,
ProxySettingsInput, StatisticsStorage, Store, TabSettings, TokenPricingSettings,
},
Error, Result,
};
@@ -605,10 +605,13 @@ impl ControlService {
.llm_calls(limit)
.await?
.into_iter()
.map(|call| CallSummary {
call,
call_kind: "provider_llm",
route: "local_byok",
.map(|call| {
let route = call_route(&call.run_id);
CallSummary {
call,
call_kind: "provider_llm",
route,
}
})
.collect::<Vec<_>>();
calls.extend(
@@ -626,13 +629,14 @@ impl ControlService {
pub async fn call(&self, call_id: &str) -> Result<CallDetail> {
if let Some(call) = self.store.llm_call(call_id).await? {
let cursor_trace = self.cursor_trace_detail(&call.run_id).await?;
let route = call_route(&call.run_id);
return Ok(CallDetail {
request: self.store.llm_call_request(call_id).await?,
response_chunks: self.store.llm_call_chunks(call_id).await?,
call: CallSummary {
call,
call_kind: "provider_llm",
route: "local_byok",
route,
},
cursor_trace,
});
@@ -691,6 +695,17 @@ impl ControlService {
self.store.port_settings().await
}
pub async fn external_api_settings(&self) -> Result<ExternalApiSettings> {
self.store.external_api_settings().await
}
pub async fn set_external_api_settings(
&self,
settings: ExternalApiSettings,
) -> Result<ExternalApiSettings> {
self.store.set_external_api_settings(settings).await
}
pub async fn set_ports(&self, settings: PortSettings) -> Result<PortSettings> {
self.store.set_port_settings(settings).await?;
Ok(settings)
@@ -761,6 +776,14 @@ impl ControlService {
}
}
fn call_route(run_id: &str) -> &'static str {
if run_id.starts_with("external-api:") {
"external_api"
} else {
"local_byok"
}
}
fn official_call(trace: CursorRunTraceSummary) -> CallSummary {
let model_id = trace.model_id.clone().unwrap_or_else(|| "Cursor".into());
let ttfb = trace
+15 -2
View File
@@ -8,8 +8,8 @@ use axum::{
use serde::{Deserialize, Serialize};
use crate::store::{
CommitPromptLocale, CommitSettings, DesktopSettings, PortSettings, ProxySettings,
ProxySettingsInput, StatisticsStorage, StatisticsStorageScope, TabSettings,
CommitPromptLocale, CommitSettings, DesktopSettings, ExternalApiSettings, PortSettings,
ProxySettings, ProxySettingsInput, StatisticsStorage, StatisticsStorageScope, TabSettings,
TokenPricingSettings,
};
@@ -37,6 +37,19 @@ pub async fn update_ports(
Ok(Json(service.set_ports(settings).await?))
}
pub async fn get_external_api(
State(service): State<ControlService>,
) -> Result<Json<ExternalApiSettings>> {
Ok(Json(service.external_api_settings().await?))
}
pub async fn update_external_api(
State(service): State<ControlService>,
Json(settings): Json<ExternalApiSettings>,
) -> Result<Json<ExternalApiSettings>> {
Ok(Json(service.set_external_api_settings(settings).await?))
}
pub async fn get_storage(State(service): State<ControlService>) -> Result<Json<StatisticsStorage>> {
Ok(Json(service.statistics_storage().await?))
}
+1 -1
View File
@@ -480,7 +480,7 @@ fn required_u64(value: &Value, name: &str) -> Result<u64> {
.ok_or_else(|| Error::Provider(format!("Anthropic event is missing {name}")))
}
fn anthropic_usage(value: &Value) -> Usage {
pub(crate) fn anthropic_usage(value: &Value) -> Usage {
let input_tokens = value.get("input_tokens").and_then(Value::as_u64);
let cache_read_tokens = value.get("cache_read_input_tokens").and_then(Value::as_u64);
let cache_write_tokens = value
+15
View File
@@ -21,6 +21,21 @@ pub use event::*;
pub use openai_chat::OpenAiChatProvider;
pub use openai_responses::OpenAiResponsesProvider;
pub use recorder::CallRecorder;
pub(crate) use router::custom_headers;
pub(crate) fn native_usage(
kind: crate::model::ProviderType,
value: &serde_json::Value,
) -> crate::model::Usage {
match kind {
crate::model::ProviderType::OpenAiChat => openai_chat::openai_usage(value),
crate::model::ProviderType::OpenAiResponses => openai_responses::responses_usage(value),
crate::model::ProviderType::Anthropic => anthropic::anthropic_usage(value),
crate::model::ProviderType::Plugin => {
unreachable!("plugin calls have no native HTTP protocol")
}
}
}
pub use router::{build as build_provider, ProviderRouter};
pub type ProviderStream = Pin<Box<dyn Stream<Item = Result<ModelEvent>> + Send>>;
+1 -1
View File
@@ -522,7 +522,7 @@ fn required_u64(value: &Value, name: &str) -> Result<u64> {
.ok_or_else(|| Error::Provider(format!("OpenAI Responses event is missing {name}")))
}
fn responses_usage(value: &Value) -> Usage {
pub(crate) fn responses_usage(value: &Value) -> Usage {
let input_tokens = value.get("input_tokens").and_then(Value::as_u64);
Usage {
input_tokens,
+2 -2
View File
@@ -41,7 +41,7 @@ pub struct CallRecorder {
inner: Arc<Inner>,
}
pub(super) struct CancelOnDrop {
pub(crate) struct CancelOnDrop {
recorder: CallRecorder,
}
@@ -133,7 +133,7 @@ impl CallRecorder {
self.inner.finished.load(Ordering::Acquire)
}
pub(super) fn cancel_on_drop(&self) -> CancelOnDrop {
pub(crate) fn cancel_on_drop(&self) -> CancelOnDrop {
CancelOnDrop {
recorder: self.clone(),
}
+1 -1
View File
@@ -308,7 +308,7 @@ fn root_error_message(error: &(dyn std::error::Error + 'static)) -> String {
current.to_string()
}
fn custom_headers(
pub(crate) fn custom_headers(
value: &serde_json::Value,
conversation_id: &str,
) -> Result<reqwest::header::HeaderMap> {
+82 -3
View File
@@ -13,6 +13,7 @@ const DESKTOP_SETTINGS_KEY: &str = "desktop_lifecycle";
const COMMIT_SETTINGS_KEY: &str = "commit_settings";
const CURSOR_TAKEOVER_ENABLED_KEY: &str = "cursor_takeover_enabled";
const PRICING_SETTINGS_KEY: &str = "token_pricing";
const EXTERNAL_API_SETTINGS_KEY: &str = "external_api";
/// Embedded default system prompts for commit message generation.
pub const DEFAULT_COMMIT_PROMPT_ZH_CN: &str = include_str!("../../prompt/cursor/commit/zh-CN.md");
@@ -26,6 +27,12 @@ pub struct PortSettings {
pub service_port: u16,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
pub struct ExternalApiSettings {
pub enabled: bool,
pub api_key: String,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub struct TokenPricingSettings {
pub input_per_million: f64,
@@ -212,6 +219,39 @@ fn read_proxy_settings(value: &str) -> ProxySettingsSecret {
}
impl Store {
pub async fn external_api_settings(&self) -> Result<ExternalApiSettings> {
let value = sqlx::query_scalar::<_, String>(
"SELECT value_json FROM service_settings WHERE setting_key = ?",
)
.bind(EXTERNAL_API_SETTINGS_KEY)
.fetch_optional(&self.pool)
.await?;
value
.map(|value| serde_json::from_str(&value).map_err(Into::into))
.unwrap_or_else(|| Ok(ExternalApiSettings::default()))
}
pub async fn set_external_api_settings(
&self,
mut settings: ExternalApiSettings,
) -> Result<ExternalApiSettings> {
settings.api_key = settings.api_key.trim().to_owned();
if settings.enabled && settings.api_key.is_empty() {
return Err(crate::Error::Config(
"external API key is required when enabled".into(),
));
}
let value_json = serde_json::to_string(&settings)?;
let _write = self.writes.lock().await;
sqlx::query("INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms")
.bind(EXTERNAL_API_SETTINGS_KEY)
.bind(value_json)
.bind(now_ms())
.execute(&self.pool)
.await?;
Ok(settings)
}
pub(crate) async fn cursor_takeover_enabled(&self) -> Result<bool> {
let value = sqlx::query_scalar::<_, String>(
"SELECT value_json FROM service_settings WHERE setting_key = ?",
@@ -495,9 +535,9 @@ impl Store {
#[cfg(test)]
mod tests {
use super::{
read_proxy_settings, CommitPromptLocale, CommitSettings, ProxyMode, ProxySettingsInput,
ProxySettingsSecret, Store, TokenPricingSettings, DEFAULT_COMMIT_PROMPT_EN_US,
DEFAULT_COMMIT_PROMPT_ZH_CN, PROXY_SETTINGS_KEY,
read_proxy_settings, CommitPromptLocale, CommitSettings, ExternalApiSettings, ProxyMode,
ProxySettingsInput, ProxySettingsSecret, Store, TokenPricingSettings,
DEFAULT_COMMIT_PROMPT_EN_US, DEFAULT_COMMIT_PROMPT_ZH_CN, PROXY_SETTINGS_KEY,
};
/// The `outbound_proxy` row exactly as builds before the `system` -> `default`
@@ -632,4 +672,43 @@ mod tests {
assert_eq!(store.pricing_settings().await.unwrap(), custom);
}
#[tokio::test]
async fn external_api_requires_a_key_and_persists_its_switch() {
let directory = tempfile::tempdir().unwrap();
let url = format!("sqlite://{}", directory.path().join("test.db").display());
let store = Store::connect(&url).await.unwrap();
assert_eq!(
store.external_api_settings().await.unwrap(),
ExternalApiSettings::default()
);
assert!(store
.set_external_api_settings(ExternalApiSettings {
enabled: true,
api_key: String::new(),
})
.await
.is_err());
let settings = ExternalApiSettings {
enabled: true,
api_key: "local-test-key".into(),
};
assert_eq!(
store
.set_external_api_settings(settings.clone())
.await
.unwrap(),
settings
);
assert_eq!(
Store::connect(&url)
.await
.unwrap()
.external_api_settings()
.await
.unwrap(),
settings
);
}
}