TypeScript
fix(cursor): explain model rejections from the account catalog (#19678)
Wout Stiens71aa1173b079
diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.tsindex 8921df5b5e8..d5dfad31a1c 100644--- a/packages/provider-core/src/server/failure.ts+++ b/packages/provider-core/src/server/failure.ts@@ -45,6 +45,7 @@ function causeMessage(cause: unknown): string | undefined {case "ContextHandoffBudgetError":return new ContextHandoffBudgetError().message;case "ClaudeBackgroundWorkBlocksQueryReplacementError":+ case "CursorModelUnavailableError":return stringField(cause, "message");case "ContextHandoffDeliveryUncertainError":return "T3 could not confirm whether conversation history reached the provider. Retry the turn to recover the session.";diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.tsindex 43fb080eec3..5c702795fb7 100644--- a/packages/provider-cursor/src/server/adapter.test.ts+++ b/packages/provider-cursor/src/server/adapter.test.ts@@ -26,6 +26,7 @@ import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";+import { makeProviderFailure } from "@t3tools/provider-core/server/failure";import {cursorMcpServers,cursorRuntimeAgentPolicy,@@ -35,6 +36,7 @@ import {nestedToolCallFromEnvelope,} from "./adapter.ts";import * as CursorAgentSdk from "./CursorAgentSdk.ts";+import { ConfigurationError } from "./sdk.ts";const decodeCursorSettings = Schema.decodeEffect(CursorSettings);@@ -777,6 +779,128 @@ describe("CursorAdapterV2", () => {),);+ it.effect("names a custom model Cursor's account catalog rejects", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-model-" });+ const instanceId = ProviderInstanceId.make("cursor");+ const threadId = ThreadId.make("cursor-custom-model-thread");+ const catalogModel = { instanceId, model: "composer-2.5" };+ const customModel = { instanceId, model: "deepseek/deepseek-v4.1-flash" };+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({+ runtimeMode: "full-access",+ interactionMode: "default",+ cwd: workspace,+ });+ // The SDK checks every create, resume, and send model against the account catalog.+ const checkModel = (method: string, model: { readonly id: string } | undefined) =>+ model === undefined || model.id === "composer-2.5"+ ? Effect.void+ : Effect.fail(+ new CursorAgentSdk.CursorAgentSdkRunnerError({+ method,+ cause: new ConfigurationError(+ `Cannot use this model: ${model.id}. Available models: default, composer-2.5. Use Cursor.models.list() to discover valid selections.`,+ { isRetryable: false },+ ),+ }),+ );+ const adapter = yield* makeCursorAdapterV2({+ instanceId,+ settings: yield* decodeCursorSettings({}),+ environment: { HOME: workspace },+ }).pipe(+ Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {+ assertComplete: Effect.void,+ open: (input) =>+ checkModel(`agent.${input.operation}`, input.options.model).pipe(+ Effect.as({+ agentId: "native-cursor-custom-model",+ listMessages: Effect.succeed([]),+ close: Effect.void,+ send: (sendInput) =>+ checkModel("run.start", sendInput.options?.model).pipe(+ Effect.andThen(Effect.die("unexpected Cursor run")),+ ),+ }),+ ),+ }),+ Effect.provide(TestProviderHost.layer({ cwd: workspace })),+ );+ const runtime = yield* adapter.openSession({+ threadId,+ providerSessionId: ProviderSessionId.make("cursor-custom-model-session"),+ modelSelection: catalogModel,+ runtimePolicy,+ });+ const expected =+ 'Cursor cannot run the model "deepseek/deepseek-v4.1-flash". Cursor only runs models from your Cursor account. Choose one of those, or use OpenCode for OpenRouter and other API-key models.';++ // A new thread created with the custom model.+ const createFailure = yield* runtime+ .ensureThread({ threadId, modelSelection: customModel, runtimePolicy })+ .pipe(Effect.flip);+ assert.equal(makeProviderFailure({ cause: createFailure }).message, expected);++ // An existing thread switched to the custom model.+ const providerThread = yield* runtime.ensureThread({+ threadId,+ modelSelection: catalogModel,+ runtimePolicy,+ });+ const now = yield* DateTime.now;+ const sendFailure = yield* runtime+ .startTurn({+ threadId,+ providerThread,+ modelSelection: customModel,+ runtimePolicy,+ runId: RunId.make("cursor-custom-model-run"),+ runOrdinal: 1,+ providerTurnOrdinal: 1,+ attemptId: RunAttemptId.make("cursor-custom-model-attempt"),+ rootNodeId: NodeId.make("cursor-custom-model-root"),+ appThread: {+ id: threadId,+ projectId: ProjectId.make("cursor-custom-model-project"),+ createdBy: "user",+ creationSource: "web",+ title: "Cursor custom model",+ providerInstanceId: instanceId,+ modelSelection: customModel,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ activeProviderThreadId: providerThread.id,+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: null,+ },+ message: {+ messageId: MessageId.make("cursor-custom-model-message"),+ createdBy: "user",+ creationSource: "web",+ text: "Hello.",+ attachments: [],+ },+ })+ .pipe(Effect.flip);+ assert.equal(makeProviderFailure({ cause: sendFailure }).message, expected);+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),+ ),+ ),+ );+it("maps Cursor auto and model parameters to SDK selections", () => {assert.deepEqual(cursorSdkModelSelection({diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.tsindex 1786a0115c8..9eae35fe47e 100644--- a/packages/provider-cursor/src/server/adapter.ts+++ b/packages/provider-cursor/src/server/adapter.ts@@ -74,6 +74,7 @@ import {subagentThreadTitle,} from "@t3tools/provider-core/server/subagentProjection";import * as CursorAgentSdk from "./CursorAgentSdk.ts";+import { ConfigurationError } from "./sdk.ts";export { cursorSdkModelSelection } from "./sdkModel.ts";export const CURSOR_DRIVER_KIND = CursorAgentSdk.CURSOR_PROVIDER;@@ -326,6 +327,35 @@ export function makeCursorAgentOptions(input: {};}+/**+ * Raised when Cursor rejects the selected model, usually a custom model outside+ * the account catalog. `makeProviderFailure` shows its message to the user.+ */+class CursorModelUnavailableError extends Schema.TaggedError<CursorModelUnavailableError>()(+ "CursorModelUnavailableError",+ {+ model: Schema.String,+ cause: Schema.Defect(),+ },+) {+ override get message(): string {+ return `Cursor cannot run the model "${this.model}". Cursor only runs models from your Cursor account. Choose one of those, or use OpenCode for OpenRouter and other API-key models.`;+ }+}++/**+ * Maps runner failures from opening or sending to an agent. The SDK checks the+ * model against the account catalog before either and rejects it with an+ * uncoded ConfigurationError listing every account model, so its message+ * prefix is the only signal.+ */+const classifyCursorModelRejection =+ (modelSelection: ModelSelection) => (error: CursorAgentSdk.CursorAgentSdkRunnerError) =>+ error.cause instanceof ConfigurationError &&+ error.cause.message.startsWith("Cannot use this model:")+ ? new CursorModelUnavailableError({ model: modelSelection.model, cause: error.cause })+ : error;+function stableJson(value: unknown): string {try {return JSON.stringify(value, null, 2);@@ -2094,19 +2124,21 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (yield* existing.session.close.pipe(Effect.ignore);yield* Ref.set(liveAgent, null);}- const sdkSession = yield* runner.open({- operation: openInput.operation,- ...(openInput.agentId === undefined ? {} : { agentId: openInput.agentId }),- options: makeCursorAgentOptions({- ...(apiKey === undefined ? {} : { apiKey }),- modelSelection: openInput.modelSelection,- runtimePolicy: openInput.runtimePolicy,+ const sdkSession = yield* runner+ .open({+ operation: openInput.operation,+ ...(openInput.agentId === undefined ? {} : { agentId: openInput.agentId }),+ options: makeCursorAgentOptions({+ ...(apiKey === undefined ? {} : { apiKey }),+ modelSelection: openInput.modelSelection,+ runtimePolicy: openInput.runtimePolicy,+ threadId: openInput.threadId,+ mcpSession: yield* mcpSessions.read(openInput.threadId),+ }),threadId: openInput.threadId,- mcpSession: yield* mcpSessions.read(openInput.threadId),- }),- threadId: openInput.threadId,- providerSessionId: input.providerSessionId,- });+ providerSessionId: input.providerSessionId,+ })+ .pipe(Effect.mapError(classifyCursorModelRejection(openInput.modelSelection)));const next = {nativeThreadId: sdkSession.agentId,session: sdkSession,@@ -2215,21 +2247,23 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (const pendingUpdates: Array<InteractionUpdate> = [];let context: ActiveCursorTurn | null = null;// MCP send overrides replace the ambient servers loaded when the agent opens.- const sdkRun = yield* agent.session.send({- message,- options: {- model: cursorSdkModelSelection(turnInput.modelSelection),- mode: turnInput.runtimePolicy.interactionMode === "plan" ? "plan" : "agent",- },- onDelta: (update) => {- if (context === null) {- return Effect.sync(() => {- pendingUpdates.push(update);- });- }- return handleInteractionUpdate(context, update);- },- });+ const sdkRun = yield* agent.session+ .send({+ message,+ options: {+ model: cursorSdkModelSelection(turnInput.modelSelection),+ mode: turnInput.runtimePolicy.interactionMode === "plan" ? "plan" : "agent",+ },+ onDelta: (update) => {+ if (context === null) {+ return Effect.sync(() => {+ pendingUpdates.push(update);+ });+ }+ return handleInteractionUpdate(context, update);+ },+ })+ .pipe(Effect.mapError(classifyCursorModelRejection(turnInput.modelSelection)));const startedAt = yield* DateTime.now;const completed = yield* Deferred.make<void, never>();const providerTurnId = idAllocator.derive.providerTurn({diff --git a/packages/provider-cursor/src/server/sdk.ts b/packages/provider-cursor/src/server/sdk.tsindex f9d3507e029..431f3cf8cd8 100644--- a/packages/provider-cursor/src/server/sdk.ts+++ b/packages/provider-cursor/src/server/sdk.ts@@ -7,6 +7,7 @@ const requireCursorSdk = NodeModule.createRequire(import.meta.url);export const {Agent,AuthenticationError,+ ConfigurationError,createAgentPlatform,Cursor,CursorSdkError,