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

status.ts

367 lines11.3 KB

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