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
This commit is contained in:
Julius Marminge committed 2026-06-30 10:29:47 -07:00
1 parent 7bf0a2ce15
commit c2132ee7dd
21 files changed
+508 -3150

No files matched your search

+1 -1
View File
@@ -204,7 +204,7 @@ const mobileEndorsementRows = [
<div class="harness-mark"><img src="/harnesses/cursor_light.svg" alt="" /></div>
<div class="harness-meta">
<div class="harness-name">Cursor</div>
<div class="harness-tag">cursor-agent</div>
<div class="harness-tag">@cursor/sdk</div>
</div>
</div>
</div>
-35
View File
@@ -228,35 +228,6 @@ function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
];
}
function modelConfigOptionsFor(modelId: string): ReadonlyArray<AcpSchema.SessionConfigOption> {
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<AcpSchema.SessionConfigOption>;
}> {
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<AcpSchema.SessionMode> = [
{
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));
}
@@ -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<SelectLeafOption | SelectGroupOption>;
};
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<void>((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<JsonRpcId, PendingRequest>();
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<JsonValue | undefined>((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;
});
@@ -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<string, McpServerConfig> | 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: {
@@ -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,
);
},
);
@@ -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<CursorSettings, CursorDriverEnv> = {
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<CursorSettings, CursorDriverEnv> = {
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<CursorSettings, CursorDriverEnv> = {
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
maintenanceCapabilities,
maintenanceCapabilities: MAINTENANCE_CAPABILITIES,
getSettings: snapshotSettings.getSettings,
streamSettings: snapshotSettings.streamSettings,
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
@@ -157,16 +126,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
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(
@@ -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<string, string>,
) {
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 [email protected]\\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<EffectAcpSchema.SessionConfigOption>;
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<EffectAcpSchema.SessionConfigOption>;
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<EffectAcpSchema.SessionConfigOption>;
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: "[email protected]",
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: "[email protected]",
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: "[email protected]",
}),
stderr: "",
}),
).toEqual({
version: "2026.04.09-f2b0fcd",
status: "ready",
auth: {
status: "authenticated",
email: "[email protected]",
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" },
]);
});
});
File diff suppressed because it is too large. Load diff
@@ -78,8 +78,6 @@ const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings =>
const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings => ({
enabled: false,
binaryPath: "agent",
apiEndpoint: "",
customModels: [],
...overrides,
});
@@ -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),
),
);
});
@@ -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");
});
});
@@ -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<UserInputQuestion> {
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 };
}
@@ -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<EffectAcpSchema.SessionConfigOption> = [
{
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" },
]);
});
});
@@ -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<CursorSettings, "apiEndpoint" | "binaryPath">;
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<unknown, EffectAcpErrors.AcpError>;
readonly setModel: (model: string) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
}
export function applyCursorAcpModelSelection<E>(input: {
readonly runtime: CursorAcpModelSelectionRuntime;
readonly model: string | null | undefined;
readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined;
readonly mapError: (context: CursorAcpModelSelectionErrorContext) => E;
}): Effect.Effect<void, E> {
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,
}),
),
);
}
});
}
@@ -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<Record<string, string>> = {
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),
}),
),
}),
};
}
@@ -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<string> }> = [];
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"],
},
]);
@@ -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, string>): 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<A, E, R>(
env: Record<string, string>,
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
) {
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<string> {
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<string, unknown> },
);
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();
}),
);
});
@@ -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 = <S extends Schema.Top>({
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<S["Type"], TextGenerationError, S["DecodingServices"]> =>
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"]);
});
+34
View File
@@ -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({});
-21
View File
@@ -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)),
});
@@ -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);