The best way to control Claude Code, Codex and more from any computer or phone
| 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 HostProcess from "@t3tools/shared/HostProcess"; |
| 3 | import * as Context from "effect/Context"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import * as Path from "effect/Path"; |
| 8 | import * as Schema from "effect/Schema"; |
| 9 | |
| 10 | import { loadCursorSdk, loadCursorSqlite } from "./sdk.ts"; |
| 11 | |
| 12 | // The SDK leaves a shell-error promise unhandled, which would exit the server. |
| 13 | const CURSOR_SHELL_SPAWN_MARKERS = [ |
| 14 | "dump_zsh_state", |
| 15 | "dump_bash_state", |
| 16 | "__CURSOR_SANDBOX_ENV_RESTORE", |
| 17 | ] as const; |
| 18 | |
| 19 | function isCursorShellSpawnFailure(reason: unknown): boolean { |
| 20 | if (typeof reason !== "object" || reason === null) { |
| 21 | return false; |
| 22 | } |
| 23 | const syscall = Reflect.get(reason, "syscall"); |
| 24 | const code = Reflect.get(reason, "code"); |
| 25 | const spawnargs = Reflect.get(reason, "spawnargs"); |
| 26 | if (typeof syscall !== "string" || !syscall.startsWith("spawn") || typeof code !== "string") { |
| 27 | return false; |
| 28 | } |
| 29 | if (!Array.isArray(spawnargs)) { |
| 30 | return false; |
| 31 | } |
| 32 | return spawnargs.some( |
| 33 | (arg) => |
| 34 | typeof arg === "string" && CURSOR_SHELL_SPAWN_MARKERS.some((marker) => arg.includes(marker)), |
| 35 | ); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * The SDK writes final frames from promises nothing awaits. A closed stream rejects them |
| 40 | * with WriteIterableClosedError; an ended request body rejects them with the Aborted |
| 41 | * ConnectError its connect-node pump wraps around ERR_STREAM_WRITE_AFTER_END. The classes |
| 42 | * are minified, so only `name` identifies them. |
| 43 | */ |
| 44 | function isCursorClosedStreamWrite(reason: unknown): boolean { |
| 45 | if (!(reason instanceof Error)) { |
| 46 | return false; |
| 47 | } |
| 48 | if (reason.name === "WriteIterableClosedError") { |
| 49 | return true; |
| 50 | } |
| 51 | return ( |
| 52 | reason.name === "ConnectError" && |
| 53 | reason.cause instanceof Error && |
| 54 | Reflect.get(reason.cause, "code") === "ERR_STREAM_WRITE_AFTER_END" |
| 55 | ); |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * When the SDK's stall detector fires it aborts the request, then rejects a promise |
| 60 | * nothing awaits. The abort is the SDK's own recovery, so it must not stop the server. |
| 61 | * Only an abort raised from `onStall` counts; any other AbortError is still unexpected. |
| 62 | */ |
| 63 | function isCursorStallAbort(reason: unknown): boolean { |
| 64 | return ( |
| 65 | reason instanceof Error && |
| 66 | reason.name === "AbortError" && |
| 67 | typeof reason.stack === "string" && |
| 68 | /^\s+at (?:\S+\.)?onStall\b/m.test(reason.stack) |
| 69 | ); |
| 70 | } |
| 71 | |
| 72 | function onUnhandledRejection(reason: unknown): void { |
| 73 | if (isCursorShellSpawnFailure(reason)) { |
| 74 | console.error("Cursor shell spawn failed. The server will keep running.", reason); |
| 75 | return; |
| 76 | } |
| 77 | if (isCursorClosedStreamWrite(reason)) { |
| 78 | console.error("Cursor SDK wrote to a closed stream. The server will keep running."); |
| 79 | return; |
| 80 | } |
| 81 | if (isCursorStallAbort(reason)) { |
| 82 | console.error("Cursor SDK aborted a stalled request. The server will keep running."); |
| 83 | return; |
| 84 | } |
| 85 | if (process.listenerCount("unhandledRejection") > 1) { |
| 86 | return; |
| 87 | } |
| 88 | console.error(reason); |
| 89 | process.exit(1); |
| 90 | } |
| 91 | |
| 92 | const decodeCursorCliConfig = Schema.decodeEffect( |
| 93 | Schema.fromJsonString( |
| 94 | Schema.Struct({ |
| 95 | network: Schema.optionalKey( |
| 96 | Schema.Struct({ useHttp1ForAgent: Schema.optionalKey(Schema.Boolean) }), |
| 97 | ), |
| 98 | }), |
| 99 | ), |
| 100 | ); |
| 101 | |
| 102 | // Proxies without HTTP/2 need this Cursor CLI setting, which the SDK never reads itself. |
| 103 | const readCursorCliUseHttp1ForAgent = Effect.gen(function* () { |
| 104 | const fileSystem = yield* FileSystem.FileSystem; |
| 105 | const path = yield* Path.Path; |
| 106 | const { CURSOR_CONFIG_DIR, XDG_CONFIG_HOME } = yield* HostProcess.Environment; |
| 107 | const configDirectory = CURSOR_CONFIG_DIR?.trim() |
| 108 | ? CURSOR_CONFIG_DIR |
| 109 | : XDG_CONFIG_HOME?.trim() |
| 110 | ? path.join(XDG_CONFIG_HOME, "cursor") |
| 111 | : path.join(yield* HostProcess.HomeDirectory, ".cursor"); |
| 112 | const configPath = path.join(configDirectory, "cli-config.json"); |
| 113 | const config = yield* fileSystem.readFileString(configPath).pipe( |
| 114 | Effect.flatMap(decodeCursorCliConfig), |
| 115 | Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined), |
| 116 | Effect.catch(() => |
| 117 | Effect.logWarning("Cursor CLI config could not be read; using the default agent transport", { |
| 118 | path: configPath, |
| 119 | }).pipe(Effect.as(undefined)), |
| 120 | ), |
| 121 | ); |
| 122 | return config?.network?.useHttp1ForAgent === true; |
| 123 | }).pipe(Effect.withSpan("CursorSdk.readCliUseHttp1ForAgent")); |
| 124 | |
| 125 | /** Keeps the shell spawn guard armed while in-process agents run. */ |
| 126 | export class CursorSdk extends Context.Service< |
| 127 | CursorSdk, |
| 128 | { |
| 129 | readonly load: typeof loadCursorSdk; |
| 130 | readonly loadSqlite: typeof loadCursorSqlite; |
| 131 | } |
| 132 | >()("@t3tools/provider-cursor/server/CursorSdk") {} |
| 133 | |
| 134 | /** Provide once per process: a second guard would defer to the first and swallow real rejections. */ |
| 135 | export const layer = Layer.effect( |
| 136 | CursorSdk, |
| 137 | Effect.gen(function* () { |
| 138 | yield* Effect.acquireRelease( |
| 139 | Effect.sync(() => { |
| 140 | process.on("unhandledRejection", onUnhandledRejection); |
| 141 | }), |
| 142 | () => |
| 143 | Effect.sync(() => { |
| 144 | process.off("unhandledRejection", onUnhandledRejection); |
| 145 | }), |
| 146 | ); |
| 147 | // The SDK picks the agent transport per process, so no provider instance can own this. |
| 148 | const useHttp1ForAgent = yield* readCursorCliUseHttp1ForAgent; |
| 149 | let configured = false; |
| 150 | yield* Effect.addFinalizer(() => |
| 151 | Effect.sync(() => { |
| 152 | if (configured) loadCursorSdk().Cursor.configure({ local: { useHttp1ForAgent: null } }); |
| 153 | }), |
| 154 | ); |
| 155 | return CursorSdk.of({ |
| 156 | load: () => { |
| 157 | const sdk = loadCursorSdk(); |
| 158 | if (useHttp1ForAgent && !configured) { |
| 159 | sdk.Cursor.configure({ local: { useHttp1ForAgent: true } }); |
| 160 | configured = true; |
| 161 | } |
| 162 | return sdk; |
| 163 | }, |
| 164 | loadSqlite: loadCursorSqlite, |
| 165 | }); |
| 166 | }), |
| 167 | ); |