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 authored and maria-rcks committed 2026-08-03 11:45:07 -04:00
1 parent 0ccf9c60bd
commit bc40ae8d28
21 files changed
+515 -3175

No files matched your search

@@ -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,9 +1,7 @@
import * as Crypto from "effect/Crypto";
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";
@@ -22,27 +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 crypto = yield* Crypto.Crypto;
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,
@@ -50,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" },
}).pipe(Effect.provideService(Crypto.Crypto, crypto));
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(
@@ -111,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),
});
}
@@ -146,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,
}),
),
@@ -158,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"] =
@@ -259,10 +250,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"]);
});