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

status.ts

356 lines10.9 KB

1import type { SDKModel, SDKUser } from "@cursor/sdk";
2import type {
3 ModelCapabilities,
4 ProviderOptionDescriptor,
5 ServerProviderAuth,
6 ServerProviderModel,
7 ServerProviderState,
8} from "@t3tools/contracts";
9import type { CursorSettings } from "../settings.ts";
10import { createModelCapabilities } from "@t3tools/shared/model";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Option from "effect/Option";
14import * as Result from "effect/Result";
15​
16import { cursorSdkParameterPriority, cursorSdkProviderOptionId } from "./sdkModel.ts";
17import {
18 buildBooleanOptionDescriptor,
19 buildSelectOptionDescriptor,
20 buildServerProvider,
21 providerModelsFromSettings,
22 type ServerProviderDraft,
23} from "@t3tools/provider-core/server/snapshotProbe";
24import * as CursorSdkCatalog from "./CursorSdkCatalog.ts";
25​
26const CURSOR_PRESENTATION = {
27 displayName: "Cursor",
28 supportsConversationRollback: false,
29 showInteractionModeToggle: true,
30} as const;
31const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
32 optionDescriptors: [],
33});
34​
35const CURSOR_SDK_CATALOG_TIMEOUT_MS = 15_000;
36​
37export const buildInitialCursorProviderSnapshot = Effect.fn(
38 "CursorProviderStatus.buildInitialCursorProviderSnapshot",
39)(function* (cursorSettings: CursorSettings): Effect.fn.Return<ServerProviderDraft> {
40 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
41 const models = getCursorFallbackModels(cursorSettings);
42​
43 if (!cursorSettings.enabled) {
44 return buildServerProvider({
45 presentation: CURSOR_PRESENTATION,
46 enabled: false,
47 checkedAt,
48 models,
49 probe: {
50 installed: false,
51 version: null,
52 status: "warning",
53 auth: { status: "unknown" },
54 message: "Cursor is disabled in T3 Code settings.",
55 },
56 });
57 }
58​
59 return buildServerProvider({
60 presentation: CURSOR_PRESENTATION,
61 enabled: true,
62 checkedAt,
63 models,
64 probe: {
65 installed: true,
66 version: null,
67 status: "warning",
68 auth: { status: "unknown" },
69 message: "Checking Cursor SDK availability...",
70 },
71 });
72});
73​
74function getCursorFallbackModels(
75 cursorSettings: Pick<CursorSettings, "customModels">,
76): ReadonlyArray<ServerProviderModel> {
77 return providerModelsFromSettings([], cursorSettings.customModels, EMPTY_CAPABILITIES);
79​
80function toTitleCaseWords(value: string): string {
81 const parts: Array<string> = [];
82 for (const part of value.split(/[\s_-]+/g)) {
83 if (part.length > 0) {
84 parts.push(part.charAt(0).toUpperCase() + part.slice(1).toLowerCase());
85 }
86 }
87 return parts.join(" ");
89​
90function cursorSdkDefaultParameterValue(model: SDKModel, parameterId: string): string | undefined {
91 return model.variants
92 ?.find((variant) => variant.isDefault)
93 ?.params.find((parameter) => parameter.id === parameterId)?.value;
95​
96export function buildCursorCapabilitiesFromSdkModel(model: SDKModel): ModelCapabilities {
97 const seen = new Set<string>();
98 const optionDescriptors: Array<ProviderOptionDescriptor> = [];
99 const parameters = (model.parameters ?? [])
100 .map((parameter, index) => ({ parameter, index }))
101 .toSorted(
102 (left, right) =>
103 cursorSdkParameterPriority(left.parameter.id) -
104 cursorSdkParameterPriority(right.parameter.id) || left.index - right.index,
105 );
106 for (const { parameter } of parameters) {
107 const nativeId = parameter.id.trim();
108 const id = cursorSdkProviderOptionId(nativeId);
109 if (!nativeId || !id || seen.has(id)) {
110 continue;
111 }
112 seen.add(id);
113​
114 const values = parameter.values.flatMap((entry) => {
115 const value = entry.value.trim();
116 if (!value) {
117 return [];
118 }
119 return [
120 {
121 value,
122 label: entry.displayName?.trim() || value,
123 },
124 ];
125 });
126 if (values.length === 0) {
127 continue;
128 }
129​
130 const label = parameter.displayName?.trim() || toTitleCaseWords(id);
131 const defaultValue = cursorSdkDefaultParameterValue(model, nativeId);
132 const normalizedValues = new Set(values.map((entry) => entry.value.toLowerCase()));
133 if (values.length === 2 && normalizedValues.has("true") && normalizedValues.has("false")) {
134 if (defaultValue === "true" || defaultValue === "false") {
135 optionDescriptors.push(
136 buildBooleanOptionDescriptor({
137 id,
138 label,
139 currentValue: defaultValue === "true",
140 }),
141 );
142 } else {
143 optionDescriptors.push(buildBooleanOptionDescriptor({ id, label }));
144 }
145 continue;
146 }
147​
148 optionDescriptors.push(
149 buildSelectOptionDescriptor({
150 id,
151 label,
152 options: values.map((entry) => ({
153 ...entry,
154 ...(entry.value === defaultValue ? { isDefault: true } : {}),
155 })),
156 }),
157 );
158 }
159​
160 return createModelCapabilities({ optionDescriptors });
162​
163export function buildCursorDiscoveredModelsFromSdk(
164 models: ReadonlyArray<SDKModel>,
165): ReadonlyArray<ServerProviderModel> {
166 const seen = new Set<string>();
167 return models.flatMap((model) => {
168 const slug = model.id.trim();
169 const name = model.displayName.trim();
170 if (!slug || !name || seen.has(slug)) {
171 return [];
172 }
173 seen.add(slug);
174 return [
175 {
176 slug,
177 name,
178 isCustom: false,
179 capabilities: buildCursorCapabilitiesFromSdkModel(model),
180 } satisfies ServerProviderModel,
181 ];
182 });
184​
185function cursorSdkAuth(user: SDKUser, type: "api-key" | "browser"): ServerProviderAuth {
186 const email = user.userEmail?.trim();
187 const apiKeyName = user.apiKeyName.trim();
188 return {
189 status: "authenticated",
190 type,
191 label:
192 type === "browser"
193 ? "Cursor account"
194 : apiKeyName
195 ? `Cursor API key (${apiKeyName})`
196 : "Cursor API key",
197 ...(email ? { email } : {}),
198 };
200​
201interface CursorProviderProbeResult {
202 readonly version: string | null;
203 readonly status: Exclude<ServerProviderState, "disabled">;
204 readonly auth: ServerProviderAuth;
205 readonly message?: string;
207​
208function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): string | undefined {
209 const parts: Array<string> = [];
210 for (const message of messages) {
211 const trimmed = message?.trim();
212 if (trimmed) {
213 parts.push(trimmed);
214 }
215 }
216 return parts.length > 0 ? parts.join(" ") : undefined;
218​
219export function buildCursorProviderSnapshot(input: {
220 readonly checkedAt: string;
221 readonly cursorSettings: CursorSettings;
222 readonly parsed: CursorProviderProbeResult;
223 readonly discoveredModels?: ReadonlyArray<ServerProviderModel>;
224 readonly discoveryWarning?: string;
225}): ServerProviderDraft {
226 const message = joinProviderMessages(input.parsed.message, input.discoveryWarning);
227 return buildServerProvider({
228 presentation: CURSOR_PRESENTATION,
229 enabled: input.cursorSettings.enabled,
230 checkedAt: input.checkedAt,
231 models: providerModelsFromSettings(
232 input.discoveredModels ?? [],
233 input.cursorSettings.customModels,
234 EMPTY_CAPABILITIES,
235 ),
236 probe: {
237 installed: true,
238 version: input.parsed.version,
239 status:
240 input.discoveryWarning && input.parsed.status === "ready" ? "warning" : input.parsed.status,
241 auth: input.parsed.auth,
242 ...(message ? { message } : {}),
243 },
244 });
246​
247export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(function* (
248 cursorSettings: CursorSettings,
249 environment?: NodeJS.ProcessEnv,
250 authenticationType: "api-key" | "browser" = "api-key",
251): Effect.fn.Return<ServerProviderDraft, never, CursorSdkCatalog.CursorSdkCatalog> {
252 const checkedAt = DateTime.formatIso(yield* DateTime.now);
253 const fallbackModels = getCursorFallbackModels(cursorSettings);
254​
255 if (!cursorSettings.enabled) {
256 return buildServerProvider({
257 presentation: CURSOR_PRESENTATION,
258 enabled: false,
259 checkedAt,
260 models: fallbackModels,
261 probe: {
262 installed: false,
263 version: null,
264 status: "warning",
265 auth: { status: "unknown" },
266 message: "Cursor is disabled in T3 Code settings.",
267 },
268 });
269 }
270​
271 const sdkApiKey = environment?.CURSOR_API_KEY?.trim();
272 if (!sdkApiKey) {
273 return buildServerProvider({
274 presentation: CURSOR_PRESENTATION,
275 enabled: cursorSettings.enabled,
276 checkedAt,
277 models: fallbackModels,
278 probe: {
279 installed: true,
280 version: null,
281 status: "error",
282 auth: { status: "unauthenticated" },
283 message: "Sign in with Cursor or add CURSOR_API_KEY in provider settings.",
284 },
285 });
286 }
287​
288 const sdkCatalog = yield* CursorSdkCatalog.CursorSdkCatalog;
289 const catalogResult = yield* sdkCatalog
290 .read(sdkApiKey)
291 .pipe(Effect.timeoutOption(CURSOR_SDK_CATALOG_TIMEOUT_MS), Effect.result);
292​
293 if (Result.isFailure(catalogResult)) {
294 yield* Effect.logWarning("Cursor SDK catalog probe failed", {
295 cause: catalogResult.failure.cause,
296 });
297 const failure = catalogResult.failure;
298 let message = "Cursor SDK catalog request failed. Check server logs for details.";
299 if (failure.authenticationFailure) {
300 message =
301 authenticationType === "browser"
302 ? "Cursor sign-in expired or was rejected. Sign in again in provider settings."
303 : "Cursor SDK authentication failed. Check CURSOR_API_KEY.";
304 } else if (failure.planRequired) {
305 message =
306 authenticationType === "browser"
307 ? "Cursor needs a paid plan to run in T3 Code. Upgrade this account or sign in with a different one."
308 : "Cursor needs a paid plan to run in T3 Code. Upgrade the account that owns CURSOR_API_KEY or use a key from a paid account.";
309 }
310 return buildServerProvider({
311 presentation: CURSOR_PRESENTATION,
312 enabled: cursorSettings.enabled,
313 checkedAt,
314 models: fallbackModels,
315 probe: {
316 installed: true,
317 version: null,
318 status: "error",
319 auth: { status: failure.authenticationFailure ? "unauthenticated" : "unknown" },
320 message,
321 },
322 });
323 }
324​
325 if (Option.isNone(catalogResult.success)) {
326 return buildServerProvider({
327 presentation: CURSOR_PRESENTATION,
328 enabled: cursorSettings.enabled,
329 checkedAt,
330 models: fallbackModels,
331 probe: {
332 installed: true,
333 version: null,
334 status: "error",
335 auth: { status: "unknown" },
336 message: `Cursor SDK catalog request timed out after ${CURSOR_SDK_CATALOG_TIMEOUT_MS}ms.`,
337 },
338 });
339 }
340​
341 const snapshot = catalogResult.success.value;
342 const discoveredModels = buildCursorDiscoveredModelsFromSdk(snapshot.models);
343 return buildCursorProviderSnapshot({
344 checkedAt,
345 cursorSettings,
346 parsed: {
347 version: null,
348 status: "ready",
349 auth: cursorSdkAuth(snapshot.user, authenticationType),
350 },
351 discoveredModels,
352 ...(discoveredModels.length === 0
353 ? { discoveryWarning: "Cursor SDK model discovery returned no built-in models." }
354 : {}),
355 });
356});