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

+312
View File
@@ -0,0 +1,312 @@
//! Implements Cursor account information services.
use axum::{
body::{Body, Bytes},
extract::Extension,
http::{header, Request, Response},
};
use prost::Message;
use serde_json::{Map, Value};
use crate::{api::cursor::proxy, Result};
const LOCAL_AUTH_ID: &str = "local_ultra";
const LOCAL_EMAIL: &str = "cursor@ai.com";
const LOCAL_ULTRA_PLAN_INCLUDED_CENTS: i32 = 20_000;
#[derive(Clone, PartialEq, Message)]
struct GetEmailResponse {
#[prost(string, tag = "1")]
email: String,
#[prost(int32, tag = "2")]
sign_up_type: i32,
}
#[derive(Clone, PartialEq, Message)]
struct GetMeResponse {
#[prost(string, tag = "1")]
auth_id: String,
#[prost(int32, tag = "2")]
user_id: i32,
#[prost(string, optional, tag = "3")]
email: Option<String>,
#[prost(string, optional, tag = "4")]
first_name: Option<String>,
#[prost(string, optional, tag = "5")]
last_name: Option<String>,
#[prost(string, optional, tag = "8")]
created_at: Option<String>,
#[prost(bool, optional, tag = "9")]
is_enterprise_user: Option<bool>,
#[prost(string, optional, tag = "11")]
email_domain_type: Option<String>,
#[prost(string, optional, tag = "12")]
country: Option<String>,
}
#[derive(Clone, PartialEq, Message)]
struct GetUserProfileResponse {
#[prost(bool, optional, tag = "4")]
public_visibility_allowed: Option<bool>,
#[prost(string, optional, tag = "5")]
max_visibility: Option<String>,
}
#[derive(Clone, PartialEq, Message)]
struct GetCurrentPeriodUsageResponse {
#[prost(int64, tag = "1")]
billing_cycle_start: i64,
#[prost(int64, tag = "2")]
billing_cycle_end: i64,
#[prost(message, optional, tag = "3")]
plan_usage: Option<PlanUsage>,
#[prost(message, optional, tag = "4")]
spend_limit_usage: Option<SpendLimitUsage>,
#[prost(int32, optional, tag = "5")]
display_threshold: Option<i32>,
#[prost(bool, tag = "6")]
enabled: bool,
#[prost(string, tag = "7")]
display_message: String,
#[prost(string, optional, tag = "11")]
auto_model_selected_display_message: Option<String>,
#[prost(string, optional, tag = "12")]
named_model_selected_display_message: Option<String>,
}
#[derive(Clone, PartialEq, Message)]
struct PlanUsage {
#[prost(int32, tag = "1")]
total_spend: i32,
#[prost(int32, tag = "2")]
included_spend: i32,
#[prost(int32, tag = "4")]
remaining: i32,
#[prost(int32, tag = "5")]
limit: i32,
#[prost(bool, optional, tag = "6")]
remaining_bonus: Option<bool>,
#[prost(string, optional, tag = "7")]
bonus_tooltip: Option<String>,
#[prost(int32, optional, tag = "8")]
auto_spend: Option<i32>,
#[prost(int32, optional, tag = "9")]
api_spend: Option<i32>,
#[prost(double, optional, tag = "12")]
auto_percent_used: Option<f64>,
#[prost(double, optional, tag = "13")]
api_percent_used: Option<f64>,
#[prost(double, optional, tag = "14")]
total_percent_used: Option<f64>,
}
#[derive(Clone, PartialEq, Message)]
struct SpendLimitUsage {
#[prost(string, tag = "8")]
limit_type: String,
}
#[derive(Clone, PartialEq, Message)]
struct GetUsageLimitStatusAndActiveGrantsResponse {
#[prost(message, optional, tag = "1")]
usage_limit_policy_status: Option<UsageLimitPolicyStatus>,
}
#[derive(Clone, PartialEq, Message)]
struct UsageLimitPolicyStatus {
#[prost(bool, tag = "1")]
is_in_slow_pool: bool,
#[prost(map = "string, string", tag = "5")]
features: std::collections::HashMap<String, String>,
#[prost(bool, tag = "6")]
can_configure_spend_limit: bool,
#[prost(bool, tag = "8")]
has_pending_request: bool,
#[prost(string, repeated, tag = "9")]
allowed_model_ids: Vec<String>,
#[prost(string, repeated, tag = "10")]
allowed_model_tags: Vec<String>,
}
#[derive(Clone, Copy, PartialEq, Message)]
struct Empty {}
pub async fn get_email(
Extension(upstream): Extension<proxy::CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
forward_or(upstream, request, || {
proto(GetEmailResponse {
email: LOCAL_EMAIL.into(),
sign_up_type: 3,
})
})
.await
}
pub async fn get_me(
Extension(upstream): Extension<proxy::CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
forward_or(upstream, request, || {
proto(GetMeResponse {
auth_id: LOCAL_AUTH_ID.into(),
user_id: 1,
email: Some(LOCAL_EMAIL.into()),
first_name: Some("Cursor".into()),
last_name: Some("Local".into()),
created_at: Some(chrono::Utc::now().to_rfc3339()),
is_enterprise_user: Some(false),
email_domain_type: Some("personal".into()),
country: Some("US".into()),
})
})
.await
}
pub async fn get_teams(
Extension(upstream): Extension<proxy::CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
forward_or(upstream, request, || proto(Empty {})).await
}
pub async fn get_user_profile(
Extension(upstream): Extension<proxy::CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
forward_or(upstream, request, || {
proto(GetUserProfileResponse {
public_visibility_allowed: Some(true),
max_visibility: Some("PUBLIC".into()),
})
})
.await
}
pub async fn current_period_usage() -> Result<Response<Body>> {
let now = chrono::Utc::now();
proto(GetCurrentPeriodUsageResponse {
billing_cycle_start: (now - chrono::Duration::days(30)).timestamp_millis(),
billing_cycle_end: (now + chrono::Duration::days(10 * 365)).timestamp_millis(),
plan_usage: Some(PlanUsage {
total_spend: 0,
included_spend: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
remaining: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
limit: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
remaining_bonus: Some(false),
bonus_tooltip: Some("Ultra local account mock is active.".into()),
auto_spend: Some(0),
api_spend: Some(0),
auto_percent_used: Some(0.0),
api_percent_used: Some(0.0),
total_percent_used: Some(0.0),
}),
spend_limit_usage: Some(SpendLimitUsage {
limit_type: "user".into(),
}),
display_threshold: Some(99_999_999),
enabled: true,
display_message: "Ultra plan active".into(),
auto_model_selected_display_message: Some("Ultra plan active".into()),
named_model_selected_display_message: Some("Ultra plan active".into()),
})
}
pub async fn usage_limit_status() -> Result<Response<Body>> {
proto(GetUsageLimitStatusAndActiveGrantsResponse {
usage_limit_policy_status: Some(UsageLimitPolicyStatus {
is_in_slow_pool: false,
features: Default::default(),
can_configure_spend_limit: true,
has_pending_request: false,
allowed_model_ids: Vec::new(),
allowed_model_tags: Vec::new(),
}),
})
}
pub async fn stripe_profile(
Extension(upstream): Extension<proxy::CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
match proxy::forward_buffered(&upstream, request).await {
Ok(response) if response.status.is_success() => {
let mut profile = serde_json::from_slice::<Map<String, Value>>(&response.body)?;
ultra(&mut profile);
Ok(response.with_body(Bytes::from(serde_json::to_vec(&profile)?)))
}
Ok(response) => {
tracing::warn!(status = %response.status, "Cursor account upstream rejected profile; using local Ultra identity");
json(ultra_profile())
}
Err(error) => {
tracing::warn!(%error, "Cursor account upstream unavailable; using local Ultra identity");
json(ultra_profile())
}
}
}
async fn forward_or(
upstream: proxy::CursorProxy,
request: Request<Body>,
fallback: impl FnOnce() -> Result<Response<Body>>,
) -> Result<Response<Body>> {
match proxy::forward_buffered(&upstream, request).await {
Ok(response) if response.status.is_success() => Ok(response.into_response()),
Ok(response) => {
tracing::warn!(status = %response.status, "Cursor identity upstream rejected request; using local identity");
fallback()
}
Err(error) => {
tracing::warn!(%error, "Cursor identity upstream unavailable; using local identity");
fallback()
}
}
}
fn proto(message: impl Message) -> Result<Response<Body>> {
response("application/proto", message.encode_to_vec())
}
fn json(value: Value) -> Result<Response<Body>> {
response("application/json", serde_json::to_vec(&value)?)
}
fn response(content_type: &'static str, body: Vec<u8>) -> Result<Response<Body>> {
let length = body.len();
let mut response = Response::new(Body::from(body));
response.headers_mut().insert(
header::CONTENT_TYPE,
axum::http::HeaderValue::from_static(content_type),
);
response.headers_mut().insert(
header::CONTENT_LENGTH,
length
.to_string()
.parse()
.expect("body length is always a valid header value"),
);
Ok(response)
}
fn ultra(profile: &mut Map<String, Value>) {
profile.insert("membershipType".into(), Value::String("ultra".into()));
profile.insert(
"individualMembershipType".into(),
Value::String("ultra".into()),
);
profile.insert("subscriptionStatus".into(), Value::String("active".into()));
}
fn ultra_profile() -> Value {
serde_json::json!({
"membershipType": "ultra",
"individualMembershipType": "ultra",
"subscriptionStatus": "active",
"lastPaymentFailed": false,
"pendingCancellationDate": null,
"daysRemainingOnTrial": 0,
"paymentId": LOCAL_AUTH_ID,
"isTeamMember": false
})
}
+176
View File
@@ -0,0 +1,176 @@
//! Implements Cursor analytics endpoints and event handling.
use axum::{
body::{Body, Bytes},
extract::Extension,
http::{header, HeaderValue, Request, Response, StatusCode},
};
use base64::{engine::general_purpose::STANDARD, Engine};
use bytes::{BufMut, BytesMut};
use prost::Message;
use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};
use crate::{api::cursor::proxy, Error, Result};
pub const BOOTSTRAP_STATSIG_PATH: &str = "/aiserver.v1.AnalyticsService/BootstrapStatsig";
const AGENT_RETRIES_GATE: &str = "nal_agent_retries";
const LOCAL_RULE: &str = "local_enabled";
#[derive(Clone, PartialEq, Message)]
struct BootstrapStatsigResponse {
#[prost(string, tag = "1")]
config: String,
#[prost(uint64, tag = "2")]
generated_at_ms: u64,
}
pub async fn bootstrap_statsig(
Extension(upstream): Extension<proxy::CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
match proxy::forward_buffered(&upstream, request).await {
Ok(response) if response.status.is_success() => match patch_upstream(response) {
Ok(response) => Ok(response),
Err(error) => {
tracing::warn!(%error, "Cursor Statsig bootstrap was invalid; using local bootstrap");
local_response()
}
},
Ok(response) => {
tracing::warn!(status = %response.status, "Cursor Statsig bootstrap was rejected; using local bootstrap");
local_response()
}
Err(error) => {
tracing::warn!(%error, "Cursor Statsig bootstrap was unavailable; using local bootstrap");
local_response()
}
}
}
fn patch_upstream(response: proxy::BufferedResponse) -> Result<Response<Body>> {
let (framed, payload) = unary_payload(&response.body)?;
let mut message = BootstrapStatsigResponse::decode(payload)?;
let mut config = serde_json::from_str::<Value>(&message.config)?;
enable_agent_retries(&mut config)?;
message.config = serde_json::to_string(&config)?;
Ok(response.with_body(encode_unary(&message, framed)))
}
fn local_response() -> Result<Response<Body>> {
let generated_at_ms = chrono::Utc::now().timestamp_millis() as u64;
let mut config = json!({
"feature_gates": {},
"dynamic_configs": {},
"layer_configs": {},
"user": {
"userID": "local_ultra",
"customIDs": { "localUserID": "local_ultra" }
},
"has_updates": true,
"hash_used": "none",
"sdkParams": {
"stableID": "local_ultra",
"disableDiagnosticsLogging": true
},
"time": generated_at_ms
});
enable_agent_retries(&mut config)?;
let message = BootstrapStatsigResponse {
config: serde_json::to_string(&config)?,
generated_at_ms,
};
let body = message.encode_to_vec();
let mut response = Response::new(Body::from(body.clone()));
*response.status_mut() = StatusCode::OK;
response.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/proto"),
);
response.headers_mut().insert(
header::CONTENT_LENGTH,
body.len()
.to_string()
.parse()
.expect("body length is a valid header value"),
);
Ok(response)
}
fn enable_agent_retries(config: &mut Value) -> Result<()> {
let gate_key = statsig_key(config, AGENT_RETRIES_GATE);
let root = config
.as_object_mut()
.ok_or_else(|| Error::Protocol("Statsig bootstrap config must be an object".into()))?;
let gates = root
.entry("feature_gates")
.or_insert_with(|| Value::Object(Map::new()))
.as_object_mut()
.ok_or_else(|| Error::Protocol("Statsig feature_gates must be an object".into()))?;
gates.insert(gate_key.clone(), enabled_gate(&gate_key));
Ok(())
}
fn statsig_key(config: &Value, name: &str) -> String {
match config.get("hash_used").and_then(Value::as_str) {
Some("djb2") => djb2(name),
Some("sha256") => STANDARD.encode(Sha256::digest(name.as_bytes())),
_ => name.to_owned(),
}
}
fn djb2(value: &str) -> String {
value
.encode_utf16()
.fold(0_u32, |hash, character| {
hash.wrapping_mul(31).wrapping_add(u32::from(character))
})
.to_string()
}
fn enabled_gate(name: &str) -> Value {
json!({
"name": name,
"value": true,
"rule_id": LOCAL_RULE,
"ruleID": LOCAL_RULE,
"group_name": LOCAL_RULE,
"groupName": LOCAL_RULE,
"secondary_exposures": [],
"secondaryExposures": [],
"undelegated_secondary_exposures": [],
"undelegatedSecondaryExposures": [],
"is_device_based": false,
"isDeviceBased": false,
"id_type": "userID",
"idType": "userID"
})
}
fn unary_payload(body: &Bytes) -> Result<(bool, &[u8])> {
if body.len() < 5 {
return Ok((false, body));
}
let flags = body[0];
let length = u32::from_be_bytes([body[1], body[2], body[3], body[4]]) as usize;
if length != body.len() - 5 {
return Ok((false, body));
}
if flags != 0 {
return Err(Error::Protocol(format!(
"cannot patch compressed or terminal Statsig frame: flags={flags}"
)));
}
Ok((true, &body[5..]))
}
fn encode_unary(message: &impl Message, framed: bool) -> Bytes {
let payload = message.encode_to_vec();
if !framed {
return Bytes::from(payload);
}
let mut output = BytesMut::with_capacity(5 + payload.len());
output.put_u8(0);
output.put_u32(payload.len() as u32);
output.extend_from_slice(&payload);
output.freeze()
}
+320
View File
@@ -0,0 +1,320 @@
//! Synchronizes content-addressed blobs with Cursor.
use std::{
collections::{HashMap, HashSet},
sync::{
atomic::{AtomicU32, Ordering},
Arc,
},
time::Duration,
};
use tokio::sync::{oneshot, Mutex};
use crate::{
cursor::protocol::proto::agent::v1 as pb,
cursor::services::observability::CursorTraceRecorder,
cursor::transport::TransportHandle,
store::{BlobEdge, BlobId, Store},
Error, Result,
};
type BlobSetSender = oneshot::Sender<Result<()>>;
#[derive(Clone)]
pub struct BlobSynchronizer {
inner: Arc<Inner>,
}
struct Inner {
request_id: String,
store: Store,
handle: TransportHandle,
next_id: AtomicU32,
set_requests: Mutex<HashMap<u32, PendingSet>>,
acked_blobs: Mutex<HashSet<BlobId>>,
get_requests: Mutex<HashMap<u32, PendingGet>>,
}
struct PendingSet {
blob_id: BlobId,
sent_at: std::time::Instant,
result: BlobSetSender,
}
struct PendingGet {
blob_id: BlobId,
result: oneshot::Sender<Result<Option<Vec<u8>>>>,
}
impl BlobSynchronizer {
pub fn new(request_id: String, store: Store, handle: TransportHandle) -> Self {
Self {
inner: Arc::new(Inner {
request_id,
store,
handle,
next_id: AtomicU32::new(1),
set_requests: Mutex::new(HashMap::new()),
acked_blobs: Mutex::new(HashSet::new()),
get_requests: Mutex::new(HashMap::new()),
}),
}
}
pub fn request_id(&self) -> &str {
&self.inner.request_id
}
pub(crate) fn trace(&self) -> Option<&CursorTraceRecorder> {
self.inner.handle.trace()
}
pub async fn persist(&self, data: &[u8], edges: &[BlobEdge]) -> Result<BlobId> {
let id = self.inner.store.put_blob(data, edges).await?;
let result = self.ensure_set(&id, data).await;
if let Some(trace) = self.inner.handle.trace() {
trace
.linked_blob(
"blob_set",
"byok_server",
&id,
serde_json::json!({
"byte_count": data.len(),
"status": if result.is_ok() { "acknowledged" } else { "error" },
"error": result.as_ref().err().map(ToString::to_string),
"edges": edges.iter().map(|edge| serde_json::json!({
"child_blob_id": edge.child.to_base64(),
"field_name": edge.field_name,
})).collect::<Vec<_>>(),
}),
)
.await;
}
result?;
Ok(id)
}
async fn ensure_set(&self, blob_id: &BlobId, data: &[u8]) -> Result<()> {
if self.inner.acked_blobs.lock().await.contains(blob_id) {
return Ok(());
}
let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
let (sender, receiver) = oneshot::channel();
self.inner.set_requests.lock().await.insert(
id,
PendingSet {
blob_id: blob_id.clone(),
sent_at: std::time::Instant::now(),
result: sender,
},
);
if let Err(error) = self.inner.handle.emit(&pb::AgentServerMessage {
ttft_breakdown: None,
message: Some(pb::agent_server_message::Message::KvServerMessage(
pb::KvServerMessage {
id,
span_context: None,
message: Some(pb::kv_server_message::Message::SetBlobArgs(
pb::SetBlobArgs {
blob_id: blob_id.as_bytes().to_vec(),
blob_data: data.to_vec(),
},
)),
},
)),
}) {
self.inner.set_requests.lock().await.remove(&id);
return Err(error);
}
let cancellation = self.inner.handle.disconnect_token();
let result = tokio::select! {
result = receiver => result.map_err(|_| Error::Protocol("KV SET response channel closed".into()))?,
_ = cancellation.cancelled() => Err(Error::Cancelled),
_ = tokio::time::sleep(Duration::from_secs(60)) => Err(Error::Protocol(format!("KV SET timed out: {}", blob_id.to_base64()))),
};
if result.is_err() {
self.inner.set_requests.lock().await.remove(&id);
}
result
}
pub async fn get(&self, blob_id: &BlobId) -> Result<Option<Vec<u8>>> {
if let Some(data) = self.inner.store.get_blob(blob_id).await? {
if let Some(trace) = self.inner.handle.trace() {
trace
.linked_blob(
"blob_get",
"byok_server",
blob_id,
serde_json::json!({
"byte_count": data.len(),
"source": "local_store",
"status": "found",
}),
)
.await;
}
return Ok(Some(data));
}
let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
let (sender, receiver) = oneshot::channel();
self.inner.get_requests.lock().await.insert(
id,
PendingGet {
blob_id: blob_id.clone(),
result: sender,
},
);
self.inner.handle.emit(&pb::AgentServerMessage {
ttft_breakdown: None,
message: Some(pb::agent_server_message::Message::KvServerMessage(
pb::KvServerMessage {
id,
span_context: None,
message: Some(pb::kv_server_message::Message::GetBlobArgs(
pb::GetBlobArgs {
blob_id: blob_id.as_bytes().to_vec(),
},
)),
},
)),
})?;
let cancellation = self.inner.handle.disconnect_token();
let result = tokio::select! {
result = receiver => result.map_err(|_| Error::Protocol("KV GET response channel closed".into()))?,
_ = cancellation.cancelled() => Err(Error::Cancelled),
_ = tokio::time::sleep(Duration::from_secs(60)) => Err(Error::Protocol(format!("KV GET timed out: {}", blob_id.to_base64()))),
};
if result.is_err() {
self.inner.get_requests.lock().await.remove(&id);
}
if let Some(trace) = self.inner.handle.trace() {
match &result {
Ok(Some(data)) => {
trace
.linked_blob(
"blob_get",
"cursor_client",
blob_id,
serde_json::json!({
"byte_count": data.len(),
"source": "cursor_client",
"status": "found",
}),
)
.await;
}
Ok(None) => {
trace
.artifact(
"blob_get",
"cursor_client",
&[],
serde_json::json!({
"blob_id": blob_id.to_base64(),
"status": "missing",
}),
)
.await;
}
Err(error) => {
trace
.artifact(
"blob_get",
"cursor_client",
&[],
serde_json::json!({
"blob_id": blob_id.to_base64(),
"status": "error",
"error": error.to_string(),
}),
)
.await;
}
}
}
result
}
pub async fn cache_received(&self, blob_id: &BlobId, data: &[u8]) -> Result<()> {
let actual = BlobId::digest(data);
if actual != *blob_id {
return Err(Error::Protocol(format!(
"received Blob hash mismatch: expected {}, got {}",
blob_id.to_base64(),
actual.to_base64()
)));
}
self.inner.store.put_blob(data, &[]).await?;
Ok(())
}
pub async fn handle_client(&self, message: pb::KvClientMessage) -> Result<()> {
match message.message {
Some(pb::kv_client_message::Message::SetBlobResult(result)) => {
if let Some(pending) = self.inner.set_requests.lock().await.remove(&message.id) {
if let Some(error) = result.error {
tracing::error!(
request_id = self.request_id(),
kv_id = message.id,
blob_id = pending.blob_id.to_base64(),
error = error.message,
"Cursor rejected Blob SET"
);
let _ = pending.result.send(Err(Error::Protocol(format!(
"KV SET {}: {}",
pending.blob_id.to_base64(),
error.message
))));
} else {
tracing::debug!(
request_id = self.request_id(),
kv_id = message.id,
blob_id = pending.blob_id.to_base64(),
elapsed_ms = pending.sent_at.elapsed().as_millis(),
"Cursor acknowledged Blob SET"
);
self.inner.acked_blobs.lock().await.insert(pending.blob_id);
let _ = pending.result.send(Ok(()));
}
} else {
tracing::warn!(
request_id = self.request_id(),
kv_id = message.id,
"unknown Cursor Blob SET acknowledgement"
);
}
}
Some(pb::kv_client_message::Message::GetBlobResult(result)) => {
if let Some(pending) = self.inner.get_requests.lock().await.remove(&message.id) {
let value = if let Some(error) = result.error {
Err(Error::Protocol(format!("KV GET: {}", error.message)))
} else if let Some(data) = result.blob_data {
let actual = BlobId::digest(&data);
if actual != pending.blob_id {
Err(Error::Protocol(format!(
"KV GET Blob hash mismatch: expected {}, got {}",
pending.blob_id.to_base64(),
actual.to_base64()
)))
} else {
self.inner.store.put_blob(&data, &[]).await?;
Ok(Some(data))
}
} else {
Ok(None)
};
let _ = pending.result.send(value);
} else {
tracing::warn!(
request_id = self.request_id(),
kv_id = message.id,
"unknown Cursor Blob GET response"
);
}
}
None => {}
}
Ok(())
}
}
+197
View File
@@ -0,0 +1,197 @@
//! Hydrates request context blobs supplied by Cursor.
use std::{sync::Arc, time::Duration};
use prost::Message;
use tokio::sync::{oneshot, Mutex};
use crate::{
cursor::{protocol::proto::agent::v1 as pb, transport::TransportHandle},
store::{BlobId, Store},
Error, Result,
};
type ContextSender = oneshot::Sender<Result<pb::RequestContext>>;
#[derive(Clone)]
pub(crate) struct RequestContextSynchronizer {
handle: TransportHandle,
store: Store,
pending: Arc<Mutex<Option<ContextSender>>>,
}
impl RequestContextSynchronizer {
pub(crate) fn new(handle: TransportHandle, store: Store) -> Self {
Self {
handle,
store,
pending: Arc::new(Mutex::new(None)),
}
}
pub(crate) async fn refresh_if_missing(
&self,
references: &pb::RequestContextPartReferences,
conversation_id: &str,
) -> Result<Option<pb::RequestContext>> {
if !self.has_missing_part(references).await? {
return Ok(None);
}
let context = self.load(conversation_id).await?;
self.cache_parts(&context).await?;
Ok(Some(context))
}
pub(crate) async fn get(&self, id: &BlobId) -> Result<Option<Vec<u8>>> {
self.store.get_blob(id).await
}
pub(crate) async fn load(&self, conversation_id: &str) -> Result<pb::RequestContext> {
let (sender, receiver) = oneshot::channel();
let mut pending = self.pending.lock().await;
if pending.is_some() {
return Err(Error::Protocol(
"Cursor request context is already being loaded".into(),
));
}
*pending = Some(sender);
drop(pending);
tracing::info!(
request_id = self.handle.request_id(),
conversation_id,
"requesting uncached Cursor context"
);
if let Err(error) = self.handle.emit(&pb::AgentServerMessage {
ttft_breakdown: None,
message: Some(pb::agent_server_message::Message::ExecServerMessage(
pb::ExecServerMessage {
id: 0,
message: Some(pb::exec_server_message::Message::RequestContextArgs(
pb::RequestContextArgs {
notes_session_id: Some(conversation_id.into()),
..Default::default()
},
)),
..Default::default()
},
)),
}) {
self.pending.lock().await.take();
return Err(error);
}
let cancellation = self.handle.disconnect_token();
let result = tokio::select! {
result = receiver => result.map_err(|_| Error::Protocol("request context response channel closed".into()))?,
_ = cancellation.cancelled() => Err(Error::Cancelled),
_ = tokio::time::sleep(Duration::from_secs(60)) => Err(Error::Protocol("request context timed out".into())),
};
if result.is_err() {
self.pending.lock().await.take();
}
result
}
pub(crate) async fn handle_client(&self, message: &pb::ExecClientMessage) -> bool {
if message.id != 0 {
return false;
}
let Some(pb::exec_client_message::Message::RequestContextResult(result)) =
message.message.as_ref()
else {
return false;
};
let Some(sender) = self.pending.lock().await.take() else {
tracing::warn!(
request_id = self.handle.request_id(),
"unexpected Cursor request context result"
);
return true;
};
use pb::request_context_result::Result as ContextResult;
let result = match result.result.as_ref() {
Some(ContextResult::Success(success)) => success
.request_context
.clone()
.ok_or_else(|| Error::Protocol("Cursor returned empty request context".into())),
Some(ContextResult::Error(error)) => Err(Error::Protocol(format!(
"Cursor request context failed: {}",
error.error
))),
Some(ContextResult::Rejected(rejected)) => Err(Error::Protocol(format!(
"Cursor rejected request context: {}",
rejected.reason
))),
None => Err(Error::Protocol(
"Cursor returned no request context result".into(),
)),
};
let _ = sender.send(result);
true
}
pub(crate) async fn handle_stream_close(&self, id: u32) -> bool {
id == 0 && self.pending.lock().await.is_some()
}
pub(crate) async fn handle_throw(&self, id: u32, message: String) -> bool {
let sender = if id == 0 {
self.pending.lock().await.take()
} else {
None
};
let Some(sender) = sender else { return false };
let _ = sender.send(Err(Error::Protocol(message)));
true
}
async fn has_missing_part(&self, parts: &pb::RequestContextPartReferences) -> Result<bool> {
for raw_id in [
parts.rules_blob_id.as_slice(),
parts.skills_blob_id.as_slice(),
parts.subagents_blob_id.as_slice(),
parts.mcps_blob_id.as_slice(),
] {
if raw_id.is_empty() {
continue;
}
let id = BlobId::from_bytes(raw_id)?;
if self.store.get_blob(&id).await?.is_none() {
return Ok(true);
}
}
Ok(false)
}
async fn cache_parts(&self, context: &pb::RequestContext) -> Result<()> {
self.cache_part(&pb::RequestContextRulesPart {
rules: context.rules.clone(),
non_file_rules: context.non_file_rules.clone(),
cloud_rule: context.cloud_rule.clone(),
})
.await?;
self.cache_part(&pb::RequestContextSkillsPart {
agent_skills: context.agent_skills.clone(),
skill_options: context.skill_options.clone(),
})
.await?;
self.cache_part(&pb::RequestContextSubagentsPart {
custom_subagents: context.custom_subagents.clone(),
})
.await?;
self.cache_part(&pb::RequestContextMcpsPart {
tools: context.tools.clone(),
mcp_instructions: context.mcp_instructions.clone(),
mcp_file_system_options: context.mcp_file_system_options.clone(),
mcp_meta_tool_options: context.mcp_meta_tool_options.clone(),
})
.await
}
async fn cache_part<T: Message>(&self, part: &T) -> Result<()> {
let data = part.encode_to_vec();
self.store.put_blob(&data, &[]).await?;
Ok(())
}
}
+10
View File
@@ -0,0 +1,10 @@
//! Exposes Cursor services outside the Agent loop.
pub mod account;
pub mod analytics;
pub mod blob_sync;
pub mod context_sync;
pub mod model_catalog;
pub mod observability;
pub mod tab;
pub mod usage;
+520
View File
@@ -0,0 +1,520 @@
//! Publishes the configured model catalog to Cursor.
use axum::{
body::{Body, Bytes},
extract::{Extension, State},
http::{header, HeaderValue, Request, Response, StatusCode},
};
use bytes::{BufMut, BytesMut};
use prost::Message;
use crate::{
api::cursor::proxy::{self, CursorProxy},
cursor::{protocol::proto::agent::v1 as agent, transport::TransportRegistry},
model::{format_token_count, parse_token_count, ModelConfig, ModelType},
Error, Result,
};
#[derive(Clone, PartialEq, Message)]
struct AvailableModelsAddition {
#[prost(string, repeated, tag = "1")]
model_names: Vec<String>,
#[prost(message, repeated, tag = "2")]
models: Vec<AvailableModel>,
}
#[derive(Clone, PartialEq, Message)]
struct AvailableModel {
#[prost(string, tag = "1")]
name: String,
#[prost(bool, tag = "2")]
default_on: bool,
#[prost(bool, optional, tag = "5")]
supports_agent: Option<bool>,
#[prost(int32, optional, tag = "6")]
degradation_status: Option<i32>,
#[prost(message, optional, tag = "8")]
tooltip_data: Option<TooltipData>,
#[prost(bool, optional, tag = "9")]
supports_thinking: Option<bool>,
#[prost(bool, optional, tag = "10")]
supports_images: Option<bool>,
#[prost(bool, optional, tag = "14")]
supports_max_mode: Option<bool>,
#[prost(string, optional, tag = "17")]
client_display_name: Option<String>,
#[prost(string, optional, tag = "18")]
server_model_name: Option<String>,
#[prost(bool, optional, tag = "19")]
supports_non_max_mode: Option<bool>,
#[prost(message, optional, tag = "20")]
tooltip_data_for_max_mode: Option<TooltipData>,
#[prost(bool, optional, tag = "21")]
is_recommended_for_background_composer: Option<bool>,
#[prost(bool, optional, tag = "22")]
supports_plan_mode: Option<bool>,
#[prost(string, optional, tag = "24")]
inputbox_short_model_name: Option<String>,
#[prost(bool, optional, tag = "25")]
supports_sandboxing: Option<bool>,
#[prost(bool, optional, tag = "26")]
supports_cmd_k: Option<bool>,
#[prost(message, repeated, tag = "29")]
parameter_definitions: Vec<ModelParameterDefinition>,
#[prost(message, repeated, tag = "30")]
variants: Vec<ModelVariant>,
#[prost(string, repeated, tag = "36")]
legacy_slugs: Vec<String>,
#[prost(int32, optional, tag = "38")]
named_model_section_index: Option<i32>,
#[prost(string, optional, tag = "41")]
vendor_name: Option<String>,
#[prost(message, optional, tag = "42")]
vendor: Option<AvailableModelVendor>,
#[prost(message, repeated, tag = "48")]
model_picker_badges: Vec<ModelPickerBadge>,
}
#[derive(Clone, PartialEq, Message)]
struct TooltipData {
#[prost(string, optional, tag = "7")]
markdown_content: Option<String>,
}
#[derive(Clone, PartialEq, Message)]
struct ModelParameterDefinition {
#[prost(string, tag = "1")]
id: String,
#[prost(string, tag = "2")]
name: String,
#[prost(string, optional, tag = "3")]
markdown_tooltip: Option<String>,
#[prost(message, optional, tag = "4")]
parameter_type: Option<ModelParameterType>,
#[prost(bool, optional, tag = "5")]
is_cycleable_by_hotkey: Option<bool>,
}
#[derive(Clone, PartialEq, Message)]
struct ModelParameterType {
#[prost(message, optional, tag = "1")]
boolean_parameter: Option<BooleanParameter>,
#[prost(message, optional, tag = "2")]
enum_parameter: Option<EnumParameter>,
}
#[derive(Clone, PartialEq, Message)]
struct BooleanParameter {
#[prost(message, repeated, tag = "1")]
values: Vec<BooleanParameterValue>,
}
#[derive(Clone, PartialEq, Message)]
struct BooleanParameterValue {
#[prost(string, tag = "1")]
value: String,
#[prost(string, optional, tag = "2")]
display_name: Option<String>,
#[prost(bool, optional, tag = "3")]
increases_model_cost: Option<bool>,
}
#[derive(Clone, PartialEq, Message)]
struct EnumParameter {
#[prost(message, repeated, tag = "1")]
values: Vec<EnumParameterValue>,
}
#[derive(Clone, PartialEq, Message)]
struct EnumParameterValue {
#[prost(string, tag = "1")]
value: String,
#[prost(string, optional, tag = "2")]
display_name: Option<String>,
}
#[derive(Clone, PartialEq, Message)]
struct ModelVariant {
#[prost(message, repeated, tag = "1")]
parameter_values: Vec<ModelParameterValue>,
#[prost(string, tag = "2")]
display_name: String,
#[prost(bool, tag = "3")]
is_max_mode: bool,
#[prost(bool, optional, tag = "4")]
is_default_max_config: Option<bool>,
#[prost(bool, optional, tag = "5")]
is_default_non_max_config: Option<bool>,
#[prost(message, optional, tag = "6")]
tooltip_data: Option<TooltipData>,
#[prost(string, optional, tag = "8")]
display_name_outside_picker: Option<String>,
#[prost(string, optional, tag = "9")]
variant_string_representation: Option<String>,
#[prost(string, optional, tag = "11")]
legacy_slug: Option<String>,
}
#[derive(Clone, PartialEq, Message)]
struct ModelParameterValue {
#[prost(string, tag = "1")]
id: String,
#[prost(string, tag = "2")]
value: String,
}
#[derive(Clone, PartialEq, Message)]
struct ModelPickerBadge {
#[prost(string, tag = "1")]
label: String,
#[prost(int32, tag = "2")]
variant: i32,
#[prost(bool, tag = "3")]
dismiss_on_selection: bool,
}
#[derive(Clone, PartialEq, Message)]
struct AvailableModelVendor {
#[prost(int32, tag = "1")]
id: i32,
#[prost(string, tag = "2")]
display_name: String,
}
#[derive(Clone, PartialEq, Message)]
struct UsableModelsAddition {
#[prost(message, repeated, tag = "1")]
models: Vec<agent::ModelDetails>,
}
const CONTEXTS: [(&str, &str); 4] = [
("200k", "200K"),
("356k", "356K"),
("800k", "800K"),
("1m", "1M"),
];
const EFFORTS: [(&str, &str); 5] = [
("low", "Low"),
("medium", "Medium"),
("high", "High"),
("xhigh", "Extra High"),
("max", "Max"),
];
const DEFAULT_CONTEXT: &str = "200k";
fn context_options(model: &ModelConfig) -> Vec<(String, String)> {
let mut contexts = CONTEXTS
.into_iter()
.map(|(value, display_name)| (value.to_owned(), display_name.to_owned()))
.collect::<Vec<_>>();
if let Some(tokens) = model.context_window_tokens {
let value = tokens.to_string();
let duplicate = contexts
.iter()
.any(|(existing, _)| parse_token_count(existing) == Some(tokens));
if !duplicate {
contexts.push((value, format!("{} (Custom)", format_token_count(tokens))));
}
}
contexts
}
pub async fn available_models(
State(registry): State<TransportRegistry>,
Extension(proxy): Extension<CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
let models = registry.store().models().await?;
tracing::info!(
model_count = models.len(),
"appending BYOK models to Cursor AvailableModels"
);
let available_models = models.iter().map(available_model).collect::<Vec<_>>();
let local = AvailableModelsAddition {
model_names: models
.iter()
.map(|model| model.model_hash.clone())
.collect(),
models: available_models,
}
.encode_to_vec();
match proxy::forward_buffered(&proxy, request).await {
Ok(upstream) => merge_response(upstream, local),
Err(error) => {
tracing::warn!(%error, "Cursor AvailableModels upstream unavailable; using local catalog");
Ok(local_response(local))
}
}
}
pub async fn usable_models(
State(registry): State<TransportRegistry>,
Extension(proxy): Extension<CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
let models = registry.store().models().await?;
tracing::info!(
model_count = models.len(),
"appending BYOK models to Cursor GetUsableModels"
);
let local = UsableModelsAddition {
models: models.iter().map(usable_model).collect(),
}
.encode_to_vec();
match proxy::forward_buffered(&proxy, request).await {
Ok(upstream) => merge_response(upstream, local),
Err(error) => {
tracing::warn!(%error, "Cursor GetUsableModels upstream unavailable; using local catalog");
Ok(local_response(local))
}
}
}
fn merge_response(upstream: proxy::BufferedResponse, extra: Vec<u8>) -> Result<Response<Body>> {
if !upstream.status.is_success() {
tracing::warn!(status = %upstream.status, "Cursor model catalog upstream rejected request; using local catalog");
return Ok(local_response(extra));
}
let (framed, payload) = unary_payload(&upstream.body)?;
let body = if framed {
let mut merged = BytesMut::with_capacity(5 + payload.len() + extra.len());
merged.put_u8(0);
merged.put_u32((payload.len() + extra.len()) as u32);
merged.extend_from_slice(payload);
merged.extend_from_slice(&extra);
merged.freeze()
} else {
let mut merged = BytesMut::with_capacity(payload.len() + extra.len());
merged.extend_from_slice(payload);
merged.extend_from_slice(&extra);
merged.freeze()
};
Ok(upstream.with_body(body))
}
fn local_response(body: Vec<u8>) -> Response<Body> {
let mut response = Response::new(Body::from(body));
*response.status_mut() = StatusCode::OK;
response.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/proto"),
);
response
}
fn unary_payload(body: &Bytes) -> Result<(bool, &[u8])> {
if body.len() < 5 {
return Ok((false, body));
}
let flags = body[0];
let length = u32::from_be_bytes([body[1], body[2], body[3], body[4]]) as usize;
if length != body.len() - 5 {
return Ok((false, body));
}
if flags != 0 {
return Err(Error::Protocol(format!(
"cannot merge compressed or terminal model catalog frame: flags={flags}"
)));
}
Ok((true, &body[5..]))
}
fn available_model(model: &ModelConfig) -> AvailableModel {
let contexts = context_options(model);
let variants = model_variants(model, &contexts);
let legacy_slugs = variants
.iter()
.filter_map(|variant| variant.legacy_slug.clone())
.collect();
let tooltip = model_tooltip(model);
AvailableModel {
name: model.model_hash.clone(),
default_on: true,
supports_agent: Some(true),
degradation_status: Some(0),
tooltip_data: Some(tooltip.clone()),
supports_thinking: Some(true),
supports_images: Some(true),
supports_max_mode: Some(true),
client_display_name: Some(model.display_name.clone()),
server_model_name: Some(model.model_hash.clone()),
supports_non_max_mode: Some(true),
tooltip_data_for_max_mode: Some(tooltip),
is_recommended_for_background_composer: Some(false),
supports_plan_mode: Some(true),
inputbox_short_model_name: Some(model.display_name.clone()),
supports_sandboxing: Some(true),
supports_cmd_k: Some(false),
parameter_definitions: model_parameters(&contexts),
variants,
legacy_slugs,
named_model_section_index: Some(1),
vendor_name: Some("cursor".into()),
vendor: Some(AvailableModelVendor {
id: 6,
display_name: "Cursor".into(),
}),
model_picker_badges: vec![ModelPickerBadge {
label: match model.model_type {
ModelType::OpenAi => "OpenAI".into(),
ModelType::Anthropic => "Anthropic".into(),
},
variant: 1,
dismiss_on_selection: false,
}],
}
}
fn model_parameters(contexts: &[(String, String)]) -> Vec<ModelParameterDefinition> {
vec![
ModelParameterDefinition {
id: "context".into(),
name: "Context".into(),
markdown_tooltip: Some("Context size used to trigger conversation compaction.".into()),
parameter_type: Some(ModelParameterType {
boolean_parameter: None,
enum_parameter: Some(EnumParameter {
values: contexts
.iter()
.map(|(value, display_name)| EnumParameterValue {
value: value.clone(),
display_name: Some(display_name.clone()),
})
.collect(),
}),
}),
is_cycleable_by_hotkey: Some(false),
},
ModelParameterDefinition {
id: "reasoning".into(),
name: "Effort".into(),
markdown_tooltip: Some("Effort the model uses to generate its response.".into()),
parameter_type: Some(ModelParameterType {
boolean_parameter: None,
enum_parameter: Some(EnumParameter {
values: EFFORTS
.into_iter()
.map(|(value, display_name)| EnumParameterValue {
value: value.into(),
display_name: Some(display_name.into()),
})
.collect(),
}),
}),
is_cycleable_by_hotkey: Some(true),
},
ModelParameterDefinition {
id: "fast".into(),
name: "Fast".into(),
markdown_tooltip: Some("Significantly faster but consumes more usage".into()),
parameter_type: Some(ModelParameterType {
boolean_parameter: Some(BooleanParameter {
values: vec![
BooleanParameterValue {
value: "false".into(),
display_name: None,
increases_model_cost: None,
},
BooleanParameterValue {
value: "true".into(),
display_name: Some("Fast".into()),
increases_model_cost: Some(true),
},
],
}),
enum_parameter: None,
}),
is_cycleable_by_hotkey: Some(false),
},
]
}
fn model_variants(model: &ModelConfig, contexts: &[(String, String)]) -> Vec<ModelVariant> {
let mut variants = Vec::with_capacity(contexts.len() * EFFORTS.len() * 2);
for (context, context_name) in contexts {
for (effort, effort_name) in EFFORTS {
for fast in [false, true] {
variants.push(model_variant(
model,
context,
context_name,
effort,
effort_name,
fast,
));
}
}
}
variants
}
fn model_variant(
model: &ModelConfig,
context: &str,
context_name: &str,
effort: &str,
effort_name: &str,
fast: bool,
) -> ModelVariant {
let mut suffix = Vec::with_capacity(3);
if context != DEFAULT_CONTEXT {
suffix.push(context_name);
}
suffix.push(effort_name);
if fast {
suffix.push("Fast");
}
let suffix = suffix.join(" ");
let display_name = format!(
"{} <span style=\"color: var(--cursor-text-tertiary);\">{suffix}</span>",
model.display_name
);
let is_default = context == DEFAULT_CONTEXT && effort == "high" && !fast;
ModelVariant {
parameter_values: vec![
ModelParameterValue {
id: "context".into(),
value: context.into(),
},
ModelParameterValue {
id: "reasoning".into(),
value: effort.into(),
},
ModelParameterValue {
id: "fast".into(),
value: fast.to_string(),
},
],
display_name: display_name.clone(),
is_max_mode: false,
is_default_max_config: is_default.then_some(true),
is_default_non_max_config: is_default.then_some(true),
tooltip_data: Some(model_tooltip(model)),
display_name_outside_picker: Some(display_name),
variant_string_representation: Some(format!(
"{}[context={context},reasoning={effort},fast={fast}]",
model.model_hash
)),
legacy_slug: Some(format!(
"{}-{context}-{effort}{}",
model.model_hash,
if fast { "-fast" } else { "" }
)),
}
}
fn model_tooltip(model: &ModelConfig) -> TooltipData {
TooltipData {
markdown_content: Some(model.tooltip_data.clone()),
}
}
fn usable_model(model: &ModelConfig) -> agent::ModelDetails {
agent::ModelDetails {
model_id: model.model_hash.clone(),
display_model_id: model.model_hash.clone(),
display_name: model.display_name.clone(),
display_name_short: model.display_name.clone(),
thinking_details: Some(agent::ThinkingDetails::default()),
..Default::default()
}
}
+225
View File
@@ -0,0 +1,225 @@
//! Records Cursor request traces and artifacts.
use std::{
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::{Duration, Instant},
};
use tokio::sync::Mutex;
use crate::store::{BlobId, BufferedCursorTraceChunk, Store};
#[derive(Clone)]
pub struct CursorTraceRecorder {
store: Store,
request_id: String,
chunks: Arc<Mutex<TraceChunkBuffer>>,
finished: Arc<AtomicBool>,
}
#[derive(Default)]
struct TraceChunkBuffer {
chunks: Vec<BufferedCursorTraceChunk>,
bytes: usize,
first_chunk_at: Option<Instant>,
generation: u64,
}
const MAX_BUFFERED_CHUNKS: usize = 32;
const MAX_BUFFERED_BYTES: usize = 256 * 1024;
const MAX_BUFFER_AGE: Duration = Duration::from_millis(50);
impl CursorTraceRecorder {
pub async fn begin(
store: Store,
request_id: &str,
conversation_id: Option<&str>,
route: &str,
model_id: Option<&str>,
) -> Option<Self> {
match store
.start_cursor_trace_if_detailed(request_id, conversation_id, route, model_id)
.await
{
Ok(true) => Some(Self {
store,
request_id: request_id.into(),
chunks: Arc::new(Mutex::new(TraceChunkBuffer::default())),
finished: Arc::new(AtomicBool::new(false)),
}),
Ok(false) => None,
Err(error) => {
tracing::warn!(request_id, %error, "failed to start Cursor trace");
None
}
}
}
pub async fn resume(store: Store, request_id: &str) -> Option<Self> {
match store.cursor_trace_exists(request_id).await {
Ok(true) => Some(Self {
store,
request_id: request_id.into(),
chunks: Arc::new(Mutex::new(TraceChunkBuffer::default())),
finished: Arc::new(AtomicBool::new(false)),
}),
Ok(false) => None,
Err(error) => {
tracing::warn!(request_id, %error, "failed to resume Cursor trace");
None
}
}
}
pub fn request_id(&self) -> &str {
&self.request_id
}
pub async fn request(&self, artifact_type: &str, data: &[u8], metadata: serde_json::Value) {
if let Err(error) = self
.store
.append_cursor_trace_artifact(
&self.request_id,
artifact_type,
"cursor_client",
data,
&metadata,
)
.await
{
tracing::warn!(request_id = self.request_id, %error, "failed to record Cursor request artifact");
return;
}
if let Err(error) = self
.store
.add_cursor_trace_request_bytes(&self.request_id, data.len())
.await
{
tracing::warn!(request_id = self.request_id, %error, "failed to update Cursor request trace size");
}
}
pub async fn artifact(
&self,
artifact_type: &str,
source: &str,
data: &[u8],
metadata: serde_json::Value,
) {
if let Err(error) = self
.store
.append_cursor_trace_artifact(&self.request_id, artifact_type, source, data, &metadata)
.await
{
tracing::warn!(request_id = self.request_id, %error, artifact_type, "failed to record Cursor trace artifact");
}
}
pub async fn linked_blob(
&self,
artifact_type: &str,
source: &str,
blob_id: &BlobId,
metadata: serde_json::Value,
) {
if let Err(error) = self
.store
.link_cursor_trace_artifact(&self.request_id, artifact_type, source, blob_id, &metadata)
.await
{
tracing::warn!(request_id = self.request_id, %error, artifact_type, "failed to link Cursor trace Blob");
}
}
pub async fn response_started(&self, status: u16) {
if let Err(error) = self
.store
.start_cursor_trace_response(&self.request_id, status)
.await
{
tracing::warn!(request_id = self.request_id, %error, "failed to start Cursor response trace");
}
}
pub async fn response_chunk(&self, source: &str, data: &[u8]) {
let mut buffer = self.chunks.lock().await;
if self.finished.load(Ordering::Acquire) {
return;
}
let schedule_flush = if buffer.chunks.is_empty() {
buffer.generation = buffer.generation.wrapping_add(1);
buffer.first_chunk_at = Some(Instant::now());
Some(buffer.generation)
} else {
None
};
buffer.bytes += data.len();
buffer
.chunks
.push(BufferedCursorTraceChunk::new(source, data));
let expired = buffer
.first_chunk_at
.is_some_and(|started| started.elapsed() >= MAX_BUFFER_AGE);
if buffer.chunks.len() >= MAX_BUFFERED_CHUNKS
|| buffer.bytes >= MAX_BUFFERED_BYTES
|| expired
{
if let Err(error) = self.flush_locked(&mut buffer).await {
tracing::warn!(request_id = self.request_id, %error, "failed to record Cursor response chunk");
}
}
drop(buffer);
if let Some(generation) = schedule_flush {
let recorder = self.clone();
tokio::spawn(async move {
tokio::time::sleep(MAX_BUFFER_AGE).await;
let mut buffer = recorder.chunks.lock().await;
if buffer.generation == generation {
if let Err(error) = recorder.flush_locked(&mut buffer).await {
tracing::warn!(request_id = recorder.request_id, %error, "failed to flush Cursor response chunks");
}
}
});
}
}
pub async fn finish(&self, error: Option<&str>) {
if self.finished.swap(true, Ordering::AcqRel) {
return;
}
let mut buffer = self.chunks.lock().await;
if let Err(store_error) = self.flush_locked(&mut buffer).await {
tracing::warn!(request_id = self.request_id, %store_error, "failed to flush Cursor response chunks");
}
drop(buffer);
if let Err(store_error) = self
.store
.finish_cursor_trace(&self.request_id, error)
.await
{
tracing::warn!(request_id = self.request_id, %store_error, "failed to finish Cursor trace");
}
}
async fn flush_locked(&self, buffer: &mut TraceChunkBuffer) -> crate::Result<()> {
if buffer.chunks.is_empty() {
return Ok(());
}
let chunks = std::mem::take(&mut buffer.chunks);
buffer.bytes = 0;
buffer.first_chunk_at = None;
if let Err(error) = self
.store
.add_cursor_trace_response_chunks(&self.request_id, &chunks)
.await
{
buffer.bytes = chunks.iter().map(|chunk| chunk.data.len()).sum();
buffer.first_chunk_at = Some(Instant::now());
buffer.chunks = chunks;
return Err(error);
}
Ok(())
}
}
+52
View File
@@ -0,0 +1,52 @@
//! Implements Cursor tab metadata services.
use axum::{
body::Body,
extract::{Extension, State},
http::{Request, Response},
routing::post,
Router,
};
use crate::{api::cursor::proxy, cursor::transport::TransportRegistry, Result};
pub const TAB_PATHS: [&str; 17] = [
"/aiserver.v1.AiService/StreamCpp",
"/aiserver.v1.AiService/StreamNextCursorPrediction",
"/aiserver.v1.AiService/GetCppEditClassification",
"/aiserver.v1.AiService/RefreshTabContext",
"/aiserver.v1.AiService/CppConfig",
"/aiserver.v1.AiService/CppEditHistoryStatus",
"/aiserver.v1.AiService/CppAppend",
"/aiserver.v1.AiService/CppEditHistoryAppend",
"/aiserver.v1.AiService/ReportAiCodeChangeMetrics",
"/aiserver.v1.AiService/WriteGitCommitMessage",
"/aiserver.v1.AiService/WriteGitBranchName",
"/aiserver.v1.CppService/AvailableModels",
"/aiserver.v1.CppService/RecordCppFate",
"/aiserver.v1.FileSyncService/FSSyncFile",
"/aiserver.v1.FileSyncService/FSIsEnabledForUser",
"/aiserver.v1.FileSyncService/FSConfig",
"/aiserver.v1.FileSyncService/FSUploadFile",
];
pub fn is_tab_path(path: &str) -> bool {
TAB_PATHS.contains(&path)
}
pub fn router() -> Router<TransportRegistry> {
TAB_PATHS.into_iter().fold(Router::new(), |router, path| {
router.route(path, post(forward))
})
}
async fn forward(
State(registry): State<TransportRegistry>,
Extension(upstream): Extension<proxy::CursorProxy>,
request: Request<Body>,
) -> Result<Response<Body>> {
let settings = registry.store().tab_settings().await?;
match settings.service_url() {
Some(service_url) => proxy::forward_to_service(&upstream, request, service_url).await,
None => proxy::forward(Extension(upstream), request).await,
}
}
+219
View File
@@ -0,0 +1,219 @@
//! Builds Cursor usage and context breakdown data.
use std::collections::HashSet;
use crate::{
cursor::protocol::proto::agent::v1 as pb,
model::{CanonicalMessage, ContentPart, MessageContent, Origin, ToolDefinition},
Result,
};
const CATEGORIES: [(&str, &str); 8] = [
("system_prompt", "System prompt"),
("tools", "Tool definitions"),
("rules", "Rules"),
("skills", "Skills"),
("mcp", "MCP & dynamic tools"),
("subagents", "Subagent definitions"),
("summarized_conversation", "Summarized conversation"),
("conversation", "Conversation"),
];
const EASTER_EGG_CATEGORY: (&str, &str) = ("leookun", "@leookun stole 1 token 😂");
const SYSTEM: usize = 0;
const TOOLS: usize = 1;
const RULES: usize = 2;
const SKILLS: usize = 3;
const MCP: usize = 4;
const SUBAGENTS: usize = 5;
const SUMMARY: usize = 6;
const CONVERSATION: usize = 7;
#[derive(Clone, Copy, Default)]
struct Measure {
characters: u64,
token_units: u64,
}
impl Measure {
fn add(&mut self, text: &str) {
self.characters += text.encode_utf16().count() as u64;
let mut units = 0_u64;
for character in text.chars() {
let width = character.len_utf16() as u64;
units += if character.is_ascii() {
width * 273
} else {
width * 550
};
}
self.token_units += units;
}
fn estimated_tokens(self) -> u64 {
self.token_units.div_ceil(1_000)
}
}
pub(crate) fn breakdown(
used_tokens: u32,
max_tokens: u32,
baseline: Option<&pb::PromptTokenBreakdownSnapshot>,
instructions: &str,
tools: &[ToolDefinition],
dynamic_tools: &HashSet<String>,
messages: &[CanonicalMessage],
) -> Result<pb::PromptTokenBreakdownSnapshot> {
let mut measures = [Measure::default(); 8];
measures[SYSTEM].add(instructions);
for tool in tools {
let encoded = serde_json::to_string(tool)?;
if dynamic_tools.contains(&tool.name) {
measures[MCP].add(&encoded);
} else {
measures[TOOLS].add(&encoded);
}
}
for message in messages {
measure_message(message, &mut measures)?;
}
let mut estimates = [0_u64; 8];
for index in 0..CONVERSATION {
estimates[index] = measures[index].estimated_tokens();
}
if measures[SUMMARY].characters != 0 {
estimates[SUMMARY] = measures[SUMMARY].estimated_tokens();
} else if let Some(summary) = baseline.and_then(|snapshot| {
snapshot
.categories
.iter()
.find(|category| category.id == CATEGORIES[SUMMARY].0)
}) {
measures[SUMMARY].characters = summary.character_count.unwrap_or(0) as u64;
estimates[SUMMARY] = summary.estimated_tokens as u64;
}
let easter_egg_tokens = 1_u64;
let categorized_tokens = used_tokens as u64;
fit_special_estimates(&mut estimates, categorized_tokens);
estimates[CONVERSATION] =
categorized_tokens.saturating_sub(estimates[..CONVERSATION].iter().sum::<u64>());
let mut categories = CATEGORIES
.iter()
.enumerate()
.map(|(index, (id, label))| pb::PromptTokenBreakdownCategory {
id: (*id).into(),
label: (*label).into(),
estimated_tokens: estimates[index].min(u32::MAX as u64) as u32,
character_count: (measures[index].characters != 0)
.then_some(measures[index].characters.min(u32::MAX as u64) as u32),
})
.collect::<Vec<_>>();
categories.push(pb::PromptTokenBreakdownCategory {
id: EASTER_EGG_CATEGORY.0.into(),
label: EASTER_EGG_CATEGORY.1.into(),
estimated_tokens: easter_egg_tokens as u32,
character_count: None,
});
Ok(pb::PromptTokenBreakdownSnapshot {
total_used_tokens: used_tokens,
max_tokens,
categories,
})
}
fn measure_message(message: &CanonicalMessage, measures: &mut [Measure; 8]) -> Result<()> {
match &message.content {
MessageContent::Parts { parts } => {
for part in parts {
if let ContentPart::Text { text } = part {
if message.origin == Origin::Runtime {
measure_runtime(text, measures);
} else {
measures[CONVERSATION].add(text);
}
}
}
}
MessageContent::Assistant {
text,
thinking,
tool_calls,
..
} => {
measures[CONVERSATION].add(text);
measures[CONVERSATION].add(thinking);
measures[CONVERSATION].add(&serde_json::to_string(tool_calls)?);
}
MessageContent::ToolResult(result) => {
measures[CONVERSATION].add(&serde_json::to_string(result)?);
}
}
Ok(())
}
fn measure_runtime(text: &str, measures: &mut [Measure; 8]) {
let mut ranges = Vec::new();
collect_ranges(text, "rules", RULES, &mut ranges);
collect_ranges(text, "rule", RULES, &mut ranges);
collect_ranges(text, "agent_skills", SKILLS, &mut ranges);
collect_ranges(text, "skill", SKILLS, &mut ranges);
collect_ranges(text, "subagents", SUBAGENTS, &mut ranges);
collect_ranges(text, "mcp_meta_tools", MCP, &mut ranges);
collect_ranges(text, "conversation_summary", SUMMARY, &mut ranges);
ranges.sort_by_key(|range| range.0);
let mut cursor = 0;
for (start, end, category) in ranges {
if start < cursor {
continue;
}
measures[CONVERSATION].add(&text[cursor..start]);
measures[category].add(&text[start..end]);
cursor = end;
}
measures[CONVERSATION].add(&text[cursor..]);
}
fn collect_ranges(text: &str, tag: &str, category: usize, output: &mut Vec<(usize, usize, usize)>) {
let opening = format!("<{tag}");
let closing = format!("</{tag}>");
let mut cursor = 0;
while let Some(relative_start) = text[cursor..].find(&opening) {
let start = cursor + relative_start;
let Some(open_end) = text[start..].find('>').map(|offset| start + offset + 1) else {
break;
};
let Some(relative_end) = text[open_end..].find(&closing) else {
break;
};
let end = open_end + relative_end + closing.len();
output.push((start, end, category));
cursor = end;
}
}
fn fit_special_estimates(estimates: &mut [u64; 8], total: u64) {
let special_total = estimates[..CONVERSATION].iter().sum::<u64>();
if special_total <= total || special_total == 0 {
return;
}
let original = *estimates;
let mut assigned = 0;
for index in 0..CONVERSATION {
estimates[index] = original[index].saturating_mul(total) / special_total;
assigned += estimates[index];
}
let mut remainder = total - assigned;
let mut order = (0..CONVERSATION).collect::<Vec<_>>();
order.sort_by_key(|index| {
std::cmp::Reverse(original[*index].saturating_mul(total) % special_total)
});
for index in order {
if remainder == 0 {
break;
}
estimates[index] += 1;
remainder -= 1;
}
}