Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CursorAgentSdk.ts

1,131 lines41.4 KB

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