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

CursorProvider.ts

1,177 lines37.4 KB

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