Open History to see the last commit
1import type {
2 AgentMessage,
3 AgentOptions,
4 InteractionUpdate,
5 Run,
6 RunRecord,
7 RunResult,
8 SDKUserMessage,
9 SendOptions,
10 SteerAckOutcome,
11} from "@cursor/sdk";
12import * as NodeAsyncHooks from "node:async_hooks";
13import {
14 NonNegativeInt,
15 type OrchestrationV2ProviderSession,
16 ProviderDriverKind,
17 type ThreadId,
18} from "@t3tools/contracts";
19import * as Context from "effect/Context";
20import * as Deferred from "effect/Deferred";
21import * as Effect from "effect/Effect";
22import * as Exit from "effect/Exit";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Ref from "effect/Ref";
26import * as Schema from "effect/Schema";
27import * as Semaphore from "effect/Semaphore";
28
29import * as CursorSdk from "./CursorSdk.ts";
30import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
31
32export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const;
33export const CURSOR_PROVIDER = ProviderDriverKind.make("cursor");
34
35export class CursorAgentSdkRunnerError extends Schema.TaggedError<CursorAgentSdkRunnerError>()(
36 "CursorAgentSdkRunnerError",
37 {
38 method: Schema.String,
39 cause: Schema.Defect(),
40 },
41) {
42 override get message(): string {
43 return `Cursor Agent SDK ${this.method} failed.`;
44 }
45}
46
47export function cursorSdkFailureMessage(error: CursorAgentSdkRunnerError): string {
48 const reason = sdkErrorReason(error.cause);
49 return reason === undefined
50 ? error.message
51 : `Cursor Agent SDK ${error.method} failed: ${reason}`;
52}
53
54// The SDK maps backend details to codes like PRO_USER_USAGE_LIMIT or RATE_LIMITED, without a status.
55const CURSOR_USAGE_LIMIT_CODE =
56 /^(?:resource_exhausted|rate_limited(?:_changeable)?|\w*_usage_limit|\w*_rate_limit(?:_exceeded)?)$/i;
57
58export function isCursorUsageLimitError(cause: unknown): boolean {
59 const error = isCursorAgentSdkRunnerError(cause) ? cause.cause : cause;
60 if (typeof error !== "object" || error === null) return false;
61 const code = Reflect.get(error, "code");
62 return (
63 Reflect.get(error, "name") === "RateLimitError" ||
64 Reflect.get(error, "status") === 429 ||
65 (typeof code === "string" && CURSOR_USAGE_LIMIT_CODE.test(code))
66 );
67}
68
69/**
70 * Names of the inline MCP servers a Cursor team policy rejected. The SDK refuses the whole run
71 * with an InlineMcpServersBlockedError, which it wraps in an UnknownAgentError.
72 */
73export function blockedInlineMcpServers(cause: unknown): ReadonlyArray<string> {
74 const seen = new Set<unknown>();
75 let current = isCursorAgentSdkRunnerError(cause) ? cause.cause : cause;
76 while (typeof current === "object" && current !== null && !seen.has(current)) {
77 seen.add(current);
78 const servers = Reflect.get(current, "servers");
79 if (Reflect.get(current, "name") === "InlineMcpServersBlockedError" && Array.isArray(servers)) {
80 return servers.flatMap((server: unknown) => {
81 const name =
82 typeof server === "object" && server !== null ? Reflect.get(server, "name") : undefined;
83 return typeof name === "string" ? [name] : [];
84 });
85 }
86 current = Reflect.get(current, "cause");
87 }
88 return [];
89}
90
91const GENERIC_SDK_ERROR_CODES = new Set(["", "error", "unknown"]);
92
93function sdkErrorReason(cause: unknown): string | undefined {
94 if (!(cause instanceof Error)) return undefined;
95 const message = cause.message.trim();
96 if (message.length === 0) return undefined;
97 const code = Reflect.get(cause, "code");
98 const status = Reflect.get(cause, "status");
99 const details = [
100 ...(typeof code === "string" && !GENERIC_SDK_ERROR_CODES.has(code) && !message.includes(code)
101 ? [code]
102 : []),
103 ...(typeof status === "number" ? [`HTTP ${status}`] : []),
104 ];
105 return details.length === 0 ? message : `${message} (${details.join(", ")})`;
106}
107
108export const isCursorAgentSdkRunnerError = Schema.is(CursorAgentSdkRunnerError);
109
110export interface CursorAgentSdkOpenInput {
111 readonly operation: "create" | "resume";
112 readonly agentId?: string;
113 readonly storeCwd?: string;
114 readonly options: AgentOptions;
115 readonly threadId: ThreadId;
116 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
117}
118
119export interface CursorAgentSdkSendInput<Error> {
120 readonly message: string | SDKUserMessage;
121 readonly options?: Omit<SendOptions, "onDelta">;
122 readonly onDelta?: (update: InteractionUpdate) => Effect.Effect<void, Error>;
123 /** Runs `agent.summarize()` instead, which takes no message or options. */
124 readonly summarize?: boolean;
125 /** Runs `agent.resume()`: Cursor's ResumeAction from the latest checkpoint, with no message. */
126 readonly resume?: boolean;
127 /**
128 * Runs, in order, when a background shell this agent starts from now on starts and when it
129 * ends, which is often long after the run.
130 */
131 readonly onBackgroundShell?: (event: CursorBackgroundShellEvent) => Effect.Effect<void>;
132 /** Runs as the SDK enters each slow step of preparing the run, before the run starts. */
133 readonly onStartupPhase?: (phase: string) => Effect.Effect<void>;
134}
135
136interface CursorBackgroundShellRef {
137 /** The shell id Cursor gave the agent. */
138 readonly id: string;
139 readonly pid: number | undefined;
140 readonly command: string;
141}
142
143export type CursorBackgroundShellEvent =
144 | (CursorBackgroundShellRef & { readonly type: "started"; readonly stop: () => void })
145 | (CursorBackgroundShellRef & {
146 readonly type: "ended";
147 /** Killed by the agent or by `stop`, rather than exiting by itself. */
148 readonly stopped: boolean;
149 readonly exitCode: number | undefined;
150 /** The file Cursor logs the shell's output to. */
151 readonly outputPath: string | undefined;
152 });
153
154export interface CursorAgentSdkRun {
155 readonly runId: string;
156 readonly agentId: string;
157 readonly wait: Effect.Effect<RunResult, CursorAgentSdkRunnerError>;
158 readonly cancel: Effect.Effect<void, CursorAgentSdkRunnerError>;
159 /** Absent on test doubles that never steer. The live runner always sets it. */
160 readonly steer?: (text: string) => Effect.Effect<SteerAckOutcome, CursorAgentSdkRunnerError>;
161}
162
163export interface CursorContextUsage {
164 readonly usedTokens: number;
165 readonly maxTokens: number;
166}
167
168// The SDK types a checkpoint as `unknown`; Cursor keeps the conversation's context fill on it.
169const CursorCheckpoint = Schema.Struct({
170 tokenDetails: Schema.Struct({ usedTokens: NonNegativeInt, maxTokens: NonNegativeInt }),
171});
172const decodeCursorCheckpoint = Schema.decodeUnknownOption(CursorCheckpoint);
173
174export interface CursorAgentSdkSession {
175 readonly agentId: string;
176 readonly send: <Error>(
177 input: CursorAgentSdkSendInput<Error>,
178 ) => Effect.Effect<CursorAgentSdkRun, CursorAgentSdkRunnerError>;
179 readonly listMessages: Effect.Effect<ReadonlyArray<AgentMessage>, CursorAgentSdkRunnerError>;
180 /** Context fill at the latest checkpoint, if Cursor saved one. Absent on test doubles. */
181 readonly readContextUsage?: Effect.Effect<
182 CursorContextUsage | undefined,
183 CursorAgentSdkRunnerError
184 >;
185 /**
186 * Whether a run (the latest when omitted) saved a checkpoint of its own. Cursor keeps a stopped
187 * run only from its first checkpoint on; before that the conversation lacks the run's request.
188 */
189 readonly runCheckpointed?: (runId?: string) => Effect.Effect<boolean, CursorAgentSdkRunnerError>;
190 /**
191 * Rewinds the conversation to just before the run after `runId`, as `cursor-agent` /rewind does.
192 * The open agent keeps its old conversation in memory, so reopen it before the next send.
193 */
194 readonly rewindAfterRun?: (runId: string) => Effect.Effect<void, CursorAgentSdkRunnerError>;
195 /** False once an out-of-process worker has terminated or started closing; absent on in-process sessions. */
196 readonly isAlive?: () => boolean;
197 /** Completes once `isAlive` turns false; absent on in-process sessions. */
198 readonly ended?: Effect.Effect<void>;
199 readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
200}
201
202export interface CursorAgentSdkTextGenerateInput {
203 readonly prompt: string;
204 readonly apiKey: string;
205 readonly model: NonNullable<AgentOptions["model"]>;
206 readonly cwd: string;
207 readonly stateRoot: string;
208}
209
210export class CursorAgentSdkRunner extends Context.Service<
211 CursorAgentSdkRunner,
212 {
213 readonly open: (
214 input: CursorAgentSdkOpenInput,
215 ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;
216 readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;
217 /** Absent on in-process test doubles; the out-of-process runner provides it. */
218 readonly textGenerate?: (
219 input: CursorAgentSdkTextGenerateInput,
220 ) => Effect.Effect<RunResult, CursorAgentSdkRunnerError>;
221 }
222>()("@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner") {}
223
224export interface CursorAgentSdkLoggedAgentOptions {
225 readonly model?: AgentOptions["model"];
226 readonly hasName?: boolean;
227 readonly mode?: AgentOptions["mode"];
228 readonly local?: {
229 readonly hasCwd?: boolean;
230 readonly autoReview?: boolean;
231 readonly settingSources?: AgentOptions["local"] extends infer Local
232 ? Local extends { readonly settingSources?: infer Sources }
233 ? Sources
234 : never
235 : never;
236 readonly sandboxEnabled?: boolean;
237 readonly enableAgentRetries?: boolean;
238 readonly hasCustomTools?: boolean;
239 };
240 readonly agents?: ReadonlyArray<string>;
241}
242
243export interface CursorAgentSdkLoggedSendOptions {
244 readonly model?: SendOptions["model"];
245 readonly mode?: SendOptions["mode"];
246 readonly hasMcpServers?: boolean;
247 readonly mcpServerNames?: ReadonlyArray<string>;
248 readonly local?: {
249 readonly force?: boolean;
250 readonly hasCustomTools?: boolean;
251 };
252 readonly idempotencyKey?: string;
253}
254
255export type CursorAgentSdkProtocolLogEvent =
256 | {
257 readonly direction: "outgoing";
258 readonly stage: "decoded";
259 readonly payload: {
260 readonly type: "agent.open";
261 readonly operation: CursorAgentSdkOpenInput["operation"];
262 readonly agentId?: string;
263 readonly options: CursorAgentSdkLoggedAgentOptions;
264 };
265 }
266 | {
267 readonly direction: "incoming";
268 readonly stage: "decoded";
269 readonly payload: {
270 readonly type: "agent.opened";
271 readonly agentId: string;
272 };
273 }
274 | {
275 readonly direction: "outgoing";
276 readonly stage: "decoded";
277 readonly payload: {
278 readonly type: "run.start";
279 readonly message: string | SDKUserMessage;
280 readonly options: CursorAgentSdkLoggedSendOptions;
281 };
282 }
283 | {
284 readonly direction: "outgoing";
285 readonly stage: "decoded";
286 readonly payload: {
287 readonly type: "run.resume";
288 readonly options: CursorAgentSdkLoggedSendOptions;
289 };
290 }
291 | {
292 readonly direction: "incoming";
293 readonly stage: "decoded";
294 readonly payload: {
295 readonly type: "run.started";
296 readonly runId: string;
297 readonly agentId: string;
298 };
299 }
300 | {
301 readonly direction: "incoming";
302 readonly stage: "decoded";
303 readonly payload: {
304 readonly type: "interaction.update";
305 readonly runId: string;
306 readonly update: InteractionUpdate;
307 };
308 }
309 | {
310 readonly direction: "incoming";
311 readonly stage: "decoded";
312 readonly payload: {
313 readonly type: "run.completed";
314 readonly result: RunResult;
315 };
316 }
317 | {
318 readonly direction: "outgoing";
319 readonly stage: "decoded";
320 readonly payload: {
321 readonly type: "run.steer";
322 readonly runId: string;
323 readonly text: string;
324 };
325 }
326 | {
327 readonly direction: "incoming";
328 readonly stage: "decoded";
329 readonly payload: {
330 readonly type: "run.steered";
331 readonly runId: string;
332 readonly outcome: SteerAckOutcome;
333 };
334 }
335 | {
336 readonly direction: "outgoing";
337 readonly stage: "decoded";
338 readonly payload: {
339 readonly type: "run.cancel";
340 readonly runId: string;
341 };
342 }
343 | {
344 readonly direction: "outgoing";
345 readonly stage: "decoded";
346 readonly payload: {
347 readonly type: "agent.messages.list";
348 readonly agentId: string;
349 };
350 }
351 | {
352 readonly direction: "outgoing";
353 readonly stage: "decoded";
354 readonly payload: {
355 readonly type: "agent.rewind";
356 readonly agentId: string;
357 readonly afterRunId: string;
358 };
359 }
360 | {
361 readonly direction: "incoming";
362 readonly stage: "decoded";
363 readonly payload: {
364 readonly type: "agent.messages";
365 readonly agentId: string;
366 readonly messages: ReadonlyArray<AgentMessage>;
367 };
368 }
369 | {
370 readonly direction: "outgoing";
371 readonly stage: "decoded";
372 readonly payload: {
373 readonly type: "agent.close";
374 readonly agentId: string;
375 };
376 };
377
378export type CursorAgentSdkProtocolLogger = (
379 event: CursorAgentSdkProtocolLogEvent,
380) => Effect.Effect<void>;
381
382function runnerError(cause: unknown, method: string): CursorAgentSdkRunnerError {
383 return isCursorAgentSdkRunnerError(cause)
384 ? cause
385 : new CursorAgentSdkRunnerError({ method, cause });
386}
387
388function isActiveRunConflict(cause: unknown): boolean {
389 return cause instanceof Error && /already has active run/i.test(cause.message);
390}
391
392export function isCursorCancellationError(cause: unknown): boolean {
393 let current = cause;
394 const seen = new Set<object>();
395
396 while (typeof current === "object" && current !== null && !seen.has(current)) {
397 if (Reflect.get(current, "name") === "AbortError") {
398 return true;
399 }
400 seen.add(current);
401 current = Reflect.get(current, "cause");
402 }
403
404 return false;
405}
406
407export function loggedCursorAgentOptions(options: AgentOptions): CursorAgentSdkLoggedAgentOptions {
408 return {
409 ...(options.model === undefined ? {} : { model: options.model }),
410 ...(options.name === undefined ? {} : { hasName: true }),
411 ...(options.mode === undefined ? {} : { mode: options.mode }),
412 ...(options.local === undefined
413 ? {}
414 : {
415 local: {
416 ...(options.local.cwd === undefined ? {} : { hasCwd: true }),
417 ...(options.local.autoReview === undefined
418 ? {}
419 : { autoReview: options.local.autoReview }),
420 ...(options.local.settingSources === undefined
421 ? {}
422 : { settingSources: options.local.settingSources }),
423 ...(options.local.sandboxOptions === undefined
424 ? {}
425 : { sandboxEnabled: options.local.sandboxOptions.enabled }),
426 ...(options.local.enableAgentRetries === undefined
427 ? {}
428 : { enableAgentRetries: options.local.enableAgentRetries }),
429 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
430 },
431 }),
432 ...(options.agents === undefined ? {} : { agents: Object.keys(options.agents).toSorted() }),
433 };
434}
435
436export function loggedCursorSendOptions(
437 options: Omit<SendOptions, "onDelta"> | undefined,
438): CursorAgentSdkLoggedSendOptions {
439 if (options === undefined) {
440 return {};
441 }
442 const mcpServerNames =
443 options.mcpServers === undefined ? undefined : Object.keys(options.mcpServers).toSorted();
444 return {
445 ...(options.model === undefined ? {} : { model: options.model }),
446 ...(options.mode === undefined ? {} : { mode: options.mode }),
447 ...(mcpServerNames === undefined ? {} : { hasMcpServers: true, mcpServerNames }),
448 ...(options.local === undefined
449 ? {}
450 : {
451 local: {
452 ...(options.local.force === undefined ? {} : { force: options.local.force }),
453 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
454 },
455 }),
456 ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
457 };
458}
459
460export function makeCursorAgentSdkProtocolLogger(input: {
461 readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;
462 readonly threadId: ThreadId;
463 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
464}): CursorAgentSdkProtocolLogger | undefined {
465 if (input.nativeEventLogger === undefined) {
466 return undefined;
467 }
468 const nativeEventLogger = input.nativeEventLogger;
469 return (event) =>
470 nativeEventLogger
471 .write(
472 {
473 provider: CURSOR_PROVIDER,
474 protocol: CURSOR_AGENT_SDK_PROTOCOL,
475 kind: "protocol",
476 providerSessionId: input.providerSessionId,
477 event,
478 },
479 input.threadId,
480 )
481 .pipe(Effect.ignore);
482}
483
484type CursorLocalStore = NonNullable<NonNullable<AgentOptions["local"]>["store"]>;
485
486interface DisposableCursorLocalStore extends CursorLocalStore {
487 readonly dispose: () => Promise<void>;
488}
489
490function isDisposableCursorLocalStore(value: unknown): value is DisposableCursorLocalStore {
491 return (
492 typeof value === "object" &&
493 value !== null &&
494 "agents" in value &&
495 "runs" in value &&
496 "checkpoints" in value &&
497 "runEvents" in value &&
498 "dispose" in value &&
499 typeof value.dispose === "function"
500 );
501}
502
503interface CursorBackgroundShell {
504 readonly conversationId?: unknown;
505 readonly command?: unknown;
506 readonly shell: {
507 readonly id?: unknown;
508 readonly pid?: unknown;
509 readonly abort: () => void;
510 readonly onComplete: (
511 listener: (completion: {
512 readonly code?: unknown;
513 readonly aborted?: unknown;
514 readonly outputPath?: unknown;
515 }) => void,
516 ) => void;
517 };
518}
519
520// The SDK names no step while it prepares a run, which can take minutes, so the @cursor/sdk patch
521// calls this hook as it enters each one. The hook is global: async context finds the send.
522const STARTUP_PHASE_HOOK = Symbol.for("@cursor/sdk.startupPhase");
523const startupPhaseListener = new NodeAsyncHooks.AsyncLocalStorage<(phase: string) => void>();
524
525function listeningForStartupPhases<A>(listener: (phase: string) => void, start: () => A): A {
526 const hooks = globalThis as Record<symbol, unknown>;
527 hooks[STARTUP_PHASE_HOOK] ??= (phase: unknown) => {
528 if (typeof phase === "string") startupPhaseListener.getStore()?.(phase);
529 };
530 return startupPhaseListener.run(listener, start);
531}
532
533// The SDK kills an agent's background shells when its run ends and reports their exit to no one.
534// The @cursor/sdk patch offers each new one to this hook; true keeps it past the run.
535const BACKGROUND_SHELL_HOOK = Symbol.for("@cursor/sdk.backgroundShell");
536const backgroundShellListeners = new Map<string, (event: CursorBackgroundShellEvent) => void>();
537
538function listenForBackgroundShells(
539 agentId: string,
540 listener: (event: CursorBackgroundShellEvent) => void,
541) {
542 const hooks = globalThis as Record<symbol, unknown>;
543 hooks[BACKGROUND_SHELL_HOOK] ??= ({ conversationId, command, shell }: CursorBackgroundShell) => {
544 const notify =
545 typeof conversationId === "string" ? backgroundShellListeners.get(conversationId) : undefined;
546 if (notify === undefined) return false;
547 const ref = {
548 id: String(shell.id),
549 pid: typeof shell.pid === "number" ? shell.pid : undefined,
550 command: typeof command === "string" ? command : "",
551 };
552 notify({ ...ref, type: "started", stop: () => shell.abort() });
553 shell.onComplete((completion) =>
554 notify({
555 ...ref,
556 type: "ended",
557 stopped: completion.aborted === true,
558 exitCode: typeof completion.code === "number" ? completion.code : undefined,
559 outputPath: typeof completion.outputPath === "string" ? completion.outputPath : undefined,
560 }),
561 );
562 return true;
563 };
564 backgroundShellListeners.set(agentId, listener);
565}
566
567export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
568 protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
569) {
570 const sdk = yield* CursorSdk.CursorSdk;
571
572 // Prime with cursorsandbox before any Full access run; the SDK caches sandbox support per process.
573 const sandboxSupportPrimeStarted = yield* Ref.make(false);
574 const sandboxSupportPrimed = yield* Deferred.make<void>();
575 const primeCursorSandboxSupport = Effect.fn("CursorAgentSdkRunner.primeSandboxSupport")(
576 function* (options: AgentOptions) {
577 if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
578 return yield* Deferred.await(sandboxSupportPrimed);
579 }
580 yield* Effect.tryPromise({
581 try: async () => {
582 const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
583 const platform = await sdk
584 .load()
585 .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
586 const release = await platform.prewarmLocalWorkspace({
587 ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
588 local: {
589 ...(cwd === undefined ? {} : { cwd }),
590 settingSources: [],
591 sandboxOptions: { enabled: true },
592 },
593 });
594 await release();
595 },
596 catch: (cause) => runnerError(cause, "prewarmLocalWorkspace"),
597 }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
598 },
599 );
600
601 // Ref-count one SqliteLocalAgentStore per workspace so concurrent sessions share a single
602 // index.db handle while still disposing handles, page caches, and FDs once the last one closes.
603 interface WorkspaceStoreLease {
604 readonly store: DisposableCursorLocalStore;
605 users: number;
606 }
607 const workspaceStores = new Map<string, WorkspaceStoreLease>();
608 const workspaceStoreLock = yield* Semaphore.make(1);
609 const acquireWorkspaceStore = (workspaceRef: string, method: string) =>
610 workspaceStoreLock.withPermits(1)(
611 Effect.suspend(() => {
612 const existing = workspaceStores.get(workspaceRef);
613 if (existing !== undefined) {
614 existing.users += 1;
615 return Effect.succeed(existing);
616 }
617 return Effect.tryPromise({
618 try: async () => {
619 const candidate = await sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef });
620 return isDisposableCursorLocalStore(candidate) ? candidate : undefined;
621 },
622 catch: (cause) => runnerError(cause, method),
623 }).pipe(
624 Effect.map((opened) => {
625 if (opened === undefined) return undefined;
626 const lease: WorkspaceStoreLease = {
627 // T3 persists its own event log and does not tail SDK run events.
628 store: Object.assign(opened, { persistRunEvents: false }),
629 users: 1,
630 };
631 workspaceStores.set(workspaceRef, lease);
632 return lease;
633 }),
634 );
635 }),
636 );
637 const releaseWorkspaceStore = (workspaceRef: string, lease: WorkspaceStoreLease) =>
638 workspaceStoreLock.withPermits(1)(
639 Effect.suspend(() => {
640 lease.users -= 1;
641 if (lease.users > 0) return Effect.void;
642 if (workspaceStores.get(workspaceRef) === lease) {
643 workspaceStores.delete(workspaceRef);
644 }
645 return Effect.tryPromise({
646 try: () => lease.store.dispose(),
647 catch: () => undefined,
648 }).pipe(Effect.ignore);
649 }),
650 );
651
652 return CursorAgentSdkRunner.of({
653 open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
654 const { Agent, createAgentPlatform } = yield* Effect.try({
655 try: sdk.load,
656 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
657 });
658 if (input.options.local?.sandboxOptions?.enabled === false) {
659 yield* primeCursorSandboxSupport(input.options);
660 }
661 const protocolLogger = protocolLoggerFor(input);
662 const log = (event: CursorAgentSdkProtocolLogEvent) =>
663 protocolLogger === undefined ? Effect.void : protocolLogger(event);
664
665 yield* log({
666 direction: "outgoing",
667 stage: "decoded",
668 payload: {
669 type: "agent.open",
670 operation: input.operation,
671 ...(input.agentId === undefined ? {} : { agentId: input.agentId }),
672 options: loggedCursorAgentOptions(input.options),
673 },
674 });
675
676 // Cursor uses cwd for both execution and store lookup; a moved thread keeps its original store.
677 const cwd =
678 typeof input.options.local?.cwd === "string"
679 ? input.options.local.cwd
680 : input.options.local?.cwd?.[0];
681 const storeCwd = input.storeCwd;
682 const storeWorkspace =
683 input.operation === "resume" && storeCwd !== undefined ? storeCwd : cwd;
684 const ownedStoreLease =
685 input.options.local?.store === undefined && storeWorkspace !== undefined
686 ? yield* acquireWorkspaceStore(storeWorkspace, `agent.${input.operation}`)
687 : undefined;
688 let storeReleased = false;
689 const disposeOwnedStore =
690 ownedStoreLease === undefined || storeWorkspace === undefined
691 ? Effect.void
692 : Effect.suspend(() => {
693 if (storeReleased) return Effect.void;
694 storeReleased = true;
695 return releaseWorkspaceStore(storeWorkspace, ownedStoreLease);
696 });
697 const effectiveStore =
698 ownedStoreLease === undefined ? input.options.local?.store : ownedStoreLease.store;
699 const effectiveOptions: AgentOptions =
700 effectiveStore === undefined || effectiveStore === input.options.local?.store
701 ? input.options
702 : {
703 ...input.options,
704 local: {
705 ...input.options.local,
706 store: effectiveStore,
707 },
708 };
709
710 const { storePlatform, agent } = yield* Effect.gen(function* () {
711 const resolvedStorePlatform =
712 input.operation === "resume" &&
713 storeCwd !== undefined &&
714 storeCwd !== input.options.local?.cwd
715 ? yield* Effect.tryPromise({
716 try: () =>
717 createAgentPlatform({
718 workspaceRef: storeCwd,
719 ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),
720 }),
721 catch: (cause) => runnerError(cause, "agent.resume"),
722 })
723 : undefined;
724 const openedAgent = yield* Effect.tryPromise({
725 try: () =>
726 input.operation === "create"
727 ? Agent.create(effectiveOptions)
728 : resolvedStorePlatform === undefined
729 ? Agent.resume(input.agentId!, effectiveOptions)
730 : resolvedStorePlatform.resumeAgent(input.agentId!, effectiveOptions),
731 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
732 });
733 yield* log({
734 direction: "incoming",
735 stage: "decoded",
736 payload: {
737 type: "agent.opened",
738 agentId: openedAgent.agentId,
739 },
740 });
741 return { storePlatform: resolvedStorePlatform, agent: openedAgent };
742 }).pipe(Effect.onExit((exit) => (Exit.isFailure(exit) ? disposeOwnedStore : Effect.void)));
743 let shellListener: ((event: CursorBackgroundShellEvent) => void) | undefined;
744
745 const runOptions = {
746 runtime: "local" as const,
747 ...(cwd === undefined ? {} : { cwd }),
748 ...(effectiveStore === undefined ? {} : { store: effectiveStore }),
749 };
750 let abandonedRunRecoveryAvailable = input.operation === "resume";
751 const storeView = async () =>
752 storePlatform ??
753 (await createAgentPlatform({
754 ...(cwd === undefined ? {} : { workspaceRef: cwd }),
755 ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),
756 }));
757
758 return {
759 agentId: agent.agentId,
760 send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) {
761 const context = yield* Effect.context();
762 const options = loggedCursorSendOptions(sendInput.options);
763 yield* sendInput.resume === true
764 ? log({
765 direction: "outgoing",
766 stage: "decoded",
767 payload: { type: "run.resume", options },
768 })
769 : log({
770 direction: "outgoing",
771 stage: "decoded",
772 payload: { type: "run.start", message: sendInput.message, options },
773 });
774
775 const onBackgroundShell = sendInput.onBackgroundShell;
776 if (onBackgroundShell !== undefined) {
777 let delivered = Promise.resolve();
778 shellListener = (event) => {
779 delivered = delivered
780 .then(() => Effect.runPromiseWith(context)(onBackgroundShell(event)))
781 .catch(() => undefined);
782 };
783 listenForBackgroundShells(agent.agentId, shellListener);
784 }
785
786 let callbacksReady = false;
787 const pendingUpdates: Array<InteractionUpdate> = [];
788 let callbackFailure: { readonly cause: unknown } | undefined;
789 let callbackChain = Promise.resolve();
790 let runId = "";
791 const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
792 callbackChain = callbackChain
793 .then(() => {
794 if (callbackFailure !== undefined) {
795 return;
796 }
797 return Effect.runPromiseWith(context)(
798 log({
799 direction: "incoming",
800 stage: "decoded",
801 payload: {
802 type: "interaction.update",
803 runId,
804 update,
805 },
806 }).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)),
807 );
808 })
809 .catch((cause) => {
810 callbackFailure ??= { cause };
811 });
812 return callbackChain;
813 };
814
815 const startSdkRun = () => {
816 if (sendInput.summarize === true) return agent.summarize();
817 const options: SendOptions = {
818 ...sendInput.options,
819 onDelta: async ({ update }) => {
820 if (!callbacksReady) {
821 pendingUpdates.push(update);
822 return;
823 }
824 await dispatchUpdate(update);
825 },
826 };
827 if (sendInput.resume !== true) return agent.send(sendInput.message, options);
828 if (agent.resume === undefined) {
829 throw new Error("This Cursor SDK agent cannot resume.");
830 }
831 return agent.resume(options);
832 };
833 const onStartupPhase = sendInput.onStartupPhase;
834 const startRun = () =>
835 Effect.tryPromise({
836 try: () =>
837 onStartupPhase === undefined
838 ? startSdkRun()
839 : listeningForStartupPhases((phase) => {
840 void Effect.runPromiseWith(context)(onStartupPhase(phase));
841 }, startSdkRun),
842 catch: (cause) =>
843 runnerError(cause, sendInput.resume === true ? "run.resume" : "run.start"),
844 });
845 const run = yield* startRun().pipe(
846 Effect.catchIf(
847 (error) => abandonedRunRecoveryAvailable && isActiveRunConflict(error.cause),
848 (error) =>
849 Effect.gen(function* () {
850 abandonedRunRecoveryAvailable = false;
851 // Local stores list runs oldest first, so the active run is on the
852 // last page and every page has to be read to reach it.
853 let activeRun: Run | undefined;
854 let cursor: string | undefined;
855 do {
856 const page = yield* Effect.tryPromise({
857 try: () =>
858 storePlatform === undefined
859 ? Agent.listRuns(agent.agentId, {
860 ...runOptions,
861 ...(cursor === undefined ? {} : { cursor }),
862 })
863 : storePlatform.listRuns(
864 agent.agentId,
865 cursor === undefined ? {} : { cursor },
866 ),
867 catch: (cause) => runnerError(cause, "agent.listRuns"),
868 });
869 activeRun =
870 page.items.findLast((candidate) => candidate.status === "running") ??
871 activeRun;
872 cursor = page.nextCursor;
873 } while (cursor !== undefined);
874 if (activeRun === undefined) {
875 return yield* error;
876 }
877 yield* log({
878 direction: "outgoing",
879 stage: "decoded",
880 payload: { type: "run.cancel", runId: activeRun.id },
881 });
882 yield* Effect.tryPromise({
883 try: () =>
884 storePlatform === undefined
885 ? Agent.cancelRun(activeRun.id, runOptions)
886 : storePlatform.cancelRun(activeRun.id),
887 catch: (cause) => runnerError(cause, "agent.cancelRun"),
888 });
889 return yield* startRun();
890 }),
891 ),
892 );
893 abandonedRunRecoveryAvailable = false;
894 runId = run.id;
895 yield* log({
896 direction: "incoming",
897 stage: "decoded",
898 payload: {
899 type: "run.started",
900 runId: run.id,
901 agentId: run.agentId,
902 },
903 });
904 callbacksReady = true;
905 for (const update of pendingUpdates) {
906 yield* Effect.tryPromise({
907 try: () => dispatchUpdate(update),
908 catch: (cause) => runnerError(cause, "run.onDelta"),
909 });
910 }
911
912 return {
913 runId: run.id,
914 agentId: run.agentId,
915 wait: Effect.tryPromise({
916 try: async () => {
917 const result = await run.wait();
918 await callbackChain;
919 if (callbackFailure !== undefined) {
920 throw callbackFailure.cause;
921 }
922 return result;
923 },
924 catch: (cause) => runnerError(cause, "run.wait"),
925 }).pipe(
926 Effect.tap((result) =>
927 log({
928 direction: "incoming",
929 stage: "decoded",
930 payload: {
931 type: "run.completed",
932 result,
933 },
934 }),
935 ),
936 ),
937 steer: Effect.fn("CursorAgentSdkRun.steer")((text: string) =>
938 log({
939 direction: "outgoing",
940 stage: "decoded",
941 payload: {
942 type: "run.steer",
943 runId: run.id,
944 text,
945 },
946 }).pipe(
947 Effect.andThen(
948 Effect.tryPromise({
949 try: () => run.steer?.(text) ?? Promise.resolve("revert_to_followup" as const),
950 catch: (cause) => runnerError(cause, "run.steer"),
951 }),
952 ),
953 Effect.tap((outcome) =>
954 log({
955 direction: "incoming",
956 stage: "decoded",
957 payload: {
958 type: "run.steered",
959 runId: run.id,
960 outcome,
961 },
962 }),
963 ),
964 ),
965 ),
966 cancel: log({
967 direction: "outgoing",
968 stage: "decoded",
969 payload: {
970 type: "run.cancel",
971 runId: run.id,
972 },
973 }).pipe(
974 Effect.andThen(
975 Effect.tryPromise({
976 try: async () => {
977 try {
978 await run.cancel();
979 } catch (cause) {
980 if (!isCursorCancellationError(cause)) {
981 throw cause;
982 }
983 }
984 },
985 catch: (cause) => runnerError(cause, "run.cancel"),
986 }),
987 ),
988 ),
989 } satisfies CursorAgentSdkRun;
990 }),
991 listMessages: log({
992 direction: "outgoing",
993 stage: "decoded",
994 payload: {
995 type: "agent.messages.list",
996 agentId: agent.agentId,
997 },
998 }).pipe(
999 Effect.andThen(
1000 Effect.tryPromise({
1001 try: () =>
1002 storePlatform === undefined
1003 ? Agent.messages.list(agent.agentId, {
1004 runtime: "local",
1005 ...(cwd === undefined ? {} : { cwd }),
1006 ...(effectiveStore === undefined ? {} : { store: effectiveStore }),
1007 })
1008 : storePlatform.getAgentMessages(agent.agentId),
1009 catch: (cause) => runnerError(cause, "agent.messages.list"),
1010 }),
1011 ),
1012 Effect.tap((messages) =>
1013 log({
1014 direction: "incoming",
1015 stage: "decoded",
1016 payload: {
1017 type: "agent.messages",
1018 agentId: agent.agentId,
1019 messages,
1020 },
1021 }),
1022 ),
1023 ),
1024 readContextUsage: Effect.tryPromise({
1025 try: async () => (await storeView()).checkpointStore.loadLatest(agent.agentId),
1026 catch: (cause) => runnerError(cause, "agent.checkpoint.load"),
1027 }).pipe(
1028 Effect.map((checkpoint) => {
1029 const usage = Option.getOrUndefined(decodeCursorCheckpoint(checkpoint))?.tokenDetails;
1030 // An unset protobuf message reads as zeros.
1031 return usage === undefined || usage.maxTokens === 0 ? undefined : usage;
1032 }),
1033 ),
1034 runCheckpointed: (runId) =>
1035 Effect.tryPromise({
1036 try: async () => {
1037 const { store } = await storeView();
1038 let run: RunRecord | null | undefined;
1039 if (runId !== undefined) {
1040 run = await store.getRun(agent.agentId, runId);
1041 } else {
1042 let cursor: string | undefined;
1043 do {
1044 const page = await store.listRuns(
1045 agent.agentId,
1046 cursor === undefined ? {} : { cursor },
1047 );
1048 for (const candidate of page.items) {
1049 if (!run || candidate.turnNumber >= run.turnNumber) run = candidate;
1050 }
1051 cursor = page.nextCursor;
1052 } while (cursor !== undefined);
1053 }
1054 const checkpoint = run?.latestCheckpointRef?.blobId;
1055 return checkpoint !== undefined && checkpoint !== run?.startCheckpointRef?.blobId;
1056 },
1057 catch: (cause) => runnerError(cause, "agent.run.get"),
1058 }),
1059 rewindAfterRun: (runId) =>
1060 log({
1061 direction: "outgoing",
1062 stage: "decoded",
1063 payload: { type: "agent.rewind", agentId: agent.agentId, afterRunId: runId },
1064 }).pipe(
1065 Effect.andThen(
1066 Effect.tryPromise({
1067 try: async () => {
1068 const { store, checkpointStore } = await storeView();
1069 const runs: Array<RunRecord> = [];
1070 let cursor: string | undefined;
1071 do {
1072 const page = await store.listRuns(
1073 agent.agentId,
1074 cursor === undefined ? {} : { cursor },
1075 );
1076 runs.push(...page.items);
1077 cursor = page.nextCursor;
1078 } while (cursor !== undefined);
1079 const kept = runs.find((candidate) => candidate.runId === runId);
1080 if (kept === undefined) {
1081 throw new Error(`Cursor agent ${agent.agentId} has no run ${runId}.`);
1082 }
1083 const unwound = runs
1084 .filter((candidate) => candidate.turnNumber > kept.turnNumber)
1085 .toSorted((a, b) => a.turnNumber - b.turnNumber)[0];
1086 if (unwound === undefined) return;
1087 const anchor = unwound.startCheckpointRef?.blobId;
1088 if (anchor === undefined) {
1089 throw new Error(`Cursor run ${unwound.runId} has no starting checkpoint.`);
1090 }
1091 const blobStore = await checkpointStore.getBlobStore(agent.agentId);
1092 const getBlob =
1093 typeof blobStore === "object" && blobStore !== null
1094 ? Reflect.get(blobStore, "getBlob")
1095 : undefined;
1096 if (typeof getBlob !== "function") {
1097 throw new Error("Cursor's checkpoint store cannot read blobs.");
1098 }
1099 const bytes: unknown = await getBlob.call(
1100 blobStore,
1101 undefined,
1102 Buffer.from(anchor, "hex"),
1103 );
1104 if (!(bytes instanceof Uint8Array)) {
1105 throw new Error(`Cursor checkpoint ${anchor} is missing.`);
1106 }
1107 // Checkpoints are content-addressed, so re-saving the anchor's bytes moves the
1108 // agent's head back to that exact root, like cursor-agent's latestRootBlobId reset.
1109 await checkpointStore.saveCheckpoint(agent.agentId, { toBinary: () => bytes });
1110 },
1111 catch: (cause) => runnerError(cause, "agent.rewind"),
1112 }),
1113 ),
1114 ),
1115 close: log({
1116 direction: "outgoing",
1117 stage: "decoded",
1118 payload: {
1119 type: "agent.close",
1120 agentId: agent.agentId,
1121 },
1122 }).pipe(
1123 Effect.andThen(
1124 Effect.try({
1125 try: () => {
1126 // A resumed session may already listen for this agent.
1127 if (backgroundShellListeners.get(agent.agentId) === shellListener) {
1128 backgroundShellListeners.delete(agent.agentId);
1129 }
1130 agent.close();
1131 },
1132 catch: (cause) => runnerError(cause, "agent.close"),
1133 }),
1134 ),
1135 Effect.ensuring(disposeOwnedStore),
1136 ),
1137 } satisfies CursorAgentSdkSession;
1138 }),
1139 assertComplete: Effect.void,
1140 });
1141});
1142
1143export const layer = Layer.effect(
1144 CursorAgentSdkRunner,
1145 Effect.gen(function* () {
1146 const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
1147 return yield* makeCursorAgentSdkRunner((input) =>
1148 makeCursorAgentSdkProtocolLogger({
1149 nativeEventLogger,
1150 threadId: input.threadId,
1151 providerSessionId: input.providerSessionId,
1152 }),
1153 );
1154 }),
1155);