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