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

CursorProvider.ts

1,153 lines36.4 KB

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