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 {
13 NonNegativeInt,
14 type OrchestrationV2ProviderSession,
15 ProviderDriverKind,
16 type ThreadId,
17} from "@t3tools/contracts";
18import * as Context from "effect/Context";
19import * as Deferred from "effect/Deferred";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Ref from "effect/Ref";
24import * as Schema from "effect/Schema";
25
26import * as CursorSdk from "./CursorSdk.ts";
27import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
28
29export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const;
30export const CURSOR_PROVIDER = ProviderDriverKind.make("cursor");
31
32export class CursorAgentSdkRunnerError extends Schema.TaggedError<CursorAgentSdkRunnerError>()(
33 "CursorAgentSdkRunnerError",
34 {
35 method: Schema.String,
36 cause: Schema.Defect(),
37 },
38) {
39 override get message(): string {
40 return `Cursor Agent SDK ${this.method} failed.`;
41 }
42}
43
44export function cursorSdkFailureMessage(error: CursorAgentSdkRunnerError): string {
45 const reason = sdkErrorReason(error.cause);
46 return reason === undefined
47 ? error.message
48 : `Cursor Agent SDK ${error.method} failed: ${reason}`;
49}
50
51// The SDK maps backend details to codes like PRO_USER_USAGE_LIMIT or RATE_LIMITED, without a status.
52const CURSOR_USAGE_LIMIT_CODE =
53 /^(?:resource_exhausted|rate_limited(?:_changeable)?|\w*_usage_limit|\w*_rate_limit(?:_exceeded)?)$/i;
54
55export function isCursorUsageLimitError(cause: unknown): boolean {
56 const error = isCursorAgentSdkRunnerError(cause) ? cause.cause : cause;
57 if (typeof error !== "object" || error === null) return false;
58 const code = Reflect.get(error, "code");
59 return (
60 Reflect.get(error, "name") === "RateLimitError" ||
61 Reflect.get(error, "status") === 429 ||
62 (typeof code === "string" && CURSOR_USAGE_LIMIT_CODE.test(code))
63 );
64}
65
66const GENERIC_SDK_ERROR_CODES = new Set(["", "error", "unknown"]);
67
68function sdkErrorReason(cause: unknown): string | undefined {
69 if (!(cause instanceof Error)) return undefined;
70 const message = cause.message.trim();
71 if (message.length === 0) return undefined;
72 const code = Reflect.get(cause, "code");
73 const status = Reflect.get(cause, "status");
74 const details = [
75 ...(typeof code === "string" && !GENERIC_SDK_ERROR_CODES.has(code) && !message.includes(code)
76 ? [code]
77 : []),
78 ...(typeof status === "number" ? [`HTTP ${status}`] : []),
79 ];
80 return details.length === 0 ? message : `${message} (${details.join(", ")})`;
81}
82
83export const isCursorAgentSdkRunnerError = Schema.is(CursorAgentSdkRunnerError);
84
85export interface CursorAgentSdkOpenInput {
86 readonly operation: "create" | "resume";
87 readonly agentId?: string;
88 readonly storeCwd?: string;
89 readonly options: AgentOptions;
90 readonly threadId: ThreadId;
91 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
92}
93
94export interface CursorAgentSdkSendInput<Error> {
95 readonly message: string | SDKUserMessage;
96 readonly options?: Omit<SendOptions, "onDelta">;
97 readonly onDelta?: (update: InteractionUpdate) => Effect.Effect<void, Error>;
98 /** Runs `agent.summarize()` instead, which takes no message or options. */
99 readonly summarize?: boolean;
100 /** Runs `agent.resume()`: Cursor's ResumeAction from the latest checkpoint, with no message. */
101 readonly resume?: boolean;
102}
103
104export interface CursorAgentSdkRun {
105 readonly runId: string;
106 readonly agentId: string;
107 readonly wait: Effect.Effect<RunResult, CursorAgentSdkRunnerError>;
108 readonly cancel: Effect.Effect<void, CursorAgentSdkRunnerError>;
109 /** Absent on test doubles that never steer. The live runner always sets it. */
110 readonly steer?: (text: string) => Effect.Effect<SteerAckOutcome, CursorAgentSdkRunnerError>;
111}
112
113export interface CursorContextUsage {
114 readonly usedTokens: number;
115 readonly maxTokens: number;
116}
117
118// The SDK types a checkpoint as `unknown`; Cursor keeps the conversation's context fill on it.
119const CursorCheckpoint = Schema.Struct({
120 tokenDetails: Schema.Struct({ usedTokens: NonNegativeInt, maxTokens: NonNegativeInt }),
121});
122const decodeCursorCheckpoint = Schema.decodeUnknownOption(CursorCheckpoint);
123
124export interface CursorAgentSdkSession {
125 readonly agentId: string;
126 readonly send: <Error>(
127 input: CursorAgentSdkSendInput<Error>,
128 ) => Effect.Effect<CursorAgentSdkRun, CursorAgentSdkRunnerError>;
129 readonly listMessages: Effect.Effect<ReadonlyArray<AgentMessage>, CursorAgentSdkRunnerError>;
130 /** Context fill at the latest checkpoint, if Cursor saved one. Absent on test doubles. */
131 readonly readContextUsage?: Effect.Effect<
132 CursorContextUsage | undefined,
133 CursorAgentSdkRunnerError
134 >;
135 /**
136 * Whether a run (the latest when omitted) saved a checkpoint of its own. Cursor keeps a stopped
137 * run only from its first checkpoint on; before that the conversation lacks the run's request.
138 */
139 readonly runCheckpointed?: (runId?: string) => Effect.Effect<boolean, CursorAgentSdkRunnerError>;
140 /**
141 * Rewinds the conversation to just before the run after `runId`, as `cursor-agent` /rewind does.
142 * The open agent keeps its old conversation in memory, so reopen it before the next send.
143 */
144 readonly rewindAfterRun?: (runId: string) => Effect.Effect<void, CursorAgentSdkRunnerError>;
145 readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
146}
147
148export class CursorAgentSdkRunner extends Context.Service<
149 CursorAgentSdkRunner,
150 {
151 readonly open: (
152 input: CursorAgentSdkOpenInput,
153 ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;
154 readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;
155 }
156>()("@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner") {}
157
158export interface CursorAgentSdkLoggedAgentOptions {
159 readonly model?: AgentOptions["model"];
160 readonly hasName?: boolean;
161 readonly mode?: AgentOptions["mode"];
162 readonly local?: {
163 readonly hasCwd?: boolean;
164 readonly autoReview?: boolean;
165 readonly settingSources?: AgentOptions["local"] extends infer Local
166 ? Local extends { readonly settingSources?: infer Sources }
167 ? Sources
168 : never
169 : never;
170 readonly sandboxEnabled?: boolean;
171 readonly enableAgentRetries?: boolean;
172 readonly hasCustomTools?: boolean;
173 };
174 readonly agents?: ReadonlyArray<string>;
175}
176
177export interface CursorAgentSdkLoggedSendOptions {
178 readonly model?: SendOptions["model"];
179 readonly mode?: SendOptions["mode"];
180 readonly hasMcpServers?: boolean;
181 readonly mcpServerNames?: ReadonlyArray<string>;
182 readonly local?: {
183 readonly force?: boolean;
184 readonly hasCustomTools?: boolean;
185 };
186 readonly idempotencyKey?: string;
187}
188
189export type CursorAgentSdkProtocolLogEvent =
190 | {
191 readonly direction: "outgoing";
192 readonly stage: "decoded";
193 readonly payload: {
194 readonly type: "agent.open";
195 readonly operation: CursorAgentSdkOpenInput["operation"];
196 readonly agentId?: string;
197 readonly options: CursorAgentSdkLoggedAgentOptions;
198 };
199 }
200 | {
201 readonly direction: "incoming";
202 readonly stage: "decoded";
203 readonly payload: {
204 readonly type: "agent.opened";
205 readonly agentId: string;
206 };
207 }
208 | {
209 readonly direction: "outgoing";
210 readonly stage: "decoded";
211 readonly payload: {
212 readonly type: "run.start";
213 readonly message: string | SDKUserMessage;
214 readonly options: CursorAgentSdkLoggedSendOptions;
215 };
216 }
217 | {
218 readonly direction: "outgoing";
219 readonly stage: "decoded";
220 readonly payload: {
221 readonly type: "run.resume";
222 readonly options: CursorAgentSdkLoggedSendOptions;
223 };
224 }
225 | {
226 readonly direction: "incoming";
227 readonly stage: "decoded";
228 readonly payload: {
229 readonly type: "run.started";
230 readonly runId: string;
231 readonly agentId: string;
232 };
233 }
234 | {
235 readonly direction: "incoming";
236 readonly stage: "decoded";
237 readonly payload: {
238 readonly type: "interaction.update";
239 readonly runId: string;
240 readonly update: InteractionUpdate;
241 };
242 }
243 | {
244 readonly direction: "incoming";
245 readonly stage: "decoded";
246 readonly payload: {
247 readonly type: "run.completed";
248 readonly result: RunResult;
249 };
250 }
251 | {
252 readonly direction: "outgoing";
253 readonly stage: "decoded";
254 readonly payload: {
255 readonly type: "run.steer";
256 readonly runId: string;
257 readonly text: string;
258 };
259 }
260 | {
261 readonly direction: "incoming";
262 readonly stage: "decoded";
263 readonly payload: {
264 readonly type: "run.steered";
265 readonly runId: string;
266 readonly outcome: SteerAckOutcome;
267 };
268 }
269 | {
270 readonly direction: "outgoing";
271 readonly stage: "decoded";
272 readonly payload: {
273 readonly type: "run.cancel";
274 readonly runId: string;
275 };
276 }
277 | {
278 readonly direction: "outgoing";
279 readonly stage: "decoded";
280 readonly payload: {
281 readonly type: "agent.messages.list";
282 readonly agentId: string;
283 };
284 }
285 | {
286 readonly direction: "outgoing";
287 readonly stage: "decoded";
288 readonly payload: {
289 readonly type: "agent.rewind";
290 readonly agentId: string;
291 readonly afterRunId: string;
292 };
293 }
294 | {
295 readonly direction: "incoming";
296 readonly stage: "decoded";
297 readonly payload: {
298 readonly type: "agent.messages";
299 readonly agentId: string;
300 readonly messages: ReadonlyArray<AgentMessage>;
301 };
302 }
303 | {
304 readonly direction: "outgoing";
305 readonly stage: "decoded";
306 readonly payload: {
307 readonly type: "agent.close";
308 readonly agentId: string;
309 };
310 };
311
312export type CursorAgentSdkProtocolLogger = (
313 event: CursorAgentSdkProtocolLogEvent,
314) => Effect.Effect<void>;
315
316function runnerError(cause: unknown, method: string): CursorAgentSdkRunnerError {
317 return isCursorAgentSdkRunnerError(cause)
318 ? cause
319 : new CursorAgentSdkRunnerError({ method, cause });
320}
321
322function isActiveRunConflict(cause: unknown): boolean {
323 return cause instanceof Error && /already has active run/i.test(cause.message);
324}
325
326export function isCursorCancellationError(cause: unknown): boolean {
327 let current = cause;
328 const seen = new Set<object>();
329
330 while (typeof current === "object" && current !== null && !seen.has(current)) {
331 if (Reflect.get(current, "name") === "AbortError") {
332 return true;
333 }
334 seen.add(current);
335 current = Reflect.get(current, "cause");
336 }
337
338 return false;
339}
340
341export function loggedCursorAgentOptions(options: AgentOptions): CursorAgentSdkLoggedAgentOptions {
342 return {
343 ...(options.model === undefined ? {} : { model: options.model }),
344 ...(options.name === undefined ? {} : { hasName: true }),
345 ...(options.mode === undefined ? {} : { mode: options.mode }),
346 ...(options.local === undefined
347 ? {}
348 : {
349 local: {
350 ...(options.local.cwd === undefined ? {} : { hasCwd: true }),
351 ...(options.local.autoReview === undefined
352 ? {}
353 : { autoReview: options.local.autoReview }),
354 ...(options.local.settingSources === undefined
355 ? {}
356 : { settingSources: options.local.settingSources }),
357 ...(options.local.sandboxOptions === undefined
358 ? {}
359 : { sandboxEnabled: options.local.sandboxOptions.enabled }),
360 ...(options.local.enableAgentRetries === undefined
361 ? {}
362 : { enableAgentRetries: options.local.enableAgentRetries }),
363 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
364 },
365 }),
366 ...(options.agents === undefined ? {} : { agents: Object.keys(options.agents).toSorted() }),
367 };
368}
369
370export function loggedCursorSendOptions(
371 options: Omit<SendOptions, "onDelta"> | undefined,
372): CursorAgentSdkLoggedSendOptions {
373 if (options === undefined) {
374 return {};
375 }
376 const mcpServerNames =
377 options.mcpServers === undefined ? undefined : Object.keys(options.mcpServers).toSorted();
378 return {
379 ...(options.model === undefined ? {} : { model: options.model }),
380 ...(options.mode === undefined ? {} : { mode: options.mode }),
381 ...(mcpServerNames === undefined ? {} : { hasMcpServers: true, mcpServerNames }),
382 ...(options.local === undefined
383 ? {}
384 : {
385 local: {
386 ...(options.local.force === undefined ? {} : { force: options.local.force }),
387 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
388 },
389 }),
390 ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
391 };
392}
393
394function makeCursorAgentSdkProtocolLogger(input: {
395 readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;
396 readonly threadId: ThreadId;
397 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
398}): CursorAgentSdkProtocolLogger | undefined {
399 if (input.nativeEventLogger === undefined) {
400 return undefined;
401 }
402 const nativeEventLogger = input.nativeEventLogger;
403 return (event) =>
404 nativeEventLogger
405 .write(
406 {
407 provider: CURSOR_PROVIDER,
408 protocol: CURSOR_AGENT_SDK_PROTOCOL,
409 kind: "protocol",
410 providerSessionId: input.providerSessionId,
411 event,
412 },
413 input.threadId,
414 )
415 .pipe(Effect.ignore);
416}
417
418interface CursorShellStreamOutput {
419 readonly conversationId?: unknown;
420 readonly toolCallId?: unknown;
421 readonly event: {
422 readonly case: "stdout" | "stderr";
423 readonly value: { readonly data: unknown };
424 };
425}
426
427// The SDK reports shell-output-delta only for user-started shell commands, so
428// patches/@cursor__sdk@1.2.0.patch publishes agent shell output on this hook.
429const SHELL_STREAM_OUTPUT_HOOK = Symbol.for("@cursor/sdk.shellStreamOutput");
430const shellStreamListeners = new Set<(output: CursorShellStreamOutput) => void>();
431
432function subscribeShellStreamOutput(listener: (output: CursorShellStreamOutput) => void) {
433 const hooks = globalThis as Record<symbol, unknown>;
434 hooks[SHELL_STREAM_OUTPUT_HOOK] ??= (output: CursorShellStreamOutput) => {
435 for (const notify of shellStreamListeners) notify(output);
436 };
437 shellStreamListeners.add(listener);
438 return () => {
439 shellStreamListeners.delete(listener);
440 };
441}
442
443export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
444 protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
445) {
446 const sdk = yield* CursorSdk.CursorSdk;
447
448 // Prime with cursorsandbox before any Full access run; the SDK caches sandbox support per process.
449 const sandboxSupportPrimeStarted = yield* Ref.make(false);
450 const sandboxSupportPrimed = yield* Deferred.make<void>();
451 const primeCursorSandboxSupport = Effect.fn("CursorAgentSdkRunner.primeSandboxSupport")(
452 function* (options: AgentOptions) {
453 if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
454 return yield* Deferred.await(sandboxSupportPrimed);
455 }
456 yield* Effect.tryPromise({
457 try: async () => {
458 const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
459 const platform = await sdk
460 .load()
461 .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
462 const release = await platform.prewarmLocalWorkspace({
463 ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
464 local: {
465 ...(cwd === undefined ? {} : { cwd }),
466 settingSources: [],
467 sandboxOptions: { enabled: true },
468 },
469 });
470 await release();
471 },
472 catch: (cause) => runnerError(cause, "prewarmLocalWorkspace"),
473 }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
474 },
475 );
476
477 return CursorAgentSdkRunner.of({
478 open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
479 const { Agent, createAgentPlatform } = yield* Effect.try({
480 try: sdk.load,
481 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
482 });
483 if (input.options.local?.sandboxOptions?.enabled === false) {
484 yield* primeCursorSandboxSupport(input.options);
485 }
486 const protocolLogger = protocolLoggerFor(input);
487 const log = (event: CursorAgentSdkProtocolLogEvent) =>
488 protocolLogger === undefined ? Effect.void : protocolLogger(event);
489
490 yield* log({
491 direction: "outgoing",
492 stage: "decoded",
493 payload: {
494 type: "agent.open",
495 operation: input.operation,
496 ...(input.agentId === undefined ? {} : { agentId: input.agentId }),
497 options: loggedCursorAgentOptions(input.options),
498 },
499 });
500
501 // Cursor uses cwd for both execution and store lookup; a moved thread keeps its original store.
502 const storeCwd = input.storeCwd;
503 const storePlatform =
504 input.operation === "resume" &&
505 storeCwd !== undefined &&
506 storeCwd !== input.options.local?.cwd
507 ? yield* Effect.tryPromise({
508 try: () =>
509 createAgentPlatform({
510 workspaceRef: storeCwd,
511 ...(input.options.local?.store === undefined
512 ? {}
513 : { localStore: input.options.local.store }),
514 }),
515 catch: (cause) => runnerError(cause, "agent.resume"),
516 })
517 : undefined;
518 const agent = yield* Effect.tryPromise({
519 try: () =>
520 input.operation === "create"
521 ? Agent.create(input.options)
522 : storePlatform === undefined
523 ? Agent.resume(input.agentId!, input.options)
524 : storePlatform.resumeAgent(input.agentId!, input.options),
525 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
526 });
527
528 yield* log({
529 direction: "incoming",
530 stage: "decoded",
531 payload: {
532 type: "agent.opened",
533 agentId: agent.agentId,
534 },
535 });
536
537 const cwd =
538 typeof input.options.local?.cwd === "string"
539 ? input.options.local.cwd
540 : input.options.local?.cwd?.[0];
541 const runOptions = {
542 runtime: "local" as const,
543 ...(cwd === undefined ? {} : { cwd }),
544 ...(input.options.local?.store === undefined ? {} : { store: input.options.local.store }),
545 };
546 let abandonedRunRecoveryAvailable = input.operation === "resume";
547 const storeView = async () =>
548 storePlatform ??
549 (await createAgentPlatform({
550 ...(cwd === undefined ? {} : { workspaceRef: cwd }),
551 ...(input.options.local?.store === undefined
552 ? {}
553 : { localStore: input.options.local.store }),
554 }));
555
556 return {
557 agentId: agent.agentId,
558 send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) {
559 const context = yield* Effect.context();
560 const options = loggedCursorSendOptions(sendInput.options);
561 yield* sendInput.resume === true
562 ? log({
563 direction: "outgoing",
564 stage: "decoded",
565 payload: { type: "run.resume", options },
566 })
567 : log({
568 direction: "outgoing",
569 stage: "decoded",
570 payload: { type: "run.start", message: sendInput.message, options },
571 });
572
573 let callbacksReady = false;
574 const pendingUpdates: Array<InteractionUpdate> = [];
575 let callbackFailure: { readonly cause: unknown } | undefined;
576 let callbackChain = Promise.resolve();
577 let runId = "";
578 const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
579 callbackChain = callbackChain
580 .then(() => {
581 if (callbackFailure !== undefined) {
582 return;
583 }
584 return Effect.runPromiseWith(context)(
585 log({
586 direction: "incoming",
587 stage: "decoded",
588 payload: {
589 type: "interaction.update",
590 runId,
591 update,
592 },
593 }).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)),
594 );
595 })
596 .catch((cause) => {
597 callbackFailure ??= { cause };
598 });
599 return callbackChain;
600 };
601
602 const startRun = () =>
603 Effect.tryPromise({
604 try: () => {
605 if (sendInput.summarize === true) return agent.summarize();
606 const options: SendOptions = {
607 ...sendInput.options,
608 onDelta: async ({ update }) => {
609 if (!callbacksReady) {
610 pendingUpdates.push(update);
611 return;
612 }
613 await dispatchUpdate(update);
614 },
615 };
616 if (sendInput.resume !== true) return agent.send(sendInput.message, options);
617 if (agent.resume === undefined) {
618 throw new Error("This Cursor SDK agent cannot resume.");
619 }
620 return agent.resume(options);
621 },
622 catch: (cause) =>
623 runnerError(cause, sendInput.resume === true ? "run.resume" : "run.start"),
624 });
625 const run = yield* startRun().pipe(
626 Effect.catchIf(
627 (error) => abandonedRunRecoveryAvailable && isActiveRunConflict(error.cause),
628 (error) =>
629 Effect.gen(function* () {
630 abandonedRunRecoveryAvailable = false;
631 // Local stores list runs oldest first, so the active run is on the
632 // last page and every page has to be read to reach it.
633 let activeRun: Run | undefined;
634 let cursor: string | undefined;
635 do {
636 const page = yield* Effect.tryPromise({
637 try: () =>
638 storePlatform === undefined
639 ? Agent.listRuns(agent.agentId, {
640 ...runOptions,
641 ...(cursor === undefined ? {} : { cursor }),
642 })
643 : storePlatform.listRuns(
644 agent.agentId,
645 cursor === undefined ? {} : { cursor },
646 ),
647 catch: (cause) => runnerError(cause, "agent.listRuns"),
648 });
649 activeRun =
650 page.items.findLast((candidate) => candidate.status === "running") ??
651 activeRun;
652 cursor = page.nextCursor;
653 } while (cursor !== undefined);
654 if (activeRun === undefined) {
655 return yield* error;
656 }
657 yield* log({
658 direction: "outgoing",
659 stage: "decoded",
660 payload: { type: "run.cancel", runId: activeRun.id },
661 });
662 yield* Effect.tryPromise({
663 try: () =>
664 storePlatform === undefined
665 ? Agent.cancelRun(activeRun.id, runOptions)
666 : storePlatform.cancelRun(activeRun.id),
667 catch: (cause) => runnerError(cause, "agent.cancelRun"),
668 });
669 return yield* startRun();
670 }),
671 ),
672 );
673 abandonedRunRecoveryAvailable = false;
674 runId = run.id;
675 yield* log({
676 direction: "incoming",
677 stage: "decoded",
678 payload: {
679 type: "run.started",
680 runId: run.id,
681 agentId: run.agentId,
682 },
683 });
684 callbacksReady = true;
685 const unsubscribeShellOutput = subscribeShellStreamOutput((output) => {
686 if (output.conversationId !== agent.agentId || typeof output.toolCallId !== "string") {
687 return;
688 }
689 void dispatchUpdate({
690 type: "shell-output-delta",
691 event: { ...output.event, toolCallId: output.toolCallId },
692 });
693 });
694 for (const update of pendingUpdates) {
695 yield* Effect.tryPromise({
696 try: () => dispatchUpdate(update),
697 catch: (cause) => runnerError(cause, "run.onDelta"),
698 });
699 }
700
701 return {
702 runId: run.id,
703 agentId: run.agentId,
704 wait: Effect.tryPromise({
705 try: async () => {
706 const result = await run.wait();
707 await callbackChain;
708 if (callbackFailure !== undefined) {
709 throw callbackFailure.cause;
710 }
711 return result;
712 },
713 catch: (cause) => runnerError(cause, "run.wait"),
714 }).pipe(
715 Effect.ensuring(Effect.sync(unsubscribeShellOutput)),
716 Effect.tap((result) =>
717 log({
718 direction: "incoming",
719 stage: "decoded",
720 payload: {
721 type: "run.completed",
722 result,
723 },
724 }),
725 ),
726 ),
727 steer: Effect.fn("CursorAgentSdkRun.steer")((text: string) =>
728 log({
729 direction: "outgoing",
730 stage: "decoded",
731 payload: {
732 type: "run.steer",
733 runId: run.id,
734 text,
735 },
736 }).pipe(
737 Effect.andThen(
738 Effect.tryPromise({
739 try: () => run.steer?.(text) ?? Promise.resolve("revert_to_followup" as const),
740 catch: (cause) => runnerError(cause, "run.steer"),
741 }),
742 ),
743 Effect.tap((outcome) =>
744 log({
745 direction: "incoming",
746 stage: "decoded",
747 payload: {
748 type: "run.steered",
749 runId: run.id,
750 outcome,
751 },
752 }),
753 ),
754 ),
755 ),
756 cancel: log({
757 direction: "outgoing",
758 stage: "decoded",
759 payload: {
760 type: "run.cancel",
761 runId: run.id,
762 },
763 }).pipe(
764 Effect.andThen(
765 Effect.tryPromise({
766 try: async () => {
767 try {
768 await run.cancel();
769 } catch (cause) {
770 if (!isCursorCancellationError(cause)) {
771 throw cause;
772 }
773 }
774 },
775 catch: (cause) => runnerError(cause, "run.cancel"),
776 }),
777 ),
778 ),
779 } satisfies CursorAgentSdkRun;
780 }),
781 listMessages: log({
782 direction: "outgoing",
783 stage: "decoded",
784 payload: {
785 type: "agent.messages.list",
786 agentId: agent.agentId,
787 },
788 }).pipe(
789 Effect.andThen(
790 Effect.tryPromise({
791 try: () =>
792 storePlatform === undefined
793 ? Agent.messages.list(agent.agentId, {
794 runtime: "local",
795 ...(cwd === undefined ? {} : { cwd }),
796 ...(input.options.local?.store === undefined
797 ? {}
798 : { store: input.options.local.store }),
799 })
800 : storePlatform.getAgentMessages(agent.agentId),
801 catch: (cause) => runnerError(cause, "agent.messages.list"),
802 }),
803 ),
804 Effect.tap((messages) =>
805 log({
806 direction: "incoming",
807 stage: "decoded",
808 payload: {
809 type: "agent.messages",
810 agentId: agent.agentId,
811 messages,
812 },
813 }),
814 ),
815 ),
816 readContextUsage: Effect.tryPromise({
817 try: async () => (await storeView()).checkpointStore.loadLatest(agent.agentId),
818 catch: (cause) => runnerError(cause, "agent.checkpoint.load"),
819 }).pipe(
820 Effect.map((checkpoint) => {
821 const usage = Option.getOrUndefined(decodeCursorCheckpoint(checkpoint))?.tokenDetails;
822 // An unset protobuf message reads as zeros.
823 return usage === undefined || usage.maxTokens === 0 ? undefined : usage;
824 }),
825 ),
826 runCheckpointed: (runId) =>
827 Effect.tryPromise({
828 try: async () => {
829 const { store } = await storeView();
830 let run: RunRecord | null | undefined;
831 if (runId !== undefined) {
832 run = await store.getRun(agent.agentId, runId);
833 } else {
834 let cursor: string | undefined;
835 do {
836 const page = await store.listRuns(
837 agent.agentId,
838 cursor === undefined ? {} : { cursor },
839 );
840 for (const candidate of page.items) {
841 if (!run || candidate.turnNumber >= run.turnNumber) run = candidate;
842 }
843 cursor = page.nextCursor;
844 } while (cursor !== undefined);
845 }
846 const checkpoint = run?.latestCheckpointRef?.blobId;
847 return checkpoint !== undefined && checkpoint !== run?.startCheckpointRef?.blobId;
848 },
849 catch: (cause) => runnerError(cause, "agent.run.get"),
850 }),
851 rewindAfterRun: (runId) =>
852 log({
853 direction: "outgoing",
854 stage: "decoded",
855 payload: { type: "agent.rewind", agentId: agent.agentId, afterRunId: runId },
856 }).pipe(
857 Effect.andThen(
858 Effect.tryPromise({
859 try: async () => {
860 const { store, checkpointStore } = await storeView();
861 const runs: Array<RunRecord> = [];
862 let cursor: string | undefined;
863 do {
864 const page = await store.listRuns(
865 agent.agentId,
866 cursor === undefined ? {} : { cursor },
867 );
868 runs.push(...page.items);
869 cursor = page.nextCursor;
870 } while (cursor !== undefined);
871 const kept = runs.find((candidate) => candidate.runId === runId);
872 if (kept === undefined) {
873 throw new Error(`Cursor agent ${agent.agentId} has no run ${runId}.`);
874 }
875 const unwound = runs
876 .filter((candidate) => candidate.turnNumber > kept.turnNumber)
877 .toSorted((a, b) => a.turnNumber - b.turnNumber)[0];
878 if (unwound === undefined) return;
879 const anchor = unwound.startCheckpointRef?.blobId;
880 if (anchor === undefined) {
881 throw new Error(`Cursor run ${unwound.runId} has no starting checkpoint.`);
882 }
883 const blobStore = await checkpointStore.getBlobStore(agent.agentId);
884 const getBlob =
885 typeof blobStore === "object" && blobStore !== null
886 ? Reflect.get(blobStore, "getBlob")
887 : undefined;
888 if (typeof getBlob !== "function") {
889 throw new Error("Cursor's checkpoint store cannot read blobs.");
890 }
891 const bytes: unknown = await getBlob.call(
892 blobStore,
893 undefined,
894 Buffer.from(anchor, "hex"),
895 );
896 if (!(bytes instanceof Uint8Array)) {
897 throw new Error(`Cursor checkpoint ${anchor} is missing.`);
898 }
899 // Checkpoints are content-addressed, so re-saving the anchor's bytes moves the
900 // agent's head back to that exact root, like cursor-agent's latestRootBlobId reset.
901 await checkpointStore.saveCheckpoint(agent.agentId, { toBinary: () => bytes });
902 },
903 catch: (cause) => runnerError(cause, "agent.rewind"),
904 }),
905 ),
906 ),
907 close: log({
908 direction: "outgoing",
909 stage: "decoded",
910 payload: {
911 type: "agent.close",
912 agentId: agent.agentId,
913 },
914 }).pipe(
915 Effect.andThen(
916 Effect.try({
917 try: () => agent.close(),
918 catch: (cause) => runnerError(cause, "agent.close"),
919 }),
920 ),
921 ),
922 } satisfies CursorAgentSdkSession;
923 }),
924 assertComplete: Effect.void,
925 });
926});
927
928export const layer = Layer.effect(
929 CursorAgentSdkRunner,
930 Effect.gen(function* () {
931 const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
932 return yield* makeCursorAgentSdkRunner((input) =>
933 makeCursorAgentSdkProtocolLogger({
934 nativeEventLogger,
935 threadId: input.threadId,
936 providerSessionId: input.providerSessionId,
937 }),
938 );
939 }),
940);