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

CursorProvider.ts

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