Skip to content

Commit 34b1673

Browse files
committed
fix(cursor): normalize empty and failure-state Computer Use tool results (#1920)
Scoped re-implementation of PR #1920 per the campaign disposition (REDESIGN-SMALL: apply formatted text at the native toolResultPart plus a decode test). Resolves the #1866 empty/truncated Computer Use results. - New tool-result-normalize.ts: blank or empty-exec-wrapper output on node_repl / Computer Use tools becomes an actionable error; known runtime failure states reported as plain text (SkyComputerUseError, sky is not defined, redeclared identifier, unsupported import) are marked isError with one-line recovery guidance. Everything else passes byte-identical. - Wired at all four wire sites: toolResultContentItems (native McpText), toolResultPart (McpSuccess.isError), toolResultToText (replay text), and the two sites that bypass it — the externalModel branch of conversationTurns (the cursor/grok-4.6 repro path) and the root-prompt prefix. - Decode test proves the native ConversationStep wire carries the normalized text and isError via fromBinary, plus unit rows per failure state and byte-identical passes for non-computer-use tools. Out of scope (deferred, disclosed on the issue): screenshot stripping and AXTree text compaction from the original PR — the native path already bounds step size by real serialized bytes, dropping images oldest-first. Credit: original PR #1920.
1 parent 69650fa commit 34b1673

3 files changed

Lines changed: 273 additions & 7 deletions

File tree

‎src/adapters/cursor/protobuf-request.ts‎

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type { OcxAssistantContentPart, OcxMessage, OcxToolResultMessage } from "
55
import { namespacedToolName } from "../../types";
66
import type { CursorRunRequest } from "./types";
77
import { isCursorExternalWireModel } from "./discovery";
8+
import { normalizeCursorToolResultText } from "./tool-result-normalize";
89
import { debugProviderDiagnostic } from "../../lib/debug";
910
import {
1011
createCursorBlobRequestScope,
@@ -240,7 +241,9 @@ function rootPromptMessages(request: CursorRunRequest, requestScope: CursorBlobR
240241
}
241242
// Assistant tool CALLS are intentionally NOT replayed as visible "[Tool Call]" text here.
242243
} else if (message.role === "toolResult") {
243-
const prefix = message.isError ? "[Tool Error]" : "[Tool Result]";
244+
// #1920: the prefix must reflect the NORMALIZED error state (an empty
245+
// node_repl result is an error even when the runtime said isError=false).
246+
const prefix = normalizedToolResult(message, contentToText(message.content)).isError ? "[Tool Error]" : "[Tool Result]";
244247
const text = `${prefix}\n${toolResultToText(message)}`;
245248
entries.push(rootBlobCandidate(
246249
toolResultRootPayload(text),
@@ -427,7 +430,11 @@ function toolResultContentItems(
427430
) {
428431
const parts = decoded ?? decodeResultParts(message);
429432
if (!parts) {
430-
const text = typeof message.content === "string" ? message.content : "";
433+
const raw = typeof message.content === "string" ? message.content : "";
434+
// #1920/#1866: empty or failure-state Computer Use / node_repl results are
435+
// normalized before they reach the native wire (isError is applied in
436+
// toolResultPart via normalizedToolResult below).
437+
const { text } = normalizedToolResult(message, raw);
431438
return [create(McpToolResultContentItemSchema, {
432439
content: { case: "text" as const, value: create(McpTextContentSchema, { text }) },
433440
})];
@@ -483,16 +490,30 @@ function toolResultContentItems(
483490
}
484491

485492
function toolResultToText(message: OcxToolResultMessage): string {
493+
const normalized = normalizedToolResult(message, contentToText(message.content));
486494
return [
487495
"[tool_result]",
488496
`call_id: ${message.toolCallId}`,
489497
`name: ${namespacedToolName(message.toolNamespace, message.toolName)}`,
490-
`is_error: ${message.isError}`,
498+
`is_error: ${normalized.isError}`,
491499
"output:",
492-
contentToText(message.content),
500+
normalized.text,
493501
].join("\n");
494502
}
495503

504+
/**
505+
* Shared #1920 normalization entry: pure-text results only. Image-bearing or
506+
* encrypted results pass through untouched (their content is not plain text).
507+
*/
508+
function normalizedToolResult(message: OcxToolResultMessage, text: string): { text: string; isError: boolean } {
509+
if (message.containsEncryptedContent) return { text, isError: message.isError };
510+
return normalizeCursorToolResultText(text, {
511+
toolName: message.toolName,
512+
toolNamespace: message.toolNamespace,
513+
isError: message.isError,
514+
});
515+
}
516+
496517
function argBytes(value: unknown): Uint8Array {
497518
try {
498519
return toBinary(ValueSchema, fromJson(ValueSchema, value as JsonValue));
@@ -546,11 +567,15 @@ function toolCallStep(
546567
}
547568

548569
function toolResultPart(message: OcxToolResultMessage, decoded?: DecodedResultPart[], maxImages?: number) {
570+
const parts = decoded ?? decodeResultParts(message);
571+
const normalizedIsError = parts
572+
? message.isError
573+
: normalizedToolResult(message, typeof message.content === "string" ? message.content : "").isError;
549574
return create(McpToolResultSchema, {
550575
result: {
551576
case: "success",
552577
value: create(McpSuccessSchema, {
553-
isError: message.isError,
578+
isError: normalizedIsError,
554579
content: toolResultContentItems(message, decoded, maxImages),
555580
}),
556581
},
@@ -643,11 +668,15 @@ function conversationTurns(
643668
if (message.role === "toolResult") {
644669
if (!current) continue;
645670
if (externalModel) {
646-
const prefix = message.isError ? "[Tool Error]" : "[Tool Result]";
671+
// #1920/#1866: this external-replay site bypasses toolResultToText, so it
672+
// must consume the normalizer directly — cursor/grok-4.6 is the exact
673+
// reported repro path for empty Computer Use results.
674+
const normalized = normalizedToolResult(message, contentToText(message.content));
675+
const prefix = normalized.isError ? "[Tool Error]" : "[Tool Result]";
647676
current.steps.push(storeCursorBlob(toBinary(ConversationStepSchema, create(ConversationStepSchema, {
648677
message: {
649678
case: "assistantMessage",
650-
value: create(AssistantMessageSchema, { text: `${prefix}\n${contentToText(message.content)}` }),
679+
value: create(AssistantMessageSchema, { text: `${prefix}\n${normalized.text}` }),
651680
},
652681
})), requestScope));
653682
continue;
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/**
2+
* Cursor tool-result normalization for Computer Use / node_repl surfaces (#1920/#1866).
3+
*
4+
* Scoped re-implementation of PR #1920 per the 260818 campaign disposition
5+
* (REDESIGN-SMALL: "apply formatted.text at native toolResultPart + decode test").
6+
* Only empty-output and known-failure-state normalization ships here; screenshot
7+
* stripping and AXTree text compaction from the original PR are deliberately out
8+
* of scope (the native path already bounds step size by real serialized bytes,
9+
* dropping images oldest-first — see toolCallStep in protobuf-request.ts).
10+
*/
11+
12+
const COMPUTER_USE_TOOL_NAMES = new Set([
13+
"node_repl",
14+
"node_repl__js",
15+
"mcp__node_repl__js",
16+
"get_app_state",
17+
"list_apps",
18+
"screenshot",
19+
"computer_use",
20+
]);
21+
22+
function isNodeReplOrComputerUseTool(toolName?: string, toolNamespace?: string): boolean {
23+
if (toolNamespace && (toolNamespace === "mcp__node_repl" || toolNamespace.includes("node_repl") || toolNamespace.includes("computer_use"))) {
24+
return true;
25+
}
26+
if (!toolName) return false;
27+
const lower = toolName.toLowerCase();
28+
if (COMPUTER_USE_TOOL_NAMES.has(lower)) return true;
29+
return lower.startsWith("mcp__node_repl") || lower.startsWith("mcp__computer_use");
30+
}
31+
32+
/** Failure states the Computer Use / node_repl runtime reports as PLAIN TEXT inside a non-error result. */
33+
const RUNTIME_FAILURE_GUIDANCE: ReadonlyArray<{ marker: string; guidance: string }> = [
34+
{
35+
marker: "SkyComputerUseError",
36+
guidance: "The Computer Use runtime rejected this action. Re-check application state with get_app_state before retrying.",
37+
},
38+
{
39+
marker: "sky is not defined",
40+
guidance: "The sky binding is unavailable in this context; Computer Use calls only work inside the privileged node_repl session.",
41+
},
42+
{
43+
marker: "has already been declared",
44+
guidance: "The node_repl session keeps earlier declarations; rename the variable or use var/reassignment instead of redeclaring.",
45+
},
46+
{
47+
marker: "unsupported import in exec",
48+
guidance: "Imports are not available in this exec context; use the injected globals instead.",
49+
},
50+
];
51+
52+
/** Matches exec wrappers whose only payload is an empty-output marker. */
53+
const EMPTY_EXEC_OUTPUT_REGEX = /^(?:(?:Script completed|Script failed|Command finished|Execution finished)[^\n]*\n+)?(?:Wall time[^\n]*\n+)?(?:Output:\s*)?(?:<empty>)?\s*$/;
54+
55+
export interface NormalizedToolResultText {
56+
text: string;
57+
isError: boolean;
58+
/** True when normalization changed either field (lets callers skip work on the common path). */
59+
changed: boolean;
60+
}
61+
62+
/**
63+
* Normalize a Cursor-bound tool-result TEXT payload:
64+
* - blank / empty-exec-wrapper output on Computer Use or node_repl tools becomes an
65+
* actionable error instead of an empty string the model silently accepts;
66+
* - known runtime failure states reported as plain text are marked isError with a
67+
* one-line recovery hint appended.
68+
* Everything else passes through byte-identical.
69+
*/
70+
export function normalizeCursorToolResultText(
71+
text: string,
72+
options: { toolName?: string; toolNamespace?: string; isError?: boolean } = {},
73+
): NormalizedToolResultText {
74+
const isError = options.isError === true;
75+
const computerUse = isNodeReplOrComputerUseTool(options.toolName, options.toolNamespace);
76+
if (computerUse && EMPTY_EXEC_OUTPUT_REGEX.test(text.trim())) {
77+
return {
78+
text: "[empty output: the tool ran but produced no stdout or return value. Verify application state with get_app_state, or make the script emit output.]",
79+
isError: true,
80+
changed: true,
81+
};
82+
}
83+
if (!isError) {
84+
for (const { marker, guidance } of RUNTIME_FAILURE_GUIDANCE) {
85+
if (text.includes(marker)) {
86+
return { text: `${text}\n[recovery: ${guidance}]`, isError: true, changed: true };
87+
}
88+
}
89+
}
90+
return { text, isError, changed: false };
91+
}
92+
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import { describe, expect, test } from "bun:test";
2+
import { create, fromBinary } from "@bufbuild/protobuf";
3+
import { handleCursorNativeKv } from "../src/adapters/cursor/native-exec";
4+
import { encodeCursorRunRequest } from "../src/adapters/cursor/protobuf-request";
5+
import { normalizeCursorToolResultText } from "../src/adapters/cursor/tool-result-normalize";
6+
import {
7+
AgentClientMessageSchema,
8+
ConversationTurnStructureSchema,
9+
ConversationStepSchema,
10+
GetBlobArgsSchema,
11+
KvServerMessageSchema,
12+
} from "../src/adapters/cursor/gen/agent_pb";
13+
import type { OcxMessage } from "../src/types";
14+
15+
function blobData(blobId: Uint8Array): Uint8Array {
16+
const reply = fromBinary(AgentClientMessageSchema, handleCursorNativeKv(create(KvServerMessageSchema, {
17+
id: 1,
18+
message: { case: "getBlobArgs", value: create(GetBlobArgsSchema, { blobId }) },
19+
})));
20+
if (reply.message.case !== "kvClientMessage") throw new Error("not kv");
21+
const kv = reply.message.value;
22+
if (kv.message.case !== "getBlobResult") throw new Error("not blob result");
23+
return kv.message.value.blobData;
24+
}
25+
26+
/** Decode the native-wire McpToolResult attached to the first tool call step. */
27+
function decodedToolResult(bytes: Uint8Array) {
28+
const msg = fromBinary(AgentClientMessageSchema, bytes);
29+
const run = msg.message.case === "runRequest" ? msg.message.value : undefined;
30+
const turnIds = run?.conversationState?.turns ?? [];
31+
for (const turnId of turnIds) {
32+
const turn = fromBinary(ConversationTurnStructureSchema, blobData(turnId));
33+
if (turn.turn.case !== "agentConversationTurn") continue;
34+
for (const stepId of turn.turn.value.steps ?? []) {
35+
const step = fromBinary(ConversationStepSchema, blobData(stepId));
36+
if (step.message.case !== "toolCall") continue;
37+
const tool = step.message.value.tool;
38+
if (tool.case !== "mcpToolCall") continue;
39+
const result = tool.value.result;
40+
if (result?.result.case !== "success") continue;
41+
return result.result.value;
42+
}
43+
}
44+
return undefined;
45+
}
46+
47+
function requestWith(resultContent: string, toolOverrides: Partial<{ toolName: string; toolNamespace?: string; isError: boolean }> = {}) {
48+
const rawMessages: OcxMessage[] = [
49+
{ role: "user", content: "run it", timestamp: 1 },
50+
{
51+
role: "assistant",
52+
model: "cursor/auto",
53+
timestamp: 2,
54+
content: [{ type: "toolCall", id: "call_1", name: toolOverrides.toolName ?? "js", namespace: toolOverrides.toolNamespace ?? "mcp__node_repl", arguments: {} }],
55+
},
56+
{
57+
role: "toolResult",
58+
toolCallId: "call_1",
59+
toolName: toolOverrides.toolName ?? "js",
60+
toolNamespace: "toolNamespace" in toolOverrides ? toolOverrides.toolNamespace : "mcp__node_repl",
61+
content: resultContent,
62+
isError: toolOverrides.isError ?? false,
63+
timestamp: 3,
64+
},
65+
];
66+
return encodeCursorRunRequest({
67+
modelId: "composer-2.5",
68+
conversationId: "cursor_normalize_test",
69+
system: ["You are helpful."],
70+
messages: [{ role: "tool", content: "[tool_result]" }],
71+
rawMessages,
72+
});
73+
}
74+
75+
describe("normalizeCursorToolResultText (#1920/#1866 unit rows)", () => {
76+
test("blank node_repl output becomes an actionable error", () => {
77+
const out = normalizeCursorToolResultText("", { toolName: "js", toolNamespace: "mcp__node_repl" });
78+
expect(out.isError).toBe(true);
79+
expect(out.text).toContain("get_app_state");
80+
});
81+
82+
test("empty exec wrapper (Script completed + <empty>) normalizes for node_repl", () => {
83+
const out = normalizeCursorToolResultText("Script completed\nOutput:\n<empty>", { toolName: "node_repl" });
84+
expect(out.isError).toBe(true);
85+
expect(out.text).toContain("[empty output");
86+
});
87+
88+
test.each([
89+
["SkyComputerUseError: focus lost", "get_app_state"],
90+
["ReferenceError: sky is not defined", "privileged node_repl"],
91+
["SyntaxError: Identifier 'x' has already been declared", "redeclaring"],
92+
["unsupported import in exec", "injected globals"],
93+
])("runtime failure %p is marked as error with guidance", (payload, hint) => {
94+
const out = normalizeCursorToolResultText(payload, { toolName: "js", toolNamespace: "mcp__node_repl" });
95+
expect(out.isError).toBe(true);
96+
expect(out.text).toContain(payload);
97+
expect(out.text).toContain(hint);
98+
});
99+
100+
test("a non-computer-use tool with empty output stays byte-identical", () => {
101+
const out = normalizeCursorToolResultText("", { toolName: "read_file" });
102+
expect(out.changed).toBe(false);
103+
expect(out.text).toBe("");
104+
expect(out.isError).toBe(false);
105+
});
106+
107+
test("ordinary non-empty output on node_repl stays byte-identical", () => {
108+
const out = normalizeCursorToolResultText("42", { toolName: "js", toolNamespace: "mcp__node_repl" });
109+
expect(out.changed).toBe(false);
110+
expect(out.text).toBe("42");
111+
});
112+
113+
test("an already-error result is not double-annotated", () => {
114+
const out = normalizeCursorToolResultText("SkyComputerUseError: x", { toolName: "js", toolNamespace: "mcp__node_repl", isError: true });
115+
expect(out.changed).toBe(false);
116+
expect(out.isError).toBe(true);
117+
});
118+
});
119+
120+
describe("native wire decode (#1920 disposition: formatted text at toolResultPart)", () => {
121+
test("an empty node_repl result decodes as normalized error text with isError=true on the wire", () => {
122+
const result = decodedToolResult(requestWith(""));
123+
expect(result).toBeDefined();
124+
expect(result!.isError).toBe(true);
125+
const first = result!.content[0];
126+
expect(first.content.case).toBe("text");
127+
expect(first.content.case === "text" ? first.content.value.text : "").toContain("[empty output");
128+
});
129+
130+
test("a failure-state node_repl result decodes with recovery guidance and isError=true", () => {
131+
const result = decodedToolResult(requestWith("ReferenceError: sky is not defined"));
132+
expect(result).toBeDefined();
133+
expect(result!.isError).toBe(true);
134+
const first = result!.content[0];
135+
expect(first.content.case === "text" ? first.content.value.text : "").toContain("recovery");
136+
});
137+
138+
test("a normal tool result decodes byte-identical (no normalization side effects)", () => {
139+
const result = decodedToolResult(requestWith("plain output", { toolName: "read_file", toolNamespace: undefined }));
140+
expect(result).toBeDefined();
141+
expect(result!.isError).toBe(false);
142+
const first = result!.content[0];
143+
expect(first.content.case === "text" ? first.content.value.text : "").toBe("plain output");
144+
});
145+
});

0 commit comments

Comments
 (0)