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

textGeneration.ts

211 lines7.6 KB

1import * as FileSystem from "effect/FileSystem";
2​
3import type { AgentOptions, RunResult } from "@cursor/sdk";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7​
8import { type ProviderSetupError, TextGenerationError } from "@t3tools/contracts";
9import type { CursorSettings } from "../settings.ts";
10​
11import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
12import { cursorSdkModelSelection } from "./sdkModel.ts";
13import type { CursorAuth } from "./auth.ts";
14import * as CursorSdk from "./CursorSdk.ts";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16​
17const CURSOR_TIMEOUT_MS = 180_000;
18​
19const isTextGenerationError = Schema.is(TextGenerationError);
20​
21function cursorSdkResultDetail(result: RunResult): string {
22 switch (result.status) {
23 case "cancelled":
24 return "Cursor SDK request was cancelled.";
25 case "error":
26 return "Cursor SDK request finished with an error.";
27 case "finished":
28 return "Cursor SDK returned empty output.";
29 }
31​
32/**
33 * The SDK throws this when `sandboxOptions.enabled` is set and local sandboxing
34 * is unavailable. That happens on hosts that cannot launch `cursorsandbox`, and
35 * also after an unsandboxed run caches "unsupported" for the process.
36 */
37function cursorSandboxUnsupported(cause: unknown): boolean {
38 const seen = new Set<object>();
39 let current = cause;
40 while (typeof current === "object" && current !== null && !seen.has(current)) {
41 seen.add(current);
42 if (current instanceof Error && current.message.includes("sandboxing is not supported")) {
43 return true;
44 }
45 current = Reflect.get(current, "cause");
46 }
47 return false;
49​
50export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* (
51 cursorSettings: CursorSettings,
52 environment?: NodeJS.ProcessEnv,
53 resolveApiKey?: Effect.Effect<string, ProviderSetupError>,
54 withAccess?: CursorAuth["withAccess"],
55) {
56 const fs = yield* FileSystem.FileSystem;
57 const { Agent, SqliteLocalAgentStore } = yield* CursorSdk.CursorSdk;
58 const resolvedEnvironment = environment ?? process.env;
59​
60 const resolveCursorApiKey = (operation: TextGenerationOperations.Operation) =>
61 Effect.gen(function* () {
62 if (!cursorSettings.enabled) {
63 return yield* new TextGenerationError({
64 operation,
65 detail: "Cursor is disabled in T3 Code settings.",
66 });
67 }
68​
69 const apiKey = resolveApiKey
70 ? yield* resolveApiKey
71 : resolvedEnvironment.CURSOR_API_KEY?.trim();
72 if (!apiKey) {
73 return yield* new TextGenerationError({
74 operation,
75 detail: "Sign in with Cursor or add CURSOR_API_KEY in provider settings.",
76 });
77 }
78​
79 return apiKey;
80 });
81​
82 const runCursorJson: TextGenerationOperations.Runner = (input) => {
83 const { operation, prompt, modelSelection } = input;
84 return Effect.gen(function* () {
85 const apiKey = yield* resolveCursorApiKey(operation);
86 // The SDK loads sandbox.json independently of settingSources and lets it
87 // expand the writable paths. Its public API cannot override that policy.
88 if (yield* fs.exists(`${yield* HostProcess.HomeDirectory}/.cursor/sandbox.json`)) {
89 return yield* new TextGenerationError({
90 operation,
91 detail:
92 "Cursor text generation cannot enforce workspace isolation with a custom ~/.cursor/sandbox.json. Use another text-generation provider.",
93 });
94 }
95 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-" });
96 // The SDK keeps SQLite handles open after `agent.close()` and only releases
97 // them from a store the caller disposes. Its state lives outside `cwd` so the
98 // agent's workspace stays empty.
99 const stateRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-state-" });
100 const store = yield* Effect.acquireRelease(
101 Effect.tryPromise(() => SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot })),
102 (store) => Effect.tryPromise(() => store.dispose()).pipe(Effect.ignore({ log: true })),
103 );
104 const agentOptions = {
105 apiKey,
106 mode: "plan",
107 model: cursorSdkModelSelection(modelSelection),
108 local: {
109 cwd,
110 store,
111 autoReview: false,
112 sandboxOptions: { enabled: true },
113 settingSources: [],
114 enableAgentRetries: true,
115 },
116 } satisfies AgentOptions;
117 const createCursorAgent = (sandboxEnabled: boolean) =>
118 Effect.tryPromise((signal) =>
119 Agent.create(
120 sandboxEnabled
121 ? agentOptions
122 : {
123 ...agentOptions,
124 local: {
125 ...agentOptions.local,
126 sandboxOptions: { enabled: false },
127 },
128 },
129 ).then((agent) => {
130 if (signal.aborted) agent.close();
131 return agent;
132 }),
133 );
134​
135 const request = Effect.gen(function* () {
136 // When the SDK refuses it, the empty temp directory and empty setting
137 // sources still keep this run off the user's project.
138 const agent = yield* Effect.acquireRelease(
139 createCursorAgent(true).pipe(
140 Effect.catchIf(cursorSandboxUnsupported, () => createCursorAgent(false)),
141 ),
142 (agent) =>
143 Effect.tryPromise(() => agent[Symbol.asyncDispose]()).pipe(
144 Effect.timeout("5 seconds"),
145 Effect.ignore({ log: true }),
146 ),
147 { interruptible: true },
148 );
149 const run = yield* Effect.tryPromise((signal) =>
150 agent.send(prompt).then((run) => {
151 if (signal.aborted) void run.cancel().catch(() => undefined);
152 return run;
153 }),
154 );
155 yield* Effect.addFinalizer(() =>
156 run.status === "running"
157 ? Effect.tryPromise(() => run.cancel()).pipe(
158 Effect.timeout("5 seconds"),
159 Effect.ignore({ log: true }),
160 )
161 : Effect.void,
162 );
163 return yield* Effect.tryPromise(() => run.wait());
164 }).pipe(Effect.scoped);
165 const promptResult = yield* request.pipe(
166 Effect.timeoutOption(CURSOR_TIMEOUT_MS),
167 Effect.flatMap(
168 Option.match({
169 onNone: () =>
170 Effect.fail(
171 new TextGenerationError({
172 operation,
173 detail: "Cursor SDK request timed out.",
174 }),
175 ),
176 onSome: (value) => Effect.succeed(value),
177 }),
178 ),
179 );
180​
181 const rawResult = promptResult.result?.trim() ?? "";
182 if (promptResult.status !== "finished" || !rawResult) {
183 return yield* new TextGenerationError({
184 operation,
185 detail: cursorSdkResultDetail(promptResult),
186 });
187 }
188​
189 return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
190 }).pipe(
191 // Scope this call inside `withAccess`, so sign-out closes the agent before its store.
192 Effect.scoped,
193 (effect) => (withAccess ? withAccess(effect) : effect),
194 Effect.scoped,
195 Effect.mapError((cause) =>
196 isTextGenerationError(cause)
197 ? cause
198 : new TextGenerationError({
199 operation,
200 detail: "Cursor SDK text generation failed.",
201 cause,
202 }),
203 ),
204 );
205 };
206​
207 return TextGenerationOperations.fromRunner(
208 "CursorTextGeneration",
209 TextGenerationOperations.withoutInvestigation("Cursor", runCursorJson),
210 );
211});