Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CursorSdk.ts

80 lines2.8 KB

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 { loadCursorSdk, loadCursorSqlite } from "./sdk.ts";
7​
8// The SDK leaves a shell-error promise unhandled, which would exit the server.
9const CURSOR_SHELL_SPAWN_MARKERS = [
10 "dump_zsh_state",
11 "dump_bash_state",
12 "__CURSOR_SANDBOX_ENV_RESTORE",
13] as const;
14​
15function isCursorShellSpawnFailure(reason: unknown): boolean {
16 if (typeof reason !== "object" || reason === null) {
17 return false;
18 }
19 const syscall = Reflect.get(reason, "syscall");
20 const code = Reflect.get(reason, "code");
21 const spawnargs = Reflect.get(reason, "spawnargs");
22 if (typeof syscall !== "string" || !syscall.startsWith("spawn") || typeof code !== "string") {
23 return false;
24 }
25 if (!Array.isArray(spawnargs)) {
26 return false;
27 }
28 return spawnargs.some(
29 (arg) =>
30 typeof arg === "string" && CURSOR_SHELL_SPAWN_MARKERS.some((marker) => arg.includes(marker)),
31 );
33​
34/**
35 * After a local exec fails, the SDK writes a final frame to the exec's stream from
36 * a promise nothing awaits. If that stream has already closed, the write rejects.
37 * The SDK's class is minified, so only its `name` identifies it.
38 */
39function isCursorClosedStreamWrite(reason: unknown): boolean {
40 return reason instanceof Error && reason.name === "WriteIterableClosedError";
42​
43function onUnhandledRejection(reason: unknown): void {
44 if (isCursorShellSpawnFailure(reason)) {
45 console.error("Cursor shell spawn failed. The server will keep running.", reason);
46 return;
47 }
48 if (isCursorClosedStreamWrite(reason)) {
49 console.error("Cursor SDK wrote to a closed exec stream. The server will keep running.");
50 return;
51 }
52 if (process.listenerCount("unhandledRejection") > 1) {
53 return;
54 }
55 console.error(reason);
56 process.exit(1);
58​
59/** Keeps the shell spawn guard armed while in-process agents run. */
60export class CursorSdk extends Context.Service<
61 CursorSdk,
62 {
63 readonly load: typeof loadCursorSdk;
64 readonly loadSqlite: typeof loadCursorSqlite;
65 }
66>()("@t3tools/provider-cursor/server/CursorSdk") {}
67​
68/** Provide once per process: a second guard would defer to the first and swallow real rejections. */
69export const layer = Layer.effect(
70 CursorSdk,
71 Effect.acquireRelease(
72 Effect.sync(() => {
73 process.on("unhandledRejection", onUnhandledRejection);
74 }),
75 () =>
76 Effect.sync(() => {
77 process.off("unhandledRejection", onUnhandledRejection);
78 }),
79 ).pipe(Effect.as(CursorSdk.of({ load: loadCursorSdk, loadSqlite: loadCursorSqlite }))),
80);