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