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