mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 01:05:10 +08:00
refactor: rebuild desktop app with Tauri
This commit is contained in:
1 parent
a3ec2a0dfc
commit
4053a7fb20
808 files changed
+87359
-181491
No files matched your search
@@ -0,0 +1,186 @@
|
||||
//! Advertisement service contract and desktop HTTP handler.
|
||||
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
Json,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
use super::ControlService;
|
||||
|
||||
// 此广告拉取不涉及用户隐私,用户id随机产生
|
||||
// 开源项目广告为作者唯一收入来源,PR时请勿去除此广告
|
||||
|
||||
pub(super) const ADS_ENDPOINT: &str = "http://127.0.0.1:8080/api/v1/ads?placement=menu";
|
||||
pub(super) const DEVICE_ID_HEADER: &str = "X-Cursor-Assistant-Device-ID";
|
||||
pub(super) const OS_HEADER: &str = "X-Cursor-Assistant-OS";
|
||||
pub(super) const APP_VERSION_HEADER: &str = "X-Cursor-Assistant-Version";
|
||||
pub(super) const DISABLED_AD_IDS_HEADER: &str = "disable-ad-ids";
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdRuntime {
|
||||
pub slots: Vec<AdSlot>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdSlot {
|
||||
pub id: String,
|
||||
pub enabled: bool,
|
||||
pub placement: AdPlacement,
|
||||
pub target: AdTarget,
|
||||
pub content: AdContent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AdPlacement {
|
||||
Menu,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdTarget {
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub image_url: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdContent {
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub image_url: String,
|
||||
pub details: Vec<AdDetail>,
|
||||
pub button: AdButton,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdDetail {
|
||||
pub label: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdButton {
|
||||
pub label: String,
|
||||
pub action: AdAction,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdAction {
|
||||
#[serde(rename = "type")]
|
||||
pub action_type: AdActionType,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdDismissalInput {
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AdActionType {
|
||||
OpenBrowser,
|
||||
}
|
||||
|
||||
impl AdRuntime {
|
||||
pub(super) fn into_menu_slots(mut self) -> Result<Self> {
|
||||
self.slots
|
||||
.retain(|slot| slot.enabled && slot.placement == AdPlacement::Menu);
|
||||
for slot in &self.slots {
|
||||
validate_http_url(&slot.target.image_url, "target.imageUrl")?;
|
||||
validate_http_url(&slot.content.image_url, "content.imageUrl")?;
|
||||
validate_http_url(&slot.content.button.action.url, "content.button.action.url")?;
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_http_url(value: &str, field: &str) -> Result<()> {
|
||||
let url = Url::parse(value)
|
||||
.map_err(|error| Error::Provider(format!("advertisement {field} is invalid: {error}")))?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return Err(Error::Provider(format!(
|
||||
"advertisement {field} must be an absolute HTTP or HTTPS URL"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
State(service): State<ControlService>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<AdRuntime>> {
|
||||
let disabled_ad_ids = headers
|
||||
.get(DISABLED_AD_IDS_HEADER)
|
||||
.and_then(|value| value.to_str().ok());
|
||||
Ok(Json(service.ads(disabled_ad_ids).await?))
|
||||
}
|
||||
|
||||
pub async fn dismiss(
|
||||
State(service): State<ControlService>,
|
||||
Path(ad_id): Path<String>,
|
||||
Json(input): Json<AdDismissalInput>,
|
||||
) -> Result<StatusCode> {
|
||||
service.dismiss_ad(&ad_id, &input).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn filters_disabled_slots_without_limiting_menu_ads() {
|
||||
let slot = |id: &str, enabled| AdSlot {
|
||||
id: id.into(),
|
||||
enabled,
|
||||
placement: AdPlacement::Menu,
|
||||
target: AdTarget {
|
||||
title: id.into(),
|
||||
description: String::new(),
|
||||
image_url: "https://example.com/target.png".into(),
|
||||
},
|
||||
content: AdContent {
|
||||
title: id.into(),
|
||||
description: String::new(),
|
||||
image_url: "https://example.com/content.png".into(),
|
||||
details: Vec::new(),
|
||||
button: AdButton {
|
||||
label: "Open".into(),
|
||||
action: AdAction {
|
||||
action_type: AdActionType::OpenBrowser,
|
||||
url: "https://example.com".into(),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
let runtime = AdRuntime {
|
||||
slots: vec![
|
||||
slot("one", true),
|
||||
slot("disabled", false),
|
||||
slot("two", true),
|
||||
slot("three", true),
|
||||
slot("four", true),
|
||||
],
|
||||
}
|
||||
.into_menu_slots()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
runtime
|
||||
.slots
|
||||
.iter()
|
||||
.map(|slot| slot.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["one", "two", "three", "four"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use axum::{
|
||||
extract::{Path, Query, State},
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::Result;
|
||||
|
||||
use super::{CallDetail, CallSummary, ControlService};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CallQuery {
|
||||
#[serde(default = "default_limit")]
|
||||
limit: i64,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
State(service): State<ControlService>,
|
||||
Query(query): Query<CallQuery>,
|
||||
) -> Result<Json<Vec<CallSummary>>> {
|
||||
Ok(Json(service.calls(query.limit).await?))
|
||||
}
|
||||
|
||||
pub async fn detail(
|
||||
State(service): State<ControlService>,
|
||||
Path(call_id): Path<String>,
|
||||
) -> Result<Json<CallDetail>> {
|
||||
Ok(Json(service.call(&call_id).await?))
|
||||
}
|
||||
|
||||
fn default_limit() -> i64 {
|
||||
100
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use axum::{extract::State, http::StatusCode, Json};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
model::{ProviderEndpoint, ProviderEndpointInput, ProviderModel, ProviderModelInput},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::{ControlService, DiscoveredModels};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum ProviderSelection {
|
||||
Existing { provider_id: i64 },
|
||||
New { input: ProviderEndpointInput },
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateCursorModels {
|
||||
pub provider: ProviderSelection,
|
||||
pub models: Vec<ProviderModelInput>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct CreatedCursorModels {
|
||||
pub provider: ProviderEndpoint,
|
||||
pub models: Vec<ProviderModel>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct DiscoverCursorModels {
|
||||
pub provider: ProviderSelection,
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(service): State<ControlService>,
|
||||
Json(input): Json<CreateCursorModels>,
|
||||
) -> Result<(StatusCode, Json<CreatedCursorModels>)> {
|
||||
let (provider, models) = match input.provider {
|
||||
ProviderSelection::Existing { provider_id } => {
|
||||
let provider = service
|
||||
.providers()
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|provider| provider.provider_id == provider_id)
|
||||
.ok_or_else(|| crate::Error::RunNotFound(format!("provider {provider_id}")))?;
|
||||
let models = service.save_models(provider_id, &input.models).await?;
|
||||
(provider, models)
|
||||
}
|
||||
ProviderSelection::New { input: provider } => {
|
||||
service
|
||||
.create_provider_with_models(&provider, &input.models)
|
||||
.await?
|
||||
}
|
||||
};
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(CreatedCursorModels { provider, models }),
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn discover(
|
||||
State(service): State<ControlService>,
|
||||
Json(input): Json<DiscoverCursorModels>,
|
||||
) -> Result<Json<DiscoveredModels>> {
|
||||
match input.provider {
|
||||
ProviderSelection::Existing { provider_id } => {
|
||||
Ok(Json(service.discover_models(provider_id).await?))
|
||||
}
|
||||
ProviderSelection::New { input } => Ok(Json(service.discover_input(&input).await?)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use axum::{extract::State, Json};
|
||||
|
||||
use crate::{
|
||||
harness::{CursorHarnessStatus, SetEnabled},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::ControlService;
|
||||
|
||||
pub async fn status(State(service): State<ControlService>) -> Result<Json<CursorHarnessStatus>> {
|
||||
Ok(Json(service.cursor_harness().status().await?))
|
||||
}
|
||||
|
||||
pub async fn initialize_ca(
|
||||
State(service): State<ControlService>,
|
||||
) -> Result<Json<CursorHarnessStatus>> {
|
||||
Ok(Json(service.cursor_harness().initialize_ca().await?))
|
||||
}
|
||||
|
||||
pub async fn set_enabled(
|
||||
State(service): State<ControlService>,
|
||||
Json(input): Json<SetEnabled>,
|
||||
) -> Result<Json<CursorHarnessStatus>> {
|
||||
Ok(Json(
|
||||
service.cursor_harness().set_enabled(input.enabled).await?,
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
mod ads;
|
||||
mod calls;
|
||||
mod cursor_models;
|
||||
mod harness;
|
||||
mod models;
|
||||
mod overview;
|
||||
mod providers;
|
||||
mod service;
|
||||
mod settings;
|
||||
|
||||
use axum::{
|
||||
body::{to_bytes, Body},
|
||||
extract::State,
|
||||
http::{header, header::CONTENT_TYPE, HeaderValue, Method, Request, Response, StatusCode},
|
||||
routing::{any, get, post, put},
|
||||
Router,
|
||||
};
|
||||
use tower_http::{
|
||||
cors::{AllowOrigin, CorsLayer},
|
||||
services::ServeDir,
|
||||
};
|
||||
use url::{Host, Url};
|
||||
|
||||
pub use service::{
|
||||
CallDetail, CallSummary, ControlService, DiscoveredModels, ObservabilitySettings,
|
||||
};
|
||||
|
||||
pub fn web_router(service: ControlService, assets: impl AsRef<std::path::Path>) -> Router {
|
||||
Router::new()
|
||||
.nest_service(
|
||||
"/__byok-api__",
|
||||
ServeDir::new(assets).append_index_html_on_directories(true),
|
||||
)
|
||||
.merge(api_router(service))
|
||||
}
|
||||
|
||||
pub fn proxy_web_router(service: ControlService, target: Url) -> Router {
|
||||
frontend_proxy_router(target).merge(api_router(service))
|
||||
}
|
||||
|
||||
fn frontend_proxy_router(target: Url) -> Router {
|
||||
let state = FrontendProxy {
|
||||
client: reqwest::Client::new(),
|
||||
target: target.as_str().trim_end_matches('/').to_string(),
|
||||
};
|
||||
Router::new()
|
||||
.route("/__byok-api__/", any(proxy_frontend))
|
||||
.route("/__byok-api__/{*path}", any(proxy_frontend))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FrontendProxy {
|
||||
client: reqwest::Client,
|
||||
target: String,
|
||||
}
|
||||
|
||||
async fn proxy_frontend(
|
||||
State(proxy): State<FrontendProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Response<Body> {
|
||||
let (parts, body) = request.into_parts();
|
||||
let path = parts
|
||||
.uri
|
||||
.path_and_query()
|
||||
.map(|value| value.as_str())
|
||||
.unwrap_or("/__byok-api__/");
|
||||
let mut upstream = proxy
|
||||
.client
|
||||
.request(parts.method, format!("{}{path}", proxy.target));
|
||||
for (name, value) in &parts.headers {
|
||||
if name != header::HOST && name != header::CONNECTION {
|
||||
upstream = upstream.header(name, value);
|
||||
}
|
||||
}
|
||||
let body = match to_bytes(body, 64 * 1024 * 1024).await {
|
||||
Ok(body) => body,
|
||||
Err(error) => return proxy_error(error),
|
||||
};
|
||||
let upstream = match upstream.body(body).send().await {
|
||||
Ok(response) => response,
|
||||
Err(error) => return proxy_error(error),
|
||||
};
|
||||
let status = upstream.status();
|
||||
let headers = upstream.headers().clone();
|
||||
let body = match upstream.bytes().await {
|
||||
Ok(body) => body,
|
||||
Err(error) => return proxy_error(error),
|
||||
};
|
||||
let mut response = Response::new(Body::from(body));
|
||||
*response.status_mut() = status;
|
||||
for (name, value) in &headers {
|
||||
if name != header::CONNECTION
|
||||
&& name != header::TRANSFER_ENCODING
|
||||
&& name != header::CONTENT_LENGTH
|
||||
{
|
||||
response.headers_mut().insert(name, value.clone());
|
||||
}
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
fn proxy_error(error: impl std::fmt::Display) -> Response<Body> {
|
||||
tracing::warn!(%error, "frontend development proxy failed");
|
||||
Response::builder()
|
||||
.status(StatusCode::BAD_GATEWAY)
|
||||
.body(Body::from("frontend development server is unavailable"))
|
||||
.expect("static proxy error response")
|
||||
}
|
||||
|
||||
pub fn api_router(service: ControlService) -> Router {
|
||||
Router::new()
|
||||
.route("/__byok-api__/api/ads", get(ads::get))
|
||||
.route(
|
||||
"/__byok-api__/api/ads/{ad_id}/dismissals",
|
||||
post(ads::dismiss),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/providers",
|
||||
get(providers::list).post(providers::create),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/providers/{provider_id}",
|
||||
put(providers::update).delete(providers::remove),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/providers/{provider_id}/models/discover",
|
||||
post(models::discover),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/providers/{provider_id}/models",
|
||||
post(models::save),
|
||||
)
|
||||
.route("/__byok-api__/api/models", get(models::list))
|
||||
.route("/__byok-api__/api/overview", get(overview::get))
|
||||
.route(
|
||||
"/__byok-api__/api/models/{model_hash}",
|
||||
put(models::update).delete(models::remove),
|
||||
)
|
||||
.route("/__byok-api__/api/llm-calls", get(calls::list))
|
||||
.route("/__byok-api__/api/llm-calls/{call_id}", get(calls::detail))
|
||||
.route(
|
||||
"/__byok-api__/api/settings/observability",
|
||||
get(settings::get).put(settings::update),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/settings/ports",
|
||||
get(settings::get_ports).put(settings::update_ports),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/settings/storage/statistics",
|
||||
get(settings::get_storage).delete(settings::clear_storage),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/settings/proxy",
|
||||
get(settings::get_proxy).put(settings::update_proxy),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/harness/cursor/status",
|
||||
get(harness::status),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/harness/cursor/ca/initialize",
|
||||
post(harness::initialize_ca),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/harness/cursor/enabled",
|
||||
put(harness::set_enabled),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/harness/cursor/models",
|
||||
post(cursor_models::create),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/harness/cursor/models/discover",
|
||||
post(cursor_models::discover),
|
||||
)
|
||||
.with_state(service)
|
||||
.layer(desktop_cors())
|
||||
}
|
||||
|
||||
fn desktop_cors() -> CorsLayer {
|
||||
CorsLayer::new()
|
||||
.allow_origin(AllowOrigin::predicate(|origin, _| local_origin(origin)))
|
||||
.allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
|
||||
.allow_headers([
|
||||
CONTENT_TYPE,
|
||||
header::HeaderName::from_static("disable-ad-ids"),
|
||||
])
|
||||
}
|
||||
|
||||
fn local_origin(origin: &HeaderValue) -> bool {
|
||||
let Ok(origin) = origin.to_str() else {
|
||||
return false;
|
||||
};
|
||||
if origin.eq_ignore_ascii_case("tauri://localhost") {
|
||||
return true;
|
||||
}
|
||||
let Ok(origin) = Url::parse(origin) else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(origin.scheme(), "http" | "https")
|
||||
|| !origin.username().is_empty()
|
||||
|| origin.password().is_some()
|
||||
|| origin.path() != "/"
|
||||
|| origin.query().is_some()
|
||||
|| origin.fragment().is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match origin.host() {
|
||||
Some(Host::Domain(host)) => {
|
||||
host.eq_ignore_ascii_case("localhost") || host.eq_ignore_ascii_case("tauri.localhost")
|
||||
}
|
||||
Some(Host::Ipv4(address)) => {
|
||||
address.is_loopback() || address.is_private() || address.is_link_local()
|
||||
}
|
||||
Some(Host::Ipv6(address)) => {
|
||||
address.is_loopback() || address.is_unique_local() || address.is_unicast_link_local()
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{header, HeaderValue, Request},
|
||||
};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn control_routes_only_exist_below_the_reserved_namespace() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let store = crate::store::Store::connect(&format!(
|
||||
"sqlite://{}",
|
||||
directory.path().join("control.db").display()
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let router = api_router(ControlService::new(store).unwrap());
|
||||
|
||||
let response = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/__byok-api__/api/providers")
|
||||
.header(header::ORIGIN, "tauri://localhost")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), axum::http::StatusCode::OK);
|
||||
assert_eq!(
|
||||
response.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN),
|
||||
Some(&HeaderValue::from_static("tauri://localhost"))
|
||||
);
|
||||
|
||||
let response = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/__byok-api__/api/overview")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), axum::http::StatusCode::OK);
|
||||
|
||||
let response = router
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/providers")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), axum::http::StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn development_frontend_proxy_preserves_the_reserved_path_and_query() {
|
||||
let upstream = Router::new().route(
|
||||
"/__byok-api__/{*path}",
|
||||
get(|request: Request<Body>| async move {
|
||||
request.uri().path_and_query().unwrap().as_str().to_string()
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let task = tokio::spawn(async move { axum::serve(listener, upstream).await.unwrap() });
|
||||
let router = frontend_proxy_router(format!("http://{address}").parse().unwrap());
|
||||
|
||||
let response = router
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/__byok-api__/src/index.tsx?direct=1")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
assert_eq!(body, "/__byok-api__/src/index.tsx?direct=1");
|
||||
task.abort();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cors_only_allows_tauri_loopback_and_private_network_origins() {
|
||||
for origin in [
|
||||
"tauri://localhost",
|
||||
"http://tauri.localhost",
|
||||
"http://localhost:1420",
|
||||
"http://127.0.0.1:1420",
|
||||
"https://192.168.1.20:8443",
|
||||
"http://[::1]:1420",
|
||||
"http://[fd00::20]:1420",
|
||||
] {
|
||||
assert!(local_origin(&origin.parse().unwrap()), "{origin}");
|
||||
}
|
||||
for origin in [
|
||||
"https://example.com",
|
||||
"https://8.8.8.8",
|
||||
"https://localhost.example.com",
|
||||
"null",
|
||||
] {
|
||||
assert!(!local_origin(&origin.parse().unwrap()), "{origin}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{
|
||||
model::{ProviderModel, ProviderModelInput},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::{ControlService, DiscoveredModels};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SaveModels {
|
||||
pub models: Vec<ProviderModelInput>,
|
||||
}
|
||||
|
||||
pub async fn list(State(service): State<ControlService>) -> Result<Json<Vec<ProviderModel>>> {
|
||||
Ok(Json(service.models().await?))
|
||||
}
|
||||
|
||||
pub async fn save(
|
||||
State(service): State<ControlService>,
|
||||
Path(provider_id): Path<i64>,
|
||||
Json(input): Json<SaveModels>,
|
||||
) -> Result<(StatusCode, Json<Vec<ProviderModel>>)> {
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(service.save_models(provider_id, &input.models).await?),
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn remove(
|
||||
State(service): State<ControlService>,
|
||||
Path(model_hash): Path<String>,
|
||||
) -> Result<StatusCode> {
|
||||
service.delete_model(&model_hash).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
State(service): State<ControlService>,
|
||||
Path(model_hash): Path<String>,
|
||||
Json(input): Json<ProviderModelInput>,
|
||||
) -> Result<Json<ProviderModel>> {
|
||||
Ok(Json(service.update_model(&model_hash, &input).await?))
|
||||
}
|
||||
|
||||
pub async fn discover(
|
||||
State(service): State<ControlService>,
|
||||
Path(provider_id): Path<i64>,
|
||||
) -> Result<Json<DiscoveredModels>> {
|
||||
Ok(Json(service.discover_models(provider_id).await?))
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! HTTP handler for the desktop overview aggregates.
|
||||
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{model::Overview, Result};
|
||||
|
||||
use super::ControlService;
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct OverviewRange {
|
||||
start_ms: Option<i64>,
|
||||
end_ms: Option<i64>,
|
||||
model_hashes: Option<String>,
|
||||
provider_ids: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
State(service): State<ControlService>,
|
||||
Query(range): Query<OverviewRange>,
|
||||
) -> Result<Json<Overview>> {
|
||||
Ok(Json(
|
||||
service
|
||||
.overview(
|
||||
range.start_ms,
|
||||
range.end_ms,
|
||||
range.model_hashes.as_deref(),
|
||||
range.provider_ids.as_deref(),
|
||||
)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
Json,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
model::{ProviderEndpoint, ProviderEndpointInput},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::ControlService;
|
||||
|
||||
pub async fn list(State(service): State<ControlService>) -> Result<Json<Vec<ProviderEndpoint>>> {
|
||||
Ok(Json(service.providers().await?))
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(service): State<ControlService>,
|
||||
Json(input): Json<ProviderEndpointInput>,
|
||||
) -> Result<(StatusCode, Json<ProviderEndpoint>)> {
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(service.create_provider(&input).await?),
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
State(service): State<ControlService>,
|
||||
Path(provider_id): Path<i64>,
|
||||
Json(input): Json<ProviderEndpointInput>,
|
||||
) -> Result<Json<ProviderEndpoint>> {
|
||||
Ok(Json(service.update_provider(provider_id, &input).await?))
|
||||
}
|
||||
|
||||
pub async fn remove(
|
||||
State(service): State<ControlService>,
|
||||
Path(provider_id): Path<i64>,
|
||||
) -> Result<StatusCode> {
|
||||
service.delete_provider(provider_id).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use reqwest::header::{HeaderName, HeaderValue};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
use super::ads::{
|
||||
AdDismissalInput, AdRuntime, ADS_ENDPOINT, APP_VERSION_HEADER, DEVICE_ID_HEADER,
|
||||
DISABLED_AD_IDS_HEADER, OS_HEADER,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
harness::CursorHarness,
|
||||
model::{
|
||||
CursorRunTraceArtifact, CursorRunTraceSummary, LlmCallRequest, LlmCallResponseChunk,
|
||||
LlmCallSummary, Overview, ProviderEndpoint, ProviderEndpointInput, ProviderEndpointSecret,
|
||||
ProviderModel, ProviderModelInput, ProviderType,
|
||||
},
|
||||
store::{PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage, Store},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ControlService {
|
||||
store: Store,
|
||||
cursor_harness: CursorHarness,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct DiscoveredModels {
|
||||
pub models: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct CallDetail {
|
||||
pub call: CallSummary,
|
||||
pub request: Option<LlmCallRequest>,
|
||||
pub response_chunks: Vec<LlmCallResponseChunk>,
|
||||
pub cursor_trace: Option<CursorTraceDetail>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct CallSummary {
|
||||
#[serde(flatten)]
|
||||
pub call: LlmCallSummary,
|
||||
pub call_kind: &'static str,
|
||||
pub route: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct CursorTraceDetail {
|
||||
pub trace: CursorRunTraceSummary,
|
||||
pub artifacts: Vec<CursorTraceArtifactDetail>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct CursorTraceArtifactDetail {
|
||||
pub seq: i64,
|
||||
pub artifact_type: String,
|
||||
pub source: String,
|
||||
pub metadata: serde_json::Value,
|
||||
pub created_at_ms: i64,
|
||||
pub byte_count: usize,
|
||||
pub encoding: &'static str,
|
||||
pub data: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
|
||||
pub struct ObservabilitySettings {
|
||||
pub detailed: bool,
|
||||
}
|
||||
|
||||
impl ControlService {
|
||||
pub fn new(store: Store) -> Result<Self> {
|
||||
Ok(Self {
|
||||
cursor_harness: CursorHarness::new(store.clone())?,
|
||||
store,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn cursor_harness(&self) -> &CursorHarness {
|
||||
&self.cursor_harness
|
||||
}
|
||||
|
||||
pub(super) async fn ads(&self, disabled_ad_ids: Option<&str>) -> Result<AdRuntime> {
|
||||
let client = crate::network::client(&self.store).await?;
|
||||
let installation_id = self.store.installation_id().await?;
|
||||
let mut request = client
|
||||
.get(ADS_ENDPOINT)
|
||||
.header(DEVICE_ID_HEADER, installation_id)
|
||||
.header(OS_HEADER, std::env::consts::OS)
|
||||
.header(APP_VERSION_HEADER, env!("CARGO_PKG_VERSION"))
|
||||
.timeout(std::time::Duration::from_secs(5));
|
||||
if let Some(disabled_ad_ids) = disabled_ad_ids.filter(|value| !value.is_empty()) {
|
||||
request = request.header(DISABLED_AD_IDS_HEADER, disabled_ad_ids);
|
||||
}
|
||||
let response = request.send().await?;
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
let message = response.text().await.unwrap_or_default();
|
||||
return Err(Error::Provider(format!(
|
||||
"advertisement service failed ({status}): {}",
|
||||
message.chars().take(200).collect::<String>()
|
||||
)));
|
||||
}
|
||||
response.json::<AdRuntime>().await?.into_menu_slots()
|
||||
}
|
||||
|
||||
pub(super) async fn dismiss_ad(&self, ad_id: &str, input: &AdDismissalInput) -> Result<()> {
|
||||
let client = crate::network::client(&self.store).await?;
|
||||
let installation_id = self.store.installation_id().await?;
|
||||
let mut endpoint = Url::parse(ADS_ENDPOINT).map_err(|error| {
|
||||
Error::Config(format!("advertisement endpoint is invalid: {error}"))
|
||||
})?;
|
||||
endpoint.set_query(None);
|
||||
endpoint
|
||||
.path_segments_mut()
|
||||
.map_err(|_| Error::Config("advertisement endpoint cannot contain an ad id".into()))?
|
||||
.push(ad_id)
|
||||
.push("dismissals");
|
||||
let response = client
|
||||
.post(endpoint)
|
||||
.header(DEVICE_ID_HEADER, installation_id)
|
||||
.header(OS_HEADER, std::env::consts::OS)
|
||||
.header(APP_VERSION_HEADER, env!("CARGO_PKG_VERSION"))
|
||||
.json(input)
|
||||
.timeout(std::time::Duration::from_secs(5))
|
||||
.send()
|
||||
.await?;
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
let message = response.text().await.unwrap_or_default();
|
||||
return Err(Error::Provider(format!(
|
||||
"advertisement dismissal failed ({status}): {}",
|
||||
message.chars().take(200).collect::<String>()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn providers(&self) -> Result<Vec<ProviderEndpoint>> {
|
||||
self.store.providers().await
|
||||
}
|
||||
|
||||
pub async fn create_provider(&self, input: &ProviderEndpointInput) -> Result<ProviderEndpoint> {
|
||||
self.store.create_provider(input).await
|
||||
}
|
||||
|
||||
pub async fn update_provider(
|
||||
&self,
|
||||
provider_id: i64,
|
||||
input: &ProviderEndpointInput,
|
||||
) -> Result<ProviderEndpoint> {
|
||||
self.store.update_provider(provider_id, input).await
|
||||
}
|
||||
|
||||
pub async fn delete_provider(&self, provider_id: i64) -> Result<()> {
|
||||
self.store.delete_provider(provider_id).await
|
||||
}
|
||||
|
||||
pub async fn models(&self) -> Result<Vec<ProviderModel>> {
|
||||
self.store.provider_models(false).await
|
||||
}
|
||||
|
||||
pub async fn overview(
|
||||
&self,
|
||||
start_ms: Option<i64>,
|
||||
end_ms: Option<i64>,
|
||||
model_hashes: Option<&str>,
|
||||
provider_ids: Option<&str>,
|
||||
) -> Result<Overview> {
|
||||
self.store
|
||||
.overview(start_ms, end_ms, model_hashes, provider_ids)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn save_models(
|
||||
&self,
|
||||
provider_id: i64,
|
||||
models: &[ProviderModelInput],
|
||||
) -> Result<Vec<ProviderModel>> {
|
||||
self.store.save_provider_models(provider_id, models).await
|
||||
}
|
||||
|
||||
pub async fn delete_model(&self, model_hash: &str) -> Result<()> {
|
||||
self.store.delete_provider_model(model_hash).await
|
||||
}
|
||||
|
||||
pub async fn update_model(
|
||||
&self,
|
||||
model_hash: &str,
|
||||
input: &ProviderModelInput,
|
||||
) -> Result<ProviderModel> {
|
||||
self.store.update_provider_model(model_hash, input).await
|
||||
}
|
||||
|
||||
pub async fn create_provider_with_models(
|
||||
&self,
|
||||
provider: &ProviderEndpointInput,
|
||||
models: &[ProviderModelInput],
|
||||
) -> Result<(ProviderEndpoint, Vec<ProviderModel>)> {
|
||||
self.store
|
||||
.create_provider_with_models(provider, models)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn discover_input(&self, input: &ProviderEndpointInput) -> Result<DiscoveredModels> {
|
||||
let client = crate::network::client(&self.store).await?;
|
||||
let endpoint = ProviderEndpoint {
|
||||
provider_id: 0,
|
||||
name: input.name.clone(),
|
||||
provider_type: input.provider_type,
|
||||
base_url: crate::model::normalize_base_url(&input.base_url)?,
|
||||
has_api_key: input
|
||||
.api_key
|
||||
.as_deref()
|
||||
.is_some_and(|value| !value.is_empty()),
|
||||
custom_headers: input.custom_headers.clone(),
|
||||
extra_params: input.extra_params.clone(),
|
||||
created_at_ms: 0,
|
||||
updated_at_ms: 0,
|
||||
};
|
||||
let secret = ProviderEndpointSecret {
|
||||
endpoint,
|
||||
api_key: input.api_key.clone().unwrap_or_default(),
|
||||
custom_headers: input.custom_headers.clone(),
|
||||
};
|
||||
let mut models = match input.provider_type {
|
||||
ProviderType::OpenAiChat | ProviderType::OpenAiResponses => {
|
||||
openai_models(&client, &secret).await?
|
||||
}
|
||||
ProviderType::Anthropic => anthropic_models(&client, &secret).await?,
|
||||
};
|
||||
models.sort();
|
||||
models.dedup();
|
||||
Ok(DiscoveredModels { models })
|
||||
}
|
||||
|
||||
pub async fn discover_models(&self, provider_id: i64) -> Result<DiscoveredModels> {
|
||||
let client = crate::network::client(&self.store).await?;
|
||||
let provider = self
|
||||
.store
|
||||
.provider(provider_id)
|
||||
.await?
|
||||
.ok_or_else(|| Error::RunNotFound(format!("provider {provider_id}")))?;
|
||||
let mut models = match provider.endpoint.provider_type {
|
||||
ProviderType::OpenAiChat | ProviderType::OpenAiResponses => {
|
||||
openai_models(&client, &provider).await?
|
||||
}
|
||||
ProviderType::Anthropic => anthropic_models(&client, &provider).await?,
|
||||
};
|
||||
models.sort();
|
||||
models.dedup();
|
||||
Ok(DiscoveredModels { models })
|
||||
}
|
||||
|
||||
pub async fn calls(&self, limit: i64) -> Result<Vec<CallSummary>> {
|
||||
let mut calls = self
|
||||
.store
|
||||
.llm_calls(limit)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|call| CallSummary {
|
||||
call,
|
||||
call_kind: "provider_llm",
|
||||
route: "local_byok",
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
calls.extend(
|
||||
self.store
|
||||
.official_cursor_traces(limit)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(official_call),
|
||||
);
|
||||
calls.sort_by_key(|call| std::cmp::Reverse(call.call.created_at_ms));
|
||||
calls.truncate(limit.clamp(1, 500) as usize);
|
||||
Ok(calls)
|
||||
}
|
||||
|
||||
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?;
|
||||
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",
|
||||
},
|
||||
cursor_trace,
|
||||
});
|
||||
}
|
||||
let request_id = call_id.strip_prefix("cursor:").unwrap_or(call_id);
|
||||
let trace = self
|
||||
.store
|
||||
.cursor_trace(request_id)
|
||||
.await?
|
||||
.filter(|trace| trace.route == "cursor_official")
|
||||
.ok_or_else(|| Error::RunNotFound(format!("call {call_id}")))?;
|
||||
Ok(CallDetail {
|
||||
call: official_call(trace.clone()),
|
||||
request: None,
|
||||
response_chunks: Vec::new(),
|
||||
cursor_trace: Some(self.cursor_trace_detail_from(trace).await?),
|
||||
})
|
||||
}
|
||||
|
||||
async fn cursor_trace_detail(&self, request_id: &str) -> Result<Option<CursorTraceDetail>> {
|
||||
let Some(trace) = self.store.cursor_trace(request_id).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(self.cursor_trace_detail_from(trace).await?))
|
||||
}
|
||||
|
||||
async fn cursor_trace_detail_from(
|
||||
&self,
|
||||
trace: CursorRunTraceSummary,
|
||||
) -> Result<CursorTraceDetail> {
|
||||
let artifacts = self
|
||||
.store
|
||||
.cursor_trace_artifacts(&trace.request_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(cursor_artifact)
|
||||
.collect();
|
||||
Ok(CursorTraceDetail { trace, artifacts })
|
||||
}
|
||||
|
||||
pub async fn observability(&self) -> Result<ObservabilitySettings> {
|
||||
Ok(ObservabilitySettings {
|
||||
detailed: self.store.detailed_logging().await?,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn set_observability(
|
||||
&self,
|
||||
settings: ObservabilitySettings,
|
||||
) -> Result<ObservabilitySettings> {
|
||||
self.store.set_detailed_logging(settings.detailed).await?;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
pub async fn ports(&self) -> Result<PortSettings> {
|
||||
self.store.port_settings().await
|
||||
}
|
||||
|
||||
pub async fn set_ports(&self, settings: PortSettings) -> Result<PortSettings> {
|
||||
self.store.set_port_settings(settings).await?;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
pub async fn statistics_storage(&self) -> Result<StatisticsStorage> {
|
||||
self.store.statistics_storage().await
|
||||
}
|
||||
|
||||
pub async fn clear_statistics_storage(&self) -> Result<StatisticsStorage> {
|
||||
self.store.clear_statistics_storage().await
|
||||
}
|
||||
|
||||
pub async fn proxy_settings(&self) -> Result<ProxySettings> {
|
||||
self.store.proxy_settings().await
|
||||
}
|
||||
|
||||
pub async fn set_proxy_settings(&self, settings: ProxySettingsInput) -> Result<ProxySettings> {
|
||||
self.store.set_proxy_settings(settings).await
|
||||
}
|
||||
}
|
||||
|
||||
fn official_call(trace: CursorRunTraceSummary) -> CallSummary {
|
||||
let model_id = trace.model_id.clone().unwrap_or_else(|| "Cursor".into());
|
||||
let ttfb = trace
|
||||
.first_response_at_ms
|
||||
.map(|value| (value - trace.received_at_ms).max(0));
|
||||
let duration = trace
|
||||
.finished_at_ms
|
||||
.map(|value| (value - trace.received_at_ms).max(0));
|
||||
let error = trace.error_message.clone();
|
||||
CallSummary {
|
||||
call: LlmCallSummary {
|
||||
call_id: format!("cursor:{}", trace.request_id),
|
||||
run_id: trace.request_id.clone(),
|
||||
conversation_id: trace
|
||||
.conversation_id
|
||||
.clone()
|
||||
.unwrap_or_else(|| trace.request_id.clone()),
|
||||
provider_call_index: 0,
|
||||
model_hash: None,
|
||||
provider_type: "cursor-official".into(),
|
||||
provider_url: "https://api2.cursor.sh".into(),
|
||||
request_type: "cursor-run-sse".into(),
|
||||
request_url: "https://api2.cursor.sh/agent.v1.AgentService/RunSSE".into(),
|
||||
model_id: model_id.clone(),
|
||||
display_name: model_id,
|
||||
reasoning_effort: None,
|
||||
fast: None,
|
||||
status: trace.status.clone(),
|
||||
finish_reason: None,
|
||||
created_at_ms: trace.received_at_ms,
|
||||
request_started_at_ms: Some(trace.received_at_ms),
|
||||
response_headers_at_ms: trace.first_response_at_ms,
|
||||
first_event_at_ms: trace.first_response_at_ms,
|
||||
first_text_at_ms: None,
|
||||
finished_at_ms: trace.finished_at_ms,
|
||||
queue_ms: None,
|
||||
ttfb_ms: ttfb,
|
||||
ttft_ms: None,
|
||||
duration_ms: duration,
|
||||
input_tokens: None,
|
||||
output_tokens: None,
|
||||
total_tokens: None,
|
||||
cache_read_tokens: None,
|
||||
cache_write_tokens: None,
|
||||
reasoning_tokens: None,
|
||||
usage: None,
|
||||
message_count: 0,
|
||||
tool_count: 0,
|
||||
request_bytes: Some(trace.request_bytes),
|
||||
response_bytes: trace.response_bytes,
|
||||
stream_event_count: trace.response_event_count,
|
||||
http_status: trace.http_status,
|
||||
error_kind: error.as_ref().map(|_| "cursor_official".into()),
|
||||
error_message: error,
|
||||
detailed: true,
|
||||
},
|
||||
call_kind: "cursor_official",
|
||||
route: "cursor_official",
|
||||
}
|
||||
}
|
||||
|
||||
fn cursor_artifact(artifact: CursorRunTraceArtifact) -> CursorTraceArtifactDetail {
|
||||
let byte_count = artifact.data.len();
|
||||
let (encoding, data) = match readable_utf8(&artifact.data) {
|
||||
Some(value) => ("utf8", value.into()),
|
||||
None => ("base64", STANDARD.encode(&artifact.data)),
|
||||
};
|
||||
CursorTraceArtifactDetail {
|
||||
seq: artifact.seq,
|
||||
artifact_type: artifact.artifact_type,
|
||||
source: artifact.source,
|
||||
metadata: artifact.metadata,
|
||||
created_at_ms: artifact.created_at_ms,
|
||||
byte_count,
|
||||
encoding,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
fn readable_utf8(data: &[u8]) -> Option<&str> {
|
||||
let value = std::str::from_utf8(data).ok()?;
|
||||
value
|
||||
.chars()
|
||||
.all(|character| !character.is_control() || matches!(character, '\n' | '\r' | '\t'))
|
||||
.then_some(value)
|
||||
}
|
||||
|
||||
async fn openai_models(
|
||||
client: &reqwest::Client,
|
||||
provider: &ProviderEndpointSecret,
|
||||
) -> Result<Vec<String>> {
|
||||
let mut request = client.get(format!("{}/models", provider.endpoint.base_url));
|
||||
if !provider.api_key.is_empty() {
|
||||
request = request.bearer_auth(&provider.api_key);
|
||||
}
|
||||
let response = apply_custom_headers(request, &provider.custom_headers)?
|
||||
.send()
|
||||
.await?;
|
||||
let status = response.status();
|
||||
let body: serde_json::Value = response.json().await?;
|
||||
if !status.is_success() {
|
||||
return Err(Error::Provider(format!(
|
||||
"model discovery failed ({status}): {body}"
|
||||
)));
|
||||
}
|
||||
Ok(model_ids(body.get("data").unwrap_or(&body)))
|
||||
}
|
||||
|
||||
async fn anthropic_models(
|
||||
client: &reqwest::Client,
|
||||
provider: &ProviderEndpointSecret,
|
||||
) -> Result<Vec<String>> {
|
||||
let mut after_id = None::<String>;
|
||||
let mut found = BTreeSet::new();
|
||||
loop {
|
||||
let mut request = client
|
||||
.get(format!("{}/models", provider.endpoint.base_url))
|
||||
.query(&[("limit", "100")])
|
||||
.header("anthropic-version", "2023-06-01");
|
||||
if !provider.api_key.is_empty() {
|
||||
request = request.header("x-api-key", &provider.api_key);
|
||||
}
|
||||
if let Some(after_id) = &after_id {
|
||||
request = request.query(&[("after_id", after_id)]);
|
||||
}
|
||||
let response = apply_custom_headers(request, &provider.custom_headers)?
|
||||
.send()
|
||||
.await?;
|
||||
let status = response.status();
|
||||
let body: serde_json::Value = response.json().await?;
|
||||
if !status.is_success() {
|
||||
return Err(Error::Provider(format!(
|
||||
"model discovery failed ({status}): {body}"
|
||||
)));
|
||||
}
|
||||
found.extend(model_ids(body.get("data").unwrap_or(&body)));
|
||||
if body.get("has_more").and_then(serde_json::Value::as_bool) != Some(true) {
|
||||
break;
|
||||
}
|
||||
after_id = body
|
||||
.get("last_id")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::to_owned);
|
||||
if after_id.is_none() {
|
||||
return Err(Error::Provider(
|
||||
"Anthropic model response has_more without last_id".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(found.into_iter().collect())
|
||||
}
|
||||
|
||||
fn model_ids(value: &serde_json::Value) -> Vec<String> {
|
||||
value
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|item| match item {
|
||||
serde_json::Value::String(id) => Some(id.clone()),
|
||||
serde_json::Value::Object(object) => object
|
||||
.get("id")
|
||||
.or_else(|| object.get("name"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::to_owned),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn apply_custom_headers(
|
||||
mut request: reqwest::RequestBuilder,
|
||||
headers: &serde_json::Value,
|
||||
) -> Result<reqwest::RequestBuilder> {
|
||||
let object = headers
|
||||
.as_object()
|
||||
.ok_or_else(|| Error::Config("custom headers must be an object".into()))?;
|
||||
for (name, value) in object {
|
||||
let value = value
|
||||
.as_str()
|
||||
.ok_or_else(|| Error::Config(format!("custom header {name} must be a string")))?;
|
||||
let name = HeaderName::try_from(name)
|
||||
.map_err(|error| Error::Config(format!("invalid header name: {error}")))?;
|
||||
let value = HeaderValue::try_from(value)
|
||||
.map_err(|error| Error::Config(format!("invalid header value: {error}")))?;
|
||||
request = request.header(name, value);
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
use crate::Result;
|
||||
use axum::{extract::State, Json};
|
||||
|
||||
use crate::store::{PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage};
|
||||
|
||||
use super::{ControlService, ObservabilitySettings};
|
||||
|
||||
pub async fn get(State(service): State<ControlService>) -> Result<Json<ObservabilitySettings>> {
|
||||
Ok(Json(service.observability().await?))
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
State(service): State<ControlService>,
|
||||
Json(settings): Json<ObservabilitySettings>,
|
||||
) -> Result<Json<ObservabilitySettings>> {
|
||||
Ok(Json(service.set_observability(settings).await?))
|
||||
}
|
||||
|
||||
pub async fn get_ports(State(service): State<ControlService>) -> Result<Json<PortSettings>> {
|
||||
Ok(Json(service.ports().await?))
|
||||
}
|
||||
|
||||
pub async fn update_ports(
|
||||
State(service): State<ControlService>,
|
||||
Json(settings): Json<PortSettings>,
|
||||
) -> Result<Json<PortSettings>> {
|
||||
Ok(Json(service.set_ports(settings).await?))
|
||||
}
|
||||
|
||||
pub async fn get_storage(State(service): State<ControlService>) -> Result<Json<StatisticsStorage>> {
|
||||
Ok(Json(service.statistics_storage().await?))
|
||||
}
|
||||
|
||||
pub async fn clear_storage(
|
||||
State(service): State<ControlService>,
|
||||
) -> Result<Json<StatisticsStorage>> {
|
||||
Ok(Json(service.clear_statistics_storage().await?))
|
||||
}
|
||||
|
||||
pub async fn get_proxy(State(service): State<ControlService>) -> Result<Json<ProxySettings>> {
|
||||
Ok(Json(service.proxy_settings().await?))
|
||||
}
|
||||
|
||||
pub async fn update_proxy(
|
||||
State(service): State<ControlService>,
|
||||
Json(settings): Json<ProxySettingsInput>,
|
||||
) -> Result<Json<ProxySettings>> {
|
||||
Ok(Json(service.set_proxy_settings(settings).await?))
|
||||
}
|
||||
Reference in new issue
Block a user