Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

add cursor tool bridge state machine

Raine Virtaae65f74025fb
diff --git a/src/providers/cursor/mod.rs b/src/providers/cursor/mod.rs
index ceeed69..e2842a0 100644
--- a/src/providers/cursor/mod.rs
+++ b/src/providers/cursor/mod.rs
@@ -6,6 +6,8 @@ pub mod proto;
pub mod request;
pub mod response;
pub mod sse;
+pub mod tool_bridge;
+pub mod tool_use_xml;
use async_trait::async_trait;
use axum::Json;
@@ -19,7 +21,11 @@ use crate::providers::cursor::auth::load_cursor_token;
use crate::providers::cursor::client::CursorHttpClient;
use crate::providers::cursor::model::resolve_cursor_model;
use crate::providers::cursor::request::render_cursor_prompt;
-use crate::providers::cursor::response::decode_cursor_upstream;
+use crate::providers::cursor::response::{decode_cursor_upstream, decode_upstream_response};
+use crate::providers::cursor::tool_bridge::{
+ BridgeRegistry, advertised_tool_names, can_bridge_cursor_native_tools, find_tool_result,
+ resume_cursor_tool_bridge, start_cursor_tool_bridge,
+};
// ---------------------------------------------------------------------------
// Provider
@@ -53,7 +59,7 @@ impl Provider for CursorProvider {
&CURSOR_CLI
}
- async fn handle_messages(&self, body: MessagesRequest, _ctx: RequestContext) -> Response {
+ async fn handle_messages(&self, body: MessagesRequest, ctx: RequestContext) -> Response {
let message_id = format!("msg_{}", uuid::Uuid::new_v4().to_string().replace('-', ""));
let want_stream = body.stream;
let model = body.model.as_deref().unwrap_or("cursor");
@@ -67,6 +73,21 @@ impl Provider for CursorProvider {
);
}
+ if let Some(ref session_id) = ctx.session_id {
+ if let Some(pending) = BridgeRegistry::pending_tool(session_id) {
+ if let Some(result) = find_tool_result(&body, pending.tool_use_id()) {
+ let (_result_messages, sse_bytes) =
+ resume_cursor_tool_bridge(session_id, &message_id, model, result, &pending);
+ let headers = [
+ (http::header::CONTENT_TYPE, "text/event-stream"),
+ (http::header::CACHE_CONTROL, "no-cache"),
+ (http::header::CONNECTION, "keep-alive"),
+ ];
+ return (headers, sse_bytes).into_response();
+ }
+ }
+ }
+
let token = match load_cursor_token() {
Some(t) => t,
None => {
@@ -90,13 +111,46 @@ impl Provider for CursorProvider {
};
if want_stream {
- let sse_bytes = sse::frame_cursor_stream(&upstream, &message_id, model);
- let headers = [
- (http::header::CONTENT_TYPE, "text/event-stream"),
- (http::header::CACHE_CONTROL, "no-cache"),
- (http::header::CONNECTION, "keep-alive"),
- ];
- (headers, sse_bytes).into_response()
+ let session_id = ctx.session_id.as_deref();
+ let bridge_eligible = can_bridge_cursor_native_tools(&body, session_id);
+
+ if bridge_eligible {
+ let events = match decode_upstream_response(&upstream.body) {
+ Ok(e) => e,
+ Err(e) => {
+ return json_error(
+ StatusCode::BAD_GATEWAY,
+ "api_error",
+ format!("Response decoding error: {e}"),
+ );
+ }
+ };
+
+ let allowed = advertised_tool_names(&body);
+ let (sse_bytes, _paused) = start_cursor_tool_bridge(
+ &message_id,
+ model,
+ session_id.unwrap(),
+ &events,
+ allowed,
+ Box::new(|| uuid::Uuid::new_v4().to_string().replace('-', "")),
+ );
+
+ let headers = [
+ (http::header::CONTENT_TYPE, "text/event-stream"),
+ (http::header::CACHE_CONTROL, "no-cache"),
+ (http::header::CONNECTION, "keep-alive"),
+ ];
+ (headers, sse_bytes).into_response()
+ } else {
+ let sse_bytes = sse::frame_cursor_stream(&upstream, &message_id, model);
+ let headers = [
+ (http::header::CONTENT_TYPE, "text/event-stream"),
+ (http::header::CACHE_CONTROL, "no-cache"),
+ (http::header::CONNECTION, "keep-alive"),
+ ];
+ (headers, sse_bytes).into_response()
+ }
} else {
match decode_cursor_upstream(&upstream, &message_id, model) {
Ok(json) => (StatusCode::OK, Json(json)).into_response(),
diff --git a/src/providers/cursor/sse.rs b/src/providers/cursor/sse.rs
index 5742323..98004cd 100644
--- a/src/providers/cursor/sse.rs
+++ b/src/providers/cursor/sse.rs
@@ -82,7 +82,7 @@ fn format_sse_error(error: &str) -> Vec<u8> {
}
/// Format a single SSE event into bytes.
-fn format_sse_event_bytes(event: &str, data: &serde_json::Value) -> Vec<u8> {
+pub(crate) fn format_sse_event_bytes(event: &str, data: &serde_json::Value) -> Vec<u8> {
let json_str = serde_json::to_string(data).unwrap_or_else(|_| "{}".to_string());
format!("event: {event}\ndata: {json_str}\n\n").into_bytes()
}
@@ -125,7 +125,7 @@ impl<'a> CursorSseFramer<'a> {
}
}
- fn ensure_start(&mut self) {
+ pub fn ensure_start(&mut self) {
if self.started {
return;
}
@@ -196,7 +196,7 @@ impl<'a> CursorSseFramer<'a> {
.extend_from_slice(&format_sse_event_bytes(EVENT_CONTENT_BLOCK_START, &data));
}
- fn close_open_blocks(&mut self) {
+ pub fn close_open_blocks(&mut self) {
if self.thinking_open {
let data = serde_json::json!({
"type": "content_block_stop",
@@ -266,6 +266,53 @@ impl<'a> CursorSseFramer<'a> {
self.usage_output_tokens = output_tokens;
}
+ pub fn next_content_block_index(&mut self) -> i32 {
+ let index = self.next_index;
+ self.next_index += 1;
+ index
+ }
+
+ /// Emit a tool_use pause: content block + message_delta with
+ /// stop_reason="tool_use" + message_stop.
+ pub fn emit_tool_pause(&mut self, tool_use_id: &str, tool_name: &str, partial_json: &str) {
+ self.close_open_blocks();
+ self.ensure_start();
+ let index = self.next_content_block_index();
+
+ let data = serde_json::json!({
+ "type": "content_block_start",
+ "index": index,
+ "content_block": {
+ "type": "tool_use",
+ "id": tool_use_id,
+ "name": tool_name,
+ "input": {}
+ }
+ });
+ self.output
+ .extend_from_slice(&format_sse_event_bytes(EVENT_CONTENT_BLOCK_START, &data));
+
+ let data = serde_json::json!({
+ "type": "content_block_delta",
+ "index": index,
+ "delta": {
+ "type": "input_json_delta",
+ "partial_json": partial_json
+ }
+ });
+ self.output
+ .extend_from_slice(&format_sse_event_bytes(EVENT_CONTENT_BLOCK_DELTA, &data));
+
+ let data = serde_json::json!({
+ "type": "content_block_stop",
+ "index": index
+ });
+ self.output
+ .extend_from_slice(&format_sse_event_bytes(EVENT_CONTENT_BLOCK_STOP, &data));
+
+ self.emit_final_message("tool_use");
+ }
+
pub fn emit_final_message(&mut self, stop_reason: &str) {
if self.finalized {
return;
@@ -493,9 +540,6 @@ mod tests {
let sse = frame_cursor_stream(&upstream, "msg_1", "cursor-test");
let sse_str = String::from_utf8_lossy(&sse);
let events = parse_sse_events(&sse_str);
- let event_names: Vec<&str> = events.iter().map(|e| e.0.as_str()).collect();
-
- // Should have thinking content block start and delta
assert!(events.iter().any(|(_, data)| {
data.get("content_block")
.and_then(|c| c.get("type"))
diff --git a/src/providers/cursor/tool_bridge.rs b/src/providers/cursor/tool_bridge.rs
new file mode 100644
index 0000000..6b0ff7e
--- /dev/null
+++ b/src/providers/cursor/tool_bridge.rs
@@ -0,0 +1,1326 @@
+//! Cursor tool bridge: state machine, result builders, pending tool tracking,
+//! stream re-entry, and SSE pause/resume.
+//!
+//! The bridge coordinates the pause-and-continue lifecycle when the Cursor
+//! upstream emits a `<tool_use>` text block. The bridge pauses the SSE stream,
+//! stores the pending tool, and waits for Claude's `tool_result` in the next
+//! client request. On resume it builds Cursor protocol result messages and
+//! continues producing SSE output from stored upstream events.
+
+use std::collections::BTreeSet;
+use std::sync::Mutex;
+
+use once_cell::sync::Lazy;
+
+use crate::anthropic::schema::MessagesRequest;
+use crate::providers::cursor::response::CursorStreamEvent;
+use crate::providers::cursor::sse::CursorSseFramer;
+use crate::providers::cursor::tool_use_xml::{CursorToolUseXmlParser, RecoveredCursorEvent};
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+/// Execution context for a Cursor tool.
+#[derive(Debug, Clone, PartialEq)]
+pub struct CursorExec {
+ pub id: Option<u64>,
+ pub exec_id: Option<String>,
+ pub args: serde_json::Value,
+}
+
+/// A tool result produced by Claude.
+#[derive(Debug, Clone, PartialEq)]
+pub struct CursorNativeToolResult {
+ pub content: String,
+ pub is_error: bool,
+}
+
+/// A pending Cursor tool that Claude must fulfill.
+#[derive(Debug, Clone)]
+pub enum PendingCursorTool {
+ Read {
+ tool_use_id: String,
+ path: String,
+ },
+ Write {
+ tool_use_id: String,
+ path: String,
+ content: String,
+ },
+ Bash {
+ tool_use_id: String,
+ command: String,
+ working_directory: String,
+ timeout_ms: u64,
+ },
+}
+
+impl PendingCursorTool {
+ pub fn name(&self) -> &'static str {
+ match self {
+ Self::Read { .. } => "Read",
+ Self::Write { .. } => "Write",
+ Self::Bash { .. } => "Bash",
+ }
+ }
+
+ pub fn tool_use_id(&self) -> &str {
+ match self {
+ Self::Read { tool_use_id, .. }
+ | Self::Write { tool_use_id, .. }
+ | Self::Bash { tool_use_id, .. } => tool_use_id,
+ }
+ }
+
+ /// Build the JSON input that matches the Claude tool_use block.
+ pub fn input_json(&self) -> serde_json::Value {
+ match self {
+ Self::Read { path, .. } => {
+ serde_json::json!({ "file_path": path })
+ }
+ Self::Write { path, content, .. } => {
+ serde_json::json!({ "file_path": path, "content": content })
+ }
+ Self::Bash {
+ command,
+ working_directory,
+ timeout_ms,
+ ..
+ } => {
+ let cmd = if working_directory.is_empty() {
+ command.clone()
+ } else {
+ format!("cd '{}' && {command}", working_directory)
+ };
+ serde_json::json!({
+ "command": cmd,
+ "timeout": timeout_ms,
+ "description": "Run Cursor-requested shell command",
+ "run_in_background": false,
+ "dangerouslyDisableSandbox": false
+ })
+ }
+ }
+ }
+}
+
+/// Bridge state stored per session.
+#[derive(Debug)]
+pub struct CursorBridgeState {
+ pub session_id: String,
+ pub message_id: String,
+ pub model: String,
+ pub pending_tool: Option<PendingCursorTool>,
+ pub remaining_events: Vec<CursorStreamEvent>,
+ pub event_cursor: usize,
+ pub input_tokens: u64,
+ pub output_tokens: u64,
+ pub allowed_tool_names: Option<BTreeSet<String>>,
+ pub xml_parser: CursorToolUseXmlParser,
+}
+
+impl CursorBridgeState {
+ fn new(
+ session_id: String,
+ message_id: String,
+ model: String,
+ allowed_tool_names: Option<BTreeSet<String>>,
+ id_factory: Box<dyn FnMut() -> String + Send>,
+ ) -> Self {
+ Self {
+ session_id,
+ message_id,
+ model,
+ pending_tool: None,
+ remaining_events: Vec::new(),
+ event_cursor: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ allowed_tool_names: allowed_tool_names.clone(),
+ xml_parser: CursorToolUseXmlParser::new_with_id_factory(allowed_tool_names, id_factory),
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Global bridge registry
+// ---------------------------------------------------------------------------
+
+static BRIDGE_REGISTRY: Lazy<Mutex<BridgeRegistryInner>> =
+ Lazy::new(|| Mutex::new(BridgeRegistryInner::new()));
+
+struct BridgeRegistryInner {
+ sessions: Vec<CursorBridgeState>,
+}
+
+impl BridgeRegistryInner {
+ fn new() -> Self {
+ Self {
+ sessions: Vec::new(),
+ }
+ }
+}
+
+/// Global registry of active bridge sessions.
+pub struct BridgeRegistry;
+
+impl BridgeRegistry {
+ /// Insert a new bridge state for a session.
+ pub fn insert(state: CursorBridgeState) {
+ let mut reg = BRIDGE_REGISTRY.lock().unwrap();
+ reg.sessions.push(state);
+ }
+
+ /// Get the bridge state for a session.
+ pub fn get(session_id: &str) -> Option<usize> {
+ let reg = BRIDGE_REGISTRY.lock().unwrap();
+ reg.sessions.iter().position(|s| s.session_id == session_id)
+ }
+
+ /// Get the pending tool for a session (if any).
+ pub fn pending_tool(session_id: &str) -> Option<PendingCursorTool> {
+ let reg = BRIDGE_REGISTRY.lock().unwrap();
+ reg.sessions
+ .iter()
+ .find(|s| s.session_id == session_id)
+ .and_then(|s| s.pending_tool.clone())
+ }
+
+ /// Take the bridge state for a session (removes it).
+ pub fn take(session_id: &str) -> Option<CursorBridgeState> {
+ let mut reg = BRIDGE_REGISTRY.lock().unwrap();
+ let pos = reg
+ .sessions
+ .iter()
+ .position(|s| s.session_id == session_id)?;
+ Some(reg.sessions.swap_remove(pos))
+ }
+
+ /// Remove a bridge state for a session.
+ pub fn remove(session_id: &str) {
+ let mut reg = BRIDGE_REGISTRY.lock().unwrap();
+ reg.sessions.retain(|s| s.session_id != session_id);
+ }
+
+ /// Insert or update the pending tool for a session.
+ pub fn set_pending_tool(session_id: &str, tool: PendingCursorTool) {
+ let mut reg = BRIDGE_REGISTRY.lock().unwrap();
+ if let Some(state) = reg.sessions.iter_mut().find(|s| s.session_id == session_id) {
+ state.pending_tool = Some(tool);
+ }
+ }
+
+ /// Update usage for a session.
+ pub fn record_usage(session_id: &str, input_tokens: u64, output_tokens: u64) {
+ let mut reg = BRIDGE_REGISTRY.lock().unwrap();
+ if let Some(state) = reg.sessions.iter_mut().find(|s| s.session_id == session_id) {
+ state.input_tokens = input_tokens.max(state.input_tokens);
+ state.output_tokens = output_tokens.max(state.output_tokens);
+ }
+ }
+
+ /// Clear all bridge state.
+ pub fn clear() {
+ let mut reg = BRIDGE_REGISTRY.lock().unwrap();
+ reg.sessions.clear();
+ }
+
+ /// Number of active sessions.
+ pub fn active_count() -> usize {
+ let reg = BRIDGE_REGISTRY.lock().unwrap();
+ reg.sessions.len()
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Tool detection helpers
+// ---------------------------------------------------------------------------
+
+/// Extract advertised tool names from a MessagesRequest.
+pub fn advertised_tool_names(body: &MessagesRequest) -> Option<BTreeSet<String>> {
+ let tools = body.extra.get("tools")?.as_array()?;
+ if tools.is_empty() {
+ return None;
+ }
+ let names: BTreeSet<String> = tools
+ .iter()
+ .filter_map(|t| t.get("name").and_then(|n| n.as_str()))
+ .map(|n| n.to_string())
+ .collect();
+ if names.is_empty() { None } else { Some(names) }
+}
+
+/// Whether the request can use the Cursor native tool bridge.
+///
+/// Returns `true` when the request is streaming, has a session id, and
+/// advertises at least one of Read, Write, or Bash.
+pub fn can_bridge_cursor_native_tools(body: &MessagesRequest, session_id: Option<&str>) -> bool {
+ let _sid = match session_id {
+ Some(id) if !id.is_empty() => id,
+ _ => return false,
+ };
+ if !body.stream {
+ return false;
+ }
+ let names = match advertised_tool_names(body) {
+ Some(n) => n,
+ None => return false,
+ };
+ names.contains("Read") || names.contains("Write") || names.contains("Bash")
+}
+
+// ---------------------------------------------------------------------------
+// Result helpers
+// ---------------------------------------------------------------------------
+
+/// Find the last `tool_result` block matching `tool_use_id` in the request.
+pub fn find_tool_result<'a>(
+ body: &'a MessagesRequest,
+ tool_use_id: &str,
+) -> Option<&'a serde_json::Value> {
+ for message in body.messages.iter().rev() {
+ if message.role != "user" {
+ continue;
+ }
+ let blocks = match &message.content {
+ serde_json::Value::Array(arr) => arr,
+ _ => continue,
+ };
+ for block in blocks.iter().rev() {
+ if block.get("type").and_then(|t| t.as_str()) == Some("tool_result")
+ && block.get("tool_use_id").and_then(|t| t.as_str()) == Some(tool_use_id)
+ {
+ return Some(block);
+ }
+ }
+ }
+ None
+}
+
+/// Render the content of a `tool_result` block into a string.
+///
+/// Mirrors the TypeScript `renderToolResultContent` function.
+pub fn render_tool_result_content(result: &serde_json::Value) -> String {
+ let content = match result.get("content") {
+ Some(serde_json::Value::String(s)) => return s.clone(),
+ Some(serde_json::Value::Array(arr)) => arr.clone(),
+ _ => return String::new(),
+ };
+ let parts: Vec<String> = content
+ .iter()
+ .map(|block| match block.get("type").and_then(|t| t.as_str()) {
+ Some("text") => block
+ .get("text")
+ .and_then(|t| t.as_str())
+ .unwrap_or("")
+ .to_string(),
+ Some("image") => "[image result omitted]".to_string(),
+ Some("thinking") => block
+ .get("thinking")
+ .and_then(|t| t.as_str())
+ .unwrap_or("")
+ .to_string(),
+ _ => serde_json::to_string(block).unwrap_or_default(),
+ })
+ .collect();
+ parts.join("\n")
+}
+
+/// Whether a `tool_result` block indicates an error.
+pub fn tool_result_is_error(result: &serde_json::Value) -> bool {
+ result
+ .get("is_error")
+ .and_then(|e| e.as_bool())
+ .unwrap_or(false)
+}
+
+/// Build the partial JSON string for a pending tool's input (for the
+/// input_json_delta in the tool_use content block).
+pub fn build_tool_use_input_json(tool: &PendingCursorTool) -> String {
+ serde_json::to_string(&tool.input_json()).unwrap_or_else(|_| "{}".to_string())
+}
+
+// ---------------------------------------------------------------------------
+// Cursor protocol message builders
+// ---------------------------------------------------------------------------
+
+/// Inject `id` and `execId` fields into a JSON payload.
+pub fn with_exec_ids(
+ exec: &CursorExec,
+ mut payload: serde_json::Map<String, serde_json::Value>,
+) -> serde_json::Value {
+ if let Some(id) = exec.id {
+ payload.insert("id".into(), id.into());
+ }
+ if let Some(ref exec_id) = exec.exec_id {
+ payload.insert("execId".into(), exec_id.clone().into());
+ }
+ serde_json::Value::Object(payload)
+}
+
+/// Build the Cursor `readResult` message from a Claude `tool_result`.
+pub fn build_read_result_from_native(
+ exec: &CursorExec,
+ result: &CursorNativeToolResult,
+) -> serde_json::Value {
+ let path = exec
+ .args
+ .get("file_path")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ let content = &result.content;
+ let lines = if content.is_empty() {
+ 0
+ } else {
+ content.lines().count()
+ };
+ let file_size = content.len().to_string();
+
+ let read_result = if result.is_error {
+ serde_json::json!({
+ "success": {
+ "path": path,
+ "content": content,
+ "totalLines": lines,
+ "fileSize": file_size
+ }
+ })
+ } else {
+ serde_json::json!({
+ "success": {
+ "path": path,
+ "content": content,
+ "totalLines": lines,
+ "fileSize": file_size
+ }
+ })
+ };
+
+ let mut map = serde_json::Map::new();
+ map.insert("readResult".into(), read_result);
+ with_exec_ids(exec, map)
+}
+
+/// Build the Cursor `writeResult` message from a Claude `tool_result`.
+pub fn build_write_result_from_native(
+ exec: &CursorExec,
+ result: &CursorNativeToolResult,
+) -> serde_json::Value {
+ let path = exec
+ .args
+ .get("file_path")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ let write_result = if result.is_error {
+ serde_json::json!({
+ "error": {
+ "path": path,
+ "error": result.content
+ }
+ })
+ } else {
+ let lines = if result.content.is_empty() {
+ 0
+ } else {
+ result.content.lines().count()
+ };
+ serde_json::json!({
+ "success": {
+ "path": path,
+ "linesCreated": lines,
+ "fileSize": result.content.len()
+ }
+ })
+ };
+
+ let mut map = serde_json::Map::new();
+ map.insert("writeResult".into(), write_result);
+ with_exec_ids(exec, map)
+}
+
+/// Build the collection of Cursor `shellStream` messages from a Claude
+/// `tool_result`.
+///
+/// Returns: start, stdout/stderr, exit, streamClose.
+pub fn build_shell_stream_result(
+ exec: &CursorExec,
+ result: &CursorNativeToolResult,
+ local_execution_time: std::time::Duration,
+ cwd: &str,
+) -> Vec<serde_json::Value> {
+ let mut messages: Vec<serde_json::Value> = Vec::new();
+
+ // Start
+ let start_msg = with_exec_ids(
+ exec,
+ serde_json::json!({ "shellStream": { "start": {} } })
+ .as_object()
+ .cloned()
+ .unwrap_or_default(),
+ );
+ messages.push(start_msg);
+
+ // Content (stdout or stderr)
+ if !result.content.is_empty() {
+ let stream_key = if result.is_error { "stderr" } else { "stdout" };
+ let content_msg = with_exec_ids(
+ exec,
+ serde_json::json!({ "shellStream": { stream_key: { "data": result.content } } })
+ .as_object()
+ .cloned()
+ .unwrap_or_default(),
+ );
+ messages.push(content_msg);
+ }
+
+ // Exit
+ let exit_code: u32 = if result.is_error { 1 } else { 0 };
+ let exit_msg = with_exec_ids(
+ exec,
+ serde_json::json!({
+ "shellStream": {
+ "exit": {
+ "code": exit_code,
+ "cwd": cwd,
+ "localExecutionTimeMs": local_execution_time.as_millis() as u64,
+ }
+ }
+ })
+ .as_object()
+ .cloned()
+ .unwrap_or_default(),
+ );
+ messages.push(exit_msg);
+
+ // Stream close
+ if let Some(id) = exec.id {
+ let close_msg = serde_json::json!({
+ "execClientControlMessage": {
+ "streamClose": {
+ "id": id
+ }
+ }
+ });
+ messages.push(close_msg);
+ } else {
+ let close_msg = serde_json::json!({
+ "execClientControlMessage": {
+ "streamClose": {}
+ }
+ });
+ messages.push(close_msg);
+ }
+
+ messages
+}
+
+// ---------------------------------------------------------------------------
+// Bridge start and resume
+// ---------------------------------------------------------------------------
+
+/// Start a new tool bridge session.
+///
+/// Processes upstream events through XML recovery. When a `<tool_use>` is
+/// recovered, emits the SSE pause (tool_use content block + message_stop with
+/// stop_reason="tool_use") and stores the bridge state for resume.
+///
+/// Returns the SSE bytes and whether a tool_use pause was emitted.
+pub fn start_cursor_tool_bridge(
+ message_id: &str,
+ model: &str,
+ session_id: &str,
+ events: &[CursorStreamEvent],
+ allowed_tool_names: Option<BTreeSet<String>>,
+ id_factory: Box<dyn FnMut() -> String + Send>,
+) -> (Vec<u8>, bool) {
+ let mut sse = Vec::new();
+ let mut framer = CursorSseFramer::new(&mut sse, message_id, model);
+
+ let mut state = CursorBridgeState::new(
+ session_id.to_string(),
+ message_id.to_string(),
+ model.to_string(),
+ allowed_tool_names,
+ id_factory,
+ );
+
+ let mut paused = false;
+
+ for event in events {
+ if paused {
+ state.remaining_events.push(event.clone());
+ continue;
+ }
+
+ match event {
+ CursorStreamEvent::ThinkingDelta { text } => {
+ framer.emit_thinking_delta(text);
+ }
+ CursorStreamEvent::TextDelta { text } => {
+ let recovered = state.xml_parser.push(text);
+ for recovered_event in &recovered {
+ if paused {
+ if let RecoveredCursorEvent::Text(t) = recovered_event {
+ state
+ .remaining_events
+ .push(CursorStreamEvent::TextDelta { text: t.clone() });
+ }
+ continue;
+ }
+ match recovered_event {
+ RecoveredCursorEvent::Text(t) => {
+ framer.emit_text_delta(t);
+ }
+ RecoveredCursorEvent::ToolUse(tool_use) => {
+ let input_json = serde_json::to_string(&tool_use.input)
+ .unwrap_or_else(|_| "{}".to_string());
+ framer.emit_tool_pause(&tool_use.id, &tool_use.name, &input_json);
+
+ if let Some(pending) = pending_from_recovered_tool(tool_use) {
+ state.pending_tool = Some(pending);
+ }
+
+ paused = true;
+ }
+ }
+ }
+ }
+ CursorStreamEvent::Usage {
+ input_tokens,
+ output_tokens,
+ ..
+ } => {
+ framer.record_usage(*input_tokens, *output_tokens, 0, 0);
+ state.input_tokens = *input_tokens;
+ state.output_tokens = *output_tokens;
+ }
+ CursorStreamEvent::Session { .. } => {
+ // Session info is not mapped to SSE events
+ }
+ CursorStreamEvent::End => {
+ // If we haven't paused, finalize normally
+ if !paused {
+ // Process any remaining XML before finalizing
+ let flushed = state.xml_parser.flush();
+ for evt in &flushed {
+ if let RecoveredCursorEvent::ToolUse(tool_use) = evt {
+ let input_json = serde_json::to_string(&tool_use.input)
+ .unwrap_or_else(|_| "{}".to_string());
+ framer.emit_tool_pause(&tool_use.id, &tool_use.name, &input_json);
+ if let Some(pending) = pending_from_recovered_tool(tool_use) {
+ state.pending_tool = Some(pending);
+ }
+ paused = true;
+ }
+ }
+ if !paused {
+ framer.finalize();
+ }
+ }
+ }
+ }
+ }
+
+ if paused {
+ let remaining = state.remaining_events.clone();
+ let mut stored_state = CursorBridgeState::new(
+ session_id.to_string(),
+ message_id.to_string(),
+ model.to_string(),
+ state.allowed_tool_names.clone(),
+ Box::new(|| {
+ format!(
+ "call_cursor_{}",
+ uuid::Uuid::new_v4().to_string().replace('-', "")
+ )
+ }),
+ );
+ stored_state.pending_tool = state.pending_tool.clone();
+ stored_state.remaining_events = remaining;
+ stored_state.event_cursor = 0;
+ stored_state.input_tokens = state.input_tokens;
+ stored_state.output_tokens = state.output_tokens;
+ BridgeRegistry::insert(stored_state);
+ }
+
+ if !paused {
+ // Flush any remaining text from XML parser
+ let flushed = state.xml_parser.flush();
+ for evt in &flushed {
+ if let RecoveredCursorEvent::ToolUse(tool_use) = evt {
+ let input_json =
+ serde_json::to_string(&tool_use.input).unwrap_or_else(|_| "{}".to_string());
+ framer.emit_tool_pause(&tool_use.id, &tool_use.name, &input_json);
+ if let Some(pending) = pending_from_recovered_tool(tool_use) {
+ state.pending_tool = Some(pending);
+ }
+ paused = true;
+ }
+ }
+ if !paused {
+ framer.finalize();
+ }
+ }
+
+ (sse, paused)
+}
+
+/// Resume a paused tool bridge session.
+///
+/// Finds the stored state by session_id, resolves the pending tool with
+/// Claude's `tool_result`, and continues producing SSE from remaining events.
+pub fn resume_cursor_tool_bridge(
+ session_id: &str,
+ new_message_id: &str,
+ new_model: &str,
+ result: &serde_json::Value,
+ pending_tool: &PendingCursorTool,
+) -> (Vec<serde_json::Value>, Vec<u8>) {
+ let native_result = CursorNativeToolResult {
+ content: render_tool_result_content(result),
+ is_error: tool_result_is_error(result),
+ };
+
+ // Build Cursor protocol messages for the resolved tool
+ let exec = CursorExec {
+ id: None,
+ exec_id: None,
+ args: pending_tool.input_json(),
+ };
+ let result_messages = match pending_tool {
+ PendingCursorTool::Read { .. } => {
+ let msg = build_read_result_from_native(&exec, &native_result);
+ vec![msg]
+ }
+ PendingCursorTool::Write { .. } => {
+ let msg = build_write_result_from_native(&exec, &native_result);
+ vec![msg]
+ }
+ PendingCursorTool::Bash {
+ working_directory, ..
+ } => build_shell_stream_result(
+ &exec,
+ &native_result,
+ std::time::Duration::from_millis(0),
+ working_directory,
+ ),
+ };
+
+ // Generate SSE continuation from remaining events
+ let mut sse = Vec::new();
+ let mut framer = CursorSseFramer::new(&mut sse, new_message_id, new_model);
+
+ // Retrieve stored state for remaining events
+ let remaining: Vec<CursorStreamEvent> = BridgeRegistry::pending_tool(session_id)
+ .and_then(|_| BridgeRegistry::take(session_id))
+ .map(|state| state.remaining_events)
+ .unwrap_or_default();
+
+ if remaining.is_empty() {
+ // No remaining events: just finalize
+ framer.finalize();
+ } else {
+ let mut xml_parser = CursorToolUseXmlParser::new(None);
+ let mut paused_again = false;
+
+ for event in &remaining {
+ match event {
+ CursorStreamEvent::ThinkingDelta { text } => {
+ if !paused_again {
+ framer.emit_thinking_delta(text);
+ }
+ }
+ CursorStreamEvent::TextDelta { text } => {
+ if paused_again {
+ continue;
+ }
+ let recovered = xml_parser.push(text);
+ for evt in &recovered {
+ match evt {
+ RecoveredCursorEvent::Text(t) => {
+ framer.emit_text_delta(t);
+ }
+ RecoveredCursorEvent::ToolUse(tool_use) => {
+ let input_json = serde_json::to_string(&tool_use.input)
+ .unwrap_or_else(|_| "{}".to_string());
+ framer.emit_tool_pause(&tool_use.id, &tool_use.name, &input_json);
+ paused_again = true;
+ }
+ }
+ }
+ }
+ CursorStreamEvent::Usage {
+ input_tokens,
+ output_tokens,
+ ..
+ } => {
+ if !paused_again {
+ framer.record_usage(*input_tokens, *output_tokens, 0, 0);
+ }
+ }
+ CursorStreamEvent::Session { .. } => {}
+ CursorStreamEvent::End => {
+ if !paused_again {
+ // Flush before finalizing
+ let flushed = xml_parser.flush();
+ for evt in &flushed {
+ if let RecoveredCursorEvent::ToolUse(tool_use) = evt {
+ let input_json = serde_json::to_string(&tool_use.input)
+ .unwrap_or_else(|_| "{}".to_string());
+ framer.emit_tool_pause(&tool_use.id, &tool_use.name, &input_json);
+ paused_again = true;
+ }
+ }
+ if !paused_again {
+ framer.finalize();
+ }
+ }
+ }
+ }
+ }
+
+ if !paused_again {
+ let flushed = xml_parser.flush();
+ for evt in &flushed {
+ if let RecoveredCursorEvent::ToolUse(tool_use) = evt {
+ let input_json =
+ serde_json::to_string(&tool_use.input).unwrap_or_else(|_| "{}".to_string());
+ framer.emit_tool_pause(&tool_use.id, &tool_use.name, &input_json);
+ paused_again = true;
+ }
+ }
+ if !paused_again {
+ framer.finalize();
+ }
+ }
+
+ if paused_again && !remaining.is_empty() {
+ let state = CursorBridgeState::new(
+ session_id.to_string(),
+ new_message_id.to_string(),
+ new_model.to_string(),
+ None,
+ Box::new(|| {
+ format!(
+ "call_cursor_{}",
+ uuid::Uuid::new_v4().to_string().replace('-', "")
+ )
+ }),
+ );
+ BridgeRegistry::insert(state);
+ }
+ }
+
+ (result_messages, sse)
+}
+
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+/// Create a `PendingCursorTool` from a recovered XML tool_use event.
+fn pending_from_recovered_tool(
+ tool_use: &crate::providers::cursor::tool_use_xml::RecoveredCursorToolUse,
+) -> Option<PendingCursorTool> {
+ match tool_use.name.as_str() {
+ "Read" => {
+ let file_path = tool_use
+ .input
+ .get("file_path")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ Some(PendingCursorTool::Read {
+ tool_use_id: tool_use.id.clone(),
+ path: file_path,
+ })
+ }
+ "Write" => {
+ let file_path = tool_use
+ .input
+ .get("file_path")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let content = tool_use
+ .input
+ .get("content")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ Some(PendingCursorTool::Write {
+ tool_use_id: tool_use.id.clone(),
+ path: file_path,
+ content,
+ })
+ }
+ "Bash" => {
+ let command = tool_use
+ .input
+ .get("command")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let working_directory = String::new();
+ let timeout_ms = tool_use
+ .input
+ .get("timeout")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(30_000);
+ Some(PendingCursorTool::Bash {
+ tool_use_id: tool_use.id.clone(),
+ command,
+ working_directory,
+ timeout_ms,
+ })
+ }
+ _ => None,
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::anthropic::schema::MessagesRequest;
+ use std::sync::Mutex;
+
+ /// Serialize tests that share the global bridge registry.
+ static REGISTRY_LOCK: Mutex<()> = Mutex::new(());
+
+ // -----------------------------------------------------------------------
+ // PendingCursorTool tests
+ // -----------------------------------------------------------------------
+
+ #[test]
+ fn pending_read_input_matches_claude_read_tool() {
+ let tool = PendingCursorTool::Read {
+ tool_use_id: "call_cursor_1".into(),
+ path: "/tmp/a".into(),
+ };
+ let json = tool.input_json();
+ assert_eq!(json["file_path"], "/tmp/a");
+ assert_eq!(tool.name(), "Read");
+ assert_eq!(tool.tool_use_id(), "call_cursor_1");
+ }
+
+ #[test]
+ fn pending_write_input_matches_claude_write_tool() {
+ let tool = PendingCursorTool::Write {
+ tool_use_id: "call_cursor_2".into(),
+ path: "/tmp/b".into(),
+ content: "hello".into(),
+ };
+ let json = tool.input_json();
+ assert_eq!(json["file_path"], "/tmp/b");
+ assert_eq!(json["content"], "hello");
+ assert_eq!(tool.name(), "Write");
+ }
+
+ #[test]
+ fn pending_bash_input_matches_claude_bash_tool() {
+ let tool = PendingCursorTool::Bash {
+ tool_use_id: "call_cursor_3".into(),
+ command: "pwd".into(),
+ working_directory: "/tmp".into(),
+ timeout_ms: 30_000,
+ };
+ let json = tool.input_json();
+ assert_eq!(json["command"], "cd '/tmp' && pwd");
+ assert_eq!(json["timeout"], 30_000);
+ assert_eq!(json["description"], "Run Cursor-requested shell command");
+ assert_eq!(tool.name(), "Bash");
+ }
+
+ #[test]
+ fn pending_bash_no_working_directory() {
+ let tool = PendingCursorTool::Bash {
+ tool_use_id: "call_cursor_4".into(),
+ command: "ls".into(),
+ working_directory: "".into(),
+ timeout_ms: 10_000,
+ };
+ let json = tool.input_json();
+ // Without a working directory, command is passed as-is
+ assert_eq!(json["command"], "ls");
+ }
+
+ // -----------------------------------------------------------------------
+ // Result builder tests
+ // -----------------------------------------------------------------------
+
+ #[test]
+ fn with_exec_ids_adds_id_and_exec_id() {
+ let exec = CursorExec {
+ id: Some(7),
+ exec_id: Some("exec-1".into()),
+ args: serde_json::json!({}),
+ };
+ let mut payload = serde_json::Map::new();
+ payload.insert("test".into(), serde_json::json!("value"));
+ let result = with_exec_ids(&exec, payload);
+ assert_eq!(result["id"], 7);
+ assert_eq!(result["execId"], "exec-1");
+ assert_eq!(result["test"], "value");
+ }
+
+ #[test]
+ fn with_exec_ids_omits_missing_fields() {
+ let exec = CursorExec {
+ id: None,
+ exec_id: None,
+ args: serde_json::json!({}),
+ };
+ let mut payload = serde_json::Map::new();
+ payload.insert("test".into(), serde_json::json!("v"));
+ let result = with_exec_ids(&exec, payload);
+ assert!(result.get("id").is_none());
+ assert!(result.get("execId").is_none());
+ assert_eq!(result["test"], "v");
+ }
+
+ #[test]
+ fn read_result_from_successful_result() {
+ let exec = CursorExec {
+ id: Some(1),
+ exec_id: None,
+ args: serde_json::json!({"file_path": "/tmp/a"}),
+ };
+ let result = CursorNativeToolResult {
+ content: "file content".into(),
+ is_error: false,
+ };
+ let msg = build_read_result_from_native(&exec, &result);
+ assert_eq!(msg["id"], 1);
+ assert_eq!(msg["readResult"]["success"]["path"], "/tmp/a");
+ assert_eq!(msg["readResult"]["success"]["content"], "file content");
+ assert_eq!(msg["readResult"]["success"]["totalLines"], 1);
+ }
+
+ #[test]
+ fn write_result_from_successful_result() {
+ let exec = CursorExec {
+ id: Some(2),
+ exec_id: None,
+ args: serde_json::json!({"file_path": "/tmp/b", "content": "hi"}),
+ };
+ let result = CursorNativeToolResult {
+ content: "success".into(),
+ is_error: false,
+ };
+ let msg = build_write_result_from_native(&exec, &result);
+ assert_eq!(msg["id"], 2);
+ assert_eq!(msg["writeResult"]["success"]["path"], "/tmp/b");
+ assert_eq!(msg["writeResult"]["success"]["linesCreated"], 1);
+ }
+
+ #[test]
+ fn write_result_from_error_result() {
+ let exec = CursorExec {
+ id: Some(3),
+ exec_id: None,
+ args: serde_json::json!({"file_path": "/tmp/c"}),
+ };
+ let result = CursorNativeToolResult {
+ content: "permission denied".into(),
+ is_error: true,
+ };
+ let msg = build_write_result_from_native(&exec, &result);
+ assert_eq!(msg["writeResult"]["error"]["path"], "/tmp/c");
+ assert_eq!(msg["writeResult"]["error"]["error"], "permission denied");
+ }
+
+ #[test]
+ fn shell_stream_result_emits_start_output_exit_and_close() {
+ let exec = CursorExec {
+ id: Some(7),
+ exec_id: Some("e".into()),
+ args: serde_json::json!({}),
+ };
+ let messages = build_shell_stream_result(
+ &exec,
+ &CursorNativeToolResult {
+ content: "hi".into(),
+ is_error: false,
+ },
+ std::time::Duration::from_millis(3),
+ "/tmp",
+ );
+ assert_eq!(messages.len(), 4);
+ // Start
+ assert!(
+ messages[0]
+ .get("shellStream")
+ .and_then(|s| s.get("start"))
+ .is_some()
+ );
+ // Stdout content
+ assert_eq!(messages[1]["shellStream"]["stdout"]["data"], "hi");
+ // Exit
+ assert_eq!(messages[2]["shellStream"]["exit"]["code"], 0);
+ assert_eq!(messages[2]["shellStream"]["exit"]["cwd"], "/tmp");
+ // Stream close
+ assert_eq!(
+ messages[3]["execClientControlMessage"]["streamClose"]["id"],
+ 7
+ );
+ }
+
+ #[test]
+ fn shell_stream_handles_error_result() {
+ let exec = CursorExec {
+ id: Some(8),
+ exec_id: None,
+ args: serde_json::json!({}),
+ };
+ let messages = build_shell_stream_result(
+ &exec,
+ &CursorNativeToolResult {
+ content: "error msg".into(),
+ is_error: true,
+ },
+ std::time::Duration::from_millis(5),
+ "/tmp",
+ );
+ assert_eq!(messages.len(), 4);
+ assert_eq!(messages[1]["shellStream"]["stderr"]["data"], "error msg");
+ assert_eq!(messages[2]["shellStream"]["exit"]["code"], 1);
+ }
+
+ // -----------------------------------------------------------------------
+ // find_tool_result tests
+ // -----------------------------------------------------------------------
+
+ #[test]
+ fn finds_tool_result_in_request() {
+ let body: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model": "cursor:gpt-5.5",
+ "messages": [
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "result text"}]}
+ ]
+ }))
+ .unwrap();
+ let result = find_tool_result(&body, "call_1");
+ assert!(result.is_some());
+ assert_eq!(
+ result.unwrap().get("content").and_then(|c| c.as_str()),
+ Some("result text")
+ );
+ }
+
+ #[test]
+ fn find_tool_result_returns_none_when_not_found() {
+ let body: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model": "cursor:gpt-5.5",
+ "messages": [
+ {"role": "user", "content": [{"type": "text", "text": "hello"}]}
+ ]
+ }))
+ .unwrap();
+ assert!(find_tool_result(&body, "call_1").is_none());
+ }
+
+ #[test]
+ fn find_tool_result_scans_newest_first() {
+ let body: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model": "cursor:gpt-5.5",
+ "messages": [
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "old"}]},
+ {"role": "assistant", "content": "ok"},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "new"}]}
+ ]
+ }))
+ .unwrap();
+ let result = find_tool_result(&body, "call_1");
+ assert!(result.is_some());
+ assert_eq!(
+ result.unwrap().get("content").and_then(|c| c.as_str()),
+ Some("new")
+ );
+ }
+
+ // -----------------------------------------------------------------------
+ // advertised_tool_names tests
+ // -----------------------------------------------------------------------
+
+ #[test]
+ fn advertised_tool_names_extracts_read_write_bash() {
+ let body: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model": "cursor:gpt-5.5",
+ "messages": [{"role": "user", "content": "hi"}],
+ "tools": [
+ {"name": "Read", "description": "read", "input_schema": {}},
+ {"name": "Write", "description": "write", "input_schema": {}},
+ {"name": "Bash", "description": "bash", "input_schema": {}}
+ ]
+ }))
+ .unwrap();
+ let names = advertised_tool_names(&body).unwrap();
+ assert!(names.contains("Read"));
+ assert!(names.contains("Write"));
+ assert!(names.contains("Bash"));
+ }
+
+ #[test]
+ fn advertised_tool_names_no_tools_returns_none() {
+ let body: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model": "cursor:gpt-5.5",
+ "messages": [{"role": "user", "content": "hi"}]
+ }))
+ .unwrap();
+ assert!(advertised_tool_names(&body).is_none());
+ }
+
+ #[test]
+ fn can_bridge_returns_true_for_stream_with_read_tool() {
+ let body: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model": "cursor:gpt-5.5",
+ "stream": true,
+ "messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"name": "Read", "description": "read", "input_schema": {}}]
+ }))
+ .unwrap();
+ assert!(can_bridge_cursor_native_tools(&body, Some("session-1")));
+ }
+
+ #[test]
+ fn can_bridge_returns_false_for_non_streaming() {
+ let body: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model": "cursor:gpt-5.5",
+ "stream": false,
+ "messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"name": "Read", "description": "read", "input_schema": {}}]
+ }))
+ .unwrap();
+ assert!(!can_bridge_cursor_native_tools(&body, Some("session-1")));
+ }
+
+ #[test]
+ fn can_bridge_returns_false_without_session_id() {
+ let body: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model": "cursor:gpt-5.5",
+ "stream": true,
+ "messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"name": "Read", "description": "read", "input_schema": {}}]
+ }))
+ .unwrap();
+ assert!(!can_bridge_cursor_native_tools(&body, None));
+ assert!(!can_bridge_cursor_native_tools(&body, Some("")));
+ }
+
+ // -----------------------------------------------------------------------
+ // BridgeRegistry tests
+ // -----------------------------------------------------------------------
+
+ #[test]
+ fn bridge_registry_manages_sessions() {
+ let _lock = REGISTRY_LOCK.lock().unwrap();
+ BridgeRegistry::clear();
+ assert_eq!(BridgeRegistry::active_count(), 0);
+
+ let state = CursorBridgeState::new(
+ "session-test".into(),
+ "msg-1".into(),
+ "cursor-test".into(),
+ None,
+ Box::new(|| "id".into()),
+ );
+ BridgeRegistry::insert(state);
+ assert_eq!(BridgeRegistry::active_count(), 1);
+ assert!(BridgeRegistry::get("session-test").is_some());
+
+ let state = BridgeRegistry::take("session-test");
+ assert!(state.is_some());
+ assert_eq!(BridgeRegistry::active_count(), 0);
+ }
+
+ #[test]
+ fn bridge_registry_set_and_get_pending_tool() {
+ let _lock = REGISTRY_LOCK.lock().unwrap();
+ BridgeRegistry::clear();
+ let state = CursorBridgeState::new(
+ "session-pt".into(),
+ "msg-1".into(),
+ "cursor-test".into(),
+ None,
+ Box::new(|| "id".into()),
+ );
+ BridgeRegistry::insert(state);
+
+ let tool = PendingCursorTool::Read {
+ tool_use_id: "call_1".into(),
+ path: "/tmp/a".into(),
+ };
+ BridgeRegistry::set_pending_tool("session-pt", tool);
+
+ let retrieved = BridgeRegistry::pending_tool("session-pt");
+ assert!(retrieved.is_some());
+ assert_eq!(retrieved.unwrap().name(), "Read");
+
+ BridgeRegistry::clear();
+ }
+
+ // -----------------------------------------------------------------------
+ // render_tool_result_content tests
+ // -----------------------------------------------------------------------
+
+ #[test]
+ fn renders_string_content() {
+ let result = serde_json::json!({
+ "type": "tool_result",
+ "content": "plain string"
+ });
+ assert_eq!(render_tool_result_content(&result), "plain string");
+ }
+
+ #[test]
+ fn renders_array_content() {
+ let result = serde_json::json!({
+ "type": "tool_result",
+ "content": [
+ {"type": "text", "text": "part one"},
+ {"type": "text", "text": "part two"}
+ ]
+ });
+ let rendered = render_tool_result_content(&result);
+ assert!(rendered.contains("part one"));
+ assert!(rendered.contains("part two"));
+ }
+
+ #[test]
+ fn renders_mixed_content_types() {
+ let result = serde_json::json!({
+ "type": "tool_result",
+ "content": [
+ {"type": "text", "text": "text result"},
+ {"type": "image", "source": {"type": "base64", "data": "AAAA"}}
+ ]
+ });
+ let rendered = render_tool_result_content(&result);
+ assert!(rendered.contains("text result"));
+ assert!(rendered.contains("[image result omitted]"));
+ }
+
+ #[test]
+ fn render_empty_tool_result() {
+ let result = serde_json::json!({"type": "tool_result"});
+ assert_eq!(render_tool_result_content(&result), "");
+ }
+
+ #[test]
+ fn detects_error_from_tool_result() {
+ let result = serde_json::json!({"type": "tool_result", "is_error": true});
+ assert!(tool_result_is_error(&result));
+
+ let result = serde_json::json!({"type": "tool_result", "is_error": false});
+ assert!(!tool_result_is_error(&result));
+
+ let result = serde_json::json!({"type": "tool_result"});
+ assert!(!tool_result_is_error(&result));
+ }
+}
diff --git a/src/providers/cursor/tool_use_xml.rs b/src/providers/cursor/tool_use_xml.rs
new file mode 100644
index 0000000..ade797a
--- /dev/null
+++ b/src/providers/cursor/tool_use_xml.rs
@@ -0,0 +1,518 @@
+//! XML tool-use recovery parser.
+//!
+//! Recovers `<tool_use id="..." name="...">{"json"}</tool_use>` from text delta
+//! chunks that arrive incrementally from the upstream. Produces structured
+//! `RecoveredCursorEvent` values for the bridge to emit as Anthropic tool_use
+//! content blocks.
+
+use std::collections::BTreeSet;
+use std::fmt;
+
+/// An event recovered from a text delta chunk.
+#[derive(Debug, Clone, PartialEq)]
+pub enum RecoveredCursorEvent {
+ Text(String),
+ ToolUse(RecoveredCursorToolUse),
+}
+
+/// A recovered `<tool_use>` XML element.
+#[derive(Debug, Clone, PartialEq)]
+pub struct RecoveredCursorToolUse {
+ /// Injected unique identifier (generated by the id factory, not from XML).
+ pub id: String,
+ /// The `id` attribute from the XML element, if present.
+ pub original_id: Option<String>,
+ /// The `name` attribute from the XML element.
+ pub name: String,
+ /// The parsed JSON input object.
+ pub input: serde_json::Map<String, serde_json::Value>,
+}
+
+/// Parser that incrementally recovers `<tool_use>` XML elements from text
+/// delta chunks.
+pub struct CursorToolUseXmlParser {
+ buffer: String,
+ recovered_tool_use: bool,
+ allowed_tool_names: Option<BTreeSet<String>>,
+ id_factory: Box<dyn FnMut() -> String + Send>,
+}
+
+impl fmt::Debug for CursorToolUseXmlParser {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("CursorToolUseXmlParser")
+ .field("buffer", &self.buffer)
+ .field("recovered_tool_use", &self.recovered_tool_use)
+ .field("allowed_tool_names", &self.allowed_tool_names)
+ .field("id_factory", &"<fn>")
+ .finish()
+ }
+}
+
+impl CursorToolUseXmlParser {
+ /// Create a parser with the default UUID-based id factory.
+ pub fn new(allowed_tool_names: Option<BTreeSet<String>>) -> Self {
+ Self::new_with_id_factory(allowed_tool_names, default_id_factory())
+ }
+
+ /// Create a parser with a custom id factory for deterministic tests.
+ pub fn new_with_id_factory(
+ allowed_tool_names: Option<BTreeSet<String>>,
+ id_factory: impl FnMut() -> String + Send + 'static,
+ ) -> Self {
+ Self {
+ buffer: String::new(),
+ recovered_tool_use: false,
+ allowed_tool_names,
+ id_factory: Box::new(id_factory),
+ }
+ }
+
+ /// Whether any tool_use has been recovered so far.
+ pub fn saw_tool_use(&self) -> bool {
+ self.recovered_tool_use
+ }
+
+ /// Push a new text delta chunk and drain any complete events.
+ pub fn push(&mut self, text: &str) -> Vec<RecoveredCursorEvent> {
+ self.buffer.push_str(text);
+ self.drain(false)
+ }
+
+ /// Flush any remaining buffered text, yielding any leftover events.
+ pub fn flush(&mut self) -> Vec<RecoveredCursorEvent> {
+ self.drain(true)
+ }
+
+ fn drain(&mut self, flush: bool) -> Vec<RecoveredCursorEvent> {
+ let mut events: Vec<RecoveredCursorEvent> = Vec::new();
+
+ loop {
+ if self.buffer.is_empty() {
+ break;
+ }
+
+ // Drop redundant close tags that can appear after recovery.
+ if self.drop_redundant_close_tag() {
+ continue;
+ }
+
+ // Look for the start of a <tool_use tag.
+ let start = self.buffer.find("<tool_use");
+ if start.is_none() {
+ // No tag start found: hold back a prefix of the buffer that
+ // could be a partial <tool_use marker, unless we are flushing.
+ let hold = if flush {
+ 0
+ } else {
+ tool_use_prefix_suffix_length(&self.buffer)
+ };
+ let end = self.buffer.len().saturating_sub(hold);
+ let text = self.buffer[..end].to_string();
+ if !text.is_empty() {
+ self.push_text(&mut events, &text);
+ }
+ self.buffer = self.buffer[end..].to_string();
+ break;
+ }
+
+ let start = start.unwrap();
+
+ // Emit any text before the tag.
+ if start > 0 {
+ self.push_text(&mut events, &self.buffer[..start]);
+ self.buffer = self.buffer[start..].to_string();
+ continue;
+ }
+
+ // Look for the close tag.
+ let close_start = self.buffer.find("</tool_use>");
+ if close_start.is_none() {
+ // No close tag yet; if we are flushing, emit the whole buffer
+ // as text. Otherwise hold and wait for more data.
+ if flush {
+ self.push_text(&mut events, &self.buffer);
+ self.buffer.clear();
+ }
+ break;
+ }
+
+ let close_start = close_start.unwrap();
+ let close_end = close_start + "</tool_use>".len();
+ let raw = self.buffer[..close_end].to_string();
+
+ // Try to parse a complete <tool_use...>...</tool_use> element.
+ if let Some(parsed) = self.parse_tool_use(&raw) {
+ self.recovered_tool_use = true;
+ events.push(RecoveredCursorEvent::ToolUse(parsed));
+ } else {
+ self.push_text(&mut events, &raw);
+ }
+
+ self.buffer = self.buffer[close_end..].to_string();
+ }
+
+ events
+ }
+
+ /// Try to parse a complete `<tool_use ...>...</tool_use>` element.
+ fn parse_tool_use(&mut self, raw: &str) -> Option<RecoveredCursorToolUse> {
+ let re = regex_lite::Regex::new(r"^<tool_use\b([^>]*)>([\s\S]*?)</tool_use>$").ok()?;
+ let caps = re.captures(raw)?;
+ let attrs_str = caps.get(1).map(|m| m.as_str()).unwrap_or("");
+ let body = caps.get(2).map(|m| m.as_str()).unwrap_or("");
+
+ let attrs = parse_xml_attributes(attrs_str);
+ let name = attrs.get("name")?;
+ let original_id = attrs.get("id").cloned();
+ let original_id = if original_id.as_deref() == Some("") {
+ None
+ } else {
+ original_id
+ };
+
+ // Check allowed tool names.
+ if let Some(ref allowed) = self.allowed_tool_names {
+ if !allowed.contains(name) {
+ return None;
+ }
+ }
+
+ // Parse the JSON body.
+ let trimmed = body.trim();
+ let input_value: serde_json::Value = if trimmed.is_empty() {
+ serde_json::Value::Object(serde_json::Map::new())
+ } else {
+ match serde_json::from_str(trimmed) {
+ Ok(v) => v,
+ Err(_) => return None,
+ }
+ };
+
+ let input = match input_value {
+ serde_json::Value::Object(map) => map,
+ _ => return None,
+ };
+
+ let id = (self.id_factory)();
+
+ Some(RecoveredCursorToolUse {
+ id,
+ original_id,
+ name: name.clone(),
+ input,
+ })
+ }
+
+ /// Drop a redundant `</tool_use>` close tag that follows an already-
+ /// recovered tool_use (the XML stream may contain duplicate close tags
+ /// after recovery).
+ fn drop_redundant_close_tag(&mut self) -> bool {
+ if !self.recovered_tool_use {
+ return false;
+ }
+ let trimmed_start = self.buffer.len() - self.buffer.trim_start().len();
+ let slice = &self.buffer[trimmed_start..];
+ if let Some(rest) = slice.strip_prefix("</tool_use>") {
+ let prefix = &self.buffer[..trimmed_start];
+ self.buffer = format!("{prefix}{rest}");
+ true
+ } else if let Some(rest) = slice.strip_prefix("</tool_use") {
+ let prefix = &self.buffer[..trimmed_start];
+ self.buffer = format!("{prefix}{rest}");
+ true
+ } else {
+ false
+ }
+ }
+
+ /// Push text into events, filtering empty text and trailing whitespace
+ /// after a recovered tool_use.
+ fn push_text(&self, events: &mut Vec<RecoveredCursorEvent>, text: &str) {
+ if text.is_empty() {
+ return;
+ }
+ if self.recovered_tool_use && text.trim().is_empty() {
+ return;
+ }
+ events.push(RecoveredCursorEvent::Text(text.to_string()));
+ }
+}
+
+fn default_id_factory() -> Box<dyn FnMut() -> String + Send> {
+ Box::new(|| {
+ let id = uuid::Uuid::new_v4().to_string().replace('-', "");
+ format!("call_cursor_{id}")
+ })
+}
+
+// ---------------------------------------------------------------------------
+// XML attribute parsing
+// ---------------------------------------------------------------------------
+
+fn parse_xml_attributes(source: &str) -> std::collections::HashMap<String, String> {
+ let mut attrs = std::collections::HashMap::new();
+ let re = regex_lite::Regex::new(r#"([A-Za-z_][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')"#).ok();
+ let re = match re {
+ Some(r) => r,
+ None => return attrs,
+ };
+ for cap in re.captures_iter(source) {
+ let key = cap.get(1).map(|m| m.as_str()).unwrap_or("");
+ let value = cap
+ .get(2)
+ .or_else(|| cap.get(3))
+ .map(|m| m.as_str())
+ .unwrap_or("");
+ if !key.is_empty() {
+ attrs.insert(key.to_string(), decode_xml_attribute(value));
+ }
+ }
+ attrs
+}
+
+fn decode_xml_attribute(value: &str) -> String {
+ value
+ .replace("&quot;", "\"")
+ .replace("&apos;", "'")
+ .replace("&lt;", "<")
+ .replace("&gt;", ">")
+ .replace("&amp;", "&")
+}
+
+/// Compute how many characters at the end of `value` could be a partial
+/// `<tool_use` marker. Returns a length in [0, "<tool_use".len() - 1].
+fn tool_use_prefix_suffix_length(value: &str) -> usize {
+ let marker = "<tool_use";
+ let max = marker.len().saturating_sub(1).min(value.len());
+ for len in (1..=max).rev() {
+ if value.ends_with(&marker[..len]) {
+ return len;
+ }
+ }
+ 0
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn test_id_factory() -> Box<dyn FnMut() -> String + Send> {
+ let mut counter = 0u64;
+ Box::new(move || {
+ counter += 1;
+ format!("call_cursor_test_{counter}")
+ })
+ }
+
+ #[test]
+ fn recovers_complete_tool_use_xml() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(
+ Some(["Read".to_string()].into_iter().collect()),
+ test_id_factory(),
+ );
+ let input = r#"before <tool_use id="x" name="Read">{"file_path":"a"}</tool_use> after"#;
+ let events = parser.push(input);
+ assert_eq!(events.len(), 3);
+ assert_eq!(events[0], RecoveredCursorEvent::Text("before ".into()));
+ assert!(matches!(&events[1], RecoveredCursorEvent::ToolUse(tool) if tool.name == "Read"));
+ assert_eq!(events[2], RecoveredCursorEvent::Text(" after".into()));
+ assert!(parser.saw_tool_use());
+ assert!(parser.flush().is_empty());
+ }
+
+ #[test]
+ fn recovers_split_tool_use_xml() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(
+ Some(["Read".to_string()].into_iter().collect()),
+ test_id_factory(),
+ );
+ assert_eq!(
+ parser.push("before <tool_"),
+ vec![RecoveredCursorEvent::Text("before ".into())]
+ );
+ let events = parser.push(r#"use id="x" name="Read">{"file_path":"a"}</tool_use> after"#);
+ assert!(matches!(&events[0], RecoveredCursorEvent::ToolUse(tool) if tool.name == "Read"));
+ assert_eq!(events[1], RecoveredCursorEvent::Text(" after".into()));
+ assert!(parser.flush().is_empty());
+ }
+
+ #[test]
+ fn recovers_tool_use_without_original_id() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(
+ Some(["Read".to_string()].into_iter().collect()),
+ test_id_factory(),
+ );
+ let events = parser.push(r#"<tool_use name="Read">{"x":1}</tool_use>"#);
+ assert_eq!(events.len(), 1);
+ if let RecoveredCursorEvent::ToolUse(tool) = &events[0] {
+ assert_eq!(tool.original_id, None);
+ assert_eq!(tool.name, "Read");
+ assert_eq!(tool.input.get("x").and_then(|v| v.as_i64()), Some(1));
+ } else {
+ panic!("expected ToolUse");
+ }
+ }
+
+ #[test]
+ fn recovers_tool_use_with_original_id() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(
+ Some(["Write".to_string()].into_iter().collect()),
+ test_id_factory(),
+ );
+ let events = parser.push(
+ r#"<tool_use id="orig-1" name="Write">{"file_path":"b","content":"hi"}</tool_use>"#,
+ );
+ assert_eq!(events.len(), 1);
+ if let RecoveredCursorEvent::ToolUse(tool) = &events[0] {
+ assert_eq!(tool.original_id.as_deref(), Some("orig-1"));
+ assert_eq!(tool.name, "Write");
+ } else {
+ panic!("expected ToolUse");
+ }
+ }
+
+ #[test]
+ fn filters_disallowed_tool_names() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(
+ Some(["Read".to_string()].into_iter().collect()),
+ test_id_factory(),
+ );
+ // Bash is not in allowed set, so the text is emitted as-is.
+ let events = parser.push(r#"<tool_use id="x" name="Bash">{"command":"pwd"}</tool_use>"#);
+ assert_eq!(events.len(), 1);
+ assert!(matches!(&events[0], RecoveredCursorEvent::Text(t)
+ if t.contains("Bash")));
+ assert!(!parser.saw_tool_use());
+ }
+
+ #[test]
+ fn invalid_json_fallback_to_text() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(
+ Some(["Read".to_string()].into_iter().collect()),
+ test_id_factory(),
+ );
+ let events = parser.push(r#"<tool_use id="x" name="Read">{invalid}</tool_use>"#);
+ assert_eq!(events.len(), 1);
+ assert!(matches!(&events[0], RecoveredCursorEvent::Text(_)));
+ assert!(!parser.saw_tool_use());
+ }
+
+ #[test]
+ fn redundant_close_tag_after_recovery() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(
+ Some(["Read".to_string()].into_iter().collect()),
+ test_id_factory(),
+ );
+ // First recover a tool_use.
+ let events = parser.push(r#"<tool_use name="Read">{}</tool_use>"#);
+ assert_eq!(events.len(), 1);
+ assert!(parser.saw_tool_use());
+
+ // Push a redundant close tag (common in streaming XML).
+ let events = parser.push("</tool_use>");
+ // Should be silently dropped, no text events.
+ assert!(events.is_empty());
+ }
+
+ #[test]
+ fn flush_returns_remaining_text() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(
+ Some(["Read".to_string()].into_iter().collect()),
+ test_id_factory(),
+ );
+ // Push an incomplete tag.
+ let events = parser.push("some text <tool_use name=\"Read\">{\"a\":1}");
+ // No close tag yet, so only text before partial tag should emit.
+ // But the parser holds back the partial prefix, so "some text " emits.
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0], RecoveredCursorEvent::Text("some text ".into()));
+
+ // Flush should emit the remaining buffer as text since the tag
+ // could not be completed.
+ let events = parser.flush();
+ assert!(!events.is_empty());
+ assert!(matches!(&events[0], RecoveredCursorEvent::Text(t)
+ if t.contains("<tool_use") || t.contains("name")));
+ }
+
+ #[test]
+ fn empty_push_does_nothing() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(None, test_id_factory());
+ let events = parser.push("");
+ assert!(events.is_empty());
+ assert!(parser.flush().is_empty());
+ }
+
+ #[test]
+ fn text_only_chunks() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(None, test_id_factory());
+ assert_eq!(
+ parser.push("hello world"),
+ vec![RecoveredCursorEvent::Text("hello world".into())]
+ );
+ assert!(parser.flush().is_empty());
+ }
+
+ #[test]
+ fn multiple_tool_uses_in_one_push() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(
+ Some(
+ ["Read".to_string(), "Write".to_string()]
+ .into_iter()
+ .collect(),
+ ),
+ test_id_factory(),
+ );
+ let events = parser.push(
+ r#"<tool_use name="Read">{"file_path":"a"}</tool_use><tool_use name="Write">{"file_path":"b","content":"c"}</tool_use>"#,
+ );
+ assert_eq!(events.len(), 2);
+ assert!(matches!(&events[0], RecoveredCursorEvent::ToolUse(t) if t.name == "Read"));
+ assert!(matches!(&events[1], RecoveredCursorEvent::ToolUse(t) if t.name == "Write"));
+ }
+
+ #[test]
+ fn parse_xml_attributes_extracts_name_and_id() {
+ let attrs = parse_xml_attributes(r#"id="abc" name="Read""#);
+ assert_eq!(attrs.get("name").map(|s| s.as_str()), Some("Read"));
+ assert_eq!(attrs.get("id").map(|s| s.as_str()), Some("abc"));
+ }
+
+ #[test]
+ fn parse_xml_handles_single_quotes() {
+ let attrs = parse_xml_attributes(r#"name='Read'"#);
+ assert_eq!(attrs.get("name").map(|s| s.as_str()), Some("Read"));
+ }
+
+ #[test]
+ fn parse_xml_decodes_entities() {
+ let attrs = parse_xml_attributes(r#"name="Read &amp; Write""#);
+ assert_eq!(attrs.get("name").map(|s| s.as_str()), Some("Read & Write"));
+ }
+
+ #[test]
+ fn tool_use_prefix_suffix_identifies_partial_tag() {
+ assert_eq!(tool_use_prefix_suffix_length("<tool_"), 6);
+ assert_eq!(tool_use_prefix_suffix_length("<tool_us"), 8);
+ assert_eq!(tool_use_prefix_suffix_length("hello <tool_"), 6);
+ assert_eq!(tool_use_prefix_suffix_length("hello"), 0);
+ assert_eq!(tool_use_prefix_suffix_length("<"), 1); // "<" is a prefix of "<tool_use"
+ }
+
+ #[test]
+ fn saw_tool_use_starts_false() {
+ let parser = CursorToolUseXmlParser::new_with_id_factory(None, test_id_factory());
+ assert!(!parser.saw_tool_use());
+ }
+
+ #[test]
+ fn empty_input_after_flush() {
+ let mut parser = CursorToolUseXmlParser::new_with_id_factory(None, test_id_factory());
+ let events = parser.push("hello");
+ assert_eq!(events.len(), 1);
+ // Flush with no partial tag should be empty.
+ assert!(parser.flush().is_empty());
+ // Another flush should also be empty.
+ assert!(parser.flush().is_empty());
+ }
+}
diff --git a/tests/cursor_native.rs b/tests/cursor_native.rs
index de5c391..8074be9 100644
--- a/tests/cursor_native.rs
+++ b/tests/cursor_native.rs
@@ -699,6 +699,467 @@ async fn cursor_provider_handle_messages_returns_anthropic_json() {
}
}
+// ---------------------------------------------------------------------------
+// Cursor tool bridge integration tests
+// ---------------------------------------------------------------------------
+
+#[test]
+fn bridge_start_pauses_on_tool_use_xml() {
+ use claude_code_proxy::providers::cursor::response::*;
+ use claude_code_proxy::providers::cursor::tool_bridge::*;
+
+ // Create upstream events with a text delta containing XML tool_use
+ let events = vec![
+ CursorStreamEvent::TextDelta {
+ text: "before ".to_string(),
+ },
+ CursorStreamEvent::TextDelta {
+ text: r#"<tool_use id="x" name="Read">{"file_path":"/tmp/a"}</tool_use>"#.to_string(),
+ },
+ CursorStreamEvent::TextDelta {
+ text: " after".to_string(),
+ },
+ CursorStreamEvent::Usage {
+ input_tokens: 10,
+ output_tokens: 5,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ },
+ CursorStreamEvent::End,
+ ];
+
+ let allowed: std::collections::BTreeSet<String> =
+ ["Read".to_string(), "Write".to_string(), "Bash".to_string()]
+ .into_iter()
+ .collect();
+
+ let mut counter = 0u64;
+ let id_factory = Box::new(move || {
+ counter += 1;
+ format!("call_cursor_test_{counter}")
+ });
+
+ let (sse, paused) = start_cursor_tool_bridge(
+ "msg_1",
+ "cursor-test",
+ "session-bridge-1",
+ &events,
+ Some(allowed),
+ id_factory,
+ );
+
+ assert!(paused, "bridge should pause on tool_use");
+
+ let sse_str = String::from_utf8_lossy(&sse);
+ let parsed = parse_sse_events(&sse_str);
+
+ let event_names: Vec<&str> = parsed.iter().map(|(n, _)| n.as_str()).collect();
+ assert!(
+ event_names.contains(&"content_block_start"),
+ "expected content_block_start for tool_use"
+ );
+ assert!(
+ event_names.contains(&"message_stop"),
+ "expected message_stop"
+ );
+
+ let msg_delta = parsed
+ .iter()
+ .find(|(n, _)| n == "message_delta")
+ .map(|(_, d)| d.clone());
+ assert!(msg_delta.is_some(), "expected message_delta");
+ assert_eq!(
+ msg_delta.unwrap()["delta"]["stop_reason"],
+ "tool_use",
+ "stop_reason should be tool_use"
+ );
+
+ // Clean up
+ BridgeRegistry::remove("session-bridge-1");
+}
+
+#[test]
+fn bridge_start_passes_through_without_tool_use() {
+ use claude_code_proxy::providers::cursor::response::*;
+ use claude_code_proxy::providers::cursor::tool_bridge::*;
+
+ let events = vec![
+ CursorStreamEvent::TextDelta {
+ text: "hello world".to_string(),
+ },
+ CursorStreamEvent::Usage {
+ input_tokens: 5,
+ output_tokens: 1,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ },
+ CursorStreamEvent::End,
+ ];
+
+ let (sse, paused) = start_cursor_tool_bridge(
+ "msg_2",
+ "cursor-test",
+ "session-bridge-2",
+ &events,
+ None,
+ Box::new(|| "id".into()),
+ );
+
+ assert!(!paused, "bridge should NOT pause without tool_use");
+
+ let sse_str = String::from_utf8_lossy(&sse);
+ let parsed = parse_sse_events(&sse_str);
+ let event_names: Vec<&str> = parsed.iter().map(|(n, _)| n.as_str()).collect();
+
+ assert!(event_names.contains(&"message_start"));
+ assert!(event_names.contains(&"content_block_delta"));
+ assert!(event_names.contains(&"message_delta"));
+ assert!(event_names.contains(&"message_stop"));
+
+ // Verify stop_reason is end_turn
+ let msg_delta = parsed
+ .iter()
+ .find(|(n, _)| n == "message_delta")
+ .map(|(_, d)| d.clone());
+ assert_eq!(
+ msg_delta.unwrap()["delta"]["stop_reason"],
+ "end_turn",
+ "stop_reason should be end_turn without tool_use"
+ );
+}
+
+#[test]
+fn bridge_start_creates_pending_tool_in_registry() {
+ use claude_code_proxy::providers::cursor::response::*;
+ use claude_code_proxy::providers::cursor::tool_bridge::*;
+
+ // Clean state
+ BridgeRegistry::clear();
+
+ let events = vec![CursorStreamEvent::TextDelta {
+ text: r#"<tool_use name="Read">{"file_path":"/tmp/test"}</tool_use>"#.to_string(),
+ }];
+
+ let allowed: std::collections::BTreeSet<String> = ["Read".to_string()].into_iter().collect();
+
+ let (_, paused) = start_cursor_tool_bridge(
+ "msg_3",
+ "cursor-test",
+ "session-bridge-pt",
+ &events,
+ Some(allowed),
+ Box::new(|| "call_test".into()),
+ );
+
+ assert!(paused);
+
+ let pending = BridgeRegistry::pending_tool("session-bridge-pt");
+ assert!(pending.is_some(), "pending tool should be stored");
+ assert_eq!(pending.unwrap().name(), "Read");
+
+ BridgeRegistry::remove("session-bridge-pt");
+}
+
+#[test]
+fn bridge_resume_continues_after_tool_use_pause() {
+ use claude_code_proxy::providers::cursor::response::*;
+ use claude_code_proxy::providers::cursor::tool_bridge::*;
+
+ BridgeRegistry::clear();
+
+ // Events: tool_use in the middle, text after
+ let events = vec![
+ CursorStreamEvent::TextDelta {
+ text: "before ".to_string(),
+ },
+ CursorStreamEvent::TextDelta {
+ text: r#"<tool_use name="Read">{"file_path":"/tmp/a"}</tool_use>"#.to_string(),
+ },
+ CursorStreamEvent::TextDelta {
+ text: " continued".to_string(),
+ },
+ CursorStreamEvent::Usage {
+ input_tokens: 10,
+ output_tokens: 5,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ },
+ CursorStreamEvent::End,
+ ];
+
+ let allowed: std::collections::BTreeSet<String> = ["Read".to_string()].into_iter().collect();
+
+ let mut counter = 0u64;
+ let id_factory = Box::new(move || {
+ counter += 1;
+ format!("call_cursor_test_{counter}")
+ });
+
+ let (_first_sse, paused) = start_cursor_tool_bridge(
+ "msg_first",
+ "cursor-test",
+ "session-resume-1",
+ &events,
+ Some(allowed),
+ id_factory,
+ );
+ assert!(paused);
+
+ let body: claude_code_proxy::MessagesRequest =
+ serde_json::from_value(serde_json::json!({
+ "model": "cursor-test",
+ "messages": [
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_cursor_test_1", "content": "result text"}]}
+ ]
+ }))
+ .unwrap();
+
+ let pending =
+ BridgeRegistry::pending_tool("session-resume-1").expect("should have pending tool");
+ assert_eq!(pending.tool_use_id(), "call_cursor_test_1");
+
+ let result = find_tool_result(&body, pending.tool_use_id()).expect("should find tool result");
+
+ let (result_msgs, second_sse) = resume_cursor_tool_bridge(
+ "session-resume-1",
+ "msg_second",
+ "cursor-test",
+ result,
+ &pending,
+ );
+
+ assert!(!result_msgs.is_empty(), "should have result messages");
+
+ let sse_str = String::from_utf8_lossy(&second_sse);
+ let parsed = parse_sse_events(&sse_str);
+ let event_names: Vec<&str> = parsed.iter().map(|(n, _)| n.as_str()).collect();
+
+ assert!(
+ event_names.contains(&"message_start"),
+ "resume should have message_start in {event_names:?}"
+ );
+ assert!(
+ event_names.contains(&"message_stop"),
+ "resume should have message_stop in {event_names:?}"
+ );
+
+ let text_deltas: Vec<&str> = parsed
+ .iter()
+ .filter_map(|(n, d)| {
+ if n == "content_block_delta" {
+ d["delta"]["text"].as_str()
+ } else {
+ None
+ }
+ })
+ .collect();
+ let combined = text_deltas.join("");
+ assert!(
+ combined.contains("continued"),
+ "resume should include remaining text deltas"
+ );
+
+ BridgeRegistry::remove("session-resume-1");
+}
+
+#[test]
+fn bridge_rejects_tool_not_in_allowed_list() {
+ use claude_code_proxy::providers::cursor::response::*;
+ use claude_code_proxy::providers::cursor::tool_bridge::*;
+
+ BridgeRegistry::clear();
+
+ let events = vec![CursorStreamEvent::TextDelta {
+ text: r#"<tool_use name="Bash">{"command":"pwd"}</tool_use>"#.to_string(),
+ }];
+
+ let allowed: std::collections::BTreeSet<String> = ["Read".to_string()].into_iter().collect();
+
+ let (sse, paused) = start_cursor_tool_bridge(
+ "msg_filter",
+ "cursor-test",
+ "session-filter-1",
+ &events,
+ Some(allowed),
+ Box::new(|| "id".into()),
+ );
+
+ assert!(!paused, "should NOT pause for disallowed tool");
+
+ let sse_str = String::from_utf8_lossy(&sse);
+ let parsed = parse_sse_events(&sse_str);
+ let _event_names: Vec<&str> = parsed.iter().map(|(n, _)| n.as_str()).collect();
+
+ let msg_delta = parsed
+ .iter()
+ .find(|(n, _)| n == "message_delta")
+ .map(|(_, d)| d.clone());
+ assert_eq!(
+ msg_delta.unwrap()["delta"]["stop_reason"],
+ "end_turn",
+ "disallowed tool should not trigger tool_use"
+ );
+
+ BridgeRegistry::remove("session-filter-1");
+}
+
+#[test]
+fn bridge_result_messages_have_correct_read_shape() {
+ use claude_code_proxy::providers::cursor::tool_bridge::*;
+
+ let exec = CursorExec {
+ id: Some(42),
+ exec_id: None,
+ args: serde_json::json!({"file_path": "/tmp/readme.txt"}),
+ };
+ let result = CursorNativeToolResult {
+ content: "file contents here".into(),
+ is_error: false,
+ };
+
+ let msg = build_read_result_from_native(&exec, &result);
+ let msg_obj = msg.as_object().unwrap();
+
+ assert_eq!(msg_obj.get("id").and_then(|v| v.as_i64()), Some(42));
+
+ let read_result = msg_obj.get("readResult").unwrap();
+ assert!(read_result.get("success").is_some());
+ let success = read_result.get("success").unwrap();
+ assert_eq!(
+ success.get("path").and_then(|v| v.as_str()),
+ Some("/tmp/readme.txt")
+ );
+ assert_eq!(
+ success.get("content").and_then(|v| v.as_str()),
+ Some("file contents here")
+ );
+ assert_eq!(success.get("totalLines").and_then(|v| v.as_i64()), Some(1));
+}
+
+#[test]
+fn bridge_result_messages_have_correct_write_shape() {
+ use claude_code_proxy::providers::cursor::tool_bridge::*;
+
+ let exec = CursorExec {
+ id: Some(99),
+ exec_id: Some("exec-write-1".into()),
+ args: serde_json::json!({"file_path": "/tmp/writeme.txt", "content": "data"}),
+ };
+
+ let result = CursorNativeToolResult {
+ content: "written".into(),
+ is_error: false,
+ };
+ let msg = build_write_result_from_native(&exec, &result);
+ let msg_obj = msg.as_object().unwrap();
+ assert_eq!(
+ msg_obj.get("execId").and_then(|v| v.as_str()),
+ Some("exec-write-1")
+ );
+ let write_result = msg_obj.get("writeResult").unwrap();
+ let success = write_result.get("success").unwrap();
+ assert_eq!(
+ success.get("path").and_then(|v| v.as_str()),
+ Some("/tmp/writeme.txt")
+ );
+ assert!(success.get("linesCreated").is_some());
+ assert!(success.get("fileSize").is_some());
+
+ let error_result = CursorNativeToolResult {
+ content: "permission denied".into(),
+ is_error: true,
+ };
+ let err_msg = build_write_result_from_native(&exec, &error_result);
+ let err_obj = err_msg.as_object().unwrap();
+ let write_result = err_obj.get("writeResult").unwrap();
+ let error = write_result.get("error").unwrap();
+ assert_eq!(
+ error.get("path").and_then(|v| v.as_str()),
+ Some("/tmp/writeme.txt")
+ );
+ assert!(
+ error
+ .get("error")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .contains("permission")
+ );
+}
+
+#[test]
+fn bridge_shell_stream_result_has_correct_shape() {
+ use claude_code_proxy::providers::cursor::tool_bridge::*;
+
+ let exec = CursorExec {
+ id: Some(7),
+ exec_id: Some("exec-shell".into()),
+ args: serde_json::json!({}),
+ };
+
+ let result = CursorNativeToolResult {
+ content: "stdout output".into(),
+ is_error: false,
+ };
+
+ let messages = build_shell_stream_result(
+ &exec,
+ &result,
+ std::time::Duration::from_millis(150),
+ "/home/user",
+ );
+
+ assert_eq!(messages.len(), 4, "start + stdout + exit + close");
+
+ assert!(
+ messages[0]
+ .get("shellStream")
+ .and_then(|s| s.get("start"))
+ .is_some()
+ );
+
+ assert_eq!(
+ messages[1]["shellStream"]["stdout"]["data"],
+ "stdout output"
+ );
+
+ assert_eq!(messages[2]["shellStream"]["exit"]["code"], 0);
+ assert_eq!(messages[2]["shellStream"]["exit"]["cwd"], "/home/user");
+
+ assert_eq!(
+ messages[3]["execClientControlMessage"]["streamClose"]["id"],
+ 7
+ );
+}
+
+// ---------------------------------------------------------------------------
+// No TypeScript sidecar
+// ---------------------------------------------------------------------------
+
+#[test]
+fn cursor_provider_has_no_typescript_sidecar() {
+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/providers/cursor");
+ let mut stack = vec![root.clone()];
+ while let Some(dir) = stack.pop() {
+ match std::fs::read_dir(&dir) {
+ Ok(entries) => {
+ for entry in entries {
+ let path = entry.unwrap().path();
+ if path.is_dir() {
+ stack.push(path);
+ continue;
+ }
+ let ext = path.extension().and_then(|e| e.to_str());
+ assert_ne!(ext, Some("ts"), "TypeScript file found at {:?}", path);
+ }
+ }
+ Err(_) => {
+ // Directory may not exist (e.g., if cursor provider was removed)
+ return;
+ }
+ }
+ }
+}
+
// ---------------------------------------------------------------------------
// SSE parser helper (mirrors sse.rs internal helper for cross-module access)
// ---------------------------------------------------------------------------