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