-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathcursor.ts
More file actions
1758 lines (1670 loc) · 65.3 KB
/
Copy pathcursor.ts
File metadata and controls
1758 lines (1670 loc) · 65.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
declare const EdgeRuntime: string | undefined;
/**
* CursorExecutor — talks to Cursor's agent.v1.AgentService/Run endpoint.
*
* cursor-agent (CLI) and the cursor IDE both use this RPC for every model id
* (auto, composer-*, claude-*, gpt-*, gemini-*). The legacy
* aiserver.v1.ChatService/StreamUnifiedChatWithTools rejects "auto" and
* "composer-*" with errors, so we migrated this executor over.
*
* Wire format & schema details live in ../utils/cursorAgentProtobuf.ts.
*/
import { BaseExecutor, mergeUpstreamExtraHeaders } from "./base.ts";
import { PROVIDERS, HTTP_STATUS } from "../config/constants.ts";
import { getAccessToken } from "../services/tokenRefresh.ts";
import {
buildAgentRequestBody,
decodeAgentServerMessage,
decodeExecServerEvent,
decodeKvServerEvent,
encodeRequestContextResponse,
encodeKvGetBlobResult,
encodeKvSetBlobResult,
encodeExecReadRejected,
encodeExecWriteRejected,
encodeExecDeleteRejected,
encodeExecLsRejected,
encodeExecShellRejected,
encodeExecBackgroundShellSpawnRejected,
encodeExecGrepError,
encodeExecFetchError,
encodeExecWriteShellStdinError,
encodeExecDiagnosticsResult,
flattenMessages,
openAIToolsToMcpDefs,
type ChatMessage,
type EncodedImage,
type ExecServerEvent,
type McpToolDefinition,
type OpenAITool,
} from "../utils/cursorAgentProtobuf.ts";
import { resolveCursorImages, extractImageUrls, CursorImageError } from "../utils/cursorImages.ts";
import {
estimateInputTokens,
estimateOutputTokens,
addBufferToUsage,
} from "../utils/usageTracking.ts";
import {
formatCursorAgentClientVersion,
getCursorAgentCliVersion,
} from "../utils/cursorAgentCliVersion.ts";
import { sanitizeErrorMessage } from "../utils/error.ts";
import { generateToolCallId } from "../translator/helpers/toolCallHelper.ts";
import {
parseComposerToolCalls,
createStreamingState,
feedStreamingChunk,
type StreamingState as ComposerStreamingState,
} from "../utils/composerToolCalls.ts";
import { cursorSessionManager, type CursorSession } from "../services/cursorSessionManager.ts";
import {
CursorApiKeyExchangeError,
invalidateCursorSessionToken,
isCursorApiKey,
resolveCursorBearerToken,
stripCursorOAuthTokenPrefix,
} from "../services/cursorApiKeyAuth.ts";
import crypto from "crypto";
import * as fs from "node:fs";
import * as zlib from "node:zlib";
import { promisify } from "node:util";
import { toolChoiceDirectiveLine, buildCursorOutputConstraints } from "./cursor/prompt.ts";
import {
bridgeCursorBuiltinTool,
bridgeCursorNativeTodoWrite,
extractLatestTodoHistory,
selectCursorBridgeTools,
type CursorClientPlatform,
type CursorTodoHistoryItem,
} from "./cursor/builtinToolBridge.ts";
import {
isComposerModel,
visibleComposerContentFromThinking,
composerReasoningRemainder,
} from "./cursor/composer.ts";
import { CursorServerConfigError, resolveCursorAgentUrl } from "./cursor/agentEndpoint.ts";
import {
classifyCursorError,
isCursorBenignCancelError,
resolveCursorEmptyTurnError,
type ClassifiedCursorError,
} from "./cursor/cursorErrors.ts";
import { getActiveSyncedCatalog } from "../../src/lib/db/models/activeSyncedCatalog.ts";
// Composer helpers re-exported for external importers (tests).
export {
isComposerModel,
visibleComposerContentFromThinking,
composerReasoningRemainder,
} from "./cursor/composer.ts";
// Reject reason text aligned with kaitranntt/CLIProxyAPIPlus — proven to
// keep cursor's model from retrying the same built-in tool indefinitely.
// The model adapts and either answers from context or uses declared MCP tools.
const BUILTIN_TOOL_REJECT_REASON =
"Tool not available in this environment. Use the MCP tools provided instead.";
const gunzipAsync = promisify(zlib.gunzip);
// Tool-commit directive — adapted from composer-api's TOOL_SYSTEM_DIRECTIVE.
// composer-2.5 otherwise narrates intent ("Checking the weather...") and ends
// the turn ~20% of the time instead of actually invoking a declared tool. This
// directive, prepended to the user text only when the request declares tools,
// tells the model to commit to the tool call rather than describe it as prose.
const TOOL_COMMIT_DIRECTIVE = [
"You are serving an OpenAI-compatible API request and the client has provided executable tools.",
"When a tool is needed to answer (real-time data, web/search lookups, file or project operations), you MUST issue the actual tool call. Do NOT describe what you are about to do as prose and then stop — call the tool.",
"Answer directly only when no tool is needed.",
"Do not emit duplicate tool calls: call each operation once, then continue after the tool result is returned.",
"Never claim that tools are unavailable.",
].join("\n");
// NOTE: composer-api primes the model into "agent mode" with a fabricated
// prior switch_mode exchange (AGENT_MODE_PRIMER). On OmniRoute's native-tool
// agent endpoint that primer is counterproductive — it references a
// non-existent switch_mode tool and measurably LOWERED the tool-call rate in
// live A/B (56% vs 69%), so it is intentionally not ported.
/**
* Build the ExecClientMessage frame that responds to a built-in tool request.
* Returns null for the request_context handshake (caller handles separately
* to inject MCP tools in Phase 3) and for exec_mcp (model is invoking a
* declared MCP tool — Phase 5 surfaces this as an OpenAI tool_calls delta).
*/
function buildExecRejection(event: ExecServerEvent): Buffer | null {
switch (event.kind) {
case "exec_request_context":
case "exec_mcp":
return null;
case "exec_read":
return encodeExecReadRejected(
event.execMsgId,
event.execId,
event.path,
BUILTIN_TOOL_REJECT_REASON
);
case "exec_write":
return encodeExecWriteRejected(
event.execMsgId,
event.execId,
event.path,
BUILTIN_TOOL_REJECT_REASON
);
case "exec_delete":
return encodeExecDeleteRejected(
event.execMsgId,
event.execId,
event.path,
BUILTIN_TOOL_REJECT_REASON
);
case "exec_ls":
return encodeExecLsRejected(
event.execMsgId,
event.execId,
event.path,
BUILTIN_TOOL_REJECT_REASON
);
case "exec_grep":
return encodeExecGrepError(event.execMsgId, event.execId, BUILTIN_TOOL_REJECT_REASON);
case "exec_diagnostics":
// Diagnostics has no rejection variant — return an empty success.
return encodeExecDiagnosticsResult(event.execMsgId, event.execId);
case "exec_shell":
case "exec_shell_stream":
return encodeExecShellRejected(
event.execMsgId,
event.execId,
event.command,
event.workingDir,
BUILTIN_TOOL_REJECT_REASON
);
case "exec_bg_shell":
return encodeExecBackgroundShellSpawnRejected(
event.execMsgId,
event.execId,
event.command,
event.workingDir,
BUILTIN_TOOL_REJECT_REASON
);
case "exec_fetch":
return encodeExecFetchError(
event.execMsgId,
event.execId,
event.url,
BUILTIN_TOOL_REJECT_REASON
);
case "exec_write_shell_stdin":
return encodeExecWriteShellStdinError(
event.execMsgId,
event.execId,
BUILTIN_TOOL_REJECT_REASON
);
}
}
// Detect cloud environment (Edge runtime, Cloudflare Workers, etc.)
const isCloudEnv = () => {
if (typeof caches !== "undefined" && typeof caches === "object") return true;
if (typeof EdgeRuntime !== "undefined") return true;
return false;
};
// Lazy import http2 (only in Node.js environment)
let http2: typeof import("http2") | null = null;
if (!isCloudEnv()) {
try {
http2 = await import("http2");
} catch {
http2 = null;
}
}
// Phase 10: CURSOR_DEBUG=1 enables verbose streaming debug logs (decoded
// frame summaries, exec router dispatches, session lifecycle events).
// CURSOR_STREAM_DEBUG is kept as a backward-compatible alias.
const CURSOR_DEBUG = process.env.CURSOR_DEBUG === "1" || process.env.CURSOR_STREAM_DEBUG === "1";
const debugLog = (...args: unknown[]) => {
if (CURSOR_DEBUG) console.log(...args);
};
// Phase 8: max wall-clock time before we give up on the upstream and abort
// the stream. Cursor's longest-observed plain chat takes ~90s; tool-using
// turns can be longer. Five minutes is generous but bounded. A malformed env
// value (NaN / non-positive) falls back to the default rather than breaking
// setTimeout.
const CURSOR_STREAM_TIMEOUT_MS = (() => {
const parsed = parseInt(process.env.CURSOR_STREAM_TIMEOUT_MS || "300000", 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : 300000;
})();
// Upper bound on a single Connect-RPC frame. The 4-byte length prefix can
// declare up to 4 GiB; a corrupt or hostile upstream could send a huge length
// that forces driveH2's rolling buffer to grow unbounded (OOM) while it waits
// for bytes that never arrive. Real cursor frames are well under 1 MiB
// (largest observed: a ~13 KB KV blob), so 16 MiB is a generous ceiling that
// turns the failure into a clean stream error instead of memory exhaustion.
const CURSOR_MAX_FRAME_BYTES = 16 * 1024 * 1024;
type CursorHttpResponse = {
status: number;
headers: Record<string, unknown>;
body: Buffer;
};
function tryParseJsonError(payload: Buffer): { message: string; status: number } | null {
if (payload.length < 2 || payload[0] !== 0x7b) return null;
try {
const text = payload.toString("utf8");
if (!text.includes('"error"')) return null;
const parsed = JSON.parse(text);
const err = parsed?.error || {};
const rawMessage =
err?.details?.[0]?.debug?.details?.title ||
err?.details?.[0]?.debug?.details?.detail ||
err?.message ||
(typeof err?.code === "string" ? `${err.code}: ${text}` : text);
const codeHint =
typeof err?.code === "string" &&
!String(rawMessage).toLowerCase().includes(err.code.toLowerCase())
? `${err.code}: ${rawMessage}`
: String(rawMessage);
const classified = classifyCursorError(codeHint);
return { message: classified.message, status: classified.status };
} catch {
return null;
}
}
/** True when the turn produced no client-visible assistant payload. */
function isCursorEmptyTurn(ctx: StreamCtx): boolean {
return (
ctx.totalText.length === 0 &&
ctx.thinkingText.length === 0 &&
ctx.toolCalls.length === 0 &&
!ctx.composerInlineToolCallsEmitted
);
}
// ─── Phase 4: streaming dispatch context ───────────────────────────────────
//
// One StreamCtx flows through a single execute() call. It owns the live
// SSE emission state (responseId, created timestamp, model id, role-chunk
// flag) plus aggregate state (totalText, tokenDelta) needed for the final
// usage chunk and JSON-mode aggregation. Phases 5 (tool calls) and 8
// (end-signal hardening) extend it.
export type StreamCtx = {
responseId: string;
created: number;
model: string;
emit: (chunk: string) => void;
emittedRoleChunk: boolean;
totalText: string;
thinkingText: string;
tokenDelta: number;
// End-signal tracking (Phase 8 hardens this further).
receivedText: boolean;
kvAfterTextSeen: boolean;
endReason: "turn_ended" | "kv_after_text" | "tool_calls" | "server_end" | null;
// Mid-stream JSON error (rare; emitted once with the error code).
midStreamError: { message: string; status: number } | null;
// Phase 5: tool-call indexing for parallel calls. Each McpArgs gets a
// monotonically-increasing index in the OpenAI delta. emittedToolCalls
// tracks how many were emitted so finalizeSseStream picks the right
// finish_reason ("tool_calls" vs "stop").
emittedToolCallIndex: number;
// Captured tool calls (for JSON-mode aggregation). Each entry maps to
// one OpenAI tool_calls[] item.
toolCalls: Array<{
id: string;
name: string;
argumentsJson: string;
}>;
// Phase 6: maps OpenAI tool_call_id → cursor exec info, so a follow-up
// role:"tool" message can be answered on the open h2 stream via
// encodeExecMcpResult.
pendingToolCalls: Map<string, { execMsgId: number; execId: string; toolName: string }>;
// Built-in Cursor tools are bridged to external OpenAI tool calls by first
// rejecting the native request. Their result therefore cannot resume on the
// same h2 stream and must use the existing full-history cold-resume path.
requiresColdResume: boolean;
// Composer thinking-as-content (decolua/9router#1310): tracks how much of
// the visible suffix (after the last `</think>`) has already been streamed
// out as `content` deltas, so we only emit the incremental tail per frame.
composerVisibleEmittedLength: number;
// Composer DeepSeek-format inline tool-call parser state (decolua/9router#1335).
// Null for non-Composer models (no overhead). When set, the streaming parser
// holds back text inside `<|tool▁calls▁begin|>...<|tool▁calls▁end|>` markers
// and emits structured tool_calls SSE chunks once the block closes.
composerToolParserState: ComposerStreamingState | null;
// True once we've emitted structured tool_calls from the inline Composer parser
// (to avoid double-emitting if the block appears in multiple accumulated frames).
composerInlineToolCallsEmitted: boolean;
};
export function newStreamCtx(model: string, emit: (chunk: string) => void): StreamCtx {
return {
responseId: `chatcmpl-cursor-${Date.now()}`,
created: Math.floor(Date.now() / 1000),
model,
emit,
emittedRoleChunk: false,
totalText: "",
thinkingText: "",
tokenDelta: 0,
receivedText: false,
kvAfterTextSeen: false,
endReason: null,
midStreamError: null,
emittedToolCallIndex: 0,
toolCalls: [],
pendingToolCalls: new Map(),
requiresColdResume: false,
composerVisibleEmittedLength: 0,
composerToolParserState: isComposerModel(model) ? createStreamingState() : null,
composerInlineToolCallsEmitted: false,
};
}
function emitChunk(ctx: StreamCtx, delta: object, finishReason: string | null = null) {
const payload = {
id: ctx.responseId,
object: "chat.completion.chunk",
created: ctx.created,
model: ctx.model,
choices: [{ index: 0, delta, finish_reason: finishReason }],
};
ctx.emit(`data: ${JSON.stringify(payload)}\n\n`);
}
/**
* Emit a terminal OpenAI SSE error matching `buildStreamErrorChunks` shape
* (`finish_reason: "error"` + `error.message`) so #8649 sawError stands down
* and Model Test All keeps the classified Cursor message.
*/
export function emitCursorSseError(ctx: StreamCtx, classified: ClassifiedCursorError): void {
const payload = {
id: ctx.responseId,
object: "chat.completion.chunk",
created: ctx.created,
model: ctx.model,
choices: [{ index: 0, delta: {}, finish_reason: "error" }],
error: {
message: classified.message,
type: classified.type,
},
};
ctx.emit(`data: ${JSON.stringify(payload)}\n\n`);
ctx.emit("data: [DONE]\n\n");
}
export function buildCursorUsage(ctx: StreamCtx, body: { messages?: ChatMessage[] }) {
const promptTokens = estimateInputTokens(body);
const completionTokens =
ctx.tokenDelta > 0
? ctx.tokenDelta
: estimateOutputTokens(ctx.totalText.length + ctx.thinkingText.length);
const usage: Record<string, unknown> = {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: promptTokens + completionTokens,
estimated: true,
};
if (ctx.thinkingText.length > 0) {
usage.completion_tokens_details = {
reasoning_tokens: estimateOutputTokens(ctx.thinkingText.length),
};
}
return addBufferToUsage(usage);
}
function emitUsage(ctx: StreamCtx, body: { messages?: ChatMessage[] }) {
// Always emit a usage chunk on the success path — the OpenAI streaming
// contract is that every completed response carries usage. buildCursorUsage
// already degrades cleanly to prompt-only counts when the model produced no
// text/thinking (e.g. an empty turn), so there's no need to skip it. The
// mid-stream-error path in finalizeSseStream returns before calling this, so
// errored responses still don't get a spurious usage chunk.
const usage = buildCursorUsage(ctx, body);
const payload = {
id: ctx.responseId,
object: "chat.completion.chunk",
created: ctx.created,
model: ctx.model,
choices: [],
usage,
};
ctx.emit(`data: ${JSON.stringify(payload)}\n\n`);
}
function emitDone(ctx: StreamCtx) {
ctx.emit("data: [DONE]\n\n");
}
export function inferCursorClientPlatform(
messages: ChatMessage[]
): CursorClientPlatform | undefined {
const systemMessages = messages.filter((message) => message.role === "system");
if (systemMessages.length === 0) return undefined;
const text = flattenMessages(systemMessages);
const platforms = new Set<CursorClientPlatform>();
const metadataPattern =
/\b(?:client\s+)?(?:platform|os|operating\s+system)\s*[:=]\s*["']?(win32|windows|linux|darwin|macos|posix)\b/gi;
for (const match of text.matchAll(metadataPattern)) {
platforms.add(/^(?:win32|windows)$/i.test(match[1]) ? "windows" : "posix");
}
return platforms.size === 1 ? [...platforms][0] : undefined;
}
/** Emit one complete OpenAI-compatible structured tool call. */
function emitStructuredToolCall(
ctx: StreamCtx,
toolName: string,
args: Record<string, unknown>
): string {
if (!ctx.emittedRoleChunk) {
emitChunk(ctx, { role: "assistant", content: "" });
ctx.emittedRoleChunk = true;
}
const idx = ctx.emittedToolCallIndex++;
const openAIToolCallId = generateToolCallId();
const argumentsJson = JSON.stringify(args);
emitChunk(ctx, {
tool_calls: [
{
index: idx,
id: openAIToolCallId,
type: "function",
function: { name: toolName, arguments: "" },
},
],
});
emitChunk(ctx, {
tool_calls: [
{
index: idx,
function: { arguments: argumentsJson },
},
],
});
ctx.toolCalls.push({ id: openAIToolCallId, name: toolName, argumentsJson });
return openAIToolCallId;
}
/**
* Process one decoded Connect-RPC frame payload: dispatch ExecServerMessage
* events (rejection / context ack / mcp_args), decode AgentServerMessage
* interaction updates, and emit OpenAI SSE deltas for any text content.
*
* Returns true if an end-of-response signal was observed.
*
* The h2 `req` (used to write rejection acks back on the same stream) is
* passed via opts so this function works for both the streaming h2 path
* and the buffered fetch fallback (where opts.req is undefined).
*
* Mutates `ackedExecIds` so each exec_id is dispatched exactly once even
* when the same payload is seen multiple times during incremental decoding.
*/
export function processFrame(
payload: Buffer,
ctx: StreamCtx,
ackedExecIds: Set<string>,
opts: {
h2Req?: import("http2").ClientHttp2Stream;
mcpTools?: McpToolDefinition[];
blobStore?: Map<string, Buffer>;
clientPlatform?: CursorClientPlatform;
todoHistory?: CursorTodoHistoryItem[];
} = {}
): void {
// 1. JSON error envelope (Connect-RPC style — usually status > 200).
const jsonError = tryParseJsonError(payload);
if (jsonError) {
if (ctx.totalText.length === 0) {
ctx.midStreamError = jsonError;
ctx.endReason = "server_end";
} else {
// Already streamed content — terminate cleanly.
ctx.endReason = "server_end";
}
return;
}
// 2a. KV server message: cursor requesting a blob (system prompt) or
// saving an assistant turn. We reply on the same stream so the model
// proceeds. The opaque request_metadata is echoed so cursor can match
// request to response.
const kvEvent = decodeKvServerEvent(payload);
if (kvEvent && opts.h2Req) {
if (kvEvent.kind === "kv_get_blob") {
const hex = kvEvent.blobId.toString("hex");
const blob = opts.blobStore?.get(hex) ?? Buffer.alloc(0);
try {
opts.h2Req.write(encodeKvGetBlobResult(kvEvent.kvId, blob, kvEvent.requestMetadata));
} catch (e) {
console.debug(`[CURSOR] KV get_blob write failed:`, e);
}
} else if (kvEvent.kind === "kv_set_blob") {
if (opts.blobStore) {
opts.blobStore.set(kvEvent.blobId.toString("hex"), kvEvent.blobData);
}
try {
opts.h2Req.write(encodeKvSetBlobResult(kvEvent.kvId, kvEvent.requestMetadata));
} catch (e) {
console.debug(`[CURSOR] KV set_blob write failed:`, e);
}
}
}
// 2b. ExecServerMessage dispatch (request_context, built-in rejection, mcp).
// Dedup by kind+execId+execMsgId — request_context and mcp_args both
// arrive with empty execId in the current cursor schema, so a single
// execId-only set would collapse them.
const event = decodeExecServerEvent(payload);
const dedupKey = event ? `${event.kind}:${event.execId}:${event.execMsgId}` : "";
if (event && !ackedExecIds.has(dedupKey)) {
ackedExecIds.add(dedupKey);
if (event.kind === "exec_request_context") {
if (opts.h2Req) {
try {
// Cursor receives tools via AgentRunRequest.mcp_tools (request body)
// — sending them again in the request_context ack causes the
// server to stall silently. Empty ack only.
opts.h2Req.write(encodeRequestContextResponse(event.execMsgId, event.execId));
} catch (e) {
console.debug(`[CURSOR] request_context ack write failed:`, e);
}
}
} else if (event.kind === "exec_mcp") {
// Phase 5: surface the model-invoked MCP tool as an OpenAI tool_calls
// SSE delta. Two chunks are emitted per call: an init chunk with the
// tool's id+name+empty args, then a chunk with the JSON-stringified
// args. Parallel tool calls share one finish chunk (Phase 8 closes).
const openAIToolCallId = emitStructuredToolCall(ctx, event.toolName, event.args ?? {});
// Phase 6: remember the cursor exec ids so a follow-up role:"tool"
// message can be replied with encodeExecMcpResult on the open h2 stream.
ctx.pendingToolCalls.set(openAIToolCallId, {
execMsgId: event.execMsgId,
execId: event.execId,
toolName: event.toolName,
});
// Cursor pauses after mcp_args waiting for the client to either send
// a tool result via ExecMcpResult or close the stream. We mark
// endReason now so driveH2 returns; the session manager keeps the h2
// alive for the next OpenAI call (which arrives with role:"tool").
ctx.endReason = "tool_calls";
} else {
// Cursor/Fable frequently chooses its native Shell tool even when the
// OpenAI client declared external tools. If a schema-compatible shell
// tool exists, surface the native request as a structured OpenAI call.
// We still send the typed rejection upstream, then close this h2 stream;
// the role:"tool" follow-up is resumed cold from the full history.
const bridge = bridgeCursorBuiltinTool(event, opts.mcpTools ?? [], opts.clientPlatform);
const rejection = buildExecRejection(event);
if (rejection && opts.h2Req) {
try {
opts.h2Req.write(rejection);
} catch (e) {
console.debug(`[CURSOR] exec rejection write failed:`, e);
}
}
if (bridge) {
emitStructuredToolCall(ctx, bridge.toolName, bridge.arguments);
ctx.requiresColdResume = true;
ctx.endReason = "tool_calls";
}
}
}
// 3. Interaction update deltas → OpenAI SSE chunks.
let deltas;
try {
deltas = decodeAgentServerMessage(payload);
} catch (err) {
debugLog("[cursor-agent] decode failed:", (err as Error).message);
return;
}
for (const d of deltas) {
if (d.kind === "native_todo_write") {
const dedupKey = `native_todo_write:${d.toolCallId}`;
if (!ackedExecIds.has(dedupKey)) {
ackedExecIds.add(dedupKey);
const bridge = bridgeCursorNativeTodoWrite(d, opts.mcpTools ?? [], opts.todoHistory);
if (bridge) {
emitStructuredToolCall(ctx, bridge.toolName, bridge.arguments);
ctx.requiresColdResume = true;
ctx.endReason = "tool_calls";
}
}
} else if (d.kind === "text" && d.text) {
if (!ctx.emittedRoleChunk) {
emitChunk(ctx, { role: "assistant", content: "" });
ctx.emittedRoleChunk = true;
}
ctx.totalText += d.text;
ctx.receivedText = true;
emitChunk(ctx, { content: d.text });
} else if (d.kind === "thinking" && d.text) {
if (!ctx.emittedRoleChunk) {
emitChunk(ctx, { role: "assistant", content: "" });
ctx.emittedRoleChunk = true;
}
ctx.thinkingText += d.text;
ctx.receivedText = true;
// Composer (decolua/9router#1310) encodes the visible reply inside the
// thinking field, after a final `</think>` marker. Emit the post-marker
// suffix as plain `content` (so OpenAI-compatible clients see the reply)
// and keep the pre-marker chain-of-thought out of `reasoning_content` —
// it was never intended for the user.
if (isComposerModel(ctx.model)) {
const visible = visibleComposerContentFromThinking(ctx.thinkingText);
if (visible.length > ctx.composerVisibleEmittedLength) {
// Feed the full accumulated visible text into the DeepSeek inline
// tool-call streaming parser (decolua/9router#1335). It tracks how
// much has already been safely emitted and returns only the new
// safe delta — i.e. text that precedes any `<|tool▁calls▁begin|>`
// marker (or a partial prefix of one). When the closing marker
// arrives, it sets ready=true and provides the parsed tool_calls.
if (ctx.composerToolParserState) {
const parseOut = feedStreamingChunk(ctx.composerToolParserState, visible);
// composerVisibleEmittedLength tracks what the parser has "emitted"
// — stays in sync via state.emitted.
ctx.composerVisibleEmittedLength = ctx.composerToolParserState.emitted;
if (parseOut.safeDelta) {
ctx.totalText += parseOut.safeDelta;
emitChunk(ctx, { content: parseOut.safeDelta });
}
if (
parseOut.ready &&
parseOut.toolCalls.length > 0 &&
!ctx.composerInlineToolCallsEmitted
) {
ctx.composerInlineToolCallsEmitted = true;
for (const tc of parseOut.toolCalls) {
const toolCallIndex = ctx.emittedToolCallIndex++;
ctx.toolCalls.push({
id: tc.id,
name: tc.function.name,
argumentsJson: tc.function.arguments,
});
emitChunk(ctx, {
tool_calls: [
{
index: toolCallIndex,
id: tc.id,
type: "function",
function: { name: tc.function.name, arguments: tc.function.arguments },
},
],
});
}
}
} else {
// Non-composer or state not initialised — fall back to direct emit.
const deltaContent = visible.slice(ctx.composerVisibleEmittedLength);
ctx.composerVisibleEmittedLength = visible.length;
ctx.totalText += deltaContent;
emitChunk(ctx, { content: deltaContent });
}
}
} else {
emitChunk(ctx, { reasoning_content: d.text });
}
} else if (d.kind === "token_delta") {
ctx.tokenDelta += d.tokens;
} else if (d.kind === "turn_ended") {
if (ctx.endReason !== "tool_calls") ctx.endReason = "turn_ended";
} else if (d.kind === "tool_call_completed" && ctx.toolCalls.length > 0) {
// Phase 6: model paused awaiting tool result. driveH2 returns but the
// h2 stream stays open — the session manager keeps it alive for the
// next OpenAI call (which will arrive with role:"tool" results).
ctx.endReason = "tool_calls";
} else if (
d.kind === "kv_server_message" &&
ctx.receivedText &&
ctx.endReason !== "tool_calls"
) {
// Cursor short-circuits turn_ended for plain chats — kv_server_message
// after text means the model finished and the server is saving the
// turn. Phase 8 keeps both signals as defense-in-depth.
//
// Safe vs tool calls (composer family only): when the model invokes a
// tool, the exec_mcp event always arrives at or before this kv
// checkpoint (verified across many live composer-2.5 trials — a tool call
// never follows kv_after_text), so endReason is already "tool_calls" by
// the time we get here. Ending on kv_after_text therefore never truncates
// a pending tool call on composer.
//
// Non-composer models (cursor/grok-4.5-high, auto, ...) emit the KV
// checkpoint as a blob-store side-channel frame (envelope field 4,
// kv_get_blob/kv_set_blob) with NO turn-completion semantics, and it can
// arrive while the model is still streaming a long preamble BEFORE a
// pending exec_mcp. Ending the turn there drops that exec_mcp, leaving a
// narration-only finish_reason "stop" with zero tool_calls (#10215). On
// this family only the real terminal signals (turn_ended,
// tool_call_completed, server_end) decide — kvAfterTextSeen is kept purely
// as an observational flag, never as the turn terminator.
ctx.kvAfterTextSeen = true;
if (isComposerModel(ctx.model)) {
ctx.endReason = "kv_after_text";
}
}
}
}
export class CursorExecutor extends BaseExecutor {
constructor(provider: "cursor" | "cursor-api" = "cursor") {
super(provider, PROVIDERS[provider]);
}
buildUrl() {
return PROVIDERS.cursor.baseUrl;
}
/**
* API-key connections carry a `crsr_…` key that api2.cursor.sh does not
* accept as a Bearer; swap it for the exchanged session token before the
* h2 stream is opened. OAuth/IDE-session connections pass through untouched.
*/
async resolveExecutionCredentials(credentials) {
if (!isCursorApiKey(credentials?.apiKey)) return credentials;
try {
const accessToken = await resolveCursorBearerToken(credentials);
return { ...credentials, accessToken };
} catch (err) {
const status =
err instanceof CursorApiKeyExchangeError ? err.status : HTTP_STATUS.SERVER_ERROR;
const message = err instanceof Error ? err.message : String(err);
return new Response(
JSON.stringify({
error: {
message: sanitizeErrorMessage(message),
type: status === HTTP_STATUS.UNAUTHORIZED ? "authentication_error" : "connection_error",
code: "",
},
}),
{ status, headers: { "Content-Type": "application/json" } }
);
}
}
buildHeaders(credentials) {
const ghostMode = credentials.providerSpecificData?.ghostMode !== false;
const cleanToken = stripCursorOAuthTokenPrefix(credentials.accessToken ?? "");
const requestId = crypto.randomUUID();
const traceParent = `00-${crypto.randomBytes(16).toString("hex")}-${crypto.randomBytes(8).toString("hex")}-01`;
// Mirrors cursor-agent's actual headers for agent.v1.AgentService/Run.
// Notably: no x-cursor-checksum, no machineId, no x-amzn-trace-id.
// Only advertise gzip (not brotli) — our Connect-RPC frame decoder
// only handles gzip-compressed message bodies.
return {
authorization: `Bearer ${cleanToken}`,
"backend-traceparent": traceParent,
"connect-accept-encoding": "gzip",
"connect-protocol-version": "1",
"content-type": "application/connect+proto",
traceparent: traceParent,
"user-agent": "connect-es/1.6.1",
"x-cursor-client-type": "cli",
"x-cursor-client-version": formatCursorAgentClientVersion(getCursorAgentCliVersion()),
"x-ghost-mode": ghostMode ? "true" : "false",
"x-original-request-id": requestId,
"x-request-id": requestId,
};
}
/**
* Build the request body and return it alongside the request-scoped
* blobStore. cursor's models (auto, claude-*, gpt-*) don't reliably
* follow system-role content delivered via the KV blob channel — even
* though the blob is requested and our reply is accepted, the model
* proceeds without applying the prompt.
*
* As a pragmatic workaround we prepend the system content into the
* UserMessage text (the pre-Phase-7 behavior). The KV-blob handshake
* machinery is still in place for any future schema where cursor honors
* root_prompt_messages_json semantically — verified end-to-end with
* wire-tap captures.
*/
/**
* Assemble the user text + resolved tools shared by the sync (transformRequest)
* and async (buildRequest) request builders. Image resolution is intentionally
* NOT done here — it's async and only the cold-path buildRequest needs it.
*/
private assembleTextAndTools(body: {
messages?: ChatMessage[];
tools?: unknown;
tool_choice?: unknown;
max_tokens?: unknown;
max_completion_tokens?: unknown;
stop?: unknown;
response_format?: unknown;
}): { userText: string; tools: OpenAITool[] | undefined } {
const messages: ChatMessage[] = body.messages || [];
const declaredTools: OpenAITool[] | undefined = Array.isArray(body.tools)
? (body.tools as OpenAITool[])
: undefined;
// tool_choice:"none" means "do not call any tool" — honor it by advertising
// no tools at all (matches OpenAI semantics; composer-api does the same).
const tools = body.tool_choice === "none" ? undefined : declaredTools;
// flattenMessages prepends any role:"system" messages into the user
// text (proven path that cursor's models honor). Image parts in the content
// are ignored here (they carry no text) and resolved separately.
let userText = flattenMessages(messages);
// When the request declares tools, prepend the tool-commit directive so
// composer-2.5 reliably invokes them instead of narrating intent and
// stopping. Measured live: tool-call rate ~53% → ~88% with the directive.
// tool_choice "required"/specific-function add a forcing line on top.
// Default-on; set CURSOR_TOOL_DIRECTIVE=0 to opt out. See TOOL_COMMIT_DIRECTIVE.
if (tools && tools.length > 0 && process.env.CURSOR_TOOL_DIRECTIVE !== "0") {
userText = `${TOOL_COMMIT_DIRECTIVE}${toolChoiceDirectiveLine(body.tool_choice)}\n\n${userText}`;
}
// Surface OpenAI output params cursor ignores natively (response_format /
// max_tokens / stop) as trailing prompt constraints.
userText += buildCursorOutputConstraints(body);
return { userText, tools };
}
/**
* Resolve any OpenAI image_url parts in the request's user messages into
* inlined cursor images. Returns undefined when the request carries no
* images (keeps the request byte-identical to the text-only path). Throws
* CursorImageError on invalid / oversized / SSRF-blocked input.
*/
private async resolveRequestImages(body: {
messages?: ChatMessage[];
}): Promise<EncodedImage[] | undefined> {
const messages: ChatMessage[] = body.messages || [];
const imageUrls: string[] = [];
for (const m of messages) {
// Images only ride on user turns (the openai-to-cursor translator keeps
// them only there). System/assistant/tool turns carry no vision input.
if (m.role === "user") {
for (const u of extractImageUrls(m.content)) imageUrls.push(u);
}
}
if (imageUrls.length === 0) return undefined;
return resolveCursorImages(imageUrls);
}
/**
* Exact ids from the active Cursor synced catalog. Empty/unavailable →
* undefined so resolveRequestedModel keeps #7289 offline splitting.
*/
private async loadLiveCatalogIds(): Promise<ReadonlySet<string> | undefined> {
try {
const catalog = await getActiveSyncedCatalog(this.provider);
if (!catalog.models.length) return undefined;
return new Set(catalog.models.map((model) => model.id));
} catch {
return undefined;
}
}
private async buildRequest(
model: string,
body: {
messages?: ChatMessage[];
tools?: unknown;
tool_choice?: unknown;
conversation_id?: string;
max_tokens?: unknown;
max_completion_tokens?: unknown;
stop?: unknown;
response_format?: unknown;
}
): Promise<{ body: Uint8Array; blobStore: Map<string, Buffer> }> {
const { userText, tools } = this.assembleTextAndTools(body);
const [images, liveCatalogIds] = await Promise.all([
this.resolveRequestImages(body),
this.loadLiveCatalogIds(),
]);
const blobStore = new Map<string, Buffer>();
const requestBody = buildAgentRequestBody({
modelId: model,
userText,
conversationId: body.conversation_id,
tools,
blobStore,
images,
liveCatalogIds,
});
return { body: requestBody, blobStore };
}
transformRequest(model, body, _stream, _credentials) {
// Sync interface method (not used by cursor's own execute() path, which
// uses the async buildRequest). Text-only — image resolution is async.
const { userText, tools } = this.assembleTextAndTools(body);
const blobStore = new Map<string, Buffer>();
return buildAgentRequestBody({
modelId: model,
userText,
conversationId: body.conversation_id,
tools,
blobStore,
});
}
// ─── h2 lifecycle: open + drive (Phase 4 streaming refactor) ─────────────
//
// openH2 establishes the bidirectional stream and waits for the response
// headers (so we can decide whether to commit to a streaming SSE Response
// or return an error). driveH2 then consumes data events incrementally,
// dispatching frames through processFrame so SSE chunks land on the
// ReadableStream controller as the upstream produces them.
//
// The fetch fallback (cloud envs without http2) preserves the legacy
// buffer-then-decode behavior — Connect-RPC bidirectional ack-on-same-stream
// can't run over a one-shot fetch anyway.
private async openH2(
url: string,
headers: Record<string, string>,
body: Uint8Array,
signal?: AbortSignal
): Promise<{
status: number;
headers: Record<string, string | number>;
client: import("http2").ClientHttp2Session;
req: import("http2").ClientHttp2Stream;
initialBytes: Buffer;
consumeError: () => Promise<Buffer>;
}> {
if (!http2) throw new Error("http2 module not available");
return new Promise((resolve, reject) => {
const urlObj = new URL(url);
const client = http2!.connect(`https://${urlObj.host}`);
const earlyChunks: Buffer[] = [];
let resolved = false;
client.on("error", (err) => {
if (!resolved) reject(err);
});
const req = client.request({
":method": "POST",
":path": urlObj.pathname,
":authority": urlObj.host,
":scheme": "https",
...headers,
});
const onAbort = () => {
try {