@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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