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
328/**
329 * Runs agents through the Cursor SDK, logging every frame to the protocol
330 * logger chosen for each opened agent. The live layer writes the native
331 * provider event log; the replay recorder turns the same frames into a
332 * transcript.
333 */
334export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
335 protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
336) {
337 const { Agent, createAgentPlatform } = yield* CursorSdk.CursorSdk;
338
339 /**
340 * The Cursor SDK decides once per process whether local sandboxing works, and
341 * caches the answer the first time any run starts. Only sandboxed runs point
342 * it at its `cursorsandbox` helper first, so after an unsandboxed (Full access)
343 * run it caches "unsupported" and rejects every later sandboxed run until the
344 * server restarts. Warming a bare sandboxed executor before the first
345 * unsandboxed agent opens lets the SDK find the helper and cache the real
346 * answer. Warming is best effort: on a machine without sandbox support it
347 * fails, the SDK caches "unsupported", and sandboxed runs report that as
348 * before.
349 */
350 const sandboxSupportPrimeStarted = yield* Ref.make(false);
351 const sandboxSupportPrimed = yield* Deferred.make<void>();
352 const primeCursorSandboxSupport = Effect.fn("CursorAgentSdkRunner.primeSandboxSupport")(
353 function* (options: AgentOptions) {
354 if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
355 return yield* Deferred.await(sandboxSupportPrimed);
356 }
357 yield* Effect.tryPromise(async () => {
358 const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
359 const platform = await createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
360 const release = await platform.prewarmLocalWorkspace({
361 ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
362 local: {
363 ...(cwd === undefined ? {} : { cwd }),
364 settingSources: [],
365 sandboxOptions: { enabled: true },
366 },
367 });
368 await release();
369 }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
370 },
371 );
372
373 return CursorAgentSdkRunner.of({
374 open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
375 if (input.options.local?.sandboxOptions?.enabled === false) {
376 yield* primeCursorSandboxSupport(input.options);
377 }
378 const protocolLogger = protocolLoggerFor(input);
379 const log = (event: CursorAgentSdkProtocolLogEvent) =>
380 protocolLogger === undefined ? Effect.void : protocolLogger(event);
381
382 yield* log({
383 direction: "outgoing",
384 stage: "decoded",
385 payload: {
386 type: "agent.open",
387 operation: input.operation,
388 ...(input.agentId === undefined ? {} : { agentId: input.agentId }),
389 options: loggedCursorAgentOptions(input.options),
390 },
391 });
392
393 const agent = yield* Effect.tryPromise({
394 try: () =>
395 input.operation === "create"
396 ? Agent.create(input.options)
397 : Agent.resume(input.agentId!, input.options),
398 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
399 });
400
401 yield* log({
402 direction: "incoming",
403 stage: "decoded",
404 payload: {
405 type: "agent.opened",
406 agentId: agent.agentId,
407 },
408 });
409
410 const cwd =
411 typeof input.options.local?.cwd === "string"
412 ? input.options.local.cwd
413 : input.options.local?.cwd?.[0];
414 const runOptions = {
415 runtime: "local" as const,
416 ...(cwd === undefined ? {} : { cwd }),
417 ...(input.options.local?.store === undefined ? {} : { store: input.options.local.store }),
418 };
419 let abandonedRunRecoveryAvailable = input.operation === "resume";
420
421 return {
422 agentId: agent.agentId,
423 send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) {
424 const context = yield* Effect.context();
425 yield* log({
426 direction: "outgoing",
427 stage: "decoded",
428 payload: {
429 type: "run.start",
430 message: sendInput.message,
431 options: loggedCursorSendOptions(sendInput.options),
432 },
433 });
434
435 let callbacksReady = false;
436 const pendingUpdates: Array<InteractionUpdate> = [];
437 let callbackFailure: { readonly cause: unknown } | undefined;
438 let callbackChain = Promise.resolve();
439 let runId = "";
440 const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
441 callbackChain = callbackChain
442 .then(() => {
443 if (callbackFailure !== undefined) {
444 return;
445 }
446 return Effect.runPromiseWith(context)(
447 log({
448 direction: "incoming",
449 stage: "decoded",
450 payload: {
451 type: "interaction.update",
452 runId,
453 update,
454 },
455 }).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)),
456 );
457 })
458 .catch((cause) => {
459 callbackFailure ??= { cause };
460 });
461 return callbackChain;
462 };
463
464 const startRun = () =>
465 Effect.tryPromise({
466 try: () =>
467 agent.send(sendInput.message, {
468 ...sendInput.options,
469 onDelta: async ({ update }) => {
470 if (!callbacksReady) {
471 pendingUpdates.push(update);
472 return;
473 }
474 await dispatchUpdate(update);
475 },
476 }),
477 catch: (cause) => runnerError(cause, "run.start"),
478 });
479 const run = yield* startRun().pipe(
480 Effect.catchIf(
481 (error) => abandonedRunRecoveryAvailable && isActiveRunConflict(error.cause),
482 (error) =>
483 Effect.gen(function* () {
484 abandonedRunRecoveryAvailable = false;
485 const latestRun = yield* Effect.tryPromise({
486 try: () => Agent.listRuns(agent.agentId, { ...runOptions, limit: 1 }),
487 catch: (cause) => runnerError(cause, "agent.listRuns"),
488 });
489 const activeRun = latestRun.items.find(
490 (candidate) => candidate.status === "running",
491 );
492 if (activeRun === undefined) {
493 return yield* error;
494 }
495 yield* log({
496 direction: "outgoing",
497 stage: "decoded",
498 payload: { type: "run.cancel", runId: activeRun.id },
499 });
500 yield* Effect.tryPromise({
501 try: () => Agent.cancelRun(activeRun.id, runOptions),
502 catch: (cause) => runnerError(cause, "agent.cancelRun"),
503 });
504 return yield* startRun();
505 }),
506 ),
507 );
508 abandonedRunRecoveryAvailable = false;
509 runId = run.id;
510 yield* log({
511 direction: "incoming",
512 stage: "decoded",
513 payload: {
514 type: "run.started",
515 runId: run.id,
516 agentId: run.agentId,
517 },
518 });
519 callbacksReady = true;
520 for (const update of pendingUpdates) {
521 yield* Effect.tryPromise({
522 try: () => dispatchUpdate(update),
523 catch: (cause) => runnerError(cause, "run.onDelta"),
524 });
525 }
526
527 return {
528 runId: run.id,
529 agentId: run.agentId,
530 wait: Effect.tryPromise({
531 try: async () => {
532 const result = await run.wait();
533 await callbackChain;
534 if (callbackFailure !== undefined) {
535 throw callbackFailure.cause;
536 }
537 return result;
538 },
539 catch: (cause) => runnerError(cause, "run.wait"),
540 }).pipe(
541 Effect.tap((result) =>
542 log({
543 direction: "incoming",
544 stage: "decoded",
545 payload: {
546 type: "run.completed",
547 result,
548 },
549 }),
550 ),
551 ),
552 cancel: log({
553 direction: "outgoing",
554 stage: "decoded",
555 payload: {
556 type: "run.cancel",
557 runId: run.id,
558 },
559 }).pipe(
560 Effect.andThen(
561 Effect.tryPromise({
562 try: async () => {
563 try {
564 await run.cancel();
565 } catch (cause) {
566 if (!isCursorCancellationError(cause)) {
567 throw cause;
568 }
569 }
570 },
571 catch: (cause) => runnerError(cause, "run.cancel"),
572 }),
573 ),
574 ),
575 } satisfies CursorAgentSdkRun;
576 }),
577 listMessages: log({
578 direction: "outgoing",
579 stage: "decoded",
580 payload: {
581 type: "agent.messages.list",
582 agentId: agent.agentId,
583 },
584 }).pipe(
585 Effect.andThen(
586 Effect.tryPromise({
587 try: () =>
588 Agent.messages.list(agent.agentId, {
589 runtime: "local",
590 ...(cwd === undefined ? {} : { cwd }),
591 }),
592 catch: (cause) => runnerError(cause, "agent.messages.list"),
593 }),
594 ),
595 Effect.tap((messages) =>
596 log({
597 direction: "incoming",
598 stage: "decoded",
599 payload: {
600 type: "agent.messages",
601 agentId: agent.agentId,
602 messages,
603 },
604 }),
605 ),
606 ),
607 close: log({
608 direction: "outgoing",
609 stage: "decoded",
610 payload: {
611 type: "agent.close",
612 agentId: agent.agentId,
613 },
614 }).pipe(
615 Effect.andThen(
616 Effect.try({
617 try: () => agent.close(),
618 catch: (cause) => runnerError(cause, "agent.close"),
619 }),
620 ),
621 ),
622 } satisfies CursorAgentSdkSession;
623 }),
624 assertComplete: Effect.void,
625 });
626});
627
628export const layer = Layer.effect(
629 CursorAgentSdkRunner,
630 Effect.gen(function* () {
631 const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
632 return yield* makeCursorAgentSdkRunner((input) =>
633 makeCursorAgentSdkProtocolLogger({
634 nativeEventLogger,
635 threadId: input.threadId,
636 providerSessionId: input.providerSessionId,
637 }),
638 );
639 }),
640);