The best way to control Claude Code, Codex and more from any computer or phone
refactor(provider-cursor): follow the Effect service conventions (#17545)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 9, 2026 at 10:11 UTC
33806e73555107b8ac8fb18fd15b9dfb87ec6557
17 files changed
+247
-229
apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts
+3
-1
@@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
3
import * as Config from "effect/Config";
4
import * as Console from "effect/Console";
5
import * as Effect from "effect/Effect";
6
+import * as Layer from "effect/Layer";
7
import * as FileSystem from "effect/FileSystem";
8
import * as Option from "effect/Option";
9
import * as Path from "effect/Path";
@@ -10,6 +11,7 @@ import * as Redacted from "effect/Redacted";
11
import * as Schema from "effect/Schema";
12
import * as Struct from "effect/Struct";
13
import { Command, Flag } from "effect/cli";
14
+import * as CursorSdk from "@t3tools/provider-cursor/server/CursorSdk";
15
16
import {
17
recordCursorAgentSdkReplayTranscript,
@@ -219,6 +221,6 @@ const recordCursorReplayCommand = Command.make(
221
);
222
223
Command.run(recordCursorReplayCommand, { version: "0.0.0" }).pipe(
222
- Effect.provide(NodeServices.layer),
224
+ Effect.provide(Layer.mergeAll(CursorSdk.layer, NodeServices.layer)),
225
NodeRuntime.runMain,
226
);
apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts
+4
-4
@@ -213,7 +213,7 @@ function replayRunnerError(
213
214
export function makeCursorAgentSdkReplayRunner(
215
transcript: CursorAgentSdkReplayTranscript,
216
-): CursorAgentSdk.CursorAgentSdkRunnerShape {
216
+): CursorAgentSdk.CursorAgentSdkRunner["Service"] {
217
let cursor = 0;
218
let failure: CursorAgentSdkReplayError | null = null;
219
let cursorAdvanced = makeSignal();
@@ -491,7 +491,7 @@ export function makeCursorAgentSdkReplayRunner(
491
function layerCursorAgentSdkReplay(
492
transcript: CursorAgentSdkReplayTranscript,
493
options?: {
494
- readonly runner?: CursorAgentSdk.CursorAgentSdkRunnerShape;
494
+ readonly runner?: CursorAgentSdk.CursorAgentSdkRunner["Service"];
495
readonly assertCompleteOnFinalize?: boolean;
496
},
497
): Layer.Layer<CursorAgentSdk.CursorAgentSdkRunner> {
@@ -512,7 +512,7 @@ function layerCursorAgentSdkReplay(
512
export function layer(
513
transcript: CursorAgentSdkReplayTranscript,
514
options?: {
515
- readonly runner?: CursorAgentSdk.CursorAgentSdkRunnerShape;
515
+ readonly runner?: CursorAgentSdk.CursorAgentSdkRunner["Service"];
516
readonly assertCompleteOnFinalize?: boolean;
517
},
518
) {
@@ -807,7 +807,7 @@ export const recordCursorAgentSdkReplayTranscript = Effect.fn(
807
heldUntilCancel = [];
808
}
809
});
810
- const runner = CursorAgentSdk.makeCursorAgentSdkRunner(() => recordFrame);
810
+ const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => recordFrame);
811
812
const awaitSignal = (signal: Deferred.Deferred<void>, description: string) =>
813
Deferred.await(signal).pipe(
apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts
+3
-1
@@ -3,6 +3,7 @@ import * as Layer from "effect/Layer";
3
import * as ClaudeAdapterV2 from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
4
import * as CodexAdapterV2 from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
5
import * as CursorAgentSdk from "@t3tools/provider-cursor/server/CursorAgentSdk";
6
+import * as CursorSdk from "@t3tools/provider-cursor/server/CursorSdk";
7
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
8
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
9
@@ -10,6 +11,7 @@ export type ProviderOrchestrationAdapterInfrastructure =
11
| ClaudeAdapterV2.ClaudeAgentSdkQueryRunner
12
| CodexAdapterV2.CodexAppServerClientFactory
13
| CursorAgentSdk.CursorAgentSdkRunner
14
+ | CursorSdk.CursorSdk
15
| IdAllocator.IdAllocatorV2;
16
17
/**
@@ -21,7 +23,7 @@ export type ProviderOrchestrationAdapterInfrastructure =
23
export const layer = Layer.mergeAll(
24
ClaudeAdapterV2.layerQueryRunner,
25
CodexAdapterV2.layerAppServerClientFactory,
24
- CursorAgentSdk.layer,
26
+ CursorAgentSdk.layer.pipe(Layer.provideMerge(CursorSdk.layer)),
27
IdAllocator.layer,
28
ProviderContinuationRequests.layer,
29
);
packages/provider-cursor/package.json
+4
@@ -22,6 +22,10 @@
22
"./server/CursorAgentSdk": {
23
"types": "./src/server/CursorAgentSdk.ts",
24
"import": "./src/server/CursorAgentSdk.ts"
25
+ },
26
+ "./server/CursorSdk": {
27
+ "types": "./src/server/CursorSdk.ts",
28
+ "import": "./src/server/CursorSdk.ts"
29
}
30
},
31
"scripts": {
packages/provider-cursor/src/server/CursorAgentSdk.test.ts
+3
@@ -7,6 +7,7 @@ import { vi } from "vite-plus/test";
7
8
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
9
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
10
+import * as CursorSdk from "./CursorSdk.ts";
11
12
const cursorSdkMock = vi.hoisted(() => {
13
const closeExecutionOrder: Array<string> = [];
@@ -102,6 +103,7 @@ vi.mock("./sdk.ts", () => ({
103
list: vi.fn(async () => []),
104
},
105
},
106
+ createAgentPlatform: vi.fn(),
107
}));
108
109
const layerTest = CursorAgentSdk.layer.pipe(
@@ -124,6 +126,7 @@ const layerTest = CursorAgentSdk.layer.pipe(
126
canonical: undefined,
127
}),
128
),
129
+ Layer.provide(CursorSdk.layer),
130
Layer.provide(NodeServices.layer),
131
);
132
packages/provider-cursor/src/server/CursorAgentSdk.ts
+51
-49
@@ -12,11 +12,13 @@ import {
12
type ThreadId,
13
} from "@t3tools/contracts";
14
import * as Context from "effect/Context";
15
+import * as Deferred from "effect/Deferred";
16
import * as Effect from "effect/Effect";
17
import * as Layer from "effect/Layer";
18
+import * as Ref from "effect/Ref";
19
import * as Schema from "effect/Schema";
20
19
-import { Agent, createAgentPlatform } from "./sdk.ts";
21
+import * as CursorSdk from "./CursorSdk.ts";
22
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
23
24
export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const;
@@ -66,16 +68,14 @@ export interface CursorAgentSdkSession {
68
readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
69
}
70
69
-export interface CursorAgentSdkRunnerShape {
70
- readonly open: (
71
- input: CursorAgentSdkOpenInput,
72
- ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;
73
- readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;
74
-}
75
-
71
export class CursorAgentSdkRunner extends Context.Service<
72
CursorAgentSdkRunner,
78
- CursorAgentSdkRunnerShape
73
+ {
74
+ readonly open: (
75
+ input: CursorAgentSdkOpenInput,
76
+ ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;
77
+ readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;
78
+ }
79
>()("@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner") {}
80
81
export interface CursorAgentSdkLoggedAgentOptions {
@@ -298,49 +298,55 @@ function makeCursorAgentSdkProtocolLogger(input: {
298
.pipe(Effect.ignore);
299
}
300
301
-/**
302
- * The Cursor SDK decides once per process whether local sandboxing works, and
303
- * caches the answer the first time any run starts. Only sandboxed runs point
304
- * it at its `cursorsandbox` helper first, so after an unsandboxed (Full access)
305
- * run it caches "unsupported" and rejects every later sandboxed run until the
306
- * server restarts. Warming a bare sandboxed executor before the first
307
- * unsandboxed agent opens lets the SDK find the helper and cache the real
308
- * answer. Warming is best effort: on a machine without sandbox support it
309
- * fails, the SDK caches "unsupported", and sandboxed runs report that as
310
- * before.
311
- */
312
-let cursorSandboxSupportPrime: Promise<void> | undefined;
313
-
314
-function primeCursorSandboxSupport(options: AgentOptions): Promise<void> {
315
- cursorSandboxSupportPrime ??= (async () => {
316
- const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
317
- const platform = await createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
318
- const release = await platform.prewarmLocalWorkspace({
319
- ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
320
- local: {
321
- ...(cwd === undefined ? {} : { cwd }),
322
- settingSources: [],
323
- sandboxOptions: { enabled: true },
324
- },
325
- });
326
- await release();
327
- })().catch(() => undefined);
328
- return cursorSandboxSupportPrime;
329
-}
330
-
301
/**
302
* Runs agents through the Cursor SDK, logging every frame to the protocol
303
* logger chosen for each opened agent. The live layer writes the native
304
* provider event log; the replay recorder turns the same frames into a
305
* transcript.
306
*/
337
-export function makeCursorAgentSdkRunner(
307
+export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
308
protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
339
-): CursorAgentSdkRunnerShape {
309
+) {
310
+ const { Agent, createAgentPlatform } = yield* CursorSdk.CursorSdk;
311
+
312
+ /**
313
+ * The Cursor SDK decides once per process whether local sandboxing works, and
314
+ * caches the answer the first time any run starts. Only sandboxed runs point
315
+ * it at its `cursorsandbox` helper first, so after an unsandboxed (Full access)
316
+ * run it caches "unsupported" and rejects every later sandboxed run until the
317
+ * server restarts. Warming a bare sandboxed executor before the first
318
+ * unsandboxed agent opens lets the SDK find the helper and cache the real
319
+ * answer. Warming is best effort: on a machine without sandbox support it
320
+ * fails, the SDK caches "unsupported", and sandboxed runs report that as
321
+ * before.
322
+ */
323
+ const sandboxSupportPrimeStarted = yield* Ref.make(false);
324
+ const sandboxSupportPrimed = yield* Deferred.make<void>();
325
+ const primeCursorSandboxSupport = Effect.fn("CursorAgentSdkRunner.primeSandboxSupport")(
326
+ function* (options: AgentOptions) {
327
+ if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
328
+ return yield* Deferred.await(sandboxSupportPrimed);
329
+ }
330
+ yield* Effect.tryPromise(async () => {
331
+ const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
332
+ const platform = await createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
333
+ const release = await platform.prewarmLocalWorkspace({
334
+ ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
335
+ local: {
336
+ ...(cwd === undefined ? {} : { cwd }),
337
+ settingSources: [],
338
+ sandboxOptions: { enabled: true },
339
+ },
340
+ });
341
+ await release();
342
+ }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
343
+ },
344
+ );
345
+
346
return CursorAgentSdkRunner.of({
347
open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
348
if (input.options.local?.sandboxOptions?.enabled === false) {
343
- yield* Effect.promise(() => primeCursorSandboxSupport(input.options));
349
+ yield* primeCursorSandboxSupport(input.options);
350
}
351
const protocolLogger = protocolLoggerFor(input);
352
const log = (event: CursorAgentSdkProtocolLogEvent) =>
@@ -590,17 +596,13 @@ export function makeCursorAgentSdkRunner(
596
}),
597
assertComplete: Effect.void,
598
});
593
-}
599
+});
600
595
-export const layer: Layer.Layer<
596
- CursorAgentSdkRunner,
597
- never,
598
- ProviderEventLoggers.ProviderEventLoggers
599
-> = Layer.effect(
601
+export const layer = Layer.effect(
602
CursorAgentSdkRunner,
603
Effect.gen(function* () {
604
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
603
- return makeCursorAgentSdkRunner((input) =>
605
+ return yield* makeCursorAgentSdkRunner((input) =>
606
makeCursorAgentSdkProtocolLogger({
607
nativeEventLogger,
608
threadId: input.threadId,
packages/provider-cursor/src/server/CursorSdk.test.ts
renamed
+52
-62
@@ -2,9 +2,11 @@
2
import * as NodeChildProcess from "node:child_process";
3
import { describe, expect, it } from "vite-plus/test";
4
5
-const cursorSdkUrl = new URL("./sdk.ts", import.meta.url).href;
5
+import { isCursorShellSpawnFailure } from "./CursorSdk.ts";
6
7
-// Loads sdk.ts in a fresh process. @cursor/sdk is stubbed so the guard
7
+const cursorSdkUrl = new URL("./CursorSdk.ts", import.meta.url).href;
8
+
9
+// Builds the CursorSdk layer in a fresh process. @cursor/sdk is stubbed so the guard
10
// can be tested without the real package. The vitest worker already has its
11
// own unhandledRejection listener, which would hide the process-exit behavior.
12
const probeProgram = `
@@ -30,56 +32,16 @@ registerHooks({
32
},
33
});
34
33
-const { isCursorShellSpawnFailure } = await import(${JSON.stringify(cursorSdkUrl)});
35
+const { layer } = await import(${JSON.stringify(cursorSdkUrl)});
36
+const Effect = await import("effect/Effect");
37
+const Layer = await import("effect/Layer");
38
+const Exit = await import("effect/Exit");
39
+const Scope = await import("effect/Scope");
40
+const scope = Scope.makeUnsafe();
41
+await Effect.runPromise(Layer.buildWithScope(layer, scope));
42
const mode = process.argv[1];
43
const missingCwd = join(tmpdir(), "t3-missing-cwd-" + process.pid);
44
37
-if (mode === "predicate") {
38
- const cursorShell = Object.assign(new Error("spawn /bin/zsh ENOENT"), {
39
- code: "ENOENT",
40
- syscall: "spawn /bin/zsh",
41
- path: "/bin/zsh",
42
- spawnargs: ["-c", "dump_zsh_state >&4", "--", "true"],
43
- });
44
- const bashShell = Object.assign(new Error("spawn bash ENOENT"), {
45
- code: "ENOENT",
46
- syscall: "spawn bash",
47
- spawnargs: ["-c", "dump_bash_state >&4"],
48
- });
49
- const sandboxRestore = Object.assign(new Error("spawn /bin/zsh ENOENT"), {
50
- code: "ENOENT",
51
- syscall: "spawn /bin/zsh",
52
- spawnargs: ["-c", "builtin eval \\"\${__CURSOR_SANDBOX_ENV_RESTORE:-}\\""],
53
- });
54
- const gitSpawn = Object.assign(new Error("spawn git ENOENT"), {
55
- code: "ENOENT",
56
- syscall: "spawn git",
57
- path: "git",
58
- spawnargs: ["status"],
59
- });
60
- const plainZsh = Object.assign(new Error("spawn /bin/zsh ENOENT"), {
61
- code: "ENOENT",
62
- syscall: "spawn /bin/zsh",
63
- path: "/bin/zsh",
64
- spawnargs: ["-lc", "true"],
65
- });
66
- console.log(
67
- JSON.stringify({
68
- cursorShell: isCursorShellSpawnFailure(cursorShell),
69
- bashShell: isCursorShellSpawnFailure(bashShell),
70
- sandboxRestore: isCursorShellSpawnFailure(sandboxRestore),
71
- gitSpawn: isCursorShellSpawnFailure(gitSpawn),
72
- plainZsh: isCursorShellSpawnFailure(plainZsh),
73
- open: isCursorShellSpawnFailure(
74
- Object.assign(new Error("open failed"), { code: "ENOENT", syscall: "open" }),
75
- ),
76
- plain: isCursorShellSpawnFailure(new Error("boom")),
77
- string: isCursorShellSpawnFailure("spawn ENOENT"),
78
- }),
79
- );
80
- process.exit(0);
81
-}
82
-
45
if (mode === "cursor-shell") {
46
const child = spawn("/bin/zsh", ["-c", "dump_zsh_state >&4", "--", "true"], {
47
cwd: missingCwd,
@@ -88,6 +50,16 @@ if (mode === "cursor-shell") {
50
Promise.reject(error);
51
});
52
setTimeout(() => process.exit(0), 500);
53
+} else if (mode === "released") {
54
+ await Effect.runPromise(Scope.close(scope, Exit.void));
55
+ Promise.reject(
56
+ Object.assign(new Error("spawn /bin/zsh ENOENT"), {
57
+ code: "ENOENT",
58
+ syscall: "spawn /bin/zsh",
59
+ spawnargs: ["-c", "dump_zsh_state >&4"],
60
+ }),
61
+ );
62
+ setTimeout(() => process.exit(0), 500);
63
} else if (mode === "other-spawn") {
64
Promise.reject(
65
Object.assign(new Error("spawn git ENOENT"), {
@@ -147,19 +119,31 @@ function runProbe(mode: string): Promise<{ code: number | null; stdout: string;
119
}
120
121
describe("isCursorShellSpawnFailure", () => {
150
- it("matches only Cursor's shell wrapper", async () => {
151
- const result = await runProbe("predicate");
152
- expect(result.code).toBe(0);
153
- expect(JSON.parse(result.stdout)).toEqual({
154
- cursorShell: true,
155
- bashShell: true,
156
- sandboxRestore: true,
157
- gitSpawn: false,
158
- plainZsh: false,
159
- open: false,
160
- plain: false,
161
- string: false,
162
- });
122
+ it("matches only Cursor's shell wrapper", () => {
123
+ const spawnFailure = (syscall: string, spawnargs: ReadonlyArray<string>) =>
124
+ Object.assign(new Error(`${syscall} ENOENT`), { code: "ENOENT", syscall, spawnargs });
125
+ expect(
126
+ isCursorShellSpawnFailure(
127
+ spawnFailure("spawn /bin/zsh", ["-c", "dump_zsh_state >&4", "--", "true"]),
128
+ ),
129
+ ).toBe(true);
130
+ expect(
131
+ isCursorShellSpawnFailure(spawnFailure("spawn bash", ["-c", "dump_bash_state >&4"])),
132
+ ).toBe(true);
133
+ expect(
134
+ isCursorShellSpawnFailure(
135
+ spawnFailure("spawn /bin/zsh", ["-c", 'builtin eval "${__CURSOR_SANDBOX_ENV_RESTORE:-}"']),
136
+ ),
137
+ ).toBe(true);
138
+ expect(isCursorShellSpawnFailure(spawnFailure("spawn git", ["status"]))).toBe(false);
139
+ expect(isCursorShellSpawnFailure(spawnFailure("spawn /bin/zsh", ["-lc", "true"]))).toBe(false);
140
+ expect(
141
+ isCursorShellSpawnFailure(
142
+ Object.assign(new Error("open failed"), { code: "ENOENT", syscall: "open" }),
143
+ ),
144
+ ).toBe(false);
145
+ expect(isCursorShellSpawnFailure(new Error("boom"))).toBe(false);
146
+ expect(isCursorShellSpawnFailure("spawn ENOENT")).toBe(false);
147
});
148
});
149
@@ -184,6 +168,12 @@ describe("Cursor shell spawn guard", () => {
168
expect(result.stderr).toContain("boom");
169
});
170
171
+ it("removes the guard when the layer is released", async () => {
172
+ const result = await runProbe("released");
173
+ expect(result.code).toBe(1);
174
+ expect(result.stderr).not.toContain("The server will keep running.");
175
+ });
176
+
177
it("leaves a spawn with no error listener fatal", async () => {
178
const result = await runProbe("spawn-without-listener");
179
expect(result.code).toBe(1);
packages/provider-cursor/src/server/CursorSdk.ts
new
+83
@@ -0,0 +1,83 @@
1
+// @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.
2
+import * as Context from "effect/Context";
3
+import * as Effect from "effect/Effect";
4
+import * as Layer from "effect/Layer";
5
+
6
+import { Agent, createAgentPlatform } from "./sdk.ts";
7
+
8
+/**
9
+ * The Cursor Agent SDK runs in this process and spawns a shell for tool
10
+ * calls. The command is Cursor's sandbox wrapper (`dump_zsh_state`,
11
+ * `dump_bash_state`, `__CURSOR_SANDBOX_ENV_RESTORE`). A bad working directory
12
+ * makes Node report `spawn /bin/zsh ENOENT`. The SDK listens for that error,
13
+ * then rejects an internal promise nothing awaits. Node exits on that
14
+ * unhandled rejection and takes the server with it.
15
+ *
16
+ * The guard ignores only that rejection. Every other unhandled rejection
17
+ * still prints and exits when this is the process's only listener, matching
18
+ * Node's default. `child_process.spawn` itself is left alone, so git,
19
+ * terminals, and other providers keep their own error handling.
20
+ */
21
+const CURSOR_SHELL_SPAWN_MARKERS = [
22
+ "dump_zsh_state",
23
+ "dump_bash_state",
24
+ "__CURSOR_SANDBOX_ENV_RESTORE",
25
+] as const;
26
+
27
+export function isCursorShellSpawnFailure(reason: unknown): boolean {
28
+ if (typeof reason !== "object" || reason === null) {
29
+ return false;
30
+ }
31
+ const syscall = Reflect.get(reason, "syscall");
32
+ const code = Reflect.get(reason, "code");
33
+ const spawnargs = Reflect.get(reason, "spawnargs");
34
+ if (typeof syscall !== "string" || !syscall.startsWith("spawn") || typeof code !== "string") {
35
+ return false;
36
+ }
37
+ if (!Array.isArray(spawnargs)) {
38
+ return false;
39
+ }
40
+ return spawnargs.some(
41
+ (arg) =>
42
+ typeof arg === "string" && CURSOR_SHELL_SPAWN_MARKERS.some((marker) => arg.includes(marker)),
43
+ );
44
+}
45
+
46
+function onUnhandledRejection(reason: unknown): void {
47
+ if (isCursorShellSpawnFailure(reason)) {
48
+ console.error("Cursor shell spawn failed. The server will keep running.", reason);
49
+ return;
50
+ }
51
+ // Another handler registered besides this one owns the decision.
52
+ if (process.listenerCount("unhandledRejection") > 1) {
53
+ return;
54
+ }
55
+ console.error(reason);
56
+ process.exit(1);
57
+}
58
+
59
+/**
60
+ * The SDK entry points that run agents in this process. Reaching them through
61
+ * this service keeps the shell spawn guard armed while they are in use.
62
+ */
63
+export class CursorSdk extends Context.Service<
64
+ CursorSdk,
65
+ {
66
+ readonly Agent: typeof Agent;
67
+ readonly createAgentPlatform: typeof createAgentPlatform;
68
+ }
69
+>()("@t3tools/provider-cursor/server/CursorSdk") {}
70
+
71
+/** Provide once per process: a second guard would defer to the first and swallow real rejections. */
72
+export const layer = Layer.effect(
73
+ CursorSdk,
74
+ Effect.acquireRelease(
75
+ Effect.sync(() => {
76
+ process.on("unhandledRejection", onUnhandledRejection);
77
+ }),
78
+ () =>
79
+ Effect.sync(() => {
80
+ process.off("unhandledRejection", onUnhandledRejection);
81
+ }),
82
+ ).pipe(Effect.as(CursorSdk.of({ Agent, createAgentPlatform }))),
83
+);
packages/provider-cursor/src/server/CursorSdkCatalog.ts
+11
-8
@@ -28,13 +28,14 @@ export class CursorSdkCatalogError extends Schema.TaggedError<CursorSdkCatalogEr
28
}
29
}
30
31
-export interface CursorSdkCatalogShape {
32
- readonly read: (apiKey: string) => Effect.Effect<CursorSdkCatalogSnapshot, CursorSdkCatalogError>;
33
-}
34
-
35
-export class CursorSdkCatalog extends Context.Service<CursorSdkCatalog, CursorSdkCatalogShape>()(
36
- "@t3tools/provider-cursor/server/CursorSdkCatalog",
37
-) {}
31
+export class CursorSdkCatalog extends Context.Service<
32
+ CursorSdkCatalog,
33
+ {
34
+ readonly read: (
35
+ apiKey: string,
36
+ ) => Effect.Effect<CursorSdkCatalogSnapshot, CursorSdkCatalogError>;
37
+ }
38
+>()("@t3tools/provider-cursor/server/CursorSdkCatalog") {}
39
40
function isAuthenticationFailure(cause: unknown): boolean {
41
return (
@@ -87,6 +88,8 @@ export const makeCursorSdkCatalog = Effect.fn("CursorSdkCatalog.make")(function*
88
89
export const layer = Layer.effect(CursorSdkCatalog, makeCursorSdkCatalog());
90
90
-export function layerTest(read: CursorSdkCatalogShape["read"]): Layer.Layer<CursorSdkCatalog> {
91
+export function layerTest(
92
+ read: CursorSdkCatalog["Service"]["read"],
93
+): Layer.Layer<CursorSdkCatalog> {
94
return Layer.succeed(CursorSdkCatalog, CursorSdkCatalog.of({ read }));
95
}
packages/provider-cursor/src/server/adapter.ts
-22
@@ -34,7 +34,6 @@ import * as DateTime from "effect/DateTime";
34
import * as Deferred from "effect/Deferred";
35
import * as Effect from "effect/Effect";
36
import * as FileSystem from "effect/FileSystem";
37
-import * as Layer from "effect/Layer";
37
import * as Option from "effect/Option";
38
import * as Path from "effect/Path";
39
import * as Queue from "effect/Queue";
@@ -2645,24 +2644,3 @@ export const CursorAdapterV2Driver: ProviderAdapterDriver<
2644
),
2645
),
2646
};
2648
-
2649
-const layer: Layer.Layer<
2650
- ProviderAdapter.ProviderAdapterV2,
2651
- never,
2652
- | CursorAgentSdk.CursorAgentSdkRunner
2653
- | FileSystem.FileSystem
2654
- | Path.Path
2655
- | IdAllocator.IdAllocatorV2
2656
- | McpProviderSessions.McpProviderSessions
2657
- | ProviderHost.ProviderHost
2658
-> = Layer.effect(
2659
- ProviderAdapter.ProviderAdapterV2,
2660
- Effect.gen(function* () {
2661
- const hostEnvironment = yield* HostProcessEnvironment;
2662
- return yield* makeCursorAdapterV2({
2663
- instanceId: CURSOR_DEFAULT_INSTANCE_ID,
2664
- settings: DEFAULT_CURSOR_SETTINGS,
2665
- environment: hostEnvironment,
2666
- });
2667
- }),
2668
-);
packages/provider-cursor/src/server/driver.test.ts
+3
-1
@@ -7,13 +7,14 @@ import * as Layer from "effect/Layer";
7
import * as Option from "effect/Option";
8
import * as Stream from "effect/Stream";
9
import { vi } from "vite-plus/test";
10
-import { HttpClient } from "effect/http";
10
+import * as HttpClient from "effect/http/HttpClient";
11
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12
13
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
14
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
15
import { CursorDriver } from "./driver.ts";
16
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
17
+import * as CursorSdk from "./CursorSdk.ts";
18
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
19
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
20
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
@@ -23,6 +24,7 @@ const layerTest = TestProviderHost.layer({ runBackgroundWork: false }).pipe(
24
Layer.provideMerge(NodeServices.layer),
25
Layer.provideMerge(IdAllocator.layer),
26
Layer.provideMerge(McpProviderSessions.layer),
27
+ Layer.provideMerge(CursorSdk.layer),
28
Layer.provideMerge(
29
Layer.mock(CursorAgentSdk.CursorAgentSdkRunner)({
30
open: () => Effect.die("Maintenance resolution must not open a Cursor session"),
packages/provider-cursor/src/server/driver.ts
+4
-2
@@ -13,7 +13,7 @@ import * as Crypto from "effect/Crypto";
13
import * as FileSystem from "effect/FileSystem";
14
import * as Path from "effect/Path";
15
import * as Schema from "effect/Schema";
16
-import { HttpClient } from "effect/http";
16
+import * as HttpClient from "effect/http/HttpClient";
17
import { readCursorUsageLimits } from "./usageLimits.ts";
18
19
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
@@ -40,6 +40,7 @@ import { probeCursorSkills } from "./skills.ts";
40
import { makeCursorAuth } from "./auth.ts";
41
import * as CursorCredentialStore from "./credentialStore.ts";
42
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
43
+import * as CursorSdk from "./CursorSdk.ts";
44
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
45
const isSdkRunnerError = Schema.is(CursorAgentSdk.CursorAgentSdkRunnerError);
46
@@ -55,6 +56,7 @@ export type CursorDriverEnv =
56
| FileSystem.FileSystem
57
| Path.Path
58
| HttpClient.HttpClient
59
+ | CursorSdk.CursorSdk
60
| ProviderHost.ProviderHost;
61
62
export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
@@ -238,7 +240,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
240
new ProviderDriverError({
241
driver: DRIVER_KIND,
242
instanceId,
241
- detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,
243
+ detail: "Failed to build Cursor snapshot.",
244
cause,
245
}),
246
),
packages/provider-cursor/src/server/sdk.ts
+1
-64
@@ -1,69 +1,6 @@
1
-// @effect-diagnostics nodeBuiltinImport:off globalConsole:off -- Installed before the SDK loads, outside an Effect runtime. stderr must match Node's default unhandled-rejection print.
1
+// @effect-diagnostics nodeBuiltinImport:off -- The SDK must load from disk beside its Webpack chunks.
2
import * as NodeModule from "node:module";
3
4
-/**
5
- * The Cursor Agent SDK runs in this process and spawns a shell for tool
6
- * calls. The command is Cursor's sandbox wrapper (`dump_zsh_state`,
7
- * `dump_bash_state`, `__CURSOR_SANDBOX_ENV_RESTORE`). A bad working directory
8
- * makes Node report `spawn /bin/zsh ENOENT`. The SDK listens for that error,
9
- * then rejects an internal promise nothing awaits. Node exits on that
10
- * unhandled rejection and takes the server with it.
11
- *
12
- * This listener ignores only that rejection. Every other unhandled rejection
13
- * still prints and exits when this is the process's only listener, matching
14
- * Node's default. `child_process.spawn` itself is left alone, so git,
15
- * terminals, and other providers keep their own error handling.
16
- */
17
-const CURSOR_SHELL_SPAWN_MARKERS = [
18
- "dump_zsh_state",
19
- "dump_bash_state",
20
- "__CURSOR_SANDBOX_ENV_RESTORE",
21
-] as const;
22
-
23
-export function isCursorShellSpawnFailure(reason: unknown): boolean {
24
- if (typeof reason !== "object" || reason === null) {
25
- return false;
26
- }
27
- const syscall = Reflect.get(reason, "syscall");
28
- const code = Reflect.get(reason, "code");
29
- const spawnargs = Reflect.get(reason, "spawnargs");
30
- if (typeof syscall !== "string" || !syscall.startsWith("spawn") || typeof code !== "string") {
31
- return false;
32
- }
33
- if (!Array.isArray(spawnargs)) {
34
- return false;
35
- }
36
- return spawnargs.some(
37
- (arg) =>
38
- typeof arg === "string" && CURSOR_SHELL_SPAWN_MARKERS.some((marker) => arg.includes(marker)),
39
- );
40
-}
41
-
42
-let cursorShellSpawnGuardInstalled = false;
43
-
44
-function installCursorShellSpawnGuard(): void {
45
- if (cursorShellSpawnGuardInstalled) {
46
- return;
47
- }
48
- cursorShellSpawnGuardInstalled = true;
49
-
50
- process.on("unhandledRejection", (reason) => {
51
- if (isCursorShellSpawnFailure(reason)) {
52
- console.error("Cursor shell spawn failed. The server will keep running.", reason);
53
- return;
54
- }
55
- // Another handler registered besides this one owns the decision.
56
- if (process.listenerCount("unhandledRejection") > 1) {
57
- return;
58
- }
59
- console.error(reason);
60
- process.exit(1);
61
- });
62
-}
63
-
64
-// Arm before the SDK loads. Its shell tools spawn from this process.
65
-installCursorShellSpawnGuard();
66
-
4
// Cursor's Webpack chunks and local helpers must stay beside the SDK entry.
5
// createRequire also loads that disk-backed package from a Node SEA executable.
6
const requireCursorSdk = NodeModule.createRequire(import.meta.url);
packages/provider-cursor/src/server/textGeneration.test.ts
+18
-12
@@ -5,12 +5,14 @@ import { describe, expect, it } from "@effect/vitest";
5
import * as Effect from "effect/Effect";
6
import * as FileSystem from "effect/FileSystem";
7
import * as Fiber from "effect/Fiber";
8
+import * as Layer from "effect/Layer";
9
import * as TestClock from "effect/testing/TestClock";
10
import * as Schema from "effect/Schema";
11
import { createModelSelection } from "@t3tools/shared/model";
12
import { beforeEach, vi } from "vite-plus/test";
13
14
import { makeCursorTextGeneration } from "./textGeneration.ts";
15
+import * as CursorSdk from "./CursorSdk.ts";
16
17
const cursorSdkMock = vi.hoisted(() => ({
18
create: vi.fn<(options: unknown) => Promise<unknown>>(),
@@ -25,13 +27,17 @@ const cursorSdkMock = vi.hoisted(() => ({
27
})),
28
}));
29
28
-vi.mock("./sdk.ts", () => ({ Agent: { create: cursorSdkMock.create } }));
30
+vi.mock("./sdk.ts", () => ({
31
+ Agent: { create: cursorSdkMock.create },
32
+ createAgentPlatform: vi.fn(),
33
+}));
34
35
let hasCustomPolicy = false;
36
const layerFs = FileSystem.layerNoop({
37
exists: () => Effect.succeed(hasCustomPolicy),
38
makeTempDirectoryScoped: () => Effect.succeed("/isolated-text-generation"),
39
});
40
+const layerTest = Layer.merge(layerFs, CursorSdk.layer);
41
42
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
43
const cursorSettings = decodeCursorSettings({ enabled: true });
@@ -90,7 +96,7 @@ describe("CursorTextGeneration", () => {
96
expect(cursorSdkMock.create).toHaveBeenLastCalledWith(
97
expect.objectContaining({ apiKey: "second-browser-key" }),
98
);
93
- }).pipe(Effect.provide(layerFs)),
99
+ }).pipe(Effect.provide(layerTest)),
100
);
101
102
it.effect("uses the Cursor SDK prompt API with model parameters and API key", () =>
@@ -139,7 +145,7 @@ describe("CursorTextGeneration", () => {
145
enableAgentRetries: true,
146
},
147
});
142
- }).pipe(Effect.provide(layerFs)),
148
+ }).pipe(Effect.provide(layerTest)),
149
);
150
151
it.effect("continues in the temp directory when the SDK cannot sandbox", () =>
@@ -175,7 +181,7 @@ describe("CursorTextGeneration", () => {
181
enableAgentRetries: true,
182
},
183
});
178
- }).pipe(Effect.provide(layerFs)),
184
+ }).pipe(Effect.provide(layerTest)),
185
);
186
187
it.effect("does not retry Agent.create for errors other than an unsupported sandbox", () =>
@@ -199,7 +205,7 @@ describe("CursorTextGeneration", () => {
205
206
expect(error.detail).toBe("Cursor SDK text generation failed.");
207
expect(cursorSdkMock.create).toHaveBeenCalledTimes(1);
202
- }).pipe(Effect.provide(layerFs)),
208
+ }).pipe(Effect.provide(layerTest)),
209
);
210
211
it.effect("accepts json objects with extra assistant text around them", () =>
@@ -227,7 +233,7 @@ describe("CursorTextGeneration", () => {
233
234
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
235
expect(generated.body).toBe("");
230
- }).pipe(Effect.provide(layerFs)),
236
+ }).pipe(Effect.provide(layerTest)),
237
);
238
239
it.effect("generates thread titles through Cursor SDK text generation", () =>
@@ -251,7 +257,7 @@ describe("CursorTextGeneration", () => {
257
});
258
259
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
254
- }).pipe(Effect.provide(layerFs)),
260
+ }).pipe(Effect.provide(layerTest)),
261
);
262
263
it.effect.each(["error", "cancelled"] as const)(
@@ -285,7 +291,7 @@ describe("CursorTextGeneration", () => {
291
: "Cursor SDK request finished with an error.",
292
);
293
expect(cursorSdkMock.close).toHaveBeenCalledOnce();
288
- }).pipe(Effect.provide(layerFs)),
294
+ }).pipe(Effect.provide(layerTest)),
295
);
296
297
it.effect("fails closed when ambient sandbox policy can expand write access", () =>
@@ -301,7 +307,7 @@ describe("CursorTextGeneration", () => {
307
);
308
expect(failure.detail).toContain("custom ~/.cursor/sandbox.json");
309
expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
304
- }).pipe(Effect.provide(layerFs)),
310
+ }).pipe(Effect.provide(layerTest)),
311
);
312
313
it.effect("cancels the native run when text generation times out", () =>
@@ -327,7 +333,7 @@ describe("CursorTextGeneration", () => {
333
expect((yield* Fiber.join(result)).detail).toContain("timed out");
334
expect(cursorSdkMock.cancel).toHaveBeenCalledOnce();
335
expect(cursorSdkMock.close).toHaveBeenCalledOnce();
330
- }).pipe(Effect.provide(layerFs), Effect.scoped),
336
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
337
);
338
339
it.effect.each(["create", "send"] as const)(
@@ -389,7 +395,7 @@ describe("CursorTextGeneration", () => {
395
expect(cursorSdkMock.close).toHaveBeenCalledOnce();
396
expect(wait).not.toHaveBeenCalled();
397
if (phase === "send") expect(cursorSdkMock.cancel).toHaveBeenCalledOnce();
392
- }).pipe(Effect.provide(layerFs), Effect.scoped),
398
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
399
);
400
401
it.effect("requires CURSOR_API_KEY before calling the SDK", () =>
@@ -411,6 +417,6 @@ describe("CursorTextGeneration", () => {
417
418
expect(error.detail).toBe("Sign in with Cursor or add CURSOR_API_KEY in provider settings.");
419
expect(cursorSdkMock.prompt).not.toHaveBeenCalled();
414
- }).pipe(Effect.provide(layerFs)),
420
+ }).pipe(Effect.provide(layerTest)),
421
);
422
});
packages/provider-cursor/src/server/textGeneration.ts
+2
-1
@@ -2,7 +2,6 @@ import * as NodeOS from "node:os";
2
import * as FileSystem from "effect/FileSystem";
3
4
import type { AgentOptions, RunResult } from "@cursor/sdk";
5
-import { Agent } from "./sdk.ts";
5
import * as Effect from "effect/Effect";
6
import * as Option from "effect/Option";
7
import * as Schema from "effect/Schema";
@@ -13,6 +12,7 @@ import type { CursorSettings } from "../settings.ts";
12
import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
13
import { cursorSdkModelSelection } from "./sdkModel.ts";
14
import type { CursorAuth } from "./auth.ts";
15
+import * as CursorSdk from "./CursorSdk.ts";
16
17
const CURSOR_TIMEOUT_MS = 180_000;
18
@@ -58,6 +58,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
58
withAccess?: CursorAuth["withAccess"],
59
) {
60
const fs = yield* FileSystem.FileSystem;
61
+ const { Agent } = yield* CursorSdk.CursorSdk;
62
const resolvedEnvironment = environment ?? process.env;
63
64
const resolveCursorApiKey = (operation: TextGenerationOperations.Operation) =>
packages/provider-cursor/src/server/usageLimits.test.ts
+2
-1
@@ -4,7 +4,8 @@ import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
4
import * as Effect from "effect/Effect";
5
import * as FileSystem from "effect/FileSystem";
6
import * as Path from "effect/Path";
7
-import { HttpClient, HttpClientResponse } from "effect/http";
7
+import * as HttpClient from "effect/http/HttpClient";
8
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
9
import { cursorUsageResponseToLimits, readCursorUsageLimits } from "./usageLimits.ts";
10
11
const withNodeServices = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>) =>
packages/provider-cursor/src/server/usageLimits.ts
+3
-1
@@ -9,7 +9,9 @@ import * as FileSystem from "effect/FileSystem";
9
import * as Option from "effect/Option";
10
import * as Path from "effect/Path";
11
import * as Schema from "effect/Schema";
12
-import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
12
+import * as HttpClient from "effect/http/HttpClient";
13
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
14
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
15
import {
16
clampPercent,
17
makeUnavailableUsageLimits,