Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CursorDriver.ts

290 lines10.6 KB

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 * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
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 "../makeManagedServerProvider.ts";
33import {
34 defaultProviderContinuationIdentity,
35 type ProviderDriver,
36 type ProviderInstance,
37} from "../ProviderDriver.ts";
38import { withInstanceIdentity } from "./instanceIdentity.ts";
39import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
40import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
41import {
42 haveProviderSnapshotSettingsChanged,
43 makeProviderSnapshotSettingsSource,
44 type ProviderSnapshotSettings,
45} from "../providerUpdateSettings.ts";
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 | BackgroundPolicy.BackgroundPolicy
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 fileSystem = yield* FileSystem.FileSystem;
83 const path = yield* Path.Path;
84 const httpClient = yield* HttpClient.HttpClient;
85 const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;
86 const processEnv = mergeProviderInstanceEnvironment(environment);
87 const continuationIdentity = defaultProviderContinuationIdentity({
88 driverKind: DRIVER_KIND,
89 instanceId,
90 });
91 const stampIdentity = withInstanceIdentity({
92 instanceId,
93 driverKind: DRIVER_KIND,
94 displayName: displayName ?? "Cursor",
95 accentColor,
96 continuationGroupKey: continuationIdentity.continuationKey,
97 });
98 const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
99 const credentials = yield* CursorCredentialStore.makeCursorCredentialStore(
100 instanceId,
101 path.join(
102 (yield* ServerConfig.ServerConfig).stateDir,
103 "provider-auth",
104 encodeURIComponent(instanceId),
105 "cursor.json",
106 ),
107 ).pipe(
108 Effect.mapError(
109 (cause) =>
110 new ProviderDriverError({
111 driver: DRIVER_KIND,
112 instanceId,
113 detail: "Could not open the Cursor credential store.",
114 cause,
115 }),
116 ),
117 );
118 const auth = yield* makeCursorAuth({
119 instanceId,
120 displayName: displayName ?? "Cursor",
121 enabled,
122 ...(processEnv.CURSOR_API_KEY ? { apiKey: processEnv.CURSOR_API_KEY } : {}),
123 store: credentials.store,
124 credentialBinding: credentials.binding,
125 onChanged: (signedIn): Effect.Effect<void, ProviderSetupError> =>
126 snapshot.refresh.pipe(
127 Effect.flatMap((provider) =>
128 !signedIn || provider.auth.status === "authenticated"
129 ? Effect.void
130 : Effect.fail(
131 new ProviderSetupError({
132 instanceId,
133 operation: "start",
134 detail: provider.message ?? "Could not verify the Cursor sign-in. Try again.",
135 }),
136 ),
137 ),
138 ),
139 });
140 const stampSnapshot: typeof stampIdentity = (draft) =>
141 stampIdentity({
142 ...draft,
143 setup: { canAuthenticate: !auth.usesApiKey, canInstall: false },
144 auth: {
145 ...draft.auth,
146 canLogout: !auth.usesApiKey,
147 },
148 });
149​
150 const orchestrationAdapter = yield* CursorAdapterV2Driver.create({
151 instanceId,
152 displayName,
153 accentColor,
154 environment,
155 enabled,
156 config,
157 }).pipe(
158 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
159 ...sdkRunner,
160 open: (input) =>
161 auth.requireApiKey.pipe(
162 Effect.flatMap((apiKey) =>
163 Effect.acquireRelease(
164 sdkRunner
165 .open({ ...input, options: { ...input.options, apiKey } })
166 .pipe(
167 Effect.flatMap((session) =>
168 Effect.cached(session.close).pipe(
169 Effect.map((close) => ({ ...session, close })),
170 ),
171 ),
172 ),
173 (session) => session.close.pipe(Effect.ignore),
174 ),
175 ),
176 auth.withAccess,
177 Effect.mapError((cause) =>
178 isSdkRunnerError(cause)
179 ? cause
180 : new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "open", cause }),
181 ),
182 ),
183 }),
184 Effect.mapError(
185 (cause) =>
186 new ProviderDriverError({
187 driver: DRIVER_KIND,
188 instanceId,
189 detail: "Failed to build Cursor orchestration adapter.",
190 cause,
191 }),
192 ),
193 );
194 const textGeneration = yield* makeCursorTextGeneration(
195 effectiveConfig,
196 processEnv,
197 auth.requireApiKey,
198 auth.withAccess,
199 );
200​
201 const checkProvider = auth.readApiKey.pipe(
202 Effect.orElseSucceed(() => undefined),
203 Effect.flatMap((apiKey) =>
204 checkCursorProviderStatus(
205 effectiveConfig,
206 {
207 ...processEnv,
208 CURSOR_API_KEY: apiKey,
209 },
210 auth.usesApiKey ? "api-key" : "browser",
211 ).pipe(
212 Effect.flatMap((snapshot) =>
213 effectiveConfig.enabled &&
214 snapshot.installed &&
215 snapshot.auth.status === "authenticated"
216 ? serverSettings.getSettings.pipe(
217 Effect.flatMap((settings) =>
218 readCursorUsageLimits(
219 effectiveConfig,
220 { ...processEnv, CURSOR_API_KEY: apiKey },
221 settings.cursorKeychainUsageEnabled,
222 ),
223 ),
224 Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),
225 )
226 : Effect.succeed(snapshot),
227 ),
228 ),
229 ),
230 Effect.provideService(HttpClient.HttpClient, httpClient),
231 Effect.provideService(FileSystem.FileSystem, fileSystem),
232 Effect.provideService(Path.Path, path),
233 Effect.map(stampSnapshot),
234 Effect.provide(CursorSdkCatalog.layer),
235 );
236​
237 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
238 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
239 resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
240 getSettings: snapshotSettings.getSettings,
241 streamSettings: snapshotSettings.streamSettings,
242 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
243 initialSnapshot: (settings) =>
244 buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampSnapshot)),
245 checkProvider,
246 }).pipe(
247 Effect.mapError(
248 (cause) =>
249 new ProviderDriverError({
250 driver: DRIVER_KIND,
251 instanceId,
252 detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,
253 cause,
254 }),
255 ),
256 );
257​
258 return {
259 instanceId,
260 driverKind: DRIVER_KIND,
261 continuationIdentity,
262 displayName,
263 accentColor,
264 enabled,
265 auth: auth.controller,
266 snapshot,
267 snapshotForCwd: (cwd) =>
268 !effectiveConfig.enabled
269 ? snapshot.getSnapshot
270 : Effect.all([
271 snapshot.getSnapshot,
272 probeCursorSkills(cwd, processEnv).pipe(
273 Effect.provideService(FileSystem.FileSystem, fileSystem),
274 Effect.provideService(Path.Path, path),
275 Effect.mapError(
276 (cause) =>
277 new ProviderDriverError({
278 driver: DRIVER_KIND,
279 instanceId,
280 detail: `Failed to discover Cursor skills for '${cwd}'`,
281 cause,
282 }),
283 ),
284 ),
285 ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),
286 orchestrationAdapter,
287 textGeneration,
288 } satisfies ProviderInstance;
289 }),
290};