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 environment: processEnv,
171 getModels: () => catalogModels,
172 }).pipe(
173 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
174 ...sdkRunner,
175 open: (input) =>
176 auth.requireApiKey.pipe(
177 Effect.flatMap((apiKey) =>
178 Effect.acquireRelease(
179 sdkRunner
180 .open({ ...input, options: { ...input.options, apiKey } })
181 .pipe(
182 Effect.flatMap((session) =>
183 Effect.cached(session.close).pipe(
184 Effect.map((close) => ({ ...session, close })),
185 ),
186 ),
187 ),
188 (session) => session.close.pipe(Effect.ignore),
189 ),
190 ),
191 auth.withAccess,
192 Effect.mapError((cause) =>
193 isSdkRunnerError(cause)
194 ? cause
195 : new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "open", cause }),
196 ),
197 ),
198 }),
199 Effect.mapError(
200 (cause) =>
201 new ProviderDriverError({
202 driver: DRIVER_KIND,
203 instanceId,
204 detail: "Failed to build Cursor orchestration adapter.",
205 cause,
206 }),
207 ),
208 );
209 const textGeneration = yield* makeCursorTextGeneration(
210 effectiveConfig,
211 processEnv,
212 auth.requireApiKey,
213 auth.withAccess,
214 );
215
216 const checkProvider = auth.readApiKey.pipe(
217 Effect.orElseSucceed(() => undefined),
218 Effect.flatMap((apiKey) =>
219 checkCursorProviderStatus(
220 effectiveConfig,
221 {
222 ...processEnv,
223 CURSOR_API_KEY: apiKey,
224 },
225 auth.usesApiKey ? "api-key" : "browser",
226 ).pipe(
227 Effect.filterOrElse(
228 (snapshot) =>
229 !(
230 effectiveConfig.enabled &&
231 snapshot.installed &&
232 snapshot.auth.status === "authenticated"
233 ),
234 (snapshot) =>
235 host.settings.get.pipe(
236 Effect.flatMap((settings) =>
237 readCursorUsageLimits(
238 effectiveConfig,
239 { ...processEnv, CURSOR_API_KEY: apiKey },
240 settings.cursorKeychainUsageEnabled,
241 ),
242 ),
243 Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),
244 ),
245 ),
246 ),
247 ),
248 Effect.provideService(HttpClient.HttpClient, httpClient),
249 Effect.provideService(FileSystem.FileSystem, fileSystem),
250 Effect.provideService(Path.Path, path),
251 Effect.provideService(CursorKeychain.CursorKeychain, keychain),
252 Effect.map(stampSnapshot),
253 Effect.tap((provider) =>
254 Effect.sync(() => {
255 // A failed check lists only custom models, so keep the last loaded catalog.
256 if (provider.models.some((model) => !model.isCustom)) {
257 catalogModels = provider.models;
258 }
259 }),
260 ),
261 Effect.provide(CursorSdkCatalog.layer),
262 );
263
264 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
265 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
266 resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
267 getSettings: snapshotSettings.getSettings,
268 streamSettings: snapshotSettings.streamSettings,
269 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
270 initialSnapshot: (settings) =>
271 buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampSnapshot)),
272 checkProvider,
273 }).pipe(
274 Effect.mapError(
275 (cause) =>
276 new ProviderDriverError({
277 driver: DRIVER_KIND,
278 instanceId,
279 detail: "Failed to build Cursor snapshot.",
280 cause,
281 }),
282 ),
283 );
284
285 return {
286 instanceId,
287 driverKind: DRIVER_KIND,
288 continuationIdentity,
289 displayName,
290 accentColor,
291 enabled,
292 auth: auth.controller,
293 snapshot,
294 snapshotForCwd: (cwd) =>
295 !effectiveConfig.enabled
296 ? snapshot.getSnapshot
297 : Effect.all([
298 snapshot.getSnapshot,
299 probeCursorSkills(cwd, processEnv).pipe(
300 Effect.provideService(FileSystem.FileSystem, fileSystem),
301 Effect.provideService(Path.Path, path),
302 Effect.mapError(
303 (cause) =>
304 new ProviderDriverError({
305 driver: DRIVER_KIND,
306 instanceId,
307 detail: `Failed to discover Cursor skills for '${cwd}'`,
308 cause,
309 }),
310 ),
311 ),
312 ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),
313 orchestrationAdapter,
314 textGeneration,
315 } satisfies ProviderInstance;
316 }),
317};