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

CursorProvider.ts

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