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