Open History to see the last commit
1/**
2 * CursorDriver — `ProviderDriver` for the Cursor Agent SDK runtime.
3 *
4 * Provider status, model discovery, orchestration, and text generation use the
5 * official Cursor SDK with an instance browser login or CURSOR_API_KEY.
6 *
7 * @module provider/Drivers/CursorDriver
8 */
9import { ProviderDriverKind, ProviderSetupError } from "@t3tools/contracts";
10import { CursorSettings } from "../settings.ts";
11import * as Effect from "effect/Effect";
12import * as Crypto from "effect/Crypto";
13import * as FileSystem from "effect/FileSystem";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import { HttpClient } from "effect/http";
17import { readCursorUsageLimits } from "./usageLimits.ts";
18
19import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
20import { makeCursorTextGeneration } from "./textGeneration.ts";
21import { CursorAdapterV2Driver, type CursorAdapterV2DriverEnv } from "./adapter.ts";
22import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
23import { buildInitialCursorProviderSnapshot, checkCursorProviderStatus } from "./status.ts";
24import * as CursorSdkCatalog from "./CursorSdkCatalog.ts";
25import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
26import {
27 defaultProviderContinuationIdentity,
28 type ProviderDriver,
29 type ProviderInstance,
30} from "@t3tools/provider-core/server/driver";
31import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
32import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
33import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
34import {
35 haveProviderSnapshotSettingsChanged,
36 makeProviderSnapshotSettingsSource,
37 type ProviderSnapshotSettings,
38} from "@t3tools/provider-core/server/snapshotSettings";
39import { probeCursorSkills } from "./skills.ts";
40import { makeCursorAuth } from "./auth.ts";
41import * as CursorCredentialStore from "./credentialStore.ts";
42import * as CursorAgentSdk from "./CursorAgentSdk.ts";
43const decodeCursorSettings = Schema.decodeSync(CursorSettings);
44const isSdkRunnerError = Schema.is(CursorAgentSdk.CursorAgentSdkRunnerError);
45
46const DRIVER_KIND = ProviderDriverKind.make("cursor");
47const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({
48 provider: DRIVER_KIND,
49 packageName: null,
50});
51
52export type CursorDriverEnv =
53 | CursorAdapterV2DriverEnv
54 | Crypto.Crypto
55 | FileSystem.FileSystem
56 | Path.Path
57 | HttpClient.HttpClient
58 | ProviderHost.ProviderHost;
59
60export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
61 driverKind: DRIVER_KIND,
62 metadata: {
63 displayName: "Cursor",
64 supportsMultipleInstances: true,
65 },
66 configSchema: CursorSettings,
67 defaultConfig: (): CursorSettings => decodeCursorSettings({}),
68 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
69 Effect.gen(function* () {
70 const host = yield* ProviderHost.ProviderHost;
71 const fileSystem = yield* FileSystem.FileSystem;
72 const path = yield* Path.Path;
73 const httpClient = yield* HttpClient.HttpClient;
74 const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;
75 const processEnv = mergeProviderInstanceEnvironment(environment);
76 const continuationIdentity = defaultProviderContinuationIdentity({
77 driverKind: DRIVER_KIND,
78 instanceId,
79 });
80 const stampIdentity = withInstanceIdentity({
81 instanceId,
82 driverKind: DRIVER_KIND,
83 displayName: displayName ?? "Cursor",
84 accentColor,
85 continuationGroupKey: continuationIdentity.continuationKey,
86 });
87 const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
88 const credentials = yield* CursorCredentialStore.makeCursorCredentialStore(
89 instanceId,
90 path.join(
91 host.paths.stateDir,
92 "provider-auth",
93 encodeURIComponent(instanceId),
94 "cursor.json",
95 ),
96 ).pipe(
97 Effect.mapError(
98 (cause) =>
99 new ProviderDriverError({
100 driver: DRIVER_KIND,
101 instanceId,
102 detail: "Could not open the Cursor credential store.",
103 cause,
104 }),
105 ),
106 );
107 const auth = yield* makeCursorAuth({
108 instanceId,
109 displayName: displayName ?? "Cursor",
110 enabled,
111 ...(processEnv.CURSOR_API_KEY ? { apiKey: processEnv.CURSOR_API_KEY } : {}),
112 store: credentials.store,
113 credentialBinding: credentials.binding,
114 onChanged: (signedIn): Effect.Effect<void, ProviderSetupError> =>
115 snapshot.refresh.pipe(
116 Effect.flatMap((provider) =>
117 !signedIn || provider.auth.status === "authenticated"
118 ? Effect.void
119 : Effect.fail(
120 new ProviderSetupError({
121 instanceId,
122 operation: "start",
123 detail: provider.message ?? "Could not verify the Cursor sign-in. Try again.",
124 }),
125 ),
126 ),
127 ),
128 });
129 const stampSnapshot: typeof stampIdentity = (draft) =>
130 stampIdentity({
131 ...draft,
132 setup: { canAuthenticate: !auth.usesApiKey, canInstall: false },
133 auth: {
134 ...draft.auth,
135 canLogout: !auth.usesApiKey,
136 },
137 });
138
139 const orchestrationAdapter = yield* CursorAdapterV2Driver.create({
140 instanceId,
141 displayName,
142 accentColor,
143 environment,
144 enabled,
145 config,
146 }).pipe(
147 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
148 ...sdkRunner,
149 open: (input) =>
150 auth.requireApiKey.pipe(
151 Effect.flatMap((apiKey) =>
152 Effect.acquireRelease(
153 sdkRunner
154 .open({ ...input, options: { ...input.options, apiKey } })
155 .pipe(
156 Effect.flatMap((session) =>
157 Effect.cached(session.close).pipe(
158 Effect.map((close) => ({ ...session, close })),
159 ),
160 ),
161 ),
162 (session) => session.close.pipe(Effect.ignore),
163 ),
164 ),
165 auth.withAccess,
166 Effect.mapError((cause) =>
167 isSdkRunnerError(cause)
168 ? cause
169 : new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "open", cause }),
170 ),
171 ),
172 }),
173 Effect.mapError(
174 (cause) =>
175 new ProviderDriverError({
176 driver: DRIVER_KIND,
177 instanceId,
178 detail: "Failed to build Cursor orchestration adapter.",
179 cause,
180 }),
181 ),
182 );
183 const textGeneration = yield* makeCursorTextGeneration(
184 effectiveConfig,
185 processEnv,
186 auth.requireApiKey,
187 auth.withAccess,
188 );
189
190 const checkProvider = auth.readApiKey.pipe(
191 Effect.orElseSucceed(() => undefined),
192 Effect.flatMap((apiKey) =>
193 checkCursorProviderStatus(
194 effectiveConfig,
195 {
196 ...processEnv,
197 CURSOR_API_KEY: apiKey,
198 },
199 auth.usesApiKey ? "api-key" : "browser",
200 ).pipe(
201 Effect.flatMap((snapshot) =>
202 effectiveConfig.enabled &&
203 snapshot.installed &&
204 snapshot.auth.status === "authenticated"
205 ? host.settings.get.pipe(
206 Effect.flatMap((settings) =>
207 readCursorUsageLimits(
208 effectiveConfig,
209 { ...processEnv, CURSOR_API_KEY: apiKey },
210 settings.cursorKeychainUsageEnabled,
211 ),
212 ),
213 Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),
214 )
215 : Effect.succeed(snapshot),
216 ),
217 ),
218 ),
219 Effect.provideService(HttpClient.HttpClient, httpClient),
220 Effect.provideService(FileSystem.FileSystem, fileSystem),
221 Effect.provideService(Path.Path, path),
222 Effect.map(stampSnapshot),
223 Effect.provide(CursorSdkCatalog.layer),
224 );
225
226 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, host.settings);
227 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
228 resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
229 getSettings: snapshotSettings.getSettings,
230 streamSettings: snapshotSettings.streamSettings,
231 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
232 initialSnapshot: (settings) =>
233 buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampSnapshot)),
234 checkProvider,
235 }).pipe(
236 Effect.mapError(
237 (cause) =>
238 new ProviderDriverError({
239 driver: DRIVER_KIND,
240 instanceId,
241 detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,
242 cause,
243 }),
244 ),
245 );
246
247 return {
248 instanceId,
249 driverKind: DRIVER_KIND,
250 continuationIdentity,
251 displayName,
252 accentColor,
253 enabled,
254 auth: auth.controller,
255 snapshot,
256 snapshotForCwd: (cwd) =>
257 !effectiveConfig.enabled
258 ? snapshot.getSnapshot
259 : Effect.all([
260 snapshot.getSnapshot,
261 probeCursorSkills(cwd, processEnv).pipe(
262 Effect.provideService(FileSystem.FileSystem, fileSystem),
263 Effect.provideService(Path.Path, path),
264 Effect.mapError(
265 (cause) =>
266 new ProviderDriverError({
267 driver: DRIVER_KIND,
268 instanceId,
269 detail: `Failed to discover Cursor skills for '${cwd}'`,
270 cause,
271 }),
272 ),
273 ),
274 ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),
275 orchestrationAdapter,
276 textGeneration,
277 } satisfies ProviderInstance;
278 }),
279};