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