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