@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 328 lines 11.3 KB
Raw
1 import {
2 ProviderDriverKind,
3 ProviderSetupError,
4 type ServerProviderModel,
5 } from "@t3tools/contracts";
6 import { CursorSettings } from "../settings.ts";
7 import type { SDKModel } from "@cursor/sdk";
8 import * as Effect from "effect/Effect";
9 import * as SecureRandom from "effect/crypto/SecureRandom";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Path from "effect/Path";
12 import * as Schema from "effect/Schema";
13 import * as HttpClient from "effect/http/HttpClient";
14 import { cursorRateModel } from "./accountUsage.ts";
15 import { readCursorUsageLimits } from "./usageLimits.ts";
16
17 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
18 import { makeCursorTextGeneration } from "./textGeneration.ts";
19 import { makeCursorAdapterV2, type CursorAdapterV2DriverEnv } from "./adapter.ts";
20 import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
21 import { buildInitialCursorProviderSnapshot, checkCursorProviderStatus } from "./status.ts";
22 import * as CursorSdkCatalog from "./CursorSdkCatalog.ts";
23 import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
24 import {
25 defaultProviderContinuationIdentity,
26 type ProviderDriver,
27 type ProviderInstance,
28 } from "@t3tools/provider-core/server/driver";
29 import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
30 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
31 import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
32 import {
33 haveProviderSnapshotSettingsChanged,
34 makeProviderSnapshotSettingsSource,
35 type ProviderSnapshotSettings,
36 } from "@t3tools/provider-core/server/snapshotSettings";
37 import { probeCursorSkills } from "./skills.ts";
38 import { makeCursorAuth } from "./auth.ts";
39 import * as CursorCredentialStore from "./credentialStore.ts";
40 import * as CursorAgentSdk from "./CursorAgentSdk.ts";
41 import * as CursorSdk from "./CursorSdk.ts";
42 import * as CursorUsageAccounts from "./CursorUsageAccounts.ts";
43
44 const decodeCursorSettings = Schema.decodeSync(CursorSettings);
45 const isSdkRunnerError = Schema.is(CursorAgentSdk.CursorAgentSdkRunnerError);
46
47 const DRIVER_KIND = ProviderDriverKind.make("cursor");
48 const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({
49 provider: DRIVER_KIND,
50 packageName: null,
51 });
52
53 export type CursorDriverEnv =
54 | CursorAdapterV2DriverEnv
55 | SecureRandom.SecureRandom
56 | FileSystem.FileSystem
57 | Path.Path
58 | HttpClient.HttpClient
59 | CursorSdk.CursorSdk
60 | ProviderHost.ProviderHost;
61
62 export 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 rateModel: cursorRateModel,
78 scan: ({ instances, windowStartMs, retentionCutoffMs, awaitRefresh }) =>
79 CursorUsageAccounts.CursorUsageAccounts.pipe(
80 Effect.flatMap((accounts) =>
81 accounts.scan({
82 instances,
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 sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;
103 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
104 const continuationIdentity = defaultProviderContinuationIdentity({
105 driverKind: DRIVER_KIND,
106 instanceId,
107 });
108 const stampIdentity = withInstanceIdentity({
109 instanceId,
110 driverKind: DRIVER_KIND,
111 displayName: displayName ?? "Cursor",
112 accentColor,
113 continuationGroupKey: continuationIdentity.continuationKey,
114 });
115 const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
116 const credentials = yield* CursorCredentialStore.makeCursorCredentialStore(
117 instanceId,
118 path.join(
119 host.paths.stateDir,
120 "provider-auth",
121 encodeURIComponent(instanceId),
122 "cursor.json",
123 ),
124 ).pipe(
125 Effect.mapError(
126 (cause) =>
127 new ProviderDriverError({
128 driver: DRIVER_KIND,
129 instanceId,
130 detail: "Could not open the Cursor credential store.",
131 cause,
132 }),
133 ),
134 );
135 const auth = yield* makeCursorAuth({
136 instanceId,
137 displayName: displayName ?? "Cursor",
138 enabled,
139 ...(processEnv.CURSOR_API_KEY ? { apiKey: processEnv.CURSOR_API_KEY } : {}),
140 store: credentials.store,
141 credentialBinding: credentials.binding,
142 onChanged: (signedIn): Effect.Effect<void, ProviderSetupError> =>
143 snapshot.refresh.pipe(
144 Effect.flatMap((provider) =>
145 !signedIn || provider.auth.status === "authenticated"
146 ? Effect.void
147 : Effect.fail(
148 new ProviderSetupError({
149 instanceId,
150 operation: "start",
151 detail: provider.message ?? "Could not verify the Cursor sign-in. Try again.",
152 }),
153 ),
154 ),
155 ),
156 });
157 const stampSnapshot: typeof stampIdentity = (draft) =>
158 stampIdentity({
159 ...draft,
160 setup: { canAuthenticate: !auth.usesApiKey, canInstall: false },
161 auth: {
162 ...draft.auth,
163 canLogout: !auth.usesApiKey,
164 },
165 });
166
167 let catalogModels: ReadonlyArray<ServerProviderModel> = [];
168 let catalogSdkModels: ReadonlyArray<SDKModel> = [];
169 const orchestrationAdapter = yield* makeCursorAdapterV2({
170 instanceId,
171 environment: processEnv,
172 getModels: () => catalogModels,
173 getSdkModels: () => catalogSdkModels,
174 }).pipe(
175 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
176 ...sdkRunner,
177 open: (input) =>
178 auth.requireApiKey.pipe(
179 Effect.flatMap((apiKey) =>
180 Effect.acquireRelease(
181 sdkRunner
182 .open({ ...input, options: { ...input.options, apiKey } })
183 .pipe(
184 Effect.flatMap((session) =>
185 Effect.cached(session.close).pipe(
186 Effect.map((close) => ({ ...session, close })),
187 ),
188 ),
189 ),
190 (session) => session.close.pipe(Effect.ignore),
191 ),
192 ),
193 auth.withAccess,
194 Effect.mapError((cause) =>
195 isSdkRunnerError(cause)
196 ? cause
197 : new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "open", cause }),
198 ),
199 ),
200 }),
201 Effect.mapError(
202 (cause) =>
203 new ProviderDriverError({
204 driver: DRIVER_KIND,
205 instanceId,
206 detail: "Failed to build Cursor orchestration adapter.",
207 cause,
208 }),
209 ),
210 );
211 const textGeneration = yield* makeCursorTextGeneration(
212 effectiveConfig,
213 processEnv,
214 auth.requireApiKey,
215 auth.withAccess,
216 () => catalogModels,
217 () => catalogSdkModels,
218 sdkRunner,
219 );
220
221 const checkProvider = auth.readApiKey.pipe(
222 Effect.orElseSucceed(() => undefined),
223 Effect.flatMap((apiKey) =>
224 checkCursorProviderStatus(
225 effectiveConfig,
226 {
227 ...processEnv,
228 CURSOR_API_KEY: apiKey,
229 },
230 auth.usesApiKey ? "api-key" : "browser",
231 ).pipe(
232 Effect.filterOrElse(
233 (snapshot) =>
234 !(
235 effectiveConfig.enabled &&
236 snapshot.installed &&
237 snapshot.auth.status === "authenticated"
238 ),
239 (snapshot) =>
240 readCursorUsageLimits(effectiveConfig, {
241 ...processEnv,
242 CURSOR_API_KEY: apiKey,
243 }).pipe(Effect.map((usageLimits) => ({ ...snapshot, usageLimits }))),
244 ),
245 ),
246 ),
247 Effect.provideService(FileSystem.FileSystem, fileSystem),
248 Effect.provideService(Path.Path, path),
249 Effect.map(stampSnapshot),
250 Effect.tap((provider) =>
251 Effect.sync(() => {
252 // A failed check lists only custom models, so keep the last loaded catalog.
253 if (provider.models.some((model) => !model.isCustom)) {
254 catalogModels = provider.models;
255 }
256 }),
257 ),
258 Effect.provideServiceEffect(
259 CursorSdkCatalog.CursorSdkCatalog,
260 Effect.map(CursorSdkCatalog.CursorSdkCatalog, (catalog) =>
261 CursorSdkCatalog.CursorSdkCatalog.of({
262 // Untraced: CursorSdkCatalog.read already spans this call.
263 read: Effect.fnUntraced(function* (apiKey) {
264 const snapshot = yield* catalog.read(apiKey);
265 if (snapshot.models.length > 0) catalogSdkModels = snapshot.models;
266 return snapshot;
267 }),
268 }),
269 ),
270 ),
271 Effect.provide(CursorSdkCatalog.layer),
272 Effect.provideService(HttpClient.HttpClient, httpClient),
273 );
274
275 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
276 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
277 resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
278 getSettings: snapshotSettings.getSettings,
279 streamSettings: snapshotSettings.streamSettings,
280 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
281 initialSnapshot: (settings) =>
282 buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampSnapshot)),
283 checkProvider,
284 }).pipe(
285 Effect.mapError(
286 (cause) =>
287 new ProviderDriverError({
288 driver: DRIVER_KIND,
289 instanceId,
290 detail: "Failed to build Cursor snapshot.",
291 cause,
292 }),
293 ),
294 );
295
296 return {
297 instanceId,
298 driverKind: DRIVER_KIND,
299 continuationIdentity,
300 displayName,
301 accentColor,
302 enabled,
303 auth: auth.controller,
304 snapshot,
305 snapshotForCwd: (cwd) =>
306 !effectiveConfig.enabled
307 ? snapshot.getSnapshot
308 : Effect.all([
309 snapshot.getSnapshot,
310 probeCursorSkills(cwd, processEnv).pipe(
311 Effect.provideService(FileSystem.FileSystem, fileSystem),
312 Effect.provideService(Path.Path, path),
313 Effect.mapError(
314 (cause) =>
315 new ProviderDriverError({
316 driver: DRIVER_KIND,
317 instanceId,
318 detail: `Failed to discover Cursor skills for '${cwd}'`,
319 cause,
320 }),
321 ),
322 ),
323 ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),
324 orchestrationAdapter,
325 textGeneration,
326 } satisfies ProviderInstance;
327 }),
328 };