Open History to see the last commit
1import * as nodeFs from "node:fs";
2import * as nodeOs from "node:os";
3import * as nodePath from "node:path";
4
5import type {
6 CursorSettings,
7 ModelCapabilities,
8 ProviderOptionSelection,
9 ServerProvider,
10 ServerProviderAuth,
11 ServerProviderModel,
12 ServerProviderState,
13 ServerSettingsError,
14} from "@t3tools/contracts";
15import type * as EffectAcpSchema from "effect-acp/schema";
16import { Cause, Effect, Equal, Exit, Layer, Option, Result, Stream } from "effect";
17import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
18import {
19 createModelCapabilities,
20 getProviderOptionBooleanSelectionValue,
21 getProviderOptionStringSelectionValue,
22} from "@t3tools/shared/model";
23
24import {
25 buildBooleanOptionDescriptor,
26 buildSelectOptionDescriptor,
27 buildServerProvider,
28 collectStreamAsString,
29 isCommandMissingCause,
30 providerModelsFromSettings,
31 type CommandResult,
32} from "../providerSnapshot.ts";
33import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
34import { CursorProvider } from "../Services/CursorProvider.ts";
35import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
36import { ServerSettingsService } from "../../serverSettings.ts";
37
38const PROVIDER = "cursor" as const;
39const CURSOR_PRESENTATION = {
40 displayName: "Cursor",
41 badgeLabel: "Early Access",
42 showInteractionModeToggle: true,
43} as const;
44const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
45 optionDescriptors: [],
46});
47
48const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
49const CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT = "4 seconds";
50const CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY = 4;
51const CURSOR_REFRESH_INTERVAL = "1 hour";
52const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
53export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
54 _meta: {
55 parameterizedModelPicker: true,
56 },
57} satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
58
59function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): ServerProvider {
60 const checkedAt = new Date().toISOString();
61 const models = getCursorFallbackModels(cursorSettings);
62
63 if (!cursorSettings.enabled) {
64 return buildServerProvider({
65 provider: PROVIDER,
66 presentation: CURSOR_PRESENTATION,
67 enabled: false,
68 checkedAt,
69 models,
70 probe: {
71 installed: false,
72 version: null,
73 status: "warning",
74 auth: { status: "unknown" },
75 message: "Cursor is disabled in T3 Code settings.",
76 },
77 });
78 }
79
80 return buildServerProvider({
81 provider: PROVIDER,
82 presentation: CURSOR_PRESENTATION,
83 enabled: true,
84 checkedAt,
85 models,
86 probe: {
87 installed: true,
88 version: null,
89 status: "warning",
90 auth: { status: "unknown" },
91 message: "Checking Cursor Agent availability...",
92 },
93 });
94}
95
96interface CursorSessionSelectOption {
97 readonly value: string;
98 readonly name: string;
99}
100
101interface CursorAcpDiscoveredModel {
102 readonly slug: string;
103 readonly name: string;
104 readonly capabilities: ModelCapabilities;
105}
106
107function flattenSessionConfigSelectOptions(
108 configOption: EffectAcpSchema.SessionConfigOption | undefined,
109): ReadonlyArray<CursorSessionSelectOption> {
110 if (!configOption || configOption.type !== "select") {
111 return [];
112 }
113 return configOption.options.flatMap((entry) =>
114 "value" in entry
115 ? [{ value: entry.value.trim(), name: entry.name.trim() } satisfies CursorSessionSelectOption]
116 : entry.options.map(
117 (option) =>
118 ({
119 value: option.value.trim(),
120 name: option.name.trim(),
121 }) satisfies CursorSessionSelectOption,
122 ),
123 );
124}
125
126function normalizeCursorReasoningValue(value: string | null | undefined): string | undefined {
127 const normalized = value?.trim().toLowerCase();
128 switch (normalized) {
129 case "low":
130 case "medium":
131 case "high":
132 case "max":
133 return normalized;
134 case "xhigh":
135 case "extra-high":
136 case "extra high":
137 return "xhigh";
138 default:
139 return undefined;
140 }
141}
142
143function findCursorModelConfigOption(
144 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
145): EffectAcpSchema.SessionConfigOption | undefined {
146 return configOptions.find((option) => option.category === "model");
147}
148
149function getCursorConfigOptionCategory(option: EffectAcpSchema.SessionConfigOption): string {
150 return option.category?.trim().toLowerCase() ?? "";
151}
152
153function isCursorEffortConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {
154 const id = option.id.trim().toLowerCase();
155 const name = option.name.trim().toLowerCase();
156 return (
157 id === "effort" ||
158 id === "reasoning" ||
159 name === "effort" ||
160 name === "reasoning" ||
161 name.includes("effort") ||
162 name.includes("reasoning")
163 );
164}
165
166function findCursorEffortConfigOption(
167 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
168): EffectAcpSchema.SessionConfigOption | undefined {
169 const candidates = configOptions.filter(
170 (option) => option.type === "select" && isCursorEffortConfigOption(option),
171 );
172 return (
173 candidates.find((option) => getCursorConfigOptionCategory(option) === "model_option") ??
174 candidates.find((option) => option.id.trim().toLowerCase() === "effort") ??
175 candidates.find((option) => getCursorConfigOptionCategory(option) === "thought_level") ??
176 candidates[0]
177 );
178}
179
180function isCursorContextConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {
181 const id = option.id.trim().toLowerCase();
182 const name = option.name.trim().toLowerCase();
183 return id === "context" || id === "context_size" || name.includes("context");
184}
185
186function isCursorFastConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {
187 const id = option.id.trim().toLowerCase();
188 const name = option.name.trim().toLowerCase();
189 return id === "fast" || name === "fast" || name.includes("fast mode");
190}
191
192function isCursorThinkingConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {
193 const id = option.id.trim().toLowerCase();
194 const name = option.name.trim().toLowerCase();
195 return id === "thinking" || name.includes("thinking");
196}
197
198function isBooleanLikeConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {
199 if (option.type === "boolean") {
200 return true;
201 }
202 if (option.type !== "select") {
203 return false;
204 }
205 const values = new Set(
206 flattenSessionConfigSelectOptions(option).map((entry) => entry.value.trim().toLowerCase()),
207 );
208 return values.has("true") && values.has("false");
209}
210
211function getBooleanCurrentValue(
212 option: EffectAcpSchema.SessionConfigOption | undefined,
213): boolean | undefined {
214 if (!option) {
215 return undefined;
216 }
217 if (option.type === "boolean") {
218 return option.currentValue;
219 }
220 if (option.type !== "select") {
221 return undefined;
222 }
223 const normalized = option.currentValue?.trim().toLowerCase();
224 if (normalized === "true") {
225 return true;
226 }
227 if (normalized === "false") {
228 return false;
229 }
230 return undefined;
231}
232
233export function buildCursorCapabilitiesFromConfigOptions(
234 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
235): ModelCapabilities {
236 if (!configOptions || configOptions.length === 0) {
237 return EMPTY_CAPABILITIES;
238 }
239
240 const reasoningConfig = findCursorEffortConfigOption(configOptions);
241 const reasoningEffortLevels =
242 reasoningConfig?.type === "select"
243 ? flattenSessionConfigSelectOptions(reasoningConfig).flatMap((entry) => {
244 const normalizedValue = normalizeCursorReasoningValue(entry.value);
245 if (!normalizedValue) {
246 return [];
247 }
248 return [
249 {
250 value: normalizedValue,
251 label: entry.name,
252 ...(normalizeCursorReasoningValue(reasoningConfig.currentValue) === normalizedValue
253 ? { isDefault: true }
254 : {}),
255 },
256 ];
257 })
258 : [];
259
260 const contextOption = configOptions.find(
261 (option) => option.category === "model_config" && isCursorContextConfigOption(option),
262 );
263 const contextWindowOptions =
264 contextOption?.type === "select"
265 ? flattenSessionConfigSelectOptions(contextOption).map((entry) => {
266 if (contextOption.currentValue === entry.value) {
267 return {
268 value: entry.value,
269 label: entry.name,
270 isDefault: true,
271 };
272 }
273 return {
274 value: entry.value,
275 label: entry.name,
276 };
277 })
278 : [];
279
280 const fastOption = configOptions.find(
281 (option) => option.category === "model_config" && isCursorFastConfigOption(option),
282 );
283 const thinkingOption = configOptions.find(
284 (option) => option.category === "model_config" && isCursorThinkingConfigOption(option),
285 );
286 const fastCurrentValue = getBooleanCurrentValue(fastOption);
287 const thinkingCurrentValue = getBooleanCurrentValue(thinkingOption);
288 const optionDescriptors = [
289 ...(reasoningEffortLevels.length > 0
290 ? [
291 buildSelectOptionDescriptor({
292 id: "reasoning",
293 label: reasoningConfig?.name?.trim() || "Reasoning",
294 options: reasoningEffortLevels,
295 }),
296 ]
297 : []),
298 ...(contextWindowOptions.length > 0
299 ? [
300 buildSelectOptionDescriptor({
301 id: "contextWindow",
302 label: contextOption?.name?.trim() || "Context Window",
303 options: contextWindowOptions,
304 }),
305 ]
306 : []),
307 ...(fastOption && isBooleanLikeConfigOption(fastOption)
308 ? [
309 typeof fastCurrentValue === "boolean"
310 ? buildBooleanOptionDescriptor({
311 id: "fastMode",
312 label: fastOption.name?.trim() || "Fast Mode",
313 currentValue: fastCurrentValue,
314 })
315 : buildBooleanOptionDescriptor({
316 id: "fastMode",
317 label: fastOption.name?.trim() || "Fast Mode",
318 }),
319 ]
320 : []),
321 ...(thinkingOption && isBooleanLikeConfigOption(thinkingOption)
322 ? [
323 typeof thinkingCurrentValue === "boolean"
324 ? buildBooleanOptionDescriptor({
325 id: "thinking",
326 label: thinkingOption.name?.trim() || "Thinking",
327 currentValue: thinkingCurrentValue,
328 })
329 : buildBooleanOptionDescriptor({
330 id: "thinking",
331 label: thinkingOption.name?.trim() || "Thinking",
332 }),
333 ]
334 : []),
335 ];
336
337 return createModelCapabilities({
338 optionDescriptors,
339 });
340}
341
342function buildCursorDiscoveredModels(
343 discoveredModels: ReadonlyArray<CursorAcpDiscoveredModel>,
344): ReadonlyArray<ServerProviderModel> {
345 const seen = new Set<string>();
346 return discoveredModels.flatMap((model) => {
347 if (!model.slug || seen.has(model.slug)) {
348 return [];
349 }
350 seen.add(model.slug);
351 return [
352 {
353 slug: model.slug,
354 name: model.name,
355 isCustom: false,
356 capabilities: model.capabilities,
357 } satisfies ServerProviderModel,
358 ];
359 });
360}
361
362function hasCursorModelCapabilities(model: Pick<ServerProviderModel, "capabilities">): boolean {
363 return (model.capabilities?.optionDescriptors?.length ?? 0) > 0;
364}
365
366export function buildCursorDiscoveredModelsFromConfigOptions(
367 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
368): ReadonlyArray<ServerProviderModel> {
369 if (!configOptions || configOptions.length === 0) {
370 return [];
371 }
372
373 const modelOption = findCursorModelConfigOption(configOptions);
374 const modelChoices = flattenSessionConfigSelectOptions(modelOption);
375 if (!modelOption || modelChoices.length === 0) {
376 return [];
377 }
378
379 const currentModelValue =
380 modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined;
381 const currentModelCapabilities = buildCursorCapabilitiesFromConfigOptions(configOptions);
382
383 return buildCursorDiscoveredModels(
384 modelChoices.map((modelChoice) => ({
385 slug: modelChoice.value.trim(),
386 name: modelChoice.name.trim(),
387 capabilities:
388 currentModelValue === modelChoice.value.trim()
389 ? currentModelCapabilities
390 : EMPTY_CAPABILITIES,
391 })),
392 );
393}
394
395const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) =>
396 Effect.gen(function* () {
397 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
398 const acpContext = yield* Layer.build(
399 AcpSessionRuntime.layer({
400 spawn: {
401 command: cursorSettings.binaryPath,
402 args: [
403 ...(cursorSettings.apiEndpoint ? (["-e", cursorSettings.apiEndpoint] as const) : []),
404 "acp",
405 ],
406 cwd: process.cwd(),
407 },
408 cwd: process.cwd(),
409 clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
410 authMethodId: "cursor_login",
411 clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
412 }).pipe(Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner))),
413 );
414 return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
415 });
416
417const withCursorAcpProbeRuntime = <A, E, R>(
418 cursorSettings: CursorSettings,
419 useRuntime: (acp: AcpSessionRuntime["Service"]) => Effect.Effect<A, E, R>,
420) => makeCursorAcpProbeRuntime(cursorSettings).pipe(Effect.flatMap(useRuntime), Effect.scoped);
421
422function normalizeCursorConfigOptionToken(value: string | null | undefined): string {
423 return (
424 value
425 ?.trim()
426 .toLowerCase()
427 .replace(/[\s_-]+/g, "-") ?? ""
428 );
429}
430
431function findCursorSelectOptionValue(
432 configOption: EffectAcpSchema.SessionConfigOption | undefined,
433 matcher: (option: CursorSessionSelectOption) => boolean,
434): string | undefined {
435 return flattenSessionConfigSelectOptions(configOption).find(matcher)?.value;
436}
437
438function findCursorBooleanConfigValue(
439 configOption: EffectAcpSchema.SessionConfigOption | undefined,
440 requested: boolean,
441): string | boolean | undefined {
442 if (!configOption) {
443 return undefined;
444 }
445 if (configOption.type === "boolean") {
446 return requested;
447 }
448 return findCursorSelectOptionValue(
449 configOption,
450 (option) => normalizeCursorConfigOptionToken(option.value) === String(requested),
451 );
452}
453
454export function resolveCursorAcpBaseModelId(model: string | null | undefined): string {
455 const trimmed = model?.trim();
456 const base = trimmed && trimmed.length > 0 ? trimmed : "default";
457 return base.includes("[") ? base.slice(0, base.indexOf("[")) : base;
458}
459
460export function resolveCursorAcpConfigUpdates(
461 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
462 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
463): ReadonlyArray<{ readonly configId: string; readonly value: string | boolean }> {
464 if (!configOptions || configOptions.length === 0) {
465 return [];
466 }
467
468 const updates: Array<{ readonly configId: string; readonly value: string | boolean }> = [];
469
470 const reasoningOption = findCursorEffortConfigOption(configOptions);
471 const requestedReasoning = normalizeCursorReasoningValue(
472 getProviderOptionStringSelectionValue(selections, "reasoning"),
473 );
474 if (reasoningOption && requestedReasoning) {
475 const value = findCursorSelectOptionValue(reasoningOption, (option) => {
476 const normalizedValue = normalizeCursorReasoningValue(option.value);
477 const normalizedName = normalizeCursorReasoningValue(option.name);
478 return normalizedValue === requestedReasoning || normalizedName === requestedReasoning;
479 });
480 if (value) {
481 updates.push({ configId: reasoningOption.id, value });
482 }
483 }
484
485 const contextOption = configOptions.find(
486 (option) => option.category === "model_config" && isCursorContextConfigOption(option),
487 );
488 const requestedContextWindow = getProviderOptionStringSelectionValue(selections, "contextWindow");
489 if (contextOption && requestedContextWindow) {
490 const value = findCursorSelectOptionValue(
491 contextOption,
492 (option) =>
493 normalizeCursorConfigOptionToken(option.value) ===
494 normalizeCursorConfigOptionToken(requestedContextWindow) ||
495 normalizeCursorConfigOptionToken(option.name) ===
496 normalizeCursorConfigOptionToken(requestedContextWindow),
497 );
498 if (value) {
499 updates.push({ configId: contextOption.id, value });
500 }
501 }
502
503 const fastOption = configOptions.find(
504 (option) => option.category === "model_config" && isCursorFastConfigOption(option),
505 );
506 const requestedFastMode = getProviderOptionBooleanSelectionValue(selections, "fastMode");
507 if (fastOption && typeof requestedFastMode === "boolean") {
508 const value = findCursorBooleanConfigValue(fastOption, requestedFastMode);
509 if (value !== undefined) {
510 updates.push({ configId: fastOption.id, value });
511 }
512 }
513
514 const thinkingOption = configOptions.find(
515 (option) => option.category === "model_config" && isCursorThinkingConfigOption(option),
516 );
517 const requestedThinking = getProviderOptionBooleanSelectionValue(selections, "thinking");
518 if (thinkingOption && typeof requestedThinking === "boolean") {
519 const value = findCursorBooleanConfigValue(thinkingOption, requestedThinking);
520 if (value !== undefined) {
521 updates.push({ configId: thinkingOption.id, value });
522 }
523 }
524
525 return updates;
526}
527
528export const discoverCursorModelsViaAcp = (cursorSettings: CursorSettings) =>
529 withCursorAcpProbeRuntime(cursorSettings, (acp) =>
530 Effect.map(acp.start(), (started) =>
531 buildCursorDiscoveredModelsFromConfigOptions(started.sessionSetupResult.configOptions ?? []),
532 ),
533 );
534
535export const discoverCursorModelCapabilitiesViaAcp = (
536 cursorSettings: CursorSettings,
537 existingModels: ReadonlyArray<ServerProviderModel>,
538) =>
539 withCursorAcpProbeRuntime(cursorSettings, (acp) =>
540 Effect.gen(function* () {
541 const started = yield* acp.start();
542 const initialConfigOptions = started.sessionSetupResult.configOptions ?? [];
543 const modelOption = findCursorModelConfigOption(initialConfigOptions);
544 const modelChoices = flattenSessionConfigSelectOptions(modelOption);
545 if (!modelOption || modelChoices.length === 0) {
546 return [];
547 }
548
549 const currentModelValue =
550 modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined;
551 const capabilitiesBySlug = new Map<string, ModelCapabilities>();
552 if (currentModelValue) {
553 capabilitiesBySlug.set(
554 currentModelValue,
555 buildCursorCapabilitiesFromConfigOptions(initialConfigOptions),
556 );
557 }
558
559 const targetModelSlugs = new Set(
560 existingModels
561 .filter((model) => !model.isCustom && !hasCursorModelCapabilities(model))
562 .map((model) => model.slug),
563 );
564 if (targetModelSlugs.size === 0) {
565 return buildCursorDiscoveredModels(
566 modelChoices.map((modelChoice) => ({
567 slug: modelChoice.value.trim(),
568 name: modelChoice.name.trim(),
569 capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,
570 })),
571 );
572 }
573
574 const probedCapabilities = yield* Effect.forEach(
575 modelChoices,
576 (modelChoice) => {
577 const modelSlug = modelChoice.value.trim();
578 if (!modelSlug || !targetModelSlugs.has(modelSlug) || capabilitiesBySlug.has(modelSlug)) {
579 return Effect.void.pipe(
580 Effect.as<readonly [string, ModelCapabilities] | undefined>(undefined),
581 );
582 }
583
584 return withCursorAcpProbeRuntime(cursorSettings, (probeAcp) =>
585 Effect.gen(function* () {
586 const probeStarted = yield* probeAcp.start();
587 const probeConfigOptions = probeStarted.sessionSetupResult.configOptions ?? [];
588 const probeModelOption = findCursorModelConfigOption(probeConfigOptions);
589 const probeCurrentModelValue =
590 probeModelOption?.type === "select"
591 ? probeModelOption.currentValue?.trim() || undefined
592 : undefined;
593 yield* Effect.annotateCurrentSpan({
594 "cursor.acp.model.value": modelSlug,
595 "cursor.acp.model.currentValue": probeCurrentModelValue,
596 "cursor.acp.config_option_id": probeModelOption?.id ?? modelOption.id,
597 });
598 const nextConfigOptions =
599 probeCurrentModelValue === modelSlug
600 ? probeConfigOptions
601 : yield* probeAcp
602 .setConfigOption(probeModelOption?.id ?? modelOption.id, modelSlug)
603 .pipe(Effect.map((response) => response.configOptions ?? probeConfigOptions));
604 return [
605 modelSlug,
606 buildCursorCapabilitiesFromConfigOptions(nextConfigOptions),
607 ] as const;
608 }),
609 ).pipe(
610 Effect.timeout(CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT),
611 Effect.retry({ times: 3 }),
612 Effect.withSpan("cursor-acp-model-capability-probe"),
613 Effect.catchCause((cause) =>
614 Effect.logWarning("Cursor ACP capability probe failed", {
615 modelSlug,
616 cause: Cause.pretty(cause),
617 }),
618 ),
619 );
620 },
621 { concurrency: CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY },
622 );
623
624 for (const entry of probedCapabilities) {
625 if (!entry) {
626 continue;
627 }
628 capabilitiesBySlug.set(entry[0], entry[1]);
629 }
630
631 return buildCursorDiscoveredModels(
632 modelChoices.map((modelChoice) => ({
633 slug: modelChoice.value.trim(),
634 name: modelChoice.name.trim(),
635 capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,
636 })),
637 );
638 }).pipe(Effect.withSpan("cursor-acp-model-capability-discovery", {})),
639 );
640
641export function getCursorFallbackModels(
642 cursorSettings: Pick<CursorSettings, "customModels">,
643): ReadonlyArray<ServerProviderModel> {
644 return providerModelsFromSettings([], PROVIDER, cursorSettings.customModels, EMPTY_CAPABILITIES);
645}
646
647/** Timeout for `agent about` — it's slower than a simple `--version` probe. */
648const ABOUT_TIMEOUT_MS = 8_000;
649
650/** Strip ANSI escape sequences so we can parse plain key-value lines. */
651function stripAnsi(text: string): string {
652 // eslint-disable-next-line no-control-regex
653 return text.replace(/\x1b\[[0-9;]*[A-Za-z]|\x1b\].*?\x07/g, "");
654}
655
656/**
657 * Extract a value from `agent about` key-value output.
658 * Lines look like: `CLI Version 2026.03.20-44cb435`
659 */
660function extractAboutField(plain: string, key: string): string | undefined {
661 const regex = new RegExp(`^${key}\\s{2,}(.+)$`, "mi");
662 const match = regex.exec(plain);
663 return match?.[1]?.trim();
664}
665
666export interface CursorAboutResult {
667 readonly version: string | null;
668 readonly status: Exclude<ServerProviderState, "disabled">;
669 readonly auth: ServerProviderAuth;
670 readonly message?: string;
671}
672
673function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): string | undefined {
674 const parts = messages
675 .map((message) => message?.trim())
676 .filter((message): message is string => Boolean(message));
677 return parts.length > 0 ? parts.join(" ") : undefined;
678}
679
680export function buildCursorProviderSnapshot(input: {
681 readonly checkedAt: string;
682 readonly cursorSettings: CursorSettings;
683 readonly parsed: CursorAboutResult;
684 readonly discoveredModels?: ReadonlyArray<ServerProviderModel>;
685 readonly discoveryWarning?: string;
686}): ServerProvider {
687 const message = joinProviderMessages(input.parsed.message, input.discoveryWarning);
688 return buildServerProvider({
689 provider: PROVIDER,
690 presentation: CURSOR_PRESENTATION,
691 enabled: input.cursorSettings.enabled,
692 checkedAt: input.checkedAt,
693 models: providerModelsFromSettings(
694 input.discoveredModels ?? [],
695 PROVIDER,
696 input.cursorSettings.customModels,
697 EMPTY_CAPABILITIES,
698 ),
699 probe: {
700 installed: true,
701 version: input.parsed.version,
702 status:
703 input.discoveryWarning && input.parsed.status === "ready" ? "warning" : input.parsed.status,
704 auth: input.parsed.auth,
705 ...(message ? { message } : {}),
706 },
707 });
708}
709
710interface CursorAboutJsonPayload {
711 readonly cliVersion?: unknown;
712 readonly subscriptionTier?: unknown;
713 readonly userEmail?: unknown;
714}
715
716export function parseCursorVersionDate(version: string | null | undefined): number | undefined {
717 const match = version?.trim().match(/^(\d{4})\.(\d{2})\.(\d{2})(?:\b|-|$)/);
718 if (!match) {
719 return undefined;
720 }
721 const [, year, month, day] = match;
722 return Number(`${year}${month}${day}`);
723}
724
725export function parseCursorCliConfigChannel(raw: string): string | undefined {
726 try {
727 const parsed = JSON.parse(raw) as unknown;
728 if (
729 typeof parsed === "object" &&
730 parsed !== null &&
731 "channel" in parsed &&
732 typeof parsed.channel === "string"
733 ) {
734 const channel = parsed.channel.trim().toLowerCase();
735 return channel.length > 0 ? channel : undefined;
736 }
737 } catch {
738 return undefined;
739 }
740 return undefined;
741}
742
743function toTitleCaseWords(value: string): string {
744 return value
745 .split(/[\s_-]+/g)
746 .filter((part) => part.length > 0)
747 .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
748 .join(" ");
749}
750
751function cursorSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
752 const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
753 if (!normalized) return undefined;
754
755 switch (normalized) {
756 case "team":
757 return "Team";
758 case "pro":
759 return "Pro";
760 case "free":
761 return "Free";
762 case "business":
763 return "Business";
764 case "enterprise":
765 return "Enterprise";
766 default:
767 return toTitleCaseWords(subscriptionType!);
768 }
769}
770
771function cursorAuthMetadata(
772 subscriptionType: string | undefined,
773): Pick<ServerProviderAuth, "label" | "type"> | undefined {
774 if (!subscriptionType) {
775 return undefined;
776 }
777 const subscriptionLabel = cursorSubscriptionLabel(subscriptionType);
778 return {
779 type: subscriptionType,
780 label: `Cursor ${subscriptionLabel ?? toTitleCaseWords(subscriptionType)} Subscription`,
781 };
782}
783
784function parseCursorAboutJsonPayload(raw: string): CursorAboutJsonPayload | undefined {
785 const trimmed = raw.trim();
786 if (!trimmed.startsWith("{")) {
787 return undefined;
788 }
789 try {
790 const parsed = JSON.parse(trimmed) as unknown;
791 if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
792 return undefined;
793 }
794 return parsed as CursorAboutJsonPayload;
795 } catch {
796 return undefined;
797 }
798}
799
800function hasOwn(record: object, key: string): boolean {
801 return Object.prototype.hasOwnProperty.call(record, key);
802}
803
804function isCursorAboutJsonFormatUnsupported(result: CommandResult): boolean {
805 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
806 return (
807 lowerOutput.includes("unknown option '--format'") ||
808 lowerOutput.includes("unexpected argument '--format'") ||
809 lowerOutput.includes("unrecognized option '--format'") ||
810 lowerOutput.includes("unknown argument '--format'")
811 );
812}
813
814function readCursorCliConfigChannel(): string | undefined {
815 try {
816 const configPath = nodePath.join(nodeOs.homedir(), ".cursor", "cli-config.json");
817 return parseCursorCliConfigChannel(nodeFs.readFileSync(configPath, "utf8"));
818 } catch {
819 return undefined;
820 }
821}
822
823export function getCursorParameterizedModelPickerUnsupportedMessage(input: {
824 readonly version: string | null | undefined;
825 readonly channel: string | null | undefined;
826}): string | undefined {
827 const reasons: Array<string> = [];
828 const versionDate = parseCursorVersionDate(input.version);
829 if (
830 versionDate !== undefined &&
831 versionDate < CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE
832 ) {
833 reasons.push(
834 `Cursor Agent CLI version ${input.version} is too old for Cursor ACP parameterized model picker`,
835 );
836 }
837
838 const normalizedChannel = input.channel?.trim().toLowerCase();
839 if (
840 normalizedChannel !== undefined &&
841 normalizedChannel.length > 0 &&
842 normalizedChannel !== "lab"
843 ) {
844 reasons.push(
845 `Cursor Agent CLI channel is ${JSON.stringify(input.channel)}, but parameterized model picker is only available on the lab channel`,
846 );
847 }
848
849 if (reasons.length === 0) {
850 return undefined;
851 }
852
853 return `${reasons.join(". ")}. Run \`agent set-channel lab && agent update\` and use Cursor Agent CLI 2026.04.08 or newer.`;
854}
855
856/**
857 * Parse the output of `agent about` to extract version and authentication
858 * status in a single probe.
859 *
860 * Example output (logged in):
861 * ```
862 * About Cursor CLI
863 *
864 * CLI Version 2026.03.20-44cb435
865 * User Email user@example.com
866 * ```
867 *
868 * Example output (logged out):
869 * ```
870 * About Cursor CLI
871 *
872 * CLI Version 2026.03.20-44cb435
873 * User Email Not logged in
874 * ```
875 */
876export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult {
877 const jsonPayload = parseCursorAboutJsonPayload(result.stdout);
878 if (jsonPayload) {
879 const version =
880 typeof jsonPayload.cliVersion === "string" ? jsonPayload.cliVersion.trim() : null;
881 const hasUserEmailField = hasOwn(jsonPayload, "userEmail");
882 const userEmail =
883 typeof jsonPayload.userEmail === "string" ? jsonPayload.userEmail.trim() : undefined;
884 const subscriptionType =
885 typeof jsonPayload.subscriptionTier === "string"
886 ? jsonPayload.subscriptionTier.trim()
887 : undefined;
888 const authMetadata = cursorAuthMetadata(subscriptionType);
889
890 if (hasUserEmailField && jsonPayload.userEmail == null) {
891 return {
892 version,
893 status: "error",
894 auth: { status: "unauthenticated" },
895 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
896 };
897 }
898
899 if (!userEmail) {
900 if (result.code === 0) {
901 return {
902 version,
903 status: "ready",
904 auth: {
905 status: "unknown",
906 ...authMetadata,
907 },
908 };
909 }
910 return {
911 version,
912 status: "warning",
913 auth: { status: "unknown" },
914 message: "Could not verify Cursor Agent authentication status.",
915 };
916 }
917
918 const lowerEmail = userEmail.toLowerCase();
919 if (
920 lowerEmail === "not logged in" ||
921 lowerEmail.includes("login required") ||
922 lowerEmail.includes("authentication required")
923 ) {
924 return {
925 version,
926 status: "error",
927 auth: { status: "unauthenticated" },
928 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
929 };
930 }
931
932 return {
933 version,
934 status: "ready",
935 auth: {
936 status: "authenticated",
937 ...authMetadata,
938 },
939 };
940 }
941
942 const combined = `${result.stdout}\n${result.stderr}`;
943 const lowerOutput = combined.toLowerCase();
944
945 // If the command itself isn't recognised, we're on an old CLI version.
946 if (
947 lowerOutput.includes("unknown command") ||
948 lowerOutput.includes("unrecognized command") ||
949 lowerOutput.includes("unexpected argument")
950 ) {
951 return {
952 version: null,
953 status: "warning",
954 auth: { status: "unknown" },
955 message: "The `agent about` command is unavailable in this version of the Cursor Agent CLI.",
956 };
957 }
958
959 const plain = stripAnsi(combined);
960 const version = extractAboutField(plain, "CLI Version") ?? null;
961 const userEmail = extractAboutField(plain, "User Email");
962
963 // Determine auth from the User Email field.
964 if (userEmail === undefined) {
965 // Field missing entirely — can't determine auth.
966 if (result.code === 0) {
967 return { version, status: "ready", auth: { status: "unknown" } };
968 }
969 return {
970 version,
971 status: "warning",
972 auth: { status: "unknown" },
973 message: "Could not verify Cursor Agent authentication status.",
974 };
975 }
976
977 const lowerEmail = userEmail.toLowerCase();
978 if (
979 lowerEmail === "not logged in" ||
980 lowerEmail.includes("login required") ||
981 lowerEmail.includes("authentication required")
982 ) {
983 return {
984 version,
985 status: "error",
986 auth: { status: "unauthenticated" },
987 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
988 };
989 }
990
991 // Any non-empty email value means authenticated.
992 return { version, status: "ready", auth: { status: "authenticated" } };
993}
994
995const runCursorCommand = (args: ReadonlyArray<string>) =>
996 Effect.gen(function* () {
997 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
998 const cursorSettings = yield* Effect.service(ServerSettingsService).pipe(
999 Effect.flatMap((service) => service.getSettings),
1000 Effect.map((settings) => settings.providers.cursor),
1001 );
1002 const command = ChildProcess.make(cursorSettings.binaryPath, [...args], {
1003 shell: process.platform === "win32",
1004 });
1005
1006 const child = yield* spawner.spawn(command);
1007 const [stdout, stderr, exitCode] = yield* Effect.all(
1008 [
1009 collectStreamAsString(child.stdout),
1010 collectStreamAsString(child.stderr),
1011 child.exitCode.pipe(Effect.map(Number)),
1012 ],
1013 { concurrency: "unbounded" },
1014 );
1015
1016 return { stdout, stderr, code: exitCode } satisfies CommandResult;
1017 }).pipe(Effect.scoped);
1018
1019const runCursorAboutCommand = Effect.gen(function* () {
1020 const jsonResult = yield* runCursorCommand(["about", "--format", "json"]);
1021 if (!isCursorAboutJsonFormatUnsupported(jsonResult)) {
1022 return jsonResult;
1023 }
1024 return yield* runCursorCommand(["about"]);
1025});
1026
1027export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
1028 function* (): Effect.fn.Return<
1029 ServerProvider,
1030 ServerSettingsError,
1031 ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
1032 > {
1033 const cursorSettings = yield* Effect.service(ServerSettingsService).pipe(
1034 Effect.flatMap((service) => service.getSettings),
1035 Effect.map((settings) => settings.providers.cursor),
1036 );
1037 const checkedAt = new Date().toISOString();
1038 const fallbackModels = getCursorFallbackModels(cursorSettings);
1039
1040 if (!cursorSettings.enabled) {
1041 return buildServerProvider({
1042 provider: PROVIDER,
1043 presentation: CURSOR_PRESENTATION,
1044 enabled: false,
1045 checkedAt,
1046 models: fallbackModels,
1047 probe: {
1048 installed: false,
1049 version: null,
1050 status: "warning",
1051 auth: { status: "unknown" },
1052 message: "Cursor is disabled in T3 Code settings.",
1053 },
1054 });
1055 }
1056
1057 // Single `agent about` probe: returns version + auth status in one call.
1058 const aboutProbe = yield* runCursorAboutCommand.pipe(
1059 Effect.timeoutOption(ABOUT_TIMEOUT_MS),
1060 Effect.result,
1061 );
1062
1063 if (Result.isFailure(aboutProbe)) {
1064 const error = aboutProbe.failure;
1065 return buildServerProvider({
1066 provider: PROVIDER,
1067 presentation: CURSOR_PRESENTATION,
1068 enabled: cursorSettings.enabled,
1069 checkedAt,
1070 models: fallbackModels,
1071 probe: {
1072 installed: !isCommandMissingCause(error),
1073 version: null,
1074 status: "error",
1075 auth: { status: "unknown" },
1076 message: isCommandMissingCause(error)
1077 ? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
1078 : `Failed to execute Cursor Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
1079 },
1080 });
1081 }
1082
1083 if (Option.isNone(aboutProbe.success)) {
1084 return buildServerProvider({
1085 provider: PROVIDER,
1086 presentation: CURSOR_PRESENTATION,
1087 enabled: cursorSettings.enabled,
1088 checkedAt,
1089 models: fallbackModels,
1090 probe: {
1091 installed: true,
1092 version: null,
1093 status: "error",
1094 auth: { status: "unknown" },
1095 message: "Cursor Agent CLI is installed but timed out while running `agent about`.",
1096 },
1097 });
1098 }
1099
1100 const parsed = parseCursorAboutOutput(aboutProbe.success.value);
1101 const parameterizedModelPickerUnsupportedMessage =
1102 getCursorParameterizedModelPickerUnsupportedMessage({
1103 version: parsed.version,
1104 channel: readCursorCliConfigChannel(),
1105 });
1106 if (parameterizedModelPickerUnsupportedMessage) {
1107 return buildServerProvider({
1108 provider: PROVIDER,
1109 presentation: CURSOR_PRESENTATION,
1110 enabled: cursorSettings.enabled,
1111 checkedAt,
1112 models: fallbackModels,
1113 probe: {
1114 installed: true,
1115 version: parsed.version,
1116 status: "error",
1117 auth: parsed.auth,
1118 message:
1119 parsed.auth.status === "unauthenticated" && parsed.message
1120 ? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}`
1121 : parameterizedModelPickerUnsupportedMessage,
1122 },
1123 });
1124 }
1125 let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();
1126 let discoveryWarning: string | undefined;
1127 if (parsed.auth.status !== "unauthenticated") {
1128 const discoveryExit = yield* Effect.exit(
1129 discoverCursorModelsViaAcp(cursorSettings).pipe(
1130 Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
1131 ),
1132 );
1133 if (Exit.isFailure(discoveryExit)) {
1134 yield* Effect.logWarning("Cursor ACP model discovery failed", {
1135 cause: Cause.pretty(discoveryExit.cause),
1136 });
1137 discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
1138 } else if (Option.isNone(discoveryExit.value)) {
1139 discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
1140 } else if (discoveryExit.value.value.length === 0) {
1141 discoveryWarning = "Cursor ACP model discovery returned no built-in models.";
1142 } else {
1143 discoveredModels = discoveryExit.value;
1144 }
1145 }
1146 return buildCursorProviderSnapshot({
1147 checkedAt,
1148 cursorSettings,
1149 parsed,
1150 discoveredModels: Option.getOrElse(
1151 Option.filter(discoveredModels, (models) => models.length > 0),
1152 () => [] as const,
1153 ),
1154 ...(discoveryWarning ? { discoveryWarning } : {}),
1155 });
1156 },
1157);
1158
1159export const CursorProviderLive = Layer.effect(
1160 CursorProvider,
1161 Effect.gen(function* () {
1162 const serverSettings = yield* ServerSettingsService;
1163 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1164
1165 const checkProvider = checkCursorProviderStatus().pipe(
1166 Effect.provideService(ServerSettingsService, serverSettings),
1167 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1168 );
1169
1170 return yield* makeManagedServerProvider<CursorSettings>({
1171 getSettings: serverSettings.getSettings.pipe(
1172 Effect.map((settings) => settings.providers.cursor),
1173 Effect.orDie,
1174 ),
1175 streamSettings: serverSettings.streamChanges.pipe(
1176 Stream.map((settings) => settings.providers.cursor),
1177 ),
1178 haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
1179 initialSnapshot: buildInitialCursorProviderSnapshot,
1180 checkProvider,
1181 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => {
1182 if (
1183 !settings.enabled ||
1184 snapshot.auth.status === "unauthenticated" ||
1185 !snapshot.models.some((model) => !model.isCustom && !hasCursorModelCapabilities(model))
1186 ) {
1187 return Effect.void;
1188 }
1189
1190 return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models).pipe(
1191 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1192 Effect.flatMap((discoveredModels) => {
1193 if (discoveredModels.length === 0) {
1194 return Effect.void;
1195 }
1196
1197 return publishSnapshot({
1198 ...snapshot,
1199 models: providerModelsFromSettings(
1200 discoveredModels,
1201 PROVIDER,
1202 settings.customModels,
1203 EMPTY_CAPABILITIES,
1204 ),
1205 });
1206 }),
1207 Effect.catchCause((cause) =>
1208 Effect.logWarning("Cursor ACP background capability enrichment failed", {
1209 models: snapshot.models.map((model) => model.slug),
1210 cause: Cause.pretty(cause),
1211 }).pipe(Effect.asVoid),
1212 ),
1213 );
1214 },
1215 refreshInterval: CURSOR_REFRESH_INTERVAL,
1216 });
1217 }),
1218);