feat: initialize server structure and database schema

- Added initial server setup with Cargo.toml defining dependencies and project structure.
- Created build.rs for generating protobuf bindings and validating wire contracts.
- Established database schema with initial migration files for conversations, messages, and runs.
- Introduced tools and prompts for Cursor functionality, enhancing user interaction capabilities.
This commit is contained in:
leookun committed 2026-08-30 01:33:39 +08:00
1 parent d200b3791d
commit 44e2d8057a
206 files changed
+37923 -21

No files matched your search

+148
View File
@@ -0,0 +1,148 @@
//! Implements advertisement configuration endpoints.
//! 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 = "https://tab.leokun.cn/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";
pub(super) const LANGUAGE_HEADER: &str = "accept-language";
#[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, ad_language(&headers)).await?,
))
}
fn ad_language(headers: &HeaderMap) -> &'static str {
match headers
.get(LANGUAGE_HEADER)
.and_then(|value| value.to_str().ok())
{
Some(value) if value.eq_ignore_ascii_case("zh-CN") => "zh-CN",
_ => "en-US",
}
}
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)
}
+34
View File
@@ -0,0 +1,34 @@
//! Implements provider call inspection endpoints.
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
}
+28
View File
@@ -0,0 +1,28 @@
//! Implements local application control endpoints.
use axum::{extract::State, Json};
use crate::{
local_app::{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?,
))
}
+221
View File
@@ -0,0 +1,221 @@
//! Exposes the local control API.
mod ads;
mod calls;
mod harness;
mod models;
mod overview;
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, LegacyModelImportPreview,
LegacyModelImportResult, ModelConnectivityResult, ModelDiscoveryInput, 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/models",
get(models::list).post(models::create),
)
.route("/__byok-api__/api/models/discover", post(models::discover))
.route(
"/__byok-api__/api/models/import-v0049",
get(models::preview_v0049).post(models::import_v0049),
)
.route("/__byok-api__/api/models/order", put(models::reorder))
.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/models/{model_hash}/test/{test_id}",
post(models::test).delete(models::cancel),
)
.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/settings/tab",
get(settings::get_tab).put(settings::update_tab),
)
.route(
"/__byok-api__/api/settings/desktop",
get(settings::get_desktop).put(settings::update_desktop),
)
.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),
)
.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::ACCEPT_LANGUAGE,
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,
}
}
+98
View File
@@ -0,0 +1,98 @@
//! Implements model configuration endpoints.
use axum::{
extract::{Path, State},
http::StatusCode,
Json,
};
use serde::Deserialize;
use crate::{
model::{ModelConfig, ModelConfigInput},
Result,
};
use super::{
ControlService, DiscoveredModels, LegacyModelImportPreview, LegacyModelImportResult,
ModelConnectivityResult, ModelDiscoveryInput,
};
#[derive(Deserialize)]
pub struct SaveModels {
pub models: Vec<ModelConfigInput>,
}
#[derive(Deserialize)]
pub struct ModelOrder {
pub model_hashes: Vec<String>,
}
pub async fn list(State(service): State<ControlService>) -> Result<Json<Vec<ModelConfig>>> {
Ok(Json(service.models().await?))
}
pub async fn create(
State(service): State<ControlService>,
Json(input): Json<SaveModels>,
) -> Result<(StatusCode, Json<Vec<ModelConfig>>)> {
Ok((
StatusCode::CREATED,
Json(service.create_models(&input.models).await?),
))
}
pub async fn reorder(
State(service): State<ControlService>,
Json(input): Json<ModelOrder>,
) -> Result<Json<Vec<ModelConfig>>> {
Ok(Json(service.reorder_models(&input.model_hashes).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<ModelConfigInput>,
) -> Result<Json<ModelConfig>> {
Ok(Json(service.update_model(&model_hash, &input).await?))
}
pub async fn test(
State(service): State<ControlService>,
Path((model_hash, test_id)): Path<(String, String)>,
) -> Result<Json<ModelConnectivityResult>> {
Ok(Json(service.test_model(&model_hash, &test_id).await?))
}
pub async fn cancel(
State(service): State<ControlService>,
Path((_model_hash, test_id)): Path<(String, String)>,
) -> Result<StatusCode> {
service.cancel_model_test(&test_id);
Ok(StatusCode::NO_CONTENT)
}
pub async fn discover(
State(service): State<ControlService>,
Json(input): Json<ModelDiscoveryInput>,
) -> Result<Json<DiscoveredModels>> {
Ok(Json(service.discover_models(&input).await?))
}
pub async fn import_v0049(
State(service): State<ControlService>,
) -> Result<Json<LegacyModelImportResult>> {
Ok(Json(service.import_v0049_models().await?))
}
pub async fn preview_v0049(
State(service): State<ControlService>,
) -> Result<Json<LegacyModelImportPreview>> {
Ok(Json(service.preview_v0049_models().await?))
}
+30
View File
@@ -0,0 +1,30 @@
//! Implements control dashboard overview endpoints.
//! 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>,
}
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())
.await?,
))
}
+932
View File
@@ -0,0 +1,932 @@
//! Implements control API routing and shared state.
use std::{
collections::{BTreeMap, BTreeSet},
sync::{Arc, Mutex},
time::Instant,
};
use base64::{engine::general_purpose::STANDARD, Engine};
use futures_util::StreamExt;
use reqwest::header::{HeaderName, HeaderValue};
use serde::{Deserialize, Serialize};
use tokio_util::sync::CancellationToken;
use url::Url;
use super::ads::{
AdDismissalInput, AdRuntime, ADS_ENDPOINT, APP_VERSION_HEADER, DEVICE_ID_HEADER,
DISABLED_AD_IDS_HEADER, LANGUAGE_HEADER, OS_HEADER,
};
use crate::{
local_app::CursorHarness,
model::{
ContentPart, CursorRunTraceArtifact, CursorRunTraceSummary, LlmCallRequest,
LlmCallResponseChunk, LlmCallSummary, ModelConfig, ModelConfigInput, ModelInvocation,
ModelRequest, ModelSpec, ModelType, Overview, ProjectedContent, ProjectedMessage,
PromptSpec, ProviderType, Role,
},
provider::{is_valid_response_event, ModelEvent, Provider},
store::{
DesktopSettings, PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage, Store,
TabSettings,
},
Error, Result,
};
#[derive(Clone)]
pub struct ControlService {
store: Store,
cursor_harness: CursorHarness,
provider: Arc<dyn Provider>,
model_tests: Arc<Mutex<BTreeMap<String, CancellationToken>>>,
}
#[derive(Clone, Debug, Serialize)]
pub struct DiscoveredModels {
pub models: Vec<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct LegacyModelImportResult {
pub imported: usize,
pub skipped: usize,
pub total: usize,
}
#[derive(Clone, Debug, Serialize)]
pub struct LegacyModelImportPreview {
pub source: String,
pub total: usize,
pub new_models: usize,
pub existing_models: usize,
pub models: Vec<LegacyModelImportPreviewItem>,
}
#[derive(Clone, Debug, Serialize)]
pub struct LegacyModelImportPreviewItem {
pub model_hash: String,
pub display_name: String,
pub model_id: String,
#[serde(rename = "type")]
pub model_type: ModelType,
pub existing: bool,
}
#[derive(Clone, Debug, Deserialize)]
pub struct ModelDiscoveryInput {
#[serde(rename = "type")]
pub model_type: ModelType,
pub base_url: String,
pub api_key: String,
#[serde(default)]
pub custom_headers_enabled: bool,
#[serde(default = "empty_json_object")]
pub custom_headers: serde_json::Value,
}
fn empty_json_object() -> serde_json::Value {
serde_json::json!({})
}
fn empty_json_object_ref() -> &'static serde_json::Value {
static EMPTY: std::sync::OnceLock<serde_json::Value> = std::sync::OnceLock::new();
EMPTY.get_or_init(empty_json_object)
}
#[derive(Clone, Debug, Serialize)]
pub struct ModelConnectivityResult {
pub duration_ms: u64,
pub first_valid_response_ms: Option<u64>,
pub output_tokens: u64,
pub tokens_per_second: f64,
pub tokens_estimated: bool,
pub output: 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, provider: Arc<dyn Provider>) -> Result<Self> {
Ok(Self {
cursor_harness: CursorHarness::new(store.clone())?,
store,
provider,
model_tests: Arc::new(Mutex::new(BTreeMap::new())),
})
}
pub fn cursor_harness(&self) -> &CursorHarness {
&self.cursor_harness
}
pub(super) async fn ads(
&self,
disabled_ad_ids: Option<&str>,
language: &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"))
.header(LANGUAGE_HEADER, language)
.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 models(&self) -> Result<Vec<ModelConfig>> {
self.store.models().await
}
pub async fn overview(
&self,
start_ms: Option<i64>,
end_ms: Option<i64>,
model_hashes: Option<&str>,
) -> Result<Overview> {
self.store.overview(start_ms, end_ms, model_hashes).await
}
pub async fn create_models(&self, models: &[ModelConfigInput]) -> Result<Vec<ModelConfig>> {
self.store.create_models(models).await
}
pub async fn reorder_models(&self, model_hashes: &[String]) -> Result<Vec<ModelConfig>> {
self.store.reorder_models(model_hashes).await
}
pub async fn delete_model(&self, model_hash: &str) -> Result<()> {
self.store.delete_model(model_hash).await
}
pub async fn update_model(
&self,
model_hash: &str,
input: &ModelConfigInput,
) -> Result<ModelConfig> {
self.store.update_model(model_hash, input).await
}
pub async fn test_model(
&self,
model_hash: &str,
test_id: &str,
) -> Result<ModelConnectivityResult> {
let cancellation = CancellationToken::new();
let cancellation = {
let mut tests = self
.model_tests
.lock()
.expect("model test registry mutex poisoned");
tests
.entry(test_id.to_owned())
.or_insert_with(|| cancellation.clone())
.clone()
};
let result = self.run_model_test(model_hash, cancellation).await;
self.model_tests
.lock()
.expect("model test registry mutex poisoned")
.remove(test_id);
result
}
pub fn cancel_model_test(&self, test_id: &str) {
let cancellation = {
let mut tests = self
.model_tests
.lock()
.expect("model test registry mutex poisoned");
tests.entry(test_id.to_owned()).or_default().clone()
};
cancellation.cancel();
}
async fn run_model_test(
&self,
model_hash: &str,
cancellation: CancellationToken,
) -> Result<ModelConnectivityResult> {
const TEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(45);
const TEST_PROMPT: &str = "Output the numbers 1 through 120 separated by a single space. No commas, no newlines, no explanation.";
let configured = self
.store
.model(model_hash)
.await?
.ok_or_else(|| Error::RunNotFound(format!("model {model_hash}")))?;
let mut model = ModelSpec::new(model_hash);
configured.configure(&mut model);
model.max_output_tokens = Some(configured.max_output_tokens().unwrap_or(65_536));
let call_id = format!("model-test-{}", uuid::Uuid::new_v4());
let invocation = ModelInvocation {
call_id: call_id.clone(),
run_id: call_id.clone(),
conversation_id: call_id.clone(),
provider_call_index: 0,
request: ModelRequest {
prompt: PromptSpec {
instructions: String::new(),
tools: Vec::new(),
},
model,
history: vec![ProjectedMessage {
message_id: "connectivity-test".into(),
role: Role::User,
content: ProjectedContent::Parts(vec![ContentPart::Text {
text: TEST_PROMPT.into(),
}]),
}],
},
};
let started = Instant::now();
let mut first_valid_response_at = None;
let mut output_tokens = None;
let mut output = String::new();
let stream = self.provider.stream(invocation, cancellation.clone());
let completed = tokio::time::timeout(TEST_TIMEOUT, async {
futures_util::pin_mut!(stream);
let mut finished = false;
while let Some(event) = stream.next().await {
let event = event?;
if first_valid_response_at.is_none() && is_valid_response_event(&event) {
first_valid_response_at = Some(Instant::now());
}
match event {
ModelEvent::TextDelta(delta) => {
output.push_str(&delta);
}
ModelEvent::Usage(usage) => {
if let Some(tokens) = usage.output_tokens.filter(|tokens| *tokens > 0) {
output_tokens = Some(
output_tokens.map_or(tokens, |current: u64| current.max(tokens)),
);
}
}
ModelEvent::Done(_) => finished = true,
_ => {}
}
}
if cancellation.is_cancelled() {
return Err(Error::Cancelled);
}
if !finished {
return Err(Error::Protocol(
"provider stream ended without Done during connectivity test".into(),
));
}
Ok(())
})
.await;
match completed {
Ok(result) => result?,
Err(_) => {
cancellation.cancel();
self.store
.finish_llm_call(
&call_id,
"error",
None,
started.elapsed().as_millis().min(i64::MAX as u128) as i64,
Some("timeout"),
Some("model connectivity test timed out after 45 seconds"),
)
.await?;
return Err(Error::Provider(
"model connectivity test timed out after 45 seconds".into(),
));
}
}
let elapsed = started.elapsed();
let output = output.trim().to_string();
if first_valid_response_at.is_none() {
return Err(Error::Provider(
"model connectivity test received no valid response".into(),
));
}
let tokens_estimated = output_tokens.is_none();
let output_tokens = output_tokens.unwrap_or_else(|| estimate_output_tokens(&output));
Ok(ModelConnectivityResult {
duration_ms: elapsed.as_millis().min(u128::from(u64::MAX)) as u64,
first_valid_response_ms: first_valid_response_at.map(|first| {
first
.duration_since(started)
.as_millis()
.min(u128::from(u64::MAX)) as u64
}),
output_tokens,
tokens_per_second: if elapsed.is_zero() {
0.0
} else {
output_tokens as f64 / elapsed.as_secs_f64()
},
tokens_estimated,
output,
})
}
pub async fn discover_models(&self, input: &ModelDiscoveryInput) -> Result<DiscoveredModels> {
let client = crate::network::client(&self.store).await?;
let base_url = crate::model::normalize_request_url(&input.base_url)?;
discover_models_from_endpoint(
&client,
match input.model_type {
ModelType::OpenAi => ProviderType::OpenAiResponses,
ModelType::Anthropic => ProviderType::Anthropic,
},
&base_url,
&input.api_key,
if input.custom_headers_enabled {
&input.custom_headers
} else {
empty_json_object_ref()
},
)
.await
}
pub async fn import_v0049_models(&self) -> Result<LegacyModelImportResult> {
let path = crate::config::v0049_config_path()?;
let outcome = self.store.import_v0049_model_config(&path).await?;
Ok(LegacyModelImportResult {
imported: outcome.imported,
skipped: outcome.skipped,
total: outcome.total,
})
}
pub async fn preview_v0049_models(&self) -> Result<LegacyModelImportPreview> {
let path = crate::config::v0049_config_path()?;
let plan = self.store.preview_v0049_model_config(&path).await?;
let total = plan.models.len();
let existing_models = plan.models.iter().filter(|model| model.existing).count();
Ok(LegacyModelImportPreview {
source: path.display().to_string(),
total,
new_models: total - existing_models,
existing_models,
models: plan
.models
.into_iter()
.map(|model| LegacyModelImportPreviewItem {
model_hash: model.model_hash,
display_name: model.input.display_name,
model_id: model.input.model_id,
model_type: model.input.model_type,
existing: model.existing,
})
.collect(),
})
}
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 clear_all_statistics_storage(&self) -> Result<StatisticsStorage> {
self.store.clear_all_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
}
pub async fn tab_settings(&self) -> Result<TabSettings> {
self.store.tab_settings().await
}
pub async fn set_tab_settings(&self, settings: TabSettings) -> Result<TabSettings> {
self.cursor_harness.set_tab_settings(settings).await
}
pub async fn desktop_settings(&self) -> Result<DesktopSettings> {
self.store.desktop_settings().await
}
pub async fn set_desktop_settings(&self, settings: DesktopSettings) -> Result<()> {
self.store.set_desktop_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,
first_valid_response_at_ms: None,
finished_at_ms: trace.finished_at_ms,
queue_ms: None,
ttfb_ms: ttfb,
ttft_ms: None,
ttfr_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 discover_models_from_endpoint(
client: &reqwest::Client,
provider_type: ProviderType,
base_url: &str,
api_key: &str,
custom_headers: &serde_json::Value,
) -> Result<DiscoveredModels> {
let mut models = match provider_type {
ProviderType::OpenAiChat | ProviderType::OpenAiResponses => {
openai_models(client, base_url, api_key, custom_headers).await?
}
ProviderType::Anthropic => {
anthropic_models(client, base_url, api_key, custom_headers).await?
}
};
models.sort();
models.dedup();
Ok(DiscoveredModels { models })
}
fn model_discovery_url(base_url: &str) -> Result<Url> {
let mut url = Url::parse(base_url)
.map_err(|error| Error::Config(format!("invalid model request URL: {error}")))?;
if url.host_str().is_none() {
return Err(Error::Config(
"model request URL must contain a host".into(),
));
}
// 在现有路径上追加,而不是整段替换:多数编程套餐的 API 挂在子路径下
// (/api/anthropic、/coding、/api/paas/v4 等),直接 set_path("/v1/models")
// 会把这些前缀吃掉,发现请求必然 404
let path = url.path().trim_end_matches('/');
let last = path.rsplit('/').next().unwrap_or("");
let versioned = last.len() > 1
&& last.starts_with('v')
&& last[1..].bytes().all(|byte| byte.is_ascii_digit());
let new_path = if let Some(parent) = path.strip_suffix("/chat/completions") {
// 完整请求 URL:剥掉端点段(chat/completions 是两段),换成 models
format!("{parent}/models")
} else if let Some(parent) = path
.strip_suffix("/responses")
.or_else(|| path.strip_suffix("/messages"))
.or_else(|| path.strip_suffix("/completions"))
{
format!("{parent}/models")
} else if path.is_empty() {
"/v1/models".to_string()
} else if versioned {
// 已带版本段(/v1、/api/v3、/api/paas/v4):只补 models
format!("{path}/models")
} else {
format!("{path}/v1/models")
};
url.set_path(&new_path);
url.set_query(None);
url.set_fragment(None);
Ok(url)
}
fn model_discovery_urls(base_url: &str) -> Result<Vec<Url>> {
let mut configured = Url::parse(base_url)
.map_err(|error| Error::Config(format!("invalid model request URL: {error}")))?;
let path = configured.path().trim_end_matches('/');
let tail = path.rsplit('/').next().unwrap_or_default();
if matches!(tail.to_ascii_lowercase().as_str(), "model" | "models") {
configured.set_query(None);
configured.set_fragment(None);
return Ok(vec![configured]);
}
let primary = model_discovery_url(base_url)?;
let versioned = tail.len() > 1
&& tail.starts_with('v')
&& tail[1..].bytes().all(|byte| byte.is_ascii_digit());
let complete_request_url = [
"/chat/completions",
"/responses",
"/messages",
"/completions",
]
.iter()
.any(|suffix| path.to_ascii_lowercase().ends_with(suffix));
if versioned || complete_request_url {
return Ok(vec![primary]);
}
let Some(prefix) = primary.path().strip_suffix("/v1/models") else {
return Ok(vec![primary]);
};
let mut fallback = primary.clone();
fallback.set_path(&format!("{prefix}/models"));
Ok(vec![primary, fallback])
}
async fn openai_models(
client: &reqwest::Client,
base_url: &str,
api_key: &str,
custom_headers: &serde_json::Value,
) -> Result<Vec<String>> {
let mut last_error = None;
for url in model_discovery_urls(base_url)? {
match openai_models_at(client, url, api_key, custom_headers).await {
Ok(models) => return Ok(models),
Err(error) => last_error = Some(error),
}
}
Err(last_error.unwrap_or_else(|| Error::Provider("no model discovery URL available".into())))
}
async fn openai_models_at(
client: &reqwest::Client,
url: Url,
api_key: &str,
custom_headers: &serde_json::Value,
) -> Result<Vec<String>> {
let mut request = client.get(url);
if !api_key.is_empty() {
request = request.bearer_auth(api_key);
}
let response = apply_discovery_headers(request, 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,
base_url: &str,
api_key: &str,
custom_headers: &serde_json::Value,
) -> Result<Vec<String>> {
let mut last_error = None;
for url in model_discovery_urls(base_url)? {
match anthropic_models_at(client, url, api_key, custom_headers).await {
Ok(models) => return Ok(models),
Err(error) => last_error = Some(error),
}
}
Err(last_error.unwrap_or_else(|| Error::Provider("no model discovery URL available".into())))
}
async fn anthropic_models_at(
client: &reqwest::Client,
url: Url,
api_key: &str,
custom_headers: &serde_json::Value,
) -> Result<Vec<String>> {
let mut after_id = None::<String>;
let mut found = BTreeSet::new();
loop {
let mut request = client
.get(url.clone())
.query(&[("limit", "100")])
.header("anthropic-version", "2023-06-01");
if !api_key.is_empty() {
request = request.header("x-api-key", api_key);
}
if let Some(after_id) = &after_id {
request = request.query(&[("after_id", after_id)]);
}
let response = apply_discovery_headers(request, 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 estimate_output_tokens(output: &str) -> u64 {
let words = output.split_whitespace().count() as u64;
if words > 0 {
words
} else if output.is_empty() {
0
} else {
(output.chars().count() as u64).div_ceil(4)
}
}
fn apply_discovery_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 {
if name.eq_ignore_ascii_case("user-agent") {
continue;
}
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)
}
+89
View File
@@ -0,0 +1,89 @@
//! Implements settings management endpoints.
use crate::Result;
use axum::{extract::State, Json};
use serde::Deserialize;
use crate::store::{
DesktopSettings, PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage,
StatisticsStorageScope, TabSettings,
};
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>,
input: Option<Json<ClearStorageInput>>,
) -> Result<Json<StatisticsStorage>> {
let scope = input.map(|Json(input)| input.scope).unwrap_or_default();
let storage = match scope {
StatisticsStorageScope::Details => service.clear_statistics_storage().await?,
StatisticsStorageScope::All => service.clear_all_statistics_storage().await?,
};
Ok(Json(storage))
}
#[derive(Deserialize)]
pub struct ClearStorageInput {
#[serde(default)]
pub scope: StatisticsStorageScope,
}
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?))
}
pub async fn get_tab(State(service): State<ControlService>) -> Result<Json<TabSettings>> {
Ok(Json(service.tab_settings().await?))
}
pub async fn update_tab(
State(service): State<ControlService>,
Json(settings): Json<TabSettings>,
) -> Result<Json<TabSettings>> {
Ok(Json(service.set_tab_settings(settings).await?))
}
pub async fn get_desktop(State(service): State<ControlService>) -> Result<Json<DesktopSettings>> {
Ok(Json(service.desktop_settings().await?))
}
pub async fn update_desktop(
State(service): State<ControlService>,
Json(settings): Json<DesktopSettings>,
) -> Result<Json<DesktopSettings>> {
service.set_desktop_settings(settings).await?;
get_desktop(State(service)).await
}