Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
refactor(cursor): remove debug artifacts after tool-result fix
Rafael Calleja70008e67e46e
diff --git a/bug_index.md b/bug_index.mddeleted file mode 100644index 3200389d1d..0000000000--- a/bug_index.md+++ /dev/null@@ -1,119 +0,0 @@-# Bug: Wire Type 4 Protobuf Error on Cursor API--## Symptom--- First request to Cursor (3 msgs, 34 tools) → WORKS-- Second request (5 msgs, 34 tools, ~140KB) → FAILS with "wire type 4" protobuf parse error-- Error comes FROM Cursor's server rejecting our encoded protobuf request--## What "wire type 4" means--- Valid protobuf wire types: 0=VARINT, 1=FIXED64, 2=LEN, 5=FIXED32-- Wire type 4 = "end group" (deprecated, never valid in modern protobuf)-- This means **corrupted protobuf data** — Cursor server reads data bytes as tag bytes-- Root cause: a LENGTH-DELIMITED field has wrong length prefix, causing parse misalignment--## Data Flow--```-Client (Claude format, 5 msgs)- → chatCore.translateRequest()- → claude-to-openai.ts (claudeToOpenAIRequest)- → openai-to-cursor.ts (buildCursorRequest)- → cursor.ts transformRequest()- → cursorProtobuf.ts generateCursorBody() → protobuf binary- → HTTP to Cursor API → "wire type 4" error-```--## Key Files--- `open-sse/translator/request/claude-to-openai.ts` — Claude→OpenAI message conversion-- `open-sse/translator/request/openai-to-cursor.ts` — OpenAI→Cursor message conversion-- `open-sse/utils/cursorProtobuf.ts` — Protobuf binary encoder-- `open-sse/executors/cursor.ts` — Cursor executor (HTTP + protobuf framing)--## Investigation Done (Session 1)--1. **Content type is NOT the issue** — `encodeField()` handles undefined/null/array gracefully (→ empty `0a 00`)-2. **openai-to-cursor always normalizes content to string** (lines 77-87)-3. **tool_calls on assistant msgs are silently ignored** by protobuf encoder (no encoding logic for them)-4. **Debug logging was added** to `encodeRequest()` and `encodeMessage()` to trace message shapes-5. **All basic varint/field encoding tests pass** — no corruption in primitives--## Investigation Done (Session 2 — current)--6. **Round-trip test PASSES** — a synthetic 4-msg + 34-tools + tool_results request encodes and decodes back perfectly-7. **Large payload test PASSES** — 100KB tool result content, frame length matches perfectly (106,810 bytes)-8. **Varint encoding tests PASS** — values up to 268M encode/decode correctly-9. **Null bytes in content work** — no corruption-10. **Missing content on assistant msgs works** — produces valid empty field--## CRITICAL CONCLUSION--The encoding logic itself is **correct for all tested patterns**. The bug is NOT in the encoder primitives.-The issue MUST be in one of:--### HIGH PRIORITY — What to investigate next--#### H1: The REAL production data has something we haven't tested--The user mentioned the log was already provided in a previous session. The 140,267 byte request-with 34 tools and 5 messages has specific data that triggers the bug. We need to:--- **Capture the exact translated messages** before protobuf encoding (add JSON.stringify dump)-- **Capture the hex dump** of the protobuf output-- **Send the hex dump to a protobuf decoder** to find where parsing breaks--#### H2: assistant message with tool_calls AND content=undefined--In openai-to-cursor.ts line 96-97, when assistant has tool_calls but empty content:--```js-const assistantMsg = { role: "assistant" }; // NO content property-if (content) {- assistantMsg.content = content;-} // content="" is falsy → skipped-```--Result: `msg.content` is `undefined`. In `encodeMessage`, this produces `encodeField(1, LEN, undefined)` → `0a 00`.-This is technically valid protobuf (empty string field), BUT Cursor's server might require the content field to be present as a non-empty string for assistant messages. The FIRST request (3 msgs) might not have an assistant message at all, while the SECOND (5 msgs) does.--**FIX TO TRY**: Always set `content: ""` on assistant messages in openai-to-cursor.ts.--#### H3: tool_calls being passed to protobuf encoder as stray properties--The Cursor message in the translated body has `{ role, content, tool_calls, tool_results }`.-The protobuf encoder only uses `content`, `role`, and `tool_results`. The `tool_calls` array-is silently ignored. BUT if Cursor's real protocol expects tool calls to be encoded differently-(maybe as part of the content or as a separate protobuf field), we might be sending incomplete data.--#### H4: Encoding `encodeVarint` with value from `>>>` unsigned shift on large numbers--`encodeVarint` uses `value >>>= 7` which treats value as unsigned 32-bit. If a tag or length-exceeds 2^31, the unsigned shift behavior could produce wrong bytes. However, tests show this-works correctly up to 268M, and our payloads are ~140KB, so this is unlikely.--## Recommended Fix (try first — LOW RISK)--In `openai-to-cursor.ts`, always ensure assistant messages have `content: ""`:--```js-// Line 96-99, change from:-const assistantMsg = { role: "assistant" };-if (content) {- assistantMsg.content = content;-}--// To:-const assistantMsg = { role: "assistant", content: content || "" };-```--## How to debug further--Add this to `cursor.ts` `transformRequest()` BEFORE `generateCursorBody()`:--```js-console.log("[CURSOR_DEBUG] Messages to encode:", JSON.stringify(messages, null, 2).slice(0, 2000));-```--Then reproduce the error and check logs for the exact message shapes.diff --git a/open-sse/executors/cursor.ts b/open-sse/executors/cursor.tsindex 4f3e619ec7..0e0c6672f9 100644--- a/open-sse/executors/cursor.ts+++ b/open-sse/executors/cursor.ts@@ -29,7 +29,6 @@ import {} from "../utils/cursorProtobuf.ts";import { estimateUsage } from "../utils/usageTracking.ts";import { FORMATS } from "../translator/formats.ts";-import { buildCursorRequest } from "../translator/request/openai-to-cursor.ts";import crypto from "crypto";import { v5 as uuidv5 } from "uuid";import zlib from "zlib";@@ -59,13 +58,18 @@ const COMPRESS_FLAG = {GZIP_BOTH: 0x03,};+const CURSOR_STREAM_DEBUG = process.env.CURSOR_STREAM_DEBUG === "1";+const debugLog = (...args: unknown[]) => {+ if (CURSOR_STREAM_DEBUG) console.log(...args);+};+function decompressPayload(payload, flags) {// Check if payload is JSON error (starts with {"error")if (payload.length > 10 && payload[0] === 0x7b && payload[1] === 0x22) {try {const text = payload.toString("utf-8");if (text.startsWith('{"error"')) {- console.log(`[DECOMPRESS] Detected JSON error, skipping decompression`);+ debugLog(`[DECOMPRESS] Detected JSON error, skipping decompression`);return payload;}} catch {}@@ -89,14 +93,14 @@ function decompressPayload(payload, flags) {try {return zlib.inflateRawSync(payload);} catch (rawErr) {- console.log(+ debugLog(`[DECOMPRESS ERROR] flags=${flags}, payloadSize=${payload.length}, gzip=${gzipErr.message}, deflate=${deflateErr.message}, raw=${rawErr.message}`);- console.log(+ debugLog(`[DECOMPRESS ERROR] First 50 bytes (hex):`,payload.slice(0, 50).toString("hex"));- console.log(+ debugLog(`[DECOMPRESS ERROR] First 50 bytes (utf8):`,payload.slice(0, 50)@@ -381,11 +385,11 @@ export class CursorExecutor extends BaseExecutor {const toolCallsMap = new Map(); // Track streaming tool calls by IDlet frameCount = 0;- console.log(`[CURSOR BUFFER] Total length: ${buffer.length} bytes`);+ debugLog(`[CURSOR BUFFER] Total length: ${buffer.length} bytes`);while (offset < buffer.length) {if (offset + 5 > buffer.length) {- console.log(+ debugLog(`[CURSOR BUFFER] Reached end, offset=${offset}, remaining=${buffer.length - offset}`);break;@@ -394,12 +398,12 @@ export class CursorExecutor extends BaseExecutor {const flags = buffer[offset];const length = buffer.readUInt32BE(offset + 1);- console.log(+ debugLog(`[CURSOR BUFFER] Frame ${frameCount + 1}: flags=0x${flags.toString(16).padStart(2, "0")}, length=${length}`);if (offset + 5 + length > buffer.length) {- console.log(+ debugLog(`[CURSOR BUFFER] Incomplete frame, offset=${offset}, length=${length}, buffer.length=${buffer.length}`);break;@@ -411,7 +415,7 @@ export class CursorExecutor extends BaseExecutor {payload = decompressPayload(payload, flags);if (!payload) {- console.log(`[CURSOR BUFFER] Frame ${frameCount}: decompression failed, skipping`);+ debugLog(`[CURSOR BUFFER] Frame ${frameCount}: decompression failed, skipping`);continue;}@@ -420,9 +424,7 @@ export class CursorExecutor extends BaseExecutor {const text = payload.toString("utf-8");if (text.startsWith("{") && text.includes('"error"')) {const hasContent = totalContent || toolCallsMap.size > 0;- console.log(- `[CURSOR BUFFER] Error frame (hasContent=${hasContent}): ${text.slice(0, 500)}`- );+ debugLog(`[CURSOR BUFFER] Error frame (hasContent=${hasContent}): ${text.slice(0, 500)}`);// If we already have content, treat error as stream termination (not fatal)if (hasContent) {break;@@ -432,11 +434,11 @@ export class CursorExecutor extends BaseExecutor {} catch {}const result = extractTextFromResponse(new Uint8Array(payload));- console.log(`[CURSOR DECODED] Frame ${frameCount}:`, result);+ debugLog(`[CURSOR DECODED] Frame ${frameCount}:`, result);if (result.error) {const hasContent = totalContent || toolCallsMap.size > 0;- console.log(`[CURSOR BUFFER] Decoded error (hasContent=${hasContent}): ${result.error}`);+ debugLog(`[CURSOR BUFFER] Decoded error (hasContent=${hasContent}): ${result.error}`);// If we already have content, treat error as stream terminationif (hasContent) {break;@@ -486,7 +488,7 @@ export class CursorExecutor extends BaseExecutor {if (result.text) totalContent += result.text;}- console.log(+ debugLog(`[CURSOR BUFFER] Parsed ${frameCount} frames, toolCallsMap size: ${toolCallsMap.size}, finalized toolCalls: ${toolCalls.length}`);@@ -494,7 +496,7 @@ export class CursorExecutor extends BaseExecutor {for (const [id, tc] of toolCallsMap.entries()) {// Check if already in final arrayif (!toolCalls.find((t) => t.id === id)) {- console.log(`[CURSOR BUFFER] Finalizing incomplete tool call: ${id}, isLast=${tc.isLast}`);+ debugLog(`[CURSOR BUFFER] Finalizing incomplete tool call: ${id}, isLast=${tc.isLast}`);toolCalls.push({id: tc.id,type: tc.type,@@ -506,7 +508,7 @@ export class CursorExecutor extends BaseExecutor {}}- console.log(`[CURSOR BUFFER] Final toolCalls count: ${toolCalls.length}`);+ debugLog(`[CURSOR BUFFER] Final toolCalls count: ${toolCalls.length}`);const message: Record<string, unknown> = {role: "assistant",@@ -551,11 +553,11 @@ export class CursorExecutor extends BaseExecutor {const toolCallsMap = new Map(); // Track streaming tool calls by IDlet frameCount = 0;- console.log(`[CURSOR BUFFER SSE] Total length: ${buffer.length} bytes`);+ debugLog(`[CURSOR BUFFER SSE] Total length: ${buffer.length} bytes`);while (offset < buffer.length) {if (offset + 5 > buffer.length) {- console.log(+ debugLog(`[CURSOR BUFFER SSE] Reached end, offset=${offset}, remaining=${buffer.length - offset}`);break;@@ -564,12 +566,12 @@ export class CursorExecutor extends BaseExecutor {const flags = buffer[offset];const length = buffer.readUInt32BE(offset + 1);- console.log(+ debugLog(`[CURSOR BUFFER SSE] Frame ${frameCount + 1}: flags=0x${flags.toString(16).padStart(2, "0")}, length=${length}`);if (offset + 5 + length > buffer.length) {- console.log(+ debugLog(`[CURSOR BUFFER SSE] Incomplete frame, offset=${offset}, length=${length}, buffer.length=${buffer.length}`);break;@@ -581,7 +583,7 @@ export class CursorExecutor extends BaseExecutor {payload = decompressPayload(payload, flags);if (!payload) {- console.log(`[CURSOR BUFFER SSE] Frame ${frameCount}: decompression failed, skipping`);+ debugLog(`[CURSOR BUFFER SSE] Frame ${frameCount}: decompression failed, skipping`);continue;}@@ -591,7 +593,7 @@ export class CursorExecutor extends BaseExecutor {if (text.startsWith("{") && text.includes('"error"')) {const hasContent = chunks.length > 0 || totalContent || toolCallsMap.size > 0;// Log the full error for debugging- console.log(+ debugLog(`[CURSOR BUFFER SSE] Error frame (hasContent=${hasContent}): ${text.slice(0, 500)}`);// If we already have content, treat error as stream termination (not fatal)@@ -603,13 +605,11 @@ export class CursorExecutor extends BaseExecutor {} catch {}const result = extractTextFromResponse(new Uint8Array(payload));- console.log(`[CURSOR DECODED SSE] Frame ${frameCount}:`, result);+ debugLog(`[CURSOR DECODED SSE] Frame ${frameCount}:`, result);if (result.error) {const hasContent = chunks.length > 0 || totalContent || toolCallsMap.size > 0;- console.log(- `[CURSOR BUFFER SSE] Decoded error (hasContent=${hasContent}): ${result.error}`- );+ debugLog(`[CURSOR BUFFER SSE] Decoded error (hasContent=${hasContent}): ${result.error}`);// If we already have content, treat error as stream terminationif (hasContent) {break;@@ -747,16 +747,14 @@ export class CursorExecutor extends BaseExecutor {}}- console.log(+ debugLog(`[CURSOR BUFFER SSE] Parsed ${frameCount} frames, toolCallsMap size: ${toolCallsMap.size}, toolCalls array: ${toolCalls.length}`);// Finalize all remaining tool calls in map (stream may have ended without isLast=true)for (const [id, tc] of toolCallsMap.entries()) {if (!toolCalls.find((t) => t.id === id)) {- console.log(- `[CURSOR BUFFER SSE] Finalizing incomplete tool call: ${id}, isLast=${tc.isLast}`- );+ debugLog(`[CURSOR BUFFER SSE] Finalizing incomplete tool call: ${id}, isLast=${tc.isLast}`);const toolCallIndex = toolCalls.length;toolCalls.push({id: tc.id,diff --git a/open-sse/utils/cursorProtobuf.ts b/open-sse/utils/cursorProtobuf.tsindex f593a6228c..d8365da646 100644--- a/open-sse/utils/cursorProtobuf.ts+++ b/open-sse/utils/cursorProtobuf.ts@@ -10,7 +10,7 @@import { v4 as uuidv4 } from "uuid";import zlib from "zlib";-const DEBUG = true;+const DEBUG = process.env.CURSOR_PROTOBUF_DEBUG === "1";const log = (tag, ...args) => DEBUG && console.log(`[PROTOBUF:${tag}]`, ...args);/**@@ -66,7 +66,6 @@ const FIELD = {MSG_ID: 13,MSG_TOOL_RESULTS: 18,MSG_IS_AGENTIC: 29,- MSG_SERVER_BUBBLE_ID: 32,MSG_UNIFIED_MODE: 47,MSG_SUPPORTED_TOOLS: 51,@@ -192,13 +191,6 @@ export function encodeField(fieldNum, wireType, value) {const tagBytes = encodeVarint(tag);if (wireType === WIRE_TYPE.VARINT) {- // Validate: VARINT value must be a number- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {- log(- "ENCODE",- `⚠️ VARINT field=${fieldNum} invalid value: type=${typeof value}, value=${value}`- );- }const valueBytes = encodeVarint(value);return concatArrays(tagBytes, valueBytes);}@@ -389,20 +381,6 @@ export function encodeMessage(hasTools = false,toolResults = []) {- // Debug: validate content type before encoding- if (- content !== null &&- content !== undefined &&- typeof content !== "string" &&- !(content instanceof Uint8Array) &&- !Buffer.isBuffer(content)- ) {- log(- "ENCODE",- `⚠️ MSG_CONTENT unexpected type: ${typeof content}, isArray=${Array.isArray(content)}, value=${JSON.stringify(content).slice(0, 200)}`- );- }-return concatArrays(encodeField(FIELD.MSG_CONTENT, WIRE_TYPE.LEN, content),encodeField(FIELD.MSG_ROLE, WIRE_TYPE.VARINT, role),@@ -550,27 +528,6 @@ export function encodeRequest(messages, modelName, tools = [], reasoningEffort =const msgId = uuidv4();const isLast = i === normalizedMessages.length - 1;- // Debug: log message shape for diagnosis- const toolResultsCount = Array.isArray(msg.tool_results) ? msg.tool_results.length : 0;- const contentStr = typeof msg.content === "string" ? msg.content : "";- const contentPreview = contentStr- .slice(0, 120)- .replace(/\r/g, "\\r")- .replace(/\n/g, "\\n")- .replace(/[^\x20-\x7E]/g, "?");- log(- "ENCODE",- `msg[${i}] role=${msg.role} contentType=${typeof msg.content} contentLen=${contentStr.length} contentPreview="${contentPreview}" contentIsArray=${Array.isArray(msg.content)} hasToolCalls=${Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0} hasToolResults=${toolResultsCount > 0} toolResultsCount=${toolResultsCount}`- );- if (toolResultsCount > 0) {- for (const tr of msg.tool_results) {- log(- "ENCODE",- ` toolResult: callId=${tr.tool_call_id} name=${tr.name} rawArgsType=${typeof tr.raw_args} rawArgsLen=${tr.raw_args?.length || 0} resultType=${typeof tr.result} resultLen=${tr.result?.length || 0}`- );- }- }-formattedMessages.push({content: msg.content,role,