@devries-cameron20 / t3code-1 / commits / 1da4a1b0f2
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(provider-cursor): use the selected context window for handoff budgets (#17462)

Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

noah cuadrado committed Oct 19, 2026 at 23:13 UTC 1da4a1b0f2aabbda932375c80e9bd974d151caa5
4 files changed +282 -11
packages/provider-cursor/src/server/adapter.ts
+7 -1
@@ -27,6 +27,7 @@ import {
27 type OrchestrationV2Subagent,
28 type OrchestrationV2TurnItem,
29 type ProviderInstanceId,
30 + type ServerProviderModel,
31 type ThreadId,
32 } from "@t3tools/contracts";
33 import { CursorSettings } from "../settings.ts";
@@ -46,7 +47,7 @@ import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresen
47 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
48 import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
49 import { CursorTransportFailure } from "./transportFailure.ts";
49 -import { cursorSdkModelSelection } from "./sdkModel.ts";
50 +import { cursorContextWindowTokens, cursorSdkModelSelection } from "./sdkModel.ts";
51 import {
52 discoverCursorSkills,
53 hasCursorSkillMention,
@@ -876,6 +877,7 @@ export interface CursorAdapterV2Options {
877 readonly instanceId: ProviderInstanceId;
878 readonly settings: CursorSettings;
879 readonly environment: NodeJS.ProcessEnv;
880 + readonly getModels?: () => ReadonlyArray<ServerProviderModel>;
881 }
882
883 export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
@@ -2428,6 +2430,10 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2430 driver: CursorAgentSdk.CURSOR_PROVIDER,
2431 providerSessionId: input.providerSessionId,
2432 providerSession: session,
2433 + getModelContextWindow: (selection) =>
2434 + selection.instanceId === adapterOptions.instanceId
2435 + ? cursorContextWindowTokens(selection, adapterOptions.getModels?.() ?? [])
2436 + : undefined,
2437 events: Stream.fromEffectRepeat(Queue.take(events)),
2438 ensureThread: Effect.fn("CursorAdapterV2.ensureThread")(
2439 function* (threadInput: ProviderAdapter.ProviderAdapterV2EnsureThreadInput) {
packages/provider-cursor/src/server/driver.test.ts
+235 -1
@@ -1,7 +1,20 @@
1 // @effect-diagnostics nodeBuiltinImport:off
2 +import type { AgentOptions, SDKModel } from "@cursor/sdk";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { expect, it } from "@effect/vitest";
4 -import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
5 +import {
6 + MessageId,
7 + NodeId,
8 + ProjectId,
9 + ProviderInstanceId,
10 + ProviderSessionId,
11 + RunAttemptId,
12 + RunId,
13 + ThreadId,
14 +} from "@t3tools/contracts";
15 +import * as DateTime from "effect/DateTime";
16 +import * as Fiber from "effect/Fiber";
17 +import * as FileSystem from "effect/FileSystem";
18 import * as Effect from "effect/Effect";
19 import * as Layer from "effect/Layer";
20 import * as Option from "effect/Option";
@@ -10,6 +23,10 @@ import { vi } from "vite-plus/test";
23 import * as HttpClient from "effect/http/HttpClient";
24 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
25
26 +import {
27 + DEFAULT_HANDOFF_TOKEN_CAP,
28 + handoffBudget,
29 +} from "@t3tools/provider-core/server/handoffBudget";
30 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
31 import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
32 import { CursorDriver } from "./driver.ts";
@@ -157,6 +174,223 @@ it.layer(layerTest)("CursorDriver", (it) => {
174 }).pipe(Effect.scoped),
175 );
176
177 + it.effect("budgets handoffs for the SDK model across catalog refreshes and option changes", () =>
178 + Effect.gen(function* () {
179 + const fileSystem = yield* FileSystem.FileSystem;
180 + const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-window-" });
181 + const catalog = Promise.withResolvers<Array<SDKModel>>();
182 + const catalogRequested = Promise.withResolvers<void>();
183 + const me = vi.spyOn(Cursor, "me").mockResolvedValue({
184 + apiKeyName: "T3 Code",
185 + createdAt: "2026-01-01T00:00:00.000Z",
186 + });
187 + const models = vi.spyOn(Cursor.models, "list").mockImplementation(() => {
188 + catalogRequested.resolve();
189 + return catalog.promise;
190 + });
191 + yield* Effect.addFinalizer(() =>
192 + Effect.sync(() => {
193 + me.mockRestore();
194 + models.mockRestore();
195 + }),
196 + );
197 + const instanceId = ProviderInstanceId.make("cursor-catalog-window");
198 + const openedModels: Array<AgentOptions["model"]> = [];
199 + const sentModels: Array<AgentOptions["model"]> = [];
200 + const instance = yield* CursorDriver.create({
201 + instanceId,
202 + displayName: "Cursor",
203 + enabled: true,
204 + environment: [{ name: "CURSOR_API_KEY", value: "catalog-window-key", sensitive: true }],
205 + config: CursorDriver.defaultConfig(),
206 + }).pipe(
207 + Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
208 + assertComplete: Effect.void,
209 + open: (request) =>
210 + Effect.sync(() => {
211 + openedModels.push(request.options.model);
212 + return {
213 + agentId: "native-cursor-window",
214 + listMessages: Effect.succeed([]),
215 + close: Effect.void,
216 + send: (input) =>
217 + Effect.sync(() => {
218 + sentModels.push(input.options?.model);
219 + const runId = `native-cursor-window-run-${sentModels.length}`;
220 + return {
221 + agentId: "native-cursor-window",
222 + runId,
223 + cancel: Effect.void,
224 + wait: Effect.succeed({
225 + id: runId,
226 + requestId: runId,
227 + status: "finished" as const,
228 + model: { id: "claude-opus-5-5" },
229 + durationMs: 1,
230 + }),
231 + };
232 + }),
233 + };
234 + }),
235 + }),
236 + );
237 + const selection = (contextWindow?: string) => ({
238 + instanceId,
239 + model: "claude-opus-5-5",
240 + ...(contextWindow === undefined
241 + ? {}
242 + : { options: [{ id: "contextWindow", value: contextWindow }] }),
243 + });
244 + const threadId = ThreadId.make("cursor-catalog-window-thread");
245 + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
246 + runtimeMode: "full-access",
247 + interactionMode: "default",
248 + cwd: workspace,
249 + });
250 + const runtime = yield* instance.orchestrationAdapter.openSession({
251 + threadId,
252 + providerSessionId: ProviderSessionId.make("cursor-catalog-window-session"),
253 + modelSelection: selection("1m"),
254 + runtimePolicy,
255 + });
256 + const refresh = yield* instance.snapshot.refresh.pipe(Effect.forkScoped);
257 + yield* Effect.promise(() => catalogRequested.promise);
258 + expect(runtime.getModelContextWindow?.(selection())).toBeUndefined();
259 + const providerThread = yield* runtime.ensureThread({
260 + threadId,
261 + modelSelection: selection("1m"),
262 + runtimePolicy,
263 + });
264 + const now = yield* DateTime.now;
265 + const startTurn = Effect.fnUntraced(function* (contextWindow?: string) {
266 + const modelSelection = selection(contextWindow);
267 + const ordinal = sentModels.length + 1;
268 + yield* runtime.startTurn({
269 + threadId,
270 + providerThread,
271 + modelSelection,
272 + runtimePolicy,
273 + runId: RunId.make(`cursor-window-run-${ordinal}`),
274 + runOrdinal: ordinal,
275 + providerTurnOrdinal: ordinal,
276 + attemptId: RunAttemptId.make(`cursor-window-attempt-${ordinal}`),
277 + rootNodeId: NodeId.make(`cursor-window-root-${ordinal}`),
278 + appThread: {
279 + id: threadId,
280 + projectId: ProjectId.make("cursor-window-project"),
281 + createdBy: "user",
282 + creationSource: "web",
283 + title: "Cursor context window",
284 + providerInstanceId: instanceId,
285 + modelSelection,
286 + runtimeMode: "full-access",
287 + interactionMode: "default",
288 + branch: null,
289 + worktreePath: null,
290 + activeProviderThreadId: providerThread.id,
291 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
292 + forkedFrom: null,
293 + createdAt: now,
294 + updatedAt: now,
295 + archivedAt: null,
296 + settledOverride: null,
297 + settledAt: null,
298 + lastVisitedAt: null,
299 + deletedAt: null,
300 + },
301 + message: {
302 + messageId: MessageId.make(`cursor-window-message-${ordinal}`),
303 + createdBy: "user",
304 + creationSource: "web",
305 + text: "Continue.",
306 + attachments: [],
307 + },
308 + });
309 + yield* runtime.events.pipe(
310 + Stream.takeUntil((event) => event.type === "turn.terminal"),
311 + Stream.runDrain,
312 + );
313 + const window = runtime.getModelContextWindow?.(modelSelection);
314 + return {
315 + model: sentModels.at(-1),
316 + window,
317 + allowance: handoffBudget({
318 + tokenCap: DEFAULT_HANDOFF_TOKEN_CAP,
319 + userText: "Continue.",
320 + attachments: [],
321 + providerThread,
322 + nativeContextEstimate: 400_000,
323 + modelContextWindow: window,
324 + }),
325 + };
326 + });
327 + const beforeCatalog = yield* startTurn("1m");
328 + catalog.resolve([
329 + {
330 + id: "claude-opus-5-5",
331 + displayName: "Claude Opus 5.5",
332 + parameters: [
333 + {
334 + id: "context",
335 + displayName: "Context",
336 + values: [{ value: "300k" }, { value: "1m" }],
337 + },
338 + ],
339 + variants: [
340 + {
341 + displayName: "Claude Opus 5.5",
342 + isDefault: true,
343 + params: [{ id: "context", value: "1m" }],
344 + },
345 + ],
346 + },
347 + ]);
348 + expect((yield* Fiber.join(refresh)).status).toBe("ready");
349 + const catalogDefault = yield* startTurn();
350 + const explicitWindow = yield* startTurn("500k");
351 + const unknownWindow = yield* startTurn("max");
352 + me.mockRejectedValue(new Error("Cursor is unreachable"));
353 + expect((yield* instance.snapshot.refresh).status).toBe("error");
354 + const retainedDefault = yield* startTurn();
355 +
356 + expect(openedModels).toEqual([
357 + {
358 + id: "claude-opus-5-5",
359 + params: [{ id: "context", value: "1m" }],
360 + },
361 + ]);
362 + expect({
363 + beforeCatalog,
364 + catalogDefault,
365 + explicitWindow,
366 + unknownWindow,
367 + retainedDefault,
368 + }).toEqual({
369 + beforeCatalog: {
370 + model: { id: "claude-opus-5-5", params: [{ id: "context", value: "1m" }] },
371 + window: 1_000_000,
372 + allowance: DEFAULT_HANDOFF_TOKEN_CAP,
373 + },
374 + catalogDefault: {
375 + model: { id: "claude-opus-5-5" },
376 + window: 1_000_000,
377 + allowance: DEFAULT_HANDOFF_TOKEN_CAP,
378 + },
379 + explicitWindow: {
380 + model: { id: "claude-opus-5-5", params: [{ id: "context", value: "500k" }] },
381 + window: 500_000,
382 + allowance: 0,
383 + },
384 + unknownWindow: {
385 + model: { id: "claude-opus-5-5", params: [{ id: "context", value: "max" }] },
386 + window: undefined,
387 + allowance: 0,
388 + },
389 + retainedDefault: catalogDefault,
390 + });
391 + }).pipe(Effect.scoped),
392 + );
393 +
394 it.effect("keeps the bundled SDK manual-only without probing or updating cursor-agent", () =>
395 Effect.gen(function* () {
396 const instance = yield* CursorDriver.create({
packages/provider-cursor/src/server/driver.ts
+19 -8
@@ -1,4 +1,8 @@
1 -import { ProviderDriverKind, ProviderSetupError } from "@t3tools/contracts";
1 +import {
2 + ProviderDriverKind,
3 + ProviderSetupError,
4 + type ServerProviderModel,
5 +} from "@t3tools/contracts";
6 import { CursorSettings } from "../settings.ts";
7 import * as Effect from "effect/Effect";
8 import * as Crypto from "effect/Crypto";
@@ -10,7 +14,7 @@ import { readCursorUsageLimits } from "./usageLimits.ts";
14
15 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
16 import { makeCursorTextGeneration } from "./textGeneration.ts";
13 -import { CursorAdapterV2Driver, type CursorAdapterV2DriverEnv } from "./adapter.ts";
17 +import { makeCursorAdapterV2, type CursorAdapterV2DriverEnv } from "./adapter.ts";
18 import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
19 import { buildInitialCursorProviderSnapshot, checkCursorProviderStatus } from "./status.ts";
20 import * as CursorSdkCatalog from "./CursorSdkCatalog.ts";
@@ -154,13 +158,12 @@ export const CursorDriver: ProviderDriver<
158 },
159 });
160
157 - const orchestrationAdapter = yield* CursorAdapterV2Driver.create({
161 + let catalogModels: ReadonlyArray<ServerProviderModel> = [];
162 + const orchestrationAdapter = yield* makeCursorAdapterV2({
163 instanceId,
159 - displayName,
160 - accentColor,
161 - environment,
162 - enabled,
163 - config,
164 + settings: effectiveConfig,
165 + environment: processEnv,
166 + getModels: () => catalogModels,
167 }).pipe(
168 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
169 ...sdkRunner,
@@ -239,6 +242,14 @@ export const CursorDriver: ProviderDriver<
242 Effect.provideService(Path.Path, path),
243 Effect.provideService(CursorKeychain.CursorKeychain, keychain),
244 Effect.map(stampSnapshot),
245 + Effect.tap((provider) =>
246 + Effect.sync(() => {
247 + // A failed check lists only custom models, so keep the last loaded catalog.
248 + if (provider.models.some((model) => !model.isCustom)) {
249 + catalogModels = provider.models;
250 + }
251 + }),
252 + ),
253 Effect.provide(CursorSdkCatalog.layer),
254 );
255
packages/provider-cursor/src/server/sdkModel.ts
+21 -1
@@ -1,5 +1,6 @@
1 import type { ModelSelection as CursorSdkModelSelection, ModelParameterValue } from "@cursor/sdk";
2 -import type { ModelSelection } from "@t3tools/contracts";
2 +import type { ModelSelection, ServerProviderModel } from "@t3tools/contracts";
3 +import { getProviderOptionCurrentValue } from "@t3tools/shared/model";
4
5 const CURSOR_SDK_PARAMETER_TO_PROVIDER_OPTION: Readonly<Record<string, string>> = {
6 context: "contextWindow",
@@ -35,6 +36,25 @@ export function cursorSdkParameterPriority(parameterId: string): number {
36 }
37 }
38
39 +export function cursorContextWindowTokens(
40 + modelSelection: ModelSelection,
41 + models: ReadonlyArray<ServerProviderModel>,
42 +): number | undefined {
43 + // The SDK forwards explicit values even when the catalog does not list them.
44 + const explicit = modelSelection.options?.find((option) => option.id === "contextWindow");
45 + let value = explicit?.value;
46 + if (explicit === undefined) {
47 + const descriptor = models
48 + .find((model) => model.slug === modelSelection.model)
49 + ?.capabilities?.optionDescriptors?.find((option) => option.id === "contextWindow");
50 + value = getProviderOptionCurrentValue(descriptor);
51 + }
52 + const match = /^(\d+)([km])$/i.exec(typeof value === "string" ? value.trim() : "");
53 + if (match === null) return undefined;
54 + const tokens = Number(match[1]) * (match[2]?.toLowerCase() === "m" ? 1_000_000 : 1_000);
55 + return Number.isSafeInteger(tokens) && tokens > 0 ? tokens : undefined;
56 +}
57 +
58 export function cursorSdkModelSelection(modelSelection: ModelSelection): CursorSdkModelSelection {
59 return {
60 id: modelSelection.model === "auto" ? "default" : modelSelection.model,