Skip to content

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

Rust

recover cursor xml tool uses

Raine Virta595b587a6a05
diff --git a/src/providers/cursor/client.test.ts b/src/providers/cursor/client.test.ts
index 7a7dc23..48adc0e 100644
--- a/src/providers/cursor/client.test.ts
+++ b/src/providers/cursor/client.test.ts
@@ -149,6 +149,30 @@ describe("Cursor protocol client", () => {
expect(clientMessages[5]).toEqual({ kvClientMessage: { getBlobResult: {}, id: 2 } });
});
+ it("answers repeated Cursor requestContextArgs messages", async () => {
+ const clientMessages = await runAndDrainCursorAgentWithFrames([
+ buildServerExecFrame(0, undefined, { case: "requestContextArgs", value: {} }),
+ buildServerExecFrame(7, "exec-context", { case: "requestContextArgs", value: {} }),
+ buildServerStreamCloseFrame(),
+ ]);
+
+ assertHeartbeatMessage(clientMessages, 1);
+ expect(clientMessages[2]?.execClientMessage.requestContextResult.success.requestContext).toBeDefined();
+ assertStreamCloseMessage(clientMessages, 3);
+ expect(clientMessages[4]).toMatchObject({
+ execClientMessage: {
+ id: 7,
+ execId: "exec-context",
+ requestContextResult: {
+ success: {
+ requestContext: expect.any(Object),
+ },
+ },
+ },
+ });
+ assertStreamCloseMessage(clientMessages, 5, 7);
+ });
+
it("sends selected images in the Cursor run request", async () => {
const { upstream, sentFrames } = await runCursorAgentWithFrames(
[buildServerStreamCloseFrame()],
diff --git a/src/providers/cursor/client.ts b/src/providers/cursor/client.ts
index b59dbbc..dc90bab 100644
--- a/src/providers/cursor/client.ts
+++ b/src/providers/cursor/client.ts
@@ -440,7 +440,6 @@ async function processServerControlFrames(
const state = controlFrameState.get(append) ?? {
buffer: Buffer.alloc(0),
execHeartbeatSent: false,
- requestContextAcked: false,
};
controlFrameState.set(append, state);
state.buffer = Buffer.concat([state.buffer, Buffer.from(chunk)]);
@@ -462,10 +461,9 @@ async function processServerControlFrames(
state.execHeartbeatSent = true;
await append({ execClientControlMessage: { heartbeat: {} } });
}
- if (oneof.value?.message?.case === "requestContextArgs" && !state.requestContextAcked) {
- state.requestContextAcked = true;
+ if (oneof.value?.message?.case === "requestContextArgs") {
await append({ execClientMessage: buildRequestContextResult(oneof.value) });
- await append({ execClientControlMessage: { streamClose: {} } });
+ await append({ execClientControlMessage: { streamClose: streamCloseForExec(oneof.value) } });
} else if (oneof.value?.message?.case === "readArgs") {
if (readHandler) {
await readHandler(oneof.value, append);
@@ -997,9 +995,13 @@ function buildInteractionResponse(query: {
const controlFrameState = new WeakMap<
(messageJson: unknown) => Promise<void>,
- { buffer: Buffer; execHeartbeatSent: boolean; requestContextAcked: boolean }
+ { buffer: Buffer; execHeartbeatSent: boolean }
>();
+function streamCloseForExec(exec: { id?: number }): Record<string, unknown> {
+ return typeof exec.id === "number" && exec.id !== 0 ? { id: exec.id } : {};
+}
+
interface CursorOneofMessage {
message?: {
case?: string;
diff --git a/src/providers/cursor/index.test.ts b/src/providers/cursor/index.test.ts
index 4ddb6f4..5684d13 100644
--- a/src/providers/cursor/index.test.ts
+++ b/src/providers/cursor/index.test.ts
@@ -307,6 +307,70 @@ describe("Cursor provider messages", () => {
expectMessageStop(resumeEvents);
});
+ it("recovers XML tool_use text while the native Cursor bridge is active", async () => {
+ const provider = createCursorTestProvider(async () => {
+ return streamFromChunks([
+ frame({
+ interactionUpdate: {
+ textDelta: {
+ text:
+ "Continuing validation: checking the diff.\n\n<tool_use id=\"old_read_id\" name=\"Bash\">\n" +
+ "{\"command\":\"git diff --check && git diff src/operations.rs\",\"description\":\"Check diff whitespace\"}\n" +
+ "</tool_use>\n<tool_use id=\"old_read_id_2\" name=\"Bash\">\n",
+ },
+ },
+ }),
+ frame({
+ interactionUpdate: {
+ textDelta: {
+ text:
+ "{\"command\":\"just check\",\"description\":\"Run project check suite\",\"block_until_ms\":300000}\n</tool_use>\n</tool_use>",
+ },
+ },
+ }),
+ frame({ interactionUpdate: { turnEnded: { inputTokens: "20", outputTokens: "10" } } }),
+ encodeConnectFrame(jsonBytes({}), 2),
+ ]);
+ });
+
+ const response = await provider.handleMessages(
+ {
+ model: "cursor",
+ stream: true,
+ tools: [{ name: "Bash", input_schema: { type: "object" } }],
+ messages: [{ role: "user", content: "continue" }],
+ },
+ fakeCursorCtx({ sessionId: "session" }),
+ );
+ const events = await collectCursorSse(response);
+ const text = events
+ .filter((event) => event.event === "content_block_delta" && event.data.delta?.type === "text_delta")
+ .map((event) => event.data.delta.text)
+ .join("");
+ const toolStarts = events.filter((event) =>
+ event.event === "content_block_start" && event.data.content_block?.type === "tool_use"
+ );
+ const inputs = events
+ .filter((event) => event.event === "content_block_delta" && event.data.delta?.type === "input_json_delta")
+ .map((event) => JSON.parse(event.data.delta.partial_json));
+
+ expect(text).toBe("Continuing validation: checking the diff.\n\n");
+ expect(text).not.toContain("<tool_use");
+ expect(toolStarts).toHaveLength(2);
+ expect(toolStarts.map((event) => event.data.content_block.name)).toEqual(["Bash", "Bash"]);
+ expect(toolStarts[0]?.data.content_block.id).toStartWith("call_cursor_");
+ expect(toolStarts[0]?.data.content_block.id).not.toBe("old_read_id");
+ expect(toolStarts[1]?.data.content_block.id).toStartWith("call_cursor_");
+ expect(toolStarts[1]?.data.content_block.id).not.toBe("old_read_id_2");
+ expect(inputs.map((input) => input.command)).toEqual([
+ "git diff --check && git diff src/operations.rs",
+ "just check",
+ ]);
+ expect(inputs[1]?.block_until_ms).toBe(300000);
+ expectMessageStopReason(events, "tool_use");
+ expectMessageStop(events);
+ });
+
it("denies Cursor shellStreamArgs instead of executing internally when Claude did not advertise Bash", async () => {
let finalResponseSent = false;
const dir = await mkdtemp(join(tmpdir(), "cursor-denied-shell-"));
diff --git a/src/providers/cursor/index.ts b/src/providers/cursor/index.ts
index 66d529d..cf4f5ce 100644
--- a/src/providers/cursor/index.ts
+++ b/src/providers/cursor/index.ts
@@ -74,6 +74,7 @@ async function handleMessages(
const selectedImages = cursorSelectedImages(body);
const wantStream = wantsDownstreamStream(body);
const conversationId = cursorConversationForRequest(body, ctx.sessionId);
+ const allowedToolNames = new Set((body.tools ?? []).map((tool) => tool.name));
log.debug("cursor request", {
requestedModel: body.model,
@@ -106,6 +107,7 @@ async function handleMessages(
traffic: ctx.traffic,
proto: deps.proto,
onSession,
+ allowedToolNames,
})
: undefined;
const bridgeRead = canBridgeCursorReadTool(body);
@@ -161,6 +163,7 @@ async function handleMessages(
traffic: ctx.traffic,
proto: deps.proto,
onSession,
+ allowedToolNames,
});
return sseResponse(stream);
}
@@ -173,6 +176,7 @@ async function handleMessages(
traffic: ctx.traffic,
proto: deps.proto,
onSession,
+ allowedToolNames,
});
return jsonResponse(result.response);
} catch (err) {
diff --git a/src/providers/cursor/tool-bridge.ts b/src/providers/cursor/tool-bridge.ts
index e31921f..c75f9ab 100644
--- a/src/providers/cursor/tool-bridge.ts
+++ b/src/providers/cursor/tool-bridge.ts
@@ -23,6 +23,11 @@ import {
import type { CursorProto } from "./proto-loader.ts";
import { cursorUsageToAnthropic } from "./translate/response.ts";
import { createCursorSseFramer } from "./sse-framing.ts";
+import {
+ CursorToolUseXmlParser,
+ type RecoveredCursorTextEvent,
+ type RecoveredCursorToolUse,
+} from "./tool-use-xml.ts";
interface PendingToolBase {
toolUseId: string;
@@ -66,6 +71,7 @@ interface CursorBridgeState {
log: Logger;
traffic?: RequestContext["traffic"];
onSession?: (sessionId: string) => void;
+ allowedToolNames?: ReadonlySet<string>;
}
const bridgeStates = new Map<string, CursorBridgeState>();
@@ -133,6 +139,7 @@ export function createCursorShellToolBridge(opts: {
traffic?: RequestContext["traffic"];
proto?: CursorProto;
onSession?: (sessionId: string) => void;
+ allowedToolNames?: ReadonlySet<string>;
}): {
readHandler: (exec: CursorReadExec, append: CursorAppendMessage) => Promise<void>;
shellStreamHandler: (exec: CursorShellStreamExec, append: CursorAppendMessage) => Promise<void>;
@@ -148,6 +155,7 @@ export function createCursorShellToolBridge(opts: {
log: opts.log,
traffic: opts.traffic,
onSession: opts.onSession,
+ allowedToolNames: opts.allowedToolNames,
};
const notifyTool = (tool: PendingNativeTool) => {
@@ -331,6 +339,7 @@ function streamBridgeUntilToolOrEnd(
emit,
mapUsage: cursorUsageToAnthropic,
});
+ const toolUseXml = new CursorToolUseXmlParser({ allowedToolNames: state.allowedToolNames });
const emitToolUseAndPause = (tool: PendingNativeTool) => {
framing.emitToolPauseMessage((index) => {
@@ -354,8 +363,44 @@ function streamBridgeUntilToolOrEnd(
});
};
+ const emitRecoveredToolUse = (tool: RecoveredCursorToolUse) => {
+ state.traffic?.writeJsonEvent("041-cursor-xml-tool-use", {
+ id: tool.id,
+ originalId: tool.originalId,
+ name: tool.name,
+ inputChars: JSON.stringify(tool.input).length,
+ });
+ framing.closeOpenBlocks();
+ framing.ensureStart();
+ const index = framing.nextContentBlockIndex();
+ emit("content_block_start", {
+ type: "content_block_start",
+ index,
+ content_block: {
+ type: "tool_use",
+ id: tool.id,
+ name: tool.name,
+ input: {},
+ },
+ });
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index,
+ delta: { type: "input_json_delta", partial_json: JSON.stringify(tool.input) },
+ });
+ emit("content_block_stop", { type: "content_block_stop", index });
+ };
+
+ const applyRecoveredEvent = (event: RecoveredCursorTextEvent) => {
+ if (event.type === "text") {
+ framing.emitTextDelta(event.text);
+ return;
+ }
+ emitRecoveredToolUse(event);
+ };
+
const emitMessageEnd = () => {
- framing.emitFinalMessage("end_turn");
+ framing.emitFinalMessage(toolUseXml.sawToolUse ? "tool_use" : "end_turn");
};
const emitStreamError = (err: unknown) => {
@@ -388,7 +433,7 @@ function streamBridgeUntilToolOrEnd(
framing.emitThinkingDelta(event.text);
break;
case "text_delta":
- framing.emitTextDelta(event.text);
+ for (const recovered of toolUseXml.push(event.text)) applyRecoveredEvent(recovered);
break;
case "usage":
framing.recordUsage(event.usage);
@@ -397,6 +442,7 @@ function streamBridgeUntilToolOrEnd(
break;
}
}
+ for (const recovered of toolUseXml.flush()) applyRecoveredEvent(recovered);
emitMessageEnd();
bridgeStates.delete(state.sessionId);
diff --git a/src/providers/cursor/tool-use-xml.ts b/src/providers/cursor/tool-use-xml.ts
new file mode 100644
index 0000000..81a664a
--- /dev/null
+++ b/src/providers/cursor/tool-use-xml.ts
@@ -0,0 +1,160 @@
+export interface RecoveredCursorToolUse {
+ type: "tool_use";
+ id: string;
+ originalId?: string;
+ name: string;
+ input: Record<string, unknown>;
+}
+
+export type RecoveredCursorTextEvent =
+ | { type: "text"; text: string }
+ | RecoveredCursorToolUse;
+
+export class CursorToolUseXmlParser {
+ private buffer = "";
+ private recoveredToolUse = false;
+ private readonly allowedToolNames?: ReadonlySet<string>;
+ private readonly idFactory: () => string;
+
+ constructor(opts: {
+ allowedToolNames?: ReadonlySet<string>;
+ idFactory?: () => string;
+ } = {}) {
+ this.allowedToolNames = opts.allowedToolNames;
+ this.idFactory = opts.idFactory ?? newCursorToolUseId;
+ }
+
+ get sawToolUse(): boolean {
+ return this.recoveredToolUse;
+ }
+
+ push(text: string): RecoveredCursorTextEvent[] {
+ this.buffer += text;
+ return this.drain(false);
+ }
+
+ flush(): RecoveredCursorTextEvent[] {
+ return this.drain(true);
+ }
+
+ private drain(flush: boolean): RecoveredCursorTextEvent[] {
+ const events: RecoveredCursorTextEvent[] = [];
+
+ while (this.buffer) {
+ if (this.dropRedundantCloseTag()) continue;
+
+ const start = this.buffer.search(/<tool_use\b/);
+ if (start === -1) {
+ const hold = flush ? 0 : toolUsePrefixSuffixLength(this.buffer);
+ const end = this.buffer.length - hold;
+ this.pushText(events, this.buffer.slice(0, end));
+ this.buffer = this.buffer.slice(end);
+ break;
+ }
+
+ if (start > 0) {
+ this.pushText(events, this.buffer.slice(0, start));
+ this.buffer = this.buffer.slice(start);
+ continue;
+ }
+
+ const closeStart = this.buffer.indexOf("</tool_use>");
+ if (closeStart === -1) {
+ if (flush) {
+ this.pushText(events, this.buffer);
+ this.buffer = "";
+ }
+ break;
+ }
+
+ const closeEnd = closeStart + "</tool_use>".length;
+ const raw = this.buffer.slice(0, closeEnd);
+ const parsed = this.parseToolUse(raw);
+ if (parsed) {
+ this.recoveredToolUse = true;
+ events.push(parsed);
+ } else {
+ this.pushText(events, raw);
+ }
+ this.buffer = this.buffer.slice(closeEnd);
+ }
+
+ return events;
+ }
+
+ private parseToolUse(raw: string): RecoveredCursorToolUse | undefined {
+ const match = raw.match(/^<tool_use\b([^>]*)>([\s\S]*?)<\/tool_use>$/);
+ if (!match) return undefined;
+ const attrs = parseXmlAttributes(match[1] ?? "");
+ const name = attrs.name;
+ if (!name) return undefined;
+ if (this.allowedToolNames && !this.allowedToolNames.has(name)) return undefined;
+
+ let input: unknown;
+ try {
+ input = JSON.parse((match[2] ?? "").trim() || "{}");
+ } catch {
+ return undefined;
+ }
+ if (!isJsonObject(input)) return undefined;
+
+ return {
+ type: "tool_use",
+ id: this.idFactory(),
+ originalId: attrs.id,
+ name,
+ input,
+ };
+ }
+
+ private pushText(events: RecoveredCursorTextEvent[], text: string): void {
+ if (!text) return;
+ if (this.recoveredToolUse && text.trim() === "") return;
+ events.push({ type: "text", text });
+ }
+
+ private dropRedundantCloseTag(): boolean {
+ if (!this.recoveredToolUse) return false;
+ const match = this.buffer.match(/^\s*<\/tool_use>\s*/);
+ if (!match?.[0]) return false;
+ this.buffer = this.buffer.slice(match[0].length);
+ return true;
+ }
+}
+
+function parseXmlAttributes(source: string): Record<string, string> {
+ const attrs: Record<string, string> = {};
+ const attrPattern = /([A-Za-z_][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
+ for (const match of source.matchAll(attrPattern)) {
+ const key = match[1];
+ const value = match[2] ?? match[3] ?? "";
+ if (key) attrs[key] = decodeXmlAttribute(value);
+ }
+ return attrs;
+}
+
+function decodeXmlAttribute(value: string): string {
+ return value
+ .replaceAll("&quot;", '"')
+ .replaceAll("&apos;", "'")
+ .replaceAll("&lt;", "<")
+ .replaceAll("&gt;", ">")
+ .replaceAll("&amp;", "&");
+}
+
+function isJsonObject(value: unknown): value is Record<string, unknown> {
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
+}
+
+function toolUsePrefixSuffixLength(value: string): number {
+ const marker = "<tool_use";
+ const max = Math.min(marker.length - 1, value.length);
+ for (let len = max; len > 0; len--) {
+ if (value.endsWith(marker.slice(0, len))) return len;
+ }
+ return 0;
+}
+
+function newCursorToolUseId(): string {
+ return `call_cursor_${crypto.randomUUID().replaceAll("-", "")}`;
+}
diff --git a/src/providers/cursor/translate/response.test.ts b/src/providers/cursor/translate/response.test.ts
index 5a73f89..0edc55c 100644
--- a/src/providers/cursor/translate/response.test.ts
+++ b/src/providers/cursor/translate/response.test.ts
@@ -38,6 +38,7 @@ async function collectDecodedCursorEvents(
async function translateCursorSse(
frames: Uint8Array[],
messageId: string,
+ allowedToolNames?: ReadonlySet<string>,
): Promise<Array<{ event: string; data: any }>> {
const downstream = translateCursorStream(
streamFromChunks(frames),
@@ -46,6 +47,7 @@ async function translateCursorSse(
model: "cursor-plan",
log: createLogger("cursor.response.test"),
proto: fakeProto,
+ allowedToolNames,
},
);
return collectCursorSse(downstream);
@@ -235,6 +237,49 @@ describe("Cursor response translation", () => {
expect(events[8]?.data.usage.output_tokens).toBe(3);
});
+ it("recovers XML tool_use text deltas as Anthropic tool calls", async () => {
+ const events = await translateCursorSse(
+ [
+ frame({ interactionUpdate: { textDelta: { text: "Continuing validation.\n\n<tool_" } } }),
+ frame({
+ interactionUpdate: {
+ textDelta: {
+ text:
+ "use id=\"old_history_id\" name=\"Bash\">\n{\"command\":\"git diff --check\",\"description\":\"Check diff\"}\n</tool_use>\n</tool_use>",
+ },
+ },
+ }),
+ frame({ interactionUpdate: { turnEnded: { inputTokens: "8", outputTokens: "3" } } }),
+ encodeConnectFrame(jsonBytes({}), 2),
+ ],
+ "msg_xml_tool",
+ new Set(["Bash"]),
+ );
+
+ const textDeltas = events
+ .filter((event) => event.event === "content_block_delta" && event.data.delta?.type === "text_delta")
+ .map((event) => event.data.delta.text)
+ .join("");
+ const toolStart = events.find((event) =>
+ event.event === "content_block_start" && event.data.content_block?.type === "tool_use"
+ );
+ const inputDelta = events.find((event) =>
+ event.event === "content_block_delta" && event.data.delta?.type === "input_json_delta"
+ );
+ const stopReason = events.find((event) => event.event === "message_delta")?.data.delta.stop_reason;
+
+ expect(textDeltas).toBe("Continuing validation.\n\n");
+ expect(textDeltas).not.toContain("<tool_use");
+ expect(toolStart?.data.content_block.name).toBe("Bash");
+ expect(toolStart?.data.content_block.id).toStartWith("call_cursor_");
+ expect(toolStart?.data.content_block.id).not.toBe("old_history_id");
+ expect(JSON.parse(inputDelta?.data.delta.partial_json)).toEqual({
+ command: "git diff --check",
+ description: "Check diff",
+ });
+ expect(stopReason).toBe("tool_use");
+ });
+
it("emits an Anthropic SSE error for Cursor Connect end errors", async () => {
const events = await translateCursorSse(
[
diff --git a/src/providers/cursor/translate/response.ts b/src/providers/cursor/translate/response.ts
index 9c4472d..43b2599 100644
--- a/src/providers/cursor/translate/response.ts
+++ b/src/providers/cursor/translate/response.ts
@@ -4,14 +4,23 @@ import type { TrafficCapture } from "../../types.ts";
import { decodeCursorStream, type CursorStreamEvent, type CursorUsage } from "../client.ts";
import type { CursorProto } from "../proto-loader.ts";
import { createCursorSseFramer } from "../sse-framing.ts";
+import {
+ CursorToolUseXmlParser,
+ type RecoveredCursorTextEvent,
+ type RecoveredCursorToolUse,
+} from "../tool-use-xml.ts";
export interface AnthropicCursorResponse {
id: string;
type: "message";
role: "assistant";
model: string;
- content: Array<{ type: "thinking"; thinking: string; signature: string } | { type: "text"; text: string }>;
- stop_reason: "end_turn" | null;
+ content: Array<
+ | { type: "thinking"; thinking: string; signature: string }
+ | { type: "text"; text: string }
+ | { type: "tool_use"; id: string; name: string; input: Record<string, unknown> }
+ >;
+ stop_reason: "end_turn" | "tool_use" | null;
stop_sequence: null;
usage: AnthropicUsage;
}
@@ -45,12 +54,50 @@ export async function accumulateCursorResponse(
traffic?: TrafficCapture;
proto?: CursorProto;
onSession?: (sessionId: string) => void;
+ allowedToolNames?: ReadonlySet<string>;
},
): Promise<{ response: AnthropicCursorResponse; cursorSessionId?: string }> {
- let text = "";
let thinking = "";
let usage: CursorUsage | undefined;
let cursorSessionId: string | undefined;
+ const content: AnthropicCursorResponse["content"] = [];
+ const toolUseXml = new CursorToolUseXmlParser({ allowedToolNames: opts.allowedToolNames });
+
+ const flushThinking = () => {
+ if (!thinking) return;
+ content.push({ type: "thinking", thinking, signature: "" });
+ thinking = "";
+ };
+
+ const appendText = (text: string) => {
+ if (!text) return;
+ const previous = content.at(-1);
+ if (previous?.type === "text") {
+ previous.text += text;
+ } else {
+ content.push({ type: "text", text });
+ }
+ };
+
+ const applyRecoveredEvent = (event: RecoveredCursorTextEvent) => {
+ flushThinking();
+ if (event.type === "text") {
+ appendText(event.text);
+ return;
+ }
+ content.push({
+ type: "tool_use",
+ id: event.id,
+ name: event.name,
+ input: event.input,
+ });
+ opts.traffic?.writeJsonEvent("041-cursor-xml-tool-use", {
+ id: event.id,
+ originalId: event.originalId,
+ name: event.name,
+ inputChars: JSON.stringify(event.input).length,
+ });
+ };
for await (const event of decodeCursorStream(upstream, opts.proto, { traffic: opts.traffic, log: opts.log })) {
opts.traffic?.writeJsonEvent("040-cursor-event", event);
@@ -63,7 +110,7 @@ export async function accumulateCursorResponse(
thinking += event.text;
break;
case "text_delta":
- text += event.text;
+ for (const recovered of toolUseXml.push(event.text)) applyRecoveredEvent(recovered);
break;
case "usage":
usage = event.usage;
@@ -72,13 +119,12 @@ export async function accumulateCursorResponse(
break;
}
}
+ for (const recovered of toolUseXml.flush()) applyRecoveredEvent(recovered);
+ flushThinking();
- const content: AnthropicCursorResponse["content"] = [];
- if (thinking) content.push({ type: "thinking", thinking, signature: "" });
- if (text) content.push({ type: "text", text });
opts.log.debug("cursor accumulate finish", {
- textChars: text.length,
- thinkingChars: thinking.length,
+ contentBlocks: content.length,
+ sawRecoveredToolUse: toolUseXml.sawToolUse,
cursorSessionId,
usage,
});
@@ -91,7 +137,7 @@ export async function accumulateCursorResponse(
role: "assistant",
model: opts.model,
content,
- stop_reason: "end_turn",
+ stop_reason: toolUseXml.sawToolUse ? "tool_use" : "end_turn",
stop_sequence: null,
usage: cursorUsageToAnthropic(usage),
},
@@ -108,6 +154,7 @@ export function translateCursorStream(
traffic?: TrafficCapture;
proto?: CursorProto;
onSession?: (sessionId: string) => void;
+ allowedToolNames?: ReadonlySet<string>;
},
): ReadableStream<Uint8Array> {
const encoder = new TextEncoder();
@@ -128,6 +175,43 @@ export function translateCursorStream(
emit,
mapUsage: cursorUsageToAnthropic,
});
+ const toolUseXml = new CursorToolUseXmlParser({ allowedToolNames: opts.allowedToolNames });
+
+ const emitRecoveredToolUse = (tool: RecoveredCursorToolUse) => {
+ opts.traffic?.writeJsonEvent("041-cursor-xml-tool-use", {
+ id: tool.id,
+ originalId: tool.originalId,
+ name: tool.name,
+ inputChars: JSON.stringify(tool.input).length,
+ });
+ framing.closeOpenBlocks();
+ framing.ensureStart();
+ const index = framing.nextContentBlockIndex();
+ emit("content_block_start", {
+ type: "content_block_start",
+ index,
+ content_block: {
+ type: "tool_use",
+ id: tool.id,
+ name: tool.name,
+ input: {},
+ },
+ });
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index,
+ delta: { type: "input_json_delta", partial_json: JSON.stringify(tool.input) },
+ });
+ emit("content_block_stop", { type: "content_block_stop", index });
+ };
+
+ const applyRecoveredEvent = (event: RecoveredCursorTextEvent) => {
+ if (event.type === "text") {
+ framing.emitTextDelta(event.text);
+ return;
+ }
+ emitRecoveredToolUse(event);
+ };
try {
for await (const event of decodeCursorStream(upstream, opts.proto, { traffic: opts.traffic, log: opts.log })) {
@@ -141,7 +225,7 @@ export function translateCursorStream(
framing.emitThinkingDelta(event.text);
break;
case "text_delta":
- framing.emitTextDelta(event.text);
+ for (const recovered of toolUseXml.push(event.text)) applyRecoveredEvent(recovered);
break;
case "usage":
framing.recordUsage(event.usage);
@@ -150,7 +234,8 @@ export function translateCursorStream(
break;
}
}
- framing.emitFinalMessage("end_turn");
+ for (const recovered of toolUseXml.flush()) applyRecoveredEvent(recovered);
+ framing.emitFinalMessage(toolUseXml.sawToolUse ? "tool_use" : "end_turn");
} catch (err) {
opts.log.warn("cursor stream error", { err: String(err) });
framing.emitError(err);