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