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

CursorProvider.ts

1,287 lines41.3 KB

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