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

driver.ts

310 lines10.5 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 { cursorRateModel } from "./accountUsage.ts";
14import { readCursorUsageLimits } from "./usageLimits.ts";
15​
16import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
17import { makeCursorTextGeneration } from "./textGeneration.ts";
18import { makeCursorAdapterV2, type CursorAdapterV2DriverEnv } from "./adapter.ts";
19import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
20import { buildInitialCursorProviderSnapshot, checkCursorProviderStatus } from "./status.ts";
21import * as CursorSdkCatalog from "./CursorSdkCatalog.ts";
22import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
23import {
24 defaultProviderContinuationIdentity,
25 type ProviderDriver,
26 type ProviderInstance,
27} from "@t3tools/provider-core/server/driver";
28import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
29import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
30import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
31import {
32 haveProviderSnapshotSettingsChanged,
33 makeProviderSnapshotSettingsSource,
34 type ProviderSnapshotSettings,
35} from "@t3tools/provider-core/server/snapshotSettings";
36import { probeCursorSkills } from "./skills.ts";
37import { makeCursorAuth } from "./auth.ts";
38import * as CursorCredentialStore from "./credentialStore.ts";
39import * as CursorAgentSdk from "./CursorAgentSdk.ts";
40import * as CursorSdk from "./CursorSdk.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​
61export const CursorDriver: ProviderDriver<
62 CursorSettings,
63 CursorDriverEnv,
64 CursorUsageAccounts.CursorUsageAccounts
65> = {
66 driverKind: DRIVER_KIND,
67 metadata: {
68 displayName: "Cursor",
69 supportsMultipleInstances: true,
70 },
71 configSchema: CursorSettings,
72 defaultConfig: (): CursorSettings => decodeCursorSettings({}),
73 usage: {
74 kind: "scan",
75 provider: "cursor",
76 rateModel: cursorRateModel,
77 scan: ({ instances, windowStartMs, retentionCutoffMs, awaitRefresh }) =>
78 CursorUsageAccounts.CursorUsageAccounts.pipe(
79 Effect.flatMap((accounts) =>
80 accounts.scan({
81 instances,
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 sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;
102 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
103 const continuationIdentity = defaultProviderContinuationIdentity({
104 driverKind: DRIVER_KIND,
105 instanceId,
106 });
107 const stampIdentity = withInstanceIdentity({
108 instanceId,
109 driverKind: DRIVER_KIND,
110 displayName: displayName ?? "Cursor",
111 accentColor,
112 continuationGroupKey: continuationIdentity.continuationKey,
113 });
114 const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
115 const credentials = yield* CursorCredentialStore.makeCursorCredentialStore(
116 instanceId,
117 path.join(
118 host.paths.stateDir,
119 "provider-auth",
120 encodeURIComponent(instanceId),
121 "cursor.json",
122 ),
123 ).pipe(
124 Effect.mapError(
125 (cause) =>
126 new ProviderDriverError({
127 driver: DRIVER_KIND,
128 instanceId,
129 detail: "Could not open the Cursor credential store.",
130 cause,
131 }),
132 ),
133 );
134 const auth = yield* makeCursorAuth({
135 instanceId,
136 displayName: displayName ?? "Cursor",
137 enabled,
138 ...(processEnv.CURSOR_API_KEY ? { apiKey: processEnv.CURSOR_API_KEY } : {}),
139 store: credentials.store,
140 credentialBinding: credentials.binding,
141 onChanged: (signedIn): Effect.Effect<void, ProviderSetupError> =>
142 snapshot.refresh.pipe(
143 Effect.flatMap((provider) =>
144 !signedIn || provider.auth.status === "authenticated"
145 ? Effect.void
146 : Effect.fail(
147 new ProviderSetupError({
148 instanceId,
149 operation: "start",
150 detail: provider.message ?? "Could not verify the Cursor sign-in. Try again.",
151 }),
152 ),
153 ),
154 ),
155 });
156 const stampSnapshot: typeof stampIdentity = (draft) =>
157 stampIdentity({
158 ...draft,
159 setup: { canAuthenticate: !auth.usesApiKey, canInstall: false },
160 auth: {
161 ...draft.auth,
162 canLogout: !auth.usesApiKey,
163 },
164 });
165​
166 let catalogModels: ReadonlyArray<ServerProviderModel> = [];
167 const orchestrationAdapter = yield* makeCursorAdapterV2({
168 instanceId,
169 environment: processEnv,
170 getModels: () => catalogModels,
171 }).pipe(
172 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
173 ...sdkRunner,
174 open: (input) =>
175 auth.requireApiKey.pipe(
176 Effect.flatMap((apiKey) =>
177 Effect.acquireRelease(
178 sdkRunner
179 .open({ ...input, options: { ...input.options, apiKey } })
180 .pipe(
181 Effect.flatMap((session) =>
182 Effect.cached(session.close).pipe(
183 Effect.map((close) => ({ ...session, close })),
184 ),
185 ),
186 ),
187 (session) => session.close.pipe(Effect.ignore),
188 ),
189 ),
190 auth.withAccess,
191 Effect.mapError((cause) =>
192 isSdkRunnerError(cause)
193 ? cause
194 : new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "open", cause }),
195 ),
196 ),
197 }),
198 Effect.mapError(
199 (cause) =>
200 new ProviderDriverError({
201 driver: DRIVER_KIND,
202 instanceId,
203 detail: "Failed to build Cursor orchestration adapter.",
204 cause,
205 }),
206 ),
207 );
208 const textGeneration = yield* makeCursorTextGeneration(
209 effectiveConfig,
210 processEnv,
211 auth.requireApiKey,
212 auth.withAccess,
213 () => catalogModels,
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 readCursorUsageLimits(effectiveConfig, {
236 ...processEnv,
237 CURSOR_API_KEY: apiKey,
238 }).pipe(Effect.map((usageLimits) => ({ ...snapshot, usageLimits }))),
239 ),
240 ),
241 ),
242 Effect.provideService(FileSystem.FileSystem, fileSystem),
243 Effect.provideService(Path.Path, path),
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 Effect.provideService(HttpClient.HttpClient, httpClient),
255 );
256​
257 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
258 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
259 resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
260 getSettings: snapshotSettings.getSettings,
261 streamSettings: snapshotSettings.streamSettings,
262 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
263 initialSnapshot: (settings) =>
264 buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampSnapshot)),
265 checkProvider,
266 }).pipe(
267 Effect.mapError(
268 (cause) =>
269 new ProviderDriverError({
270 driver: DRIVER_KIND,
271 instanceId,
272 detail: "Failed to build Cursor snapshot.",
273 cause,
274 }),
275 ),
276 );
277​
278 return {
279 instanceId,
280 driverKind: DRIVER_KIND,
281 continuationIdentity,
282 displayName,
283 accentColor,
284 enabled,
285 auth: auth.controller,
286 snapshot,
287 snapshotForCwd: (cwd) =>
288 !effectiveConfig.enabled
289 ? snapshot.getSnapshot
290 : Effect.all([
291 snapshot.getSnapshot,
292 probeCursorSkills(cwd, processEnv).pipe(
293 Effect.provideService(FileSystem.FileSystem, fileSystem),
294 Effect.provideService(Path.Path, path),
295 Effect.mapError(
296 (cause) =>
297 new ProviderDriverError({
298 driver: DRIVER_KIND,
299 instanceId,
300 detail: `Failed to discover Cursor skills for '${cwd}'`,
301 cause,
302 }),
303 ),
304 ),
305 ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),
306 orchestrationAdapter,
307 textGeneration,
308 } satisfies ProviderInstance;
309 }),
310};