diff --git a/docs/src/content/docs/providers/cursor-agent.md b/docs/src/content/docs/providers/cursor-agent.md index 424bec7b..67aee22e 100644 --- a/docs/src/content/docs/providers/cursor-agent.md +++ b/docs/src/content/docs/providers/cursor-agent.md @@ -58,7 +58,9 @@ When the OpenAI routes are enabled, Cursor models work with both `POST /v1/chat/ ## Session continuation -The proxy maps `x-claude-code-session-id` to a Cursor conversation ID in memory. Request metadata can resume a known Cursor chat through `cursor_chat_id`, `cursorChatId`, `cursor_resume`, or `cursorResume`. A proxy restart clears the in-memory mapping. +For tool-bridged requests, the proxy keeps the Cursor conversation of each Claude Code session, model, system prompt and tool set in memory: the conversation ID, the last checkpoint and the agent-store blobs. When the next request extends the transcript that conversation saw, the run sends the checkpoint back with only the new messages, so Cursor's prompt cache reuses the earlier turns instead of writing the whole context again. A changed transcript (an edit, a compaction) or tool list starts a new conversation with the full prompt. Conversations idle for 30 minutes are dropped, and a proxy restart clears them all. Set `CCP_CURSOR_CONTINUATION=off` to send the full transcript on every request. + +Each run logs `cursor_turn_usage` with Cursor's own input, output, cache-read and cache-write token counts and whether it continued a conversation. Metadata can also choose a mode per request: diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md index 3a109081..91f3985d 100644 --- a/docs/src/content/docs/reference/configuration.md +++ b/docs/src/content/docs/reference/configuration.md @@ -160,6 +160,7 @@ Proxy URLs may use `http`, `https`, `socks4`, `socks4a`, `socks5`, or `socks5h`. | `CCP_CURSOR_CLIENT_VERSION` | `cursor.clientVersion` | `0.48.5` | Changes Cursor client version headers. | | `CCP_CURSOR_AGENT_BUNDLE` | `cursor.agentBundle` | Auto-detected | Points to Cursor Agent's bundled `index.js` protobuf schemas. | | `CCP_CURSOR_AUTH_TOKEN` | none | unset | Uses a bearer token instead of proxy-owned Cursor auth storage. | +| `CCP_CURSOR_CONTINUATION` | none | on | `off` sends the full transcript on every request instead of continuing the session's Cursor conversation. | ## Shared compatibility fallbacks diff --git a/src/config.rs b/src/config.rs index a457a202..c14e1b1a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -292,6 +292,9 @@ pub fn config_override_summary_lines(cfg: &LoadedConfig) -> Vec { if env.contains_key("CCP_CURSOR_CLIENT_VERSION") { out.push("cursor.clientVersion (env)".to_string()); } + if env.contains_key("CCP_CURSOR_CONTINUATION") { + out.push("cursor.continuation (env)".to_string()); + } if env.contains_key("CCP_KIMI_USER_AGENT") { out.push("kimi.userAgent (env)".to_string()); } @@ -1071,6 +1074,19 @@ fn detect_cursor_agent_version() -> Option { }) } +/// Whether a Cursor run continues the stored conversation of its Claude Code +/// session instead of resending the whole transcript. On unless +/// `CCP_CURSOR_CONTINUATION` turns it off. +pub fn cursor_continuation() -> bool { + match std::env::var("CCP_CURSOR_CONTINUATION") { + Ok(raw) => !matches!( + raw.trim().to_ascii_lowercase().as_str(), + "0" | "false" | "no" | "off" + ), + Err(_) => true, + } +} + pub fn cursor_agent_bundle() -> Option { let env: HashMap<_, _> = std::env::vars().collect(); if let Some(raw) = env.get("CCP_CURSOR_AGENT_BUNDLE") { diff --git a/src/providers/cursor/client.rs b/src/providers/cursor/client.rs index d506d599..b4d60af1 100644 --- a/src/providers/cursor/client.rs +++ b/src/providers/cursor/client.rs @@ -9,6 +9,7 @@ use crate::providers::cursor::connect::{ ConnectFrame, ConnectFrameDecoder, FLAG_END, FLAG_GZIP, encode_connect_frame, parse_connect_error, }; +use crate::providers::cursor::continuation::{RunState, SharedRunState}; use crate::providers::cursor::model::CursorModelResolution; use crate::providers::cursor::proto; use crate::providers::cursor::request::CursorSelectedImage; @@ -52,9 +53,15 @@ pub struct LiveRun { tx: mpsc::Sender>, pub events: mpsc::Receiver, writer: tokio::task::JoinHandle<()>, + state: SharedRunState, } impl LiveRun { + /// The conversation state as of the latest frame the reader handled. + pub fn snapshot(&self) -> RunState { + self.state.lock().unwrap().clone() + } + /// Write one client message on the open request body. pub async fn send(&self, message: &proto::AgentClientMessage) -> Result<(), CursorError> { self.tx @@ -82,6 +89,7 @@ impl LiveRun { tx, events, writer: tokio::spawn(async {}), + state: RunState::new_shared(), } } @@ -92,6 +100,7 @@ impl LiveRun { tx, events, writer: tokio::spawn(async {}), + state: RunState::new_shared(), } } } @@ -153,14 +162,19 @@ impl CursorHttpClient { /// The returned handle owns the write side of the request body, so the /// caller can answer exec requests on the same stream, and a reader task /// that decodes response frames incrementally into `LiveRun::events`. + /// + /// `state` carries the conversation: a fresh one starts a new conversation, + /// a stored one continues it. The reader keeps it current as the server + /// writes blobs and checkpoints. pub async fn start_run( &self, token: &str, prompt: &str, model: &str, images: &[CursorSelectedImage], + state: SharedRunState, ) -> Result { - let transport = self.open_run(token, prompt, model, images).await?; + let transport = self.open_run(token, prompt, model, images, &state).await?; let status = transport.response.status().as_u16(); let headers = transport.response.headers().clone(); @@ -181,11 +195,10 @@ impl CursorHttpClient { let (event_tx, event_rx) = mpsc::channel::(64); let kv_tx = transport.tx.clone(); + let reader_state = std::sync::Arc::clone(&state); tokio::spawn(async move { let mut stream = transport.response.bytes_stream(); let mut decoder = ConnectFrameDecoder::new(); - let mut blobs: std::collections::HashMap, Vec> = - std::collections::HashMap::new(); loop { let next = tokio::time::timeout(RUN_IDLE_TIMEOUT, stream.next()).await; let chunk = match next { @@ -231,14 +244,20 @@ impl CursorHttpClient { let _ = event_tx.send(event).await; return; } - match decode_frame_payload(&frame) { - Ok(message) => { + match decode_frame_with_payload(&frame) { + Ok((message, payload)) => { + if message.conversation_checkpoint_update.is_some() + && let Some(checkpoint) = length_delimited_field(&payload, 3) + { + reader_state.lock().unwrap().checkpoint = Some(checkpoint.to_vec()); + } // The agent store is answered here rather than by // the pump: a blob the server is waiting on must // land even while the turn is paused on a tool. - if let Some(kv) = message.kv_server_message.as_ref() - && let Some(reply) = kv_reply(kv, &mut blobs) - { + let reply = message.kv_server_message.as_ref().and_then(|kv| { + kv_reply(kv, &mut reader_state.lock().unwrap().blobs) + }); + if let Some(reply) = reply { if kv_tx .send(Ok(encode_connect_frame(reply.encode_to_vec(), 0))) .await @@ -268,6 +287,7 @@ impl CursorHttpClient { tx: transport.tx, events: event_rx, writer: transport.writer, + state, }) } @@ -278,12 +298,23 @@ impl CursorHttpClient { prompt: &str, model: &str, images: &[CursorSelectedImage], + state: &SharedRunState, ) -> Result { let resolved = super::model::resolve_cursor_model(model) .map_err(|e| CursorError::internal(format!("model resolution: {e}")))?; let request_id = uuid::Uuid::new_v4().to_string(); - let frames = build_run_frames(prompt, &resolved, images, &request_id); + let frames = { + let state = state.lock().unwrap(); + build_run_frames( + prompt, + &resolved, + images, + &request_id, + &state.conversation_id, + state.checkpoint.as_deref(), + ) + }; let (tx, rx) = mpsc::channel::>(8); let writer_tx = tx.clone(); let writer = tokio::spawn(async move { @@ -357,7 +388,9 @@ impl CursorHttpClient { model: &str, images: &[CursorSelectedImage], ) -> Result { - let transport = self.open_run(token, prompt, model, images).await?; + let transport = self + .open_run(token, prompt, model, images, &RunState::new_shared()) + .await?; let sender = transport.writer; let status = transport.response.status().as_u16(); let headers = transport.response.headers().clone(); @@ -495,13 +528,19 @@ fn selected_context(images: &[CursorSelectedImage]) -> Option> { Some(context) } +/// The opening frames of a run. +/// +/// `checkpoint` is the `ConversationStateStructure` the server sent last in +/// this conversation; with it the server rebuilds the earlier turns from the +/// agent store, and `prompt` only has to carry what is new. fn build_run_frames( prompt: &str, resolved: &CursorModelResolution, images: &[CursorSelectedImage], request_id: &str, + conversation_id: &str, + checkpoint: Option<&[u8]>, ) -> Vec { - let conversation_id = uuid::Uuid::new_v4().to_string(); let mut user_message = field_string(1, prompt); user_message.extend(field_string(2, request_id)); if let Some(context) = selected_context(images) { @@ -512,15 +551,15 @@ fn build_run_frames( user_message.extend(field_varint(4, mode_value(resolved))); let action = field_bytes(1, &field_bytes(1, &user_message)); - let mut request = field_bytes(1, &[]); + let mut request = field_bytes(1, checkpoint.unwrap_or_default()); request.extend(field_bytes(2, &action)); request.extend(field_bytes(4, &[])); - request.extend(field_string(5, &conversation_id)); + request.extend(field_string(5, conversation_id)); request.extend(field_bytes(9, &model_message(resolved))); request.extend(field_varint(12, 0)); request.extend(field_bytes(14, &field_string(1, "default"))); request.extend(field_bytes(14, &model_message(resolved))); - request.extend(field_string(16, &conversation_id)); + request.extend(field_string(16, conversation_id)); let first = encode_connect_frame(field_bytes(1, &request), 0); let environment = request_context_env().encode_to_vec(); @@ -666,6 +705,14 @@ pub fn decode_upstream_frames(body: &[u8]) -> Result, CursorEr pub fn decode_frame_payload( frame: &ConnectFrame, ) -> Result { + decode_frame_with_payload(frame).map(|(message, _)| message) +} + +/// Decode a frame and keep its decompressed payload: prost drops the fields +/// this crate does not model, and a checkpoint goes back byte for byte. +fn decode_frame_with_payload( + frame: &ConnectFrame, +) -> Result<(proto::AgentServerMessage, Vec), CursorError> { let payload = if frame.flags & FLAG_GZIP != 0 { super::connect::decode_gzip_frame(&frame.payload) .map_err(|e| CursorError::internal(format!("gzip decompress: {e}")))? @@ -673,8 +720,48 @@ pub fn decode_frame_payload( frame.payload.to_vec() }; - proto::AgentServerMessage::decode(&payload[..]) - .map_err(|e| CursorError::internal(format!("prost decode: {e}"))) + let message = proto::AgentServerMessage::decode(&payload[..]) + .map_err(|e| CursorError::internal(format!("prost decode: {e}")))?; + Ok((message, payload)) +} + +/// The raw bytes of the last top-level length-delimited field `tag`. +fn length_delimited_field(buf: &[u8], tag: u64) -> Option<&[u8]> { + fn varint(buf: &[u8], pos: &mut usize) -> Option { + let mut value = 0u64; + for shift in (0..64).step_by(7) { + let byte = *buf.get(*pos)?; + *pos += 1; + value |= u64::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + return Some(value); + } + } + None + } + + let mut pos = 0; + let mut found = None; + while pos < buf.len() { + let key = varint(buf, &mut pos)?; + match key & 7 { + 0 => { + varint(buf, &mut pos)?; + } + 1 => pos += 8, + 2 => { + let len = usize::try_from(varint(buf, &mut pos)?).ok()?; + let end = pos.checked_add(len).filter(|end| *end <= buf.len())?; + if key >> 3 == tag { + found = Some(&buf[pos..end]); + } + pos = end; + } + 5 => pos += 4, + _ => return None, + } + } + (pos == buf.len()).then_some(found).flatten() } // --------------------------------------------------------------------------- @@ -727,6 +814,60 @@ impl std::fmt::Display for CursorError { impl std::error::Error for CursorError {} +#[cfg(test)] +mod continuation_frame_tests { + use super::*; + + #[test] + fn checkpoint_field_is_returned_byte_for_byte() { + // A checkpoint with a field prost does not model (tag 8, the turns). + let mut checkpoint = field_bytes(8, b"turn-blob-id"); + checkpoint.extend(field_bytes(5, &field_varint(1, 1200))); + let mut payload = field_varint(9, 7); + payload.extend(field_bytes(3, &checkpoint)); + + assert_eq!( + length_delimited_field(&payload, 3), + Some(checkpoint.as_slice()) + ); + } + + #[test] + fn truncated_payload_yields_no_field() { + let payload = field_bytes(3, b"checkpoint"); + + assert_eq!( + length_delimited_field(&payload[..payload.len() - 1], 3), + None + ); + } + + #[test] + fn run_request_carries_the_stored_checkpoint_and_conversation_id() { + let resolved = + crate::providers::cursor::model::resolve_cursor_model("cursor:gpt-5.5").unwrap(); + + let checkpoint = field_bytes(8, b"turn-blob-id"); + + let frames = build_run_frames( + "new turn", + &resolved, + &[], + "req-1", + "conv-1", + Some(&checkpoint), + ); + + let request = length_delimited_field(&frames[0][5..], 1).unwrap(); + assert_eq!( + length_delimited_field(request, 1), + Some(checkpoint.as_slice()) + ); + assert_eq!(length_delimited_field(request, 5), Some(&b"conv-1"[..])); + assert_eq!(length_delimited_field(request, 16), Some(&b"conv-1"[..])); + } +} + #[cfg(test)] mod model_message_tests { use super::*; diff --git a/src/providers/cursor/continuation.rs b/src/providers/cursor/continuation.rs new file mode 100644 index 00000000..a724ef14 --- /dev/null +++ b/src/providers/cursor/continuation.rs @@ -0,0 +1,442 @@ +//! Cursor conversation continuation across Claude Code requests. +//! +//! A Cursor run ends with its turn, but the server's conversation survives in +//! two pieces the client holds: the last `conversation_checkpoint_update` (a +//! `ConversationStateStructure` whose turns are blob ids) and the blobs the +//! server wrote through the agent store. Sending both back under the same +//! conversation id lets the next request carry only its new messages, so the +//! upstream prompt keeps the earlier turns as a cacheable prefix. A fresh run +//! instead flattens the whole transcript into one new user message, and the +//! prompt cache never matches past Cursor's own system prompt: every turn writes +//! the full context to the cache again. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use once_cell::sync::Lazy; +use sha2::{Digest, Sha256}; +use tokio::sync::OwnedMutexGuard; + +use crate::anthropic::schema::{Message, MessagesRequest}; +use crate::providers::cursor::request::{render_message_content, render_system}; + +/// A conversation nobody came back to for this long is dropped. +const MAX_IDLE: Duration = Duration::from_secs(30 * 60); + +/// Upper bound on kept conversations; the least recently used goes first. +const MAX_ENTRIES: usize = 32; + +/// How long a request waits for the previous run to record its final state. +const SETTLE_WAIT: Duration = Duration::from_secs(30); + +/// The conversation state of one Cursor run, shared with its reader task. +#[derive(Debug, Clone)] +pub struct RunState { + /// Sent as the run's conversation id; reused by every continued run. + pub conversation_id: String, + /// The raw `ConversationStateStructure` of the latest checkpoint. + pub checkpoint: Option>, + /// The agent store: blob id to blob, as the server wrote them. + pub blobs: HashMap, Vec>, +} + +/// A [`RunState`] the reader task updates while the caller holds it. +pub type SharedRunState = Arc>; + +impl RunState { + /// The state of a run that starts a new conversation. + pub fn new_shared() -> SharedRunState { + Arc::new(Mutex::new(Self { + conversation_id: uuid::Uuid::new_v4().to_string(), + checkpoint: None, + blobs: HashMap::new(), + })) + } +} + +/// The part of Claude Code's transcript a run has seen. +/// +/// `prefix_len` counts the messages of the request that opened or last resumed +/// the run. The run's reply becomes message `prefix_len` in Claude Code's next +/// request, and everything after that reply is new to the server. +#[derive(Debug, Clone)] +pub struct Segment { + key: String, + prefix_len: usize, + prefix_hash: String, +} + +impl Segment { + /// The segment a run serving `body` covers. + pub fn for_request(session_id: &str, body: &MessagesRequest) -> Self { + Self { + key: conversation_key(session_id, body), + prefix_len: body.messages.len(), + prefix_hash: prefix_hash(&body.messages), + } + } +} + +/// What the next run starts from. +pub enum Resume { + /// Continue the stored conversation. `delta` is the request cut down to the + /// messages the server has not seen, with no system prompt or tools. + Continue { + state: SharedRunState, + delta: MessagesRequest, + }, + /// Start a new conversation with the whole transcript. + Fresh, +} + +struct Stored { + state: RunState, + segment: Segment, +} + +type Slot = Arc>>; + +struct Entry { + slot: Slot, + touched: Instant, +} + +static STORE: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); + +/// A conversation slot whose run has not settled yet. +/// +/// The next request for the same conversation waits on it. Dropping it without +/// [`Pending::complete`] marks the run as not resumable, and that request starts +/// a new conversation. +pub struct Pending { + guard: OwnedMutexGuard>, + segment: Segment, +} + +impl Pending { + /// Record the run's final state for the next request. + pub fn complete(mut self, state: RunState) { + *self.guard = Some(Stored { + state, + segment: self.segment, + }); + } +} + +/// Claim the slot of the conversation a run covers, replacing any older one. +pub fn reserve(segment: Segment) -> Pending { + let slot: Slot = Arc::new(tokio::sync::Mutex::new(None)); + let guard = Arc::clone(&slot) + .try_lock_owned() + .expect("a new slot is unlocked"); + let mut store = STORE.lock().unwrap(); + evict(&mut store); + store.insert( + segment.key.clone(), + Entry { + slot, + touched: Instant::now(), + }, + ); + Pending { guard, segment } +} + +/// Take the stored conversation `body` continues, if any. +/// +/// Waits for a run that is still settling. Any doubt -- no entry, a run that +/// could not settle, a transcript that changed under it -- starts fresh, which +/// is what every request did before continuation existed. +pub async fn resume(session_id: &str, body: &MessagesRequest) -> Resume { + let key = conversation_key(session_id, body); + let entry = STORE.lock().unwrap().remove(&key); + let (resume, reason) = match entry { + None => (Resume::Fresh, "no_conversation"), + Some(entry) => match tokio::time::timeout(SETTLE_WAIT, entry.slot.lock_owned()).await { + Err(_) => (Resume::Fresh, "settle_timeout"), + Ok(mut guard) => match guard.take() { + None => (Resume::Fresh, "not_resumable"), + Some(stored) => match delta_request(&stored.segment, body) { + None => (Resume::Fresh, "history_changed"), + Some(delta) => ( + Resume::Continue { + state: Arc::new(Mutex::new(stored.state)), + delta, + }, + "continued", + ), + }, + }, + }, + }; + log_resume(&resume, reason, body); + resume +} + +fn log_resume(resume: &Resume, reason: &str, body: &MessagesRequest) { + let mut fields = serde_json::Map::new(); + fields.insert("outcome".into(), reason.into()); + fields.insert("messages".into(), body.messages.len().into()); + if let Resume::Continue { delta, .. } = resume { + fields.insert("deltaMessages".into(), delta.messages.len().into()); + } + crate::logging::create_logger("cursor").info("cursor_conversation", Some(fields)); +} + +/// The request cut down to what the server has not seen. +/// +/// The stored run saw `messages[..prefix_len]` and wrote the reply Claude Code +/// stored as `messages[prefix_len]`. Everything after it must come from the +/// client side: tool results, a new prompt, and the `system` messages Claude +/// Code appends after a user turn (hooks, output styles). Another assistant +/// message means the transcript moved on without this conversation. +fn delta_request(segment: &Segment, body: &MessagesRequest) -> Option { + let messages = &body.messages; + let reply = messages.get(segment.prefix_len)?; + let delta = &messages[segment.prefix_len + 1..]; + if reply.role != "assistant" + || delta.is_empty() + || delta.iter().any(|message| message.role == "assistant") + || prefix_hash(&messages[..segment.prefix_len]) != segment.prefix_hash + { + return None; + } + let mut request = body.clone(); + request.messages = delta.to_vec(); + request.extra.remove("system"); + request.extra.remove("tools"); + Some(request) +} + +/// One conversation per Claude Code session, model, system prompt and tool set. +/// +/// Side requests share the session id (the auto-mode classifier, subagents) but +/// not the prompt, so each keeps its own conversation. A changed tool list +/// starts a new one: the tools travel in the first prompt only. +fn conversation_key(session_id: &str, body: &MessagesRequest) -> String { + let mut hasher = Sha256::new(); + hasher.update(session_id.as_bytes()); + hasher.update([0]); + hasher.update(body.model.as_deref().unwrap_or("").as_bytes()); + hasher.update([0]); + hasher.update(render_system(body).unwrap_or_default().as_bytes()); + hasher.update([0]); + if let Some(tools) = body.extra.get("tools") { + hasher.update(tools.to_string().as_bytes()); + } + format!("{:x}", hasher.finalize()) +} + +/// Hash of the rendered messages: the text the server saw, so markers Claude +/// Code moves between requests (`cache_control`) do not count as a change. +fn prefix_hash(messages: &[Message]) -> String { + let mut hasher = Sha256::new(); + for message in messages { + hasher.update(message.role.as_bytes()); + hasher.update([0]); + hasher.update( + render_message_content(message) + .unwrap_or_default() + .as_bytes(), + ); + hasher.update([0]); + } + format!("{:x}", hasher.finalize()) +} + +fn evict(store: &mut HashMap) { + store.retain(|_, entry| entry.touched.elapsed() < MAX_IDLE); + while store.len() >= MAX_ENTRIES { + let Some(oldest) = store + .iter() + .min_by_key(|(_, entry)| entry.touched) + .map(|(key, _)| key.clone()) + else { + break; + }; + store.remove(&oldest); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(messages: serde_json::Value) -> MessagesRequest { + serde_json::from_value(serde_json::json!({ + "model": "cursor:claude-opus-5-5-high", + "stream": true, + "system": [{"type": "text", "text": "be brief"}], + "tools": [{"name": "Read", "description": "read", "input_schema": {}}], + "messages": messages, + })) + .unwrap() + } + + fn first_turn() -> MessagesRequest { + request(serde_json::json!([{"role": "user", "content": "first question"}])) + } + + fn second_turn() -> MessagesRequest { + request(serde_json::json!([ + {"role": "user", "content": [{"type": "text", "text": "first question", + "cache_control": {"type": "ephemeral"}}]}, + {"role": "assistant", "content": "first answer"}, + {"role": "user", "content": "second question"} + ])) + } + + fn state(conversation_id: &str) -> RunState { + RunState { + conversation_id: conversation_id.to_string(), + checkpoint: Some(vec![1, 2, 3]), + blobs: HashMap::from([(b"blob".to_vec(), b"data".to_vec())]), + } + } + + #[test] + fn delta_keeps_only_the_messages_after_the_reply() { + let segment = Segment::for_request("session-delta", &first_turn()); + + let delta = delta_request(&segment, &second_turn()).expect("continues"); + + assert_eq!(delta.messages.len(), 1); + assert_eq!(delta.messages[0].content, "second question"); + assert!(delta.extra.get("system").is_none()); + assert!(delta.extra.get("tools").is_none()); + } + + #[test] + fn delta_carries_the_system_messages_claude_code_appends() { + let first = request(serde_json::json!([ + {"role": "user", "content": "first question"}, + {"role": "system", "content": [{"type": "text", "text": "style reminder", + "cache_control": {"type": "ephemeral"}}]} + ])); + let segment = Segment::for_request("session-system", &first); + let second = request(serde_json::json!([ + {"role": "user", "content": "first question"}, + {"role": "system", "content": "style reminder"}, + {"role": "assistant", "content": "first answer"}, + {"role": "user", "content": "second question"}, + {"role": "system", "content": "style reminder"} + ])); + + let delta = delta_request(&segment, &second).expect("continues"); + + let roles: Vec<&str> = delta.messages.iter().map(|m| m.role.as_str()).collect(); + assert_eq!(roles, ["user", "system"]); + } + + #[test] + fn delta_rejects_an_edited_history() { + let segment = Segment::for_request("session-edited", &first_turn()); + let edited = request(serde_json::json!([ + {"role": "user", "content": "another first question"}, + {"role": "assistant", "content": "first answer"}, + {"role": "user", "content": "second question"} + ])); + + assert!(delta_request(&segment, &edited).is_none()); + } + + #[test] + fn delta_rejects_a_second_assistant_reply() { + let segment = Segment::for_request("session-two-replies", &first_turn()); + let moved_on = request(serde_json::json!([ + {"role": "user", "content": "first question"}, + {"role": "assistant", "content": "first answer"}, + {"role": "user", "content": "second question"}, + {"role": "assistant", "content": "an answer this conversation never gave"}, + {"role": "user", "content": "third question"} + ])); + + assert!(delta_request(&segment, &moved_on).is_none()); + } + + #[test] + fn delta_rejects_a_request_without_new_user_turns() { + let segment = Segment::for_request("session-short", &first_turn()); + let reply_only = request(serde_json::json!([ + {"role": "user", "content": "first question"}, + {"role": "assistant", "content": "first answer"} + ])); + + assert!(delta_request(&segment, &reply_only).is_none()); + } + + #[test] + fn key_separates_requests_with_another_system_prompt() { + let mut classifier = second_turn(); + classifier.extra.insert( + "system".into(), + serde_json::json!([{"type": "text", "text": "classify"}]), + ); + + assert_ne!( + conversation_key("session-key", &second_turn()), + conversation_key("session-key", &classifier) + ); + assert_eq!( + conversation_key("session-key", &first_turn()), + conversation_key("session-key", &second_turn()) + ); + } + + #[tokio::test] + async fn resume_returns_the_completed_conversation() { + reserve(Segment::for_request("session-resume", &first_turn())) + .complete(state("conv-resume")); + + let Resume::Continue { state, delta } = resume("session-resume", &second_turn()).await + else { + panic!("expected a continued conversation"); + }; + + let state = state.lock().unwrap(); + assert_eq!(state.conversation_id, "conv-resume"); + assert_eq!(state.checkpoint, Some(vec![1, 2, 3])); + assert_eq!(delta.messages.len(), 1); + } + + #[tokio::test] + async fn resume_waits_for_a_run_that_is_still_settling() { + let pending = reserve(Segment::for_request("session-settle", &first_turn())); + let settle = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(50)).await; + pending.complete(state("conv-settle")); + }); + + let resumed = resume("session-settle", &second_turn()).await; + settle.await.unwrap(); + + assert!(matches!(resumed, Resume::Continue { .. })); + } + + #[tokio::test] + async fn resume_starts_fresh_when_the_run_could_not_settle() { + drop(reserve(Segment::for_request( + "session-dropped", + &first_turn(), + ))); + + assert!(matches!( + resume("session-dropped", &second_turn()).await, + Resume::Fresh + )); + } + + #[tokio::test] + async fn a_conversation_is_resumed_once() { + reserve(Segment::for_request("session-once", &first_turn())).complete(state("conv-once")); + + assert!(matches!( + resume("session-once", &second_turn()).await, + Resume::Continue { .. } + )); + assert!(matches!( + resume("session-once", &second_turn()).await, + Resume::Fresh + )); + } +} diff --git a/src/providers/cursor/mod.rs b/src/providers/cursor/mod.rs index e8b4e208..fba18d91 100644 --- a/src/providers/cursor/mod.rs +++ b/src/providers/cursor/mod.rs @@ -1,6 +1,7 @@ pub mod auth; pub mod client; pub mod connect; +pub mod continuation; pub mod model; pub mod proto; pub mod request; @@ -30,14 +31,19 @@ use crate::providers::cursor::auth::{ run_cursor_login, }; use crate::providers::cursor::client::CursorHttpClient; +use crate::providers::cursor::continuation::{Resume, RunState, Segment}; use crate::providers::cursor::model::resolve_cursor_model; use crate::providers::cursor::request::render_cursor_prompt; use crate::providers::cursor::response::{CursorDecodeError, decode_cursor_upstream}; use crate::providers::cursor::tool_bridge::{ BridgeRegistry, LiveBridge, PumpOutcome, advertised_tool_names, can_bridge_cursor_native_tools, - exec_result_messages, find_tool_result, pump_live_bridge, + drain_to_turn_end, exec_result_messages, find_tool_result, pump_live_bridge, }; +/// How long a run stopped on a text-channel tool call may take to finish its +/// turn. The agent was told to stop after the call, so this is a safety net. +const REPLAY_DRAIN_LIMIT: std::time::Duration = std::time::Duration::from_secs(60); + // --------------------------------------------------------------------------- // Provider // --------------------------------------------------------------------------- @@ -97,6 +103,9 @@ impl Provider for CursorProvider { Some(preamble) => { let mut bridge = bridge; bridge.input_floor = response::estimate_request_input_tokens(&body); + if bridge.segment.is_some() { + bridge.segment = Some(Segment::for_request(&session_id, &body)); + } return live_sse_response(bridge, preamble, &message_id, model, &ctx); } // No result for the pending exec: the caller moved on. The @@ -148,10 +157,30 @@ impl Provider for CursorProvider { && can_bridge_cursor_native_tools(&body, Some(&session_id)) { let allowed = advertised_tool_names(&body); - return match client.start_run(&token, &prompt, model, &images).await { + let keep = crate::config::cursor_continuation(); + let segment = keep.then(|| Segment::for_request(&session_id, &body)); + let resume = match keep { + true => continuation::resume(&session_id, &body).await, + false => Resume::Fresh, + }; + let (prompt, images, state, continued) = match resume { + Resume::Continue { state, delta } => ( + render_cursor_prompt(&delta), + request::cursor_selected_images(&delta), + state, + true, + ), + Resume::Fresh => (prompt, images, RunState::new_shared(), false), + }; + return match client + .start_run(&token, &prompt, model, &images, state) + .await + { Ok(run) => { let mut bridge = LiveBridge::new(session_id, run, allowed); - bridge.input_floor = (prompt.len() / 4).max(1) as u64; + bridge.input_floor = response::estimate_request_input_tokens(&body); + bridge.segment = segment; + bridge.continued = continued; live_sse_response(bridge, Vec::new(), &message_id, model, &ctx) } Err(error) => map_cursor_error_to_response(&error), @@ -243,7 +272,7 @@ impl Provider for CursorProvider { if let Some(preamble) = resume_payload(&bridge, &body) { let (bytes, outcome) = pump_buffered(&mut bridge, preamble, &message_id, &requested).await; - finish_buffered_run(bridge, outcome); + settle_run(bridge, outcome); return Ok(Generation { body: GenerationBody::BufferedSse(bytes.into()), resolved_model: resolved.model_id, @@ -298,13 +327,19 @@ impl Provider for CursorProvider { { let allowed = advertised_tool_names(&body); let run = client - .start_run(&auth.access_token, &prompt, &requested, &images) + .start_run( + &auth.access_token, + &prompt, + &requested, + &images, + RunState::new_shared(), + ) .await .map_err(cursor_provider_error)?; let mut bridge = LiveBridge::new(session_id, run, allowed); let (bytes, outcome) = pump_buffered(&mut bridge, Vec::new(), &message_id, &requested).await; - finish_buffered_run(bridge, outcome); + settle_run(bridge, outcome); if let Some(traffic) = ctx.traffic.as_ref() { traffic.write_bytes("050-anthropic-intermediate.sse", &bytes); } @@ -410,15 +445,7 @@ fn live_sse_response( } }; - match outcome { - PumpOutcome::Tool(pending) => { - bridge.pending = Some(pending); - BridgeRegistry::insert(bridge); - } - // Nothing left to resume: the run is dropped, which closes its - // stream upstream. - PumpOutcome::Replay | PumpOutcome::Ended | PumpOutcome::Failed(_) => drop(bridge), - } + settle_run(bridge, outcome); if let Some(monitor) = monitor { let (input_tokens, output_tokens) = usage_from_anthropic_sse(&sse); @@ -446,15 +473,32 @@ fn live_sse_response( (headers, body).into_response() } -/// Keep or drop a run the buffered pump stopped on. -fn finish_buffered_run(bridge: LiveBridge, outcome: PumpOutcome) { - match outcome { - PumpOutcome::Tool(pending) => { - let mut bridge = bridge; +/// Settle a run the pump stopped on. +/// +/// A run waiting on a tool result is parked for the next request. A finished +/// turn keeps its conversation for the next request when the run has a +/// segment; a run stopped on a text-channel tool call first reads its turn to +/// the end in the background, and the next request waits for that. Anything +/// else is dropped, which closes its stream upstream. +fn settle_run(mut bridge: LiveBridge, outcome: PumpOutcome) { + match (outcome, bridge.segment.take()) { + (PumpOutcome::Tool(pending), segment) => { bridge.pending = Some(pending); + bridge.segment = segment; BridgeRegistry::insert(bridge); } - PumpOutcome::Replay | PumpOutcome::Ended | PumpOutcome::Failed(_) => drop(bridge), + (PumpOutcome::Ended, Some(segment)) => { + continuation::reserve(segment).complete(bridge.run.snapshot()); + } + (PumpOutcome::Replay, Some(segment)) => { + let pending = continuation::reserve(segment); + tokio::spawn(async move { + if drain_to_turn_end(&mut bridge, REPLAY_DRAIN_LIMIT).await { + pending.complete(bridge.run.snapshot()); + } + }); + } + (PumpOutcome::Replay | PumpOutcome::Ended | PumpOutcome::Failed(_), _) => drop(bridge), } } @@ -625,10 +669,4 @@ mod tests { assert!(models.contains(&"cursor-plan".to_string())); assert!(models.contains(&"cursor-ask".to_string())); } - - #[test] - fn cursor_cli_logout_does_not_error() { - let result = CURSOR_CLI.logout(); - assert!(result.is_ok()); - } } diff --git a/src/providers/cursor/request.rs b/src/providers/cursor/request.rs index 37393549..2181be33 100644 --- a/src/providers/cursor/request.rs +++ b/src/providers/cursor/request.rs @@ -95,7 +95,7 @@ pub fn cursor_selected_images(req: &MessagesRequest) -> Vec // Internal helpers // --------------------------------------------------------------------------- -fn render_system(req: &MessagesRequest) -> Option { +pub(crate) fn render_system(req: &MessagesRequest) -> Option { let system_value = req.extra.get("system")?; let text = match system_value { serde_json::Value::String(s) => s.clone(), @@ -124,7 +124,9 @@ fn render_system(req: &MessagesRequest) -> Option { Some(text) } -fn render_message_content(message: &crate::anthropic::schema::Message) -> Option { +pub(crate) fn render_message_content( + message: &crate::anthropic::schema::Message, +) -> Option { let blocks = message_blocks(message); let rendered: Vec = blocks.iter().filter_map(render_block).collect(); if rendered.is_empty() { diff --git a/src/providers/cursor/tool_bridge.rs b/src/providers/cursor/tool_bridge.rs index a74775f7..3360e5ab 100644 --- a/src/providers/cursor/tool_bridge.rs +++ b/src/providers/cursor/tool_bridge.rs @@ -17,6 +17,7 @@ use once_cell::sync::Lazy; use crate::anthropic::schema::MessagesRequest; use crate::providers::cursor::client::{LiveEvent, LiveRun}; +use crate::providers::cursor::continuation::Segment; use crate::providers::cursor::proto; use crate::providers::cursor::sse::{CursorSseFramer, format_sse_error}; use crate::providers::cursor::tool_use_xml::{CursorToolUseXmlParser, RecoveredCursorEvent}; @@ -83,6 +84,11 @@ pub struct LiveBridge { pub allowed: Option>, /// Estimated size of the request that opened or resumed the run. pub input_floor: u64, + /// The transcript the run has seen, when its conversation is kept for the + /// next request. + pub segment: Option, + /// Whether the run continued a stored conversation. + pub continued: bool, last_activity: Instant, } @@ -94,6 +100,8 @@ impl LiveBridge { pending: None, allowed, input_floor: 0, + segment: None, + continued: false, last_activity: Instant::now(), } } @@ -349,6 +357,7 @@ pub async fn pump_live_bridge( return PumpOutcome::Replay; } if let Some(usage) = update.turn_ended.as_ref() { + log_turn_usage(usage, bridge.continued); framer.record_usage( usage.input_tokens, usage.output_tokens, @@ -376,6 +385,58 @@ pub async fn pump_live_bridge( } } +/// Read a run to the end of its turn after the pump stopped on a tool call +/// recovered from the text channel, so the server records the reply that holds +/// it and sends its final checkpoint. +/// +/// Returns `false` when the turn cannot end without Claude Code (the agent +/// asked for a tool), fails, or outlasts `limit`. +pub async fn drain_to_turn_end(bridge: &mut LiveBridge, limit: Duration) -> bool { + let drain = async { + while let Some(event) = bridge.run.events.recv().await { + match event { + LiveEvent::Message(message) => { + if let Some(usage) = message + .interaction_update + .as_ref() + .and_then(|update| update.turn_ended.as_ref()) + { + log_turn_usage(usage, bridge.continued); + } + let Some(exec) = message.exec_server_message.as_ref() else { + continue; + }; + match exec_action(exec, bridge.allowed.as_ref()) { + ExecAction::Call { .. } => return false, + ExecAction::Answer(reply) => { + if !answer(exec, reply, &bridge.run).await { + return false; + } + } + } + } + LiveEvent::End => return true, + LiveEvent::Error(_) => return false, + } + } + // The reader only stops without an event when the run is gone. + false + }; + tokio::time::timeout(limit, drain).await.unwrap_or(false) +} + +/// One line per run: the upstream's own token counts, which Claude Code's +/// counters do not show, next to whether the run continued a conversation. +fn log_turn_usage(usage: &proto::TurnEnded, continued: bool) { + let mut fields = serde_json::Map::new(); + fields.insert("continued".into(), continued.into()); + fields.insert("inputTokens".into(), usage.input_tokens.into()); + fields.insert("outputTokens".into(), usage.output_tokens.into()); + fields.insert("cacheReadTokens".into(), usage.cache_read_tokens.into()); + fields.insert("cacheWriteTokens".into(), usage.cache_write_tokens.into()); + crate::logging::create_logger("cursor").info("cursor_turn_usage", Some(fields)); +} + /// Feed one text delta through the XML recovery parser. /// /// Returns `true` when a `` was recovered: the text channel cannot diff --git a/tests/cli.rs b/tests/cli.rs index 6f5f69af..4897c1d0 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -89,14 +89,16 @@ fn unsupported_provider_auth_command_exits_two() -> Result<(), Box Result<(), Box> { - let temp = TempDir::new()?; - let mut cmd = Command::cargo_bin("claude-code-proxy")?; - cmd.args(["kimi", "auth", "logout"]); - cmd.env("CCP_CONFIG_DIR", temp.path()); - // Logout clears the legacy path as well as the primary credential path. - cmd.env("HOME", temp.path()); - cmd.env("USERPROFILE", temp.path()); - cmd.assert().success(); + for provider in ["kimi", "cursor"] { + let temp = TempDir::new()?; + let mut cmd = Command::cargo_bin("claude-code-proxy")?; + cmd.args([provider, "auth", "logout"]); + cmd.env("CCP_CONFIG_DIR", temp.path()); + // Logout clears the legacy path as well as the primary credential path. + cmd.env("HOME", temp.path()); + cmd.env("USERPROFILE", temp.path()); + cmd.assert().success(); + } Ok(()) } diff --git a/tests/cursor_native.rs b/tests/cursor_native.rs index 6806cf85..5130fa55 100644 --- a/tests/cursor_native.rs +++ b/tests/cursor_native.rs @@ -1357,6 +1357,374 @@ async fn live_run_still_answers_plain_turns() { } } +// --------------------------------------------------------------------------- +// Conversation continuation +// --------------------------------------------------------------------------- + +/// A new user turn continues the Cursor conversation: the run carries the last +/// checkpoint and conversation id, the prompt holds only the new message, and +/// the server reads the earlier turn back from the agent store. +#[tokio::test] +async fn next_turn_continues_the_cursor_conversation() { + let _guard = ENV_LOCK.lock().await; + let (addr, records) = spawn_conversation_mock("first answer").await; + set_mock_env(addr); + + let provider = claude_code_proxy::providers::cursor::CursorProvider::new(); + let first = collect_sse( + &provider, + conversation_request(serde_json::json!([ + {"role": "user", "content": "first question"} + ])), + "continue-next-turn", + ) + .await; + let second = collect_sse( + &provider, + conversation_request(serde_json::json!([ + {"role": "user", "content": "first question"}, + {"role": "assistant", "content": "first answer"}, + {"role": "user", "content": "second question"} + ])), + "continue-next-turn", + ) + .await; + + assert!(first.contains("first answer"), "{first}"); + assert!(second.contains("second answer"), "{second}"); + let records = records.lock().unwrap().clone(); + assert_eq!(records.len(), 2); + assert!(records[0].conversation_state.is_empty()); + assert_eq!(records[1].conversation_state, checkpoint_bytes()); + assert_eq!(records[1].conversation_id, records[0].conversation_id); + assert!(records[1].prompt.contains("second question")); + assert!(!records[1].prompt.contains("first question")); + assert_eq!(records[1].blob_reply.as_deref(), Some(&b"turn-1"[..])); + clear_mock_env(); +} + +/// A tool call recovered from the text channel ends the response early; the +/// run still finishes its turn in the background, and the request carrying the +/// tool result continues the conversation with that result alone. +#[tokio::test] +async fn tool_result_after_a_text_tool_call_continues_the_conversation() { + let _guard = ENV_LOCK.lock().await; + let (addr, records) = + spawn_conversation_mock(r#"{"pattern":"*.rs"}"#).await; + set_mock_env(addr); + + let provider = claude_code_proxy::providers::cursor::CursorProvider::new(); + let first = collect_sse( + &provider, + conversation_request(serde_json::json!([ + {"role": "user", "content": "list the rust files"} + ])), + "continue-text-tool", + ) + .await; + let tool_use_id = parse_sse_events(&first) + .iter() + .find_map(|(name, data)| { + (name == "content_block_start" && data["content_block"]["name"] == "Glob") + .then(|| data["content_block"]["id"].as_str().unwrap().to_string()) + }) + .expect("turn 1 asks for Glob"); + let second = collect_sse( + &provider, + conversation_request(serde_json::json!([ + {"role": "user", "content": "list the rust files"}, + {"role": "assistant", "content": [ + {"type": "tool_use", "id": tool_use_id, "name": "Glob", + "input": {"pattern": "*.rs"}} + ]}, + {"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": tool_use_id, "content": "main.rs"} + ]} + ])), + "continue-text-tool", + ) + .await; + + assert!(second.contains("second answer"), "{second}"); + let records = records.lock().unwrap().clone(); + assert_eq!(records.len(), 2); + assert_eq!(records[1].conversation_state, checkpoint_bytes()); + assert_eq!(records[1].conversation_id, records[0].conversation_id); + assert!(records[1].prompt.contains("main.rs")); + assert!(!records[1].prompt.contains("list the rust files")); + clear_mock_env(); +} + +/// A transcript that no longer matches what the conversation saw (an edit, a +/// compaction) starts a new conversation with the whole transcript. +#[tokio::test] +async fn changed_history_starts_a_new_conversation() { + let _guard = ENV_LOCK.lock().await; + let (addr, records) = spawn_conversation_mock("first answer").await; + set_mock_env(addr); + + let provider = claude_code_proxy::providers::cursor::CursorProvider::new(); + collect_sse( + &provider, + conversation_request(serde_json::json!([ + {"role": "user", "content": "first question"} + ])), + "continue-changed", + ) + .await; + collect_sse( + &provider, + conversation_request(serde_json::json!([ + {"role": "user", "content": "summary of the earlier work"}, + {"role": "assistant", "content": "first answer"}, + {"role": "user", "content": "second question"} + ])), + "continue-changed", + ) + .await; + + let records = records.lock().unwrap().clone(); + assert_eq!(records.len(), 2); + assert!(records[1].conversation_state.is_empty()); + assert_ne!(records[1].conversation_id, records[0].conversation_id); + assert!(records[1].prompt.contains("summary of the earlier work")); + clear_mock_env(); +} + +/// What one mock `Run` received. +#[derive(Default, Clone, Debug)] +struct RunRecord { + conversation_state: Vec, + conversation_id: String, + prompt: String, + blob_reply: Option>, +} + +fn conversation_request(messages: serde_json::Value) -> serde_json::Value { + serde_json::json!({ + "model": "cursor:gpt-5.5", + "stream": true, + "system": "be brief", + "tools": [ + {"name": "Read", "description": "read", "input_schema": {"type": "object"}}, + {"name": "Glob", "description": "glob", "input_schema": {"type": "object"}} + ], + "messages": messages + }) +} + +fn set_mock_env(addr: std::net::SocketAddr) { + unsafe { + std::env::set_var("CCP_CURSOR_BASE_URL", format!("http://{addr}")); + std::env::set_var("CCP_CURSOR_AUTH_TOKEN", "proxy-token"); + } +} + +fn clear_mock_env() { + unsafe { + std::env::remove_var("CCP_CURSOR_BASE_URL"); + std::env::remove_var("CCP_CURSOR_AUTH_TOKEN"); + } +} + +/// A Cursor upstream that keeps one conversation. +/// +/// The first run stores a blob, replies with `first_reply` and sends a +/// checkpoint that refers to the blob. Every later run asks for the blob back +/// before it answers "second answer". +async fn spawn_conversation_mock( + first_reply: &'static str, +) -> (std::net::SocketAddr, Arc>>) { + use axum::Router; + use axum::body::Body; + use axum::routing::post; + use claude_code_proxy::providers::cursor::connect::{ + ConnectFrameDecoder, encode_connect_frame, + }; + use claude_code_proxy::providers::cursor::proto::*; + use futures_util::StreamExt; + use prost::Message; + + let records: Arc>> = Arc::default(); + let app = { + let records = Arc::clone(&records); + Router::new().route( + "/agent.v1.AgentService/Run", + post(move |body: Body| async move { + let run = { + let mut records = records.lock().unwrap(); + records.push(RunRecord::default()); + records.len() - 1 + }; + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + let records = Arc::clone(&records); + + tokio::spawn(async move { + let mut decoder = ConnectFrameDecoder::new(); + let mut stream = body.into_data_stream(); + let mut started = false; + while let Some(Ok(chunk)) = stream.next().await { + let Ok(frames) = decoder.push(&chunk) else { + break; + }; + for frame in frames { + if !started { + started = true; + let request = raw_field(&frame.payload, 1).unwrap_or_default(); + let prompt = [2, 1, 1, 1] + .iter() + .try_fold(request.clone(), |buf, tag| raw_field(&buf, *tag)) + .unwrap_or_default(); + { + let mut records = records.lock().unwrap(); + records[run].conversation_state = + raw_field(&request, 1).unwrap_or_default(); + records[run].conversation_id = String::from_utf8( + raw_field(&request, 5).unwrap_or_default(), + ) + .unwrap(); + records[run].prompt = String::from_utf8(prompt).unwrap(); + } + if run == 0 { + let _ = tx.send(Ok(kv_frame( + 1, + kv_server_message::Message::SetBlobArgs(SetBlobArgs { + blob_id: b"blob-1".to_vec(), + blob_data: b"turn-1".to_vec(), + }), + ))); + let _ = tx.send(Ok(text_frame(first_reply))); + let _ = tx.send(Ok(encode_connect_frame( + length_delimited(3, &checkpoint_bytes()), + 0, + ))); + let _ = tx.send(Ok(usage_frame(30, 5))); + let _ = tx.send(Ok(encode_connect_frame(b"", 2))); + } else { + let _ = tx.send(Ok(kv_frame( + 2, + kv_server_message::Message::GetBlobArgs(GetBlobArgs { + blob_id: b"blob-1".to_vec(), + }), + ))); + } + continue; + } + let Ok(message) = AgentClientMessage::decode(frame.payload.clone()) + else { + continue; + }; + if let Some(KvClientMessage { + message: Some(kv_client_message::Message::GetBlobResult(result)), + .. + }) = message.kv_client_message + { + records.lock().unwrap()[run].blob_reply = result.blob_data; + let _ = tx.send(Ok(text_frame("second answer"))); + let _ = tx.send(Ok(usage_frame(40, 5))); + let _ = tx.send(Ok(encode_connect_frame(b"", 2))); + } + } + } + }); + + let body = + Body::from_stream(futures_util::stream::unfold(rx, |mut rx| async move { + rx.recv() + .await + .map(|item: Result| (item, rx)) + })); + ( + [( + axum::http::header::CONTENT_TYPE, + "application/connect+proto", + )], + body, + ) + }), + ) + }; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + (addr, records) +} + +/// A checkpoint as the server sends it: the turns (tag 8, a blob id the crate +/// does not model) and the token counter (tag 5). +fn checkpoint_bytes() -> Vec { + let mut checkpoint = length_delimited(8, b"blob-1"); + checkpoint.extend(length_delimited(5, &[0x08, 0xb0, 0x09])); + checkpoint +} + +fn kv_frame( + id: u32, + message: claude_code_proxy::providers::cursor::proto::kv_server_message::Message, +) -> bytes::Bytes { + use claude_code_proxy::providers::cursor::connect::encode_connect_frame; + use claude_code_proxy::providers::cursor::proto::*; + use prost::Message; + + let message = AgentServerMessage { + kv_server_message: Some(KvServerMessage { + id, + message: Some(message), + }), + ..Default::default() + }; + encode_connect_frame(message.encode_to_vec(), 0) +} + +/// A length-delimited protobuf field; the payloads here stay under 128 bytes. +fn length_delimited(tag: u8, value: &[u8]) -> Vec { + let mut out = vec![(tag << 3) | 2, value.len() as u8]; + out.extend_from_slice(value); + out +} + +/// The last top-level length-delimited field `tag` of a protobuf message. +fn raw_field(buf: &[u8], tag: u64) -> Option> { + fn varint(buf: &[u8], pos: &mut usize) -> Option { + let mut value = 0u64; + for shift in (0..64).step_by(7) { + let byte = *buf.get(*pos)?; + *pos += 1; + value |= u64::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + return Some(value); + } + } + None + } + + let mut pos = 0; + let mut found = None; + while pos < buf.len() { + let key = varint(buf, &mut pos)?; + match key & 7 { + 0 => { + varint(buf, &mut pos)?; + } + 1 => pos += 8, + 2 => { + let len = varint(buf, &mut pos)? as usize; + let end = pos + len; + if key >> 3 == tag { + found = Some(buf.get(pos..end)?.to_vec()); + } + pos = end; + } + 5 => pos += 4, + _ => return None, + } + } + found +} + /// Call the provider the way the proxy does and collect the whole SSE body. async fn collect_sse( provider: &claude_code_proxy::providers::cursor::CursorProvider,