Add Cursor text generation and model mapping

- route Cursor commit/PR/branch generation through the agent CLI
- resolve separate ACP and agent model IDs for Cursor models
- improve git action failure logging and surface command output
This commit is contained in:
Julius Marminge committed 2026-04-17 16:43:47 -07:00
1 parent dbcc55637b
commit 27174db68b
9 files changed
+482 -406

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
import { Schema } from "effect";
/**
* GitCommandError - Git command execution failed.
*/
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
}
}
/**
* GitHubCliError - GitHub CLI execution or authentication failed.
*/
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
}
/**
* TextGenerationError - Commit or PR text generation failed.
*/
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
"TextGenerationError",
{
operation: Schema.String,
detail: Schema.String,
commandOutput: Schema.optional(
Schema.Struct({
stdout: Schema.optional(Schema.String),
stderr: Schema.optional(Schema.String),
exitCode: Schema.optional(Schema.Number),
}),
),
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Text generation failed in ${this.operation}: ${this.detail}`;
}
}
/**
* GitManagerError - Stacked Git workflow orchestration failed.
*/
export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `Git manager failed in ${this.operation}: ${this.detail}`;
}
}
/**
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
*/
export type GitManagerServiceError =
| GitManagerError
| GitCommandError
| GitHubCliError
| TextGenerationError;
@@ -1,27 +1,13 @@
import * as path from "node:path";
import * as os from "node:os";
import { fileURLToPath } from "node:url";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { Effect, FileSystem, Layer, Path } from "effect";
import { expect } from "vitest";
import { ServerSettingsError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
@@ -32,98 +18,159 @@ const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
Layer.provideMerge(NodeServices.layer),
);
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
const binDir = path.join(dir, "bin");
const agentPath = path.join(binDir, "agent");
mkdirSync(binDir, { recursive: true });
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 bun ${JSON.stringify(mockAgentPath)}`,
"",
].join("\n"),
"utf8",
);
chmodSync(agentPath, 0o755);
return agentPath;
}
function withFakeAcpAgent<A, E, R>(
env: Record<string, string>,
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
function makeFakeAgentBinary(
dir: string,
input: {
result: string;
requireModel?: string;
requireTrust?: boolean;
requireMode?: string;
stdinMustContain?: string;
stderr?: string;
exitCode?: number;
},
) {
return Effect.gen(function* () {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
const agentPath = makeAcpAgentWrapper(tempDir, env);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = path.join(dir, "bin");
const agentPath = path.join(binDir, "agent");
yield* fs.makeDirectory(binDir, { recursive: true });
yield* serverSettings.updateSettings({
providers: {
cursor: {
binaryPath: agentPath,
},
},
});
return yield* effect.pipe(
Effect.ensuring(
serverSettings
.updateSettings({
providers: {
cursor: {
binaryPath: previousSettings.providers.cursor.binaryPath,
},
},
})
.pipe(
Effect.catch(() => Effect.void),
Effect.ensuring(
Effect.sync(() => {
rmSync(tempDir, { recursive: true, force: true });
}),
),
Effect.asVoid,
),
),
yield* fs.writeFileString(
agentPath,
[
"#!/bin/sh",
'model=""',
'seen_trust="0"',
'mode=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--model" ]; then',
" shift",
' model="$1"',
" shift",
" continue",
" fi",
' if [ "$1" = "--trust" ]; then',
' seen_trust="1"',
" shift",
" continue",
" fi",
' if [ "$1" = "--mode" ]; then',
" shift",
' mode="$1"',
" shift",
" continue",
" fi",
" shift",
"done",
'stdin_content="$(cat)"',
...(input.requireModel !== undefined
? [
`if [ "$model" != "${input.requireModel}" ]; then`,
' printf "%s\\n" "unexpected model: $model" >&2',
" exit 11",
"fi",
]
: []),
...(input.requireTrust
? [
'if [ "$seen_trust" != "1" ]; then',
' printf "%s\\n" "missing --trust" >&2',
" exit 12",
"fi",
]
: []),
...(input.requireMode !== undefined
? [
`if [ "$mode" != "${input.requireMode}" ]; then`,
' printf "%s\\n" "unexpected mode: $mode" >&2',
" exit 13",
"fi",
]
: []),
...(input.stdinMustContain !== undefined
? [
`if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 14",
"fi",
]
: []),
...(input.stderr !== undefined
? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`]
: []),
"cat <<'__T3CODE_FAKE_AGENT_OUTPUT__'",
JSON.stringify({
type: "result",
subtype: "success",
is_error: false,
result: input.result,
}),
"__T3CODE_FAKE_AGENT_OUTPUT__",
`exit ${input.exitCode ?? 0}`,
"",
].join("\n"),
);
yield* fs.chmod(agentPath, 0o755);
return agentPath;
});
}
function waitForFileContent(path: string): Effect.Effect<string> {
return Effect.promise(async () => {
const deadline = Date.now() + 5_000;
for (;;) {
try {
return readFileSync(path, "utf8");
} catch (error) {
if (Date.now() >= deadline) {
throw error instanceof Error ? error : new Error(String(error));
}
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
});
function withFakeAgentEnv<A, E, R>(
input: {
result: string;
requireModel?: string;
requireTrust?: boolean;
requireMode?: string;
stdinMustContain?: string;
stderr?: string;
exitCode?: number;
},
effect: Effect.Effect<A, E, R>,
) {
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-cursor-text-" });
const agentPath = yield* makeFakeAgentBinary(tempDir, input);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
cursor: {
binaryPath: agentPath,
},
},
});
return { serverSettings, previousBinaryPath: previousSettings.providers.cursor.binaryPath };
}),
() => effect,
({ serverSettings, previousBinaryPath }) =>
serverSettings
.updateSettings({
providers: {
cursor: {
binaryPath: previousBinaryPath,
},
},
})
.pipe(Effect.asVoid),
);
}
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
return withFakeAcpAgent(
it.effect("uses agent CLI model ids instead of ACP bracket notation for commit messages", () =>
withFakeAgentEnv(
{
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
result: JSON.stringify({
subject: "Add generated commit message",
body: "- verify cursor acp model config path",
body: "- verify agent model mapping",
}),
requireModel: "composer-2-fast",
requireTrust: true,
requireMode: "ask",
stdinMustContain: "Staged patch:",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
@@ -136,84 +183,25 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
provider: "cursor",
model: "gpt-5.4",
options: {
reasoning: "xhigh",
fastMode: true,
contextWindow: "1m",
},
model: "composer-2",
options: { fastMode: true },
},
});
expect(generated.subject).toBe("Add generated commit message");
expect(generated.body).toBe("- verify cursor acp model config path");
const requests = 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:"),
}),
]),
);
rmSync(requestLogDir, { recursive: true, force: true });
expect(generated.body).toBe("- verify agent model mapping");
}),
);
});
),
);
it.effect("accepts json objects with extra assistant text around them", () =>
withFakeAcpAgent(
it.effect("accepts json objects with extra text around them from agent output", () =>
withFakeAgentEnv(
{
T3_ACP_PROMPT_RESPONSE_TEXT:
result:
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
requireModel: "composer-2",
requireTrust: true,
requireMode: "ask",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
@@ -234,65 +222,4 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
}),
),
);
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."',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Fix the reconnect spinner after a resumed session.",
modelSelection: {
provider: "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 = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
const exitLogPath = path.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: "",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-runtime-close",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Close runtime after generation");
const exitLog = yield* waitForFileContent(exitLogPath);
expect(exitLog).toContain("exit:0");
rmSync(exitLogDir, { recursive: true, force: true });
}),
);
});
});
+126 -128
View File
@@ -1,30 +1,29 @@
import { Effect, Layer, Option, Ref, Schema } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { CursorModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import {
type ThreadTitleGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
import { TextGenerationError } from "../Errors.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import { sanitizeCommitSubject, sanitizePrTitle, sanitizeThreadTitle } from "../Utils.ts";
import {
applyCursorAcpModelSelection,
makeCursorAcpRuntime,
} from "../../provider/acp/CursorAcpSupport.ts";
import { normalizeCliError, sanitizeCommitSubject, sanitizePrTitle } from "../Utils.ts";
import { resolveCursorAgentModel } from "../../provider/Layers/CursorProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const CURSOR_TIMEOUT_MS = 180_000;
const CursorOutputEnvelope = Schema.Struct({
type: Schema.String,
subtype: Schema.optional(Schema.String),
is_error: Schema.optional(Schema.Boolean),
result: Schema.optional(Schema.String),
});
function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
@@ -73,35 +72,25 @@ function extractJsonObject(raw: string): string {
return trimmed.slice(start);
}
function mapCursorAcpError(
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
detail: string,
cause: unknown,
): TextGenerationError {
return new TextGenerationError({
operation,
detail,
...(cause !== undefined ? { cause } : {}),
});
}
function isTextGenerationError(error: unknown): error is TextGenerationError {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
error._tag === "TextGenerationError"
);
}
const makeCursorTextGeneration = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverSettingsService = yield* Effect.service(ServerSettingsService);
const readStreamAsString = <E>(
operation: string,
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, TextGenerationError> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
Effect.mapError((cause) =>
normalizeCliError("agent", operation, cause, "Failed to collect process output"),
),
);
const runCursorJson = <S extends Schema.Top>({
operation,
cwd,
@@ -109,11 +98,7 @@ const makeCursorTextGeneration = Effect.gen(function* () {
outputSchemaJson,
modelSelection,
}: {
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
cwd: string;
prompt: string;
outputSchemaJson: S;
@@ -125,47 +110,75 @@ const makeCursorTextGeneration = Effect.gen(function* () {
(settings) => settings.providers.cursor,
).pipe(Effect.catch(() => Effect.undefined));
const outputRef = yield* Ref.make("");
const runtime = yield* makeCursorAcpRuntime({
cursorSettings,
childProcessSpawner: commandSpawner,
cwd,
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
});
const runCursorCommand = Effect.gen(function* () {
const command = ChildProcess.make(
cursorSettings?.binaryPath || "agent",
[
"-p",
"--trust",
"--mode",
"ask",
"--output-format",
"json",
"--model",
resolveCursorAgentModel(modelSelection.model, modelSelection.options),
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
);
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,
modelOptions: modelSelection.options,
mapError: ({ cause, configId, step }) =>
mapCursorAcpError(
operation,
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,
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("agent", operation, cause, "Failed to spawn Cursor Agent process"),
),
});
);
return yield* runtime.prompt({
prompt: [{ type: "text", text: prompt }],
});
}).pipe(
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError(
"agent",
operation,
cause,
"Failed to read Cursor Agent exit code",
),
),
),
],
{ concurrency: "unbounded" },
);
const commandOutput = { stdout, stderr, exitCode };
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
commandOutput,
detail:
detail.length > 0
? `Cursor Agent command failed: ${detail}`
: `Cursor Agent command failed with code ${exitCode}.`,
});
}
return commandOutput;
});
const commandOutput = yield* runCursorCommand.pipe(
Effect.scoped,
Effect.timeoutOption(CURSOR_TIMEOUT_MS),
Effect.flatMap(
Option.match({
@@ -179,21 +192,41 @@ const makeCursorTextGeneration = Effect.gen(function* () {
onSome: (value) => Effect.succeed(value),
}),
),
Effect.mapError((cause) =>
isTextGenerationError(cause)
? cause
: mapCursorAcpError(operation, "Cursor ACP request failed.", cause),
);
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(CursorOutputEnvelope))(
commandOutput.stdout,
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Cursor Agent returned unexpected output format.",
commandOutput,
cause,
}),
),
),
);
const rawResult = (yield* Ref.get(outputRef)).trim();
if (
envelope.type !== "result" ||
envelope.subtype !== "success" ||
envelope.is_error === true
) {
return yield* new TextGenerationError({
operation,
detail: "Cursor Agent returned an unsuccessful result.",
commandOutput,
});
}
const rawResult = envelope.result?.trim();
if (!rawResult) {
return yield* new TextGenerationError({
operation,
detail:
promptResult.stopReason === "cancelled"
? "Cursor ACP request was cancelled."
: "Cursor Agent returned empty output.",
detail: "Cursor Agent returned empty output.",
commandOutput,
});
}
@@ -206,18 +239,12 @@ const makeCursorTextGeneration = Effect.gen(function* () {
operation,
detail: "Cursor Agent returned invalid structured output.",
cause,
commandOutput,
}),
),
),
);
}).pipe(
Effect.mapError((cause) =>
isTextGenerationError(cause)
? cause
: mapCursorAcpError(operation, "Cursor ACP text generation failed.", cause),
),
Effect.scoped,
);
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"CursorTextGeneration.generateCommitMessage",
@@ -313,39 +340,10 @@ const makeCursorTextGeneration = Effect.gen(function* () {
};
});
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"CursorTextGeneration.generateThreadTitle",
)(function* (input) {
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generateThreadTitle",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizeThreadTitle(generated.title),
} satisfies ThreadTitleGenerationResult;
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
} satisfies TextGenerationShape;
});
+8 -7
View File
@@ -1703,16 +1703,17 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return result;
});
return yield* runAction().pipe(
Effect.ensuring(invalidateStatus(input.cwd)),
Effect.tapError((error) =>
Effect.flatMap(Ref.get(currentPhase), (phase) =>
progress.emit({
return yield* runAction.pipe(
Effect.catch((error) =>
Effect.gen(function* () {
yield* Effect.logError("Failed to run action:", error);
yield* progress.emit({
kind: "action_failed",
phase: Option.getOrNull(phase),
message: error.message,
}),
),
});
return yield* Effect.fail(error);
}),
),
);
},
@@ -19,7 +19,6 @@ import {
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
// ---------------------------------------------------------------------------
// Internal service tags so both concrete layers can coexist.
@@ -33,14 +32,10 @@ class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
class CursorTextGen extends ServiceMap.Service<CursorTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
) {}
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",
) {}
// ---------------------------------------------------------------------------
// Routing implementation
// ---------------------------------------------------------------------------
@@ -49,16 +44,14 @@ const makeRoutingTextGeneration = Effect.gen(function* () {
const codex = yield* CodexTextGen;
const claude = yield* ClaudeTextGen;
const cursor = yield* CursorTextGen;
const openCode = yield* OpenCodeTextGen;
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
provider === "claudeAgent"
? claude
: provider === "opencode"
? openCode
: provider === "cursor"
? cursor
: codex;
const providerToService = {
codex,
claudeAgent: claude,
cursor,
};
const route = (provider: TextGenerationProvider) => providerToService[provider];
return {
generateCommitMessage: (input) =>
@@ -93,14 +86,6 @@ const InternalCursorLayer = Layer.effect(
}),
).pipe(Layer.provide(CursorTextGenerationLive));
const InternalOpenCodeLayer = Layer.effect(
OpenCodeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(OpenCodeTextGenerationLive));
export const RoutingTextGenerationLive = Layer.effect(
TextGeneration,
makeRoutingTextGeneration,
@@ -108,5 +93,4 @@ export const RoutingTextGenerationLive = Layer.effect(
Layer.provide(InternalCodexLayer),
Layer.provide(InternalClaudeLayer),
Layer.provide(InternalCursorLayer),
Layer.provide(InternalOpenCodeLayer),
);
@@ -13,7 +13,7 @@ import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { makeCursorAdapterLive } from "./CursorAdapter.ts";
import { resolveCursorDispatchModel } from "./CursorProvider.ts";
import { resolveCursorAcpModelId } from "./CursorProvider.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.mjs");
@@ -169,7 +169,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect("selects the Cursor model via CLI argv instead of ACP request payloads", () =>
it.effect("selects the Cursor model via ACP config updates instead of CLI argv", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
@@ -183,7 +183,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
);
yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const dispatchedModel = resolveCursorDispatchModel("composer-2", { fastMode: true });
const dispatchedModel = resolveCursorAcpModelId("composer-2", { fastMode: true });
const session = yield* adapter.startSession({
threadId,
provider: "cursor",
@@ -198,11 +198,12 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
threadId,
input: "probe model selection",
attachments: [],
modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: true } },
});
yield* adapter.stopSession(threadId);
const argvRuns = yield* Effect.promise(() => readArgvLog(argvLogPath));
assert.deepStrictEqual(argvRuns, [["--model", dispatchedModel, "acp"]]);
assert.deepStrictEqual(argvRuns, [["acp"]]);
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const methods = requests
@@ -223,6 +224,15 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}
}
const setConfigRequests = requests.filter(
(entry) => entry.method === "session/set_config_option",
);
assert.isAbove(setConfigRequests.length, 0, "should call session/set_config_option");
assert.equal(
(setConfigRequests[setConfigRequests.length - 1]?.params as Record<string, unknown>)?.value,
dispatchedModel,
);
const promptRequest = requests.find((entry) => entry.method === "session/prompt");
assert.isDefined(promptRequest);
assert.deepStrictEqual(
@@ -465,13 +475,17 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
const argvRuns = yield* Effect.promise(() => readArgvLog(argvLogPath));
assert.lengthOf(argvRuns, 1, "session should not restart — only one spawn");
assert.deepStrictEqual(argvRuns[0], ["--model", "composer-2[fast=false]", "acp"]);
assert.deepStrictEqual(argvRuns[0], ["acp"]);
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const setConfigRequests = requests.filter(
(entry) => entry.method === "session/set_config_option",
);
assert.isAbove(setConfigRequests.length, 0, "should call session/set_config_option");
assert.equal(
(setConfigRequests[0]?.params as Record<string, unknown>)?.value,
"composer-2[fast=false]",
);
const lastSetConfig = setConfigRequests[setConfigRequests.length - 1];
assert.equal(
(lastSetConfig?.params as Record<string, unknown>)?.value,
@@ -56,7 +56,7 @@ import {
import type { AcpInboundMessage } from "../acp/AcpTypes.ts";
import { AcpProcessExitedError, AcpRpcError, type AcpError } from "../acp/AcpErrors.ts";
import { CursorAdapter, type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { resolveCursorDispatchModel } from "./CursorProvider.ts";
import { resolveCursorAcpModelId } from "./CursorProvider.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "cursor" as const;
@@ -1285,7 +1285,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
const turnId = TurnId.makeUnsafe(crypto.randomUUID());
const turnModelSelection =
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
const model = resolveCursorDispatchModel(
const model = resolveCursorAcpModelId(
turnModelSelection?.model ?? ctx.session.model,
turnModelSelection?.options,
);
@@ -1,36 +1,38 @@
import { describe, expect, it } from "vitest";
import { getCursorModelCapabilities, resolveCursorDispatchModel } from "./CursorProvider.ts";
import {
getCursorModelCapabilities,
resolveCursorAgentModel,
resolveCursorAcpModelId,
} from "./CursorProvider.ts";
describe("resolveCursorDispatchModel", () => {
describe("resolveCursorAcpModelId", () => {
it("builds bracket notation from canonical base slugs and capabilities", () => {
expect(resolveCursorDispatchModel("composer-2", { fastMode: true })).toBe(
"composer-2[fast=true]",
);
expect(resolveCursorDispatchModel("gpt-5.4", undefined)).toBe(
expect(resolveCursorAcpModelId("composer-2", { fastMode: true })).toBe("composer-2[fast=true]");
expect(resolveCursorAcpModelId("gpt-5.4", undefined)).toBe(
"gpt-5.4[reasoning=medium,context=272k,fast=false]",
);
expect(
resolveCursorDispatchModel("claude-opus-4-6", {
resolveCursorAcpModelId("claude-opus-4-6", {
reasoning: "high",
thinking: true,
contextWindow: "1m",
}),
).toBe("claude-opus-4-6[effort=high,thinking=true,context=1m]");
).toBe("claude-opus-4-6[effort=high,thinking=true,context=1m,fast=false]");
});
it("maps legacy cursor aliases onto the canonical base slug", () => {
expect(resolveCursorDispatchModel("gpt-5.4-1m", undefined)).toBe(
expect(resolveCursorAcpModelId("gpt-5.4-1m", undefined)).toBe(
"gpt-5.4[reasoning=medium,context=272k,fast=false]",
);
expect(resolveCursorDispatchModel("auto", undefined)).toBe("default[]");
expect(resolveCursorDispatchModel("claude-4.6-opus", undefined)).toBe(
"claude-opus-4-6[effort=high,thinking=true,context=200k]",
expect(resolveCursorAcpModelId("auto", undefined)).toBe("default[]");
expect(resolveCursorAcpModelId("claude-4.6-opus", undefined)).toBe(
"claude-opus-4-6[effort=high,thinking=true,context=200k,fast=false]",
);
});
it("passes custom models through unchanged", () => {
expect(resolveCursorDispatchModel("custom/internal-model", undefined)).toBe(
expect(resolveCursorAcpModelId("custom/internal-model", undefined)).toBe(
"custom/internal-model[]",
);
});
@@ -45,3 +47,30 @@ describe("getCursorModelCapabilities", () => {
expect(getCursorModelCapabilities("claude-opus-4-6").supportsThinkingToggle).toBe(true);
});
});
describe("resolveCursorAgentModel", () => {
it("maps canonical base slugs onto agent CLI model ids", () => {
expect(resolveCursorAgentModel("composer-2", { fastMode: true })).toBe("composer-2-fast");
expect(resolveCursorAgentModel("gpt-5.3-codex", { reasoning: "xhigh" })).toBe(
"gpt-5.3-codex-xhigh",
);
expect(
resolveCursorAgentModel("gpt-5.4", {
reasoning: "medium",
fastMode: true,
contextWindow: "272k",
}),
).toBe("gpt-5.4-medium-fast");
expect(resolveCursorAgentModel("claude-opus-4-6", { thinking: true })).toBe(
"claude-4.6-opus-high-thinking",
);
expect(resolveCursorAgentModel("auto", undefined)).toBe("auto");
});
it("passes custom agent model ids through unchanged", () => {
expect(resolveCursorAgentModel("gpt-5.4-mini-medium", undefined)).toBe("gpt-5.4-mini-medium");
expect(resolveCursorAgentModel("custom/internal-model", undefined)).toBe(
"custom/internal-model",
);
});
});
@@ -182,7 +182,10 @@ export function getCursorModelCapabilities(model: string | null | undefined): Mo
);
}
export function resolveCursorDispatchModel(
/**
* Resolve the ACP model ID for a Cursor model to be sent to session/set_config_option
*/
export function resolveCursorAcpModelId(
model: string | null | undefined,
modelOptions: CursorModelOptions | null | undefined,
): string {
@@ -219,6 +222,52 @@ export function resolveCursorDispatchModel(
return `${slug}[${traits.join(",")}]`;
}
/**
* Resolve the Agent CLI model ID for a Cursor model to be set as `--model` arg for the `agent` command.
*
* Yes... Cursor uses different IDs. No... I don't know why.
*/
export function resolveCursorAgentModel(
model: string | null | undefined,
modelOptions: CursorModelOptions | null | undefined,
): string {
const normalized = normalizeModelSlug(model, "cursor") ?? "default";
const slug = normalized.includes("[") ? normalized.slice(0, normalized.indexOf("[")) : normalized;
const caps = getCursorModelCapabilities(slug);
const reasoning = resolveEffort(caps, modelOptions?.reasoning);
const thinking = caps.supportsThinkingToggle ? (modelOptions?.thinking ?? true) : undefined;
const fastMode = modelOptions?.fastMode === true;
switch (slug) {
case "default":
return "auto";
case "composer-2":
return fastMode ? "composer-2-fast" : "composer-2";
case "composer-1.5":
return "composer-1.5";
case "gpt-5.3-codex": {
const suffix = reasoning && reasoning !== "medium" ? `-${reasoning}` : "";
return `gpt-5.3-codex${suffix}${fastMode ? "-fast" : ""}`;
}
case "gpt-5.3-codex-spark": {
const suffix = reasoning && reasoning !== "medium" ? `-${reasoning}` : "";
return `gpt-5.3-codex-spark-preview${suffix}`;
}
case "gpt-5.4":
return `gpt-5.4-${reasoning ?? "medium"}${fastMode ? "-fast" : ""}`;
case "claude-opus-4-6":
return thinking ? "claude-4.6-opus-high-thinking" : "claude-4.6-opus-high";
case "claude-sonnet-4-6":
return thinking ? "claude-4.6-sonnet-medium-thinking" : "claude-4.6-sonnet-medium";
case "gemini-3.1-pro":
return "gemini-3.1-pro";
case "grok-4-20":
return thinking ? "grok-4-20-thinking" : "grok-4-20";
default:
return slug === "default" ? "auto" : slug;
}
}
/** Timeout for `agent about` — it's slower than a simple `--version` probe. */
const ABOUT_TIMEOUT_MS = 8_000;