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

CursorProvider.ts

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