9router/open-sse/translator/request/openai-to-cursor.js

186 lines
6 KiB
JavaScript
Raw Normal View History

2026-02-04 23:06:20 -05:00
/**
* OpenAI to Cursor Request Translator
2026-03-11 00:59:07 -04:00
* Converts OpenAI messages to Cursor ask/agent format.
*
* Important: Cursor can loop when tool outputs are sent via protobuf tool_results
* with partial schema mismatches. For stability, tool outputs are represented as
* structured text blocks in user messages.
2026-02-04 23:06:20 -05:00
*/
import { register } from "../index.js";
import { FORMATS } from "../formats.js";
import { ROLE, OPENAI_BLOCK, CLAUDE_BLOCK } from "../schema/index.js";
import { DEFAULT_MIN_TOKENS } from "../../config/runtimeConfig.js";
2026-02-04 23:06:20 -05:00
function extractContent(content) {
if (typeof content === "string") return content;
if (Array.isArray(content)) {
2026-03-11 00:59:07 -04:00
return content
.filter(part => {
if (!part || typeof part !== "object") return false;
return part.type === OPENAI_BLOCK.TEXT && typeof part.text === "string";
2026-03-11 00:59:07 -04:00
})
.map(part => part.text || "")
.join("");
}
return "";
}
2026-03-11 00:59:07 -04:00
function sanitizeToolResultText(text) {
// Strip non-printable control chars that can produce backend request errors
return text.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "");
}
function escapeXml(text) {
return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
function buildToolResultBlock(toolName, toolCallId, resultText) {
const cleanResult = sanitizeToolResultText(resultText || "");
return [
"<tool_result>",
`<tool_name>${escapeXml(toolName || "tool")}</tool_name>`,
`<tool_call_id>${escapeXml(toolCallId || "")}</tool_call_id>`,
`<result>${escapeXml(cleanResult)}</result>`,
"</tool_result>"
].join("\n");
}
function normalizeToolCallId(id) {
return typeof id === "string" ? id.split("\n")[0] : "";
2026-02-23 09:56:40 -05:00
}
2026-02-04 23:06:20 -05:00
function convertMessages(messages) {
const result = [];
2026-03-11 00:59:07 -04:00
// Build a map of tool_call_id -> tool name from assistant tool calls
const toolCallMetaMap = new Map();
const rememberToolMeta = (toolCallId, toolName) => {
if (!toolCallId) return;
const name = toolName || "tool";
toolCallMetaMap.set(toolCallId, { name });
const normalized = normalizeToolCallId(toolCallId);
if (normalized && normalized !== toolCallId) {
toolCallMetaMap.set(normalized, { name });
}
};
for (const msg of messages) {
if (msg.role === ROLE.ASSISTANT && msg.tool_calls) {
2026-03-11 00:59:07 -04:00
for (const tc of msg.tool_calls) {
rememberToolMeta(tc.id || "", tc.function?.name || "tool");
}
}
if (msg.role === ROLE.ASSISTANT && Array.isArray(msg.content)) {
2026-03-11 00:59:07 -04:00
for (const part of msg.content) {
if (part?.type !== CLAUDE_BLOCK.TOOL_USE) continue;
2026-03-11 00:59:07 -04:00
rememberToolMeta(part.id || "", part.name || "tool");
}
}
}
for (let i = 0; i < messages.length; i++) {
const msg = messages[i];
2026-02-04 23:06:20 -05:00
if (msg.role === ROLE.SYSTEM) {
2026-03-11 00:59:07 -04:00
result.push({
role: ROLE.USER,
2026-03-11 00:59:07 -04:00
content: `[System Instructions]\n${extractContent(msg.content)}`
});
continue;
}
if (msg.role === ROLE.TOOL) {
2026-03-11 00:59:07 -04:00
const toolContent = extractContent(msg.content);
const toolCallId = msg.tool_call_id || "";
const toolMeta = toolCallMetaMap.get(toolCallId) || {};
const toolName = msg.name || toolMeta.name || "tool";
result.push({
role: ROLE.USER,
2026-03-11 00:59:07 -04:00
content: buildToolResultBlock(toolName, toolCallId, toolContent)
});
continue;
}
if (msg.role === ROLE.USER || msg.role === ROLE.ASSISTANT) {
if (msg.role === ROLE.USER && Array.isArray(msg.content)) {
2026-02-23 09:56:40 -05:00
const parts = [];
for (const block of msg.content) {
2026-03-11 00:59:07 -04:00
if (!block || typeof block !== "object") continue;
if (block.type === CLAUDE_BLOCK.TEXT) {
2026-03-11 00:59:07 -04:00
if (typeof block.text === "string") {
parts.push(block.text || "");
}
continue;
}
if (block.type === CLAUDE_BLOCK.TOOL_RESULT) {
2026-02-23 09:56:40 -05:00
const toolCallId = block.tool_use_id || "";
2026-03-11 00:59:07 -04:00
const toolMeta =
toolCallMetaMap.get(toolCallId) ||
toolCallMetaMap.get(normalizeToolCallId(toolCallId));
const toolName = toolMeta?.name || "tool";
const toolContent = extractContent(block.content);
parts.push(buildToolResultBlock(toolName, toolCallId, toolContent));
2026-02-23 09:56:40 -05:00
}
}
2026-03-11 00:59:07 -04:00
const joined = parts.filter(Boolean).join("\n");
if (joined) result.push({ role: ROLE.USER, content: joined });
2026-03-11 00:59:07 -04:00
continue;
2026-02-23 09:56:40 -05:00
}
2026-02-04 23:06:20 -05:00
2026-03-11 00:59:07 -04:00
const content = extractContent(msg.content);
2026-02-04 23:06:20 -05:00
if (msg.role === ROLE.ASSISTANT && msg.tool_calls && msg.tool_calls.length > 0) {
const assistantMsg = { role: ROLE.ASSISTANT, content: content || "" };
2026-03-11 00:59:07 -04:00
assistantMsg.tool_calls = msg.tool_calls.map(tc => {
const { index, ...rest } = tc || {};
return rest;
});
result.push(assistantMsg);
} else if (msg.role === ROLE.ASSISTANT && Array.isArray(msg.content)) {
2026-03-11 00:59:07 -04:00
const extractedToolCalls = msg.content
.filter(b => b?.type === CLAUDE_BLOCK.TOOL_USE)
2026-02-23 09:56:40 -05:00
.map(b => ({
2026-03-11 00:59:07 -04:00
id: b.id || "",
type: OPENAI_BLOCK.FUNCTION,
2026-02-23 09:56:40 -05:00
function: {
2026-03-11 00:59:07 -04:00
name: b.name || "tool",
2026-02-23 09:56:40 -05:00
arguments: JSON.stringify(b.input || {})
}
2026-03-11 00:59:07 -04:00
}))
.filter(tc => tc.id);
2026-02-23 09:56:40 -05:00
2026-03-11 00:59:07 -04:00
if (extractedToolCalls.length > 0) {
result.push({
role: ROLE.ASSISTANT,
2026-03-11 00:59:07 -04:00
content: content || "",
tool_calls: extractedToolCalls
});
} else if (content) {
result.push({ role: ROLE.ASSISTANT, content });
2026-03-11 00:59:07 -04:00
}
} else {
if (content) {
result.push({ role: msg.role, content });
}
2026-02-04 23:06:20 -05:00
}
}
}
return result;
}
export function openaiToCursorRequest(model, body, stream, credentials) {
2026-02-04 23:06:20 -05:00
const messages = convertMessages(body.messages || []);
// Strip fields irrelevant to Cursor (OpenAI/Anthropic-specific)
const { user, metadata, tool_choice, stream_options, system, ...rest } = body;
2026-02-04 23:06:20 -05:00
return {
...rest,
messages,
max_tokens: DEFAULT_MIN_TOKENS
2026-02-04 23:06:20 -05:00
};
}
register(FORMATS.OPENAI, FORMATS.CURSOR, openaiToCursorRequest, null);