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