Skip to content
TypeScript

refactor(provider-cursor): follow the Effect service conventions (#17545)

Julius Marminge33806e735551
diff --git a/apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts b/apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts
index 0f50f11ba34..44a502ef532 100644
--- a/apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts
+++ b/apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts
@@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
@@ -10,6 +11,7 @@ import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as Struct from "effect/Struct";
import { Command, Flag } from "effect/cli";
+import * as CursorSdk from "@t3tools/provider-cursor/server/CursorSdk";
import {
recordCursorAgentSdkReplayTranscript,
@@ -219,6 +221,6 @@ const recordCursorReplayCommand = Command.make(
);
Command.run(recordCursorReplayCommand, { version: "0.0.0" }).pipe(
- Effect.provide(NodeServices.layer),
+ Effect.provide(Layer.mergeAll(CursorSdk.layer, NodeServices.layer)),
NodeRuntime.runMain,
);
diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts
index a194edd4a3c..daf906ec92c 100644
--- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts
@@ -213,7 +213,7 @@ function replayRunnerError(
export function makeCursorAgentSdkReplayRunner(
transcript: CursorAgentSdkReplayTranscript,
-): CursorAgentSdk.CursorAgentSdkRunnerShape {
+): CursorAgentSdk.CursorAgentSdkRunner["Service"] {
let cursor = 0;
let failure: CursorAgentSdkReplayError | null = null;
let cursorAdvanced = makeSignal();
@@ -491,7 +491,7 @@ export function makeCursorAgentSdkReplayRunner(
function layerCursorAgentSdkReplay(
transcript: CursorAgentSdkReplayTranscript,
options?: {
- readonly runner?: CursorAgentSdk.CursorAgentSdkRunnerShape;
+ readonly runner?: CursorAgentSdk.CursorAgentSdkRunner["Service"];
readonly assertCompleteOnFinalize?: boolean;
},
): Layer.Layer<CursorAgentSdk.CursorAgentSdkRunner> {
@@ -512,7 +512,7 @@ function layerCursorAgentSdkReplay(
export function layer(
transcript: CursorAgentSdkReplayTranscript,
options?: {
- readonly runner?: CursorAgentSdk.CursorAgentSdkRunnerShape;
+ readonly runner?: CursorAgentSdk.CursorAgentSdkRunner["Service"];
readonly assertCompleteOnFinalize?: boolean;
},
) {
@@ -807,7 +807,7 @@ export const recordCursorAgentSdkReplayTranscript = Effect.fn(
heldUntilCancel = [];
}
});
- const runner = CursorAgentSdk.makeCursorAgentSdkRunner(() => recordFrame);
+ const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => recordFrame);
const awaitSignal = (signal: Deferred.Deferred<void>, description: string) =>
Deferred.await(signal).pipe(
diff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts
index 3dea8ca677e..65711612b18 100644
--- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts
+++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts
@@ -3,6 +3,7 @@ import * as Layer from "effect/Layer";
import * as ClaudeAdapterV2 from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import * as CodexAdapterV2 from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
import * as CursorAgentSdk from "@t3tools/provider-cursor/server/CursorAgentSdk";
+import * as CursorSdk from "@t3tools/provider-cursor/server/CursorSdk";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
@@ -10,6 +11,7 @@ export type ProviderOrchestrationAdapterInfrastructure =
| ClaudeAdapterV2.ClaudeAgentSdkQueryRunner
| CodexAdapterV2.CodexAppServerClientFactory
| CursorAgentSdk.CursorAgentSdkRunner
+ | CursorSdk.CursorSdk
| IdAllocator.IdAllocatorV2;
/**
@@ -21,7 +23,7 @@ export type ProviderOrchestrationAdapterInfrastructure =
export const layer = Layer.mergeAll(
ClaudeAdapterV2.layerQueryRunner,
CodexAdapterV2.layerAppServerClientFactory,
- CursorAgentSdk.layer,
+ CursorAgentSdk.layer.pipe(Layer.provideMerge(CursorSdk.layer)),
IdAllocator.layer,
ProviderContinuationRequests.layer,
);
diff --git a/packages/provider-cursor/package.json b/packages/provider-cursor/package.json
index 4a50b964733..e7d2a7c8b35 100644
--- a/packages/provider-cursor/package.json
+++ b/packages/provider-cursor/package.json
@@ -22,6 +22,10 @@
"./server/CursorAgentSdk": {
"types": "./src/server/CursorAgentSdk.ts",
"import": "./src/server/CursorAgentSdk.ts"
+ },
+ "./server/CursorSdk": {
+ "types": "./src/server/CursorSdk.ts",
+ "import": "./src/server/CursorSdk.ts"
}
},
"scripts": {
diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts
index 6a4e209bf19..5bd81aea13c 100644
--- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts
+++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts
@@ -7,6 +7,7 @@ import { vi } from "vite-plus/test";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
+import * as CursorSdk from "./CursorSdk.ts";
const cursorSdkMock = vi.hoisted(() => {
const closeExecutionOrder: Array<string> = [];
@@ -102,6 +103,7 @@ vi.mock("./sdk.ts", () => ({
list: vi.fn(async () => []),
},
},
+ createAgentPlatform: vi.fn(),
}));
const layerTest = CursorAgentSdk.layer.pipe(
@@ -124,6 +126,7 @@ const layerTest = CursorAgentSdk.layer.pipe(
canonical: undefined,
}),
),
+ Layer.provide(CursorSdk.layer),
Layer.provide(NodeServices.layer),
);
diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts
index 30d6090fab4..e0162a4d062 100644
--- a/packages/provider-cursor/src/server/CursorAgentSdk.ts
+++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts
@@ -12,11 +12,13 @@ import {
type ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
-import { Agent, createAgentPlatform } from "./sdk.ts";
+import * as CursorSdk from "./CursorSdk.ts";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const;
@@ -66,16 +68,14 @@ export interface CursorAgentSdkSession {
readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
}
-export interface CursorAgentSdkRunnerShape {
- readonly open: (
- input: CursorAgentSdkOpenInput,
- ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;
- readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;
-}
-
export class CursorAgentSdkRunner extends Context.Service<
CursorAgentSdkRunner,
- CursorAgentSdkRunnerShape
+ {
+ readonly open: (
+ input: CursorAgentSdkOpenInput,
+ ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;
+ readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;
+ }
>()("@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner") {}
export interface CursorAgentSdkLoggedAgentOptions {
@@ -298,49 +298,55 @@ function makeCursorAgentSdkProtocolLogger(input: {
.pipe(Effect.ignore);
}
-/**
- * The Cursor SDK decides once per process whether local sandboxing works, and
- * caches the answer the first time any run starts. Only sandboxed runs point
- * it at its `cursorsandbox` helper first, so after an unsandboxed (Full access)
- * run it caches "unsupported" and rejects every later sandboxed run until the
- * server restarts. Warming a bare sandboxed executor before the first
- * unsandboxed agent opens lets the SDK find the helper and cache the real
- * answer. Warming is best effort: on a machine without sandbox support it
- * fails, the SDK caches "unsupported", and sandboxed runs report that as
- * before.
- */
-let cursorSandboxSupportPrime: Promise<void> | undefined;
-
-function primeCursorSandboxSupport(options: AgentOptions): Promise<void> {
- cursorSandboxSupportPrime ??= (async () => {
- const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
- const platform = await createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
- const release = await platform.prewarmLocalWorkspace({
- ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
- local: {
- ...(cwd === undefined ? {} : { cwd }),
- settingSources: [],
- sandboxOptions: { enabled: true },
- },
- });
- await release();
- })().catch(() => undefined);
- return cursorSandboxSupportPrime;
-}
-
/**
* Runs agents through the Cursor SDK, logging every frame to the protocol
* logger chosen for each opened agent. The live layer writes the native
* provider event log; the replay recorder turns the same frames into a
* transcript.
*/
-export function makeCursorAgentSdkRunner(
+export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
-): CursorAgentSdkRunnerShape {
+) {
+ const { Agent, createAgentPlatform } = yield* CursorSdk.CursorSdk;
+
+ /**
+ * The Cursor SDK decides once per process whether local sandboxing works, and
+ * caches the answer the first time any run starts. Only sandboxed runs point
+ * it at its `cursorsandbox` helper first, so after an unsandboxed (Full access)
+ * run it caches "unsupported" and rejects every later sandboxed run until the
+ * server restarts. Warming a bare sandboxed executor before the first
+ * unsandboxed agent opens lets the SDK find the helper and cache the real
+ * answer. Warming is best effort: on a machine without sandbox support it
+ * fails, the SDK caches "unsupported", and sandboxed runs report that as
+ * before.
+ */
+ const sandboxSupportPrimeStarted = yield* Ref.make(false);
+ const sandboxSupportPrimed = yield* Deferred.make<void>();
+ const primeCursorSandboxSupport = Effect.fn("CursorAgentSdkRunner.primeSandboxSupport")(
+ function* (options: AgentOptions) {
+ if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
+ return yield* Deferred.await(sandboxSupportPrimed);
+ }
+ yield* Effect.tryPromise(async () => {
+ const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
+ const platform = await createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
+ const release = await platform.prewarmLocalWorkspace({
+ ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
+ local: {
+ ...(cwd === undefined ? {} : { cwd }),
+ settingSources: [],
+ sandboxOptions: { enabled: true },
+ },
+ });
+ await release();
+ }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
+ },
+ );
+
return CursorAgentSdkRunner.of({
open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
if (input.options.local?.sandboxOptions?.enabled === false) {
- yield* Effect.promise(() => primeCursorSandboxSupport(input.options));
+ yield* primeCursorSandboxSupport(input.options);
}
const protocolLogger = protocolLoggerFor(input);
const log = (event: CursorAgentSdkProtocolLogEvent) =>
@@ -590,17 +596,13 @@ export function makeCursorAgentSdkRunner(
}),
assertComplete: Effect.void,
});
-}
+});
-export const layer: Layer.Layer<
- CursorAgentSdkRunner,
- never,
- ProviderEventLoggers.ProviderEventLoggers
-> = Layer.effect(
+export const layer = Layer.effect(
CursorAgentSdkRunner,
Effect.gen(function* () {
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
- return makeCursorAgentSdkRunner((input) =>
+ return yield* makeCursorAgentSdkRunner((input) =>
makeCursorAgentSdkProtocolLogger({
nativeEventLogger,
threadId: input.threadId,
diff --git a/packages/provider-cursor/src/server/sdk.test.ts b/packages/provider-cursor/src/server/CursorSdk.test.ts
similarity index 67%
rename from packages/provider-cursor/src/server/sdk.test.ts
rename to packages/provider-cursor/src/server/CursorSdk.test.ts
index 06a9b6229fc..54b6b35cfcd 100644
--- a/packages/provider-cursor/src/server/sdk.test.ts
+++ b/packages/provider-cursor/src/server/CursorSdk.test.ts
@@ -2,9 +2,11 @@
import * as NodeChildProcess from "node:child_process";
import { describe, expect, it } from "vite-plus/test";
-const cursorSdkUrl = new URL("./sdk.ts", import.meta.url).href;
+import { isCursorShellSpawnFailure } from "./CursorSdk.ts";
-// Loads sdk.ts in a fresh process. @cursor/sdk is stubbed so the guard
+const cursorSdkUrl = new URL("./CursorSdk.ts", import.meta.url).href;
+
+// Builds the CursorSdk layer in a fresh process. @cursor/sdk is stubbed so the guard
// can be tested without the real package. The vitest worker already has its
// own unhandledRejection listener, which would hide the process-exit behavior.
const probeProgram = `
@@ -30,56 +32,16 @@ registerHooks({
},
});
-const { isCursorShellSpawnFailure } = await import(${JSON.stringify(cursorSdkUrl)});
+const { layer } = await import(${JSON.stringify(cursorSdkUrl)});
+const Effect = await import("effect/Effect");
+const Layer = await import("effect/Layer");
+const Exit = await import("effect/Exit");
+const Scope = await import("effect/Scope");
+const scope = Scope.makeUnsafe();
+await Effect.runPromise(Layer.buildWithScope(layer, scope));
const mode = process.argv[1];
const missingCwd = join(tmpdir(), "t3-missing-cwd-" + process.pid);
-if (mode === "predicate") {
- const cursorShell = Object.assign(new Error("spawn /bin/zsh ENOENT"), {
- code: "ENOENT",
- syscall: "spawn /bin/zsh",
- path: "/bin/zsh",
- spawnargs: ["-c", "dump_zsh_state >&4", "--", "true"],
- });
- const bashShell = Object.assign(new Error("spawn bash ENOENT"), {
- code: "ENOENT",
- syscall: "spawn bash",
- spawnargs: ["-c", "dump_bash_state >&4"],
- });
- const sandboxRestore = Object.assign(new Error("spawn /bin/zsh ENOENT"), {
- code: "ENOENT",
- syscall: "spawn /bin/zsh",
- spawnargs: ["-c", "builtin eval \\"\${__CURSOR_SANDBOX_ENV_RESTORE:-}\\""],
- });
- const gitSpawn = Object.assign(new Error("spawn git ENOENT"), {
- code: "ENOENT",
- syscall: "spawn git",
- path: "git",
- spawnargs: ["status"],
- });
- const plainZsh = Object.assign(new Error("spawn /bin/zsh ENOENT"), {
- code: "ENOENT",
- syscall: "spawn /bin/zsh",
- path: "/bin/zsh",
- spawnargs: ["-lc", "true"],
- });
- console.log(
- JSON.stringify({
- cursorShell: isCursorShellSpawnFailure(cursorShell),
- bashShell: isCursorShellSpawnFailure(bashShell),
- sandboxRestore: isCursorShellSpawnFailure(sandboxRestore),
- gitSpawn: isCursorShellSpawnFailure(gitSpawn),
- plainZsh: isCursorShellSpawnFailure(plainZsh),
- open: isCursorShellSpawnFailure(
- Object.assign(new Error("open failed"), { code: "ENOENT", syscall: "open" }),
- ),
- plain: isCursorShellSpawnFailure(new Error("boom")),
- string: isCursorShellSpawnFailure("spawn ENOENT"),
- }),
- );
- process.exit(0);
-}
-
if (mode === "cursor-shell") {
const child = spawn("/bin/zsh", ["-c", "dump_zsh_state >&4", "--", "true"], {
cwd: missingCwd,
@@ -88,6 +50,16 @@ if (mode === "cursor-shell") {
Promise.reject(error);
});
setTimeout(() => process.exit(0), 500);
+} else if (mode === "released") {
+ await Effect.runPromise(Scope.close(scope, Exit.void));
+ Promise.reject(
+ Object.assign(new Error("spawn /bin/zsh ENOENT"), {
+ code: "ENOENT",
+ syscall: "spawn /bin/zsh",
+ spawnargs: ["-c", "dump_zsh_state >&4"],
+ }),
+ );
+ setTimeout(() => process.exit(0), 500);
} else if (mode === "other-spawn") {
Promise.reject(
Object.assign(new Error("spawn git ENOENT"), {
@@ -147,19 +119,31 @@ function runProbe(mode: string): Promise<{ code: number | null; stdout: string;
}
describe("isCursorShellSpawnFailure", () => {
- it("matches only Cursor's shell wrapper", async () => {
- const result = await runProbe("predicate");
- expect(result.code).toBe(0);
- expect(JSON.parse(result.stdout)).toEqual({
- cursorShell: true,
- bashShell: true,
- sandboxRestore: true,
- gitSpawn: false,
- plainZsh: false,
- open: false,
- plain: false,
- string: false,
- });
+ it("matches only Cursor's shell wrapper", () => {
+ const spawnFailure = (syscall: string, spawnargs: ReadonlyArray<string>) =>
+ Object.assign(new Error(`${syscall} ENOENT`), { code: "ENOENT", syscall, spawnargs });
+ expect(
+ isCursorShellSpawnFailure(
+ spawnFailure("spawn /bin/zsh", ["-c", "dump_zsh_state >&4", "--", "true"]),
+ ),
+ ).toBe(true);
+ expect(
+ isCursorShellSpawnFailure(spawnFailure("spawn bash", ["-c", "dump_bash_state >&4"])),
+ ).toBe(true);
+ expect(
+ isCursorShellSpawnFailure(
+ spawnFailure("spawn /bin/zsh", ["-c", 'builtin eval "${__CURSOR_SANDBOX_ENV_RESTORE:-}"']),
+ ),
+ ).toBe(true);
+ expect(isCursorShellSpawnFailure(spawnFailure("spawn git", ["status"]))).toBe(false);
+ expect(isCursorShellSpawnFailure(spawnFailure("spawn /bin/zsh", ["-lc", "true"]))).toBe(false);
+ expect(
+ isCursorShellSpawnFailure(
+ Object.assign(new Error("open failed"), { code: "ENOENT", syscall: "open" }),
+ ),
+ ).toBe(false);
+ expect(isCursorShellSpawnFailure(new Error("boom"))).toBe(false);
+ expect(isCursorShellSpawnFailure("spawn ENOENT")).toBe(false);
});
});
@@ -184,6 +168,12 @@ describe("Cursor shell spawn guard", () => {
expect(result.stderr).toContain("boom");
});
+ it("removes the guard when the layer is released", async () => {
+ const result = await runProbe("released");
+ expect(result.code).toBe(1);
+ expect(result.stderr).not.toContain("The server will keep running.");
+ });
+
it("leaves a spawn with no error listener fatal", async () => {
const result = await runProbe("spawn-without-listener");
expect(result.code).toBe(1);
diff --git a/packages/provider-cursor/src/server/CursorSdk.ts b/packages/provider-cursor/src/server/CursorSdk.ts
new file mode 100644
index 00000000000..0497bad3125
--- /dev/null
+++ b/packages/provider-cursor/src/server/CursorSdk.ts
@@ -0,0 +1,83 @@
+// @effect-diagnostics nodeBuiltinImport:off globalConsole:off -- The guard runs in Node's unhandled-rejection callback, outside an Effect runtime. stderr must match Node's default unhandled-rejection print.
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+
+import { Agent, createAgentPlatform } from "./sdk.ts";
+
+/**
+ * The Cursor Agent SDK runs in this process and spawns a shell for tool
+ * calls. The command is Cursor's sandbox wrapper (`dump_zsh_state`,
+ * `dump_bash_state`, `__CURSOR_SANDBOX_ENV_RESTORE`). A bad working directory
+ * makes Node report `spawn /bin/zsh ENOENT`. The SDK listens for that error,
+ * then rejects an internal promise nothing awaits. Node exits on that
+ * unhandled rejection and takes the server with it.
+ *
+ * The guard ignores only that rejection. Every other unhandled rejection
+ * still prints and exits when this is the process's only listener, matching
+ * Node's default. `child_process.spawn` itself is left alone, so git,
+ * terminals, and other providers keep their own error handling.
+ */
+const CURSOR_SHELL_SPAWN_MARKERS = [
+ "dump_zsh_state",
+ "dump_bash_state",
+ "__CURSOR_SANDBOX_ENV_RESTORE",
+] as const;
+
+export function isCursorShellSpawnFailure(reason: unknown): boolean {
+ if (typeof reason !== "object" || reason === null) {
+ return false;
+ }
+ const syscall = Reflect.get(reason, "syscall");
+ const code = Reflect.get(reason, "code");
+ const spawnargs = Reflect.get(reason, "spawnargs");
+ if (typeof syscall !== "string" || !syscall.startsWith("spawn") || typeof code !== "string") {
+ return false;
+ }
+ if (!Array.isArray(spawnargs)) {
+ return false;
+ }
+ return spawnargs.some(
+ (arg) =>
+ typeof arg === "string" && CURSOR_SHELL_SPAWN_MARKERS.some((marker) => arg.includes(marker)),
+ );
+}
+
+function onUnhandledRejection(reason: unknown): void {
+ if (isCursorShellSpawnFailure(reason)) {
+ console.error("Cursor shell spawn failed. The server will keep running.", reason);
+ return;
+ }
+ // Another handler registered besides this one owns the decision.
+ if (process.listenerCount("unhandledRejection") > 1) {
+ return;
+ }
+ console.error(reason);
+ process.exit(1);
+}
+
+/**
+ * The SDK entry points that run agents in this process. Reaching them through
+ * this service keeps the shell spawn guard armed while they are in use.
+ */
+export class CursorSdk extends Context.Service<
+ CursorSdk,
+ {
+ readonly Agent: typeof Agent;
+ readonly createAgentPlatform: typeof createAgentPlatform;
+ }
+>()("@t3tools/provider-cursor/server/CursorSdk") {}
+
+/** Provide once per process: a second guard would defer to the first and swallow real rejections. */
+export const layer = Layer.effect(
+ CursorSdk,
+ Effect.acquireRelease(
+ Effect.sync(() => {
+ process.on("unhandledRejection", onUnhandledRejection);
+ }),
+ () =>
+ Effect.sync(() => {
+ process.off("unhandledRejection", onUnhandledRejection);
+ }),
+ ).pipe(Effect.as(CursorSdk.of({ Agent, createAgentPlatform }))),
+);
diff --git a/packages/provider-cursor/src/server/CursorSdkCatalog.ts b/packages/provider-cursor/src/server/CursorSdkCatalog.ts
index 1a0f6b64949..7f317cc0978 100644
--- a/packages/provider-cursor/src/server/CursorSdkCatalog.ts
+++ b/packages/provider-cursor/src/server/CursorSdkCatalog.ts
@@ -28,13 +28,14 @@ export class CursorSdkCatalogError extends Schema.TaggedError<CursorSdkCatalogEr
}
}
-export interface CursorSdkCatalogShape {
- readonly read: (apiKey: string) => Effect.Effect<CursorSdkCatalogSnapshot, CursorSdkCatalogError>;
-}
-
-export class CursorSdkCatalog extends Context.Service<CursorSdkCatalog, CursorSdkCatalogShape>()(
- "@t3tools/provider-cursor/server/CursorSdkCatalog",
-) {}
+export class CursorSdkCatalog extends Context.Service<
+ CursorSdkCatalog,
+ {
+ readonly read: (
+ apiKey: string,
+ ) => Effect.Effect<CursorSdkCatalogSnapshot, CursorSdkCatalogError>;
+ }
+>()("@t3tools/provider-cursor/server/CursorSdkCatalog") {}
function isAuthenticationFailure(cause: unknown): boolean {
return (
@@ -87,6 +88,8 @@ export const makeCursorSdkCatalog = Effect.fn("CursorSdkCatalog.make")(function*
export const layer = Layer.effect(CursorSdkCatalog, makeCursorSdkCatalog());
-export function layerTest(read: CursorSdkCatalogShape["read"]): Layer.Layer<CursorSdkCatalog> {
+export function layerTest(
+ read: CursorSdkCatalog["Service"]["read"],
+): Layer.Layer<CursorSdkCatalog> {
return Layer.succeed(CursorSdkCatalog, CursorSdkCatalog.of({ read }));
}
diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts
index eee50e4326c..ecca0e80ac7 100644
--- a/packages/provider-cursor/src/server/adapter.ts
+++ b/packages/provider-cursor/src/server/adapter.ts
@@ -34,7 +34,6 @@ import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
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 Queue from "effect/Queue";
@@ -2645,24 +2644,3 @@ export const CursorAdapterV2Driver: ProviderAdapterDriver<
),
),
};
-
-const layer: Layer.Layer<
- ProviderAdapter.ProviderAdapterV2,
- never,
- | CursorAgentSdk.CursorAgentSdkRunner
- | FileSystem.FileSystem
- | Path.Path
- | IdAllocator.IdAllocatorV2
- | McpProviderSessions.McpProviderSessions
- | ProviderHost.ProviderHost
-> = Layer.effect(
- ProviderAdapter.ProviderAdapterV2,
- Effect.gen(function* () {
- const hostEnvironment = yield* HostProcessEnvironment;
- return yield* makeCursorAdapterV2({
- instanceId: CURSOR_DEFAULT_INSTANCE_ID,
- settings: DEFAULT_CURSOR_SETTINGS,
- environment: hostEnvironment,
- });
- }),
-);
diff --git a/packages/provider-cursor/src/server/driver.test.ts b/packages/provider-cursor/src/server/driver.test.ts
index ef24403a4b2..ee0d2ba1ac8 100644
--- a/packages/provider-cursor/src/server/driver.test.ts
+++ b/packages/provider-cursor/src/server/driver.test.ts
@@ -7,13 +7,14 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import { vi } from "vite-plus/test";
-import { HttpClient } from "effect/http";
+import * as HttpClient from "effect/http/HttpClient";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
import { CursorDriver } from "./driver.ts";
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
+import * as CursorSdk from "./CursorSdk.ts";
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";
@@ -23,6 +24,7 @@ const layerTest = TestProviderHost.layer({ runBackgroundWork: false }).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(IdAllocator.layer),
Layer.provideMerge(McpProviderSessions.layer),
+ Layer.provideMerge(CursorSdk.layer),
Layer.provideMerge(
Layer.mock(CursorAgentSdk.CursorAgentSdkRunner)({
open: () => Effect.die("Maintenance resolution must not open a Cursor session"),
diff --git a/packages/provider-cursor/src/server/driver.ts b/packages/provider-cursor/src/server/driver.ts
index e007e8b6fda..698ab5a8853 100644
--- a/packages/provider-cursor/src/server/driver.ts
+++ b/packages/provider-cursor/src/server/driver.ts
@@ -13,7 +13,7 @@ import * as Crypto from "effect/Crypto";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
-import { HttpClient } from "effect/http";
+import * as HttpClient from "effect/http/HttpClient";
import { readCursorUsageLimits } from "./usageLimits.ts";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
@@ -40,6 +40,7 @@ import { probeCursorSkills } from "./skills.ts";
import { makeCursorAuth } from "./auth.ts";
import * as CursorCredentialStore from "./credentialStore.ts";
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
+import * as CursorSdk from "./CursorSdk.ts";
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
const isSdkRunnerError = Schema.is(CursorAgentSdk.CursorAgentSdkRunnerError);
@@ -55,6 +56,7 @@ export type CursorDriverEnv =
| FileSystem.FileSystem
| Path.Path
| HttpClient.HttpClient
+ | CursorSdk.CursorSdk
| ProviderHost.ProviderHost;
export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
@@ -238,7 +240,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
- detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,
+ detail: "Failed to build Cursor snapshot.",
cause,
}),
),
diff --git a/packages/provider-cursor/src/server/sdk.ts b/packages/provider-cursor/src/server/sdk.ts
index 07381bcf3a6..602a0d0d2fd 100644
--- a/packages/provider-cursor/src/server/sdk.ts
+++ b/packages/provider-cursor/src/server/sdk.ts
@@ -1,69 +1,6 @@
-// @effect-diagnostics nodeBuiltinImport:off globalConsole:off -- Installed before the SDK loads, outside an Effect runtime. stderr must match Node's default unhandled-rejection print.
+// @effect-diagnostics nodeBuiltinImport:off -- The SDK must load from disk beside its Webpack chunks.
import * as NodeModule from "node:module";
-/**
- * The Cursor Agent SDK runs in this process and spawns a shell for tool
- * calls. The command is Cursor's sandbox wrapper (`dump_zsh_state`,
- * `dump_bash_state`, `__CURSOR_SANDBOX_ENV_RESTORE`). A bad working directory
- * makes Node report `spawn /bin/zsh ENOENT`. The SDK listens for that error,
- * then rejects an internal promise nothing awaits. Node exits on that
- * unhandled rejection and takes the server with it.
- *
- * This listener ignores only that rejection. Every other unhandled rejection
- * still prints and exits when this is the process's only listener, matching
- * Node's default. `child_process.spawn` itself is left alone, so git,
- * terminals, and other providers keep their own error handling.
- */
-const CURSOR_SHELL_SPAWN_MARKERS = [
- "dump_zsh_state",
- "dump_bash_state",
- "__CURSOR_SANDBOX_ENV_RESTORE",
-] as const;
-
-export function isCursorShellSpawnFailure(reason: unknown): boolean {
- if (typeof reason !== "object" || reason === null) {
- return false;
- }
- const syscall = Reflect.get(reason, "syscall");
- const code = Reflect.get(reason, "code");
- const spawnargs = Reflect.get(reason, "spawnargs");
- if (typeof syscall !== "string" || !syscall.startsWith("spawn") || typeof code !== "string") {
- return false;
- }
- if (!Array.isArray(spawnargs)) {
- return false;
- }
- return spawnargs.some(
- (arg) =>
- typeof arg === "string" && CURSOR_SHELL_SPAWN_MARKERS.some((marker) => arg.includes(marker)),
- );
-}
-
-let cursorShellSpawnGuardInstalled = false;
-
-function installCursorShellSpawnGuard(): void {
- if (cursorShellSpawnGuardInstalled) {
- return;
- }
- cursorShellSpawnGuardInstalled = true;
-
- process.on("unhandledRejection", (reason) => {
- if (isCursorShellSpawnFailure(reason)) {
- console.error("Cursor shell spawn failed. The server will keep running.", reason);
- return;
- }
- // Another handler registered besides this one owns the decision.
- if (process.listenerCount("unhandledRejection") > 1) {
- return;
- }
- console.error(reason);
- process.exit(1);
- });
-}
-
-// Arm before the SDK loads. Its shell tools spawn from this process.
-installCursorShellSpawnGuard();
-
// Cursor's Webpack chunks and local helpers must stay beside the SDK entry.
// createRequire also loads that disk-backed package from a Node SEA executable.
const requireCursorSdk = NodeModule.createRequire(import.meta.url);
diff --git a/packages/provider-cursor/src/server/textGeneration.test.ts b/packages/provider-cursor/src/server/textGeneration.test.ts
index 8b007c9dbaf..89d6ec895d1 100644
--- a/packages/provider-cursor/src/server/textGeneration.test.ts
+++ b/packages/provider-cursor/src/server/textGeneration.test.ts
@@ -5,12 +5,14 @@ import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
+import * as Layer from "effect/Layer";
import * as TestClock from "effect/testing/TestClock";
import * as Schema from "effect/Schema";
import { createModelSelection } from "@t3tools/shared/model";
import { beforeEach, vi } from "vite-plus/test";
import { makeCursorTextGeneration } from "./textGeneration.ts";
+import * as CursorSdk from "./CursorSdk.ts";
const cursorSdkMock = vi.hoisted(() => ({
create: vi.fn<(options: unknown) => Promise<unknown>>(),
@@ -25,13 +27,17 @@ const cursorSdkMock = vi.hoisted(() => ({
})),
}));
-vi.mock("./sdk.ts", () => ({ Agent: { create: cursorSdkMock.create } }));
+vi.mock("./sdk.ts", () => ({
+ Agent: { create: cursorSdkMock.create },
+ createAgentPlatform: vi.fn(),
+}));
let hasCustomPolicy = false;
const layerFs = FileSystem.layerNoop({
exists: () => Effect.succeed(hasCustomPolicy),
makeTempDirectoryScoped: () => Effect.succeed("/isolated-text-generation"),
});
+const layerTest = Layer.merge(layerFs, CursorSdk.layer);
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
const cursorSettings = decodeCursorSettings({ enabled: true });
@@ -90,7 +96,7 @@ describe("CursorTextGeneration", () => {
expect(cursorSdkMock.create).toHaveBeenLastCalledWith(
expect.objectContaining({ apiKey: "second-browser-key" }),
);
- }).pipe(Effect.provide(layerFs)),
+ }).pipe(Effect.provide(layerTest)),
);
it.effect("uses the Cursor SDK prompt API with model parameters and API key", () =>
@@ -139,7 +145,7 @@ describe("CursorTextGeneration", () => {
enableAgentRetries: true,
},
});
- }).pipe(Effect.provide(layerFs)),
+ }).pipe(Effect.provide(layerTest)),
);
it.effect("continues in the temp directory when the SDK cannot sandbox", () =>
@@ -175,7 +181,7 @@ describe("CursorTextGeneration", () => {
enableAgentRetries: true,
},
});
- }).pipe(Effect.provide(layerFs)),
+ }).pipe(Effect.provide(layerTest)),
);
it.effect("does not retry Agent.create for errors other than an unsupported sandbox", () =>
@@ -199,7 +205,7 @@ describe("CursorTextGeneration", () => {
expect(error.detail).toBe("Cursor SDK text generation failed.");
expect(cursorSdkMock.create).toHaveBeenCalledTimes(1);
- }).pipe(Effect.provide(layerFs)),
+ }).pipe(Effect.provide(layerTest)),
);
it.effect("accepts json objects with extra assistant text around them", () =>
@@ -227,7 +233,7 @@ describe("CursorTextGeneration", () => {
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
expect(generated.body).toBe("");
- }).pipe(Effect.provide(layerFs)),
+ }).pipe(Effect.provide(layerTest)),
);
it.effect("generates thread titles through Cursor SDK text generation", () =>
@@ -251,7 +257,7 @@ describe("CursorTextGeneration", () => {
});
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
- }).pipe(Effect.provide(layerFs)),
+ }).pipe(Effect.provide(layerTest)),
);
it.effect.each(["error", "cancelled"] as const)(
@@ -285,7 +291,7 @@ describe("CursorTextGeneration", () => {
: "Cursor SDK request finished with an error.",
);
expect(cursorSdkMock.close).toHaveBeenCalledOnce();
- }).pipe(Effect.provide(layerFs)),
+ }).pipe(Effect.provide(layerTest)),
);
it.effect("fails closed when ambient sandbox policy can expand write access", () =>
@@ -301,7 +307,7 @@ describe("CursorTextGeneration", () => {
);
expect(failure.detail).toContain("custom ~/.cursor/sandbox.json");
expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
- }).pipe(Effect.provide(layerFs)),
+ }).pipe(Effect.provide(layerTest)),
);
it.effect("cancels the native run when text generation times out", () =>
@@ -327,7 +333,7 @@ describe("CursorTextGeneration", () => {
expect((yield* Fiber.join(result)).detail).toContain("timed out");
expect(cursorSdkMock.cancel).toHaveBeenCalledOnce();
expect(cursorSdkMock.close).toHaveBeenCalledOnce();
- }).pipe(Effect.provide(layerFs), Effect.scoped),
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
);
it.effect.each(["create", "send"] as const)(
@@ -389,7 +395,7 @@ describe("CursorTextGeneration", () => {
expect(cursorSdkMock.close).toHaveBeenCalledOnce();
expect(wait).not.toHaveBeenCalled();
if (phase === "send") expect(cursorSdkMock.cancel).toHaveBeenCalledOnce();
- }).pipe(Effect.provide(layerFs), Effect.scoped),
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
);
it.effect("requires CURSOR_API_KEY before calling the SDK", () =>
@@ -411,6 +417,6 @@ describe("CursorTextGeneration", () => {
expect(error.detail).toBe("Sign in with Cursor or add CURSOR_API_KEY in provider settings.");
expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
- }).pipe(Effect.provide(layerFs)),
+ }).pipe(Effect.provide(layerTest)),
);
});
diff --git a/packages/provider-cursor/src/server/textGeneration.ts b/packages/provider-cursor/src/server/textGeneration.ts
index 924d620bbc7..59fa3dfc452 100644
--- a/packages/provider-cursor/src/server/textGeneration.ts
+++ b/packages/provider-cursor/src/server/textGeneration.ts
@@ -2,7 +2,6 @@ import * as NodeOS from "node:os";
import * as FileSystem from "effect/FileSystem";
import type { AgentOptions, RunResult } from "@cursor/sdk";
-import { Agent } from "./sdk.ts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -13,6 +12,7 @@ import type { CursorSettings } from "../settings.ts";
import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
import { cursorSdkModelSelection } from "./sdkModel.ts";
import type { CursorAuth } from "./auth.ts";
+import * as CursorSdk from "./CursorSdk.ts";
const CURSOR_TIMEOUT_MS = 180_000;
@@ -58,6 +58,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
withAccess?: CursorAuth["withAccess"],
) {
const fs = yield* FileSystem.FileSystem;
+ const { Agent } = yield* CursorSdk.CursorSdk;
const resolvedEnvironment = environment ?? process.env;
const resolveCursorApiKey = (operation: TextGenerationOperations.Operation) =>
diff --git a/packages/provider-cursor/src/server/usageLimits.test.ts b/packages/provider-cursor/src/server/usageLimits.test.ts
index 634168447d9..ff765fcdec2 100644
--- a/packages/provider-cursor/src/server/usageLimits.test.ts
+++ b/packages/provider-cursor/src/server/usageLimits.test.ts
@@ -4,7 +4,8 @@ import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
-import { HttpClient, HttpClientResponse } from "effect/http";
+import * as HttpClient from "effect/http/HttpClient";
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
import { cursorUsageResponseToLimits, readCursorUsageLimits } from "./usageLimits.ts";
const withNodeServices = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>) =>
diff --git a/packages/provider-cursor/src/server/usageLimits.ts b/packages/provider-cursor/src/server/usageLimits.ts
index 24c314fe7d7..78f096f8d33 100644
--- a/packages/provider-cursor/src/server/usageLimits.ts
+++ b/packages/provider-cursor/src/server/usageLimits.ts
@@ -9,7 +9,9 @@ import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
-import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
+import * as HttpClient from "effect/http/HttpClient";
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
import {
clampPercent,
makeUnavailableUsageLimits,