-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlanguage-model.ts
More file actions
2255 lines (2160 loc) · 90.6 KB
/
Copy pathlanguage-model.ts
File metadata and controls
2255 lines (2160 loc) · 90.6 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
import fs from "node:fs"
import path from "node:path"
import { createHash } from "node:crypto"
import type { LanguageModelV3, LanguageModelV3CallOptions, LanguageModelV3StreamResult, LanguageModelV3GenerateResult, LanguageModelV3StreamPart, LanguageModelV3Usage, LanguageModelV3FinishReason } from "@ai-sdk/provider"
import type { CreateCursorOptions, CursorRetryOptions } from "./index.js"
import {
bidiRunStream,
CursorRunInterruptedError,
normalizeAgentRunOrigin,
type BidiStream,
} from "./transport/connect.js"
import { trace, traceRequestContextPaths } from "./debug.js"
import { buildRunRequest, buildHeartbeat } from "./protocol/request.js"
import { decodeFramePayload } from "./protocol/framing.js"
import { debugWalkTurnEnded, decodeMessage } from "./protocol/messages.js"
import {
parseExecServerMessage,
buildToolCallPart,
buildExecClientMessages,
buildReadRejectionMessages,
classifyMissingReadTarget,
resolveReadTargetPath,
parseExecIdFromToolCallId,
detectExecVariantField,
buildRequestContextResult,
buildMcpStateResult,
buildCustomWebToolAliases,
extractHostSubagentCatalog,
resolveCustomWebToolAlias,
remapNativeSubagentForCatalog,
remapEditToolsForCatalog,
CUSTOM_WEBFETCH_TOOL,
CUSTOM_WEBSEARCH_TOOL,
type OpencodeToolDef,
type ParsedExecRequest,
} from "./protocol/tools.js"
import { describeCursorExecVariant } from "./protocol/exec-variants.js"
import {
advertisedToolNamesFromDescriptors,
extractExecDisplayCallId,
extractProtobufSubmessage,
listProtobufFieldNumbers,
parseDisplayToolCall,
resolveBridgedOpenCodeToolCall,
} from "./protocol/tool-call-bridge.js"
import { handleKvServerMessage } from "./protocol/kv.js"
import { handleInteractionQuery } from "./protocol/interactions.js"
import { getCheckpoint, setCheckpoint } from "./protocol/checkpoint.js"
import { conversationBlobCount } from "./protocol/blob-store.js"
import {
bindConversationId,
} from "./protocol/conversation-bind.js"
import {
resolveContinuationPolicy,
sessionManager,
type CursorSession,
type Frame,
} from "./session.js"
import {
CursorAuthError,
CursorLocalCancellationError,
CursorProtocolError,
CursorProviderError,
CursorRetryExhaustedError,
CursorServerError,
CursorTransportError,
isTransientGrpcStatus,
retrySuppressedError,
toCursorProviderError,
} from "./errors.js"
import { readCache, cacheFilePath, resolveVariantParameters, paramsImplyMaxMode, extractCursorVariantParameters, resolveCursorWireModelId, type ModelInfo } from "./models.js"
import { buildRequestContext } from "./context/build.js"
import { workspaceRootFromRequestContext } from "./context/env.js"
import { opencodeGlobalCacheDir, setHostCacheDirOverride } from "./context/paths.js"
import { resolveAgentUrl } from "./agent-url.js"
import { CURSOR_API_HOST, CURSOR_COMPACTION_OPTION } from "./shared.js"
import { isCompactionSession } from "./compaction-marker.js"
import { getSessionDirectory } from "./session-directory.js"
import type { SeedHistoryMessage } from "./protocol/request.js"
import {
consumeCursorShellResult,
registerCursorShellCall,
} from "./shell-timeout.js"
import { analyzeReplayFrame, AttemptReplaySafety } from "./replay-safety.js"
import { readAllFieldsStrict } from "./protocol/struct.js"
import {
buildLanguageModelV3UsageFromEstimate,
buildLanguageModelV3UsageFromTurnEnded,
turnEndedCounter,
} from "./usage.js"
let _availableModels: ModelInfo[] | undefined
// mtime of the cache file the last time we loaded it. Compared on each call
// so discoverModels' background refresh is picked up without a process restart.
let _availableModelsMtimeMs = -1
// OpenCode omits tools from compaction calls. Keep the last real catalog per
// session so the new Cursor conversation is still born with tool definitions;
// execution remains disabled for the summary turn itself.
const toolCatalogBySession = new Map<string, OpencodeToolDef[]>()
// A compaction Run uses its own summary-agent system prompt. Its opaque Cursor
// checkpoint must never become the base for the resumed normal agent: doing so
// suppresses OpenCode's compacted prompt/system seed and makes Cursor narrate
// tool use instead of emitting exec requests. Rebase once on the next turn.
const postCompactionRebaseBySession = new Set<string>()
export const MAX_TURN_STATE_SESSIONS = 256
const DEFAULT_RETRY_POLICY = {
maxAttempts: 3,
baseDelayMs: 500,
maxDelayMs: 8_000,
} as const
const MAX_RETRY_ATTEMPTS = 10
const MAX_RETRY_DELAY_MS = 30_000
const RUN_REQUEST_DECODE_FAILED = "CURSOR_RUN_REQUEST_DECODE_FAILED"
const RUN_REQUEST_UNSUPPORTED = "CURSOR_RUN_REQUEST_UNSUPPORTED"
const RUN_REPLY_FAILED = "CURSOR_RUN_REPLY_FAILED"
type ResponseRequiredChannel = "exec" | "kv" | "interaction" | "multiple"
const RESPONSE_REQUIRED_CHANNEL_BY_FIELD = new Map<
number,
Exclude<ResponseRequiredChannel, "multiple">
>([
[2, "exec"],
[4, "kv"],
[7, "interaction"],
])
function responseRequiredChannel(payload: Uint8Array): ResponseRequiredChannel | undefined {
const fields = readAllFieldsStrict(payload)
if (fields) {
const channels = fields
.map((field) => RESPONSE_REQUIRED_CHANNEL_BY_FIELD.get(field.fn))
.filter((channel): channel is Exclude<ResponseRequiredChannel, "multiple"> => !!channel)
if (channels.length > 1) return "multiple"
return channels[0]
}
// Request tags are single-byte because all must-reply top-level fields are <16.
const tag = payload[0]
return tag !== undefined ? RESPONSE_REQUIRED_CHANNEL_BY_FIELD.get(tag >> 3) : undefined
}
export type CursorRetryPolicy = {
maxAttempts: number
baseDelayMs: number
maxDelayMs: number
}
function retryInteger(name: string, value: unknown, fallback: number): number {
const resolved = value === undefined ? fallback : value
if (typeof resolved !== "number" || !Number.isSafeInteger(resolved) || resolved <= 0) {
throw new CursorProtocolError(`Cursor retry ${name} must be a positive integer`)
}
return resolved
}
export function resolveRetryPolicy(options: CursorRetryOptions | undefined): CursorRetryPolicy {
if (options !== undefined && (options === null || typeof options !== "object" || Array.isArray(options))) {
throw new CursorProtocolError("Cursor retry options must be an object")
}
for (const key of Object.keys(options ?? {})) {
if (!["maxAttempts", "baseDelayMs", "maxDelayMs"].includes(key)) {
throw new CursorProtocolError(`Unknown Cursor retry option: ${key}`)
}
}
const maxAttempts = retryInteger("maxAttempts", options?.maxAttempts, DEFAULT_RETRY_POLICY.maxAttempts)
const baseDelayMs = retryInteger("baseDelayMs", options?.baseDelayMs, DEFAULT_RETRY_POLICY.baseDelayMs)
const maxDelayMs = retryInteger("maxDelayMs", options?.maxDelayMs, DEFAULT_RETRY_POLICY.maxDelayMs)
if (maxAttempts > MAX_RETRY_ATTEMPTS) {
throw new CursorProtocolError(`Cursor retry maxAttempts must be no greater than ${MAX_RETRY_ATTEMPTS}`)
}
if (baseDelayMs > MAX_RETRY_DELAY_MS || maxDelayMs > MAX_RETRY_DELAY_MS) {
throw new CursorProtocolError(`Cursor retry delays must be no greater than ${MAX_RETRY_DELAY_MS}ms`)
}
if (baseDelayMs > maxDelayMs) {
throw new CursorProtocolError("Cursor retry baseDelayMs must be no greater than maxDelayMs")
}
return { maxAttempts, baseDelayMs, maxDelayMs }
}
function retryDelayMs(error: CursorProviderError, attempt: number, policy: CursorRetryPolicy): number {
if (error.retryAfterMs !== undefined) return Math.min(MAX_RETRY_DELAY_MS, error.retryAfterMs)
const ceiling = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** Math.max(0, attempt - 1))
return Math.floor(Math.random() * ceiling)
}
function sleepForRetry(delayMs: number, signal?: AbortSignal): Promise<void> {
if (signal?.aborted) return Promise.reject(new CursorLocalCancellationError("Cursor retry cancelled"))
return new Promise((resolve, reject) => {
const timer = setTimeout(finish, delayMs)
const onAbort = () => finish(new CursorLocalCancellationError("Cursor retry cancelled"))
function finish(error?: Error) {
clearTimeout(timer)
signal?.removeEventListener("abort", onAbort)
if (error) reject(error)
else resolve()
}
signal?.addEventListener("abort", onAbort, { once: true })
})
}
function retryDelayFromValue(value: unknown): number | undefined {
if (typeof value === "string") {
const seconds = /^(\d+(?:\.\d+)?)s$/.exec(value.trim())
if (seconds) return Math.ceil(Number(seconds[1]) * 1_000)
const protobufDelay = retryInfoProtobufDelayMs(value.trim())
if (protobufDelay !== undefined) return protobufDelay
}
if (!value || typeof value !== "object") return undefined
const duration = value as { seconds?: unknown; nanos?: unknown }
const seconds = Number(duration.seconds ?? 0)
const nanos = Number(duration.nanos ?? 0)
if (!Number.isFinite(seconds) || !Number.isFinite(nanos) || seconds < 0 || nanos < 0) return undefined
return Math.ceil(seconds * 1_000 + nanos / 1_000_000)
}
/** Decode google.rpc.RetryInfo.value without adding another protobuf schema. */
function retryInfoProtobufDelayMs(encoded: string): number | undefined {
if (!encoded || encoded.length > 512 || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(encoded)) {
return undefined
}
let bytes: Uint8Array
try {
bytes = Buffer.from(encoded.replaceAll("-", "+").replaceAll("_", "/"), "base64")
} catch {
return undefined
}
const readVarint = (input: Uint8Array, start: number): [bigint, number] | undefined => {
let value = 0n
let shift = 0n
for (let offset = start; offset < input.length && offset < start + 10; offset++) {
const byte = input[offset]!
value |= BigInt(byte & 0x7f) << shift
if ((byte & 0x80) === 0) return [value, offset + 1]
shift += 7n
}
return undefined
}
const outerKey = readVarint(bytes, 0)
if (!outerKey || outerKey[0] !== 0x0an) return undefined
const outerLength = readVarint(bytes, outerKey[1])
if (!outerLength || outerLength[0] > BigInt(bytes.length - outerLength[1])) return undefined
const duration = bytes.subarray(
outerLength[1],
outerLength[1] + Number(outerLength[0]),
)
let offset = 0
let seconds = 0n
let nanos = 0n
while (offset < duration.length) {
const key = readVarint(duration, offset)
if (!key) return undefined
offset = key[1]
const field = Number(key[0] >> 3n)
if (Number(key[0] & 7n) !== 0) return undefined
const item = readVarint(duration, offset)
if (!item) return undefined
offset = item[1]
if (field === 1) seconds = item[0]
else if (field === 2) nanos = item[0]
}
if (seconds > BigInt(Number.MAX_SAFE_INTEGER) || nanos > 999_999_999n) return undefined
return Math.ceil(Number(seconds) * 1_000 + Number(nanos) / 1_000_000)
}
export function connectFrameError(payload: string): CursorProviderError {
try {
const envelope = JSON.parse(payload) as {
error?: { code?: unknown; details?: unknown; retryAfter?: unknown; retry_after?: unknown }
}
const code = typeof envelope.error?.code === "string" ? envelope.error.code : "unknown"
if (code === "unauthenticated" || code === "permission_denied") {
return new CursorAuthError(`Cursor authentication failed (${code}); reauthenticate with Cursor`, { code })
}
let retryAfterMs = retryDelayFromValue(
envelope.error?.retryAfter ?? envelope.error?.retry_after,
)
let hasRetryInfo = false
if (Array.isArray(envelope.error?.details)) {
for (const detail of envelope.error.details) {
if (!detail || typeof detail !== "object") continue
const record = detail as Record<string, unknown>
const type = record.type
if (type === "google.rpc.RetryInfo" || (typeof type === "string" && type.endsWith("/google.rpc.RetryInfo"))) {
hasRetryInfo = true
retryAfterMs ??= retryDelayFromValue(
record.retryDelay ?? record.retry_delay ?? record.value,
)
}
}
}
return new CursorServerError(`Cursor API error (code=${code})`, {
transient: isTransientGrpcStatus(code) || hasRetryInfo,
replaySafe: true,
code,
retryAfterMs: retryAfterMs === undefined
? undefined
: Math.min(MAX_RETRY_DELAY_MS, retryAfterMs),
})
} catch {
return new CursorProtocolError("Cursor returned a malformed Connect error envelope")
}
}
function rememberToolCatalog(sessionKey: string, tools: OpencodeToolDef[]): void {
toolCatalogBySession.delete(sessionKey)
toolCatalogBySession.set(sessionKey, tools)
while (toolCatalogBySession.size > MAX_TURN_STATE_SESSIONS) {
const oldest = toolCatalogBySession.keys().next().value as string | undefined
if (!oldest) break
toolCatalogBySession.delete(oldest)
}
}
function rememberPostCompactionRebase(sessionKey: string): void {
postCompactionRebaseBySession.delete(sessionKey)
postCompactionRebaseBySession.add(sessionKey)
while (postCompactionRebaseBySession.size > MAX_TURN_STATE_SESSIONS) {
const oldest = postCompactionRebaseBySession.values().next().value as string | undefined
if (!oldest) break
postCompactionRebaseBySession.delete(oldest)
}
}
type V3Part = LanguageModelV3StreamPart
export function createCursorLanguageModel(
modelId: string,
providerId: string,
options: CreateCursorOptions,
): LanguageModelV3 {
// Host Path.cache / explicit override wins over XDG heuristics for this process.
if (options.cacheDir) setHostCacheDirOverride(options.cacheDir)
return {
specificationVersion: "v3",
provider: providerId,
modelId,
supportedUrls: {},
async doStream(callOptions: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {
return doStreamImpl(modelId, options, callOptions)
},
async doGenerate(callOptions: LanguageModelV3CallOptions): Promise<LanguageModelV3GenerateResult> {
const result = await doStreamImpl(modelId, options, callOptions)
const parts: V3Part[] = []
const reader = result.stream.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) break
parts.push(value)
}
return foldStreamParts(parts)
},
}
}
async function doStreamImpl(
modelId: string,
options: CreateCursorOptions,
callOptions: LanguageModelV3CallOptions,
): Promise<LanguageModelV3StreamResult> {
// A raw `crsr_...` API key must be exchanged for a JWT before it can be used
// as a Bearer token (the plugin path does this in auth.ts). The accessToken
// path is already a JWT from OAuth/key-exchange, so we use it as-is.
// resolveBearerToken caches apiKey exchanges so we don't hit /auth/exchange
// on every turn.
const { resolveBearerToken } = await import("./auth.js")
const token = await resolveBearerToken({
accessToken: options.accessToken,
apiKey: options.apiKey,
baseUrl: resolveApiBaseURL(options),
})
const prompt = callOptions.prompt
const promptTokens = estimatePromptTokens(prompt)
const retryPolicy = resolveRetryPolicy(options.retry)
// pumpWithRecovery owns the complete per-turn attempt budget. Opening a
// replacement session here must be a single attempt; otherwise setup retry
// loops nest inside recovery and `maxAttempts` no longer caps total Runs.
const openSession = (startOptions?: { recovery?: CursorRunRecovery }) =>
startSession(modelId, token, callOptions, options, startOptions)
// ── Continuation vs fresh turn ──
// OpenCode embeds *all* historical tool results in every prompt. Only the
// trailing tool-message suffix (after the last assistant/user message) is a
// live continuation. Treating mid-prompt history as continuation caused
// false "orphaned tool results" errors after Cursor turn_ended and OpenCode
// started the next step with old tools still in the prompt body.
const trailingToolResults = extractTrailingToolResults(prompt)
let session = findContinuationSession(trailingToolResults)
if (session) {
// Write pending results onto the held-open Run. A dead stream closes the
// session and returns undefined so we fall through to history rebase
// instead of pumping a connection that can no longer accept writes.
session = deliverContinuationResults(session, trailingToolResults)
}
if (!session) {
if (trailingToolResults.length > 0) {
// True continuation (prompt ends with tool results) but the held-open Run
// is gone (or its write path just failed). Rebase the complete OpenCode
// prompt onto a fresh conversation: its seed history includes the
// completed tool result, so no result or advertised tool is lost and
// Cursor can continue instead of deadlocking.
const ids = trailingToolResults.map((r) => `${r.sessionId}:${r.execId}`).join(",")
trace(`continuation: ${trailingToolResults.length} interrupted trailing tool result(s) [${ids}] — rebasing fresh Run`)
session = await openSession({ recovery: { kind: "rebase" } })
} else {
// Fresh turn (prompt ends with user/assistant text). Historical tool
// results may exist mid-prompt; they are not live exec replies.
const historical = extractToolResults(prompt).length
if (historical > 0) {
trace(`fresh turn: ignoring ${historical} historical tool result(s) (not trailing)`)
}
session = await openSession()
}
}
let activeSession = session
return {
stream: new ReadableStream<V3Part>({
async pull(controller) {
// The outer try is a safety net for any throw that escapes pump() —
// e.g. an unhandled decode/gunzip error or a frames-iterator throw on
// a non-200 HTTP/2 response. Without it the pull promise rejects, the
// ReadableStream errors, and the session is never cleaned up.
try {
try {
controller.enqueue({ type: "stream-start", warnings: [] } as V3Part)
} catch (e) {
// Controller already cancelled by the consumer — stop pumping.
trace(`pull: stream-start enqueue failed (cancelled) err=${(e as Error).message}`)
return
}
activeSession = await pumpWithRecovery({
initialSession: activeSession,
controller,
abortSignal: callOptions.abortSignal,
promptTokens,
retryPolicy,
recover: (recovery) => openSession({ recovery }),
onSession: (next) => { activeSession = next },
})
try {
controller.close()
} catch (e) {
trace(`pull: close failed (already closed/cancelled) err=${(e as Error).message}`)
}
} catch (e) {
activeSession.pumpActive = false
trace(`pull: pump threw (cleaning up): ${(e as Error).message}`)
sessionManager.close(activeSession)
try {
controller.error(e instanceof Error ? e : new Error(String(e)))
} catch {
/* controller already errored/closed */
}
}
},
cancel() {
// OpenCode cancels the ReadableStream after "tool-calls"; keep the
// Cursor Run stream alive so the next doStream can write results.
trace("ReadableStream cancel() → closeUnlessPending")
sessionManager.closeUnlessPending(activeSession)
},
}),
}
}
export async function pumpWithRecovery(input: {
initialSession: CursorSession
controller: ReadableStreamDefaultController<V3Part>
abortSignal?: AbortSignal
promptTokens?: number
retryPolicy?: CursorRetryPolicy
recover: (recovery: CursorRunRecovery) => Promise<CursorSession>
onSession?: (session: CursorSession) => void
maxRecoveries?: number
}): Promise<CursorSession> {
let session = input.initialSession
const retryPolicy = input.retryPolicy ?? {
...DEFAULT_RETRY_POLICY,
maxAttempts: (input.maxRecoveries ?? 1) + 1,
}
const maxRecoveries = retryPolicy.maxAttempts - 1
const requestUsage = { outputChars: 0 }
input.onSession?.(session)
for (let attempt = 0; ; attempt++) {
const pumpedSession = session
const pumpOwner = Symbol("cursor-pump")
sessionManager.beginPump(pumpedSession, pumpOwner)
try {
await pump(
pumpedSession,
input.controller,
{
textId: crypto.randomUUID(),
reasoningId: crypto.randomUUID(),
promptTokens: input.promptTokens ?? 0,
requestUsage,
},
input.abortSignal,
)
return session
} catch (error) {
const failure = toCursorProviderError(error, {
replaySafe: error instanceof CursorProviderError ? error.replaySafe : false,
fallback: "Cursor Run interrupted",
})
if (!failure.transient) throw failure
const checkpoint = pumpedSession.resumeCheckpoint
if (!failure.replaySafe && !checkpoint) {
throw retrySuppressedError(
failure,
"after visible output or stateful server activity",
attempt + 1,
maxRecoveries + 1,
)
}
if (attempt >= maxRecoveries) {
throw new CursorRetryExhaustedError(attempt + 1, failure)
}
trace(
`Run interrupted: sessionId=${pumpedSession.sessionId} attempt=${attempt + 1}/${maxRecoveries} ` +
`err=${failure.message} — ${checkpoint ? `resuming ${checkpoint.length}B checkpoint` : "rebasing fresh Run"}`,
)
sessionManager.close(pumpedSession, "remote-error", failure)
const delayMs = retryDelayMs(failure, attempt + 1, retryPolicy)
trace(`Run retry backoff: attempt=${attempt + 1}/${maxRecoveries} delayMs=${delayMs}`)
await sleepForRetry(delayMs, input.abortSignal)
session = await input.recover(
checkpoint
? {
kind: "resume",
conversationId: pumpedSession.conversationId,
checkpoint: Uint8Array.from(checkpoint),
}
: { kind: "rebase" },
)
input.onSession?.(session)
} finally {
sessionManager.endPump(pumpedSession, pumpOwner)
}
}
}
export type CursorRunRecovery =
| { kind: "rebase" }
| { kind: "resume"; conversationId: string; checkpoint: Uint8Array }
async function startSession(
modelId: string,
token: string,
callOptions: LanguageModelV3CallOptions,
options: CreateCursorOptions,
startOptions?: { recovery?: CursorRunRecovery },
): Promise<CursorSession> {
const continuationPolicy = resolveContinuationPolicy(options.continuation)
const prompt = callOptions.prompt
const incomingTools = extractTools(callOptions)
const sessionKey = opencodeSessionKey(callOptions)
const providerOptions = callOptions.providerOptions?.cursor as Record<string, unknown> | undefined
// The classic plugin marks OpenCode's agent="compaction" through chat.params.
// OpenCode 2.0 removed that hook, so its plugin records the same fact against
// the session id from session.hook("context") instead; consult both.
// Do not infer this from tools/toolChoice: standalone no-tool calls are valid.
const isCompaction =
providerOptions?.[CURSOR_COMPACTION_OPTION] === true || isCompactionSession(sessionKey)
const toolState = resolveTurnToolState({
sessionKey,
incomingTools,
toolChoice: callOptions.toolChoice,
isCompaction,
})
const tools = toolState.advertisedTools
const webToolAliases = buildCustomWebToolAliases(tools)
const cursorTools = webToolAliases.advertisedTools
for (const [alias, candidates] of webToolAliases.ambiguous) {
trace(`web tool alias skipped: alias=${alias} ambiguous=[${candidates.join(",")}]`)
}
for (const [alias, original] of webToolAliases.aliases) {
trace(`web tool alias: ${alias} -> ${original}`)
}
const allowTools = toolState.allowTools
const discoveredSubagentCatalog = extractHostSubagentCatalog(cursorTools)
const resetState = resolveTurnConversationReset({ sessionKey, isCompaction })
const recovery = startOptions?.recovery
const resuming = recovery?.kind === "resume"
// Compaction must not reuse the prior conversation; its first normal turn
// must also rebase so the summary-agent checkpoint cannot replace the normal
// system prompt and OpenCode's newly compacted history.
const bound = resuming
? { conversationId: recovery.conversationId, reset: false, previousId: undefined }
: bindConversationId(sessionKey, { reset: resetState.reset || recovery?.kind === "rebase" })
const conversationId = bound.conversationId
if (bound.reset) {
trace(
`conversation reset: reason=${recovery?.kind === "rebase" ? "interrupted-run" : (resetState.reason ?? "unknown")} ` +
`sessionKey=${sessionKey ?? "(none)"} ` +
`previousId=${bound.previousId ?? "-"} → conversationId=${conversationId}`,
)
}
const userText = recovery?.kind === "rebase"
? "Continue the interrupted turn from the conversation history above. Do not repeat completed work."
: (extractUserText([...prompt].reverse().find((m) => m.role === "user")) || ".")
// v1 sets `options.workspaceRoot` correctly per invocation (`input.directory`,
// one plugin instance per project). OpenCode 2.0 runs one daemon across many
// projects, so its static `options.workspaceRoot` is only a last-resort
// fallback; `getSessionDirectory` carries the real per-session directory
// recorded from `session.hook("context")` in `plugin-opencode2.ts`.
const workspaceRoot = path.resolve(
getSessionDirectory(sessionKey) ?? (options.workspaceRoot || process.cwd()),
)
const baseSystemPrompt = extractSystemPrompt(prompt)
const interactionGuidance = buildOpenCodeInteractionGuidance(cursorTools, isCompaction, workspaceRoot)
const systemPrompt = interactionGuidance
? [baseSystemPrompt, interactionGuidance].filter(Boolean).join("\n\n")
: baseSystemPrompt
const history = extractPromptHistory(prompt, {
preserveTrailingUser: recovery?.kind === "rebase",
toolResults: isCompaction ? "all" : (recovery?.kind === "rebase" ? "trailing" : "omit"),
})
await loadAvailableModels()
// Resolve the region-specific Run stream origin once per process (memoized
// in agent-url.ts). Explicit agent host overrides skip GetServerConfig but
// still go through the Cursor agent-host allowlist.
const agentBaseUrl =
resolveExplicitAgentBaseURL(options) ??
(await resolveAgentUrl(token, {
apiBaseURL: resolveApiBaseURL(options),
telemetryEnabled: resolveTelemetryEnabled(options),
}))
// OpenCode merges model, agent, and selected-variant options before placing
// them under providerOptions.cursor. Read only the plugin's dedicated nested
// payload so unrelated options never become requested_model.parameters.
const picked = extractCursorVariantParameters(providerOptions)
const cursorModelId = resolveCursorWireModelId(providerOptions, modelId)
const reasoningEffort = typeof providerOptions?.reasoningEffort === "string"
? providerOptions.reasoningEffort
: undefined
const hintMaxMode = !!(providerOptions?.maxMode ?? false)
const modelInfo = _availableModels?.find((m) => m.id === cursorModelId)
const parameterValues = resolveVariantParameters(modelInfo, {
reasoningEffort,
maxMode: hintMaxMode,
picked,
})
// Wire max_mode from the hint *or* a 1m context pick — OpenCode's variant
// paramMap does not include a maxMode key when the user selects 1m.
const maxMode = hintMaxMode || paramsImplyMaxMode(parameterValues)
// Do NOT pass callOptions.abortSignal into the h2 Run stream. OpenCode aborts
// that signal when a turn ends with tool-calls; the Cursor stream must stay
// open until we write the exec results on the next doStream.
const stream = await bidiRunStream(token, {
baseURL: agentBaseUrl,
headers: options.headers,
})
const requestContext = await buildRequestContext({ workspaceRoot, tools: cursorTools })
const contextSubagents = Array.isArray(requestContext.custom_subagents)
? requestContext.custom_subagents
.map((agent) => agent && typeof agent === "object" && typeof (agent as Record<string, unknown>).name === "string"
? {
name: (agent as Record<string, unknown>).name as string,
description: typeof (agent as Record<string, unknown>).description === "string"
? (agent as Record<string, unknown>).description as string
: undefined,
}
: undefined)
.filter((agent): agent is { name: string; description: string | undefined } => !!agent)
: []
const subagentCatalog = {
...discoveredSubagentCatalog,
agents: [...new Map(
[...discoveredSubagentCatalog.agents, ...contextSubagents]
.map((agent) => [agent.name, agent]),
).values()],
}
// Resolve descriptors once from the merged OpenCode config so MCP identity is
// consistent across AgentRunRequest and both request_context reply paths.
const toolDescriptors = Array.isArray(requestContext.tools)
? requestContext.tools as Array<Record<string, unknown>>
: []
// CLI parity: echo the last conversation_checkpoint_update as conversation_state.
// After compaction reset there is no checkpoint — seed from OpenCode history.
const conversationState = resuming
? recovery.checkpoint
: (bound.reset ? undefined : getCheckpoint(conversationId))
const reqBytes = buildRunRequest({
text: userText,
modelId: cursorModelId,
conversationId,
systemPrompt: conversationState ? undefined : systemPrompt,
history: conversationState ? undefined : history,
conversationState,
parameterValues,
maxMode,
tools: cursorTools,
toolDescriptors,
requestContext,
action: resuming ? "resume" : "user",
})
// Content hashes — Cursor content-addresses large payloads; logging these lets
// us match a server get_blob_args.blob_id to what it wants served.
const sha = (b: string | Uint8Array) => createHash("sha256").update(b).digest("hex")
const skillsCount = Array.isArray(requestContext.agent_skills)
? requestContext.agent_skills.length
: 0
const hooksCtx =
typeof requestContext.hooks_additional_context === "string"
? requestContext.hooks_additional_context
: ""
const historyChars = history.reduce((n, m) => n + m.content.length, 0)
const usageEstimate = {
inputTokens: estimateTokens(
(systemPrompt?.length ?? 0) + userText.length + historyChars + (conversationState?.length ?? 0),
),
outputTokens: 0,
cacheRead: 0,
cacheWrite: 0,
reasoningTokens: 0,
}
trace(
`outbound Run: model=${cursorModelId} opencodeModel=${modelId} conversationId=${conversationId} ` +
`params=${JSON.stringify(parameterValues ?? [])} ` +
`maxMode=${maxMode} systemPromptLen=${systemPrompt?.length ?? 0} ` +
`tools=${tools.length} incomingTools=${incomingTools.length} compaction=${isCompaction} ` +
`skills=${skillsCount} hooks=${hooksCtx ? hooksCtx.split("\n").length : 0} ` +
`availableModels=${_availableModels?.length ?? 0} userTextLen=${userText.length} ` +
`historyMsgs=${history.length} historyChars=${historyChars} ` +
`checkpointLen=${conversationState?.length ?? 0} reset=${bound.reset} ` +
`resume=${resuming} ` +
`usageEstimateIn=${usageEstimate.inputTokens} runRequestBytes=${reqBytes.length}`,
)
if (hooksCtx) trace(`outbound Run hooks_additional_context: ${hooksCtx}`)
trace(`hash run_request sha256=${sha(reqBytes)}`)
if (systemPrompt) trace(`hash systemPrompt sha256=${sha(systemPrompt)}`)
if (conversationState) trace(`hash checkpoint sha256=${sha(conversationState)}`)
try {
await writeWithBackpressure(stream, reqBytes, "initial Run request")
} catch (error) {
stream.destroy()
throw error
}
const session: CursorSession = {
sessionId: crypto.randomUUID(),
conversationId,
resumeCheckpoint: undefined,
openCodeSessionId: sessionKey,
stream,
frames: stream.frames()[Symbol.asyncIterator](),
pending: new Map(),
displayToolCalls: new Map(),
nextBridgedExecId: 900_000,
blobs: new Map(),
toolDescriptors,
toolAliases: webToolAliases.aliases,
subagentCatalog,
requestContext,
allowTools,
usageEstimate,
pumpActive: false,
pumpOwner: null,
heartbeat: null,
heartbeatCancel: null,
hardDeadlineTimer: null,
semanticDeadlineCancel: null,
terminalUnsubscribe: null,
deferredTerminalReason: null,
policy: continuationPolicy,
createdAt: Date.now(),
lastInboundAt: Date.now(),
lastHeartbeatWriteAt: Date.now(),
semanticDeadlineAt: Date.now() + continuationPolicy.semanticIdleMs,
closeError: null,
closed: false,
}
sessionManager.registerSession(session)
let heartbeatWritePending = false
session.heartbeat = setInterval(() => {
if (session.closed) return
if (heartbeatWritePending) {
sessionManager.close(
session,
"heartbeat-write-failed",
new CursorTransportError("Cursor heartbeat write remained backpressured", {
transient: false,
replaySafe: false,
code: "CURSOR_HEARTBEAT_BACKPRESSURE",
}),
)
return
}
heartbeatWritePending = true
void writeWithBackpressure(stream, buildHeartbeat(), "heartbeat")
.then(() => sessionManager.recordHeartbeatWrite(session))
.catch((cause) => {
sessionManager.close(
session,
"heartbeat-write-failed",
toCursorProviderError(cause, {
replaySafe: false,
fallback: "Cursor heartbeat write failed",
}),
)
})
.finally(() => { heartbeatWritePending = false })
}, continuationPolicy.heartbeatMs)
session.heartbeat.unref?.()
session.heartbeatCancel = () => {
if (session.heartbeat) clearInterval(session.heartbeat)
}
callOptions.abortSignal?.addEventListener("abort", () => {
// Abort after tool-calls is normal — preserve pending sessions.
trace("abortSignal aborted → closeUnlessPending")
sessionManager.closeUnlessPending(session)
}, { once: true })
return session
}
/**
* OpenCode re-sends the full tool-result history on every continuation. Prefer
* the newest result that still has a live pending exec on its tagged session.
*/
export function findContinuationSession(
toolResults: Array<{ sessionId: string; execId: number }>,
): CursorSession | undefined {
for (let i = toolResults.length - 1; i >= 0; i--) {
const r = toolResults[i]
const s = sessionManager.findByExecIds(r.sessionId, [r.execId])
if (s) return s
}
return undefined
}
/**
* Deliver trailing tool results onto a live continuation session.
* Returns the same session when writes succeed (or only bridged results were
* cleared). Returns undefined after closing the session when a write fails, so
* the caller can rebase onto a fresh Run instead of pumping a dead stream.
*/
export function deliverContinuationResults(
session: CursorSession,
trailingToolResults: ExtractedToolResult[],
): CursorSession | undefined {
const pendingResults = trailingToolResults.filter(
(r) => r.sessionId === session.sessionId && session.pending.has(r.execId),
)
trace(
`continuation: ${trailingToolResults.length} trailing tool result(s), ` +
`${pendingResults.length} pending for sessionId=${session.sessionId} ` +
`pending={${[...session.pending.keys()].join(",")}}`,
)
for (const r of pendingResults) {
const claim = sessionManager.claim(session.sessionId, r.execId)
if ("kind" in claim) {
if (claim.kind === "deliverable") {
throw new CursorProtocolError("Cursor continuation claim remained unclaimed")
}
if (claim.kind === "duplicate") {
trace(`continuation: skipped duplicate execId=${r.execId} reason=${claim.reason}`)
continue
}
trace(`continuation: unavailable execId=${r.execId} reason=${claim.reason}`)
return undefined
}
const pending = claim.pending
let frames: Uint8Array[] = []
if (!pending.bridged) {
try {
const shellResult =
pending.resultField === "shell_stream"
|| pending.resultField === "background_shell_spawn_result"
? consumeCursorShellResult(r.toolCallId, r.output)
: undefined
frames = buildExecClientMessages({
execId: r.execId,
resultField: pending.resultField,
output: shellResult?.output ?? r.output,
error: r.error,
toolName: pending.toolName ?? r.toolName,
resultMetadata: pending.resultMetadata,
shellOutcome: shellResult?.outcome,
workspaceRoot: workspaceRootFromRequestContext(session.requestContext),
})
} catch (error) {
trace(`continuation: result encode FAILED execId=${r.execId} err=${(error as Error).message}`)
sessionManager.close(session, "result-write-failed")
return undefined
}
}
const outcome = sessionManager.deliverClaim(claim, frames)
if (outcome.kind !== "delivered") {
trace(`continuation: delivery stopped execId=${r.execId} reason=${outcome.reason}`)
if (outcome.kind === "duplicate") continue
return undefined
}
session.usageEstimate.inputTokens += estimateTokens(r.output.length)
if (pending.bridged) {
trace(
`continuation: completed bridged result execId=${r.execId} toolName=${pending.toolName ?? r.toolName} outLen=${r.output.length}`,
)
continue
}
trace(
`continuation: wrote exec result execId=${r.execId} field=${pending.resultField} ` +
`frames=${outcome.framesWritten} outLen=${r.output.length}`,
)
}
return session
}
async function loadAvailableModels(): Promise<void> {
const cacheDir = opencodeGlobalCacheDir()
try {
const filePath = cacheFilePath(cacheDir)
let mtime = 0
try {
const stat = await fs.promises.stat(filePath)
mtime = stat.mtimeMs
} catch {
// file missing — fall through with mtime=0
}
// Re-read when the file changed (discoverModels background refresh).
if (mtime !== _availableModelsMtimeMs) {
const cached = await readCache(cacheDir)
_availableModels = cached?.models
_availableModelsMtimeMs = mtime
}
} catch { /* ignore */ }
}
function resolveApiBaseURL(options: CreateCursorOptions): string {
return options.apiBaseURL ?? process.env.CURSOR_API_BASE_URL ?? `https://${CURSOR_API_HOST}`
}
function resolveTelemetryEnabled(options: CreateCursorOptions): boolean {
return options.telemetryEnabled ?? isTruthyEnv(process.env.CURSOR_GET_SERVER_CONFIG_TELEMETRY)
}
function resolveExplicitAgentBaseURL(options: CreateCursorOptions): string | undefined {
const raw = options.agentBaseURL ?? options.baseURL
if (!raw) return undefined
const normalized = normalizeAgentRunOrigin(raw)
if (!normalized) {
throw new CursorProtocolError(
"Invalid Cursor agent base URL override: expected https://*.cursor.sh",
)
}
return normalized
}
function isTruthyEnv(value: string | undefined): boolean {
return value === "1" || value === "true"
}
async function writeWithBackpressure(
stream: BidiStream,
message: Uint8Array,
operation: string,
): Promise<void> {
let accepted: boolean | void
try {
accepted = stream.write(message)
} catch (cause) {
throw toCursorProviderError(cause, {
replaySafe: false,
fallback: `Cursor ${operation} write failed`,
})
}
if (accepted !== false) return
if (!stream.waitForDrain) {
throw new CursorTransportError(`Cursor ${operation} write was backpressured`, {
transient: false,
replaySafe: false,
code: "CURSOR_WRITE_BACKPRESSURE",
})
}
try {
await stream.waitForDrain(5_000)
} catch (cause) {
throw toCursorProviderError(cause, {
replaySafe: false,
fallback: `Cursor ${operation} backpressure drain failed`,
})
}
}