The best way to control Claude Code, Codex and more from any computer or phone
perf(cursor): load the agent SDK only when needed (#28718)
Yash Singh committed
Nov 1, 2026 at 10:31 UTC
3fd2b855c5c6b9169cdfe3733b34011c1c5ed4b7
17 files changed
+481
-104
packages/provider-cursor/src/server/CursorAgentSdk.test.ts
+49
-10
@@ -3,6 +3,8 @@ import { assert, describe, it } from "@effect/vitest";
3
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
4
import * as Effect from "effect/Effect";
5
import * as Layer from "effect/Layer";
6
+import * as Exit from "effect/Exit";
7
+import * as Cause from "effect/Cause";
8
import { vi } from "vite-plus/test";
9
10
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
@@ -94,17 +96,19 @@ const cursorSdkMock = vi.hoisted(() => {
96
});
97
98
vi.mock("./sdk.ts", () => ({
97
- Agent: {
98
- create: cursorSdkMock.create,
99
- resume: cursorSdkMock.resume,
100
- listRuns: cursorSdkMock.listRuns,
101
- cancelRun: cursorSdkMock.cancelRun,
102
- messages: {
103
- list: vi.fn(async () => []),
99
+ loadCursorSdk: () => ({
100
+ Agent: {
101
+ create: cursorSdkMock.create,
102
+ resume: cursorSdkMock.resume,
103
+ listRuns: cursorSdkMock.listRuns,
104
+ cancelRun: cursorSdkMock.cancelRun,
105
+ messages: {
106
+ list: vi.fn(async () => []),
107
+ },
108
},
105
- },
106
- createAgentPlatform: vi.fn(),
107
- SqliteLocalAgentStore: { open: vi.fn() },
109
+ createAgentPlatform: vi.fn(),
110
+ }),
111
+ loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: vi.fn() } }),
112
}));
113
114
const layerTest = CursorAgentSdk.layer.pipe(
@@ -132,6 +136,41 @@ const layerTest = CursorAgentSdk.layer.pipe(
136
);
137
138
describe("CursorAgentSdkRunner", () => {
139
+ it.effect("constructs without loading and reports first-use load failures as runner errors", () =>
140
+ Effect.gen(function* () {
141
+ const failure = new Error("missing SDK chunk");
142
+ const load = vi.fn(() => {
143
+ throw failure;
144
+ });
145
+ const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe(
146
+ Effect.provideService(CursorSdk.CursorSdk, {
147
+ load,
148
+ loadSqlite: () => {
149
+ throw new Error("unused SQLite");
150
+ },
151
+ }),
152
+ );
153
+ assert.strictEqual(load.mock.calls.length, 0);
154
+ const result = yield* runner
155
+ .open({
156
+ operation: "create",
157
+ options: {},
158
+ threadId: ThreadId.make("lazy-load"),
159
+ providerSessionId: ProviderSessionId.make("lazy-load"),
160
+ })
161
+ .pipe(Effect.exit);
162
+ assert(Exit.isFailure(result));
163
+ assert.deepStrictEqual(
164
+ Cause.squash(result.cause),
165
+ new CursorAgentSdk.CursorAgentSdkRunnerError({
166
+ method: "agent.create",
167
+ cause: failure,
168
+ }),
169
+ );
170
+ assert.strictEqual(load.mock.calls.length, 1);
171
+ }),
172
+ );
173
+
174
it.effect("retries a resumed send after cancelling its abandoned local run", () =>
175
Effect.gen(function* () {
176
cursorSdkMock.runOperations.length = 0;
packages/provider-cursor/src/server/CursorAgentSdk.ts
+8
-2
@@ -340,7 +340,7 @@ function makeCursorAgentSdkProtocolLogger(input: {
340
export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
341
protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
342
) {
343
- const { Agent, createAgentPlatform } = yield* CursorSdk.CursorSdk;
343
+ const sdk = yield* CursorSdk.CursorSdk;
344
345
// Prime with cursorsandbox before any Full access run; the SDK caches sandbox support per process.
346
const sandboxSupportPrimeStarted = yield* Ref.make(false);
@@ -352,7 +352,9 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
352
}
353
yield* Effect.tryPromise(async () => {
354
const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
355
- const platform = await createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
355
+ const platform = await sdk
356
+ .load()
357
+ .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
358
const release = await platform.prewarmLocalWorkspace({
359
...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
360
local: {
@@ -368,6 +370,10 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
370
371
return CursorAgentSdkRunner.of({
372
open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
373
+ const { Agent } = yield* Effect.try({
374
+ try: sdk.load,
375
+ catch: (cause) => runnerError(cause, `agent.${input.operation}`),
376
+ });
377
if (input.options.local?.sandboxOptions?.enabled === false) {
378
yield* primeCursorSandboxSupport(input.options);
379
}
packages/provider-cursor/src/server/CursorSdk.test.ts
-2
@@ -5,8 +5,6 @@ import { vi } from "vite-plus/test";
5
6
import * as CursorSdk from "./CursorSdk.ts";
7
8
-vi.mock("./sdk.ts", () => ({ Agent: {}, createAgentPlatform: {}, SqliteLocalAgentStore: {} }));
9
-
8
// Shaped like the SDK's minified class: the constructor is not named after the error.
9
class o extends Error {
10
override name = "WriteIterableClosedError";
packages/provider-cursor/src/server/CursorSdk.ts
+4
-5
@@ -3,7 +3,7 @@ import * as Context from "effect/Context";
3
import * as Effect from "effect/Effect";
4
import * as Layer from "effect/Layer";
5
6
-import { Agent, createAgentPlatform, SqliteLocalAgentStore } from "./sdk.ts";
6
+import { loadCursorSdk, loadCursorSqlite } from "./sdk.ts";
7
8
// The SDK leaves a shell-error promise unhandled, which would exit the server.
9
const CURSOR_SHELL_SPAWN_MARKERS = [
@@ -60,9 +60,8 @@ function onUnhandledRejection(reason: unknown): void {
60
export class CursorSdk extends Context.Service<
61
CursorSdk,
62
{
63
- readonly Agent: typeof Agent;
64
- readonly createAgentPlatform: typeof createAgentPlatform;
65
- readonly SqliteLocalAgentStore: typeof SqliteLocalAgentStore;
63
+ readonly load: typeof loadCursorSdk;
64
+ readonly loadSqlite: typeof loadCursorSqlite;
65
}
66
>()("@t3tools/provider-cursor/server/CursorSdk") {}
67
@@ -77,5 +76,5 @@ export const layer = Layer.effect(
76
Effect.sync(() => {
77
process.off("unhandledRejection", onUnhandledRejection);
78
}),
80
- ).pipe(Effect.as(CursorSdk.of({ Agent, createAgentPlatform, SqliteLocalAgentStore }))),
79
+ ).pipe(Effect.as(CursorSdk.of({ load: loadCursorSdk, loadSqlite: loadCursorSqlite }))),
80
);
packages/provider-cursor/src/server/CursorSdkCatalog.test.ts
+135
@@ -2,6 +2,20 @@ import type { SDKModel, SDKUser } from "@cursor/sdk";
2
import { describe, expect, it } from "@effect/vitest";
3
import * as Effect from "effect/Effect";
4
import * as Exit from "effect/Exit";
5
+import * as Cause from "effect/Cause";
6
+import * as Deferred from "effect/Deferred";
7
+import * as Fiber from "effect/Fiber";
8
+import * as Layer from "effect/Layer";
9
+import * as HttpClient from "effect/http/HttpClient";
10
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
11
+import { vi } from "vite-plus/test";
12
+
13
+const sdkLoad = vi.hoisted(() =>
14
+ vi.fn(() => {
15
+ throw new Error("Catalog must not load the SDK");
16
+ }),
17
+);
18
+vi.mock("./sdk.ts", () => ({ loadCursorSdk: sdkLoad, isCursorSdkError: () => false }));
19
20
import * as CursorSdkCatalog from "./CursorSdkCatalog.ts";
21
@@ -24,6 +38,127 @@ const catalogError = () =>
38
});
39
40
describe("CursorSdkCatalog", () => {
41
+ it.effect.each([
42
+ { route: "me", status: 200, body: user, expected: "ready" },
43
+ {
44
+ route: "me",
45
+ status: 401,
46
+ body: { error: { code: "feature_unavailable" } },
47
+ expected: "unauthenticated",
48
+ },
49
+ {
50
+ route: "me",
51
+ status: 403,
52
+ body: { error: { code: "feature_unavailable" } },
53
+ expected: "no-user",
54
+ },
55
+ { route: "me", status: 403, body: "Forbidden", expected: "no-user" },
56
+ { route: "me", status: 403, body: { code: "plan_required" }, expected: "plan" },
57
+ { route: "models", status: 403, body: { error: { code: "plan_required" } }, expected: "plan" },
58
+ { route: "models", status: 403, body: {}, expected: "blocked" },
59
+ { route: "me", status: 503, body: "Unavailable", expected: "error" },
60
+ { route: "models", status: 200, body: { items: [{ id: "missing-name" }] }, expected: "error" },
61
+ { route: "me", status: 200, body: "invalid JSON", expected: "error" },
62
+ ])(
63
+ "reads $route HTTP $status as $expected without loading the SDK",
64
+ ({ route, status, body, expected }) =>
65
+ Effect.gen(function* () {
66
+ sdkLoad.mockClear();
67
+ const requests: Array<string> = [];
68
+ const models = [
69
+ {
70
+ ...model,
71
+ aliases: ["opus"],
72
+ parameters: [{ id: "fast", values: [{ value: "true" }] }],
73
+ variants: [
74
+ {
75
+ displayName: "Fast",
76
+ params: [{ id: "fast", value: "true" }],
77
+ isDefault: true,
78
+ isMaxMode: true,
79
+ },
80
+ ],
81
+ },
82
+ ];
83
+ const client = HttpClient.make((request) => {
84
+ expect(request.headers.authorization).toBe("Bearer test-key");
85
+ expect(request.method).toBe("GET");
86
+ requests.push(request.url);
87
+ const matches = request.url === `https://api.cursor.com/v1/${route}`;
88
+ const responseBody = matches
89
+ ? body
90
+ : request.url.endsWith("/me")
91
+ ? user
92
+ : { items: models };
93
+ const response =
94
+ typeof responseBody === "string"
95
+ ? new Response(responseBody, { status: matches ? status : 200 })
96
+ : Response.json(responseBody, { status: matches ? status : 200 });
97
+ return Effect.succeed(HttpClientResponse.fromWeb(request, response));
98
+ });
99
+ const catalog = yield* CursorSdkCatalog.CursorSdkCatalog.pipe(
100
+ Effect.provide(
101
+ CursorSdkCatalog.layer.pipe(
102
+ Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
103
+ ),
104
+ ),
105
+ );
106
+ expect(sdkLoad).not.toHaveBeenCalled();
107
+ const result = yield* catalog.read("test-key").pipe(Effect.exit);
108
+ expect(requests).toContain(`https://api.cursor.com/v1/${route}`);
109
+ if (expected === "ready" || expected === "no-user") {
110
+ expect(Exit.isSuccess(result)).toBe(true);
111
+ if (Exit.isSuccess(result))
112
+ expect(result.value).toEqual({
113
+ user: expected === "no-user" ? undefined : user,
114
+ models,
115
+ });
116
+ } else {
117
+ expect(Exit.isFailure(result)).toBe(true);
118
+ if (Exit.isFailure(result))
119
+ expect(Cause.squash(result.cause)).toMatchObject({
120
+ authenticationFailure: expected === "unauthenticated",
121
+ planRequired: expected === "plan",
122
+ accountBlocked: expected === "blocked",
123
+ });
124
+ }
125
+ expect(sdkLoad).not.toHaveBeenCalled();
126
+ }),
127
+ );
128
+
129
+ it.effect("shares concurrent first model discovery until the response arrives", () =>
130
+ Effect.gen(function* () {
131
+ const modelsEntered = yield* Deferred.make<void>();
132
+ const secondUserEntered = yield* Deferred.make<void>();
133
+ const response = yield* Deferred.make<ReadonlyArray<SDKModel>>();
134
+ let userCalls = 0;
135
+ let modelCalls = 0;
136
+ const catalog = yield* CursorSdkCatalog.makeCursorSdkCatalog({
137
+ readUser: () =>
138
+ Effect.gen(function* () {
139
+ userCalls += 1;
140
+ if (userCalls === 2) yield* Deferred.succeed(secondUserEntered, undefined);
141
+ return user;
142
+ }),
143
+ readModels: () =>
144
+ Effect.gen(function* () {
145
+ modelCalls += 1;
146
+ yield* Deferred.succeed(modelsEntered, undefined);
147
+ return yield* Deferred.await(response);
148
+ }),
149
+ });
150
+ expect(modelCalls).toBe(0);
151
+ const first = yield* catalog.read("test-key").pipe(Effect.forkChild);
152
+ yield* Deferred.await(modelsEntered);
153
+ const second = yield* catalog.read("test-key").pipe(Effect.forkChild);
154
+ yield* Deferred.await(secondUserEntered);
155
+ expect(modelCalls).toBe(1);
156
+ yield* Deferred.succeed(response, [model]);
157
+ expect((yield* Fiber.join(first)).models).toEqual([model]);
158
+ expect((yield* Fiber.join(second)).models).toEqual([model]);
159
+ }),
160
+ );
161
+
162
it.effect("does not cache failed or empty model discovery", () =>
163
Effect.gen(function* () {
164
let modelCalls = 0;
packages/provider-cursor/src/server/CursorSdkCatalog.ts
+112
-25
@@ -1,5 +1,10 @@
1
import type { SDKModel, SDKUser } from "@cursor/sdk";
2
import * as Cache from "effect/Cache";
3
+import * as Config from "effect/Config";
4
+import * as Option from "effect/Option";
5
+import * as HttpClient from "effect/http/HttpClient";
6
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
7
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
8
import * as Context from "effect/Context";
9
import * as Duration from "effect/Duration";
10
import * as Effect from "effect/Effect";
@@ -7,8 +12,6 @@ import * as Exit from "effect/Exit";
12
import * as Layer from "effect/Layer";
13
import * as Schema from "effect/Schema";
14
10
-import { AuthenticationError, Cursor, CursorSdkError } from "./sdk.ts";
11
-
15
export interface CursorSdkCatalogSnapshot {
16
readonly user: SDKUser | undefined;
17
readonly models: ReadonlyArray<SDKModel>;
@@ -18,6 +21,8 @@ export class CursorSdkCatalogError extends Schema.TaggedError<CursorSdkCatalogEr
21
"CursorSdkCatalogError",
22
{
23
authenticationFailure: Schema.Boolean,
24
+ status: Schema.optionalKey(Schema.Number),
25
+ code: Schema.optionalKey(Schema.String),
26
cause: Schema.Defect(),
27
},
28
) {
@@ -28,11 +33,11 @@ export class CursorSdkCatalogError extends Schema.TaggedError<CursorSdkCatalogEr
33
}
34
35
get planRequired(): boolean {
31
- return this.cause instanceof CursorSdkError && this.cause.code === "plan_required";
36
+ return this.code === "plan_required";
37
}
38
39
get accountBlocked(): boolean {
35
- return this.cause instanceof CursorSdkError && this.cause.status === 403 && !this.planRequired;
40
+ return this.status === 403 && !this.planRequired;
41
}
42
}
43
@@ -45,13 +50,6 @@ export class CursorSdkCatalog extends Context.Service<
50
}
51
>()("@t3tools/provider-cursor/server/CursorSdkCatalog") {}
52
48
-function isAuthenticationFailure(cause: unknown): boolean {
49
- return (
50
- cause instanceof AuthenticationError ||
51
- (cause instanceof CursorSdkError && cause.status === 401)
52
- );
53
-}
54
-
53
export interface CursorSdkCatalogProbes {
54
readonly readUser: (apiKey: string) => Effect.Effect<SDKUser, CursorSdkCatalogError>;
55
readonly readModels: (
@@ -59,23 +57,109 @@ export interface CursorSdkCatalogProbes {
57
) => Effect.Effect<ReadonlyArray<SDKModel>, CursorSdkCatalogError>;
58
}
59
62
-const sdkRequest = <A>(tryRequest: () => Promise<A>) =>
63
- Effect.tryPromise({
64
- try: tryRequest,
65
- catch: (cause) =>
66
- new CursorSdkCatalogError({
67
- authenticationFailure: isAuthenticationFailure(cause),
68
- cause,
60
+const CatalogUser = Schema.Struct({
61
+ apiKeyName: Schema.String,
62
+ createdAt: Schema.String,
63
+ userId: Schema.optionalKey(Schema.Number),
64
+ userEmail: Schema.optionalKey(Schema.String),
65
+ userFirstName: Schema.optionalKey(Schema.String),
66
+ userLastName: Schema.optionalKey(Schema.String),
67
+});
68
+const ModelParameterValue = Schema.Struct({ id: Schema.String, value: Schema.String });
69
+const CatalogModel = Schema.Struct({
70
+ id: Schema.String,
71
+ displayName: Schema.String,
72
+ description: Schema.optionalKey(Schema.String),
73
+ aliases: Schema.optionalKey(Schema.Array(Schema.String).pipe(Schema.mutable)),
74
+ parameters: Schema.optionalKey(
75
+ Schema.Array(
76
+ Schema.Struct({
77
+ id: Schema.String,
78
+ displayName: Schema.optionalKey(Schema.String),
79
+ values: Schema.Array(
80
+ Schema.Struct({ value: Schema.String, displayName: Schema.optionalKey(Schema.String) }),
81
+ ).pipe(Schema.mutable),
82
}),
70
- });
83
+ ).pipe(Schema.mutable),
84
+ ),
85
+ variants: Schema.optionalKey(
86
+ Schema.Array(
87
+ Schema.Struct({
88
+ params: Schema.Array(ModelParameterValue).pipe(Schema.mutable),
89
+ displayName: Schema.String,
90
+ description: Schema.optionalKey(Schema.String),
91
+ isDefault: Schema.optionalKey(Schema.Boolean),
92
+ isMaxMode: Schema.optionalKey(Schema.Boolean),
93
+ }),
94
+ ).pipe(Schema.mutable),
95
+ ),
96
+});
97
+const CatalogModels = Schema.Struct({ items: Schema.Array(CatalogModel).pipe(Schema.mutable) });
98
+const ApiError = Schema.Struct({
99
+ code: Schema.optionalKey(Schema.String),
100
+ message: Schema.optionalKey(Schema.String),
101
+});
102
+const ApiErrorEnvelope = Schema.Struct({ error: ApiError });
103
+const decodeApiError = Schema.decodeUnknownOption(ApiError);
104
+const decodeApiErrorEnvelope = Schema.decodeUnknownOption(ApiErrorEnvelope);
105
+const isCatalogError = Schema.is(CursorSdkCatalogError);
106
72
-const liveProbes: CursorSdkCatalogProbes = {
73
- readUser: (apiKey) => sdkRequest(() => Cursor.me({ apiKey })),
74
- readModels: (apiKey) => sdkRequest(() => Cursor.models.list({ apiKey })),
75
-};
107
+// Catalog discovery uses public HTTP routes so signed-in startup does not initialize the agent runtime.
108
+const makeLiveProbes = Effect.gen(function* () {
109
+ const client = yield* HttpClient.HttpClient;
110
+ const baseUrl = (yield* Config.String("CURSOR_BACKEND_URL").pipe(
111
+ Config.withDefault("https://api.cursor.com"),
112
+ Effect.orDie,
113
+ )).replace(/\/$/, "");
114
+ const request = Effect.fn("CursorSdkCatalog.request")(function* (apiKey: string, path: string) {
115
+ const response = yield* client
116
+ .execute(
117
+ HttpClientRequest.get(`${baseUrl}${path}`).pipe(HttpClientRequest.bearerToken(apiKey)),
118
+ )
119
+ .pipe(
120
+ Effect.mapError(
121
+ (cause) => new CursorSdkCatalogError({ authenticationFailure: false, cause }),
122
+ ),
123
+ );
124
+ if (response.status < 200 || response.status >= 300) {
125
+ const body = yield* response.json.pipe(Effect.orElseSucceed(() => undefined));
126
+ const nested = decodeApiErrorEnvelope(body);
127
+ const parsed = Option.isSome(nested) ? Option.some(nested.value.error) : decodeApiError(body);
128
+ const error = Option.getOrUndefined(parsed);
129
+ return yield* new CursorSdkCatalogError({
130
+ authenticationFailure: response.status === 401,
131
+ status: response.status,
132
+ ...(error?.code === undefined ? {} : { code: error.code }),
133
+ cause: new Error(error?.message ?? `Cursor ${path} returned HTTP ${response.status}.`),
134
+ });
135
+ }
136
+ return response;
137
+ });
138
+ return {
139
+ readUser: (apiKey) =>
140
+ request(apiKey, "/v1/me").pipe(
141
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(CatalogUser)),
142
+ Effect.mapError((cause) =>
143
+ isCatalogError(cause)
144
+ ? cause
145
+ : new CursorSdkCatalogError({ authenticationFailure: false, cause }),
146
+ ),
147
+ ),
148
+ readModels: (apiKey) =>
149
+ request(apiKey, "/v1/models").pipe(
150
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(CatalogModels)),
151
+ Effect.map((body) => body.items),
152
+ Effect.mapError((cause) =>
153
+ isCatalogError(cause)
154
+ ? cause
155
+ : new CursorSdkCatalogError({ authenticationFailure: false, cause }),
156
+ ),
157
+ ),
158
+ } satisfies CursorSdkCatalogProbes;
159
+});
160
161
export const makeCursorSdkCatalog = Effect.fn("CursorSdkCatalog.make")(function* (
78
- probes: CursorSdkCatalogProbes = liveProbes,
162
+ probes: CursorSdkCatalogProbes,
163
) {
164
const modelCache = yield* Cache.makeWith(probes.readModels, {
165
capacity: 32,
@@ -101,7 +185,10 @@ export const makeCursorSdkCatalog = Effect.fn("CursorSdkCatalog.make")(function*
185
});
186
});
187
104
-export const layer = Layer.effect(CursorSdkCatalog, makeCursorSdkCatalog());
188
+export const layer = Layer.effect(
189
+ CursorSdkCatalog,
190
+ Effect.flatMap(makeLiveProbes, makeCursorSdkCatalog),
191
+);
192
193
export function layerTest(
194
read: CursorSdkCatalog["Service"]["read"],
packages/provider-cursor/src/server/adapter.test.ts
+3
-1
@@ -33,7 +33,9 @@ import {
33
nestedToolCallFromEnvelope,
34
} from "./adapter.ts";
35
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
36
-import { ConfigurationError } from "./sdk.ts";
36
+import { loadCursorSdk } from "./sdk.ts";
37
+
38
+const { ConfigurationError } = loadCursorSdk();
39
40
describe("CursorAdapterV2", () => {
41
it.effect.each([
packages/provider-cursor/src/server/adapter.ts
+2
-2
@@ -68,7 +68,7 @@ import {
68
subagentThreadTitle,
69
} from "@t3tools/provider-core/server/subagentProjection";
70
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
71
-import { ConfigurationError } from "./sdk.ts";
71
+import { isCursorSdkError } from "./sdk.ts";
72
export { cursorSdkModelSelection } from "./sdkModel.ts";
73
74
const CURSOR_DRIVER_KIND = CursorAgentSdk.CURSOR_PROVIDER;
@@ -336,7 +336,7 @@ class CursorModelUnavailableError extends Schema.TaggedError<CursorModelUnavaila
336
// Uncoded SDK model rejections are identifiable only by message prefix.
337
const classifyCursorModelRejection =
338
(modelSelection: ModelSelection) => (error: CursorAgentSdk.CursorAgentSdkRunnerError) =>
339
- error.cause instanceof ConfigurationError &&
339
+ isCursorSdkError(error.cause, "ConfigurationError") &&
340
error.cause.message.startsWith("Cannot use this model:")
341
? new CursorModelUnavailableError({ model: modelSelection.model, cause: error.cause })
342
: error;
packages/provider-cursor/src/server/auth.test.ts
+3
-1
@@ -11,7 +11,9 @@ import * as Option from "effect/Option";
11
import * as Stream from "effect/Stream";
12
13
import { makeCursorAuth, type CursorAuthOptions } from "./auth.ts";
14
-import { InMemoryCredentialStore } from "./sdk.ts";
14
+import { loadCursorSdk } from "./sdk.ts";
15
+
16
+const { InMemoryCredentialStore } = loadCursorSdk();
17
18
const instanceId = ProviderInstanceId.make("cursor-personal");
19
const owner = "owner-client";
packages/provider-cursor/src/server/auth.ts
+11
-1
@@ -18,7 +18,7 @@ import * as Semaphore from "effect/Semaphore";
18
import * as Stream from "effect/Stream";
19
import * as SubscriptionRef from "effect/SubscriptionRef";
20
21
-import { Cursor, InMemoryCredentialStore } from "./sdk.ts";
21
+import { loadCursorSdk } from "./sdk.ts";
22
import type { ProviderAuthController } from "@t3tools/provider-core/server/auth";
23
24
const AUTH_TIMEOUT_MS = 300_000;
@@ -160,6 +160,16 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu
160
function* (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) {
161
yield* stopSessions.pipe(Effect.ensuring(stopSessionsWithCredentials));
162
// The SDK first writes into memory. Cancellation must not save a late login result.
163
+ const { Cursor, InMemoryCredentialStore } = yield* Effect.try({
164
+ try: loadCursorSdk,
165
+ catch: (cause) =>
166
+ new ProviderSetupError({
167
+ instanceId: options.instanceId,
168
+ operation: "start",
169
+ detail: "Could not load the Cursor SDK. Try signing in again.",
170
+ cause,
171
+ }),
172
+ });
173
const pendingStore = new InMemoryCredentialStore();
174
const urls = yield* Queue.unbounded<string>();
175
yield* Queue.take(urls).pipe(
packages/provider-cursor/src/server/driver.test.ts
+52
-29
@@ -21,6 +21,8 @@ import * as Option from "effect/Option";
21
import * as Stream from "effect/Stream";
22
import { vi } from "vite-plus/test";
23
import * as HttpClient from "effect/http/HttpClient";
24
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
25
+import * as Deferred from "effect/Deferred";
26
27
import {
28
DEFAULT_HANDOFF_TOKEN_CAP,
@@ -35,7 +37,9 @@ import * as CursorKeychain from "./CursorKeychain.ts";
37
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
39
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
38
-import { Cursor } from "./sdk.ts";
40
+import { loadCursorSdk } from "./sdk.ts";
41
+
42
+const { Cursor } = loadCursorSdk();
43
44
const layerTest = TestProviderHost.layer({ runBackgroundWork: false }).pipe(
45
Layer.provideMerge(NodeServices.layer),
@@ -83,19 +87,27 @@ it.layer(layerTest)("CursorDriver", (it) => {
87
});
88
return { apiKey: "instance-browser-key", apiKeyExpiresAtMs: 4_000_000_000_000 };
89
});
86
- const me = vi.spyOn(Cursor, "me").mockResolvedValue({
87
- apiKeyName: "T3 Code",
88
- createdAt: "2026-01-01T00:00:00.000Z",
89
- userEmail: "cursor@example.com",
90
+ const requests: Array<{ url: string; authorization: string | undefined }> = [];
91
+ const client = HttpClient.make((request) => {
92
+ requests.push({ url: request.url, authorization: request.headers.authorization });
93
+ return Effect.succeed(
94
+ HttpClientResponse.fromWeb(
95
+ request,
96
+ Response.json(
97
+ request.url.endsWith("/v1/me")
98
+ ? {
99
+ apiKeyName: "T3 Code",
100
+ createdAt: "2026-01-01T00:00:00.000Z",
101
+ userEmail: "cursor@example.com",
102
+ }
103
+ : { items: [{ id: "auto", displayName: "Auto" }] },
104
+ ),
105
+ ),
106
+ );
107
});
91
- const models = vi
92
- .spyOn(Cursor.models, "list")
93
- .mockResolvedValue([{ id: "auto", displayName: "Auto" }]);
108
yield* Effect.addFinalizer(() =>
109
Effect.sync(() => {
110
login.mockRestore();
97
- me.mockRestore();
98
- models.mockRestore();
111
}),
112
);
113
const input = {
@@ -108,6 +120,7 @@ it.layer(layerTest)("CursorDriver", (it) => {
120
const openedKeys: Array<string | undefined> = [];
121
let closed = 0;
122
const instance = yield* CursorDriver.create(input).pipe(
123
+ Effect.provideService(HttpClient.HttpClient, client),
124
Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
125
assertComplete: Effect.void,
126
open: (request) =>
@@ -131,7 +144,10 @@ it.layer(layerTest)("CursorDriver", (it) => {
144
Stream.runHead,
145
Effect.map(Option.getOrThrow),
146
);
134
- expect(me).toHaveBeenCalledWith({ apiKey: "instance-browser-key" });
147
+ expect(requests).toContainEqual({
148
+ url: "https://api.cursor.com/v1/me",
149
+ authorization: "Bearer instance-browser-key",
150
+ });
151
expect(yield* instance.snapshot.getSnapshot).toMatchObject({
152
status: "ready",
153
auth: {
@@ -158,7 +174,9 @@ it.layer(layerTest)("CursorDriver", (it) => {
174
yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
175
expect(openedKeys).toEqual(["instance-browser-key"]);
176
expect(closed).toBe(0);
161
- const recreated = yield* CursorDriver.create(input);
177
+ const recreated = yield* CursorDriver.create(input).pipe(
178
+ Effect.provideService(HttpClient.HttpClient, client),
179
+ );
180
expect((yield* recreated.snapshot.refresh).auth.status).toBe("authenticated");
181
yield* instance.auth!.logout(Effect.void);
182
expect(closed).toBe(1);
@@ -177,20 +195,24 @@ it.layer(layerTest)("CursorDriver", (it) => {
195
Effect.gen(function* () {
196
const fileSystem = yield* FileSystem.FileSystem;
197
const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-window-" });
180
- const catalog = Promise.withResolvers<Array<SDKModel>>();
181
- const catalogRequested = Promise.withResolvers<void>();
182
- const me = vi.spyOn(Cursor, "me").mockResolvedValue({
183
- apiKeyName: "T3 Code",
184
- createdAt: "2026-01-01T00:00:00.000Z",
185
- });
186
- const models = vi.spyOn(Cursor.models, "list").mockImplementation(() => {
187
- catalogRequested.resolve();
188
- return catalog.promise;
189
- });
190
- yield* Effect.addFinalizer(() =>
191
- Effect.sync(() => {
192
- me.mockRestore();
193
- models.mockRestore();
198
+ const catalog = yield* Deferred.make<Array<SDKModel>>();
199
+ const catalogRequested = yield* Deferred.make<void>();
200
+ let failUser = false;
201
+ const client = HttpClient.make((request) =>
202
+ Effect.gen(function* () {
203
+ if (request.url.endsWith("/v1/me"))
204
+ return HttpClientResponse.fromWeb(
205
+ request,
206
+ Response.json(
207
+ failUser
208
+ ? { error: { message: "Cursor is unreachable" } }
209
+ : { apiKeyName: "T3 Code", createdAt: "2026-01-01T00:00:00.000Z" },
210
+ { status: failUser ? 503 : 200 },
211
+ ),
212
+ );
213
+ yield* Deferred.succeed(catalogRequested, undefined);
214
+ const models = yield* Deferred.await(catalog);
215
+ return HttpClientResponse.fromWeb(request, Response.json({ items: models }));
216
}),
217
);
218
const instanceId = ProviderInstanceId.make("cursor-catalog-window");
@@ -203,6 +225,7 @@ it.layer(layerTest)("CursorDriver", (it) => {
225
environment: [{ name: "CURSOR_API_KEY", value: "catalog-window-key", sensitive: true }],
226
config: CursorDriver.defaultConfig(),
227
}).pipe(
228
+ Effect.provideService(HttpClient.HttpClient, client),
229
Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
230
assertComplete: Effect.void,
231
open: (request) =>
@@ -253,7 +276,7 @@ it.layer(layerTest)("CursorDriver", (it) => {
276
runtimePolicy,
277
});
278
const refresh = yield* instance.snapshot.refresh.pipe(Effect.forkScoped);
256
- yield* Effect.promise(() => catalogRequested.promise);
279
+ yield* Deferred.await(catalogRequested);
280
expect(runtime.getModelContextWindow?.(selection())).toBeUndefined();
281
const providerThread = yield* runtime.ensureThread({
282
threadId,
@@ -324,7 +347,7 @@ it.layer(layerTest)("CursorDriver", (it) => {
347
};
348
});
349
const beforeCatalog = yield* startTurn("1m");
327
- catalog.resolve([
350
+ yield* Deferred.succeed(catalog, [
351
{
352
id: "claude-opus-5-5",
353
displayName: "Claude Opus 5.5",
@@ -348,7 +371,7 @@ it.layer(layerTest)("CursorDriver", (it) => {
371
const catalogDefault = yield* startTurn();
372
const explicitWindow = yield* startTurn("500k");
373
const unknownWindow = yield* startTurn("max");
351
- me.mockRejectedValue(new Error("Cursor is unreachable"));
374
+ failUser = true;
375
expect((yield* instance.snapshot.refresh).status).toBe("error");
376
const retainedDefault = yield* startTurn();
377
packages/provider-cursor/src/server/driver.ts
+1
-1
@@ -245,7 +245,6 @@ export const CursorDriver: ProviderDriver<
245
),
246
),
247
),
248
- Effect.provideService(HttpClient.HttpClient, httpClient),
248
Effect.provideService(FileSystem.FileSystem, fileSystem),
249
Effect.provideService(Path.Path, path),
250
Effect.provideService(CursorKeychain.CursorKeychain, keychain),
@@ -259,6 +258,7 @@ export const CursorDriver: ProviderDriver<
258
}),
259
),
260
Effect.provide(CursorSdkCatalog.layer),
261
+ Effect.provideService(HttpClient.HttpClient, httpClient),
262
);
263
264
const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
packages/provider-cursor/src/server/sdk.test.ts
new
+57
@@ -0,0 +1,57 @@
1
+import { describe, expect, it, vi } from "vite-plus/test";
2
+
3
+const fixture = vi.hoisted(() => {
4
+ class SdkError extends Error {}
5
+ const sdk = {
6
+ CursorSdkError: SdkError,
7
+ AuthenticationError: SdkError,
8
+ ConfigurationError: SdkError,
9
+ };
10
+ const sqlite = { SqliteLocalAgentStore: {} };
11
+ const requireSdk = vi.fn((id: string) => (id === "@cursor/sdk" ? sdk : sqlite));
12
+ return { sdk, sqlite, requireSdk };
13
+});
14
+
15
+vi.mock("node:module", () => ({ createRequire: () => fixture.requireSdk }));
16
+
17
+describe("Cursor disk modules", () => {
18
+ it("loads on demand, shares exports across callers, and leaves SQLite unloaded", async () => {
19
+ vi.resetModules();
20
+ fixture.requireSdk.mockClear();
21
+ const sdk = await import("./sdk.ts");
22
+ expect(fixture.requireSdk).not.toHaveBeenCalled();
23
+ expect(sdk.isCursorSdkError(new Error("unloaded"), "CursorSdkError")).toBe(false);
24
+ const modules = await Promise.all([
25
+ Promise.resolve().then(sdk.loadCursorSdk),
26
+ Promise.resolve().then(sdk.loadCursorSdk),
27
+ ]);
28
+ expect(modules).toEqual([fixture.sdk, fixture.sdk]);
29
+ expect(modules[0]).toBe(modules[1]);
30
+ expect(fixture.requireSdk.mock.calls).toEqual([["@cursor/sdk"]]);
31
+ expect(
32
+ sdk.isCursorSdkError(new fixture.sdk.CursorSdkError("same class"), "CursorSdkError"),
33
+ ).toBe(true);
34
+ expect(sdk.loadCursorSqlite()).toBe(fixture.sqlite);
35
+ expect(sdk.loadCursorSqlite()).toBe(fixture.sqlite);
36
+ expect(fixture.requireSdk.mock.calls).toEqual([["@cursor/sdk"], ["@cursor/sdk/sqlite"]]);
37
+ });
38
+
39
+ it("surfaces failed loads and permits a later retry without caching partial exports", async () => {
40
+ vi.resetModules();
41
+ fixture.requireSdk.mockClear();
42
+ const sdk = await import("./sdk.ts");
43
+ const failure = new Error("missing native chunk");
44
+ fixture.requireSdk.mockImplementationOnce(() => {
45
+ throw failure;
46
+ });
47
+ expect(sdk.loadCursorSdk).toThrow(failure);
48
+ expect(sdk.isCursorSdkError(failure, "CursorSdkError")).toBe(false);
49
+ expect(sdk.loadCursorSdk()).toBe(fixture.sdk);
50
+ fixture.requireSdk.mockImplementationOnce(() => {
51
+ throw failure;
52
+ });
53
+ expect(sdk.loadCursorSqlite).toThrow(failure);
54
+ expect(sdk.loadCursorSqlite()).toBe(fixture.sqlite);
55
+ expect(fixture.requireSdk).toHaveBeenCalledTimes(4);
56
+ });
57
+});
packages/provider-cursor/src/server/sdk.ts
+28
-19
@@ -1,25 +1,34 @@
1
// @effect-diagnostics nodeBuiltinImport:off -- The SDK must load from disk beside its Webpack chunks.
2
import * as NodeModule from "node:module";
3
4
-// createRequire loads the disk-backed SDK and adjacent chunks even from a Node SEA executable.
4
+// createRequire preserves adjacent Webpack chunks and native modules in bundled/SEA builds.
5
const requireCursorSdk = NodeModule.createRequire(import.meta.url);
6
-const sdkImportStart = performance.now();
7
-export const {
8
- Agent,
9
- AuthenticationError,
10
- ConfigurationError,
11
- createAgentPlatform,
12
- Cursor,
13
- CursorSdkError,
14
- InMemoryCredentialStore,
15
-} = requireCursorSdk("@cursor/sdk") as typeof import("@cursor/sdk");
16
-if (process.env.T3CODE_STARTUP_PROFILE_DIR) {
17
- performance.measure("provider.cursor.importSdk", { start: sdkImportStart });
6
+let sdk: typeof import("@cursor/sdk") | undefined;
7
+let sqlite: typeof import("@cursor/sdk/sqlite") | undefined;
8
+
9
+export function loadCursorSdk(): typeof import("@cursor/sdk") {
10
+ if (sdk !== undefined) return sdk;
11
+ const start = performance.now();
12
+ sdk = requireCursorSdk("@cursor/sdk") as typeof import("@cursor/sdk");
13
+ if (process.env.T3CODE_STARTUP_PROFILE_DIR) {
14
+ performance.measure("provider.cursor.importSdk", { start });
15
+ }
16
+ return sdk;
17
+}
18
+
19
+export function loadCursorSqlite(): typeof import("@cursor/sdk/sqlite") {
20
+ if (sqlite !== undefined) return sqlite;
21
+ const start = performance.now();
22
+ sqlite = requireCursorSdk("@cursor/sdk/sqlite") as typeof import("@cursor/sdk/sqlite");
23
+ if (process.env.T3CODE_STARTUP_PROFILE_DIR) {
24
+ performance.measure("provider.cursor.importSqliteStore", { start });
25
+ }
26
+ return sqlite;
27
}
19
-const sqliteImportStart = performance.now();
20
-export const { SqliteLocalAgentStore } = requireCursorSdk(
21
- "@cursor/sdk/sqlite",
22
-) as typeof import("@cursor/sdk/sqlite");
23
-if (process.env.T3CODE_STARTUP_PROFILE_DIR) {
24
- performance.measure("provider.cursor.importSqliteStore", { start: sqliteImportStart });
28
+
29
+// Error classification must not initialize the SDK when the load itself failed.
30
+export function isCursorSdkError<
31
+ K extends "AuthenticationError" | "ConfigurationError" | "CursorSdkError",
32
+>(cause: unknown, kind: K): cause is InstanceType<(typeof import("@cursor/sdk"))[K]> {
33
+ return sdk !== undefined && cause instanceof sdk[kind];
34
}
packages/provider-cursor/src/server/status.test.ts
+6
-1
@@ -13,7 +13,9 @@ import {
13
checkCursorProviderStatus,
14
} from "./status.ts";
15
import * as CursorSdkCatalog from "./CursorSdkCatalog.ts";
16
-import { CursorSdkError } from "./sdk.ts";
16
+import { loadCursorSdk } from "./sdk.ts";
17
+
18
+const { CursorSdkError } = loadCursorSdk();
19
20
const decodeCursorSettings = Schema.decodeSync(CursorSettingsSchema);
21
@@ -243,6 +245,7 @@ describe("checkCursorProviderStatus", () => {
245
Effect.fail(
246
new CursorSdkCatalog.CursorSdkCatalogError({
247
authenticationFailure: false,
248
+ code: "plan_required",
249
cause: new CursorSdkError(
250
"[plan_required] Cloud Agent is not available for free users. Please upgrade to Pro.",
251
{ code: "plan_required", status: 403 },
@@ -336,6 +339,8 @@ describe("checkCursorProviderStatus", () => {
339
Effect.fail(
340
new CursorSdkCatalog.CursorSdkCatalogError({
341
authenticationFailure: meFailure.status === 401,
342
+ ...(meFailure.status === undefined ? {} : { status: meFailure.status }),
343
+ ...(meFailure.code === undefined ? {} : { code: meFailure.code }),
344
cause: meFailure,
345
}),
346
),
packages/provider-cursor/src/server/textGeneration.test.ts
+5
-3
@@ -28,9 +28,11 @@ const cursorSdkMock = vi.hoisted(() => ({
28
}));
29
30
vi.mock("./sdk.ts", () => ({
31
- Agent: { create: cursorSdkMock.create },
32
- createAgentPlatform: vi.fn(),
33
- SqliteLocalAgentStore: { open: cursorSdkMock.storeOpen },
31
+ loadCursorSdk: () => ({
32
+ Agent: { create: cursorSdkMock.create },
33
+ createAgentPlatform: vi.fn(),
34
+ }),
35
+ loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: cursorSdkMock.storeOpen } }),
36
}));
37
38
let hasCustomPolicy = false;
packages/provider-cursor/src/server/textGeneration.ts
+5
-2
@@ -50,7 +50,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
50
withAccess?: CursorAuth["withAccess"],
51
) {
52
const fs = yield* FileSystem.FileSystem;
53
- const { Agent, SqliteLocalAgentStore } = yield* CursorSdk.CursorSdk;
53
+ const sdk = yield* CursorSdk.CursorSdk;
54
const resolvedEnvironment = environment ?? process.env;
55
56
const resolveCursorApiKey = Effect.fn("CursorTextGeneration.resolveCursorApiKey")(function* (
@@ -83,6 +83,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
83
const { operation, prompt, modelSelection } = input;
84
85
const apiKey = yield* resolveCursorApiKey(operation);
86
+ const { Agent } = yield* Effect.try(sdk.load);
87
// sandbox.json expands writable paths independently of settingSources; the public API cannot override it.
88
if (yield* fs.exists(`${yield* HostProcess.HomeDirectory}/.cursor/sandbox.json`)) {
89
return yield* new TextGenerationError({
@@ -95,7 +96,9 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
96
// Only store disposal releases SDK SQLite handles; keep state outside the empty workspace.
97
const stateRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-state-" });
98
const store = yield* Effect.acquireRelease(
98
- Effect.tryPromise(() => SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot })),
99
+ Effect.tryPromise(() =>
100
+ sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot }),
101
+ ),
102
(store) => Effect.tryPromise(() => store.dispose()).pipe(Effect.ignore({ log: true })),
103
);
104
const agentOptions = {