Open History to see the last commit
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.
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5
6import { Agent, createAgentPlatform, SqliteLocalAgentStore } from "./sdk.ts";
7
8/**
9 * The SDK listens for that error, then rejects an internal promise nothing awaits.
10 * Node exits on that unhandled rejection and takes the server with it.
11 */
12const CURSOR_SHELL_SPAWN_MARKERS = [
13 "dump_zsh_state",
14 "dump_bash_state",
15 "__CURSOR_SANDBOX_ENV_RESTORE",
16] as const;
17
18export function isCursorShellSpawnFailure(reason: unknown): boolean {
19 if (typeof reason !== "object" || reason === null) {
20 return false;
21 }
22 const syscall = Reflect.get(reason, "syscall");
23 const code = Reflect.get(reason, "code");
24 const spawnargs = Reflect.get(reason, "spawnargs");
25 if (typeof syscall !== "string" || !syscall.startsWith("spawn") || typeof code !== "string") {
26 return false;
27 }
28 if (!Array.isArray(spawnargs)) {
29 return false;
30 }
31 return spawnargs.some(
32 (arg) =>
33 typeof arg === "string" && CURSOR_SHELL_SPAWN_MARKERS.some((marker) => arg.includes(marker)),
34 );
35}
36
37function onUnhandledRejection(reason: unknown): void {
38 if (isCursorShellSpawnFailure(reason)) {
39 console.error("Cursor shell spawn failed. The server will keep running.", reason);
40 return;
41 }
42 if (process.listenerCount("unhandledRejection") > 1) {
43 return;
44 }
45 console.error(reason);
46 process.exit(1);
47}
48
49/**
50 * The SDK entry points that run agents in this process. Reaching them through
51 * this service keeps the shell spawn guard armed while they are in use.
52 */
53export class CursorSdk extends Context.Service<
54 CursorSdk,
55 {
56 readonly Agent: typeof Agent;
57 readonly createAgentPlatform: typeof createAgentPlatform;
58 readonly SqliteLocalAgentStore: typeof SqliteLocalAgentStore;
59 }
60>()("@t3tools/provider-cursor/server/CursorSdk") {}
61
62/** Provide once per process: a second guard would defer to the first and swallow real rejections. */
63export const layer = Layer.effect(
64 CursorSdk,
65 Effect.acquireRelease(
66 Effect.sync(() => {
67 process.on("unhandledRejection", onUnhandledRejection);
68 }),
69 () =>
70 Effect.sync(() => {
71 process.off("unhandledRejection", onUnhandledRejection);
72 }),
73 ).pipe(Effect.as(CursorSdk.of({ Agent, createAgentPlatform, SqliteLocalAgentStore }))),
74);