Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

driver.ts

318 lines10.9 KB

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 SecureRandom from "effect/crypto/SecureRandom";
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 | SecureRandom.SecureRandom
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: ({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }) =>
78 CursorUsageAccounts.CursorUsageAccounts.pipe(
79 Effect.flatMap((accounts) =>
80 accounts.scan({
81 instances,
82 keychainUsageEnabled: settings.cursorKeychainUsageEnabled,
83 windowStartMs,
84 retentionCutoffMs,
85 awaitRefresh,
86 }),
87 ),
88 ),
89 },
90 create: Effect.fn("CursorDriver.create")(function* ({
91 instanceId,
92 displayName,
93 accentColor,
94 environment,
95 enabled,
96 config,
97 }) {
98 const host = yield* ProviderHost.ProviderHost;
99 const fileSystem = yield* FileSystem.FileSystem;
100 const path = yield* Path.Path;
101 const httpClient = yield* HttpClient.HttpClient;
102 const keychain = yield* CursorKeychain.CursorKeychain;
103 const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;
104 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
105 const continuationIdentity = defaultProviderContinuationIdentity({
106 driverKind: DRIVER_KIND,
107 instanceId,
108 });
109 const stampIdentity = withInstanceIdentity({
110 instanceId,
111 driverKind: DRIVER_KIND,
112 displayName: displayName ?? "Cursor",
113 accentColor,
114 continuationGroupKey: continuationIdentity.continuationKey,
115 });
116 const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
117 const credentials = yield* CursorCredentialStore.makeCursorCredentialStore(
118 instanceId,
119 path.join(
120 host.paths.stateDir,
121 "provider-auth",
122 encodeURIComponent(instanceId),
123 "cursor.json",
124 ),
125 ).pipe(
126 Effect.mapError(
127 (cause) =>
128 new ProviderDriverError({
129 driver: DRIVER_KIND,
130 instanceId,
131 detail: "Could not open the Cursor credential store.",
132 cause,
133 }),
134 ),
135 );
136 const auth = yield* makeCursorAuth({
137 instanceId,
138 displayName: displayName ?? "Cursor",
139 enabled,
140 ...(processEnv.CURSOR_API_KEY ? { apiKey: processEnv.CURSOR_API_KEY } : {}),
141 store: credentials.store,
142 credentialBinding: credentials.binding,
143 onChanged: (signedIn): Effect.Effect<void, ProviderSetupError> =>
144 snapshot.refresh.pipe(
145 Effect.flatMap((provider) =>
146 !signedIn || provider.auth.status === "authenticated"
147 ? Effect.void
148 : Effect.fail(
149 new ProviderSetupError({
150 instanceId,
151 operation: "start",
152 detail: provider.message ?? "Could not verify the Cursor sign-in. Try again.",
153 }),
154 ),
155 ),
156 ),
157 });
158 const stampSnapshot: typeof stampIdentity = (draft) =>
159 stampIdentity({
160 ...draft,
161 setup: { canAuthenticate: !auth.usesApiKey, canInstall: false },
162 auth: {
163 ...draft.auth,
164 canLogout: !auth.usesApiKey,
165 },
166 });
167​
168 let catalogModels: ReadonlyArray<ServerProviderModel> = [];
169 const orchestrationAdapter = yield* makeCursorAdapterV2({
170 instanceId,
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.filterOrElse(
229 (snapshot) =>
230 !(
231 effectiveConfig.enabled &&
232 snapshot.installed &&
233 snapshot.auth.status === "authenticated"
234 ),
235 (snapshot) =>
236 host.settings.get.pipe(
237 Effect.flatMap((settings) =>
238 readCursorUsageLimits(
239 effectiveConfig,
240 { ...processEnv, CURSOR_API_KEY: apiKey },
241 settings.cursorKeychainUsageEnabled,
242 ),
243 ),
244 Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),
245 ),
246 ),
247 ),
248 ),
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 Effect.provideService(HttpClient.HttpClient, httpClient),
263 );
264​
265 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
266 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
267 resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
268 getSettings: snapshotSettings.getSettings,
269 streamSettings: snapshotSettings.streamSettings,
270 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
271 initialSnapshot: (settings) =>
272 buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampSnapshot)),
273 checkProvider,
274 }).pipe(
275 Effect.mapError(
276 (cause) =>
277 new ProviderDriverError({
278 driver: DRIVER_KIND,
279 instanceId,
280 detail: "Failed to build Cursor snapshot.",
281 cause,
282 }),
283 ),
284 );
285​
286 return {
287 instanceId,
288 driverKind: DRIVER_KIND,
289 continuationIdentity,
290 displayName,
291 accentColor,
292 enabled,
293 auth: auth.controller,
294 snapshot,
295 snapshotForCwd: (cwd) =>
296 !effectiveConfig.enabled
297 ? snapshot.getSnapshot
298 : Effect.all([
299 snapshot.getSnapshot,
300 probeCursorSkills(cwd, processEnv).pipe(
301 Effect.provideService(FileSystem.FileSystem, fileSystem),
302 Effect.provideService(Path.Path, path),
303 Effect.mapError(
304 (cause) =>
305 new ProviderDriverError({
306 driver: DRIVER_KIND,
307 instanceId,
308 detail: `Failed to discover Cursor skills for '${cwd}'`,
309 cause,
310 }),
311 ),
312 ),
313 ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),
314 orchestrationAdapter,
315 textGeneration,
316 } satisfies ProviderInstance;
317 }),
318};