From c2132ee7dd754d6d6a1599bc8983f0e47dd042b8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 30 Jun 2026 10:29:28 -0700 Subject: [PATCH] Switch Cursor provider to the official SDK - remove ACP model discovery and mismatch probe code - update provider, orchestration, and tests for SDK-based flows - refresh marketing copy to match the SDK runtime --- apps/marketing/src/pages/index.astro | 2 +- apps/server/scripts/acp-mock-agent.ts | 35 - .../cursor-acp-model-mismatch-probe.ts | 442 -------- .../Adapters/CursorAdapterV2.ts | 26 +- .../CursorOrchestratorV2.live.test.ts | 81 +- .../src/provider/Drivers/CursorDriver.ts | 61 +- .../provider/Layers/CursorProvider.test.ts | 666 +----------- .../src/provider/Layers/CursorProvider.ts | 970 ++---------------- .../ProviderInstanceRegistryLive.test.ts | 2 - .../provider/acp/CursorAcpCliProbe.test.ts | 153 --- .../provider/acp/CursorAcpExtension.test.ts | 135 --- .../src/provider/acp/CursorAcpExtension.ts | 110 -- .../src/provider/acp/CursorAcpSupport.test.ts | 121 --- .../src/provider/acp/CursorAcpSupport.ts | 114 -- apps/server/src/provider/cursorSdkModel.ts | 19 + .../providerMaintenanceRunner.test.ts | 22 +- .../CursorTextGeneration.test.ts | 420 +++----- .../textGeneration/CursorTextGeneration.ts | 143 ++- packages/contracts/src/settings.test.ts | 34 + packages/contracts/src/settings.ts | 21 - .../examples/cursor-acp-client.example.ts | 81 -- 21 files changed, 508 insertions(+), 3150 deletions(-) delete mode 100644 apps/server/scripts/cursor-acp-model-mismatch-probe.ts delete mode 100644 apps/server/src/provider/acp/CursorAcpCliProbe.test.ts delete mode 100644 apps/server/src/provider/acp/CursorAcpExtension.test.ts delete mode 100644 apps/server/src/provider/acp/CursorAcpExtension.ts delete mode 100644 apps/server/src/provider/acp/CursorAcpSupport.test.ts delete mode 100644 apps/server/src/provider/acp/CursorAcpSupport.ts delete mode 100644 packages/effect-acp/test/examples/cursor-acp-client.example.ts diff --git a/apps/marketing/src/pages/index.astro b/apps/marketing/src/pages/index.astro index 69de2088d4..dbd9f7c4f2 100644 --- a/apps/marketing/src/pages/index.astro +++ b/apps/marketing/src/pages/index.astro @@ -204,7 +204,7 @@ const mobileEndorsementRows = [
Cursor
-
cursor-agent
+
@cursor/sdk
diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index e9f607e719..dce0c261aa 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -228,35 +228,6 @@ function configOptions(): ReadonlyArray { ]; } -function modelConfigOptionsFor(modelId: string): ReadonlyArray { - const previousModelId = currentModelId; - try { - currentModelId = modelId; - return configOptions().filter( - (option) => option.category !== "mode" && option.category !== "model", - ); - } finally { - currentModelId = previousModelId; - } -} - -function availableModels(): ReadonlyArray<{ - readonly value: string; - readonly name: string; - readonly configOptions: ReadonlyArray; -}> { - return [ - { value: "default", name: "Auto" }, - { value: "composer-2", name: "Composer 2" }, - { value: "gpt-5.4", name: "GPT-5.4" }, - { value: "claude-opus-4-6", name: "Opus 4.6" }, - ].map((model) => ({ - value: model.value, - name: model.name, - configOptions: modelConfigOptionsFor(model.value), - })); -} - const availableModes: ReadonlyArray = [ { id: "ask", @@ -951,12 +922,6 @@ const program = Effect.gen(function* () { ); yield* agent.handleUnknownExtRequest((method, params) => { - if (method === "cursor/list_available_models") { - return Effect.succeed({ - models: availableModels(), - }); - } - if (method !== "session/mode/set") { return Effect.fail(AcpError.AcpRequestError.methodNotFound(method)); } diff --git a/apps/server/scripts/cursor-acp-model-mismatch-probe.ts b/apps/server/scripts/cursor-acp-model-mismatch-probe.ts deleted file mode 100644 index b36c2b2d49..0000000000 --- a/apps/server/scripts/cursor-acp-model-mismatch-probe.ts +++ /dev/null @@ -1,442 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -import * as NodeChildProcess from "node:child_process"; -import * as NodeProcess from "node:process"; -import * as NodeReadline from "node:readline"; -import * as NodeTimers from "node:timers"; -import { resolveSpawnCommand } from "@t3tools/shared/shell"; -import * as Effect from "effect/Effect"; - -type JsonPrimitive = null | boolean | number | string; -type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }; - -type JsonRpcId = number | string; - -type JsonRpcMessage = { - jsonrpc?: string; - id?: JsonRpcId; - method?: string; - params?: JsonValue; - result?: JsonValue; - error?: JsonValue; - headers?: JsonValue; -}; - -type SelectLeafOption = { - value: string; - label?: string; - name?: string; -}; - -type SelectGroupOption = { - label?: string; - name?: string; - options: SelectLeafOption[]; -}; - -type SessionConfigOption = { - id: string; - name?: string; - category?: string; - type?: string; - options?: Array; -}; - -type SessionNewResult = { - sessionId: string; - configOptions?: SessionConfigOption[]; -}; - -type SetConfigResult = { - configOptions?: SessionConfigOption[]; -}; - -type PendingRequest = { - method: string; - resolve: (value: JsonValue | undefined) => void; - reject: (error: Error) => void; -}; - -const targetCwd = NodeProcess.argv[2] ?? NodeProcess.cwd(); -const targetModel = NodeProcess.argv[3] ?? "gpt-5.4"; -const promptText = NodeProcess.argv[4] ?? "helo"; -const targetReasoning = NodeProcess.env.CURSOR_REASONING ?? ""; -const targetContext = NodeProcess.env.CURSOR_CONTEXT ?? ""; -const targetFast = NodeProcess.env.CURSOR_FAST ?? ""; -const agentBin = NodeProcess.env.CURSOR_AGENT_BIN ?? "agent"; -const promptWaitMs = Number(NodeProcess.env.CURSOR_PROMPT_WAIT_MS ?? "4000"); -const requestTimeoutMs = Number(NodeProcess.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000"); - -function logSection(title: string, value: unknown) { - NodeProcess.stdout.write(`\n=== ${title} ===\n`); - NodeProcess.stdout.write(`${JSON.stringify(value, null, 2)}\n`); -} - -function fail(message: string): never { - throw new Error(message); -} - -function asString(value: JsonValue | undefined): string | null { - return typeof value === "string" ? value : null; -} - -function flattenSelectValues(option: SessionConfigOption | undefined): string[] { - if (!option || option.type !== "select" || !Array.isArray(option.options)) { - return []; - } - - const values: string[] = []; - for (const entry of option.options) { - if (!entry || typeof entry !== "object") { - continue; - } - if ("value" in entry && typeof entry.value === "string") { - values.push(entry.value); - continue; - } - if ("options" in entry && Array.isArray(entry.options)) { - for (const nested of entry.options) { - if (nested && typeof nested === "object" && typeof nested.value === "string") { - values.push(nested.value); - } - } - } - } - return values; -} - -function findConfigOption( - configOptions: SessionConfigOption[], - predicate: (option: SessionConfigOption) => boolean, -): SessionConfigOption | undefined { - return configOptions.find(predicate); -} - -function matchesKeyword(option: SessionConfigOption, keyword: string): boolean { - const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase(); - return haystack.includes(keyword.toLowerCase()); -} - -function sleep(ms: number) { - return new Promise((resolve) => { - // @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script, not an Effect runtime test. - NodeTimers.setTimeout(resolve, ms); - }); -} - -class JsonRpcChild { - readonly child: NodeChildProcess.ChildProcessWithoutNullStreams; - readonly pending = new Map(); - nextId = 1; - closed = false; - - constructor(bin: string, args: string[], cwd: string) { - const spawnCommand = Effect.runSync(resolveSpawnCommand(bin, args)); - this.child = NodeChildProcess.spawn(spawnCommand.command, spawnCommand.args, { - cwd, - shell: spawnCommand.shell, - stdio: ["pipe", "pipe", "pipe"], - env: NodeProcess.env, - }); - - this.child.on("exit", (code, signal) => { - this.closed = true; - const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`; - for (const pending of this.pending.values()) { - pending.reject(new Error(`${detail} while waiting for ${pending.method}`)); - } - this.pending.clear(); - }); - - this.child.on("error", (error) => { - this.closed = true; - for (const pending of this.pending.values()) { - pending.reject(error); - } - this.pending.clear(); - }); - - const stdout = NodeReadline.createInterface({ input: this.child.stdout }); - stdout.on("line", (line) => { - void this.handleStdoutLine(line); - }); - - const stderr = NodeReadline.createInterface({ input: this.child.stderr }); - stderr.on("line", (line) => { - NodeProcess.stdout.write(`[stderr] ${line}\n`); - }); - } - - write(message: JsonRpcMessage) { - if (this.closed) { - fail("ACP process is already closed."); - } - const payload = JSON.stringify({ - jsonrpc: "2.0", - headers: [], - ...message, - }); - NodeProcess.stdout.write(`>>> ${payload}\n`); - this.child.stdin.write(`${payload}\n`); - } - - async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) { - const id = this.nextId++; - - const responsePromise = new Promise((resolve, reject) => { - // @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script request timeout. - const timeout = NodeTimers.setTimeout(() => { - this.pending.delete(id); - reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`)); - }, timeoutMs); - - this.pending.set(id, { - method, - resolve: (value) => { - NodeTimers.clearTimeout(timeout); - resolve(value); - }, - reject: (error) => { - NodeTimers.clearTimeout(timeout); - reject(error); - }, - }); - }); - - this.write({ - id, - method, - params, - }); - - return responsePromise; - } - - notify(method: string, params: JsonValue) { - this.write({ - method, - params, - }); - } - - respond(id: JsonRpcId, result: JsonValue) { - this.write({ - id, - result, - }); - } - - respondError(id: JsonRpcId, code: number, message: string) { - this.write({ - id, - error: { - code, - message, - }, - }); - } - - async handleStdoutLine(line: string) { - if (line.trim().length === 0) { - return; - } - - NodeProcess.stdout.write(`<<< ${line}\n`); - - let message: JsonRpcMessage; - try { - message = JSON.parse(line) as JsonRpcMessage; - } catch (error) { - NodeProcess.stdout.write(`[parse-error] ${(error as Error).message}\n`); - return; - } - - if (typeof message.id !== "undefined" && !message.method) { - const pending = this.pending.get(message.id); - if (!pending) { - return; - } - this.pending.delete(message.id); - if (typeof message.error !== "undefined") { - pending.reject( - new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`), - ); - return; - } - pending.resolve(message.result); - return; - } - - if (message.method === "session/request_permission" && typeof message.id !== "undefined") { - this.respond(message.id, { - outcome: { - outcome: "selected", - optionId: "allow", - }, - }); - return; - } - - if (typeof message.id !== "undefined" && message.id !== "") { - this.respondError( - message.id, - -32601, - `Unhandled server request: ${message.method ?? "unknown"}`, - ); - } - } - - async close() { - if (this.closed) { - return; - } - this.child.kill("SIGTERM"); - await sleep(250); - if (!this.closed) { - this.child.kill("SIGKILL"); - } - } -} - -async function setSelectOptionIfAdvertised( - rpc: JsonRpcChild, - sessionId: string, - configOptions: SessionConfigOption[], - predicate: (option: SessionConfigOption) => boolean, - value: string, - label: string, -) { - if (value.length === 0) { - return configOptions; - } - - const option = findConfigOption(configOptions, predicate); - const values = flattenSelectValues(option); - if (!option || !values.includes(value)) { - logSection(`SKIP_${label}`, { - requestedValue: value, - availableValues: values, - }); - return configOptions; - } - - const response = (await rpc.request("session/set_config_option", { - sessionId, - configId: option.id, - value, - })) as SetConfigResult | null | undefined; - - logSection(`SET_${label}_RESPONSE`, response); - return response?.configOptions ?? configOptions; -} - -async function main() { - const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd); - - try { - const initializeResponse = await rpc.request("initialize", { - protocolVersion: 1, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - _meta: { - parameterizedModelPicker: true, - }, - }, - clientInfo: { - name: "cursor-acp-model-mismatch-probe", - version: "0.0.0", - }, - }); - logSection("INITIALIZE_RESPONSE", initializeResponse); - - const authenticateResponse = await rpc.request("authenticate", { - methodId: "cursor_login", - }); - logSection("AUTHENTICATE_RESPONSE", authenticateResponse); - - const sessionResponse = (await rpc.request("session/new", { - cwd: targetCwd, - mcpServers: [], - })) as SessionNewResult; - logSection("SESSION_NEW_RESPONSE", sessionResponse); - - const sessionId = asString(sessionResponse.sessionId); - if (!sessionId) { - fail("session/new did not return a sessionId."); - } - - let configOptions = sessionResponse.configOptions ?? []; - const modelConfig = findConfigOption(configOptions, (option) => option.category === "model"); - const advertisedModels = flattenSelectValues(modelConfig); - logSection("ADVERTISED_MODEL_VALUES", advertisedModels); - - if (!modelConfig || modelConfig.type !== "select") { - fail("Cursor ACP did not expose a select-type model config option."); - } - - if (!advertisedModels.includes(targetModel)) { - fail( - `Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`, - ); - } - - const setModelResponse = (await rpc.request("session/set_config_option", { - sessionId, - configId: modelConfig.id, - value: targetModel, - })) as SetConfigResult | null | undefined; - logSection("SET_MODEL_RESPONSE", setModelResponse); - - configOptions = setModelResponse?.configOptions ?? configOptions; - - configOptions = await setSelectOptionIfAdvertised( - rpc, - sessionId, - configOptions, - (option) => option.category === "thought_level", - targetReasoning, - "REASONING", - ); - - configOptions = await setSelectOptionIfAdvertised( - rpc, - sessionId, - configOptions, - (option) => option.category === "model_config" && matchesKeyword(option, "context"), - targetContext, - "CONTEXT", - ); - - configOptions = await setSelectOptionIfAdvertised( - rpc, - sessionId, - configOptions, - (option) => option.category === "model_config" && matchesKeyword(option, "fast"), - targetFast, - "FAST", - ); - - const promptResponse = await rpc.request("session/prompt", { - sessionId, - prompt: [ - { - type: "text", - text: promptText, - }, - ], - }); - logSection("PROMPT_RESPONSE", promptResponse); - - await sleep(promptWaitMs); - rpc.notify("session/cancel", { sessionId }); - } finally { - await rpc.close(); - } -} - -void main().catch((error: unknown) => { - NodeProcess.stderr.write( - `${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`, - ); - process.exitCode = 1; -}); diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts index c95f571c57..bda1e0d909 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts @@ -3,7 +3,6 @@ import type { AgentOptions, InteractionUpdate, McpServerConfig, - ModelSelection as CursorSdkModelSelection, RunResult, SDKUserMessage, ToolCall, @@ -42,7 +41,7 @@ import * as Stream from "effect/Stream"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; -import { cursorSdkParameterId } from "../../provider/cursorSdkModel.ts"; +import { cursorSdkModelSelection } from "../../provider/cursorSdkModel.ts"; import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts"; import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts"; import { makeProviderFailure } from "../ProviderFailure.ts"; @@ -88,6 +87,7 @@ import { } from "./CursorAgentSdk.ts"; export { CURSOR_PROVIDER } from "./CursorAgentSdk.ts"; +export { cursorSdkModelSelection } from "../../provider/cursorSdkModel.ts"; export const CURSOR_DRIVER_KIND = CURSOR_PROVIDER; export const CURSOR_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CURSOR_DRIVER_KIND); @@ -211,20 +211,6 @@ export function cursorRuntimeAgentPolicy( }; } -export function cursorSdkModelSelection(modelSelection: ModelSelection): CursorSdkModelSelection { - return { - id: modelSelection.model === "auto" ? "default" : modelSelection.model, - ...(modelSelection.options === undefined || modelSelection.options.length === 0 - ? {} - : { - params: modelSelection.options.map((option) => ({ - id: cursorSdkParameterId(option.id), - value: String(option.value), - })), - }), - }; -} - export function cursorMcpServers(threadId: ThreadId): Record | undefined { const session = McpProviderSession.readMcpProviderSession(threadId); if (session === undefined) { @@ -2488,14 +2474,6 @@ export const CursorAdapterV2Driver: ProviderAdapterDriver< const idAllocator = yield* IdAllocatorV2; const runner = yield* CursorAgentSdkRunner; const serverConfig = yield* ServerConfig; - if (input.config.apiEndpoint.length > 0) { - yield* Effect.logWarning( - "Cursor V2 uses the official SDK, which does not expose an API endpoint override.", - { - instanceId: input.instanceId, - }, - ); - } return makeCursorAdapterV2({ instanceId: input.instanceId, settings: { diff --git a/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts b/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts index 56abf680dd..75e0325c08 100644 --- a/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts +++ b/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts @@ -26,9 +26,10 @@ import { ServerSettingsService } from "../serverSettings.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import { OrchestratorV2 } from "./Orchestrator.ts"; +import { runDaemonWithOptions as runEffectWorkerDaemonWithOptions } from "./EffectWorker.ts"; import { OrchestrationV2LayerLive } from "./runtimeLayer.ts"; import { layer as mcpSessionRegistryTestLayer } from "../mcp/McpSessionRegistry.testkit.ts"; -import { CURSOR_MODEL_SELECTION } from "./testkit/fixtures/shared.ts"; +import { CURSOR_MODEL_SELECTION, SUBAGENT_PROMPT } from "./testkit/fixtures/shared.ts"; const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-cursor-v2-live-", @@ -96,6 +97,7 @@ describe.runIf(process.env.T3_CURSOR_LIVE_ORCHESTRATOR === "1")( "forks through portable context using real Cursor agents", () => Effect.gen(function* () { + yield* runEffectWorkerDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped); const orchestrator = yield* OrchestratorV2; const projectId = ProjectId.make("project:cursor-live-portable-fork"); const sourceThreadId = ThreadId.make("thread:cursor-live-portable-fork:source"); @@ -114,7 +116,7 @@ describe.runIf(process.env.T3_CURSOR_LIVE_ORCHESTRATOR === "1")( runtimeMode: "full-access", interactionMode: "default", branch: null, - worktreePath: null, + worktreePath: process.cwd(), }); yield* orchestrator.dispatch({ type: "message.dispatch", @@ -187,5 +189,80 @@ describe.runIf(process.env.T3_CURSOR_LIVE_ORCHESTRATOR === "1")( }).pipe(Effect.provide(liveLayer), Effect.scoped), 360_000, ); + + it.live( + "spawns native subagents with child thread lineage", + () => + Effect.gen(function* () { + yield* runEffectWorkerDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped); + const orchestrator = yield* OrchestratorV2; + const projectId = ProjectId.make("project:cursor-live-subagent-lineage"); + const sourceThreadId = ThreadId.make("thread:cursor-live-subagent-lineage"); + + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:cursor-live-subagent-lineage:create"), + threadId: sourceThreadId, + projectId, + title: "Cursor live subagent lineage", + modelSelection: CURSOR_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:cursor-live-subagent-lineage:message"), + threadId: sourceThreadId, + messageId: MessageId.make("message:cursor-live-subagent-lineage"), + text: `${SUBAGENT_PROMPT}. Do not edit files. After both subagents finish, summarize each result briefly.`, + attachments: [], + modelSelection: CURSOR_MODEL_SELECTION, + dispatchMode: { type: "start_immediately" }, + }); + + const parentProjection = yield* waitForIdle(sourceThreadId); + yield* Console.log( + `Cursor live subagent lineage completed with ${parentProjection.subagents.length} subagents.`, + ); + + assert.deepEqual( + parentProjection.runs.map((run) => [run.providerInstanceId, run.status]), + [["cursor", "completed"]], + ); + assert.isAtLeast(parentProjection.subagents.length, 1); + + for (const subagent of parentProjection.subagents) { + assert.equal(subagent.origin, "provider_native"); + assert.equal(subagent.driver, "cursor"); + assert.equal(subagent.status, "completed"); + assert.isNotNull(subagent.childThreadId); + assert.isNotNull(subagent.result); + + if (subagent.childThreadId === null) { + throw new Error(`Cursor live subagent ${subagent.id} is missing a child thread.`); + } + + const childProjection = yield* orchestrator.getThreadProjection(subagent.childThreadId); + assert.equal(childProjection.thread.lineage.parentThreadId, parentProjection.thread.id); + assert.equal(childProjection.thread.lineage.relationshipToParent, "subagent"); + assert.equal( + childProjection.thread.lineage.rootThreadId, + parentProjection.thread.lineage.rootThreadId, + ); + assert.lengthOf(childProjection.runs, 0); + assert.isTrue( + childProjection.messages.some((message) => message.role === "assistant"), + `child thread ${subagent.childThreadId} should contain the subagent response`, + ); + } + }).pipe(Effect.provide(liveLayer), Effect.scoped), + 360_000, + ); }, ); diff --git a/apps/server/src/provider/Drivers/CursorDriver.ts b/apps/server/src/provider/Drivers/CursorDriver.ts index 0796672243..579e151810 100644 --- a/apps/server/src/provider/Drivers/CursorDriver.ts +++ b/apps/server/src/provider/Drivers/CursorDriver.ts @@ -1,24 +1,16 @@ /** * CursorDriver — `ProviderDriver` for the Cursor Agent SDK runtime. * - * Provider status, model discovery, and orchestration use the official Cursor - * SDK and require CURSOR_API_KEY in the provider instance environment. - * - * Text generation is supported via the ACP runtime — `makeCursorTextGeneration` - * drives `runtime.prompt` with a structured-output schema and collects the - * agent's `agent_message_chunk` stream into a single JSON blob. + * Provider status, model discovery, orchestration, and text generation use the + * official Cursor SDK and require CURSOR_API_KEY in the provider instance + * environment. * * @module provider/Drivers/CursorDriver */ import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; import * as Duration from "effect/Duration"; -import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; -import { HttpClient } from "effect/unstable/http"; -import { ChildProcessSpawner } from "effect/unstable/process"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; @@ -31,7 +23,6 @@ import { ProviderDriverError } from "../Errors.ts"; import { buildInitialCursorProviderSnapshot, checkCursorProviderStatus, - enrichCursorSnapshot, } from "../Layers/CursorProvider.ts"; import { CursorSdkCatalogLive } from "../Layers/CursorSdkCatalog.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; @@ -42,11 +33,7 @@ import { } from "../ProviderDriver.ts"; import type { ServerProviderDraft } from "../providerSnapshot.ts"; import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts"; -import { - makeProviderMaintenanceCapabilities, - makeStaticProviderMaintenanceResolver, - resolveProviderMaintenanceCapabilitiesEffect, -} from "../providerMaintenance.ts"; +import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts"; import { haveProviderSnapshotSettingsChanged, makeProviderSnapshotSettingsSource, @@ -56,25 +43,12 @@ const decodeCursorSettings = Schema.decodeSync(CursorSettings); const DRIVER_KIND = ProviderDriverKind.make("cursor"); const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5); -const UPDATE = makeStaticProviderMaintenanceResolver( - makeProviderMaintenanceCapabilities({ - provider: DRIVER_KIND, - packageName: null, - updateExecutable: "agent", - updateArgs: ["update"], - updateLockKey: "cursor-agent", - }), -); +const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({ + provider: DRIVER_KIND, + packageName: null, +}); -export type CursorDriverEnv = - | CursorAdapterV2DriverEnv - | ChildProcessSpawner.ChildProcessSpawner - | Crypto.Crypto - | FileSystem.FileSystem - | HttpClient.HttpClient - | Path.Path - | ServerConfig - | ServerSettingsService; +export type CursorDriverEnv = CursorAdapterV2DriverEnv | ServerConfig | ServerSettingsService; const withInstanceIdentity = (input: { @@ -102,7 +76,6 @@ export const CursorDriver: ProviderDriver = { defaultConfig: (): CursorSettings => decodeCursorSettings({}), create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => Effect.gen(function* () { - const httpClient = yield* HttpClient.HttpClient; const serverSettings = yield* ServerSettingsService; const processEnv = mergeProviderInstanceEnvironment(environment); const continuationIdentity = defaultProviderContinuationIdentity({ @@ -116,10 +89,6 @@ export const CursorDriver: ProviderDriver = { continuationGroupKey: continuationIdentity.continuationKey, }); const effectiveConfig = { ...config, enabled } satisfies CursorSettings; - const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, { - binaryPath: effectiveConfig.binaryPath, - env: processEnv, - }); const orchestrationAdapter = yield* CursorAdapterV2Driver.create({ instanceId, @@ -148,7 +117,7 @@ export const CursorDriver: ProviderDriver = { const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings); const snapshot = yield* makeManagedServerProvider>({ - maintenanceCapabilities, + maintenanceCapabilities: MAINTENANCE_CAPABILITIES, getSettings: snapshotSettings.getSettings, streamSettings: snapshotSettings.streamSettings, haveSettingsChanged: haveProviderSnapshotSettingsChanged, @@ -157,16 +126,6 @@ export const CursorDriver: ProviderDriver = { checkProvider, // Model catalog and capabilities come from Cursor's SDK catalog during // provider checks. - enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) => - enrichCursorSnapshot({ - settings: settings.provider, - snapshot: currentSnapshot, - maintenanceCapabilities, - enableProviderUpdateChecks: settings.enableProviderUpdateChecks, - publishSnapshot, - stampIdentity, - httpClient, - }), refreshInterval: SNAPSHOT_REFRESH_INTERVAL, }).pipe( Effect.mapError( diff --git a/apps/server/src/provider/Layers/CursorProvider.test.ts b/apps/server/src/provider/Layers/CursorProvider.test.ts index 9de309b549..3c591f6f06 100644 --- a/apps/server/src/provider/Layers/CursorProvider.test.ts +++ b/apps/server/src/provider/Layers/CursorProvider.test.ts @@ -1,37 +1,22 @@ -import * as NodeOS from "node:os"; - import type { SDKModel } from "@cursor/sdk"; import { describe, expect, it } from "@effect/vitest"; -import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; -import * as Path from "effect/Path"; -import type * as EffectAcpSchema from "effect-acp/schema"; +import * as Schema from "effect/Schema"; import type { CursorSettings } from "@t3tools/contracts"; +import { CursorSettings as CursorSettingsSchema } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import { - buildCursorProviderSnapshot, - buildCursorCapabilitiesFromConfigOptions, buildCursorCapabilitiesFromSdkModel, buildCursorDiscoveredModelsFromSdk, + buildCursorProviderSnapshot, + buildInitialCursorProviderSnapshot, checkCursorProviderStatus, - discoverCursorModelsViaAcp, getCursorFallbackModels, - getCursorParameterizedModelPickerUnsupportedMessage, - parseCursorAboutOutput, - parseCursorCliConfigChannel, - parseCursorVersionDate, - resolveCursorAcpBaseModelId, - resolveCursorAcpConfigUpdates, } from "./CursorProvider.ts"; import { CursorSdkCatalogError, makeCursorSdkCatalogTestLayer } from "./CursorSdkCatalog.ts"; -const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () { - const path = yield* Path.Path; - return yield* path.fromFileUrl(new URL("../../../scripts/acp-mock-agent.ts", import.meta.url)); -}); +const decodeCursorSettings = Schema.decodeSync(CursorSettingsSchema); function selectDescriptor( id: string, @@ -58,249 +43,10 @@ function booleanDescriptor(id: string, label: string, currentValue?: boolean) { }; } -const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* ( - extraEnv?: Record, -) { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const mockAgentPath = yield* resolveMockAgentPath(); - const dir = yield* fileSystem.makeTempDirectory({ - directory: NodeOS.tmpdir(), - prefix: "cursor-provider-mock-", - }); - const wrapperPath = path.join(dir, "fake-agent.sh"); - const mockAgentCommand = ["node", mockAgentPath].map((arg) => JSON.stringify(arg)).join(" "); - const envExports = Object.entries(extraEnv ?? {}) - .map(([key, value]) => `export ${key}=${JSON.stringify(value)}`) - .join("\n"); - const script = `#!/bin/sh -${envExports} -exec ${mockAgentCommand} "$@" -`; - yield* fileSystem.writeFileString(wrapperPath, script); - yield* fileSystem.chmod(wrapperPath, 0o755); - return wrapperPath; -}); - -const makeMockAgentWithAboutWrapper = Effect.fn("makeMockAgentWithAboutWrapper")(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const mockAgentPath = yield* resolveMockAgentPath(); - const dir = yield* fileSystem.makeTempDirectory({ - directory: NodeOS.tmpdir(), - prefix: "cursor-provider-about-mock-", - }); - const wrapperPath = path.join(dir, "fake-agent.sh"); - const mockAgentCommand = ["node", mockAgentPath].map((arg) => JSON.stringify(arg)).join(" "); - const script = `#!/bin/sh -if [ "$1" = "about" ]; then - printf 'CLI Version 2026.04.09-f2b0fcd\\n' - printf 'User Email cursor@example.com\\n' - exit 0 -fi -exec ${mockAgentCommand} "$@" -`; - yield* fileSystem.writeFileString(wrapperPath, script); - yield* fileSystem.chmod(wrapperPath, 0o755); - return wrapperPath; -}); - -const waitForFileContent = Effect.fn("waitForFileContent")(function* ( - filePath: string, - attempts = 40, -) { - const fileSystem = yield* FileSystem.FileSystem; - for (let attempt = 0; attempt < attempts; attempt += 1) { - const content = yield* fileSystem - .readFileString(filePath) - .pipe(Effect.catch(() => Effect.void)); - if (content !== undefined) { - if (content.trim().length > 0) { - return content; - } - } - yield* Effect.sleep("50 millis"); - } - return yield* Effect.die(`Timed out waiting for file content at ${filePath}`); -}); - -const makeProviderStatusEnvFixture = Effect.fn("makeProviderStatusEnvFixture")(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const tempDir = yield* fileSystem.makeTempDirectory({ - directory: NodeOS.tmpdir(), - prefix: "cursor-provider-status-env-", - }); - return { - requestLogPath: path.join(tempDir, "requests.ndjson"), - wrapperPath: yield* makeMockAgentWithAboutWrapper(), - }; -}); - -const makeExitLogFixture = Effect.fn("makeExitLogFixture")(function* (prefix: string) { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const tempDir = yield* fileSystem.makeTempDirectory({ - directory: NodeOS.tmpdir(), - prefix, - }); - const exitLogPath = path.join(tempDir, "exit.log"); - return { - exitLogPath, - wrapperPath: yield* makeMockAgentWrapper({ - T3_ACP_EXIT_LOG_PATH: exitLogPath, - }), - }; -}); - -const parameterizedGpt54ConfigOptions = [ - { - type: "select", - currentValue: "gpt-5.4-medium-fast", - options: [{ name: "GPT-5.4", value: "gpt-5.4-medium-fast" }], - category: "model", - id: "model", - name: "Model", - }, - { - type: "select", - currentValue: "medium", - options: [ - { name: "None", value: "none" }, - { name: "Low", value: "low" }, - { name: "Medium", value: "medium" }, - { name: "High", value: "high" }, - { name: "Extra High", value: "extra-high" }, - ], - category: "thought_level", - id: "reasoning", - name: "Reasoning", - }, - { - type: "select", - currentValue: "272k", - options: [ - { name: "272K", value: "272k" }, - { name: "1M", value: "1m" }, - ], - category: "model_config", - id: "context", - name: "Context", - }, - { - type: "select", - currentValue: "false", - options: [ - { name: "Off", value: "false" }, - { name: "Fast", value: "true" }, - ], - category: "model_config", - id: "fast", - name: "Fast", - }, -] satisfies ReadonlyArray; - -const parameterizedClaudeConfigOptions = [ - { - type: "select", - currentValue: "claude-4.6-opus-high-thinking", - options: [{ name: "Opus 4.6", value: "claude-4.6-opus-high-thinking" }], - category: "model", - id: "model", - name: "Model", - }, - { - type: "select", - currentValue: "high", - options: [ - { name: "Low", value: "low" }, - { name: "Medium", value: "medium" }, - { name: "High", value: "high" }, - ], - category: "thought_level", - id: "reasoning", - name: "Reasoning", - }, - { - type: "boolean", - currentValue: true, - category: "model_config", - id: "thinking", - name: "Thinking", - }, -] satisfies ReadonlyArray; - -const parameterizedClaudeModelOptionConfigOptions = [ - { - type: "select", - currentValue: "claude-opus-4-6", - options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }], - category: "model", - id: "model", - name: "Model", - }, - { - type: "select", - currentValue: "high", - options: [ - { name: "Low", value: "low" }, - { name: "Medium", value: "medium" }, - { name: "High", value: "high" }, - ], - category: "thought_level", - id: "reasoning", - name: "Reasoning", - }, - { - type: "select", - currentValue: "max", - options: [ - { name: "Low", value: "low" }, - { name: "Medium", value: "medium" }, - { name: "High", value: "high" }, - { name: "Max", value: "max" }, - ], - category: "model_option", - id: "effort", - name: "Effort", - }, - { - type: "select", - currentValue: "true", - options: [ - { name: "Off", value: "false" }, - { name: "Fast", value: "true" }, - ], - category: "model_config", - id: "fast", - name: "Fast", - }, - { - type: "select", - currentValue: "true", - options: [ - { name: "Off", value: "false" }, - { name: ":icon-brain:", value: "true" }, - ], - category: "model_config", - id: "thinking", - name: "Thinking", - }, -] satisfies ReadonlyArray; - -const baseCursorSettings: CursorSettings = { +const baseCursorSettings: CursorSettings = decodeCursorSettings({ enabled: true, - binaryPath: "agent", - apiEndpoint: "", customModels: [], -}; -const cursorAcpDiscoveryFailedMessage = [ - "Cursor ACP model discovery failed.", - "Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.", - "See https://cursor.com/docs/cli/installation.", - "Check server logs for ACP details.", -].join(" "); -const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent"; +}); const sdkParameterizedModel = { id: "claude-opus-4-8", @@ -348,7 +94,7 @@ const sdkParameterizedModel = { } satisfies SDKModel; describe("getCursorFallbackModels", () => { - it("does not publish any built-in cursor models before ACP discovery", () => { + it("does not publish any built-in cursor models before SDK discovery", () => { expect( getCursorFallbackModels({ customModels: ["internal/cursor-model"], @@ -357,109 +103,38 @@ describe("getCursorFallbackModels", () => { }); }); +describe("buildInitialCursorProviderSnapshot", () => { + it.effect("uses SDK-specific pending status copy", () => + Effect.gen(function* () { + const provider = yield* buildInitialCursorProviderSnapshot(baseCursorSettings); + + expect(provider).toMatchObject({ + status: "warning", + message: "Checking Cursor SDK availability...", + }); + }), + ); +}); + describe("buildCursorProviderSnapshot", () => { - it("downgrades ready status to warning when ACP model discovery times out", () => { + it("downgrades ready status to warning when SDK model discovery returns no models", () => { expect( buildCursorProviderSnapshot({ checkedAt: "2026-01-01T00:00:00.000Z", cursorSettings: baseCursorSettings, parsed: { - version: "2026.04.09-f2b0fcd", + version: null, status: "ready", - auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" }, + auth: { status: "authenticated", type: "api-key", label: "Cursor API key" }, }, - discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.", + discoveryWarning: "Cursor SDK model discovery returned no built-in models.", }), ).toMatchObject({ status: "warning", - message: "Cursor ACP model discovery timed out after 15000ms.", + message: "Cursor SDK model discovery returned no built-in models.", models: [], }); }); - - it("preserves provider error state while appending discovery warnings", () => { - expect( - buildCursorProviderSnapshot({ - checkedAt: "2026-01-01T00:00:00.000Z", - cursorSettings: { - ...baseCursorSettings, - customModels: ["claude-sonnet-4-6"], - }, - parsed: { - version: "2026.04.09-f2b0fcd", - status: "error", - auth: { status: "unauthenticated" }, - message: "Cursor Agent is not authenticated. Run `agent login` and try again.", - }, - discoveryWarning: cursorAcpDiscoveryFailedMessage, - }), - ).toMatchObject({ - status: "error", - message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`, - models: [ - { - slug: "claude-sonnet-4-6", - isCustom: true, - }, - ], - }); - }); -}); - -describe("buildCursorCapabilitiesFromConfigOptions", () => { - it("derives model capabilities from parameterized Cursor ACP config options", () => { - expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual( - createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoning", "Reasoning", [ - { id: "low", label: "Low" }, - { id: "medium", label: "Medium", isDefault: true }, - { id: "high", label: "High" }, - { id: "xhigh", label: "Extra High" }, - ]), - selectDescriptor("contextWindow", "Context", [ - { id: "272k", label: "272K", isDefault: true }, - { id: "1m", label: "1M" }, - ]), - booleanDescriptor("fastMode", "Fast", false), - ], - }), - ); - }); - - it("detects boolean thinking toggles from model_config options", () => { - expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual( - createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoning", "Reasoning", [ - { id: "low", label: "Low" }, - { id: "medium", label: "Medium" }, - { id: "high", label: "High", isDefault: true }, - ]), - booleanDescriptor("thinking", "Thinking", true), - ], - }), - ); - }); - - it("prefers the newer model_option effort control over legacy thought_level", () => { - expect( - buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions), - ).toEqual( - createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoning", "Effort", [ - { id: "low", label: "Low" }, - { id: "medium", label: "Medium" }, - { id: "high", label: "High" }, - { id: "max", label: "Max", isDefault: true }, - ]), - booleanDescriptor("fastMode", "Fast", true), - booleanDescriptor("thinking", "Thinking", true), - ], - }), - ); - }); }); describe("Cursor SDK model discovery", () => { @@ -506,26 +181,22 @@ describe("checkCursorProviderStatus", () => { checkCursorProviderStatus( { ...baseCursorSettings, - binaryPath: "cursor-cli-must-not-be-invoked", customModels: ["internal/cursor-model"], }, { CURSOR_API_KEY: "test-cursor-key" }, ).pipe( Effect.provide( - Layer.mergeAll( - makeCursorSdkCatalogTestLayer((apiKey) => { - expect(apiKey).toBe("test-cursor-key"); - return Effect.succeed({ - user: { - apiKeyName: "test-key", - userEmail: "cursor@example.com", - createdAt: "2026-01-01T00:00:00.000Z", - }, - models: [sdkParameterizedModel], - }); - }), - NodeServices.layer, - ), + makeCursorSdkCatalogTestLayer((apiKey) => { + expect(apiKey).toBe("test-cursor-key"); + return Effect.succeed({ + user: { + apiKeyName: "test-key", + userEmail: "cursor@example.com", + createdAt: "2026-01-01T00:00:00.000Z", + }, + models: [sdkParameterizedModel], + }); + }), ), ), ); @@ -545,22 +216,19 @@ describe("checkCursorProviderStatus", () => { }); }); - it("surfaces SDK authentication failures without invoking the CLI", async () => { + it("surfaces SDK authentication failures", async () => { const provider = await Effect.runPromise( checkCursorProviderStatus(baseCursorSettings, { CURSOR_API_KEY: "invalid-test-key", }).pipe( Effect.provide( - Layer.mergeAll( - makeCursorSdkCatalogTestLayer(() => - Effect.fail( - new CursorSdkCatalogError({ - authenticationFailure: true, - cause: new Error("unauthorized"), - }), - ), + makeCursorSdkCatalogTestLayer(() => + Effect.fail( + new CursorSdkCatalogError({ + authenticationFailure: true, + cause: new Error("unauthorized"), + }), ), - NodeServices.layer, ), ), ), @@ -573,20 +241,12 @@ describe("checkCursorProviderStatus", () => { }); }); - it("requires a Cursor API key without probing the legacy CLI fallback", async () => { + it("requires a Cursor API key without probing any external Cursor binary", async () => { const provider = await Effect.runPromise( - checkCursorProviderStatus({ - enabled: true, - binaryPath: missingCursorBinaryPath, - apiEndpoint: "", - customModels: [], - }).pipe( + checkCursorProviderStatus(baseCursorSettings).pipe( Effect.provide( - Layer.mergeAll( - makeCursorSdkCatalogTestLayer(() => - Effect.die("SDK catalog must not be used without CURSOR_API_KEY"), - ), - NodeServices.layer, + makeCursorSdkCatalogTestLayer(() => + Effect.die("SDK catalog must not be used without CURSOR_API_KEY"), ), ), ), @@ -600,233 +260,3 @@ describe("checkCursorProviderStatus", () => { }); }); }); - -describe("discoverCursorModelsViaAcp", () => { - it.effect("passes the injected environment to ACP model discovery", () => - Effect.gen(function* () { - const { requestLogPath, wrapperPath } = yield* makeProviderStatusEnvFixture(); - const models = yield* discoverCursorModelsViaAcp( - { - enabled: true, - binaryPath: wrapperPath, - apiEndpoint: "", - customModels: [], - }, - { - ...process.env, - T3_ACP_REQUEST_LOG_PATH: requestLogPath, - }, - ); - - expect(models.map((model) => model.slug)).toEqual([ - "default", - "composer-2", - "gpt-5.4", - "claude-opus-4-6", - ]); - yield* waitForFileContent(requestLogPath).pipe( - Effect.tap((content) => Effect.sync(() => expect(content).toContain("initialize"))), - ); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect("keeps the ACP probe runtime alive long enough to discover models", () => - Effect.gen(function* () { - const wrapperPath = yield* makeMockAgentWrapper(); - const models = yield* discoverCursorModelsViaAcp({ - enabled: true, - binaryPath: wrapperPath, - apiEndpoint: "", - customModels: [], - }); - - expect(models.map((model) => model.slug)).toEqual([ - "default", - "composer-2", - "gpt-5.4", - "claude-opus-4-6", - ]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); - - it.effect("closes the ACP probe runtime after discovery completes", () => - Effect.gen(function* () { - const { exitLogPath, wrapperPath } = yield* makeExitLogFixture("cursor-provider-exit-log-"); - - yield* discoverCursorModelsViaAcp({ - enabled: true, - binaryPath: wrapperPath, - apiEndpoint: "", - customModels: [], - }); - - const exitLog = yield* waitForFileContent(exitLogPath); - expect(exitLog).toContain("SIGTERM"); - }).pipe(Effect.provide(NodeServices.layer)), - ); -}); - -describe("parseCursorAboutOutput", () => { - it("parses json about output and forwards subscription metadata", () => { - expect( - parseCursorAboutOutput({ - code: 0, - stdout: JSON.stringify({ - cliVersion: "2026.04.09-f2b0fcd", - subscriptionTier: "Team", - userEmail: "jmarminge@gmail.com", - }), - stderr: "", - }), - ).toEqual({ - version: "2026.04.09-f2b0fcd", - status: "ready", - auth: { - status: "authenticated", - email: "jmarminge@gmail.com", - type: "Team", - label: "Cursor Team Subscription", - }, - }); - }); - - it("treats json about output with a logged-out email as unauthenticated", () => { - expect( - parseCursorAboutOutput({ - code: 0, - stdout: JSON.stringify({ - cliVersion: "2026.04.09-f2b0fcd", - subscriptionTier: "Team", - userEmail: "Not logged in", - }), - stderr: "", - }), - ).toEqual({ - version: "2026.04.09-f2b0fcd", - status: "error", - auth: { - status: "unauthenticated", - }, - message: "Cursor Agent is not authenticated. Run `agent login` and try again.", - }); - }); - - it("treats json about output with a null email as unauthenticated", () => { - expect( - parseCursorAboutOutput({ - code: 0, - stdout: JSON.stringify({ - cliVersion: "2026.04.09-f2b0fcd", - subscriptionTier: null, - userEmail: null, - }), - stderr: "", - }), - ).toEqual({ - version: "2026.04.09-f2b0fcd", - status: "error", - auth: { - status: "unauthenticated", - }, - message: "Cursor Agent is not authenticated. Run `agent login` and try again.", - }); - }); -}); - -describe("Cursor parameterized model picker preview gating", () => { - it("parses Cursor CLI version dates from build versions", () => { - expect(parseCursorVersionDate("2026.04.08-c4e73a3")).toBe(20260408); - expect(parseCursorVersionDate("2026.04.09")).toBe(20260409); - expect(parseCursorVersionDate("not-a-version")).toBeUndefined(); - }); - - it("parses the Cursor CLI channel from cli-config.json", () => { - expect(parseCursorCliConfigChannel('{ "channel": "lab" }')).toBe("lab"); - expect(parseCursorCliConfigChannel('{ "channel": "stable" }')).toBe("stable"); - expect(parseCursorCliConfigChannel('{ "version": 1 }')).toBeUndefined(); - expect(parseCursorCliConfigChannel("not-json")).toBeUndefined(); - }); - - it("returns no warning when the preview requirements are met", () => { - expect( - getCursorParameterizedModelPickerUnsupportedMessage({ - version: "2026.04.08-c4e73a3", - channel: "lab", - }), - ).toBeUndefined(); - }); - - it("explains when the Cursor Agent version is too old", () => { - expect( - getCursorParameterizedModelPickerUnsupportedMessage({ - version: "2026.04.07-c4e73a3", - channel: "lab", - }), - ).toContain("too old"); - }); - - it("explains when the Cursor Agent channel is not lab", () => { - expect( - getCursorParameterizedModelPickerUnsupportedMessage({ - version: "2026.04.08-c4e73a3", - channel: "stable", - }), - ).toContain("lab channel"); - }); -}); - -describe("resolveCursorAcpBaseModelId", () => { - it("drops bracket traits without rewriting raw ACP model ids", () => { - expect(resolveCursorAcpBaseModelId("gpt-5.4[reasoning=medium,context=272k]")).toBe("gpt-5.4"); - expect(resolveCursorAcpBaseModelId("gpt-5.4-medium-fast")).toBe("gpt-5.4-medium-fast"); - expect(resolveCursorAcpBaseModelId("claude-4.6-opus-high-thinking")).toBe( - "claude-4.6-opus-high-thinking", - ); - expect(resolveCursorAcpBaseModelId("composer-2")).toBe("composer-2"); - expect(resolveCursorAcpBaseModelId("auto")).toBe("auto"); - }); -}); - -describe("resolveCursorAcpConfigUpdates", () => { - it("maps Cursor model options onto separate ACP config option updates", () => { - expect( - resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [ - { id: "reasoning", value: "xhigh" }, - { id: "fastMode", value: true }, - { id: "contextWindow", value: "1m" }, - ]), - ).toEqual([ - { configId: "reasoning", value: "extra-high" }, - { configId: "context", value: "1m" }, - { configId: "fast", value: "true" }, - ]); - }); - - it("maps boolean thinking toggles when the model exposes them separately", () => { - expect( - resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, [ - { id: "thinking", value: false }, - ]), - ).toEqual([{ configId: "thinking", value: false }]); - }); - - it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => { - expect( - resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [ - { id: "fastMode", value: false }, - ]), - ).toEqual([{ configId: "fast", value: "false" }]); - }); - - it("writes Cursor effort changes through the newer model_option config when available", () => { - expect( - resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, [ - { id: "reasoning", value: "max" }, - { id: "thinking", value: false }, - ]), - ).toEqual([ - { configId: "effort", value: "max" }, - { configId: "thinking", value: "false" }, - ]); - }); -}); diff --git a/apps/server/src/provider/Layers/CursorProvider.ts b/apps/server/src/provider/Layers/CursorProvider.ts index c5c6dc54f0..4170c09cec 100644 --- a/apps/server/src/provider/Layers/CursorProvider.ts +++ b/apps/server/src/provider/Layers/CursorProvider.ts @@ -3,49 +3,27 @@ import type { CursorSettings, ModelCapabilities, ProviderOptionDescriptor, - ProviderOptionSelection, - ServerProvider, ServerProviderAuth, ServerProviderModel, ServerProviderState, } from "@t3tools/contracts"; import { ProviderDriverKind } from "@t3tools/contracts"; -import type * as EffectAcpSchema from "effect-acp/schema"; -import { causeErrorTag } from "@t3tools/shared/observability"; +import { createModelCapabilities } from "@t3tools/shared/model"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; -import * as Schema from "effect/Schema"; -import { HttpClient } from "effect/unstable/http"; -import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; -import { - createModelCapabilities, - getProviderOptionBooleanSelectionValue, - getProviderOptionStringSelectionValue, -} from "@t3tools/shared/model"; +import { cursorSdkParameterPriority, cursorSdkProviderOptionId } from "../cursorSdkModel.ts"; import { buildBooleanOptionDescriptor, buildSelectOptionDescriptor, buildServerProvider, providerModelsFromSettings, - type CommandResult, type ServerProviderDraft, } from "../providerSnapshot.ts"; -import { - enrichProviderSnapshotWithVersionAdvisory, - type ProviderMaintenanceCapabilities, -} from "../providerMaintenance.ts"; -import { cursorSdkParameterPriority, cursorSdkProviderOptionId } from "../cursorSdkModel.ts"; -import * as AcpSessionRuntime from "../acp/AcpSessionRuntime.ts"; -import { CursorListAvailableModelsResponse } from "../acp/CursorAcpExtension.ts"; import { CursorSdkCatalog } from "./CursorSdkCatalog.ts"; -const decodeCursorListAvailableModelsResponse = Schema.decodeUnknownEffect( - CursorListAvailableModelsResponse, -); const PROVIDER = ProviderDriverKind.make("cursor"); const CURSOR_PRESENTATION = { displayName: "Cursor", @@ -57,12 +35,6 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ }); const CURSOR_SDK_CATALOG_TIMEOUT_MS = 15_000; -const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08; -export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = { - _meta: { - parameterizedModelPicker: true, - }, -} satisfies NonNullable; export function buildInitialCursorProviderSnapshot( cursorSettings: CursorSettings, @@ -97,275 +69,26 @@ export function buildInitialCursorProviderSnapshot( version: null, status: "warning", auth: { status: "unknown" }, - message: "Checking Cursor Agent availability...", + message: "Checking Cursor SDK availability...", }, }); }); } -interface CursorSessionSelectOption { - readonly value: string; - readonly name: string; -} - -interface CursorAcpDiscoveredModel { - readonly slug: string; - readonly name: string; - readonly capabilities: ModelCapabilities; -} - -function flattenSessionConfigSelectOptions( - configOption: EffectAcpSchema.SessionConfigOption | undefined, -): ReadonlyArray { - if (!configOption || configOption.type !== "select") { - return []; - } - return configOption.options.flatMap((entry) => - "value" in entry - ? [ - { - value: entry.value.trim(), - name: entry.name.trim(), - } satisfies CursorSessionSelectOption, - ] - : entry.options.map( - (option) => - ({ - value: option.value.trim(), - name: option.name.trim(), - }) satisfies CursorSessionSelectOption, - ), - ); -} - -function normalizeCursorReasoningValue(value: string | null | undefined): string | undefined { - const normalized = value?.trim().toLowerCase(); - switch (normalized) { - case "low": - case "medium": - case "high": - case "max": - return normalized; - case "xhigh": - case "extra-high": - case "extra high": - return "xhigh"; - default: - return undefined; - } -} - -function getCursorConfigOptionCategory(option: EffectAcpSchema.SessionConfigOption): string { - return option.category?.trim().toLowerCase() ?? ""; -} - -function isCursorEffortConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean { - const id = option.id.trim().toLowerCase(); - const name = option.name.trim().toLowerCase(); - return ( - id === "effort" || - id === "reasoning" || - name === "effort" || - name === "reasoning" || - name.includes("effort") || - name.includes("reasoning") - ); -} - -function findCursorEffortConfigOption( - configOptions: ReadonlyArray, -): EffectAcpSchema.SessionConfigOption | undefined { - const candidates = configOptions.filter( - (option) => option.type === "select" && isCursorEffortConfigOption(option), - ); - return ( - candidates.find((option) => getCursorConfigOptionCategory(option) === "model_option") ?? - candidates.find((option) => option.id.trim().toLowerCase() === "effort") ?? - candidates.find((option) => getCursorConfigOptionCategory(option) === "thought_level") ?? - candidates[0] - ); -} - -function isCursorContextConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean { - const id = option.id.trim().toLowerCase(); - const name = option.name.trim().toLowerCase(); - return id === "context" || id === "context_size" || name.includes("context"); -} - -function isCursorFastConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean { - const id = option.id.trim().toLowerCase(); - const name = option.name.trim().toLowerCase(); - return id === "fast" || name === "fast" || name.includes("fast mode"); -} - -function isCursorThinkingConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean { - const id = option.id.trim().toLowerCase(); - const name = option.name.trim().toLowerCase(); - return id === "thinking" || name.includes("thinking"); -} - -function isBooleanLikeConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean { - if (option.type === "boolean") { - return true; - } - if (option.type !== "select") { - return false; - } - const values = new Set( - flattenSessionConfigSelectOptions(option).map((entry) => entry.value.trim().toLowerCase()), - ); - return values.has("true") && values.has("false"); -} - -function getBooleanCurrentValue( - option: EffectAcpSchema.SessionConfigOption | undefined, -): boolean | undefined { - if (!option) { - return undefined; - } - if (option.type === "boolean") { - return option.currentValue; - } - if (option.type !== "select") { - return undefined; - } - const normalized = option.currentValue?.trim().toLowerCase(); - if (normalized === "true") { - return true; - } - if (normalized === "false") { - return false; - } - return undefined; -} - -export function buildCursorCapabilitiesFromConfigOptions( - configOptions: ReadonlyArray | null | undefined, -): ModelCapabilities { - if (!configOptions || configOptions.length === 0) { - return EMPTY_CAPABILITIES; - } - - const reasoningConfig = findCursorEffortConfigOption(configOptions); - const reasoningEffortLevels = - reasoningConfig?.type === "select" - ? flattenSessionConfigSelectOptions(reasoningConfig).flatMap((entry) => { - const normalizedValue = normalizeCursorReasoningValue(entry.value); - if (!normalizedValue) { - return []; - } - return [ - { - value: normalizedValue, - label: entry.name, - ...(normalizeCursorReasoningValue(reasoningConfig.currentValue) === normalizedValue - ? { isDefault: true } - : {}), - }, - ]; - }) - : []; - - const contextOption = configOptions.find( - (option) => option.category === "model_config" && isCursorContextConfigOption(option), - ); - const contextWindowOptions = - contextOption?.type === "select" - ? flattenSessionConfigSelectOptions(contextOption).map((entry) => { - if (contextOption.currentValue === entry.value) { - return { - value: entry.value, - label: entry.name, - isDefault: true, - }; - } - return { - value: entry.value, - label: entry.name, - }; - }) - : []; - - const fastOption = configOptions.find( - (option) => option.category === "model_config" && isCursorFastConfigOption(option), - ); - const thinkingOption = configOptions.find( - (option) => option.category === "model_config" && isCursorThinkingConfigOption(option), - ); - const fastCurrentValue = getBooleanCurrentValue(fastOption); - const thinkingCurrentValue = getBooleanCurrentValue(thinkingOption); - const optionDescriptors = [ - ...(reasoningEffortLevels.length > 0 - ? [ - buildSelectOptionDescriptor({ - id: "reasoning", - label: reasoningConfig?.name?.trim() || "Reasoning", - options: reasoningEffortLevels, - }), - ] - : []), - ...(contextWindowOptions.length > 0 - ? [ - buildSelectOptionDescriptor({ - id: "contextWindow", - label: contextOption?.name?.trim() || "Context Window", - options: contextWindowOptions, - }), - ] - : []), - ...(fastOption && isBooleanLikeConfigOption(fastOption) - ? [ - typeof fastCurrentValue === "boolean" - ? buildBooleanOptionDescriptor({ - id: "fastMode", - label: fastOption.name?.trim() || "Fast Mode", - currentValue: fastCurrentValue, - }) - : buildBooleanOptionDescriptor({ - id: "fastMode", - label: fastOption.name?.trim() || "Fast Mode", - }), - ] - : []), - ...(thinkingOption && isBooleanLikeConfigOption(thinkingOption) - ? [ - typeof thinkingCurrentValue === "boolean" - ? buildBooleanOptionDescriptor({ - id: "thinking", - label: thinkingOption.name?.trim() || "Thinking", - currentValue: thinkingCurrentValue, - }) - : buildBooleanOptionDescriptor({ - id: "thinking", - label: thinkingOption.name?.trim() || "Thinking", - }), - ] - : []), - ]; - - return createModelCapabilities({ - optionDescriptors, - }); -} - -function buildCursorDiscoveredModels( - discoveredModels: ReadonlyArray, +export function getCursorFallbackModels( + cursorSettings: Pick, ): ReadonlyArray { - const seen = new Set(); - return discoveredModels.flatMap((model) => { - if (!model.slug || seen.has(model.slug)) { - return []; + return providerModelsFromSettings([], PROVIDER, cursorSettings.customModels, EMPTY_CAPABILITIES); +} + +function toTitleCaseWords(value: string): string { + const parts: Array = []; + for (const part of value.split(/[\s_-]+/g)) { + if (part.length > 0) { + parts.push(part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()); } - seen.add(model.slug); - return [ - { - slug: model.slug, - name: model.name, - isCustom: false, - capabilities: model.capabilities, - } satisfies ServerProviderModel, - ]; - }); + } + return parts.join(" "); } function cursorSdkDefaultParameterValue(model: SDKModel, parameterId: string): string | undefined { @@ -474,222 +197,7 @@ function cursorSdkAuth(user: SDKUser): ServerProviderAuth { }; } -function buildCursorDiscoveredModelsFromAvailableModelsResponse( - response: typeof CursorListAvailableModelsResponse.Type, -): ReadonlyArray { - return buildCursorDiscoveredModels( - response.models.flatMap((model) => { - const slug = model.value.trim(); - const name = model.name.trim(); - if (!slug || !name) { - return []; - } - - return [ - { - slug, - name, - capabilities: buildCursorCapabilitiesFromConfigOptions(model.configOptions), - }, - ]; - }), - ); -} - -const makeCursorAcpProbeRuntime = ( - cursorSettings: CursorSettings, - environment?: NodeJS.ProcessEnv, -) => - Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const acpContext = yield* Layer.build( - AcpSessionRuntime.layer({ - spawn: { - command: cursorSettings.binaryPath, - args: [ - ...(cursorSettings.apiEndpoint ? (["-e", cursorSettings.apiEndpoint] as const) : []), - "acp", - ], - cwd: process.cwd(), - ...(environment ? { env: environment } : {}), - }, - cwd: process.cwd(), - clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" }, - authMethodId: "cursor_login", - clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES, - }).pipe(Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner))), - ); - return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( - Effect.provide(acpContext), - ); - }); - -const withCursorAcpProbeRuntime = ( - cursorSettings: CursorSettings, - useRuntime: (acp: AcpSessionRuntime.AcpSessionRuntime["Service"]) => Effect.Effect, - environment?: NodeJS.ProcessEnv, -) => - makeCursorAcpProbeRuntime(cursorSettings, environment).pipe( - Effect.flatMap(useRuntime), - Effect.scoped, - ); - -function normalizeCursorConfigOptionToken(value: string | null | undefined): string { - return ( - value - ?.trim() - .toLowerCase() - .replace(/[\s_-]+/g, "-") ?? "" - ); -} - -function findCursorSelectOptionValue( - configOption: EffectAcpSchema.SessionConfigOption | undefined, - matcher: (option: CursorSessionSelectOption) => boolean, -): string | undefined { - return flattenSessionConfigSelectOptions(configOption).find(matcher)?.value; -} - -function findCursorBooleanConfigValue( - configOption: EffectAcpSchema.SessionConfigOption | undefined, - requested: boolean, -): string | boolean | undefined { - if (!configOption) { - return undefined; - } - if (configOption.type === "boolean") { - return requested; - } - return findCursorSelectOptionValue( - configOption, - (option) => normalizeCursorConfigOptionToken(option.value) === String(requested), - ); -} - -export function resolveCursorAcpBaseModelId(model: string | null | undefined): string { - const trimmed = model?.trim(); - const base = trimmed && trimmed.length > 0 ? trimmed : "default"; - return base.includes("[") ? base.slice(0, base.indexOf("[")) : base; -} - -export function resolveCursorAcpConfigUpdates( - configOptions: ReadonlyArray | null | undefined, - selections: ReadonlyArray | null | undefined, -): ReadonlyArray<{ - readonly configId: string; - readonly value: string | boolean; -}> { - if (!configOptions || configOptions.length === 0) { - return []; - } - - const updates: Array<{ - readonly configId: string; - readonly value: string | boolean; - }> = []; - - const reasoningOption = findCursorEffortConfigOption(configOptions); - const requestedReasoning = normalizeCursorReasoningValue( - getProviderOptionStringSelectionValue(selections, "reasoning"), - ); - if (reasoningOption && requestedReasoning) { - const value = findCursorSelectOptionValue(reasoningOption, (option) => { - const normalizedValue = normalizeCursorReasoningValue(option.value); - const normalizedName = normalizeCursorReasoningValue(option.name); - return normalizedValue === requestedReasoning || normalizedName === requestedReasoning; - }); - if (value) { - updates.push({ configId: reasoningOption.id, value }); - } - } - - const contextOption = configOptions.find( - (option) => option.category === "model_config" && isCursorContextConfigOption(option), - ); - const requestedContextWindow = getProviderOptionStringSelectionValue(selections, "contextWindow"); - if (contextOption && requestedContextWindow) { - const value = findCursorSelectOptionValue( - contextOption, - (option) => - normalizeCursorConfigOptionToken(option.value) === - normalizeCursorConfigOptionToken(requestedContextWindow) || - normalizeCursorConfigOptionToken(option.name) === - normalizeCursorConfigOptionToken(requestedContextWindow), - ); - if (value) { - updates.push({ configId: contextOption.id, value }); - } - } - - const fastOption = configOptions.find( - (option) => option.category === "model_config" && isCursorFastConfigOption(option), - ); - const requestedFastMode = getProviderOptionBooleanSelectionValue(selections, "fastMode"); - if (fastOption && typeof requestedFastMode === "boolean") { - const value = findCursorBooleanConfigValue(fastOption, requestedFastMode); - if (value !== undefined) { - updates.push({ configId: fastOption.id, value }); - } - } - - const thinkingOption = configOptions.find( - (option) => option.category === "model_config" && isCursorThinkingConfigOption(option), - ); - const requestedThinking = getProviderOptionBooleanSelectionValue(selections, "thinking"); - if (thinkingOption && typeof requestedThinking === "boolean") { - const value = findCursorBooleanConfigValue(thinkingOption, requestedThinking); - if (value !== undefined) { - updates.push({ configId: thinkingOption.id, value }); - } - } - - return updates; -} - -const discoverCursorModelsViaListAvailableModels = ( - cursorSettings: CursorSettings, - environment?: NodeJS.ProcessEnv, -) => - withCursorAcpProbeRuntime( - cursorSettings, - (acp) => - Effect.gen(function* () { - yield* acp.start(); - const response = yield* acp.request("cursor/list_available_models", {}); - const decoded = yield* decodeCursorListAvailableModelsResponse(response); - return buildCursorDiscoveredModelsFromAvailableModelsResponse(decoded); - }), - environment, - ); - -export const discoverCursorModelsViaAcp = ( - cursorSettings: CursorSettings, - environment?: NodeJS.ProcessEnv, -) => discoverCursorModelsViaListAvailableModels(cursorSettings, environment); - -export function getCursorFallbackModels( - cursorSettings: Pick, -): ReadonlyArray { - return providerModelsFromSettings([], PROVIDER, cursorSettings.customModels, EMPTY_CAPABILITIES); -} - -/** Strip ANSI escape sequences so we can parse plain key-value lines. */ -function stripAnsi(text: string): string { - // eslint-disable-next-line no-control-regex - return text.replace(/\x1b\[[0-9;]*[A-Za-z]|\x1b\].*?\x07/g, ""); -} - -/** - * Extract a value from `agent about` key-value output. - * Lines look like: `CLI Version 2026.03.20-44cb435` - */ -function extractAboutField(plain: string, key: string): string | undefined { - const regex = new RegExp(`^${key}\\s{2,}(.+)$`, "mi"); - const match = regex.exec(plain); - return match?.[1]?.trim(); -} - -export interface CursorAboutResult { +interface CursorProviderProbeResult { readonly version: string | null; readonly status: Exclude; readonly auth: ServerProviderAuth; @@ -710,7 +218,7 @@ function joinProviderMessages(...messages: ReadonlyArray): s export function buildCursorProviderSnapshot(input: { readonly checkedAt: string; readonly cursorSettings: CursorSettings; - readonly parsed: CursorAboutResult; + readonly parsed: CursorProviderProbeResult; readonly discoveredModels?: ReadonlyArray; readonly discoveryWarning?: string; }): ServerProviderDraft { @@ -736,279 +244,6 @@ export function buildCursorProviderSnapshot(input: { }); } -interface CursorAboutJsonPayload { - readonly cliVersion?: unknown; - readonly subscriptionTier?: unknown; - readonly userEmail?: unknown; -} - -export function parseCursorVersionDate(version: string | null | undefined): number | undefined { - const match = version?.trim().match(/^(\d{4})\.(\d{2})\.(\d{2})(?:\b|-|$)/); - if (!match) { - return undefined; - } - const [, year, month, day] = match; - return Number(`${year}${month}${day}`); -} - -export function parseCursorCliConfigChannel(raw: string): string | undefined { - try { - const parsed = JSON.parse(raw) as unknown; - if ( - typeof parsed === "object" && - parsed !== null && - "channel" in parsed && - typeof parsed.channel === "string" - ) { - const channel = parsed.channel.trim().toLowerCase(); - return channel.length > 0 ? channel : undefined; - } - } catch { - return undefined; - } - return undefined; -} - -function toTitleCaseWords(value: string): string { - const parts: Array = []; - for (const part of value.split(/[\s_-]+/g)) { - if (part.length > 0) { - parts.push(part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()); - } - } - return parts.join(" "); -} - -function cursorSubscriptionLabel(subscriptionType: string | undefined): string | undefined { - const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, ""); - if (!normalized) return undefined; - - switch (normalized) { - case "team": - return "Team"; - case "pro": - return "Pro"; - case "free": - return "Free"; - case "business": - return "Business"; - case "enterprise": - return "Enterprise"; - default: - return toTitleCaseWords(subscriptionType!); - } -} - -function cursorAuthMetadata( - subscriptionType: string | undefined, -): Pick | undefined { - if (!subscriptionType) { - return undefined; - } - const subscriptionLabel = cursorSubscriptionLabel(subscriptionType); - return { - type: subscriptionType, - label: `Cursor ${subscriptionLabel ?? toTitleCaseWords(subscriptionType)} Subscription`, - }; -} - -function parseCursorAboutJsonPayload(raw: string): CursorAboutJsonPayload | undefined { - const trimmed = raw.trim(); - if (!trimmed.startsWith("{")) { - return undefined; - } - try { - const parsed = JSON.parse(trimmed) as unknown; - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { - return undefined; - } - return parsed as CursorAboutJsonPayload; - } catch { - return undefined; - } -} - -function hasOwn(record: object, key: string): boolean { - return Object.prototype.hasOwnProperty.call(record, key); -} - -export function getCursorParameterizedModelPickerUnsupportedMessage(input: { - readonly version: string | null | undefined; - readonly channel: string | null | undefined; -}): string | undefined { - const reasons: Array = []; - const versionDate = parseCursorVersionDate(input.version); - if ( - versionDate !== undefined && - versionDate < CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE - ) { - reasons.push( - `Cursor Agent CLI version ${input.version} is too old for Cursor ACP parameterized model picker`, - ); - } - - const normalizedChannel = input.channel?.trim().toLowerCase(); - if ( - normalizedChannel !== undefined && - normalizedChannel.length > 0 && - normalizedChannel !== "lab" - ) { - reasons.push( - `Cursor Agent CLI channel is ${JSON.stringify(input.channel)}, but parameterized model picker is only available on the lab channel`, - ); - } - - if (reasons.length === 0) { - return undefined; - } - - return `${reasons.join(". ")}. Run \`agent set-channel lab && agent update\` and use Cursor Agent CLI 2026.04.08 or newer.`; -} - -/** - * Parse the output of `agent about` to extract version and authentication - * status in a single probe. - * - * Example output (logged in): - * ``` - * About Cursor CLI - * - * CLI Version 2026.03.20-44cb435 - * User Email user@example.com - * ``` - * - * Example output (logged out): - * ``` - * About Cursor CLI - * - * CLI Version 2026.03.20-44cb435 - * User Email Not logged in - * ``` - */ -export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult { - const jsonPayload = parseCursorAboutJsonPayload(result.stdout); - if (jsonPayload) { - const version = - typeof jsonPayload.cliVersion === "string" ? jsonPayload.cliVersion.trim() : null; - const hasUserEmailField = hasOwn(jsonPayload, "userEmail"); - const userEmail = - typeof jsonPayload.userEmail === "string" ? jsonPayload.userEmail.trim() : undefined; - const subscriptionType = - typeof jsonPayload.subscriptionTier === "string" - ? jsonPayload.subscriptionTier.trim() - : undefined; - const authMetadata = cursorAuthMetadata(subscriptionType); - - if (hasUserEmailField && jsonPayload.userEmail == null) { - return { - version, - status: "error", - auth: { status: "unauthenticated" }, - message: "Cursor Agent is not authenticated. Run `agent login` and try again.", - }; - } - - if (!userEmail) { - if (result.code === 0) { - return { - version, - status: "ready", - auth: { - status: "unknown", - ...authMetadata, - }, - }; - } - return { - version, - status: "warning", - auth: { status: "unknown" }, - message: "Could not verify Cursor Agent authentication status.", - }; - } - - const lowerEmail = userEmail.toLowerCase(); - if ( - lowerEmail === "not logged in" || - lowerEmail.includes("login required") || - lowerEmail.includes("authentication required") - ) { - return { - version, - status: "error", - auth: { status: "unauthenticated" }, - message: "Cursor Agent is not authenticated. Run `agent login` and try again.", - }; - } - - return { - version, - status: "ready", - auth: { - status: "authenticated", - email: userEmail, - ...authMetadata, - }, - }; - } - - const combined = `${result.stdout}\n${result.stderr}`; - const lowerOutput = combined.toLowerCase(); - - // If the command itself isn't recognised, we're on an old CLI version. - if ( - lowerOutput.includes("unknown command") || - lowerOutput.includes("unrecognized command") || - lowerOutput.includes("unexpected argument") - ) { - return { - version: null, - status: "warning", - auth: { status: "unknown" }, - message: "The `agent about` command is unavailable in this version of the Cursor Agent CLI.", - }; - } - - const plain = stripAnsi(combined); - const version = extractAboutField(plain, "CLI Version") ?? null; - const userEmail = extractAboutField(plain, "User Email"); - - // Determine auth from the User Email field. - if (userEmail === undefined) { - // Field missing entirely — can't determine auth. - if (result.code === 0) { - return { version, status: "ready", auth: { status: "unknown" } }; - } - return { - version, - status: "warning", - auth: { status: "unknown" }, - message: "Could not verify Cursor Agent authentication status.", - }; - } - - const lowerEmail = userEmail.toLowerCase(); - if ( - lowerEmail === "not logged in" || - lowerEmail.includes("login required") || - lowerEmail.includes("authentication required") - ) { - return { - version, - status: "error", - auth: { status: "unauthenticated" }, - message: "Cursor Agent is not authenticated. Run `agent login` and try again.", - }; - } - - // Any non-empty email value means authenticated. - return { - version, - status: "ready", - auth: { status: "authenticated", email: userEmail }, - }; -} - export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(function* ( cursorSettings: CursorSettings, environment?: NodeJS.ProcessEnv, @@ -1033,117 +268,78 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")( } const sdkApiKey = environment?.CURSOR_API_KEY?.trim(); - if (sdkApiKey) { - const sdkCatalog = yield* CursorSdkCatalog; - const catalogResult = yield* sdkCatalog - .read(sdkApiKey) - .pipe(Effect.timeoutOption(CURSOR_SDK_CATALOG_TIMEOUT_MS), Effect.result); - - if (Result.isFailure(catalogResult)) { - yield* Effect.logWarning("Cursor SDK catalog probe failed", { - cause: catalogResult.failure.cause, - }); - const authenticationFailure = catalogResult.failure.authenticationFailure; - return buildServerProvider({ - presentation: CURSOR_PRESENTATION, - enabled: cursorSettings.enabled, - checkedAt, - models: fallbackModels, - probe: { - installed: true, - version: null, - status: "error", - auth: { status: authenticationFailure ? "unauthenticated" : "unknown" }, - message: authenticationFailure - ? "Cursor SDK authentication failed. Check CURSOR_API_KEY." - : "Cursor SDK catalog request failed. Check server logs for details.", - }, - }); - } - - if (Option.isNone(catalogResult.success)) { - return buildServerProvider({ - presentation: CURSOR_PRESENTATION, - enabled: cursorSettings.enabled, - checkedAt, - models: fallbackModels, - probe: { - installed: true, - version: null, - status: "error", - auth: { status: "unknown" }, - message: `Cursor SDK catalog request timed out after ${CURSOR_SDK_CATALOG_TIMEOUT_MS}ms.`, - }, - }); - } - - const snapshot = catalogResult.success.value; - const discoveredModels = buildCursorDiscoveredModelsFromSdk(snapshot.models); - return buildCursorProviderSnapshot({ + if (!sdkApiKey) { + return buildServerProvider({ + presentation: CURSOR_PRESENTATION, + enabled: cursorSettings.enabled, checkedAt, - cursorSettings, - parsed: { + models: fallbackModels, + probe: { + installed: true, version: null, - status: "ready", - auth: cursorSdkAuth(snapshot.user), + status: "error", + auth: { status: "unauthenticated" }, + message: "Cursor API key is required. Add CURSOR_API_KEY in provider settings.", }, - discoveredModels, - ...(discoveredModels.length === 0 - ? { discoveryWarning: "Cursor SDK model discovery returned no built-in models." } - : {}), }); } - return buildServerProvider({ - presentation: CURSOR_PRESENTATION, - enabled: cursorSettings.enabled, - checkedAt, - models: fallbackModels, - probe: { - installed: true, - version: null, - status: "error", - auth: { status: "unauthenticated" }, - message: "Cursor API key is required. Add CURSOR_API_KEY in provider settings.", - }, - }); -}); + const sdkCatalog = yield* CursorSdkCatalog; + const catalogResult = yield* sdkCatalog + .read(sdkApiKey) + .pipe(Effect.timeoutOption(CURSOR_SDK_CATALOG_TIMEOUT_MS), Effect.result); -/** - * Background maintenance enrichment for a Cursor snapshot. - * - * Used by `CursorDriver` as the `makeManagedServerProvider.enrichSnapshot` - * hook: republishes update/version advisory metadata without performing any - * model or capability discovery. Provider status and model data come from - * the Cursor SDK catalog and require CURSOR_API_KEY. - */ -export const enrichCursorSnapshot = (input: { - readonly settings: CursorSettings; - readonly snapshot: ServerProvider; - readonly maintenanceCapabilities: ProviderMaintenanceCapabilities; - readonly enableProviderUpdateChecks?: boolean; - readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect; - readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider; - readonly httpClient: HttpClient.HttpClient; -}): Effect.Effect => { - const { settings, snapshot, publishSnapshot } = input; - const stampIdentity = input.stampIdentity ?? ((value) => value); - - if (!settings.enabled || snapshot.auth.status === "unauthenticated") { - return Effect.void; + if (Result.isFailure(catalogResult)) { + yield* Effect.logWarning("Cursor SDK catalog probe failed", { + cause: catalogResult.failure.cause, + }); + const authenticationFailure = catalogResult.failure.authenticationFailure; + return buildServerProvider({ + presentation: CURSOR_PRESENTATION, + enabled: cursorSettings.enabled, + checkedAt, + models: fallbackModels, + probe: { + installed: true, + version: null, + status: "error", + auth: { status: authenticationFailure ? "unauthenticated" : "unknown" }, + message: authenticationFailure + ? "Cursor SDK authentication failed. Check CURSOR_API_KEY." + : "Cursor SDK catalog request failed. Check server logs for details.", + }, + }); } - return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, { - enableProviderUpdateChecks: input.enableProviderUpdateChecks, - }).pipe( - Effect.provideService(HttpClient.HttpClient, input.httpClient), - Effect.flatMap((enrichedSnapshot) => - publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)), - ), - Effect.catchCause((cause) => - Effect.logWarning("Cursor version advisory enrichment failed", { - errorTag: causeErrorTag(cause), - }).pipe(Effect.asVoid), - ), - ); -}; + if (Option.isNone(catalogResult.success)) { + return buildServerProvider({ + presentation: CURSOR_PRESENTATION, + enabled: cursorSettings.enabled, + checkedAt, + models: fallbackModels, + probe: { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: `Cursor SDK catalog request timed out after ${CURSOR_SDK_CATALOG_TIMEOUT_MS}ms.`, + }, + }); + } + + const snapshot = catalogResult.success.value; + const discoveredModels = buildCursorDiscoveredModelsFromSdk(snapshot.models); + return buildCursorProviderSnapshot({ + checkedAt, + cursorSettings, + parsed: { + version: null, + status: "ready", + auth: cursorSdkAuth(snapshot.user), + }, + discoveredModels, + ...(discoveredModels.length === 0 + ? { discoveryWarning: "Cursor SDK model discovery returned no built-in models." } + : {}), + }); +}); diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts index 0934925b52..6eb0d000c2 100644 --- a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts +++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts @@ -78,8 +78,6 @@ const makeClaudeConfig = (overrides: Partial): ClaudeSettings => const makeCursorConfig = (overrides: Partial): CursorSettings => ({ enabled: false, - binaryPath: "agent", - apiEndpoint: "", customModels: [], ...overrides, }); diff --git a/apps/server/src/provider/acp/CursorAcpCliProbe.test.ts b/apps/server/src/provider/acp/CursorAcpCliProbe.test.ts deleted file mode 100644 index eebe5ddd92..0000000000 --- a/apps/server/src/provider/acp/CursorAcpCliProbe.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Optional integration check against a real `agent acp` install. - * Enable with: T3_CURSOR_ACP_PROBE=1 bun run test --filter CursorAcpCliProbe - */ -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { it } from "@effect/vitest"; -import * as Console from "effect/Console"; -import * as Effect from "effect/Effect"; -import { describe, expect } from "vite-plus/test"; -import type * as EffectAcpSchema from "effect-acp/schema"; - -import * as AcpSessionRuntime from "./AcpSessionRuntime.ts"; - -describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe", () => { - it.effect("initialize and authenticate against real agent acp", () => - Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - const started = yield* runtime.start(); - expect(started.initializeResult).toBeDefined(); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - spawn: { - command: "agent", - args: ["acp"], - cwd: process.cwd(), - }, - cwd: process.cwd(), - clientCapabilities: { - _meta: { - parameterizedModelPicker: true, - }, - }, - clientInfo: { name: "t3-probe", version: "0.0.0" }, - authMethodId: "cursor_login", - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ), - ); - - it.effect("session/new returns configOptions with a model selector", () => - Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - const started = yield* runtime.start(); - const result = started.sessionSetupResult; - // @effect-diagnostics-next-line preferSchemaOverJson:off - yield* Console.log("session/new result:", JSON.stringify(result, null, 2)); - - expect(typeof started.sessionId).toBe("string"); - - const configOptions = result.configOptions; - // @effect-diagnostics-next-line preferSchemaOverJson:off - yield* Console.log("session/new configOptions:", JSON.stringify(configOptions, null, 2)); - - if (Array.isArray(configOptions)) { - const modelConfig = configOptions.find((opt) => opt.category === "model"); - const parameterizedOptions = configOptions.filter( - (opt) => - opt.category === "thought_level" || - opt.category === "model_option" || - opt.category === "model_config", - ); - // @effect-diagnostics-next-line preferSchemaOverJson:off - yield* Console.log("Model config option:", JSON.stringify(modelConfig, null, 2)); - yield* Console.log( - "Parameterized model config options:", - // @effect-diagnostics-next-line preferSchemaOverJson:off - JSON.stringify(parameterizedOptions, null, 2), - ); - expect(modelConfig).toBeDefined(); - expect(typeof modelConfig?.id).toBe("string"); - } - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - authMethodId: "cursor_login", - spawn: { - command: "agent", - args: ["acp"], - cwd: process.cwd(), - }, - cwd: process.cwd(), - clientCapabilities: { - _meta: { - parameterizedModelPicker: true, - }, - }, - clientInfo: { name: "t3-probe", version: "0.0.0" }, - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ), - ); - - it.effect("session/set_config_option switches the model in-session", () => - Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - const started = yield* runtime.start(); - const newResult = started.sessionSetupResult; - - const configOptions = newResult.configOptions; - let modelConfigId = "model"; - if (Array.isArray(configOptions)) { - const modelConfig = configOptions.find((opt) => opt.category === "model"); - if (typeof modelConfig?.id === "string") { - modelConfigId = modelConfig.id; - } - } - - const setResult: EffectAcpSchema.SetSessionConfigOptionResponse = - yield* runtime.setConfigOption(modelConfigId, "gpt-5.4"); - // @effect-diagnostics-next-line preferSchemaOverJson:off - yield* Console.log("session/set_config_option result:", JSON.stringify(setResult, null, 2)); - - if (Array.isArray(setResult.configOptions)) { - const modelConfig = setResult.configOptions.find((opt) => opt.category === "model"); - const parameterizedOptions = setResult.configOptions.filter( - (opt) => - opt.category === "thought_level" || - opt.category === "model_option" || - opt.category === "model_config", - ); - if (modelConfig?.type === "select") { - expect(modelConfig.currentValue).toBe("gpt-5.4"); - } - expect(parameterizedOptions.length).toBeGreaterThan(0); - } - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - authMethodId: "cursor_login", - spawn: { - command: "agent", - args: ["acp"], - cwd: process.cwd(), - }, - cwd: process.cwd(), - clientCapabilities: { - _meta: { - parameterizedModelPicker: true, - }, - }, - clientInfo: { name: "t3-probe", version: "0.0.0" }, - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ), - ); -}); diff --git a/apps/server/src/provider/acp/CursorAcpExtension.test.ts b/apps/server/src/provider/acp/CursorAcpExtension.test.ts deleted file mode 100644 index 0a6adb75fc..0000000000 --- a/apps/server/src/provider/acp/CursorAcpExtension.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; - -import { - CursorListAvailableModelsResponse, - extractAskQuestions, - extractPlanMarkdown, - extractTodosAsPlan, -} from "./CursorAcpExtension.ts"; - -describe("CursorAcpExtension", () => { - it("extracts ask-question prompts from the real Cursor ACP payload shape", () => { - const questions = extractAskQuestions({ - toolCallId: "ask-1", - title: "Need input", - questions: [ - { - id: "language", - prompt: "Which language should I use?", - options: [ - { id: "ts", label: "TypeScript" }, - { id: "rs", label: "Rust" }, - ], - allowMultiple: false, - }, - ], - }); - - expect(questions).toEqual([ - { - id: "language", - header: "Question", - question: "Which language should I use?", - multiSelect: false, - options: [ - { label: "TypeScript", description: "TypeScript" }, - { label: "Rust", description: "Rust" }, - ], - }, - ]); - }); - - it("defaults ask-question multi-select to false when Cursor omits allowMultiple", () => { - const questions = extractAskQuestions({ - toolCallId: "ask-2", - questions: [ - { - id: "mode", - prompt: "Which mode should I use?", - options: [ - { id: "agent", label: "Agent" }, - { id: "plan", label: "Plan" }, - ], - }, - ], - }); - - expect(questions).toEqual([ - { - id: "mode", - header: "Question", - question: "Which mode should I use?", - multiSelect: false, - options: [ - { label: "Agent", description: "Agent" }, - { label: "Plan", description: "Plan" }, - ], - }, - ]); - }); - - it("extracts plan markdown from the real Cursor create-plan payload shape", () => { - const planMarkdown = extractPlanMarkdown({ - toolCallId: "plan-1", - name: "Refactor parser", - overview: "Tighten ACP parsing", - plan: "# Plan\n\n1. Add schemas\n2. Remove casts", - todos: [ - { id: "t1", content: "Add schemas", status: "in_progress" }, - { id: "t2", content: "Remove casts", status: "pending" }, - ], - isProject: false, - }); - - expect(planMarkdown).toBe("# Plan\n\n1. Add schemas\n2. Remove casts"); - }); - - it("projects todo updates into a plan shape and drops invalid entries", () => { - expect( - extractTodosAsPlan({ - toolCallId: "todos-1", - todos: [ - { id: "1", content: "Inspect state", status: "completed" }, - { id: "2", content: " Apply fix ", status: "in_progress" }, - { id: "3", title: "Fallback title", status: "pending" }, - { id: "4", content: "Unknown status", status: "weird_status" }, - { id: "5", content: " " }, - ], - merge: true, - }), - ).toEqual({ - plan: [ - { step: "Inspect state", status: "completed" }, - { step: "Apply fix", status: "inProgress" }, - { step: "Fallback title", status: "pending" }, - { step: "Unknown status", status: "pending" }, - ], - }); - }); - - it("decodes Cursor list_available_models responses with per-model config options", () => { - const decoded = CursorListAvailableModelsResponse.make({ - models: [ - { - value: "gpt-5.4", - name: "GPT-5.4", - configOptions: [ - { - id: "reasoning", - name: "Reasoning", - category: "thought_level", - type: "select", - currentValue: "medium", - options: [ - { value: "low", name: "Low" }, - { value: "medium", name: "Medium" }, - ], - }, - ], - }, - ], - }); - - expect(decoded.models[0]?.configOptions?.[0]?.id).toBe("reasoning"); - }); -}); diff --git a/apps/server/src/provider/acp/CursorAcpExtension.ts b/apps/server/src/provider/acp/CursorAcpExtension.ts deleted file mode 100644 index 2e131a6160..0000000000 --- a/apps/server/src/provider/acp/CursorAcpExtension.ts +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Public Docs: https://cursor.com/docs/cli/acp#cursor-extension-methods - * Additional reference provided by the Cursor team: https://anysphere.enterprise.slack.com/files/U068SSJE141/F0APT1HSZRP/cursor-acp-extension-method-schemas.md - */ -import type { UserInputQuestion } from "@t3tools/contracts"; -import * as AcpSchema from "effect-acp/schema"; -import * as Schema from "effect/Schema"; - -const CursorAskQuestionOption = Schema.Struct({ - id: Schema.String, - label: Schema.String, -}); - -const CursorAskQuestion = Schema.Struct({ - id: Schema.String, - prompt: Schema.String, - options: Schema.Array(CursorAskQuestionOption), - allowMultiple: Schema.optional(Schema.Boolean), -}); - -export const CursorAskQuestionRequest = Schema.Struct({ - toolCallId: Schema.String, - title: Schema.optional(Schema.String), - questions: Schema.Array(CursorAskQuestion), -}); - -const CursorTodoStatus = Schema.String; - -const CursorTodo = Schema.Struct({ - id: Schema.optional(Schema.String), - content: Schema.optional(Schema.String), - title: Schema.optional(Schema.String), - status: Schema.optional(CursorTodoStatus), -}); - -const CursorPlanPhase = Schema.Struct({ - name: Schema.String, - todos: Schema.Array(CursorTodo), -}); - -export const CursorCreatePlanRequest = Schema.Struct({ - toolCallId: Schema.String, - name: Schema.optional(Schema.String), - overview: Schema.optional(Schema.String), - plan: Schema.String, - todos: Schema.Array(CursorTodo), - isProject: Schema.optional(Schema.Boolean), - phases: Schema.optional(Schema.Array(CursorPlanPhase)), -}); - -export const CursorUpdateTodosRequest = Schema.Struct({ - toolCallId: Schema.String, - todos: Schema.Array(CursorTodo), - merge: Schema.Boolean, -}); - -const CursorAvailableModel = Schema.Struct({ - value: Schema.String, - name: Schema.String, - configOptions: Schema.optional(Schema.Array(AcpSchema.SessionConfigOption)), -}); - -export const CursorListAvailableModelsResponse = Schema.Struct({ - models: Schema.Array(CursorAvailableModel), -}); - -export function extractAskQuestions( - params: typeof CursorAskQuestionRequest.Type, -): ReadonlyArray { - return params.questions.map((question) => ({ - id: question.id, - header: "Question", - question: question.prompt, - multiSelect: question.allowMultiple === true, - options: - question.options.length > 0 - ? question.options.map((option) => ({ - label: option.label, - description: option.label, - })) - : [{ label: "OK", description: "Continue" }], - })); -} - -export function extractPlanMarkdown(params: typeof CursorCreatePlanRequest.Type): string { - return params.plan || "# Plan\n\n(Cursor did not supply plan text.)"; -} - -export function extractTodosAsPlan(params: typeof CursorUpdateTodosRequest.Type): { - readonly explanation?: string; - readonly plan: ReadonlyArray<{ - readonly step: string; - readonly status: "pending" | "inProgress" | "completed"; - }>; -} { - const plan = params.todos.flatMap((todo) => { - const step = todo.content?.trim() ?? todo.title?.trim() ?? ""; - if (step === "") { - return []; - } - const status: "pending" | "inProgress" | "completed" = - todo.status === "completed" - ? "completed" - : todo.status === "in_progress" || todo.status === "inProgress" - ? "inProgress" - : "pending"; - return [{ step, status }]; - }); - return { plan }; -} diff --git a/apps/server/src/provider/acp/CursorAcpSupport.test.ts b/apps/server/src/provider/acp/CursorAcpSupport.test.ts deleted file mode 100644 index 78bc16c9f3..0000000000 --- a/apps/server/src/provider/acp/CursorAcpSupport.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import * as Effect from "effect/Effect"; -import type * as EffectAcpSchema from "effect-acp/schema"; -import { describe, expect, it } from "vite-plus/test"; - -import { applyCursorAcpModelSelection, buildCursorAcpSpawnInput } from "./CursorAcpSupport.ts"; - -const parameterizedGpt54ConfigOptions: ReadonlyArray = [ - { - id: "model", - name: "Model", - category: "model", - type: "select", - currentValue: "gpt-5.4-medium-fast", - options: [{ value: "gpt-5.4-medium-fast", name: "GPT-5.4" }], - }, - { - id: "reasoning", - name: "Reasoning", - category: "thought_level", - type: "select", - currentValue: "medium", - options: [ - { value: "low", name: "Low" }, - { value: "medium", name: "Medium" }, - { value: "high", name: "High" }, - { value: "extra-high", name: "Extra High" }, - ], - }, - { - id: "context", - name: "Context", - category: "model_config", - type: "select", - currentValue: "272k", - options: [ - { value: "272k", name: "272K" }, - { value: "1m", name: "1M" }, - ], - }, - { - id: "fast", - name: "Fast", - category: "model_config", - type: "select", - currentValue: "false", - options: [ - { value: "false", name: "Off" }, - { value: "true", name: "Fast" }, - ], - }, -]; - -describe("buildCursorAcpSpawnInput", () => { - it("builds the default Cursor ACP command", () => { - expect(buildCursorAcpSpawnInput(undefined, "/tmp/project")).toEqual({ - command: "agent", - args: ["acp"], - cwd: "/tmp/project", - }); - }); - - it("includes the configured api endpoint when present", () => { - expect( - buildCursorAcpSpawnInput( - { - binaryPath: "/usr/local/bin/agent", - apiEndpoint: "http://localhost:3000", - }, - "/tmp/project", - ), - ).toEqual({ - command: "/usr/local/bin/agent", - args: ["-e", "http://localhost:3000", "acp"], - cwd: "/tmp/project", - }); - }); -}); - -describe("applyCursorAcpModelSelection", () => { - it("sets the base model before applying separate config options", async () => { - const calls: Array< - | { readonly type: "model"; readonly value: string } - | { readonly type: "config"; readonly configId: string; readonly value: string | boolean } - > = []; - - const runtime = { - getConfigOptions: Effect.succeed(parameterizedGpt54ConfigOptions), - setModel: (value: string) => - Effect.sync(() => { - calls.push({ type: "model", value }); - }), - setConfigOption: (configId: string, value: string | boolean) => - Effect.sync(() => { - calls.push({ type: "config", configId, value }); - }), - }; - - await Effect.runPromise( - applyCursorAcpModelSelection({ - runtime, - model: "gpt-5.4-medium-fast[reasoning=medium,context=272k]", - selections: [ - { id: "reasoning", value: "xhigh" }, - { id: "contextWindow", value: "1m" }, - { id: "fastMode", value: true }, - ], - mapError: ({ step, configId, cause }) => - step === "set-config-option" - ? `failed to set config option ${configId}: ${cause.message}` - : `failed to set model: ${cause.message}`, - }), - ); - - expect(calls).toEqual([ - { type: "model", value: "gpt-5.4-medium-fast" }, - { type: "config", configId: "reasoning", value: "extra-high" }, - { type: "config", configId: "context", value: "1m" }, - { type: "config", configId: "fast", value: "true" }, - ]); - }); -}); diff --git a/apps/server/src/provider/acp/CursorAcpSupport.ts b/apps/server/src/provider/acp/CursorAcpSupport.ts deleted file mode 100644 index 169d7c6206..0000000000 --- a/apps/server/src/provider/acp/CursorAcpSupport.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { type CursorSettings, type ProviderOptionSelection } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Scope from "effect/Scope"; -import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; -import type * as EffectAcpErrors from "effect-acp/errors"; - -import { - CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES, - resolveCursorAcpBaseModelId, - resolveCursorAcpConfigUpdates, -} from "../Layers/CursorProvider.ts"; -import * as AcpSessionRuntime from "./AcpSessionRuntime.ts"; - -type CursorAcpRuntimeCursorSettings = Pick; - -export interface CursorAcpRuntimeInput extends Omit< - AcpSessionRuntime.AcpSessionRuntimeOptions, - "authMethodId" | "clientCapabilities" | "spawn" -> { - readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; - readonly cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined; - readonly environment?: NodeJS.ProcessEnv; -} - -export interface CursorAcpModelSelectionErrorContext { - readonly cause: EffectAcpErrors.AcpError; - readonly step: "set-config-option" | "set-model"; - readonly configId?: string; -} - -export function buildCursorAcpSpawnInput( - cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined, - cwd: string, - environment?: NodeJS.ProcessEnv, -): AcpSessionRuntime.AcpSpawnInput { - return { - command: cursorSettings?.binaryPath || "agent", - args: [ - ...(cursorSettings?.apiEndpoint ? (["-e", cursorSettings.apiEndpoint] as const) : []), - "acp", - ], - cwd, - ...(environment ? { env: environment } : {}), - }; -} - -export const makeCursorAcpRuntime = ( - input: CursorAcpRuntimeInput, -): Effect.Effect< - AcpSessionRuntime.AcpSessionRuntime["Service"], - EffectAcpErrors.AcpError, - Scope.Scope -> => - Effect.gen(function* () { - const acpContext = yield* Layer.build( - AcpSessionRuntime.layer({ - ...input, - spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment), - authMethodId: "cursor_login", - clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES, - }).pipe( - Layer.provide( - Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner), - ), - ), - ); - return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( - Effect.provide(acpContext), - ); - }); - -interface CursorAcpModelSelectionRuntime { - readonly getConfigOptions: AcpSessionRuntime.AcpSessionRuntime["Service"]["getConfigOptions"]; - readonly setConfigOption: ( - configId: string, - value: string | boolean, - ) => Effect.Effect; - readonly setModel: (model: string) => Effect.Effect; -} - -export function applyCursorAcpModelSelection(input: { - readonly runtime: CursorAcpModelSelectionRuntime; - readonly model: string | null | undefined; - readonly selections: ReadonlyArray | null | undefined; - readonly mapError: (context: CursorAcpModelSelectionErrorContext) => E; -}): Effect.Effect { - return Effect.gen(function* () { - yield* input.runtime.setModel(resolveCursorAcpBaseModelId(input.model)).pipe( - Effect.mapError((cause) => - input.mapError({ - cause, - step: "set-model", - }), - ), - ); - - const configUpdates = resolveCursorAcpConfigUpdates( - yield* input.runtime.getConfigOptions, - input.selections, - ); - for (const update of configUpdates) { - yield* input.runtime.setConfigOption(update.configId, update.value).pipe( - Effect.mapError((cause) => - input.mapError({ - cause, - step: "set-config-option", - configId: update.configId, - }), - ), - ); - } - }); -} diff --git a/apps/server/src/provider/cursorSdkModel.ts b/apps/server/src/provider/cursorSdkModel.ts index c1c21af645..c64e24b0a0 100644 --- a/apps/server/src/provider/cursorSdkModel.ts +++ b/apps/server/src/provider/cursorSdkModel.ts @@ -1,3 +1,6 @@ +import type { ModelSelection as CursorSdkModelSelection, ModelParameterValue } from "@cursor/sdk"; +import type { ModelSelection } from "@t3tools/contracts"; + const CURSOR_SDK_PARAMETER_TO_PROVIDER_OPTION: Readonly> = { context: "contextWindow", fast: "fastMode", @@ -31,3 +34,19 @@ export function cursorSdkParameterPriority(parameterId: string): number { return 4; } } + +export function cursorSdkModelSelection(modelSelection: ModelSelection): CursorSdkModelSelection { + return { + id: modelSelection.model === "auto" ? "default" : modelSelection.model, + ...(modelSelection.options === undefined || modelSelection.options.length === 0 + ? {} + : { + params: modelSelection.options.map( + (option): ModelParameterValue => ({ + id: cursorSdkParameterId(option.id), + value: String(option.value), + }), + ), + }), + }; +} diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index f33a9bbce4..07728e02b1 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -30,10 +30,10 @@ import { const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError); const CODEX_DRIVER = ProviderDriverKind.make("codex"); -const CURSOR_DRIVER = ProviderDriverKind.make("cursor"); +const NATIVE_CLI_DRIVER = ProviderDriverKind.make("nativeCli"); const OPENCODE_DRIVER = ProviderDriverKind.make("opencode"); const CODEX_INSTANCE_ID = ProviderInstanceId.make("codex"); -const CURSOR_INSTANCE_ID = ProviderInstanceId.make("cursor"); +const NATIVE_CLI_INSTANCE_ID = ProviderInstanceId.make("nativeCli"); const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode"); const encoder = new TextEncoder(); @@ -44,13 +44,13 @@ const encoder = new TextEncoder(); const NonWindowsPlatform = Layer.succeed(HostProcessPlatform, "linux"); function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabilities { - if (provider === CURSOR_DRIVER) { + if (provider === NATIVE_CLI_DRIVER) { return makeProviderMaintenanceCapabilities({ provider, packageName: null, - updateExecutable: "agent", + updateExecutable: "native-agent", updateArgs: ["update"], - updateLockKey: "cursor-agent", + updateLockKey: "native-agent", }); } return makeProviderMaintenanceCapabilities({ @@ -79,10 +79,10 @@ const baseProvider: ServerProvider = { skills: [], }; -const baseCursorProvider: ServerProvider = { +const baseNativeCliProvider: ServerProvider = { ...baseProvider, - instanceId: CURSOR_INSTANCE_ID, - driver: CURSOR_DRIVER, + instanceId: NATIVE_CLI_INSTANCE_ID, + driver: NATIVE_CLI_DRIVER, }; const baseOpenCodeProvider: ServerProvider = { @@ -220,13 +220,13 @@ describe("providerMaintenanceRunner", () => { it.effect("runs the allowlisted provider update command and records success", () => { const calls: Array<{ command: string; args: ReadonlyArray }> = []; return Effect.gen(function* () { - const { registry, updateStatesRef } = yield* makeRegistry(baseCursorProvider); + const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); const updater = yield* makeTestRunner(registry); - const result = yield* updater.updateProvider(CURSOR_DRIVER); + const result = yield* updater.updateProvider(NATIVE_CLI_DRIVER); assert.deepStrictEqual(calls, [ { - command: "agent", + command: "native-agent", args: ["update"], }, ]); diff --git a/apps/server/src/textGeneration/CursorTextGeneration.test.ts b/apps/server/src/textGeneration/CursorTextGeneration.test.ts index 2dc4720dca..42fe44a8ee 100644 --- a/apps/server/src/textGeneration/CursorTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CursorTextGeneration.test.ts @@ -1,276 +1,162 @@ -// @effect-diagnostics nodeBuiltinImport:off -import * as NodePath from "node:path"; -import * as NodeOS from "node:os"; -import * as NodeURL from "node:url"; -import * as NodeFS from "node:fs"; - -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { it } from "@effect/vitest"; -import * as Clock from "effect/Clock"; +import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import { createModelSelection } from "@t3tools/shared/model"; -import { expect } from "vite-plus/test"; +import { beforeEach, vi } from "vite-plus/test"; -import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts"; - -import * as ServerConfig from "../config.ts"; -import * as TextGeneration from "./TextGeneration.ts"; import { makeCursorTextGeneration } from "./CursorTextGeneration.ts"; + +const cursorSdkMock = vi.hoisted(() => ({ + prompt: vi.fn(async () => ({ + id: "run-cursor-text-generation-test", + status: "finished" as const, + result: + '{"subject":"Add generated commit message","body":"- verify cursor sdk text generation"}', + })), +})); + +vi.mock("@cursor/sdk", () => ({ + Agent: { + prompt: cursorSdkMock.prompt, + }, +})); + const decodeCursorSettings = Schema.decodeSync(CursorSettings); +const cursorSettings = decodeCursorSettings({ enabled: true }); -const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); -const mockAgentPath = NodePath.join(__dirname, "../../scripts/acp-mock-agent.ts"); - -function shellSingleQuote(value: string): string { - return `'${value.replaceAll("'", `'"'"'`)}'`; -} - -const CursorTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-cursor-text-generation-test-", -}).pipe(Layer.provideMerge(NodeServices.layer)); - -function makeAcpAgentWrapper(dir: string, env: Record): string { - const binDir = NodePath.join(dir, "bin"); - const agentPath = NodePath.join(binDir, "agent"); - NodeFS.mkdirSync(binDir, { recursive: true }); - NodeFS.writeFileSync( - agentPath, - [ - "#!/bin/sh", - ...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`), - 'if [ "$1" != "acp" ]; then', - ' printf "%s\\n" "unexpected args: $*" >&2', - " exit 11", - "fi", - `exec node ${JSON.stringify(mockAgentPath)}`, - "", - ].join("\n"), - "utf8", - ); - NodeFS.chmodSync(agentPath, 0o755); - return agentPath; -} - -function withFakeAcpAgent( - env: Record, - effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect, -) { - return Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-cursor-text-acp-")); - yield* Effect.addFinalizer(() => - Effect.sync(() => { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - }), - ); - const agentPath = makeAcpAgentWrapper(tempDir, env); - const config = decodeCursorSettings({ binaryPath: agentPath }); - const textGeneration = yield* makeCursorTextGeneration(config); - return yield* effectFn(textGeneration); - }).pipe(Effect.scoped); -} - -function waitForFileContent(path: string): Effect.Effect { - return Effect.gen(function* () { - const deadline = (yield* Clock.currentTimeMillis) + 5_000; - for (;;) { - const result = yield* Effect.exit(Effect.sync(() => NodeFS.readFileSync(path, "utf8"))); - if (Exit.isSuccess(result)) { - return result.value; - } - { - if ((yield* Clock.currentTimeMillis) >= deadline) { - return yield* Effect.die(result.cause); - } - } - yield* Effect.sleep(25); - } - }); -} - -it.layer(CursorTextGenerationTestLayer)("CursorTextGeneration", (it) => { - it.effect("uses ACP model config options instead of raw CLI model ids", () => { - const requestLogDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3code-cursor-text-log-"), - ); - const requestLogPath = NodePath.join(requestLogDir, "requests.ndjson"); - - return withFakeAcpAgent( - { - T3_ACP_REQUEST_LOG_PATH: requestLogPath, - T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ - subject: "Add generated commit message", - body: "- verify cursor acp model config path", - }), - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/cursor-text-generation", - stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts", - stagedPatch: - "diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts", - modelSelection: { - ...createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [ - { id: "reasoning", value: "xhigh" }, - { id: "fastMode", value: true }, - { id: "contextWindow", value: "1m" }, - ]), - }, - }); - - expect(generated.subject).toBe("Add generated commit message"); - expect(generated.body).toBe("- verify cursor acp model config path"); - - const requests = NodeFS.readFileSync(requestLogPath, "utf8") - .trim() - .split("\n") - .filter((line) => line.length > 0) - .map( - (line) => JSON.parse(line) as { method?: string; params?: Record }, - ); - - expect( - requests.find((request) => request.method === "initialize")?.params?.clientCapabilities, - ).toMatchObject({ - _meta: { - parameterizedModelPicker: true, - }, - }); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "model" && - request.params?.value === "gpt-5.4", - ), - ).toBe(true); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "reasoning" && - request.params?.value === "extra-high", - ), - ).toBe(true); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "context" && - request.params?.value === "1m", - ), - ).toBe(true); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "fast" && - request.params?.value === "true", - ), - ).toBe(true); - expect( - requests.find((request) => request.method === "session/prompt")?.params?.prompt, - ).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - type: "text", - text: expect.stringContaining("Staged patch:"), - }), - ]), - ); - - NodeFS.rmSync(requestLogDir, { recursive: true, force: true }); - }), - ); - }); - - it.effect("accepts json objects with extra assistant text around them", () => - withFakeAcpAgent( - { - T3_ACP_PROMPT_RESPONSE_TEXT: - 'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.', - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/cursor-noisy-json", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: { - instanceId: ProviderInstanceId.make("cursor"), - model: "composer-2", - }, - }); - - expect(generated.subject).toBe("Update README dummy comment with attribution and date"); - expect(generated.body).toBe(""); - }), - ), - ); - - it.effect("generates thread titles through Cursor ACP text generation", () => - withFakeAcpAgent( - { - T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ - title: '"Trim reconnect spinner status after resume."', - }), - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Fix the reconnect spinner after a resumed session.", - modelSelection: { - instanceId: ProviderInstanceId.make("cursor"), - model: "composer-2", - }, - }); - - expect(generated.title).toBe("Trim reconnect spinner status after resume."); - }), - ), - ); - - it.effect("closes the ACP child process after text generation completes", () => { - const exitLogDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3code-cursor-text-exit-log-"), - ); - const exitLogPath = NodePath.join(exitLogDir, "exit.log"); - - return withFakeAcpAgent( - { - T3_ACP_EXIT_LOG_PATH: exitLogPath, - T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ - subject: "Close runtime after generation", - body: "", - }), - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/cursor-runtime-close", - stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts", - stagedPatch: - "diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts", - modelSelection: { - instanceId: ProviderInstanceId.make("cursor"), - model: "composer-2", - }, - }); - - expect(generated.subject).toBe("Close runtime after generation"); - - const exitLog = yield* waitForFileContent(exitLogPath); - expect(exitLog).toContain("exit:0"); - - NodeFS.rmSync(exitLogDir, { recursive: true, force: true }); - }), - ); +beforeEach(() => { + cursorSdkMock.prompt.mockReset(); + cursorSdkMock.prompt.mockResolvedValue({ + id: "run-cursor-text-generation-test", + status: "finished", + result: + '{"subject":"Add generated commit message","body":"- verify cursor sdk text generation"}', }); }); + +describe("CursorTextGeneration", () => { + it.effect("uses the Cursor SDK prompt API with model parameters and API key", () => + Effect.gen(function* () { + const textGeneration = yield* makeCursorTextGeneration(cursorSettings, { + CURSOR_API_KEY: "test-cursor-key", + }); + + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/cursor-text-generation", + stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts", + stagedPatch: + "diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts", + modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [ + { id: "thinking", value: "high" }, + { id: "contextWindow", value: "1m" }, + { id: "fastMode", value: true }, + ]), + }); + + expect(generated.subject).toBe("Add generated commit message"); + expect(generated.body).toBe("- verify cursor sdk text generation"); + + expect(cursorSdkMock.prompt).toHaveBeenCalledTimes(1); + const [prompt, options] = ( + cursorSdkMock.prompt.mock.calls as unknown as Array<[string, unknown]> + )[0]!; + expect(prompt).toContain("Staged patch:"); + expect(options).toEqual({ + apiKey: "test-cursor-key", + mode: "agent", + model: { + id: "gpt-5.4", + params: [ + { id: "thinking", value: "high" }, + { id: "context", value: "1m" }, + { id: "fast", value: "true" }, + ], + }, + local: { + cwd: process.cwd(), + autoReview: false, + sandboxOptions: { enabled: false }, + enableAgentRetries: true, + }, + }); + }), + ); + + it.effect("accepts json objects with extra assistant text around them", () => + Effect.gen(function* () { + cursorSdkMock.prompt.mockResolvedValueOnce({ + id: "run-cursor-text-generation-test", + status: "finished", + result: + 'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.', + }); + const textGeneration = yield* makeCursorTextGeneration(cursorSettings, { + CURSOR_API_KEY: "test-cursor-key", + }); + + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/cursor-noisy-json", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: { + instanceId: ProviderInstanceId.make("cursor"), + model: "composer-2", + }, + }); + + expect(generated.subject).toBe("Update README dummy comment with attribution and date"); + expect(generated.body).toBe(""); + }), + ); + + it.effect("generates thread titles through Cursor SDK text generation", () => + Effect.gen(function* () { + cursorSdkMock.prompt.mockResolvedValueOnce({ + id: "run-cursor-title-generation-test", + status: "finished", + result: '{"title":"\\"Trim reconnect spinner status after resume.\\""}', + }); + const textGeneration = yield* makeCursorTextGeneration(cursorSettings, { + CURSOR_API_KEY: "test-cursor-key", + }); + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Fix the reconnect spinner after a resumed session.", + modelSelection: { + instanceId: ProviderInstanceId.make("cursor"), + model: "composer-2", + }, + }); + + expect(generated.title).toBe("Trim reconnect spinner status after resume."); + }), + ); + + it.effect("requires CURSOR_API_KEY before calling the SDK", () => + Effect.gen(function* () { + const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {}); + + const error = yield* Effect.flip( + textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/cursor-api-key", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: { + instanceId: ProviderInstanceId.make("cursor"), + model: "composer-2", + }, + }), + ); + + expect(error.detail).toBe( + "Cursor API key is required. Add CURSOR_API_KEY in provider settings.", + ); + expect(cursorSdkMock.prompt).not.toHaveBeenCalled(); + }), + ); +}); diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts index 3e1f4eb8bb..45ac4c21ab 100644 --- a/apps/server/src/textGeneration/CursorTextGeneration.ts +++ b/apps/server/src/textGeneration/CursorTextGeneration.ts @@ -1,8 +1,7 @@ +import { Agent, type AgentOptions, type RunResult } from "@cursor/sdk"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; -import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; -import { ChildProcessSpawner } from "effect/unstable/process"; import { type CursorSettings, type ModelSelection } from "@t3tools/contracts"; import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; @@ -21,26 +20,58 @@ import { sanitizePrTitle, sanitizeThreadTitle, } from "./TextGenerationUtils.ts"; -import { - applyCursorAcpModelSelection, - makeCursorAcpRuntime, -} from "../provider/acp/CursorAcpSupport.ts"; +import { cursorSdkModelSelection } from "../provider/cursorSdkModel.ts"; const CURSOR_TIMEOUT_MS = 180_000; const isTextGenerationError = Schema.is(TextGenerationError); +type CursorTextGenerationOperation = + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle"; + +function emptyCursorSdkResultDetail(result: RunResult): string { + switch (result.status) { + case "cancelled": + return "Cursor SDK request was cancelled."; + case "error": + return "Cursor SDK request finished with an error and no output."; + case "finished": + return "Cursor SDK returned empty output."; + } +} /** * Build a Cursor text-generation closure bound to a specific `CursorSettings` * payload. See `makeCodexAdapter` for the overall per-instance rationale. */ -export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* ( +export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(( cursorSettings: CursorSettings, environment?: NodeJS.ProcessEnv, -) { - const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; +) => { const resolvedEnvironment = environment ?? process.env; + const resolveCursorApiKey = (operation: CursorTextGenerationOperation) => + Effect.gen(function* () { + if (!cursorSettings.enabled) { + return yield* new TextGenerationError({ + operation, + detail: "Cursor is disabled in T3 Code settings.", + }); + } + + const apiKey = resolvedEnvironment.CURSOR_API_KEY?.trim(); + if (!apiKey) { + return yield* new TextGenerationError({ + operation, + detail: "Cursor API key is required. Add CURSOR_API_KEY in provider settings.", + }); + } + + return apiKey; + }); + const runCursorJson = ({ operation, cwd, @@ -48,59 +79,34 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu outputSchemaJson, modelSelection, }: { - operation: - | "generateCommitMessage" - | "generatePrContent" - | "generateBranchName" - | "generateThreadTitle"; + operation: CursorTextGenerationOperation; cwd: string; prompt: string; outputSchemaJson: S; modelSelection: ModelSelection; }): Effect.Effect => Effect.gen(function* () { - const outputRef = yield* Ref.make(""); - const runtime = yield* makeCursorAcpRuntime({ - cursorSettings, - environment: resolvedEnvironment, - childProcessSpawner: commandSpawner, - cwd, - clientInfo: { name: "t3-code-git-text", version: "0.0.0" }, - }); + const apiKey = yield* resolveCursorApiKey(operation); + const agentOptions = { + apiKey, + mode: "agent", + model: cursorSdkModelSelection(modelSelection), + local: { + cwd, + autoReview: false, + sandboxOptions: { enabled: false }, + enableAgentRetries: true, + }, + } satisfies AgentOptions; - yield* runtime.handleSessionUpdate((notification) => { - const update = notification.update; - if (update.sessionUpdate !== "agent_message_chunk") { - return Effect.void; - } - const content = update.content; - if (content.type !== "text") { - return Effect.void; - } - return Ref.update(outputRef, (current) => current + content.text); - }); - - const promptResult = yield* Effect.gen(function* () { - yield* runtime.start(); - yield* Effect.ignore(runtime.setMode("ask")); - yield* applyCursorAcpModelSelection({ - runtime, - model: modelSelection.model, - selections: modelSelection.options, - mapError: ({ cause, configId, step }) => - new TextGenerationError({ - operation, - detail: - step === "set-config-option" - ? `Failed to set Cursor ACP config option "${configId}" for text generation.` - : "Failed to set Cursor ACP base model for text generation.", - cause, - }), - }); - - return yield* runtime.prompt({ - prompt: [{ type: "text", text: prompt }], - }); + const promptResult = yield* Effect.tryPromise({ + try: () => Agent.prompt(prompt, agentOptions), + catch: (cause) => + new TextGenerationError({ + operation, + detail: "Cursor SDK request failed.", + cause, + }), }).pipe( Effect.timeoutOption(CURSOR_TIMEOUT_MS), Effect.flatMap( @@ -109,31 +115,19 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu Effect.fail( new TextGenerationError({ operation, - detail: "Cursor Agent request timed out.", + detail: "Cursor SDK request timed out.", }), ), onSome: (value) => Effect.succeed(value), }), ), - Effect.mapError((cause) => - isTextGenerationError(cause) - ? cause - : new TextGenerationError({ - operation, - detail: "Cursor ACP request failed.", - cause, - }), - ), ); - const rawResult = (yield* Ref.get(outputRef)).trim(); + const rawResult = promptResult.result?.trim() ?? ""; if (!rawResult) { return yield* new TextGenerationError({ operation, - detail: - promptResult.stopReason === "cancelled" - ? "Cursor ACP request was cancelled." - : "Cursor Agent returned empty output.", + detail: emptyCursorSdkResultDetail(promptResult), }); } @@ -144,7 +138,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu Effect.fail( new TextGenerationError({ operation, - detail: "Cursor Agent returned invalid structured output.", + detail: "Cursor SDK returned invalid structured output.", cause, }), ), @@ -156,11 +150,10 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu ? cause : new TextGenerationError({ operation, - detail: "Cursor ACP text generation failed.", + detail: "Cursor SDK text generation failed.", cause, }), ), - Effect.scoped, ); const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] = @@ -253,10 +246,10 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu } satisfies TextGeneration.ThreadTitleGenerationResult; }); - return { + return Effect.succeed({ generateCommitMessage, generatePrContent, generateBranchName, generateThreadTitle, - } satisfies TextGeneration.TextGeneration["Service"]; + } satisfies TextGeneration.TextGeneration["Service"]); }); diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts index ac2d47ca33..729f353724 100644 --- a/packages/contracts/src/settings.test.ts +++ b/packages/contracts/src/settings.test.ts @@ -99,6 +99,40 @@ describe("ServerSettings worktree defaults", () => { }); }); +describe("ServerSettings Cursor legacy settings", () => { + it("ignores obsolete Cursor CLI settings when reading server settings", () => { + const decoded = decodeServerSettings({ + providers: { + cursor: { + enabled: true, + binaryPath: "cursor-agent", + apiEndpoint: "http://127.0.0.1:3774", + }, + }, + }); + + expect(decoded.providers.cursor.enabled).toBe(true); + expect(decoded.providers.cursor).not.toHaveProperty("binaryPath"); + expect(decoded.providers.cursor).not.toHaveProperty("apiEndpoint"); + }); + + it("ignores obsolete Cursor CLI settings in patches", () => { + const patch = decodeServerSettingsPatch({ + providers: { + cursor: { + enabled: true, + binaryPath: "cursor-agent", + apiEndpoint: "http://127.0.0.1:3774", + }, + }, + }); + + expect(patch.providers?.cursor?.enabled).toBe(true); + expect(patch.providers?.cursor).not.toHaveProperty("binaryPath"); + expect(patch.providers?.cursor).not.toHaveProperty("apiEndpoint"); + }); +}); + describe("ServerSettingsPatch.providerInstances", () => { it("treats providerInstances as an optional whole-map replacement", () => { const patch = decodeServerSettingsPatch({}); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index a09db21ab8..dde393a930 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -252,25 +252,6 @@ export const CursorSettings = makeProviderSettingsSchema( Schema.withDecodingDefault(Effect.succeed(false)), Schema.annotateKey({ providerSettingsForm: { hidden: true } }), ), - binaryPath: makeBinaryPathSetting("agent").pipe( - Schema.annotateKey({ - title: "Binary path", - description: "Legacy Cursor Agent CLI path.", - providerSettingsForm: { hidden: true, placeholder: "agent", clearWhenEmpty: "omit" }, - }), - ), - apiEndpoint: TrimmedString.pipe( - Schema.withDecodingDefault(Effect.succeed("")), - Schema.annotateKey({ - title: "API endpoint", - description: "Legacy Cursor Agent CLI API endpoint override.", - providerSettingsForm: { - hidden: true, - placeholder: "https://...", - clearWhenEmpty: "omit", - }, - }), - ), customModels: Schema.Array(Schema.String).pipe( Schema.withDecodingDefault(Effect.succeed([])), Schema.annotateKey({ providerSettingsForm: { hidden: true } }), @@ -533,8 +514,6 @@ const ClaudeSettingsPatch = Schema.Struct({ const CursorSettingsPatch = Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean), - binaryPath: Schema.optionalKey(TrimmedString), - apiEndpoint: Schema.optionalKey(TrimmedString), customModels: Schema.optionalKey(Schema.Array(Schema.String)), }); diff --git a/packages/effect-acp/test/examples/cursor-acp-client.example.ts b/packages/effect-acp/test/examples/cursor-acp-client.example.ts deleted file mode 100644 index b7a146cf5c..0000000000 --- a/packages/effect-acp/test/examples/cursor-acp-client.example.ts +++ /dev/null @@ -1,81 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as Console from "effect/Console"; -import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; - -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; - -import * as AcpClient from "../../src/client.ts"; - -const program = Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const command = ChildProcess.make("cursor-agent", ["acp"], { - cwd: process.cwd(), - shell: false, - }); - const handle = yield* spawner.spawn(command); - const acpLayer = AcpClient.layerChildProcess(handle, { - logIncoming: true, - logOutgoing: true, - }); - - yield* Effect.gen(function* () { - const acp = yield* AcpClient.AcpClient; - - yield* acp.handleRequestPermission(() => - Effect.succeed({ - outcome: { - outcome: "selected", - optionId: "allow", - }, - }), - ); - // yield* acp.handleSessionUpdate((notification) => - // Console.log("session/update", JSON.stringify(notification)), - // ); - - const initialized = yield* acp.agent.initialize({ - protocolVersion: 1, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - _meta: { - parameterizedModelPicker: true, - }, - }, - clientInfo: { - name: "effect-acp-example", - version: "0.0.0", - }, - }); - yield* Console.log("initialized", initialized); - - const session = yield* acp.agent.createSession({ - cwd: process.cwd(), - mcpServers: [], - }); - - const config = yield* acp.agent.setSessionConfigOption({ - sessionId: session.sessionId, - configId: "model", - value: "claude-opus-4-6", - }); - - yield* Console.log("config", config); - - const result = yield* acp.agent.prompt({ - sessionId: session.sessionId, - prompt: [ - { - type: "text", - text: "Illustrate your ability to create todo lists and then execute all of them. Do not write the list to disk, illustrate your built in ability!", - }, - ], - }); - - yield* Console.log("prompt result", result); - yield* acp.agent.cancel({ sessionId: session.sessionId }); - }).pipe(Effect.provide(acpLayer)); -}); - -program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);