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

textGeneration.ts

202 lines7.1 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​
50/**
51 * Build a Cursor text-generation closure bound to a specific `CursorSettings`
52 * payload. See `makeCodexAdapter` for the overall per-instance rationale.
53 */
54export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* (
55 cursorSettings: CursorSettings,
56 environment?: NodeJS.ProcessEnv,
57 resolveApiKey?: Effect.Effect<string, ProviderSetupError>,
58 withAccess?: CursorAuth["withAccess"],
59) {
60 const fs = yield* FileSystem.FileSystem;
61 const { Agent } = yield* CursorSdk.CursorSdk;
62 const resolvedEnvironment = environment ?? process.env;
63​
64 const resolveCursorApiKey = (operation: TextGenerationOperations.Operation) =>
65 Effect.gen(function* () {
66 if (!cursorSettings.enabled) {
67 return yield* new TextGenerationError({
68 operation,
69 detail: "Cursor is disabled in T3 Code settings.",
70 });
71 }
72​
73 const apiKey = resolveApiKey
74 ? yield* resolveApiKey
75 : resolvedEnvironment.CURSOR_API_KEY?.trim();
76 if (!apiKey) {
77 return yield* new TextGenerationError({
78 operation,
79 detail: "Sign in with Cursor or add CURSOR_API_KEY in provider settings.",
80 });
81 }
82​
83 return apiKey;
84 });
85​
86 // Ignores `cwd`: the agent runs in an empty temp directory, away from the project.
87 const runCursorJson: TextGenerationOperations.Runner = (input) => {
88 const { operation, prompt, modelSelection } = input;
89 return Effect.gen(function* () {
90 const apiKey = yield* resolveCursorApiKey(operation);
91 // The SDK loads sandbox.json independently of settingSources and lets it
92 // expand the writable paths. Its public API cannot override that policy.
93 if (yield* fs.exists(`${yield* HostProcess.HomeDirectory}/.cursor/sandbox.json`)) {
94 return yield* new TextGenerationError({
95 operation,
96 detail:
97 "Cursor text generation cannot enforce workspace isolation with a custom ~/.cursor/sandbox.json. Use another text-generation provider.",
98 });
99 }
100 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-" });
101 const agentOptions = {
102 apiKey,
103 mode: "plan",
104 model: cursorSdkModelSelection(modelSelection),
105 local: {
106 cwd,
107 autoReview: false,
108 sandboxOptions: { enabled: true },
109 settingSources: [],
110 enableAgentRetries: true,
111 },
112 } satisfies AgentOptions;
113 const createCursorAgent = (sandboxEnabled: boolean) =>
114 Effect.tryPromise((signal) =>
115 Agent.create(
116 sandboxEnabled
117 ? agentOptions
118 : {
119 ...agentOptions,
120 local: {
121 ...agentOptions.local,
122 sandboxOptions: { enabled: false },
123 },
124 },
125 ).then((agent) => {
126 if (signal.aborted) agent.close();
127 return agent;
128 }),
129 );
130​
131 const request = Effect.gen(function* () {
132 // Prefer the sandbox. When the SDK refuses it, the empty temp directory
133 // and empty setting sources still keep this run off the user's project.
134 const agent = yield* Effect.acquireRelease(
135 createCursorAgent(true).pipe(
136 Effect.catchIf(cursorSandboxUnsupported, () => createCursorAgent(false)),
137 ),
138 (agent) =>
139 Effect.tryPromise(() => agent[Symbol.asyncDispose]()).pipe(
140 Effect.timeout("5 seconds"),
141 Effect.ignore({ log: true }),
142 ),
143 { interruptible: true },
144 );
145 const run = yield* Effect.tryPromise((signal) =>
146 agent.send(prompt).then((run) => {
147 if (signal.aborted) void run.cancel().catch(() => undefined);
148 return run;
149 }),
150 );
151 yield* Effect.addFinalizer(() =>
152 run.status === "running"
153 ? Effect.tryPromise(() => run.cancel()).pipe(
154 Effect.timeout("5 seconds"),
155 Effect.ignore({ log: true }),
156 )
157 : Effect.void,
158 );
159 return yield* Effect.tryPromise(() => run.wait());
160 }).pipe(Effect.scoped);
161 const promptResult = yield* request.pipe(
162 Effect.timeoutOption(CURSOR_TIMEOUT_MS),
163 Effect.flatMap(
164 Option.match({
165 onNone: () =>
166 Effect.fail(
167 new TextGenerationError({
168 operation,
169 detail: "Cursor SDK request timed out.",
170 }),
171 ),
172 onSome: (value) => Effect.succeed(value),
173 }),
174 ),
175 );
176​
177 const rawResult = promptResult.result?.trim() ?? "";
178 if (promptResult.status !== "finished" || !rawResult) {
179 return yield* new TextGenerationError({
180 operation,
181 detail: cursorSdkResultDetail(promptResult),
182 });
183 }
184​
185 return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
186 }).pipe(
187 (effect) => (withAccess ? withAccess(effect) : effect),
188 Effect.scoped,
189 Effect.mapError((cause) =>
190 isTextGenerationError(cause)
191 ? cause
192 : new TextGenerationError({
193 operation,
194 detail: "Cursor SDK text generation failed.",
195 cause,
196 }),
197 ),
198 );
199 };
200​
201 return TextGenerationOperations.fromRunner("CursorTextGeneration", runCursorJson);
202});