Handle cancelled Cursor ACP turns and simplify model ids

- propagate session cancel into pending ACP approvals
- emit cancelled turn state when interruptions resolve as cancelled
- stop adding default ACP config traits for built-in Cursor models
This commit is contained in:
Julius Marminge committed 2026-04-17 16:44:48 -07:00
1 parent 85905d5da2
commit b965cc168f
16 files changed
+427 -539

No files matched your search

+19 -1
View File
@@ -54,6 +54,7 @@ const availableModes = [
},
];
const pendingPermissionRequests = new Map();
const cancelledPromptRequestIds = new Set<number | string>();
function send(obj: unknown) {
process.stdout.write(`${JSON.stringify(obj)}\n`);
@@ -102,6 +103,17 @@ rl.on("line", (line) => {
if (method === undefined && id !== undefined && pendingPermissionRequests.has(id)) {
const pending = pendingPermissionRequests.get(id);
pendingPermissionRequests.delete(id);
const outcome = (rpcMessage.params?.outcome ??
(msg as { result?: { outcome?: unknown } }).result?.outcome) as
| { outcome?: unknown }
| undefined;
const cancelled =
cancelledPromptRequestIds.has(pending.promptRequestId) ||
(typeof outcome === "object" &&
outcome !== null &&
"outcome" in outcome &&
outcome.outcome === "cancelled");
cancelledPromptRequestIds.delete(pending.promptRequestId);
sendSessionUpdate(
{
sessionUpdate: "tool_call_update",
@@ -127,7 +139,7 @@ rl.on("line", (line) => {
send({
jsonrpc: "2.0",
id: pending.promptRequestId,
result: { stopReason: "end_turn" },
result: { stopReason: cancelled ? "cancelled" : "end_turn" },
});
return;
}
@@ -331,6 +343,12 @@ rl.on("line", (line) => {
}
if (method === AGENT_METHODS.session_cancel) {
const cancelledSessionId = rpcMessage.params?.sessionId;
for (const pending of pendingPermissionRequests.values()) {
if (pending.sessionId === cancelledSessionId) {
cancelledPromptRequestIds.add(pending.promptRequestId);
}
}
if (id !== undefined) {
send({ jsonrpc: "2.0", id, result: null });
}
@@ -13,7 +13,6 @@ import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { makeCursorAdapterLive } from "./CursorAdapter.ts";
import { resolveCursorAcpModelId } from "./CursorProvider.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
@@ -77,7 +76,11 @@ async function readJsonLines(filePath: string) {
const cursorAdapterTestLayer = it.layer(
makeCursorAdapterLive().pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-adapter-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
);
@@ -167,86 +170,6 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
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;
const threadId = ThreadId.makeUnsafe("cursor-model-probe");
const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
const requestLogPath = path.join(tempDir, "requests.ndjson");
const argvLogPath = path.join(tempDir, "argv.txt");
yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
const wrapperPath = yield* Effect.promise(() =>
makeProbeWrapper(requestLogPath, argvLogPath),
);
yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const dispatchedModel = resolveCursorAcpModelId("composer-2", { fastMode: true });
const session = yield* adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: true } },
});
assert.equal(session.model, "composer-2");
yield* adapter.sendTurn({
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, [["acp"]]);
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const methods = requests
.map((entry) => entry.method)
.filter((method): method is string => typeof method === "string");
assert.includeMembers(methods, [
"initialize",
"authenticate",
"session/new",
"session/set_mode",
"session/prompt",
]);
for (const request of requests) {
const params = request.params;
if (params && typeof params === "object" && !Array.isArray(params)) {
assert.isFalse(Object.prototype.hasOwnProperty.call(params, "model"));
}
}
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(
Object.keys((promptRequest?.params as Record<string, unknown>) ?? {}).toSorted(),
["prompt", "sessionId"],
);
const modeRequest = requests.find((entry) => entry.method === "session/set_mode");
assert.isDefined(modeRequest);
assert.deepStrictEqual(modeRequest?.params, {
sessionId: "mock-session-1",
modeId: "code",
});
}),
);
it.effect("maps app plan mode onto the ACP plan session mode", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
@@ -436,6 +359,96 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
),
);
it.effect("cancels pending ACP approvals and marks the turn cancelled when interrupted", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.makeUnsafe("cursor-cancel-probe");
const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
const requestLogPath = path.join(tempDir, "requests.ndjson");
const argvLogPath = path.join(tempDir, "argv.txt");
yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
const wrapperPath = yield* Effect.promise(() =>
makeProbeWrapper(requestLogPath, argvLogPath, { T3_ACP_EMIT_TOOL_CALLS: "1" }),
);
yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const requestResolvedReady = yield* Deferred.make<ProviderRuntimeEvent>();
const turnCompletedReady = yield* Deferred.make<ProviderRuntimeEvent>();
let interrupted = false;
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.gen(function* () {
if (String(event.threadId) !== String(threadId)) {
return;
}
if (event.type === "request.opened" && !interrupted) {
interrupted = true;
yield* adapter.interruptTurn(threadId);
return;
}
if (event.type === "request.resolved") {
yield* Deferred.succeed(requestResolvedReady, event).pipe(Effect.ignore);
return;
}
if (event.type === "turn.completed") {
yield* Deferred.succeed(turnCompletedReady, event).pipe(Effect.ignore);
}
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
});
const sendTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "cancel this turn",
attachments: [],
})
.pipe(Effect.forkChild);
const requestResolved = yield* Deferred.await(requestResolvedReady);
const turnCompleted = yield* Deferred.await(turnCompletedReady);
yield* Fiber.join(sendTurnFiber);
yield* Fiber.interrupt(runtimeEventsFiber);
assert.equal(requestResolved.type, "request.resolved");
if (requestResolved.type === "request.resolved") {
assert.equal(requestResolved.payload.decision, "cancel");
}
assert.equal(turnCompleted.type, "turn.completed");
if (turnCompleted.type === "turn.completed") {
assert.equal(turnCompleted.payload.state, "cancelled");
assert.equal(turnCompleted.payload.stopReason, "cancelled");
}
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
assert.isTrue(
requests.some(
(entry) =>
!("method" in entry) &&
typeof entry.result === "object" &&
entry.result !== null &&
"outcome" in entry.result &&
typeof entry.result.outcome === "object" &&
entry.result.outcome !== null &&
"outcome" in entry.result.outcome &&
entry.result.outcome.outcome === "cancelled",
),
);
yield* adapter.stopSession(threadId);
}),
);
it.effect("switches model in-session via session/set_config_option", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
@@ -480,10 +493,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
(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]",
);
assert.equal((setConfigRequests[0]?.params as Record<string, unknown>)?.value, "composer-2");
const lastSetConfig = setConfigRequests[setConfigRequests.length - 1];
assert.equal(
(lastSetConfig?.params as Record<string, unknown>)?.value,
+220 -45
View File
@@ -8,6 +8,8 @@ import * as nodePath from "node:path";
import {
ApprovalRequestId,
EventId,
RuntimeItemId,
type ToolLifecycleItemType,
type ProviderApprovalDecision,
type ProviderInteractionMode,
type ProviderRuntimeEvent,
@@ -43,18 +45,11 @@ import {
ProviderAdapterValidationError,
} from "../Errors.ts";
import { makeAcpSessionRuntime, type AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
import {
acpPermissionOutcome,
makeAcpContentDeltaEvent,
makeAcpPlanUpdatedEvent,
makeAcpRequestOpenedEvent,
makeAcpRequestResolvedEvent,
makeAcpToolCallEvent,
mapAcpToAdapterError,
} from "../acp/AcpAdapterSupport.ts";
import { acpPermissionOutcome, mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
import {
type AcpSessionMode,
type AcpSessionModeState,
type AcpToolCallState,
parsePermissionRequest,
} from "../acp/AcpRuntimeModel.ts";
import { makeAcpNativeLoggers } from "../acp/AcpNativeLogging.ts";
@@ -75,6 +70,7 @@ const CURSOR_RESUME_VERSION = 1 as const;
const ACP_PLAN_MODE_ALIASES = ["plan", "architect"];
const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"];
const ACP_APPROVAL_MODE_ALIASES = ["ask"];
type AcpRawSource = "acp.jsonrpc" | "acp.cursor.extension";
export interface CursorAdapterLiveOptions {
readonly nativeEventLogPath?: string;
@@ -83,11 +79,7 @@ export interface CursorAdapterLiveOptions {
interface PendingApproval {
readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
readonly requestType:
| "exec_command_approval"
| "file_read_approval"
| "file_change_approval"
| "unknown";
readonly kind: string | "unknown";
}
interface PendingUserInput {
@@ -107,6 +99,19 @@ interface CursorSessionContext {
stopped: boolean;
}
function settlePendingApprovalsAsCancelled(
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
): Effect.Effect<void> {
const pendingEntries = Array.from(pendingApprovals.values());
return Effect.forEach(
pendingEntries,
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
{
discard: true,
},
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -118,13 +123,6 @@ function parseCursorResume(raw: unknown): { sessionId: string } | undefined {
return { sessionId: raw.sessionId.trim() };
}
function toMessage(cause: unknown, fallback: string): string {
if (cause instanceof Error && cause.message.length > 0) {
return cause.message;
}
return fallback;
}
function normalizeModeSearchText(mode: AcpSessionMode): string {
return [mode.id, mode.name, mode.description]
.filter((value): value is string => typeof value === "string" && value.length > 0)
@@ -162,6 +160,55 @@ function isPlanMode(mode: AcpSessionMode): boolean {
return findModeByAliases([mode], ACP_PLAN_MODE_ALIASES) !== undefined;
}
function canonicalRequestTypeFromAcpKind(
kind: string | "unknown",
): "exec_command_approval" | "file_read_approval" | "file_change_approval" | "unknown" {
switch (kind) {
case "execute":
return "exec_command_approval";
case "read":
return "file_read_approval";
case "edit":
case "delete":
case "move":
return "file_change_approval";
default:
return "unknown";
}
}
function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
switch (kind) {
case "execute":
return "command_execution";
case "edit":
case "delete":
case "move":
return "file_change";
case "search":
case "fetch":
return "web_search";
default:
return "dynamic_tool_call";
}
}
function runtimeItemStatusFromAcpToolStatus(
status: AcpToolCallState["status"],
): "inProgress" | "completed" | "failed" | undefined {
switch (status) {
case "pending":
case "inProgress":
return "inProgress";
case "completed":
return "completed";
case "failed":
return "failed";
default:
return undefined;
}
}
function resolveRequestedModeId(input: {
readonly interactionMode: ProviderInteractionMode | undefined;
readonly runtimeMode: RuntimeMode;
@@ -217,6 +264,140 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
const makeRequestOpenedEvent = (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly requestId: RuntimeRequestId;
readonly kind: string | "unknown";
readonly detail: string;
readonly args: unknown;
readonly source: AcpRawSource;
readonly method: string;
readonly rawPayload: unknown;
}): Effect.Effect<ProviderRuntimeEvent> =>
Effect.map(makeEventStamp(), (stamp) => ({
type: "request.opened",
...stamp,
provider: PROVIDER,
threadId: input.threadId,
turnId: input.turnId,
requestId: input.requestId,
payload: {
requestType: canonicalRequestTypeFromAcpKind(input.kind),
detail: input.detail,
args: input.args,
},
raw: {
source: input.source,
method: input.method,
payload: input.rawPayload,
},
}));
const makeRequestResolvedEvent = (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly requestId: RuntimeRequestId;
readonly kind: string | "unknown";
readonly decision: ProviderApprovalDecision;
}): Effect.Effect<ProviderRuntimeEvent> =>
Effect.map(makeEventStamp(), (stamp) => ({
type: "request.resolved",
...stamp,
provider: PROVIDER,
threadId: input.threadId,
turnId: input.turnId,
requestId: input.requestId,
payload: {
requestType: canonicalRequestTypeFromAcpKind(input.kind),
decision: input.decision,
},
}));
const makePlanUpdatedEvent = (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly payload: {
readonly explanation?: string | null;
readonly plan: ReadonlyArray<{
readonly step: string;
readonly status: "pending" | "inProgress" | "completed";
}>;
};
readonly source: AcpRawSource;
readonly method: string;
readonly rawPayload: unknown;
}): Effect.Effect<ProviderRuntimeEvent> =>
Effect.map(makeEventStamp(), (stamp) => ({
type: "turn.plan.updated",
...stamp,
provider: PROVIDER,
threadId: input.threadId,
turnId: input.turnId,
payload: input.payload,
raw: {
source: input.source,
method: input.method,
payload: input.rawPayload,
},
}));
const makeToolCallRuntimeEvent = (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly toolCall: AcpToolCallState;
readonly rawPayload: unknown;
}): Effect.Effect<ProviderRuntimeEvent> =>
Effect.map(makeEventStamp(), (stamp) => {
const runtimeStatus = runtimeItemStatusFromAcpToolStatus(input.toolCall.status);
return {
type:
input.toolCall.status === "completed" || input.toolCall.status === "failed"
? "item.completed"
: "item.updated",
...stamp,
provider: PROVIDER,
threadId: input.threadId,
turnId: input.turnId,
itemId: RuntimeItemId.makeUnsafe(input.toolCall.toolCallId),
payload: {
itemType: canonicalItemTypeFromAcpToolKind(input.toolCall.kind),
...(runtimeStatus ? { status: runtimeStatus } : {}),
...(input.toolCall.title ? { title: input.toolCall.title } : {}),
...(input.toolCall.detail ? { detail: input.toolCall.detail } : {}),
...(Object.keys(input.toolCall.data).length > 0 ? { data: input.toolCall.data } : {}),
},
raw: {
source: "acp.jsonrpc",
method: "session/update",
payload: input.rawPayload,
},
} satisfies ProviderRuntimeEvent;
});
const makeContentDeltaEvent = (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly text: string;
readonly rawPayload: unknown;
}): Effect.Effect<ProviderRuntimeEvent> =>
Effect.map(makeEventStamp(), (stamp) => ({
type: "content.delta",
...stamp,
provider: PROVIDER,
threadId: input.threadId,
turnId: input.turnId,
payload: {
streamKind: "assistant_text",
delta: input.text,
},
raw: {
source: "acp.jsonrpc",
method: "session/update",
payload: input.rawPayload,
},
}));
const logNative = (
threadId: ThreadId,
method: string,
@@ -263,9 +444,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
}
ctx.lastPlanFingerprint = fingerprint;
yield* offerRuntimeEvent(
makeAcpPlanUpdatedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
yield* makePlanUpdatedEvent({
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
payload,
@@ -472,16 +651,14 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, {
decision,
requestType: permissionRequest.requestType,
kind: permissionRequest.kind,
});
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
yield* makeRequestOpenedEvent({
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
requestType: permissionRequest.requestType,
kind: permissionRequest.kind,
detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
args: params,
source: "acp.jsonrpc",
@@ -492,21 +669,22 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
yield* makeRequestResolvedEvent({
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
requestType: permissionRequest.requestType,
kind: permissionRequest.kind,
decision: resolved,
}),
);
return {
outcome: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}),
},
@@ -571,9 +749,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
case "ToolCallUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
yield* offerRuntimeEvent(
makeAcpToolCallEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
yield* makeToolCallRuntimeEvent({
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
toolCall: event.toolCall,
@@ -584,9 +760,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
case "ContentDelta":
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
yield* offerRuntimeEvent(
makeAcpContentDeltaEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
yield* makeContentDeltaEvent({
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
text: event.text,
@@ -702,7 +876,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: toMessage(cause, "Failed to read attachment."),
detail: cause.message,
cause,
}),
),
@@ -748,7 +922,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
threadId: input.threadId,
turnId,
payload: {
state: "completed",
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
@@ -763,6 +937,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* Effect.ignore(
ctx.acp.cancel.pipe(
Effect.mapError((error) =>
@@ -7,33 +7,30 @@ import {
} from "./CursorProvider.ts";
describe("resolveCursorAcpModelId", () => {
it("builds bracket notation from canonical base slugs and capabilities", () => {
it("emits ACP model ids that match explicit Cursor ACP config values", () => {
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(resolveCursorAcpModelId("gpt-5.4", undefined)).toBe("gpt-5.4");
expect(
resolveCursorAcpModelId("claude-opus-4-6", {
reasoning: "high",
thinking: true,
contextWindow: "1m",
}),
).toBe("claude-opus-4-6[effort=high,thinking=true,context=1m,fast=false]");
).toBe("claude-opus-4-6[effort=high,thinking=true,context=1m]");
expect(resolveCursorAcpModelId("gpt-5.3-codex", undefined)).toBe(
"gpt-5.3-codex[reasoning=medium,fast=false]",
);
});
it("maps legacy cursor aliases onto the canonical base slug", () => {
expect(resolveCursorAcpModelId("gpt-5.4-1m", undefined)).toBe(
"gpt-5.4[reasoning=medium,context=272k,fast=false]",
);
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]",
);
expect(resolveCursorAcpModelId("gpt-5.4-1m", undefined)).toBe("gpt-5.4");
expect(resolveCursorAcpModelId("auto", undefined)).toBe("auto[]");
expect(resolveCursorAcpModelId("claude-4.6-opus", undefined)).toBe("claude-opus-4-6");
});
it("passes custom models through unchanged", () => {
expect(resolveCursorAcpModelId("custom/internal-model", undefined)).toBe(
"custom/internal-model[]",
"custom/internal-model",
);
});
});
@@ -189,37 +189,48 @@ export function resolveCursorAcpModelId(
model: string | null | undefined,
modelOptions: CursorModelOptions | null | undefined,
): string {
const slug = normalizeModelSlug(model, "cursor") ?? "default";
const slug = normalizeModelSlug(model, "cursor") ?? "auto";
if (slug.includes("[") && slug.endsWith("]")) {
return slug;
}
const caps = getCursorModelCapabilities(slug);
const isBuiltIn = BUILT_IN_MODELS.some((candidate) => candidate.slug === slug);
if (!isBuiltIn) {
return `${slug}[]`;
return slug;
}
const traits: string[] = [];
const reasoning = resolveEffort(caps, modelOptions?.reasoning);
if (reasoning) {
traits.push(`${slug.startsWith("claude-") ? "effort" : "reasoning"}=${reasoning}`);
}
const thinking = caps.supportsThinkingToggle ? (modelOptions?.thinking ?? true) : undefined;
if (thinking !== undefined) {
traits.push(`thinking=${thinking}`);
}
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
if (contextWindow) {
traits.push(`context=${contextWindow}`);
}
if (caps.supportsFastMode) {
if (slug === "gpt-5.3-codex") {
const reasoning = resolveEffort(caps, modelOptions?.reasoning) ?? "medium";
traits.push(`reasoning=${reasoning}`);
traits.push(`fast=${modelOptions?.fastMode === true}`);
return `${slug}[${traits.join(",")}]`;
}
return `${slug}[${traits.join(",")}]`;
if (caps.supportsFastMode && modelOptions?.fastMode === true) {
traits.push("fast=true");
}
if (modelOptions?.reasoning !== undefined) {
const reasoning = resolveEffort(caps, modelOptions.reasoning);
if (reasoning) {
traits.push(`${slug.startsWith("claude-") ? "effort" : "reasoning"}=${reasoning}`);
}
}
if (caps.supportsThinkingToggle && modelOptions?.thinking !== undefined) {
traits.push(`thinking=${modelOptions.thinking}`);
}
if (modelOptions?.contextWindow !== undefined) {
const contextWindow = resolveContextWindow(caps, modelOptions.contextWindow);
if (contextWindow) {
traits.push(`context=${contextWindow}`);
}
}
return traits.length > 0 ? `${slug}[${traits.join(",")}]` : slug;
}
/**
@@ -772,13 +772,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
if (joined === "login status") {
return { stdout: "Logged in\n", stderr: "", code: 0 };
}
if (joined === "about") {
return {
stdout: "Version: 1.0.0\nUser Email: [email protected]\n",
stderr: "",
code: 0,
};
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
@@ -1,13 +1,7 @@
import { RuntimeRequestId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import * as EffectAcpErrors from "effect-acp/errors";
import {
acpPermissionOutcome,
makeAcpContentDeltaEvent,
makeAcpPlanUpdatedEvent,
makeAcpRequestOpenedEvent,
makeAcpToolCallEvent,
} from "./AcpAdapterSupport.ts";
import { acpPermissionOutcome, mapAcpToAdapterError } from "./AcpAdapterSupport.ts";
describe("AcpAdapterSupport", () => {
it("maps ACP approval decisions to permission outcomes", () => {
@@ -16,92 +10,18 @@ describe("AcpAdapterSupport", () => {
expect(acpPermissionOutcome("decline")).toBe("reject-once");
});
it("builds shared ACP-backed runtime events", () => {
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
const turnId = TurnId.makeUnsafe("turn-1");
expect(
makeAcpRequestOpenedEvent({
stamp,
provider: "cursor",
threadId: "thread-1" as never,
turnId,
requestId: RuntimeRequestId.makeUnsafe("request-1"),
requestType: "exec_command_approval",
detail: "cat package.json",
args: { command: ["cat", "package.json"] },
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: { sessionId: "session-1" },
it("maps ACP request errors to provider adapter request errors", () => {
const error = mapAcpToAdapterError(
"cursor",
"thread-1" as never,
"session/prompt",
new EffectAcpErrors.AcpRequestError({
code: -32602,
errorMessage: "Invalid params",
}),
).toMatchObject({
type: "request.opened",
provider: "cursor",
turnId,
payload: {
requestType: "exec_command_approval",
detail: "cat package.json",
},
});
);
expect(
makeAcpPlanUpdatedEvent({
stamp,
provider: "cursor",
threadId: "thread-1" as never,
turnId,
payload: {
plan: [{ step: "Inspect state", status: "inProgress" }],
},
source: "acp.cursor.extension",
method: "cursor/update_todos",
rawPayload: { todos: [] },
}),
).toMatchObject({
type: "turn.plan.updated",
raw: {
method: "cursor/update_todos",
},
});
expect(
makeAcpToolCallEvent({
stamp,
provider: "cursor",
threadId: "thread-1" as never,
turnId,
toolCall: {
toolCallId: "tool-1",
itemType: "command_execution",
status: "completed",
title: "Terminal",
detail: "bun run test",
data: { command: "bun run test" },
},
rawPayload: { sessionId: "session-1" },
}),
).toMatchObject({
type: "item.completed",
payload: {
itemType: "command_execution",
status: "completed",
},
});
expect(
makeAcpContentDeltaEvent({
stamp,
provider: "cursor",
threadId: "thread-1" as never,
turnId,
text: "hello",
rawPayload: { sessionId: "session-1" },
}),
).toMatchObject({
type: "content.delta",
payload: {
delta: "hello",
},
});
expect(error._tag).toBe("ProviderAdapterRequestError");
expect(error.message).toContain("Invalid params");
});
});
@@ -1,12 +1,7 @@
import {
RuntimeItemId,
type EventId,
type ProviderApprovalDecision,
type ProviderKind,
type ProviderRuntimeEvent,
type ThreadId,
type TurnId,
type RuntimeRequestId,
} from "@t3tools/contracts";
import { Schema } from "effect";
import * as EffectAcpErrors from "effect-acp/errors";
@@ -16,30 +11,6 @@ import {
ProviderAdapterSessionClosedError,
type ProviderAdapterError,
} from "../Errors.ts";
import type { AcpToolCallState } from "./AcpRuntimeModel.ts";
export type AcpAdapterRawSource = "acp.jsonrpc" | `acp.${string}.extension`;
export interface AcpEventStamp {
readonly eventId: EventId;
readonly createdAt: string;
}
function runtimeItemStatusFromToolCallStatus(
status: "pending" | "inProgress" | "completed" | "failed" | undefined,
): "inProgress" | "completed" | "failed" | undefined {
switch (status) {
case "pending":
case "inProgress":
return "inProgress";
case "completed":
return "completed";
case "failed":
return "failed";
default:
return undefined;
}
}
export function mapAcpToAdapterError(
provider: ProviderKind,
@@ -77,163 +48,7 @@ export function acpPermissionOutcome(decision: ProviderApprovalDecision): string
case "accept":
return "allow-once";
case "decline":
case "cancel":
default:
return "reject-once";
}
}
export function makeAcpRequestOpenedEvent(input: {
readonly stamp: AcpEventStamp;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly requestId: RuntimeRequestId;
readonly requestType:
| "exec_command_approval"
| "file_read_approval"
| "file_change_approval"
| "unknown";
readonly detail: string;
readonly args: unknown;
readonly source: AcpAdapterRawSource;
readonly method: string;
readonly rawPayload: unknown;
}): ProviderRuntimeEvent {
return {
type: "request.opened",
...input.stamp,
provider: input.provider,
threadId: input.threadId,
turnId: input.turnId,
requestId: input.requestId,
payload: {
requestType: input.requestType,
detail: input.detail,
args: input.args,
},
raw: {
source: input.source,
method: input.method,
payload: input.rawPayload,
},
};
}
export function makeAcpRequestResolvedEvent(input: {
readonly stamp: AcpEventStamp;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly requestId: RuntimeRequestId;
readonly requestType:
| "exec_command_approval"
| "file_read_approval"
| "file_change_approval"
| "unknown";
readonly decision: ProviderApprovalDecision;
}): ProviderRuntimeEvent {
return {
type: "request.resolved",
...input.stamp,
provider: input.provider,
threadId: input.threadId,
turnId: input.turnId,
requestId: input.requestId,
payload: {
requestType: input.requestType,
decision: input.decision,
},
};
}
export function makeAcpPlanUpdatedEvent(input: {
readonly stamp: AcpEventStamp;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly payload: {
readonly explanation?: string | null;
readonly plan: ReadonlyArray<{
readonly step: string;
readonly status: "pending" | "inProgress" | "completed";
}>;
};
readonly source: AcpAdapterRawSource;
readonly method: string;
readonly rawPayload: unknown;
}): ProviderRuntimeEvent {
return {
type: "turn.plan.updated",
...input.stamp,
provider: input.provider,
threadId: input.threadId,
turnId: input.turnId,
payload: input.payload,
raw: {
source: input.source,
method: input.method,
payload: input.rawPayload,
},
};
}
export function makeAcpToolCallEvent(input: {
readonly stamp: AcpEventStamp;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly toolCall: AcpToolCallState;
readonly rawPayload: unknown;
}): ProviderRuntimeEvent {
const runtimeStatus = runtimeItemStatusFromToolCallStatus(input.toolCall.status);
return {
type:
input.toolCall.status === "completed" || input.toolCall.status === "failed"
? "item.completed"
: "item.updated",
...input.stamp,
provider: input.provider,
threadId: input.threadId,
turnId: input.turnId,
itemId: RuntimeItemId.makeUnsafe(input.toolCall.toolCallId),
payload: {
itemType: input.toolCall.itemType,
...(runtimeStatus ? { status: runtimeStatus } : {}),
...(input.toolCall.title ? { title: input.toolCall.title } : {}),
...(input.toolCall.detail ? { detail: input.toolCall.detail } : {}),
...(Object.keys(input.toolCall.data).length > 0 ? { data: input.toolCall.data } : {}),
},
raw: {
source: "acp.jsonrpc",
method: "session/update",
payload: input.rawPayload,
},
};
}
export function makeAcpContentDeltaEvent(input: {
readonly stamp: AcpEventStamp;
readonly provider: ProviderKind;
readonly threadId: ThreadId;
readonly turnId: TurnId | undefined;
readonly text: string;
readonly rawPayload: unknown;
}): ProviderRuntimeEvent {
return {
type: "content.delta",
...input.stamp,
provider: input.provider,
threadId: input.threadId,
turnId: input.turnId,
payload: {
streamKind: "assistant_text",
delta: input.text,
},
raw: {
source: "acp.jsonrpc",
method: "session/update",
payload: input.rawPayload,
},
};
}
@@ -89,7 +89,7 @@ describe("AcpRuntimeModel", () => {
_tag: "ToolCallUpdated",
toolCall: {
toolCallId: "tool-1",
itemType: "command_execution",
kind: "execute",
title: "Terminal",
status: "pending",
command: "bun run typecheck",
@@ -253,11 +253,11 @@ describe("AcpRuntimeModel", () => {
});
expect(request).toMatchObject({
requestType: "exec_command_approval",
kind: "execute",
detail: "cat package.json",
toolCall: {
toolCallId: "tool-1",
itemType: "command_execution",
kind: "execute",
status: "pending",
command: "cat package.json",
},
+12 -44
View File
@@ -1,4 +1,3 @@
import type { ToolLifecycleItemType } from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -18,7 +17,7 @@ export interface AcpSessionModeState {
export interface AcpToolCallState {
readonly toolCallId: string;
readonly itemType: ToolLifecycleItemType;
readonly kind?: string;
readonly title?: string;
readonly status?: "pending" | "inProgress" | "completed" | "failed";
readonly command?: string;
@@ -35,11 +34,7 @@ export interface AcpPlanUpdate {
}
export interface AcpPermissionRequest {
readonly requestType:
| "exec_command_approval"
| "file_read_approval"
| "file_change_approval"
| "unknown";
readonly kind: string | "unknown";
readonly detail?: string;
readonly toolCall?: AcpToolCallState;
}
@@ -231,37 +226,8 @@ function extractTextContentFromToolCallContent(
return chunks.length > 0 ? chunks.join("\n") : undefined;
}
function toolLifecycleItemTypeFromKind(kind: unknown): ToolLifecycleItemType {
switch (kind) {
case "execute":
return "command_execution";
case "edit":
case "delete":
case "move":
return "file_change";
case "search":
case "fetch":
return "web_search";
default:
return "dynamic_tool_call";
}
}
function requestTypeFromToolKind(
kind: unknown,
): "exec_command_approval" | "file_read_approval" | "file_change_approval" | "unknown" {
switch (kind) {
case "execute":
return "exec_command_approval";
case "read":
return "file_read_approval";
case "edit":
case "delete":
case "move":
return "file_change_approval";
default:
return "unknown";
}
function normalizeToolKind(kind: unknown): string | undefined {
return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
}
function makeToolCallState(
@@ -292,8 +258,9 @@ function makeToolCallState(
: undefined;
const detail = command ?? normalizedTitle ?? textContent;
const data: Record<string, unknown> = { toolCallId };
if (input.kind) {
data.kind = input.kind;
const kind = normalizeToolKind(input.kind);
if (kind) {
data.kind = kind;
}
if (command) {
data.command = command;
@@ -313,7 +280,7 @@ function makeToolCallState(
const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
return {
toolCallId,
itemType: toolLifecycleItemTypeFromKind(input.kind),
...(kind ? { kind } : {}),
...(title ? { title } : {}),
...(status ? { status } : {}),
...(command ? { command } : {}),
@@ -348,13 +315,14 @@ export function mergeToolCallState(
next: AcpToolCallState,
): AcpToolCallState {
const nextKind = typeof next.data.kind === "string" ? next.data.kind : undefined;
const kind = nextKind ?? previous?.kind;
const title = next.title ?? previous?.title;
const status = next.status ?? previous?.status;
const command = next.command ?? previous?.command;
const detail = next.detail ?? previous?.detail;
return {
toolCallId: next.toolCallId,
itemType: nextKind !== undefined ? next.itemType : (previous?.itemType ?? next.itemType),
...(kind ? { kind } : {}),
...(title ? { title } : {}),
...(status ? { status } : {}),
...(command ? { command } : {}),
@@ -382,14 +350,14 @@ export function parsePermissionRequest(
},
{ fallbackStatus: "pending" },
);
const requestType = requestTypeFromToolKind(params.toolCall.kind);
const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
const detail =
toolCall?.command ??
toolCall?.title ??
toolCall?.detail ??
(typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
return {
requestType,
kind,
...(detail ? { detail } : {}),
...(toolCall ? { toolCall } : {}),
};
@@ -1,3 +1,7 @@
/**
* 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 { Schema } from "effect";
-8
View File
@@ -112,17 +112,9 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
"claude-haiku-4-5-20251001": "claude-haiku-4-5",
},
cursor: {
auto: "default",
composer: "composer-2",
"composer-1.5": "composer-1.5",
"composer-1": "composer-1.5",
"gpt-5.3-codex": "gpt-5.3-codex",
"gpt-5.3-codex-spark": "gpt-5.3-codex-spark",
"gemini-3.1-pro": "gemini-3.1-pro",
"gpt-5.4-1m": "gpt-5.4",
"claude-4.6-opus": "claude-opus-4-6",
"claude-4.6-sonnet": "claude-sonnet-4-6",
"claude-4.5-opus": "claude-opus-4-5",
"opus-4.6-thinking": "claude-opus-4-6",
"opus-4.6": "claude-opus-4-6",
"sonnet-4.6-thinking": "claude-sonnet-4-6",
+11 -1
View File
@@ -10,6 +10,11 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
const CURRENT_SCHEMA_RELEASE = "v0.11.3";
interface GenerateCommandError {
readonly _tag: "GenerateCommandError";
readonly message: string;
}
interface GeneratedPaths {
readonly generatedDir: string;
readonly upstreamSchemaPath: string;
@@ -253,7 +258,12 @@ const generateSchemas = Effect.fn("generateSchemas")(function* (skipDownload: bo
Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
Effect.flatMap((child) => child.exitCode),
Effect.tap((code) =>
code === 0 ? Effect.void : Effect.fail(new Error(`oxfmt failed with exit code ${code}`)),
code === 0
? Effect.void
: Effect.fail<GenerateCommandError>({
_tag: "GenerateCommandError",
message: `oxfmt failed with exit code ${code}`,
}),
),
);
});
-4
View File
@@ -303,10 +303,6 @@ export const fromChildProcess = Effect.fnUntraced(function* (
notification.method,
notification.params,
);
case "SessionCancel":
return handlers.extNotification
? handlers.extNotification(notification.method, notification.params)
: Effect.void;
}
},
...(handlers.extRequest || handlers.extRequests
+10 -5
View File
@@ -2,6 +2,7 @@ import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as Sink from "effect/Sink";
import * as Stdio from "effect/Stdio";
@@ -13,6 +14,10 @@ import * as AcpProtocol from "./protocol";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const UnknownJson = Schema.UnknownFromJsonString;
const encodeJson = Schema.encodeSync(UnknownJson);
const decodeJson = Schema.decodeUnknownSync(UnknownJson);
function makeInMemoryStdio() {
return Effect.gen(function* () {
@@ -57,7 +62,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
yield* transport.notifications.sendSessionCancel({ sessionId: "session-1" });
const outbound = yield* Queue.take(output);
assert.deepEqual(JSON.parse(outbound), {
assert.deepEqual(decodeJson(outbound), {
jsonrpc: "2.0",
method: "session/cancel",
params: {
@@ -68,7 +73,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
yield* Queue.offer(
input,
encoder.encode(
`${JSON.stringify({
`${encodeJson({
jsonrpc: "2.0",
method: "session/update",
params: {
@@ -91,7 +96,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
yield* Queue.offer(
input,
encoder.encode(
`${JSON.stringify({
`${encodeJson({
jsonrpc: "2.0",
method: "session/elicitation/complete",
params: {
@@ -119,7 +124,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
.sendRequest("x/test", { hello: "world" })
.pipe(Effect.forkScoped);
const outbound = yield* Queue.take(output);
assert.deepEqual(JSON.parse(outbound), {
assert.deepEqual(decodeJson(outbound), {
jsonrpc: "2.0",
id: 1,
method: "x/test",
@@ -132,7 +137,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
yield* Queue.offer(
input,
encoder.encode(
`${JSON.stringify({
`${encodeJson({
jsonrpc: "2.0",
id: 1,
result: {
-26
View File
@@ -29,11 +29,6 @@ export type AcpIncomingNotification =
readonly method: typeof CLIENT_METHODS.session_update;
readonly params: typeof AcpSchema.SessionNotification.Type;
}
| {
readonly _tag: "SessionCancel";
readonly method: "session/cancel";
readonly params: typeof AcpSchema.CancelNotification.Type;
}
| {
readonly _tag: "ElicitationComplete";
readonly method: typeof CLIENT_METHODS.session_elicitation_complete;
@@ -83,7 +78,6 @@ export interface AcpPatchedProtocol {
}
const decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);
const decodeSessionCancel = Schema.decodeUnknownEffect(AcpSchema.CancelNotification);
const decodeElicitationComplete = Schema.decodeUnknownEffect(
AcpSchema.ElicitationCompleteNotification,
);
@@ -243,26 +237,6 @@ export const makeAcpPatchedProtocol = (
Effect.flatMap(dispatchNotification),
);
}
if (message.tag === "session/cancel") {
return decodeSessionCancel(message.payload).pipe(
Effect.map(
(params) =>
({
_tag: "SessionCancel",
method: "session/cancel",
params,
}) satisfies AcpIncomingNotification,
),
Effect.mapError(
(cause) =>
new AcpError.AcpProtocolParseError({
detail: "Invalid session/cancel notification payload",
cause,
}),
),
Effect.flatMap(dispatchNotification),
);
}
if (message.tag === CLIENT_METHODS.session_elicitation_complete) {
return decodeElicitationComplete(message.payload).pipe(
Effect.map(