Open History to see the last commit
1import type {
2 AgentMessage,
3 AgentOptions,
4 InteractionUpdate,
5 RunResult,
6 SDKUserMessage,
7 SendOptions,
8} from "@cursor/sdk";
9import {
10 type OrchestrationV2ProviderSession,
11 ProviderDriverKind,
12 type ThreadId,
13} from "@t3tools/contracts";
14import * as Context from "effect/Context";
15import * as Deferred from "effect/Deferred";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Ref from "effect/Ref";
19import * as Schema from "effect/Schema";
20
21import * as CursorSdk from "./CursorSdk.ts";
22import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
23
24export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const;
25export const CURSOR_PROVIDER = ProviderDriverKind.make("cursor");
26
27export class CursorAgentSdkRunnerError extends Schema.TaggedError<CursorAgentSdkRunnerError>()(
28 "CursorAgentSdkRunnerError",
29 {
30 method: Schema.String,
31 cause: Schema.Defect(),
32 },
33) {
34 override get message(): string {
35 return `Cursor Agent SDK ${this.method} failed.`;
36 }
37}
38
39/** The failure text a user sees: the SDK's own reason, which the error's message leaves out. */
40export function cursorSdkFailureMessage(error: CursorAgentSdkRunnerError): string {
41 const reason = sdkErrorReason(error.cause);
42 return reason === undefined
43 ? error.message
44 : `Cursor Agent SDK ${error.method} failed: ${reason}`;
45}
46
47/** Codes Cursor sends when it has no specific one. */
48const GENERIC_SDK_ERROR_CODES = new Set(["", "error", "unknown"]);
49
50/** The SDK's own message, with the code and HTTP status its errors carry. */
51function sdkErrorReason(cause: unknown): string | undefined {
52 if (!(cause instanceof Error)) return undefined;
53 const message = cause.message.trim();
54 if (message.length === 0) return undefined;
55 const code = Reflect.get(cause, "code");
56 const status = Reflect.get(cause, "status");
57 const details = [
58 ...(typeof code === "string" && !GENERIC_SDK_ERROR_CODES.has(code) && !message.includes(code)
59 ? [code]
60 : []),
61 ...(typeof status === "number" ? [`HTTP ${status}`] : []),
62 ];
63 return details.length === 0 ? message : `${message} (${details.join(", ")})`;
64}
65
66export const isCursorAgentSdkRunnerError = Schema.is(CursorAgentSdkRunnerError);
67
68export interface CursorAgentSdkOpenInput {
69 readonly operation: "create" | "resume";
70 readonly agentId?: string;
71 readonly options: AgentOptions;
72 readonly threadId: ThreadId;
73 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
74}
75
76export interface CursorAgentSdkSendInput<Error> {
77 readonly message: string | SDKUserMessage;
78 readonly options?: Omit<SendOptions, "onDelta">;
79 readonly onDelta?: (update: InteractionUpdate) => Effect.Effect<void, Error>;
80}
81
82export interface CursorAgentSdkRun {
83 readonly runId: string;
84 readonly agentId: string;
85 readonly wait: Effect.Effect<RunResult, CursorAgentSdkRunnerError>;
86 readonly cancel: Effect.Effect<void, CursorAgentSdkRunnerError>;
87}
88
89export interface CursorAgentSdkSession {
90 readonly agentId: string;
91 readonly send: <Error>(
92 input: CursorAgentSdkSendInput<Error>,
93 ) => Effect.Effect<CursorAgentSdkRun, CursorAgentSdkRunnerError>;
94 readonly listMessages: Effect.Effect<ReadonlyArray<AgentMessage>, CursorAgentSdkRunnerError>;
95 readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
96}
97
98export class CursorAgentSdkRunner extends Context.Service<
99 CursorAgentSdkRunner,
100 {
101 readonly open: (
102 input: CursorAgentSdkOpenInput,
103 ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;
104 readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;
105 }
106>()("@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner") {}
107
108export interface CursorAgentSdkLoggedAgentOptions {
109 readonly model?: AgentOptions["model"];
110 readonly hasName?: boolean;
111 readonly mode?: AgentOptions["mode"];
112 readonly local?: {
113 readonly hasCwd?: boolean;
114 readonly autoReview?: boolean;
115 readonly settingSources?: AgentOptions["local"] extends infer Local
116 ? Local extends { readonly settingSources?: infer Sources }
117 ? Sources
118 : never
119 : never;
120 readonly sandboxEnabled?: boolean;
121 readonly enableAgentRetries?: boolean;
122 readonly hasCustomTools?: boolean;
123 };
124 readonly agents?: ReadonlyArray<string>;
125}
126
127export interface CursorAgentSdkLoggedSendOptions {
128 readonly model?: SendOptions["model"];
129 readonly mode?: SendOptions["mode"];
130 readonly local?: {
131 readonly force?: boolean;
132 readonly hasCustomTools?: boolean;
133 };
134 readonly idempotencyKey?: string;
135}
136
137export type CursorAgentSdkProtocolLogEvent =
138 | {
139 readonly direction: "outgoing";
140 readonly stage: "decoded";
141 readonly payload: {
142 readonly type: "agent.open";
143 readonly operation: CursorAgentSdkOpenInput["operation"];
144 readonly agentId?: string;
145 readonly options: CursorAgentSdkLoggedAgentOptions;
146 };
147 }
148 | {
149 readonly direction: "incoming";
150 readonly stage: "decoded";
151 readonly payload: {
152 readonly type: "agent.opened";
153 readonly agentId: string;
154 };
155 }
156 | {
157 readonly direction: "outgoing";
158 readonly stage: "decoded";
159 readonly payload: {
160 readonly type: "run.start";
161 readonly message: string | SDKUserMessage;
162 readonly options: CursorAgentSdkLoggedSendOptions;
163 };
164 }
165 | {
166 readonly direction: "incoming";
167 readonly stage: "decoded";
168 readonly payload: {
169 readonly type: "run.started";
170 readonly runId: string;
171 readonly agentId: string;
172 };
173 }
174 | {
175 readonly direction: "incoming";
176 readonly stage: "decoded";
177 readonly payload: {
178 readonly type: "interaction.update";
179 readonly runId: string;
180 readonly update: InteractionUpdate;
181 };
182 }
183 | {
184 readonly direction: "incoming";
185 readonly stage: "decoded";
186 readonly payload: {
187 readonly type: "run.completed";
188 readonly result: RunResult;
189 };
190 }
191 | {
192 readonly direction: "outgoing";
193 readonly stage: "decoded";
194 readonly payload: {
195 readonly type: "run.cancel";
196 readonly runId: string;
197 };
198 }
199 | {
200 readonly direction: "outgoing";
201 readonly stage: "decoded";
202 readonly payload: {
203 readonly type: "agent.messages.list";
204 readonly agentId: string;
205 };
206 }
207 | {
208 readonly direction: "incoming";
209 readonly stage: "decoded";
210 readonly payload: {
211 readonly type: "agent.messages";
212 readonly agentId: string;
213 readonly messages: ReadonlyArray<AgentMessage>;
214 };
215 }
216 | {
217 readonly direction: "outgoing";
218 readonly stage: "decoded";
219 readonly payload: {
220 readonly type: "agent.close";
221 readonly agentId: string;
222 };
223 };
224
225export type CursorAgentSdkProtocolLogger = (
226 event: CursorAgentSdkProtocolLogEvent,
227) => Effect.Effect<void>;
228
229function runnerError(cause: unknown, method: string): CursorAgentSdkRunnerError {
230 return isCursorAgentSdkRunnerError(cause)
231 ? cause
232 : new CursorAgentSdkRunnerError({ method, cause });
233}
234
235function isActiveRunConflict(cause: unknown): boolean {
236 return cause instanceof Error && /already has active run/i.test(cause.message);
237}
238
239export function isCursorCancellationError(cause: unknown): boolean {
240 let current = cause;
241 const seen = new Set<object>();
242
243 while (typeof current === "object" && current !== null && !seen.has(current)) {
244 if (Reflect.get(current, "name") === "AbortError") {
245 return true;
246 }
247 seen.add(current);
248 current = Reflect.get(current, "cause");
249 }
250
251 return false;
252}
253
254export function loggedCursorAgentOptions(options: AgentOptions): CursorAgentSdkLoggedAgentOptions {
255 return {
256 ...(options.model === undefined ? {} : { model: options.model }),
257 ...(options.name === undefined ? {} : { hasName: true }),
258 ...(options.mode === undefined ? {} : { mode: options.mode }),
259 ...(options.local === undefined
260 ? {}
261 : {
262 local: {
263 ...(options.local.cwd === undefined ? {} : { hasCwd: true }),
264 ...(options.local.autoReview === undefined
265 ? {}
266 : { autoReview: options.local.autoReview }),
267 ...(options.local.settingSources === undefined
268 ? {}
269 : { settingSources: options.local.settingSources }),
270 ...(options.local.sandboxOptions === undefined
271 ? {}
272 : { sandboxEnabled: options.local.sandboxOptions.enabled }),
273 ...(options.local.enableAgentRetries === undefined
274 ? {}
275 : { enableAgentRetries: options.local.enableAgentRetries }),
276 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
277 },
278 }),
279 ...(options.agents === undefined ? {} : { agents: Object.keys(options.agents).toSorted() }),
280 };
281}
282
283export function loggedCursorSendOptions(
284 options: Omit<SendOptions, "onDelta"> | undefined,
285): CursorAgentSdkLoggedSendOptions {
286 if (options === undefined) {
287 return {};
288 }
289 return {
290 ...(options.model === undefined ? {} : { model: options.model }),
291 ...(options.mode === undefined ? {} : { mode: options.mode }),
292 ...(options.local === undefined
293 ? {}
294 : {
295 local: {
296 ...(options.local.force === undefined ? {} : { force: options.local.force }),
297 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
298 },
299 }),
300 ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
301 };
302}
303
304function makeCursorAgentSdkProtocolLogger(input: {
305 readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;
306 readonly threadId: ThreadId;
307 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
308}): CursorAgentSdkProtocolLogger | undefined {
309 if (input.nativeEventLogger === undefined) {
310 return undefined;
311 }
312 const nativeEventLogger = input.nativeEventLogger;
313 return (event) =>
314 nativeEventLogger
315 .write(
316 {
317 provider: CURSOR_PROVIDER,
318 protocol: CURSOR_AGENT_SDK_PROTOCOL,
319 kind: "protocol",
320 providerSessionId: input.providerSessionId,
321 event,
322 },
323 input.threadId,
324 )
325 .pipe(Effect.ignore);
326}
327
328export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
329 protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
330) {
331 const sdk = yield* CursorSdk.CursorSdk;
332
333 /**
334 * The Cursor SDK decides once per process whether local sandboxing works, and
335 * caches the answer the first time any run starts. Only sandboxed runs point it
336 * at its `cursorsandbox` helper first, so after an unsandboxed (Full access)
337 * run it caches "unsupported" and rejects every later sandboxed run until the
338 * server restarts.
339 */
340 const sandboxSupportPrimeStarted = yield* Ref.make(false);
341 const sandboxSupportPrimed = yield* Deferred.make<void>();
342 const primeCursorSandboxSupport = Effect.fn("CursorAgentSdkRunner.primeSandboxSupport")(
343 function* (options: AgentOptions) {
344 if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
345 return yield* Deferred.await(sandboxSupportPrimed);
346 }
347 yield* Effect.tryPromise(async () => {
348 const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
349 const platform = await sdk.createAgentPlatform(
350 cwd === undefined ? {} : { workspaceRef: cwd },
351 );
352 const release = await platform.prewarmLocalWorkspace({
353 ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
354 local: {
355 ...(cwd === undefined ? {} : { cwd }),
356 settingSources: [],
357 sandboxOptions: { enabled: true },
358 },
359 });
360 await release();
361 }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
362 },
363 );
364
365 return CursorAgentSdkRunner.of({
366 open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
367 const { Agent } = sdk;
368 if (input.options.local?.sandboxOptions?.enabled === false) {
369 yield* primeCursorSandboxSupport(input.options);
370 }
371 const protocolLogger = protocolLoggerFor(input);
372 const log = (event: CursorAgentSdkProtocolLogEvent) =>
373 protocolLogger === undefined ? Effect.void : protocolLogger(event);
374
375 yield* log({
376 direction: "outgoing",
377 stage: "decoded",
378 payload: {
379 type: "agent.open",
380 operation: input.operation,
381 ...(input.agentId === undefined ? {} : { agentId: input.agentId }),
382 options: loggedCursorAgentOptions(input.options),
383 },
384 });
385
386 const agent = yield* Effect.tryPromise({
387 try: () =>
388 input.operation === "create"
389 ? Agent.create(input.options)
390 : Agent.resume(input.agentId!, input.options),
391 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
392 });
393
394 yield* log({
395 direction: "incoming",
396 stage: "decoded",
397 payload: {
398 type: "agent.opened",
399 agentId: agent.agentId,
400 },
401 });
402
403 const cwd =
404 typeof input.options.local?.cwd === "string"
405 ? input.options.local.cwd
406 : input.options.local?.cwd?.[0];
407 const runOptions = {
408 runtime: "local" as const,
409 ...(cwd === undefined ? {} : { cwd }),
410 ...(input.options.local?.store === undefined ? {} : { store: input.options.local.store }),
411 };
412 let abandonedRunRecoveryAvailable = input.operation === "resume";
413
414 return {
415 agentId: agent.agentId,
416 send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) {
417 const context = yield* Effect.context();
418 yield* log({
419 direction: "outgoing",
420 stage: "decoded",
421 payload: {
422 type: "run.start",
423 message: sendInput.message,
424 options: loggedCursorSendOptions(sendInput.options),
425 },
426 });
427
428 let callbacksReady = false;
429 const pendingUpdates: Array<InteractionUpdate> = [];
430 let callbackFailure: { readonly cause: unknown } | undefined;
431 let callbackChain = Promise.resolve();
432 let runId = "";
433 const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
434 callbackChain = callbackChain
435 .then(() => {
436 if (callbackFailure !== undefined) {
437 return;
438 }
439 return Effect.runPromiseWith(context)(
440 log({
441 direction: "incoming",
442 stage: "decoded",
443 payload: {
444 type: "interaction.update",
445 runId,
446 update,
447 },
448 }).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)),
449 );
450 })
451 .catch((cause) => {
452 callbackFailure ??= { cause };
453 });
454 return callbackChain;
455 };
456
457 const startRun = () =>
458 Effect.tryPromise({
459 try: () =>
460 agent.send(sendInput.message, {
461 ...sendInput.options,
462 onDelta: async ({ update }) => {
463 if (!callbacksReady) {
464 pendingUpdates.push(update);
465 return;
466 }
467 await dispatchUpdate(update);
468 },
469 }),
470 catch: (cause) => runnerError(cause, "run.start"),
471 });
472 const run = yield* startRun().pipe(
473 Effect.catchIf(
474 (error) => abandonedRunRecoveryAvailable && isActiveRunConflict(error.cause),
475 (error) =>
476 Effect.gen(function* () {
477 abandonedRunRecoveryAvailable = false;
478 const latestRun = yield* Effect.tryPromise({
479 try: () => Agent.listRuns(agent.agentId, { ...runOptions, limit: 1 }),
480 catch: (cause) => runnerError(cause, "agent.listRuns"),
481 });
482 const activeRun = latestRun.items.find(
483 (candidate) => candidate.status === "running",
484 );
485 if (activeRun === undefined) {
486 return yield* error;
487 }
488 yield* log({
489 direction: "outgoing",
490 stage: "decoded",
491 payload: { type: "run.cancel", runId: activeRun.id },
492 });
493 yield* Effect.tryPromise({
494 try: () => Agent.cancelRun(activeRun.id, runOptions),
495 catch: (cause) => runnerError(cause, "agent.cancelRun"),
496 });
497 return yield* startRun();
498 }),
499 ),
500 );
501 abandonedRunRecoveryAvailable = false;
502 runId = run.id;
503 yield* log({
504 direction: "incoming",
505 stage: "decoded",
506 payload: {
507 type: "run.started",
508 runId: run.id,
509 agentId: run.agentId,
510 },
511 });
512 callbacksReady = true;
513 for (const update of pendingUpdates) {
514 yield* Effect.tryPromise({
515 try: () => dispatchUpdate(update),
516 catch: (cause) => runnerError(cause, "run.onDelta"),
517 });
518 }
519
520 return {
521 runId: run.id,
522 agentId: run.agentId,
523 wait: Effect.tryPromise({
524 try: async () => {
525 const result = await run.wait();
526 await callbackChain;
527 if (callbackFailure !== undefined) {
528 throw callbackFailure.cause;
529 }
530 return result;
531 },
532 catch: (cause) => runnerError(cause, "run.wait"),
533 }).pipe(
534 Effect.tap((result) =>
535 log({
536 direction: "incoming",
537 stage: "decoded",
538 payload: {
539 type: "run.completed",
540 result,
541 },
542 }),
543 ),
544 ),
545 cancel: log({
546 direction: "outgoing",
547 stage: "decoded",
548 payload: {
549 type: "run.cancel",
550 runId: run.id,
551 },
552 }).pipe(
553 Effect.andThen(
554 Effect.tryPromise({
555 try: async () => {
556 try {
557 await run.cancel();
558 } catch (cause) {
559 if (!isCursorCancellationError(cause)) {
560 throw cause;
561 }
562 }
563 },
564 catch: (cause) => runnerError(cause, "run.cancel"),
565 }),
566 ),
567 ),
568 } satisfies CursorAgentSdkRun;
569 }),
570 listMessages: log({
571 direction: "outgoing",
572 stage: "decoded",
573 payload: {
574 type: "agent.messages.list",
575 agentId: agent.agentId,
576 },
577 }).pipe(
578 Effect.andThen(
579 Effect.tryPromise({
580 try: () =>
581 Agent.messages.list(agent.agentId, {
582 runtime: "local",
583 ...(cwd === undefined ? {} : { cwd }),
584 }),
585 catch: (cause) => runnerError(cause, "agent.messages.list"),
586 }),
587 ),
588 Effect.tap((messages) =>
589 log({
590 direction: "incoming",
591 stage: "decoded",
592 payload: {
593 type: "agent.messages",
594 agentId: agent.agentId,
595 messages,
596 },
597 }),
598 ),
599 ),
600 close: log({
601 direction: "outgoing",
602 stage: "decoded",
603 payload: {
604 type: "agent.close",
605 agentId: agent.agentId,
606 },
607 }).pipe(
608 Effect.andThen(
609 Effect.try({
610 try: () => agent.close(),
611 catch: (cause) => runnerError(cause, "agent.close"),
612 }),
613 ),
614 ),
615 } satisfies CursorAgentSdkSession;
616 }),
617 assertComplete: Effect.void,
618 });
619});
620
621export const layer = Layer.effect(
622 CursorAgentSdkRunner,
623 Effect.gen(function* () {
624 const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
625 return yield* makeCursorAgentSdkRunner((input) =>
626 makeCursorAgentSdkProtocolLogger({
627 nativeEventLogger,
628 threadId: input.threadId,
629 providerSessionId: input.providerSessionId,
630 }),
631 );
632 }),
633);