-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathcursor_executor.go
More file actions
1796 lines (1627 loc) · 61.2 KB
/
Copy pathcursor_executor.go
File metadata and controls
1796 lines (1627 loc) · 61.2 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
package executor
import (
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"github.com/google/uuid"
cursorauth "github.com/router-for-me/CLIProxyAPI/v7/internal/auth/cursor"
cursorproto "github.com/router-for-me/CLIProxyAPI/v7/internal/auth/cursor/proto"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/executor"
sdktranslator "github.com/router-for-me/CLIProxyAPI/v7/sdk/translator"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"golang.org/x/net/http2"
)
const (
cursorAPIURL = "https://api2.cursor.sh"
cursorRunPath = "/agent.v1.AgentService/Run"
cursorModelsPath = "/agent.v1.AgentService/GetUsableModels"
cursorClientVersion = "cli-2026.02.13-41ac335"
cursorAuthType = "cursor"
cursorHeartbeatInterval = 5 * time.Second
cursorSessionTTL = 5 * time.Minute
cursorCheckpointTTL = 30 * time.Minute
)
// CursorExecutor handles requests to the Cursor API via Connect+Protobuf protocol.
type CursorExecutor struct {
cfg *config.Config
mu sync.Mutex
sessions map[string]*cursorSession
checkpoints map[string]*savedCheckpoint // keyed by conversationId
}
// savedCheckpoint stores the server's conversation_checkpoint_update for reuse.
type savedCheckpoint struct {
data []byte // raw ConversationStateStructure protobuf bytes
blobStore map[string][]byte // blobs referenced by the checkpoint
authID string // auth that produced this checkpoint (checkpoint is auth-specific)
updatedAt time.Time
}
type cursorSession struct {
stream *cursorproto.H2Stream
blobStore map[string][]byte
mcpTools []cursorproto.McpToolDef
pending []pendingMcpExec
cancel context.CancelFunc // cancels the session-scoped heartbeat (NOT tied to HTTP request)
createdAt time.Time
authID string // auth file ID that created this session (for multi-account isolation)
toolResultCh chan []toolResultInfo // receives tool results from the next HTTP request
resumeOutCh chan cliproxyexecutor.StreamChunk // output channel for resumed response
switchOutput func(ch chan cliproxyexecutor.StreamChunk) // callback to switch output channel
}
type pendingMcpExec struct {
ExecMsgId uint32
ExecId string
ToolCallId string
ToolName string
Args string // JSON-encoded args
}
// NewCursorExecutor constructs a new executor instance.
func NewCursorExecutor(cfg *config.Config) *CursorExecutor {
e := &CursorExecutor{
cfg: cfg,
sessions: make(map[string]*cursorSession),
checkpoints: make(map[string]*savedCheckpoint),
}
go e.cleanupLoop()
return e
}
// Identifier implements ProviderExecutor.
func (e *CursorExecutor) Identifier() string { return cursorAuthType }
// CloseExecutionSession implements ExecutionSessionCloser.
func (e *CursorExecutor) CloseExecutionSession(sessionID string) {
e.mu.Lock()
defer e.mu.Unlock()
if sessionID == cliproxyauth.CloseAllExecutionSessionsID {
for k, s := range e.sessions {
s.cancel()
delete(e.sessions, k)
}
return
}
if s, ok := e.sessions[sessionID]; ok {
s.cancel()
delete(e.sessions, sessionID)
}
}
func (e *CursorExecutor) cleanupLoop() {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for range ticker.C {
e.mu.Lock()
for k, s := range e.sessions {
if time.Since(s.createdAt) > cursorSessionTTL {
s.cancel()
delete(e.sessions, k)
}
}
for k, cp := range e.checkpoints {
if time.Since(cp.updatedAt) > cursorCheckpointTTL {
delete(e.checkpoints, k)
}
}
e.mu.Unlock()
}
}
// findSessionByConversationLocked searches for a session matching the given
// conversationId regardless of authID. Used to find and clean up stale sessions
// from a previous auth after quota failover. Caller must hold e.mu.
func (e *CursorExecutor) findSessionByConversationLocked(convId string) string {
suffix := ":" + convId
for k := range e.sessions {
if strings.HasSuffix(k, suffix) {
return k
}
}
return ""
}
// cursorStatusErr implements the StatusError and RetryAfter interfaces so the
// conductor can classify Cursor errors (e.g. 429 → quota cooldown).
type cursorStatusErr struct {
code int
msg string
}
func (e cursorStatusErr) Error() string { return e.msg }
func (e cursorStatusErr) StatusCode() int { return e.code }
func (e cursorStatusErr) RetryAfter() *time.Duration { return nil } // no retry-after info from Cursor; conductor uses exponential backoff
// classifyCursorError maps Cursor Connect/H2 errors to HTTP status codes.
// Layer 1: precise match on ConnectError.Code (gRPC standard codes).
// Layer 2: fuzzy string match for H2 frame errors and unknown formats.
// Unclassified errors pass through unchanged.
func classifyCursorError(err error) error {
if err == nil {
return nil
}
// Layer 1: structured ConnectError from ParseConnectEndStream
var ce *cursorproto.ConnectError
if errors.As(err, &ce) {
log.Infof("cursor: Connect error code=%q message=%q", ce.Code, ce.Message)
switch ce.Code {
case "resource_exhausted":
return cursorStatusErr{code: 429, msg: err.Error()}
case "unauthenticated":
return cursorStatusErr{code: 401, msg: err.Error()}
case "permission_denied":
return cursorStatusErr{code: 403, msg: err.Error()}
case "unavailable":
return cursorStatusErr{code: 503, msg: err.Error()}
case "internal":
return cursorStatusErr{code: 500, msg: err.Error()}
default:
// Unknown Connect code — log for observation, treat as 502
return cursorStatusErr{code: 502, msg: err.Error()}
}
}
// Layer 2: fuzzy match for H2 errors and unstructured messages
msg := strings.ToLower(err.Error())
switch {
case strings.Contains(msg, "rate limit") || strings.Contains(msg, "quota") ||
strings.Contains(msg, "too many"):
return cursorStatusErr{code: 429, msg: err.Error()}
case strings.Contains(msg, "rst_stream") || strings.Contains(msg, "goaway"):
return cursorStatusErr{code: 502, msg: err.Error()}
}
return err
}
// PrepareRequest implements ProviderExecutor (for HttpRequest support).
func (e *CursorExecutor) PrepareRequest(req *http.Request, auth *cliproxyauth.Auth) error {
token := cursorAccessToken(auth)
if token == "" {
return fmt.Errorf("cursor: access token not found")
}
req.Header.Set("Authorization", "Bearer "+token)
return nil
}
// HttpRequest injects credentials and executes the request.
func (e *CursorExecutor) HttpRequest(ctx context.Context, auth *cliproxyauth.Auth, req *http.Request) (*http.Response, error) {
if req == nil {
return nil, fmt.Errorf("cursor: request is nil")
}
if err := e.PrepareRequest(req, auth); err != nil {
return nil, err
}
return http.DefaultClient.Do(req)
}
// CountTokens estimates token count locally using tiktoken.
func (e *CursorExecutor) CountTokens(_ context.Context, _ *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) {
defer func() {
if err != nil {
log.Warnf("cursor CountTokens error: %v", err)
} else {
log.Debugf("cursor CountTokens: model=%s result=%s", req.Model, string(resp.Payload))
}
}()
model := gjson.GetBytes(req.Payload, "model").String()
if model == "" {
model = req.Model
}
enc, err := getTokenizer(model)
if err != nil {
// Fallback: return zero tokens rather than error (avoids 502)
return cliproxyexecutor.Response{Payload: buildOpenAIUsageJSON(0)}, nil
}
// Detect format: Claude (/v1/messages) vs OpenAI (/v1/chat/completions)
var count int64
if gjson.GetBytes(req.Payload, "system").Exists() || opts.SourceFormat.String() == "claude" {
count, _ = countClaudeChatTokens(enc, req.Payload)
} else {
count, _ = countOpenAIChatTokens(enc, req.Payload)
}
return cliproxyexecutor.Response{Payload: buildOpenAIUsageJSON(count)}, nil
}
// Refresh attempts to refresh the Cursor access token.
func (e *CursorExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
refreshToken := cursorRefreshToken(auth)
if refreshToken == "" {
return nil, fmt.Errorf("cursor: no refresh token available")
}
tokens, err := cursorauth.RefreshToken(ctx, refreshToken)
if err != nil {
return nil, err
}
expiresAt := cursorauth.GetTokenExpiry(tokens.AccessToken)
newAuth := auth.Clone()
newAuth.Metadata["access_token"] = tokens.AccessToken
newAuth.Metadata["refresh_token"] = tokens.RefreshToken
newAuth.Metadata["expires_at"] = expiresAt.Format(time.RFC3339)
return newAuth, nil
}
// Execute handles non-streaming requests.
func (e *CursorExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) {
log.Debugf("cursor Execute: model=%s sourceFormat=%s payloadLen=%d", req.Model, opts.SourceFormat, len(req.Payload))
defer func() {
if r := recover(); r != nil {
log.Errorf("cursor Execute PANIC: %v", r)
err = fmt.Errorf("cursor: internal panic: %v", r)
}
if err != nil {
log.Warnf("cursor Execute error: %v", err)
}
}()
accessToken := cursorAccessToken(auth)
if accessToken == "" {
return resp, fmt.Errorf("cursor: access token not found")
}
// Translate input to OpenAI format if needed (e.g. Claude /v1/messages format)
from := opts.SourceFormat
to := sdktranslator.FromString("openai")
payload := req.Payload
if from.String() != "" && from.String() != "openai" {
payload = sdktranslator.TranslateRequest(from, to, req.Model, bytes.Clone(payload), false)
}
parsed := parseOpenAIRequest(payload)
ccSessId := extractClaudeCodeSessionId(req.Payload)
conversationId := deriveConversationId(apiKeyFromContext(ctx), ccSessId, parsed.SystemPrompt)
params := buildRunRequestParams(parsed, conversationId, req.Model)
requestBytes := cursorproto.EncodeRunRequest(params)
framedRequest := cursorproto.FrameConnectMessage(requestBytes, 0)
stream, err := openCursorH2Stream(accessToken)
if err != nil {
return resp, err
}
defer stream.Close()
// Send the request frame
if err := stream.Write(framedRequest); err != nil {
return resp, fmt.Errorf("cursor: failed to send request: %w", err)
}
// Start heartbeat
sessionCtx, sessionCancel := context.WithCancel(ctx)
defer sessionCancel()
go cursorH2Heartbeat(sessionCtx, stream)
// Collect full text from streaming response
var fullText strings.Builder
if streamErr := processH2SessionFrames(sessionCtx, stream, params.BlobStore, nil,
func(text string, isThinking bool) {
fullText.WriteString(text)
},
nil,
nil,
nil, // tokenUsage - non-streaming
nil, // onCheckpoint - non-streaming doesn't persist
); streamErr != nil && fullText.Len() == 0 {
return resp, classifyCursorError(fmt.Errorf("cursor: stream error: %w", streamErr))
}
id := "chatcmpl-" + uuid.New().String()[:28]
created := time.Now().Unix()
openaiResp := fmt.Sprintf(`{"id":"%s","object":"chat.completion","created":%d,"model":"%s","choices":[{"index":0,"message":{"role":"assistant","content":%s},"finish_reason":"stop"}],"usage":{"prompt_tokens":0,"completion_tokens":0,"total_tokens":0}}`,
id, created, parsed.Model, jsonString(fullText.String()))
// Translate response back to source format if needed
result := []byte(openaiResp)
if from.String() != "" && from.String() != "openai" {
var param any
result = sdktranslator.TranslateNonStream(ctx, to, from, req.Model, bytes.Clone(opts.OriginalRequest), payload, result, ¶m)
}
resp.Payload = result
return resp, nil
}
// ExecuteStream handles streaming requests.
// It supports MCP tool call sessions: when Cursor returns an MCP tool call,
// the H2 stream is kept alive. When Claude Code returns the tool result in
// the next request, the result is sent back on the same stream (session resume).
// This mirrors the activeSessions/resumeWithToolResults pattern in cursor-fetch.ts.
func (e *CursorExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (_ *cliproxyexecutor.StreamResult, err error) {
log.Debugf("cursor ExecuteStream: model=%s sourceFormat=%s payloadLen=%d", req.Model, opts.SourceFormat, len(req.Payload))
defer func() {
if r := recover(); r != nil {
log.Errorf("cursor ExecuteStream PANIC: %v", r)
err = fmt.Errorf("cursor: internal panic: %v", r)
}
if err != nil {
log.Warnf("cursor ExecuteStream error: %v", err)
}
}()
accessToken := cursorAccessToken(auth)
if accessToken == "" {
return nil, fmt.Errorf("cursor: access token not found")
}
// Extract session_id from metadata BEFORE translation (translation strips metadata)
ccSessionId := extractClaudeCodeSessionId(req.Payload)
if ccSessionId == "" && len(opts.OriginalRequest) > 0 {
ccSessionId = extractClaudeCodeSessionId(opts.OriginalRequest)
}
// Translate input to OpenAI format if needed
from := opts.SourceFormat
to := sdktranslator.FromString("openai")
payload := req.Payload
originalPayload := bytes.Clone(req.Payload)
if len(opts.OriginalRequest) > 0 {
originalPayload = bytes.Clone(opts.OriginalRequest)
}
if from.String() != "" && from.String() != "openai" {
log.Debugf("cursor: translating request from %s to openai", from)
payload = sdktranslator.TranslateRequest(from, to, req.Model, bytes.Clone(payload), true)
log.Debugf("cursor: translated payload len=%d", len(payload))
}
parsed := parseOpenAIRequest(payload)
log.Debugf("cursor: parsed request: model=%s userText=%d chars, turns=%d, tools=%d, toolResults=%d",
parsed.Model, len(parsed.UserText), len(parsed.Turns), len(parsed.Tools), len(parsed.ToolResults))
conversationId := deriveConversationId(apiKeyFromContext(ctx), ccSessionId, parsed.SystemPrompt)
authID := auth.ID // e.g. "cursor.json" or "cursor-account2.json"
log.Debugf("cursor: conversationId=%s authID=%s", conversationId, authID)
// Session key includes authID (H2 stream is auth-specific, not transferable).
// Checkpoint key uses conversationId only — allows detecting auth migration.
sessionKey := authID + ":" + conversationId
checkpointKey := conversationId
needsTranslate := from.String() != "" && from.String() != "openai"
// Check if we can resume an existing session with tool results
if len(parsed.ToolResults) > 0 {
e.mu.Lock()
session, hasSession := e.sessions[sessionKey]
if hasSession {
delete(e.sessions, sessionKey)
}
// If no session found for current auth, check for stale sessions from
// a different auth on the same conversation (quota failover scenario).
// Clean them up since the H2 stream belongs to the old account.
if !hasSession {
if oldKey := e.findSessionByConversationLocked(conversationId); oldKey != "" {
oldSession := e.sessions[oldKey]
log.Infof("cursor: cleaning up stale session from auth %s for conv=%s (auth migrated to %s)", oldSession.authID, conversationId, authID)
oldSession.cancel()
if oldSession.stream != nil {
oldSession.stream.Close()
}
delete(e.sessions, oldKey)
}
}
e.mu.Unlock()
if hasSession && session.stream != nil && session.authID == authID {
log.Debugf("cursor: resuming session %s with %d tool results", sessionKey, len(parsed.ToolResults))
return e.resumeWithToolResults(ctx, session, parsed, from, to, req, originalPayload, payload, needsTranslate)
}
if hasSession && session.authID != authID {
log.Warnf("cursor: session %s belongs to auth %s, but request is from %s — skipping resume", sessionKey, session.authID, authID)
}
}
// Clean up any stale session for this key (or from a previous auth on same conversation)
e.mu.Lock()
if old, ok := e.sessions[sessionKey]; ok {
old.cancel()
delete(e.sessions, sessionKey)
} else if oldKey := e.findSessionByConversationLocked(conversationId); oldKey != "" {
old := e.sessions[oldKey]
old.cancel()
if old.stream != nil {
old.stream.Close()
}
delete(e.sessions, oldKey)
}
e.mu.Unlock()
// Look up saved checkpoint for this conversation (keyed by conversationId only).
// Checkpoint is auth-specific: if auth changed (e.g. quota exhaustion failover),
// the old checkpoint is useless on the new account — discard and flatten.
e.mu.Lock()
saved, hasCheckpoint := e.checkpoints[checkpointKey]
e.mu.Unlock()
params := buildRunRequestParams(parsed, conversationId, req.Model)
if hasCheckpoint && saved.data != nil && saved.authID == authID {
// Same auth — use checkpoint normally
log.Debugf("cursor: using saved checkpoint (%d bytes) for conv=%s auth=%s", len(saved.data), checkpointKey, authID)
params.RawCheckpoint = saved.data
// Merge saved blobStore into params
if params.BlobStore == nil {
params.BlobStore = make(map[string][]byte)
}
for k, v := range saved.blobStore {
if _, exists := params.BlobStore[k]; !exists {
params.BlobStore[k] = v
}
}
} else if hasCheckpoint && saved.data != nil && saved.authID != authID {
// Auth changed (quota failover) — checkpoint is not portable across accounts.
// Discard and flatten conversation history into userText.
log.Infof("cursor: auth migrated (%s → %s) for conv=%s, discarding checkpoint and flattening context", saved.authID, authID, checkpointKey)
e.mu.Lock()
delete(e.checkpoints, checkpointKey)
e.mu.Unlock()
if len(parsed.ToolResults) > 0 || len(parsed.Turns) > 0 {
flattenConversationIntoUserText(parsed)
params = buildRunRequestParams(parsed, conversationId, req.Model)
}
} else if len(parsed.ToolResults) > 0 || len(parsed.Turns) > 0 {
// Fallback: no checkpoint available (cold resume / proxy restart).
// Flatten the full conversation history (including tool interactions) into userText.
// Cursor's turns encoding is not reliably read by the model, but userText always works.
log.Debugf("cursor: no checkpoint, flattening %d turns + %d tool results into userText", len(parsed.Turns), len(parsed.ToolResults))
flattenConversationIntoUserText(parsed)
params = buildRunRequestParams(parsed, conversationId, req.Model)
}
requestBytes := cursorproto.EncodeRunRequest(params)
framedRequest := cursorproto.FrameConnectMessage(requestBytes, 0)
stream, err := openCursorH2Stream(accessToken)
if err != nil {
return nil, err
}
if err := stream.Write(framedRequest); err != nil {
stream.Close()
return nil, fmt.Errorf("cursor: failed to send request: %w", err)
}
// Use a session-scoped context for the heartbeat that is NOT tied to the HTTP request.
// This ensures the heartbeat survives across request boundaries during MCP tool execution.
// Mirrors the TS plugin's setInterval-based heartbeat that lives independently of HTTP responses.
sessionCtx, sessionCancel := context.WithCancel(context.Background())
go cursorH2Heartbeat(sessionCtx, stream)
chunks := make(chan cliproxyexecutor.StreamChunk, 64)
chatId := "chatcmpl-" + uuid.New().String()[:28]
created := time.Now().Unix()
var streamParam any
// Tool result channel for inline mode. processH2SessionFrames blocks on it
// when mcpArgs is received, while continuing to handle KV/heartbeat.
toolResultCh := make(chan []toolResultInfo, 1)
// Switchable output: initially writes to `chunks`. After mcpArgs, the
// onMcpExec callback closes `chunks` (ending the first HTTP response),
// then processH2SessionFrames blocks on toolResultCh. When results arrive,
// it switches to `resumeOutCh` (created by resumeWithToolResults).
var outMu sync.Mutex
currentOut := chunks
emitToOut := func(chunk cliproxyexecutor.StreamChunk) {
outMu.Lock()
out := currentOut
outMu.Unlock()
if out != nil {
out <- chunk
}
}
// Wrap sendChunk/sendDone to use emitToOut
sendChunkSwitchable := func(delta string, finishReason string) {
fr := "null"
if finishReason != "" {
fr = finishReason
}
openaiJSON := fmt.Sprintf(`{"id":"%s","object":"chat.completion.chunk","created":%d,"model":"%s","choices":[{"index":0,"delta":%s,"finish_reason":%s}]}`,
chatId, created, parsed.Model, delta, fr)
sseLine := []byte("data: " + openaiJSON + "\n")
if needsTranslate {
translated := sdktranslator.TranslateStream(ctx, to, from, req.Model, originalPayload, payload, sseLine, &streamParam)
for _, t := range translated {
emitToOut(cliproxyexecutor.StreamChunk{Payload: bytes.Clone(t)})
}
} else {
emitToOut(cliproxyexecutor.StreamChunk{Payload: []byte(openaiJSON)})
}
}
sendDoneSwitchable := func() {
if needsTranslate {
done := sdktranslator.TranslateStream(ctx, to, from, req.Model, originalPayload, payload, []byte("data: [DONE]\n"), &streamParam)
for _, d := range done {
emitToOut(cliproxyexecutor.StreamChunk{Payload: bytes.Clone(d)})
}
} else {
emitToOut(cliproxyexecutor.StreamChunk{Payload: []byte("[DONE]")})
}
}
// Pre-response error detection for transparent failover:
// If the stream fails before any chunk is emitted (e.g. quota exceeded),
// ExecuteStream returns an error so the conductor retries with a different auth.
streamErrCh := make(chan error, 1)
firstChunkSent := make(chan struct{}, 1) // buffered: goroutine won't block signaling
origEmitToOut := emitToOut
emitToOut = func(chunk cliproxyexecutor.StreamChunk) {
select {
case firstChunkSent <- struct{}{}:
default:
}
origEmitToOut(chunk)
}
go func() {
var resumeOutCh chan cliproxyexecutor.StreamChunk
_ = resumeOutCh
thinkingActive := false
toolCallIndex := 0
usage := &cursorTokenUsage{}
usage.setInputEstimate(len(payload))
streamErr := processH2SessionFrames(sessionCtx, stream, params.BlobStore, params.McpTools,
func(text string, isThinking bool) {
if isThinking {
if !thinkingActive {
thinkingActive = true
sendChunkSwitchable(`{"role":"assistant","content":"<think>"}`, "")
}
sendChunkSwitchable(fmt.Sprintf(`{"content":%s}`, jsonString(text)), "")
} else {
if thinkingActive {
thinkingActive = false
sendChunkSwitchable(`{"content":"</think>"}`, "")
}
sendChunkSwitchable(fmt.Sprintf(`{"content":%s}`, jsonString(text)), "")
}
},
func(exec pendingMcpExec) {
if thinkingActive {
thinkingActive = false
sendChunkSwitchable(`{"content":"</think>"}`, "")
}
toolCallJSON := fmt.Sprintf(`{"tool_calls":[{"index":%d,"id":"%s","type":"function","function":{"name":"%s","arguments":%s}}]}`,
toolCallIndex, exec.ToolCallId, exec.ToolName, jsonString(exec.Args))
toolCallIndex++
sendChunkSwitchable(toolCallJSON, "")
sendChunkSwitchable(`{}`, `"tool_calls"`)
sendDoneSwitchable()
// Close current output to end the current HTTP SSE response
outMu.Lock()
if currentOut != nil {
close(currentOut)
currentOut = nil
}
outMu.Unlock()
// Create new resume output channel, reuse the same toolResultCh
resumeOut := make(chan cliproxyexecutor.StreamChunk, 64)
log.Debugf("cursor: saving session %s for MCP tool resume (tool=%s)", sessionKey, exec.ToolName)
e.mu.Lock()
e.sessions[sessionKey] = &cursorSession{
stream: stream,
blobStore: params.BlobStore,
mcpTools: params.McpTools,
pending: []pendingMcpExec{exec},
cancel: sessionCancel,
createdAt: time.Now(),
authID: authID,
toolResultCh: toolResultCh, // reuse same channel across rounds
resumeOutCh: resumeOut,
switchOutput: func(ch chan cliproxyexecutor.StreamChunk) {
outMu.Lock()
currentOut = ch
// Reset translator state so the new HTTP response gets
// a fresh message_start, content_block_start, etc.
streamParam = nil
// New response needs its own message ID
chatId = "chatcmpl-" + uuid.New().String()[:28]
created = time.Now().Unix()
outMu.Unlock()
},
}
e.mu.Unlock()
resumeOutCh = resumeOut
// processH2SessionFrames will now block on toolResultCh (inline wait loop)
// while continuing to handle KV messages
},
toolResultCh,
usage,
func(cpData []byte) {
// Save checkpoint keyed by conversationId, tagged with authID for migration detection
e.mu.Lock()
e.checkpoints[checkpointKey] = &savedCheckpoint{
data: cpData,
blobStore: params.BlobStore,
authID: authID,
updatedAt: time.Now(),
}
e.mu.Unlock()
log.Debugf("cursor: saved checkpoint (%d bytes) for conv=%s auth=%s", len(cpData), checkpointKey, authID)
},
)
// processH2SessionFrames returned — stream is done.
// Check if error happened before any chunks were emitted.
if streamErr != nil {
select {
case <-firstChunkSent:
// Chunks were already sent to client — can't transparently retry.
// Next request will failover via conductor's cooldown mechanism.
log.Warnf("cursor: stream error after data sent (auth=%s conv=%s): %v", authID, conversationId, streamErr)
default:
// No data sent yet — propagate error for transparent conductor retry.
log.Warnf("cursor: stream error before data sent (auth=%s conv=%s): %v — signaling retry", authID, conversationId, streamErr)
streamErrCh <- streamErr
outMu.Lock()
if currentOut != nil {
close(currentOut)
currentOut = nil
}
outMu.Unlock()
sessionCancel()
stream.Close()
return
}
}
if thinkingActive {
sendChunkSwitchable(`{"content":"</think>"}`, "")
}
// Include token usage in the final stop chunk
inputTok, outputTok := usage.get()
stopDelta := fmt.Sprintf(`{},"usage":{"prompt_tokens":%d,"completion_tokens":%d,"total_tokens":%d}`,
inputTok, outputTok, inputTok+outputTok)
// Build the stop chunk with usage embedded in the choices array level
fr := `"stop"`
openaiJSON := fmt.Sprintf(`{"id":"%s","object":"chat.completion.chunk","created":%d,"model":"%s","choices":[{"index":0,"delta":{},"finish_reason":%s}],"usage":{"prompt_tokens":%d,"completion_tokens":%d,"total_tokens":%d}}`,
chatId, created, parsed.Model, fr, inputTok, outputTok, inputTok+outputTok)
sseLine := []byte("data: " + openaiJSON + "\n")
if needsTranslate {
translated := sdktranslator.TranslateStream(ctx, to, from, req.Model, originalPayload, payload, sseLine, &streamParam)
for _, t := range translated {
emitToOut(cliproxyexecutor.StreamChunk{Payload: bytes.Clone(t)})
}
} else {
emitToOut(cliproxyexecutor.StreamChunk{Payload: []byte(openaiJSON)})
}
sendDoneSwitchable()
_ = stopDelta // unused
// Close whatever output channel is still active
outMu.Lock()
if currentOut != nil {
close(currentOut)
currentOut = nil
}
outMu.Unlock()
sessionCancel()
stream.Close()
}()
// Wait for either the first chunk or a pre-response error.
// If the stream fails before emitting any data (e.g. quota exceeded),
// return an error so the conductor retries with a different auth.
select {
case streamErr := <-streamErrCh:
return nil, classifyCursorError(fmt.Errorf("cursor: stream failed before response: %w", streamErr))
case <-firstChunkSent:
// Data started flowing — return stream to client
return &cliproxyexecutor.StreamResult{Chunks: chunks}, nil
}
}
// resumeWithToolResults injects tool results into the running processH2SessionFrames
// via the toolResultCh channel. The original goroutine from ExecuteStream is still alive,
// blocking on toolResultCh. Once we send the results, it sends the MCP result to Cursor
// and continues processing the response text — all in the same goroutine that has been
// handling KV messages the whole time.
func (e *CursorExecutor) resumeWithToolResults(
ctx context.Context,
session *cursorSession,
parsed *parsedOpenAIRequest,
from, to sdktranslator.Format,
req cliproxyexecutor.Request,
originalPayload, payload []byte,
needsTranslate bool,
) (*cliproxyexecutor.StreamResult, error) {
log.Debugf("cursor: resumeWithToolResults: injecting %d tool results via channel", len(parsed.ToolResults))
if session.toolResultCh == nil {
return nil, fmt.Errorf("cursor: session has no toolResultCh (stale session?)")
}
if session.resumeOutCh == nil {
return nil, fmt.Errorf("cursor: session has no resumeOutCh")
}
log.Debugf("cursor: resumeWithToolResults: switching output to resumeOutCh and injecting results")
// Switch the output channel BEFORE injecting results, so that when
// processH2SessionFrames unblocks and starts emitting text, it writes
// to the resumeOutCh which the new HTTP handler is reading from.
if session.switchOutput != nil {
session.switchOutput(session.resumeOutCh)
}
// Inject tool results — this unblocks the waiting processH2SessionFrames
session.toolResultCh <- parsed.ToolResults
// Return the resumeOutCh for the new HTTP handler to read from
return &cliproxyexecutor.StreamResult{Chunks: session.resumeOutCh}, nil
}
// --- H2Stream helpers ---
func openCursorH2Stream(accessToken string) (*cursorproto.H2Stream, error) {
headers := map[string]string{
":path": cursorRunPath,
"content-type": "application/connect+proto",
"connect-protocol-version": "1",
"te": "trailers",
"authorization": "Bearer " + accessToken,
"x-ghost-mode": "true",
"x-cursor-client-version": cursorClientVersion,
"x-cursor-client-type": "cli",
"x-request-id": uuid.New().String(),
}
return cursorproto.DialH2Stream("api2.cursor.sh", headers)
}
func cursorH2Heartbeat(ctx context.Context, stream *cursorproto.H2Stream) {
ticker := time.NewTicker(cursorHeartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
hb := cursorproto.EncodeHeartbeat()
frame := cursorproto.FrameConnectMessage(hb, 0)
if err := stream.Write(frame); err != nil {
return
}
}
}
}
// --- Response processing ---
// cursorTokenUsage tracks token counts from Cursor's TokenDeltaUpdate messages.
type cursorTokenUsage struct {
mu sync.Mutex
outputTokens int64
inputTokensEst int64 // estimated from request payload size
}
func (u *cursorTokenUsage) addOutput(delta int64) {
u.mu.Lock()
defer u.mu.Unlock()
u.outputTokens += delta
}
func (u *cursorTokenUsage) setInputEstimate(payloadBytes int) {
u.mu.Lock()
defer u.mu.Unlock()
// Rough estimate: ~4 bytes per token for mixed content
u.inputTokensEst = int64(payloadBytes / 4)
if u.inputTokensEst < 1 {
u.inputTokensEst = 1
}
}
func (u *cursorTokenUsage) get() (input, output int64) {
u.mu.Lock()
defer u.mu.Unlock()
return u.inputTokensEst, u.outputTokens
}
func processH2SessionFrames(
ctx context.Context,
stream *cursorproto.H2Stream,
blobStore map[string][]byte,
mcpTools []cursorproto.McpToolDef,
onText func(text string, isThinking bool),
onMcpExec func(exec pendingMcpExec),
toolResultCh <-chan []toolResultInfo, // nil for no tool result injection; non-nil to wait for results
tokenUsage *cursorTokenUsage, // tracks accumulated token usage (may be nil)
onCheckpoint func(data []byte), // called when server sends conversation_checkpoint_update
) error {
var buf bytes.Buffer
rejectReason := "Tool not available in this environment. Use the MCP tools provided instead."
log.Debugf("cursor: processH2SessionFrames started for streamID=%s, waiting for data...", stream.ID())
for {
select {
case <-ctx.Done():
log.Debugf("cursor: processH2SessionFrames exiting: context done")
return ctx.Err()
case data, ok := <-stream.Data():
if !ok {
log.Debugf("cursor: processH2SessionFrames[%s]: exiting: stream data channel closed", stream.ID())
return stream.Err() // may be RST_STREAM, GOAWAY, or nil for clean close
}
// Log first 20 bytes of raw data for debugging
previewLen := min(20, len(data))
log.Debugf("cursor: processH2SessionFrames[%s]: received %d bytes from dataCh, first bytes: %x (%q)", stream.ID(), len(data), data[:previewLen], string(data[:previewLen]))
buf.Write(data)
log.Debugf("cursor: processH2SessionFrames[%s]: buf total=%d", stream.ID(), buf.Len())
// Process all complete frames
for {
currentBuf := buf.Bytes()
if len(currentBuf) == 0 {
break
}
flags, payload, consumed, ok := cursorproto.ParseConnectFrame(currentBuf)
if !ok {
// Log detailed info about why parsing failed
previewLen := min(20, len(currentBuf))
log.Debugf("cursor: incomplete frame in buffer, waiting for more data (buf=%d bytes, first bytes: %x = %q)", len(currentBuf), currentBuf[:previewLen], string(currentBuf[:previewLen]))
break
}
buf.Next(consumed)
log.Debugf("cursor: parsed Connect frame flags=0x%02x payload=%d bytes consumed=%d", flags, len(payload), consumed)
if flags&cursorproto.ConnectEndStreamFlag != 0 {
if err := cursorproto.ParseConnectEndStream(payload); err != nil {
log.Warnf("cursor: connect end stream error: %v", err)
return err // propagate server-side errors (quota, rate limit, etc.)
}
continue
}
msg, err := cursorproto.DecodeAgentServerMessage(payload)
if err != nil {
log.Debugf("cursor: failed to decode server message: %v", err)
continue
}
log.Debugf("cursor: decoded server message type=%d", msg.Type)
switch msg.Type {
case cursorproto.ServerMsgTextDelta:
if msg.Text != "" && onText != nil {
onText(msg.Text, false)
}
case cursorproto.ServerMsgThinkingDelta:
if msg.Text != "" && onText != nil {
onText(msg.Text, true)
}
case cursorproto.ServerMsgThinkingCompleted:
// Handled by caller
case cursorproto.ServerMsgTurnEnded:
log.Debugf("cursor: TurnEnded received, stream will finish")
return nil // clean completion
case cursorproto.ServerMsgHeartbeat:
// Server heartbeat, ignore silently
continue
case cursorproto.ServerMsgCheckpoint:
if onCheckpoint != nil && len(msg.CheckpointData) > 0 {
onCheckpoint(msg.CheckpointData)
}
continue
case cursorproto.ServerMsgTokenDelta:
if tokenUsage != nil && msg.TokenDelta > 0 {
tokenUsage.addOutput(msg.TokenDelta)
}
continue
case cursorproto.ServerMsgKvGetBlob:
blobKey := cursorproto.BlobIdHex(msg.BlobId)
data := blobStore[blobKey]
resp := cursorproto.EncodeKvGetBlobResult(msg.KvId, data)
stream.Write(cursorproto.FrameConnectMessage(resp, 0))
case cursorproto.ServerMsgKvSetBlob:
blobKey := cursorproto.BlobIdHex(msg.BlobId)
blobStore[blobKey] = append([]byte(nil), msg.BlobData...)
resp := cursorproto.EncodeKvSetBlobResult(msg.KvId)
stream.Write(cursorproto.FrameConnectMessage(resp, 0))
case cursorproto.ServerMsgExecRequestCtx:
resp := cursorproto.EncodeExecRequestContextResult(msg.ExecMsgId, msg.ExecId, mcpTools)
stream.Write(cursorproto.FrameConnectMessage(resp, 0))
case cursorproto.ServerMsgExecMcpArgs:
if onMcpExec != nil {
decodedArgs := decodeMcpArgsToJSON(msg.McpArgs)
toolCallId := msg.McpToolCallId
if toolCallId == "" {
toolCallId = uuid.New().String()
}
log.Debugf("cursor: received mcpArgs from server: execMsgId=%d execId=%q toolName=%s toolCallId=%s",
msg.ExecMsgId, msg.ExecId, msg.McpToolName, toolCallId)
pending := pendingMcpExec{
ExecMsgId: msg.ExecMsgId,
ExecId: msg.ExecId,
ToolCallId: toolCallId,
ToolName: msg.McpToolName,
Args: decodedArgs,
}
onMcpExec(pending)
if toolResultCh == nil {
return nil
}
// Inline mode: wait for tool result while handling KV/heartbeat
log.Debugf("cursor: waiting for tool result on channel (inline mode)...")
var toolResults []toolResultInfo
waitLoop:
for {
select {
case <-ctx.Done():
return ctx.Err()
case results, ok := <-toolResultCh:
if !ok {
return nil
}
toolResults = results
break waitLoop
case waitData, ok := <-stream.Data():
if !ok {
return stream.Err()
}
buf.Write(waitData)
for {
cb := buf.Bytes()