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

textGeneration.ts

201 lines7.0 KB

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