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 (about: Pick<CursorAboutResult, "version" | "auth">) =>
682 Cache.get(cache, JSON.stringify([about.version, about.auth]));
683});
684
685function getCursorFallbackModels(
686 cursorSettings: Pick<CursorSettings, "customModels">,
687): ReadonlyArray<ServerProviderModel> {
688 return providerModelsFromSettings([], cursorSettings.customModels, EMPTY_CAPABILITIES);
689}
690
691/** Timeout for `agent about` — it's slower than a simple `--version` probe. */
692const ABOUT_TIMEOUT_MS = 8_000;
693
694/** Strip ANSI escape sequences so we can parse plain key-value lines. */
695function stripAnsi(text: string): string {
696 // eslint-disable-next-line no-control-regex
697 return text.replace(/\x1b\[[0-9;]*[A-Za-z]|\x1b\].*?\x07/g, "");
698}
699
700/**
701 * Extract a value from `agent about` key-value output.
702 * Lines look like: `CLI Version 2026.03.20-44cb435`
703 */
704function extractAboutField(plain: string, key: string): string | undefined {
705 const regex = new RegExp(`^${key}\\s{2,}(.+)$`, "mi");
706 const match = regex.exec(plain);
707 return match?.[1]?.trim();
708}
709
710export interface CursorAboutResult {
711 readonly version: string | null;
712 readonly status: Exclude<ServerProviderState, "disabled">;
713 readonly auth: ServerProviderAuth;
714 readonly message?: string;
715}
716
717function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): string | undefined {
718 const parts: Array<string> = [];
719 for (const message of messages) {
720 const trimmed = message?.trim();
721 if (trimmed) {
722 parts.push(trimmed);
723 }
724 }
725 return parts.length > 0 ? parts.join(" ") : undefined;
726}
727
728function buildCursorCliCommandMissingMessage(binaryPath: string): string {
729 return [
730 `Cursor CLI command \`${binaryPath}\` was not found.`,
731 `Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
732 `See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
733 ].join(" ");
734}
735
736export function buildCursorProviderSnapshot(input: {
737 readonly checkedAt: string;
738 readonly cursorSettings: CursorSettings;
739 readonly parsed: CursorAboutResult;
740 readonly discoveredModels?: ReadonlyArray<ServerProviderModel>;
741 readonly discoveryWarning?: string;
742}): ServerProviderDraft {
743 const message = joinProviderMessages(input.parsed.message, input.discoveryWarning);
744 return buildServerProvider({
745 presentation: CURSOR_PRESENTATION,
746 enabled: input.cursorSettings.enabled,
747 checkedAt: input.checkedAt,
748 models: providerModelsFromSettings(
749 input.discoveredModels ?? [],
750 input.cursorSettings.customModels,
751 EMPTY_CAPABILITIES,
752 ),
753 slashCommands: [COMPACT_SLASH_COMMAND],
754 probe: {
755 installed: true,
756 version: input.parsed.version,
757 status:
758 input.discoveryWarning && input.parsed.status === "ready" ? "warning" : input.parsed.status,
759 auth: input.parsed.auth,
760 ...(message ? { message } : {}),
761 },
762 });
763}
764
765interface CursorAboutJsonPayload {
766 readonly cliVersion?: unknown;
767 readonly subscriptionTier?: unknown;
768 readonly userEmail?: unknown;
769}
770
771export function parseCursorVersionDate(version: string | null | undefined): number | undefined {
772 const match = version?.trim().match(/^(\d{4})\.(\d{2})\.(\d{2})(?:\b|-|$)/);
773 if (!match) {
774 return undefined;
775 }
776 const [, year, month, day] = match;
777 return Number(`${year}${month}${day}`);
778}
779
780export function parseCursorCliConfigChannel(raw: string): string | undefined {
781 try {
782 const parsed = JSON.parse(raw) as unknown;
783 if (
784 typeof parsed === "object" &&
785 parsed !== null &&
786 "channel" in parsed &&
787 typeof parsed.channel === "string"
788 ) {
789 const channel = parsed.channel.trim().toLowerCase();
790 return channel.length > 0 ? channel : undefined;
791 }
792 } catch {
793 return undefined;
794 }
795 return undefined;
796}
797
798function toTitleCaseWords(value: string): string {
799 const parts: Array<string> = [];
800 for (const part of value.split(/[\s_-]+/g)) {
801 if (part.length > 0) {
802 parts.push(part.charAt(0).toUpperCase() + part.slice(1).toLowerCase());
803 }
804 }
805 return parts.join(" ");
806}
807
808function cursorSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
809 const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
810 if (!normalized) return undefined;
811
812 switch (normalized) {
813 case "team":
814 return "Team";
815 case "pro":
816 return "Pro";
817 case "free":
818 return "Free";
819 case "business":
820 return "Business";
821 case "enterprise":
822 return "Enterprise";
823 default:
824 return toTitleCaseWords(subscriptionType!);
825 }
826}
827
828function cursorAuthMetadata(
829 subscriptionType: string | undefined,
830): Pick<ServerProviderAuth, "label" | "type"> | undefined {
831 if (!subscriptionType) {
832 return undefined;
833 }
834 const subscriptionLabel = cursorSubscriptionLabel(subscriptionType);
835 return {
836 type: subscriptionType,
837 label: `Cursor ${subscriptionLabel ?? toTitleCaseWords(subscriptionType)} Subscription`,
838 };
839}
840
841function parseCursorAboutJsonPayload(raw: string): CursorAboutJsonPayload | undefined {
842 const trimmed = raw.trim();
843 if (!trimmed.startsWith("{")) {
844 return undefined;
845 }
846 try {
847 const parsed = JSON.parse(trimmed) as unknown;
848 if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
849 return undefined;
850 }
851 return parsed as CursorAboutJsonPayload;
852 } catch {
853 return undefined;
854 }
855}
856
857function hasOwn(record: object, key: string): boolean {
858 return Object.prototype.hasOwnProperty.call(record, key);
859}
860
861function isCursorAboutJsonFormatUnsupported(result: CommandResult): boolean {
862 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
863 return (
864 lowerOutput.includes("unknown option '--format'") ||
865 lowerOutput.includes("unexpected argument '--format'") ||
866 lowerOutput.includes("unrecognized option '--format'") ||
867 lowerOutput.includes("unknown argument '--format'")
868 );
869}
870
871const readCursorCliConfigChannel = Effect.fn("readCursorCliConfigChannel")(function* () {
872 const fileSystem = yield* FileSystem.FileSystem;
873 const path = yield* Path.Path;
874 const configPath = path.join(NodeOS.homedir(), ".cursor", "cli-config.json");
875 const raw = yield* fileSystem.readFileString(configPath).pipe(Effect.orElseSucceed(() => ""));
876 return parseCursorCliConfigChannel(raw);
877});
878
879export function getCursorParameterizedModelPickerUnsupportedMessage(input: {
880 readonly version: string | null | undefined;
881 readonly channel: string | null | undefined;
882}): string | undefined {
883 const reasons: Array<string> = [];
884 const versionDate = parseCursorVersionDate(input.version);
885 if (
886 versionDate !== undefined &&
887 versionDate < CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE
888 ) {
889 reasons.push(
890 `Cursor Agent CLI version ${input.version} is too old for Cursor ACP parameterized model picker`,
891 );
892 }
893
894 const normalizedChannel = input.channel?.trim().toLowerCase();
895 if (
896 normalizedChannel !== undefined &&
897 normalizedChannel.length > 0 &&
898 normalizedChannel !== "lab"
899 ) {
900 reasons.push(
901 `Cursor Agent CLI channel is ${JSON.stringify(input.channel)}, but parameterized model picker is only available on the lab channel`,
902 );
903 }
904
905 if (reasons.length === 0) {
906 return undefined;
907 }
908
909 return `${reasons.join(". ")}. Run \`agent set-channel lab && agent update\` and use Cursor Agent CLI 2026.04.08 or newer.`;
910}
911
912/**
913 * Parse the output of `agent about` to extract version and authentication
914 * status in a single probe.
915 *
916 * Example output (logged in):
917 * ```
918 * About Cursor CLI
919 *
920 * CLI Version 2026.03.20-44cb435
921 * User Email user@example.com
922 * ```
923 *
924 * Example output (logged out):
925 * ```
926 * About Cursor CLI
927 *
928 * CLI Version 2026.03.20-44cb435
929 * User Email Not logged in
930 * ```
931 */
932export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult {
933 const jsonPayload = parseCursorAboutJsonPayload(result.stdout);
934 if (jsonPayload) {
935 const version =
936 typeof jsonPayload.cliVersion === "string" ? jsonPayload.cliVersion.trim() : null;
937 const hasUserEmailField = hasOwn(jsonPayload, "userEmail");
938 const userEmail =
939 typeof jsonPayload.userEmail === "string" ? jsonPayload.userEmail.trim() : undefined;
940 const subscriptionType =
941 typeof jsonPayload.subscriptionTier === "string"
942 ? jsonPayload.subscriptionTier.trim()
943 : undefined;
944 const authMetadata = cursorAuthMetadata(subscriptionType);
945
946 if (hasUserEmailField && jsonPayload.userEmail == null) {
947 return {
948 version,
949 status: "error",
950 auth: { status: "unauthenticated" },
951 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
952 };
953 }
954
955 if (!userEmail) {
956 if (result.code === 0) {
957 return {
958 version,
959 status: "ready",
960 auth: {
961 status: "unknown",
962 ...authMetadata,
963 },
964 };
965 }
966 return {
967 version,
968 status: "warning",
969 auth: { status: "unknown" },
970 message: "Could not verify Cursor Agent authentication status.",
971 };
972 }
973
974 const lowerEmail = userEmail.toLowerCase();
975 if (
976 lowerEmail === "not logged in" ||
977 lowerEmail.includes("login required") ||
978 lowerEmail.includes("authentication required")
979 ) {
980 return {
981 version,
982 status: "error",
983 auth: { status: "unauthenticated" },
984 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
985 };
986 }
987
988 return {
989 version,
990 status: "ready",
991 auth: {
992 status: "authenticated",
993 email: userEmail,
994 ...authMetadata,
995 },
996 };
997 }
998
999 const combined = `${result.stdout}\n${result.stderr}`;
1000 const lowerOutput = combined.toLowerCase();
1001
1002 // If the command itself isn't recognised, we're on an old CLI version.
1003 if (
1004 lowerOutput.includes("unknown command") ||
1005 lowerOutput.includes("unrecognized command") ||
1006 lowerOutput.includes("unexpected argument")
1007 ) {
1008 return {
1009 version: null,
1010 status: "warning",
1011 auth: { status: "unknown" },
1012 message: "The `agent about` command is unavailable in this version of the Cursor Agent CLI.",
1013 };
1014 }
1015
1016 const plain = stripAnsi(combined);
1017 const version = extractAboutField(plain, "CLI Version") ?? null;
1018 const userEmail = extractAboutField(plain, "User Email");
1019
1020 // Determine auth from the User Email field.
1021 if (userEmail === undefined) {
1022 // Field missing entirely — can't determine auth.
1023 if (result.code === 0) {
1024 return { version, status: "ready", auth: { status: "unknown" } };
1025 }
1026 return {
1027 version,
1028 status: "warning",
1029 auth: { status: "unknown" },
1030 message: "Could not verify Cursor Agent authentication status.",
1031 };
1032 }
1033
1034 const lowerEmail = userEmail.toLowerCase();
1035 if (
1036 lowerEmail === "not logged in" ||
1037 lowerEmail.includes("login required") ||
1038 lowerEmail.includes("authentication required")
1039 ) {
1040 return {
1041 version,
1042 status: "error",
1043 auth: { status: "unauthenticated" },
1044 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
1045 };
1046 }
1047
1048 // Any non-empty email value means authenticated.
1049 return {
1050 version,
1051 status: "ready",
1052 auth: { status: "authenticated", email: userEmail },
1053 };
1054}
1055
1056const runCursorCommand = (
1057 cursorSettings: CursorSettings,
1058 args: ReadonlyArray<string>,
1059 environment?: NodeJS.ProcessEnv,
1060) =>
1061 Effect.gen(function* () {
1062 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1063 const spawnCommand = yield* resolveSpawnCommand(
1064 cursorSettings.binaryPath,
1065 args,
1066 environment ? { env: environment } : {},
1067 );
1068 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
1069 ...(environment ? { env: environment } : { extendEnv: true }),
1070 shell: spawnCommand.shell,
1071 });
1072
1073 const child = yield* spawner.spawn(command);
1074 const [stdout, stderr, exitCode] = yield* Effect.all(
1075 [
1076 collectStreamAsString(child.stdout),
1077 collectStreamAsString(child.stderr),
1078 child.exitCode.pipe(Effect.map(Number)),
1079 ],
1080 { concurrency: "unbounded" },
1081 );
1082
1083 return { stdout, stderr, code: exitCode } satisfies CommandResult;
1084 }).pipe(Effect.scoped);
1085
1086const runCursorAboutCommand = (cursorSettings: CursorSettings, environment?: NodeJS.ProcessEnv) =>
1087 Effect.gen(function* () {
1088 const jsonResult = yield* runCursorCommand(
1089 cursorSettings,
1090 ["about", "--format", "json"],
1091 environment,
1092 );
1093 if (!isCursorAboutJsonFormatUnsupported(jsonResult)) {
1094 return jsonResult;
1095 }
1096 return yield* runCursorCommand(cursorSettings, ["about"], environment);
1097 });
1098
1099export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(function* (
1100 cursorSettings: CursorSettings,
1101 environment?: NodeJS.ProcessEnv,
1102 discoverModels?: (about: CursorAboutResult) => ReturnType<typeof discoverCursorModelsViaAcp>,
1103): Effect.fn.Return<
1104 ServerProviderDraft,
1105 never,
1106 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
1107> {
1108 const checkedAt = DateTime.formatIso(yield* DateTime.now);
1109 const fallbackModels = getCursorFallbackModels(cursorSettings);
1110
1111 if (!cursorSettings.enabled) {
1112 return buildServerProvider({
1113 presentation: CURSOR_PRESENTATION,
1114 enabled: false,
1115 checkedAt,
1116 models: fallbackModels,
1117 probe: {
1118 installed: false,
1119 version: null,
1120 status: "warning",
1121 auth: { status: "unknown" },
1122 message: "Cursor is disabled in T3 Code settings.",
1123 },
1124 });
1125 }
1126
1127 // Single `agent about` probe: returns version + auth status in one call.
1128 const aboutProbe = yield* runCursorAboutCommand(cursorSettings, environment).pipe(
1129 Effect.timeoutOption(ABOUT_TIMEOUT_MS),
1130 Effect.result,
1131 );
1132
1133 if (Result.isFailure(aboutProbe)) {
1134 const error = aboutProbe.failure;
1135 yield* Effect.logWarning("Cursor Agent CLI health check failed.", {
1136 errorTag: error._tag,
1137 });
1138 return buildServerProvider({
1139 presentation: CURSOR_PRESENTATION,
1140 enabled: cursorSettings.enabled,
1141 checkedAt,
1142 models: fallbackModels,
1143 probe: {
1144 installed: !isCommandMissingCause(error),
1145 version: null,
1146 status: "error",
1147 auth: { status: "unknown" },
1148 message: isCommandMissingCause(error)
1149 ? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
1150 : "Failed to execute Cursor Agent CLI health check.",
1151 },
1152 });
1153 }
1154
1155 if (Option.isNone(aboutProbe.success)) {
1156 return buildServerProvider({
1157 presentation: CURSOR_PRESENTATION,
1158 enabled: cursorSettings.enabled,
1159 checkedAt,
1160 models: fallbackModels,
1161 probe: {
1162 installed: true,
1163 version: null,
1164 status: "error",
1165 auth: { status: "unknown" },
1166 message: "Cursor Agent CLI is installed but timed out while running `agent about`.",
1167 },
1168 });
1169 }
1170
1171 const parsed = parseCursorAboutOutput(aboutProbe.success.value);
1172 const cursorCliConfigChannel = yield* readCursorCliConfigChannel();
1173 const parameterizedModelPickerUnsupportedMessage =
1174 getCursorParameterizedModelPickerUnsupportedMessage({
1175 version: parsed.version,
1176 channel: cursorCliConfigChannel,
1177 });
1178 if (parameterizedModelPickerUnsupportedMessage) {
1179 return buildServerProvider({
1180 presentation: CURSOR_PRESENTATION,
1181 enabled: cursorSettings.enabled,
1182 checkedAt,
1183 models: fallbackModels,
1184 probe: {
1185 installed: true,
1186 version: parsed.version,
1187 status: "error",
1188 auth: parsed.auth,
1189 message:
1190 parsed.auth.status === "unauthenticated" && parsed.message
1191 ? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}`
1192 : parameterizedModelPickerUnsupportedMessage,
1193 },
1194 });
1195 }
1196 let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();
1197 let discoveryWarning: string | undefined;
1198 if (parsed.auth.status !== "unauthenticated") {
1199 const discoveryExit = yield* Effect.exit(
1200 (discoverModels
1201 ? discoverModels(parsed)
1202 : discoverCursorModelsViaAcp(cursorSettings, environment)
1203 ).pipe(Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS)),
1204 );
1205 if (Exit.isFailure(discoveryExit)) {
1206 yield* Effect.logWarning("Cursor ACP model discovery failed", {
1207 errorTag: causeErrorTag(discoveryExit.cause),
1208 });
1209 discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
1210 } else if (Option.isNone(discoveryExit.value)) {
1211 discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
1212 } else if (discoveryExit.value.value.length === 0) {
1213 discoveryWarning = "Cursor ACP model discovery returned no built-in models.";
1214 } else {
1215 discoveredModels = discoveryExit.value;
1216 }
1217 }
1218 return buildCursorProviderSnapshot({
1219 checkedAt,
1220 cursorSettings,
1221 parsed,
1222 discoveredModels: Option.getOrElse(
1223 Option.filter(discoveredModels, (models) => models.length > 0),
1224 () => [] as const,
1225 ),
1226 ...(discoveryWarning ? { discoveryWarning } : {}),
1227 });
1228});
1229
1230/**
1231 * Background maintenance enrichment for a Cursor snapshot.
1232 *
1233 * Used by `CursorDriver` as the `makeManagedServerProvider.enrichSnapshot`
1234 * hook: republishes update/version advisory metadata without performing any
1235 * model or capability discovery. Cursor model data comes exclusively from
1236 * `cursor/list_available_models` during provider status checks.
1237 */
1238export const enrichCursorSnapshot = (input: {
1239 readonly settings: CursorSettings;
1240 readonly snapshot: ServerProvider;
1241 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
1242 readonly enableProviderUpdateChecks?: boolean;
1243 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
1244 readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
1245 readonly httpClient: HttpClient.HttpClient;
1246}): Effect.Effect<void> => {
1247 const { settings, snapshot, publishSnapshot } = input;
1248 const stampIdentity = input.stampIdentity ?? ((value) => value);
1249
1250 if (!settings.enabled || snapshot.auth.status === "unauthenticated") {
1251 return Effect.void;
1252 }
1253
1254 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
1255 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
1256 }).pipe(
1257 Effect.provideService(HttpClient.HttpClient, input.httpClient),
1258 Effect.flatMap((enrichedSnapshot) =>
1259 publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
1260 ),
1261 Effect.catchCause((cause) =>
1262 Effect.logWarning("Cursor version advisory enrichment failed", {
1263 errorTag: causeErrorTag(cause),
1264 }).pipe(Effect.asVoid),
1265 ),
1266 );
1267};