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