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

textGeneration.ts

356 lines12.9 KB

1import * as FileSystem from "effect/FileSystem";
2​
3import type { AgentOptions, RunResult, SDKModel } from "@cursor/sdk";
4import * as Effect from "effect/Effect";
5import * as Schema from "effect/Schema";
6​
7import {
8 type ProviderSetupError,
9 type ServerProviderModel,
10 TextGenerationError,
11} from "@t3tools/contracts";
12import type { CursorSettings } from "../settings.ts";
13​
14import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
15import { cursorSdkModelSelection } from "./sdkModel.ts";
16import type { CursorAuth } from "./auth.ts";
17import * as CursorAgentSdk from "./CursorAgentSdk.ts";
18import * as CursorSdk from "./CursorSdk.ts";
19import * as HostProcess from "@t3tools/shared/HostProcess";
20​
21const CURSOR_TIMEOUT_MS = 180_000;
22​
23const isTextGenerationError = Schema.is(TextGenerationError);
24​
25const TEXT_GENERATION_STAGE_DETAIL: Readonly<Record<string, string>> = {
26 "textGenerate.load": "Cursor SDK could not be loaded.",
27 "textGenerate.store": "Cursor SDK agent store could not be opened.",
28 "textGenerate.create": "Cursor SDK agent could not be created.",
29 "textGenerate.dispose": "Cursor SDK agent could not be disposed.",
30 "textGenerate.send": "Cursor SDK request could not be sent.",
31 "textGenerate.cancel": "Cursor SDK run could not be cancelled.",
32 "textGenerate.wait": "Cursor SDK run failed.",
33};
34​
35function workerTextGenerationDetail(error: CursorAgentSdk.CursorAgentSdkRunnerError): string {
36 return TEXT_GENERATION_STAGE_DETAIL[error.method] ?? "Cursor SDK text generation failed.";
38​
39function cursorSdkResultDetail(result: RunResult): string {
40 switch (result.status) {
41 case "cancelled":
42 return "Cursor SDK request was cancelled.";
43 case "error":
44 return CursorAgentSdk.isCursorUsageLimitError(result.error)
45 ? "Grok Build usage limit reached. Try again later or choose another text-generation provider."
46 : "Cursor SDK request finished with an error.";
47 case "finished":
48 return "Cursor SDK returned empty output.";
49 }
51​
52// Sandboxing fails without cursorsandbox or after a process-wide unsupported result.
53function cursorSandboxUnsupported(cause: unknown): boolean {
54 const seen = new Set<object>();
55 let current = cause;
56 while (typeof current === "object" && current !== null && !seen.has(current)) {
57 seen.add(current);
58 if (current instanceof Error && current.message.includes("sandboxing is not supported")) {
59 return true;
60 }
61 current = Reflect.get(current, "cause");
62 }
63 return false;
65​
66const runCursorTextGenerationWithStore = <E>(input: {
67 readonly Agent: ReturnType<CursorSdk.CursorSdk["Service"]["load"]>["Agent"];
68 readonly store: NonNullable<NonNullable<AgentOptions["local"]>["store"]>;
69 readonly prompt: string;
70 readonly apiKey: string;
71 readonly model: NonNullable<AgentOptions["model"]>;
72 readonly cwd: string;
73 readonly mapError: (step: "create" | "dispose" | "send" | "cancel" | "wait", cause: unknown) => E;
74 readonly logDisposeErrors?: boolean;
75}): Effect.Effect<RunResult, E> => {
76 const agentOptions = {
77 apiKey: input.apiKey,
78 mode: "agent",
79 tools: [],
80 model: input.model,
81 local: {
82 cwd: input.cwd,
83 store: input.store,
84 autoReview: false,
85 sandboxOptions: { enabled: true },
86 settingSources: [],
87 enableAgentRetries: true,
88 },
89 } satisfies AgentOptions;
90​
91 const createCursorAgent = (sandboxEnabled: boolean) =>
92 Effect.tryPromise({
93 try: (signal) =>
94 input.Agent.create(
95 sandboxEnabled
96 ? agentOptions
97 : {
98 ...agentOptions,
99 local: {
100 ...agentOptions.local,
101 sandboxOptions: { enabled: false },
102 },
103 },
104 ).then((agent) => {
105 if (signal.aborted) agent.close();
106 return agent;
107 }),
108 catch: (cause) => input.mapError("create", cause),
109 });
110​
111 const runPrompt = Effect.fn("CursorTextGeneration.runPrompt")(function* (
112 sandboxEnabled: boolean,
113 ) {
114 const agent = yield* Effect.acquireRelease(
115 createCursorAgent(sandboxEnabled),
116 (agent) =>
117 Effect.tryPromise({
118 try: () => agent[Symbol.asyncDispose](),
119 catch: (cause) => input.mapError("dispose", cause),
120 }).pipe(
121 Effect.timeout("5 seconds"),
122 Effect.ignore(input.logDisposeErrors ? { log: true } : undefined),
123 ),
124 { interruptible: true },
125 );
126 const run = yield* Effect.tryPromise({
127 try: (signal) =>
128 agent.send(input.prompt).then((started) => {
129 if (signal.aborted) void started.cancel().catch(() => undefined);
130 return started;
131 }),
132 catch: (cause) => input.mapError("send", cause),
133 });
134 yield* Effect.addFinalizer(() =>
135 run.status === "running"
136 ? Effect.tryPromise({
137 try: () => run.cancel(),
138 catch: (cause) => input.mapError("cancel", cause),
139 }).pipe(
140 Effect.timeout("5 seconds"),
141 Effect.ignore(input.logDisposeErrors ? { log: true } : undefined),
142 )
143 : Effect.void,
144 );
145 return yield* Effect.tryPromise({
146 try: () => run.wait(),
147 catch: (cause) => input.mapError("wait", cause),
148 });
149 }, Effect.scoped);
150​
151 // The SDK may reject sandboxing in create or lazily in send. Empty cwd and setting
152 // sources isolate the unsandboxed retry from user projects.
153 return runPrompt(true).pipe(Effect.catchIf(cursorSandboxUnsupported, () => runPrompt(false)));
154};
155​
156export const runCursorTextGenerationInProcess = Effect.fn("CursorTextGeneration.runInProcess")(
157 function* (input: CursorAgentSdk.CursorAgentSdkTextGenerateInput) {
158 const sdk = yield* CursorSdk.CursorSdk;
159 const { Agent } = yield* Effect.try({
160 try: sdk.load,
161 catch: (cause) =>
162 new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "textGenerate.load", cause }),
163 });
164 const store = yield* Effect.acquireRelease(
165 Effect.tryPromise({
166 try: () =>
167 sdk.loadSqlite().SqliteLocalAgentStore.open({
168 workspaceRef: input.cwd,
169 stateRoot: input.stateRoot,
170 }),
171 catch: (cause) =>
172 new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "textGenerate.store", cause }),
173 }),
174 (opened) =>
175 Effect.tryPromise({
176 try: () => opened.dispose(),
177 catch: () => undefined,
178 }).pipe(Effect.ignore),
179 );
180 return yield* runCursorTextGenerationWithStore({
181 Agent,
182 store: Object.assign(store, { persistRunEvents: false }),
183 prompt: input.prompt,
184 apiKey: input.apiKey,
185 model: input.model,
186 cwd: input.cwd,
187 mapError: (step, cause) =>
188 new CursorAgentSdk.CursorAgentSdkRunnerError({ method: `textGenerate.${step}`, cause }),
189 });
190 },
191 Effect.scoped,
192);
193​
194export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* (
195 cursorSettings: CursorSettings,
196 environment?: NodeJS.ProcessEnv,
197 resolveApiKey?: Effect.Effect<string, ProviderSetupError>,
198 withAccess?: CursorAuth["withAccess"],
199 getModels?: () => ReadonlyArray<ServerProviderModel>,
200 getSdkModels?: () => ReadonlyArray<SDKModel>,
201 sdkRunner?: CursorAgentSdk.CursorAgentSdkRunner["Service"],
202) {
203 const fs = yield* FileSystem.FileSystem;
204 const sdk = yield* CursorSdk.CursorSdk;
205 const resolvedEnvironment = environment ?? process.env;
206​
207 const resolveCursorApiKey = Effect.fn("CursorTextGeneration.resolveCursorApiKey")(function* (
208 operation: TextGenerationOperations.Operation,
209 ) {
210 if (!cursorSettings.enabled) {
211 return yield* new TextGenerationError({
212 operation,
213 detail: "Grok Build is disabled in T3 Code settings.",
214 });
215 }
216​
217 const apiKey = resolveApiKey
218 ? yield* resolveApiKey
219 : resolvedEnvironment.CURSOR_API_KEY?.trim();
220 if (!apiKey) {
221 return yield* new TextGenerationError({
222 operation,
223 detail: "Sign in with Grok Build or add CURSOR_API_KEY in provider settings.",
224 });
225 }
226​
227 return apiKey;
228 });
229​
230 const runCursorJson: TextGenerationOperations.Runner = Effect.fn(
231 "CursorTextGeneration.runCursorJson",
232 )(
233 function* (input) {
234 const { operation, prompt, modelSelection } = input;
235​
236 const apiKey = yield* resolveCursorApiKey(operation);
237 const sdkFailure = (detail: string) => (cause: unknown) =>
238 new TextGenerationError({ operation, detail, cause });
239 // sandbox.json expands writable paths independently of settingSources; the public API cannot override it.
240 if (yield* fs.exists(`${yield* HostProcess.HomeDirectory}/.cursor/sandbox.json`)) {
241 return yield* new TextGenerationError({
242 operation,
243 detail:
244 "Grok Build text generation cannot enforce workspace isolation with a custom ~/.cursor/sandbox.json. Use another text-generation provider.",
245 });
246 }
247 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-" });
248 // Only store disposal releases SDK SQLite handles; keep state outside the empty workspace.
249 const stateRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-state-" });
250 const resolvedModel = cursorSdkModelSelection(
251 modelSelection,
252 getModels?.() ?? [],
253 getSdkModels?.() ?? [],
254 );
255 const runInWorker = sdkRunner?.textGenerate;
256 const executePrompt: Effect.Effect<RunResult, TextGenerationError> =
257 runInWorker !== undefined
258 ? runInWorker({
259 prompt,
260 apiKey,
261 model: resolvedModel,
262 cwd,
263 stateRoot,
264 }).pipe(
265 Effect.mapError((error) => sdkFailure(workerTextGenerationDetail(error))(error)),
266 )
267 : yield* Effect.gen(function* () {
268 const { Agent } = yield* Effect.try({
269 try: sdk.load,
270 catch: sdkFailure("Cursor SDK could not be loaded."),
271 });
272 const store = yield* Effect.acquireRelease(
273 Effect.tryPromise({
274 try: () =>
275 sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot }),
276 catch: sdkFailure("Cursor SDK agent store could not be opened."),
277 }),
278 (store) =>
279 Effect.tryPromise({
280 try: () => store.dispose(),
281 catch: sdkFailure("Cursor SDK agent store could not be disposed."),
282 }).pipe(Effect.ignore({ log: true })),
283 );
284 const textGenerationErrorDetail = {
285 create: "Cursor SDK agent could not be created.",
286 dispose: "Cursor SDK agent could not be disposed.",
287 send: "Cursor SDK request could not be sent.",
288 cancel: "Cursor SDK run could not be cancelled.",
289 wait: "Cursor SDK run failed.",
290 } as const;
291 return runCursorTextGenerationWithStore({
292 Agent,
293 store: Object.assign(store, { persistRunEvents: false }),
294 prompt,
295 apiKey,
296 model: resolvedModel,
297 cwd,
298 mapError: (step, cause) => sdkFailure(textGenerationErrorDetail[step])(cause),
299 logDisposeErrors: true,
300 });
301 });
302 const request = Effect.gen(function* () {
303 const promptResult = yield* executePrompt;
304 const rawResult = promptResult.result?.trim() ?? "";
305 if (promptResult.status !== "finished" || !rawResult) {
306 return yield* new TextGenerationError({
307 operation,
308 detail: cursorSdkResultDetail(promptResult),
309 ...(promptResult.error ? { cause: promptResult.error } : {}),
310 });
311 }
312​
313 return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
314 }).pipe(
315 Effect.retry({
316 times: 1,
317 while: (cause) => isTextGenerationError(cause) && Schema.isSchemaError(cause.cause),
318 }),
319 );
320 return yield* request.pipe(
321 Effect.timeoutOrElse({
322 duration: CURSOR_TIMEOUT_MS,
323 orElse: () =>
324 Effect.fail(
325 new TextGenerationError({
326 operation,
327 detail: "Cursor SDK request timed out.",
328 }),
329 ),
330 }),
331 );
332 },
333 (effect, input) => {
334 const { operation } = input;
335 return effect.pipe(
336 Effect.scoped,
337 (effect) => (withAccess ? withAccess(effect) : effect),
338 Effect.scoped,
339 Effect.mapError((cause) =>
340 isTextGenerationError(cause)
341 ? cause
342 : new TextGenerationError({
343 operation,
344 detail: "Cursor SDK text generation failed.",
345 cause,
346 }),
347 ),
348 );
349 },
350 );
351​
352 return TextGenerationOperations.fromRunner(
353 "CursorTextGeneration",
354 TextGenerationOperations.withoutInvestigation("Cursor", runCursorJson),
355 );
356});