Require Cursor API key for provider checks

- Switch Cursor provider status and model discovery to the SDK catalog
- Improve chat content lane alignment and provider secret handling
This commit is contained in:
Julius Marminge authored and maria-rcks committed 2026-08-03 11:45:07 -04:00
1 parent 022452d02e
commit 60dc48a413
21 files changed
+633 -340

No files matched your search

@@ -0,0 +1,119 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
import { ServerConfig } from "../../config.ts";
import {
CursorAgentSdkRunner,
CursorAgentSdkRunnerError,
cursorAgentSdkRunnerLiveLayer,
} from "./CursorAgentSdk.ts";
const cursorSdkMock = vi.hoisted(() => {
const runWait = vi.fn(async () => ({
id: "run-cursor-agent-sdk-test",
requestId: "request-cursor-agent-sdk-test",
status: "finished",
result: "ok",
model: { id: "default" },
durationMs: 1,
}));
const runCancel = vi.fn(async () => {});
const agentClose = vi.fn(() => {});
const send = vi.fn(
async (
_message: unknown,
options: { readonly onDelta?: (input: { readonly update: unknown }) => Promise<void> },
) => {
await options.onDelta?.({
update: {
type: "assistant-message-chunk",
text: "hello",
},
});
return {
id: "run-cursor-agent-sdk-test",
agentId: "agent-cursor-agent-sdk-test",
wait: runWait,
cancel: runCancel,
};
},
);
const create = vi.fn(async () => ({
agentId: "agent-cursor-agent-sdk-test",
send,
close: agentClose,
}));
return {
agentClose,
create,
runCancel,
runWait,
send,
};
});
vi.mock("@cursor/sdk", () => ({
Agent: {
create: cursorSdkMock.create,
resume: vi.fn(),
messages: {
list: vi.fn(async () => []),
},
},
}));
const testLayer = cursorAgentSdkRunnerLiveLayer.pipe(
Layer.provide(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-cursor-agent-sdk-runner-",
}),
),
Layer.provide(NodeServices.layer),
);
describe("CursorAgentSdkRunner", () => {
it.effect("surfaces interaction callback failures through run.wait", () =>
Effect.gen(function* () {
cursorSdkMock.create.mockClear();
cursorSdkMock.runWait.mockClear();
cursorSdkMock.send.mockClear();
const runner = yield* CursorAgentSdkRunner;
const session = yield* runner.open({
operation: "create",
options: {
model: { id: "default" },
mode: "agent",
local: {
cwd: process.cwd(),
autoReview: false,
sandboxOptions: { enabled: false },
enableAgentRetries: true,
},
},
threadId: ThreadId.make("thread-cursor-agent-sdk-test"),
providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-test"),
});
const callbackFailure = new Error("delta callback failed");
const run = yield* session.send({
message: "hello",
onDelta: () => Effect.fail(callbackFailure),
});
const error = yield* Effect.flip(run.wait);
assert.instanceOf(error, CursorAgentSdkRunnerError);
assert.equal(error.method, "run.wait");
assert.strictEqual(error.cause, callbackFailure);
assert.equal(cursorSdkMock.create.mock.calls.length, 1);
assert.equal(cursorSdkMock.send.mock.calls.length, 1);
assert.equal(cursorSdkMock.runWait.mock.calls.length, 1);
}).pipe(Effect.provide(testLayer)),
);
});
@@ -366,22 +366,30 @@ export const cursorAgentSdkRunnerLiveLayer: Layer.Layer<CursorAgentSdkRunner, ne
let callbacksReady = false;
const pendingUpdates: Array<InteractionUpdate> = [];
let callbackFailure: { readonly cause: unknown } | undefined;
let callbackChain = Promise.resolve();
let runId = "";
const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
callbackChain = callbackChain.then(() =>
Effect.runPromiseWith(context)(
log({
direction: "incoming",
stage: "decoded",
payload: {
type: "interaction.update",
runId,
update,
},
}).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)),
),
);
callbackChain = callbackChain
.then(() => {
if (callbackFailure !== undefined) {
return;
}
return Effect.runPromiseWith(context)(
log({
direction: "incoming",
stage: "decoded",
payload: {
type: "interaction.update",
runId,
update,
},
}).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)),
);
})
.catch((cause) => {
callbackFailure ??= { cause };
});
return callbackChain;
};
@@ -424,6 +432,9 @@ export const cursorAgentSdkRunnerLiveLayer: Layer.Layer<CursorAgentSdkRunner, ne
try: async () => {
const result = await run.wait();
await callbackChain;
if (callbackFailure !== undefined) {
throw callbackFailure.cause;
}
return result;
},
catch: (cause) => runnerError(cause, "run.wait"),
@@ -1,9 +1,8 @@
/**
* CursorDriver — `ProviderDriver` for the Cursor Agent (`cursor-agent`) runtime.
* CursorDriver — `ProviderDriver` for the Cursor Agent SDK runtime.
*
* Provider status and model discovery use the official Cursor SDK when an API
* key is configured. The ACP CLI remains the compatibility fallback for
* installations that authenticate through the local Cursor binary.
* Provider status, model discovery, and orchestration use the official Cursor
* SDK and require CURSOR_API_KEY in the provider instance environment.
*
* Text generation is supported via the ACP runtime — `makeCursorTextGeneration`
* drives `runtime.prompt` with a structured-output schema and collects the
@@ -103,10 +102,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
defaultConfig: (): CursorSettings => decodeCursorSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const processEnv = mergeProviderInstanceEnvironment(environment);
@@ -149,9 +144,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
const checkProvider = checkCursorProviderStatus(effectiveConfig, processEnv).pipe(
Effect.map(stampIdentity),
Effect.provide(CursorSdkCatalogLive),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
@@ -163,8 +155,8 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
initialSnapshot: (settings) =>
buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
checkProvider,
// Model catalog and capabilities come exclusively from Cursor's
// list_available_models extension method during provider checks.
// Model catalog and capabilities come from Cursor's SDK catalog during
// provider checks.
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
enrichCursorSnapshot({
settings: settings.provider,
@@ -30,11 +30,46 @@ import {
} from "./CursorProvider.ts";
import { CursorSdkCatalogError, makeCursorSdkCatalogTestLayer } from "./CursorSdkCatalog.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
const path = yield* Path.Path;
return yield* path.fromFileUrl(new URL("../../../scripts/acp-mock-agent.ts", import.meta.url));
});
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
function selectDescriptor(
id: string,
label: string,
options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>,
) {
return {
id,
label,
type: "select" as const,
options: [...options],
...(options.find((option) => option.isDefault)?.id
? { currentValue: options.find((option) => option.isDefault)?.id }
: {}),
};
}
function booleanDescriptor(id: string, label: string, currentValue?: boolean) {
return {
id,
label,
type: "boolean" as const,
...(typeof currentValue === "boolean" ? { currentValue } : {}),
};
}
const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* (
extraEnv?: Record<string, string>,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const mockAgentPath = yield* resolveMockAgentPath();
const dir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-provider-mock-",
});
const wrapperPath = path.join(dir, "fake-agent.sh");
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
@@ -244,6 +279,13 @@ const baseCursorSettings: CursorSettings = {
apiEndpoint: "",
customModels: [],
};
const cursorAcpDiscoveryFailedMessage = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
"See https://cursor.com/docs/cli/installation.",
"Check server logs for ACP details.",
].join(" ");
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
const sdkParameterizedModel = {
id: "claude-opus-4-8",
@@ -515,23 +557,14 @@ describe("checkCursorProviderStatus", () => {
});
});
it("passes the injected environment to ACP model discovery", async () => {
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
const provider = await runNode(
checkCursorProviderStatus(
{
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
},
{
...process.env,
CURSOR_API_KEY: "",
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
).pipe(
it("requires a Cursor API key without probing the legacy CLI fallback", async () => {
const provider = await Effect.runPromise(
checkCursorProviderStatus({
enabled: true,
binaryPath: missingCursorBinaryPath,
apiEndpoint: "",
customModels: [],
}).pipe(
Effect.provide(
Layer.mergeAll(
makeCursorSdkCatalogTestLayer(() =>
@@ -543,17 +576,44 @@ describe("checkCursorProviderStatus", () => {
),
);
expect(provider.models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
await expect(runNode(waitForFileContent(requestLogPath))).resolves.toContain("initialize");
expect(provider).toMatchObject({
installed: true,
status: "error",
auth: { status: "unauthenticated" },
message: "Cursor API key is required. Add CURSOR_API_KEY in provider settings.",
});
});
});
describe("discoverCursorModelsViaAcp", () => {
it.effect("passes the injected environment to ACP model discovery", () =>
Effect.gen(function* () {
const { requestLogPath, wrapperPath } = yield* makeProviderStatusEnvFixture();
const models = yield* discoverCursorModelsViaAcp(
{
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
},
{
...process.env,
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
);
expect(models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
yield* waitForFileContent(requestLogPath).pipe(
Effect.tap((content) => Effect.sync(() => expect(content).toContain("initialize"))),
);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("keeps the ACP probe runtime alive long enough to discover models", () =>
Effect.gen(function* () {
const wrapperPath = yield* makeMockAgentWrapper();
+14 -194
View File
@@ -1,4 +1,3 @@
import * as NodeOs from "node:os";
import type { SDKModel, SDKUser } from "@cursor/sdk";
import type {
CursorSettings,
@@ -15,29 +14,22 @@ import { causeErrorTag } from "@t3tools/shared/observability";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import {
createModelCapabilities,
getProviderOptionBooleanSelectionValue,
getProviderOptionStringSelectionValue,
} from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import {
buildBooleanOptionDescriptor,
buildSelectOptionDescriptor,
buildServerProvider,
collectStreamAsString,
isCommandMissingCause,
providerModelsFromSettings,
type CommandResult,
type ServerProviderDraft,
@@ -63,16 +55,8 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
const CURSOR_SDK_CATALOG_TIMEOUT_MS = 15_000;
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
const CURSOR_CLI_INSTALLATION_DOCS_URL = "https://cursor.com/docs/cli/installation";
const CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
"Check server logs for ACP details.",
].join(" ");
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
_meta: {
parameterizedModelPicker: true,
@@ -688,9 +672,6 @@ export function getCursorFallbackModels(
return providerModelsFromSettings([], cursorSettings.customModels, EMPTY_CAPABILITIES);
}
/** Timeout for `agent about` — it's slower than a simple `--version` probe. */
const ABOUT_TIMEOUT_MS = 8_000;
/** Strip ANSI escape sequences so we can parse plain key-value lines. */
function stripAnsi(text: string): string {
// eslint-disable-next-line no-control-regex
@@ -725,14 +706,6 @@ function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): s
return parts.length > 0 ? parts.join(" ") : undefined;
}
function buildCursorCliCommandMissingMessage(binaryPath: string): string {
return [
`Cursor CLI command \`${binaryPath}\` was not found.`,
`Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
].join(" ");
}
export function buildCursorProviderSnapshot(input: {
readonly checkedAt: string;
readonly cursorSettings: CursorSettings;
@@ -857,24 +830,6 @@ function hasOwn(record: object, key: string): boolean {
return Object.prototype.hasOwnProperty.call(record, key);
}
function isCursorAboutJsonFormatUnsupported(result: CommandResult): boolean {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
return (
lowerOutput.includes("unknown option '--format'") ||
lowerOutput.includes("unexpected argument '--format'") ||
lowerOutput.includes("unrecognized option '--format'") ||
lowerOutput.includes("unknown argument '--format'")
);
}
const readCursorCliConfigChannel = Effect.fn("readCursorCliConfigChannel")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const configPath = path.join(NodeOS.homedir(), ".cursor", "cli-config.json");
const raw = yield* fileSystem.readFileString(configPath).pipe(Effect.orElseSucceed(() => ""));
return parseCursorCliConfigChannel(raw);
});
export function getCursorParameterizedModelPickerUnsupportedMessage(input: {
readonly version: string | null | undefined;
readonly channel: string | null | undefined;
@@ -1052,57 +1007,10 @@ export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult
};
}
const runCursorCommand = (
cursorSettings: CursorSettings,
args: ReadonlyArray<string>,
environment?: NodeJS.ProcessEnv,
) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const spawnCommand = yield* resolveSpawnCommand(
cursorSettings.binaryPath,
args,
environment ? { env: environment } : {},
);
const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
...(environment ? { env: environment } : { extendEnv: true }),
shell: spawnCommand.shell,
});
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
const runCursorAboutCommand = (cursorSettings: CursorSettings, environment?: NodeJS.ProcessEnv) =>
Effect.gen(function* () {
const jsonResult = yield* runCursorCommand(
cursorSettings,
["about", "--format", "json"],
environment,
);
if (!isCursorAboutJsonFormatUnsupported(jsonResult)) {
return jsonResult;
}
return yield* runCursorCommand(cursorSettings, ["about"], environment);
});
export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(function* (
cursorSettings: CursorSettings,
environment?: NodeJS.ProcessEnv,
): Effect.fn.Return<
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | CursorSdkCatalog | FileSystem.FileSystem | Path.Path
> {
): Effect.fn.Return<ServerProviderDraft, never, CursorSdkCatalog> {
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const fallbackModels = getCursorFallbackModels(cursorSettings);
@@ -1184,105 +1092,18 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
});
}
// Single `agent about` probe: returns version + auth status in one call.
const aboutProbe = yield* runCursorAboutCommand(cursorSettings, environment).pipe(
Effect.timeoutOption(ABOUT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(aboutProbe)) {
const error = aboutProbe.failure;
yield* Effect.logWarning("Cursor Agent CLI health check failed.", {
errorTag: error._tag,
});
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
: "Failed to execute Cursor Agent CLI health check.",
},
});
}
if (Option.isNone(aboutProbe.success)) {
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Cursor Agent CLI is installed but timed out while running `agent about`.",
},
});
}
const parsed = parseCursorAboutOutput(aboutProbe.success.value);
const cursorCliConfigChannel = yield* readCursorCliConfigChannel();
const parameterizedModelPickerUnsupportedMessage =
getCursorParameterizedModelPickerUnsupportedMessage({
version: parsed.version,
channel: cursorCliConfigChannel,
});
if (parameterizedModelPickerUnsupportedMessage) {
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: parsed.version,
status: "error",
auth: parsed.auth,
message:
parsed.auth.status === "unauthenticated" && parsed.message
? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}`
: parameterizedModelPickerUnsupportedMessage,
},
});
}
let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();
let discoveryWarning: string | undefined;
if (parsed.auth.status !== "unauthenticated") {
const discoveryExit = yield* Effect.exit(
discoverCursorModelsViaAcp(cursorSettings, environment).pipe(
Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
),
);
if (Exit.isFailure(discoveryExit)) {
yield* Effect.logWarning("Cursor ACP model discovery failed", {
errorTag: causeErrorTag(discoveryExit.cause),
});
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
} else if (Option.isNone(discoveryExit.value)) {
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
} else if (discoveryExit.value.value.length === 0) {
discoveryWarning = "Cursor ACP model discovery returned no built-in models.";
} else {
discoveredModels = discoveryExit.value;
}
}
return buildCursorProviderSnapshot({
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
cursorSettings,
parsed,
discoveredModels: Option.getOrElse(
Option.filter(discoveredModels, (models) => models.length > 0),
() => [] as const,
),
...(discoveryWarning ? { discoveryWarning } : {}),
models: fallbackModels,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unauthenticated" },
message: "Cursor API key is required. Add CURSOR_API_KEY in provider settings.",
},
});
});
@@ -1291,9 +1112,8 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
*
* Used by `CursorDriver` as the `makeManagedServerProvider.enrichSnapshot`
* hook: republishes update/version advisory metadata without performing any
* model or capability discovery. Provider status checks source Cursor model
* data from the SDK when an API key is configured, with ACP discovery as the
* compatibility fallback.
* model or capability discovery. Provider status and model data come from
* the Cursor SDK catalog and require CURSOR_API_KEY.
*/
export const enrichCursorSnapshot = (input: {
readonly settings: CursorSettings;