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 readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
141}
142
143export class CursorAgentSdkRunner extends Context.Service<
144 CursorAgentSdkRunner,
145 {
146 readonly open: (
147 input: CursorAgentSdkOpenInput,
148 ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;
149 readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;
150 }
151>()("@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner") {}
152
153export interface CursorAgentSdkLoggedAgentOptions {
154 readonly model?: AgentOptions["model"];
155 readonly hasName?: boolean;
156 readonly mode?: AgentOptions["mode"];
157 readonly local?: {
158 readonly hasCwd?: boolean;
159 readonly autoReview?: boolean;
160 readonly settingSources?: AgentOptions["local"] extends infer Local
161 ? Local extends { readonly settingSources?: infer Sources }
162 ? Sources
163 : never
164 : never;
165 readonly sandboxEnabled?: boolean;
166 readonly enableAgentRetries?: boolean;
167 readonly hasCustomTools?: boolean;
168 };
169 readonly agents?: ReadonlyArray<string>;
170}
171
172export interface CursorAgentSdkLoggedSendOptions {
173 readonly model?: SendOptions["model"];
174 readonly mode?: SendOptions["mode"];
175 readonly hasMcpServers?: boolean;
176 readonly mcpServerNames?: ReadonlyArray<string>;
177 readonly local?: {
178 readonly force?: boolean;
179 readonly hasCustomTools?: boolean;
180 };
181 readonly idempotencyKey?: string;
182}
183
184export type CursorAgentSdkProtocolLogEvent =
185 | {
186 readonly direction: "outgoing";
187 readonly stage: "decoded";
188 readonly payload: {
189 readonly type: "agent.open";
190 readonly operation: CursorAgentSdkOpenInput["operation"];
191 readonly agentId?: string;
192 readonly options: CursorAgentSdkLoggedAgentOptions;
193 };
194 }
195 | {
196 readonly direction: "incoming";
197 readonly stage: "decoded";
198 readonly payload: {
199 readonly type: "agent.opened";
200 readonly agentId: string;
201 };
202 }
203 | {
204 readonly direction: "outgoing";
205 readonly stage: "decoded";
206 readonly payload: {
207 readonly type: "run.start";
208 readonly message: string | SDKUserMessage;
209 readonly options: CursorAgentSdkLoggedSendOptions;
210 };
211 }
212 | {
213 readonly direction: "outgoing";
214 readonly stage: "decoded";
215 readonly payload: {
216 readonly type: "run.resume";
217 readonly options: CursorAgentSdkLoggedSendOptions;
218 };
219 }
220 | {
221 readonly direction: "incoming";
222 readonly stage: "decoded";
223 readonly payload: {
224 readonly type: "run.started";
225 readonly runId: string;
226 readonly agentId: string;
227 };
228 }
229 | {
230 readonly direction: "incoming";
231 readonly stage: "decoded";
232 readonly payload: {
233 readonly type: "interaction.update";
234 readonly runId: string;
235 readonly update: InteractionUpdate;
236 };
237 }
238 | {
239 readonly direction: "incoming";
240 readonly stage: "decoded";
241 readonly payload: {
242 readonly type: "run.completed";
243 readonly result: RunResult;
244 };
245 }
246 | {
247 readonly direction: "outgoing";
248 readonly stage: "decoded";
249 readonly payload: {
250 readonly type: "run.steer";
251 readonly runId: string;
252 readonly text: string;
253 };
254 }
255 | {
256 readonly direction: "incoming";
257 readonly stage: "decoded";
258 readonly payload: {
259 readonly type: "run.steered";
260 readonly runId: string;
261 readonly outcome: SteerAckOutcome;
262 };
263 }
264 | {
265 readonly direction: "outgoing";
266 readonly stage: "decoded";
267 readonly payload: {
268 readonly type: "run.cancel";
269 readonly runId: string;
270 };
271 }
272 | {
273 readonly direction: "outgoing";
274 readonly stage: "decoded";
275 readonly payload: {
276 readonly type: "agent.messages.list";
277 readonly agentId: string;
278 };
279 }
280 | {
281 readonly direction: "incoming";
282 readonly stage: "decoded";
283 readonly payload: {
284 readonly type: "agent.messages";
285 readonly agentId: string;
286 readonly messages: ReadonlyArray<AgentMessage>;
287 };
288 }
289 | {
290 readonly direction: "outgoing";
291 readonly stage: "decoded";
292 readonly payload: {
293 readonly type: "agent.close";
294 readonly agentId: string;
295 };
296 };
297
298export type CursorAgentSdkProtocolLogger = (
299 event: CursorAgentSdkProtocolLogEvent,
300) => Effect.Effect<void>;
301
302function runnerError(cause: unknown, method: string): CursorAgentSdkRunnerError {
303 return isCursorAgentSdkRunnerError(cause)
304 ? cause
305 : new CursorAgentSdkRunnerError({ method, cause });
306}
307
308function isActiveRunConflict(cause: unknown): boolean {
309 return cause instanceof Error && /already has active run/i.test(cause.message);
310}
311
312export function isCursorCancellationError(cause: unknown): boolean {
313 let current = cause;
314 const seen = new Set<object>();
315
316 while (typeof current === "object" && current !== null && !seen.has(current)) {
317 if (Reflect.get(current, "name") === "AbortError") {
318 return true;
319 }
320 seen.add(current);
321 current = Reflect.get(current, "cause");
322 }
323
324 return false;
325}
326
327export function loggedCursorAgentOptions(options: AgentOptions): CursorAgentSdkLoggedAgentOptions {
328 return {
329 ...(options.model === undefined ? {} : { model: options.model }),
330 ...(options.name === undefined ? {} : { hasName: true }),
331 ...(options.mode === undefined ? {} : { mode: options.mode }),
332 ...(options.local === undefined
333 ? {}
334 : {
335 local: {
336 ...(options.local.cwd === undefined ? {} : { hasCwd: true }),
337 ...(options.local.autoReview === undefined
338 ? {}
339 : { autoReview: options.local.autoReview }),
340 ...(options.local.settingSources === undefined
341 ? {}
342 : { settingSources: options.local.settingSources }),
343 ...(options.local.sandboxOptions === undefined
344 ? {}
345 : { sandboxEnabled: options.local.sandboxOptions.enabled }),
346 ...(options.local.enableAgentRetries === undefined
347 ? {}
348 : { enableAgentRetries: options.local.enableAgentRetries }),
349 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
350 },
351 }),
352 ...(options.agents === undefined ? {} : { agents: Object.keys(options.agents).toSorted() }),
353 };
354}
355
356export function loggedCursorSendOptions(
357 options: Omit<SendOptions, "onDelta"> | undefined,
358): CursorAgentSdkLoggedSendOptions {
359 if (options === undefined) {
360 return {};
361 }
362 const mcpServerNames =
363 options.mcpServers === undefined ? undefined : Object.keys(options.mcpServers).toSorted();
364 return {
365 ...(options.model === undefined ? {} : { model: options.model }),
366 ...(options.mode === undefined ? {} : { mode: options.mode }),
367 ...(mcpServerNames === undefined ? {} : { hasMcpServers: true, mcpServerNames }),
368 ...(options.local === undefined
369 ? {}
370 : {
371 local: {
372 ...(options.local.force === undefined ? {} : { force: options.local.force }),
373 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
374 },
375 }),
376 ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
377 };
378}
379
380function makeCursorAgentSdkProtocolLogger(input: {
381 readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;
382 readonly threadId: ThreadId;
383 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
384}): CursorAgentSdkProtocolLogger | undefined {
385 if (input.nativeEventLogger === undefined) {
386 return undefined;
387 }
388 const nativeEventLogger = input.nativeEventLogger;
389 return (event) =>
390 nativeEventLogger
391 .write(
392 {
393 provider: CURSOR_PROVIDER,
394 protocol: CURSOR_AGENT_SDK_PROTOCOL,
395 kind: "protocol",
396 providerSessionId: input.providerSessionId,
397 event,
398 },
399 input.threadId,
400 )
401 .pipe(Effect.ignore);
402}
403
404interface CursorShellStreamOutput {
405 readonly conversationId?: unknown;
406 readonly toolCallId?: unknown;
407 readonly event: {
408 readonly case: "stdout" | "stderr";
409 readonly value: { readonly data: unknown };
410 };
411}
412
413// The SDK reports shell-output-delta only for user-started shell commands, so
414// patches/@cursor__sdk@1.2.0.patch publishes agent shell output on this hook.
415const SHELL_STREAM_OUTPUT_HOOK = Symbol.for("@cursor/sdk.shellStreamOutput");
416const shellStreamListeners = new Set<(output: CursorShellStreamOutput) => void>();
417
418function subscribeShellStreamOutput(listener: (output: CursorShellStreamOutput) => void) {
419 const hooks = globalThis as Record<symbol, unknown>;
420 hooks[SHELL_STREAM_OUTPUT_HOOK] ??= (output: CursorShellStreamOutput) => {
421 for (const notify of shellStreamListeners) notify(output);
422 };
423 shellStreamListeners.add(listener);
424 return () => {
425 shellStreamListeners.delete(listener);
426 };
427}
428
429export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
430 protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
431) {
432 const sdk = yield* CursorSdk.CursorSdk;
433
434 // Prime with cursorsandbox before any Full access run; the SDK caches sandbox support per process.
435 const sandboxSupportPrimeStarted = yield* Ref.make(false);
436 const sandboxSupportPrimed = yield* Deferred.make<void>();
437 const primeCursorSandboxSupport = Effect.fn("CursorAgentSdkRunner.primeSandboxSupport")(
438 function* (options: AgentOptions) {
439 if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
440 return yield* Deferred.await(sandboxSupportPrimed);
441 }
442 yield* Effect.tryPromise({
443 try: async () => {
444 const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
445 const platform = await sdk
446 .load()
447 .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
448 const release = await platform.prewarmLocalWorkspace({
449 ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
450 local: {
451 ...(cwd === undefined ? {} : { cwd }),
452 settingSources: [],
453 sandboxOptions: { enabled: true },
454 },
455 });
456 await release();
457 },
458 catch: (cause) => runnerError(cause, "prewarmLocalWorkspace"),
459 }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
460 },
461 );
462
463 return CursorAgentSdkRunner.of({
464 open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
465 const { Agent, createAgentPlatform } = yield* Effect.try({
466 try: sdk.load,
467 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
468 });
469 if (input.options.local?.sandboxOptions?.enabled === false) {
470 yield* primeCursorSandboxSupport(input.options);
471 }
472 const protocolLogger = protocolLoggerFor(input);
473 const log = (event: CursorAgentSdkProtocolLogEvent) =>
474 protocolLogger === undefined ? Effect.void : protocolLogger(event);
475
476 yield* log({
477 direction: "outgoing",
478 stage: "decoded",
479 payload: {
480 type: "agent.open",
481 operation: input.operation,
482 ...(input.agentId === undefined ? {} : { agentId: input.agentId }),
483 options: loggedCursorAgentOptions(input.options),
484 },
485 });
486
487 // Cursor uses cwd for both execution and store lookup; a moved thread keeps its original store.
488 const storeCwd = input.storeCwd;
489 const storePlatform =
490 input.operation === "resume" &&
491 storeCwd !== undefined &&
492 storeCwd !== input.options.local?.cwd
493 ? yield* Effect.tryPromise({
494 try: () =>
495 createAgentPlatform({
496 workspaceRef: storeCwd,
497 ...(input.options.local?.store === undefined
498 ? {}
499 : { localStore: input.options.local.store }),
500 }),
501 catch: (cause) => runnerError(cause, "agent.resume"),
502 })
503 : undefined;
504 const agent = yield* Effect.tryPromise({
505 try: () =>
506 input.operation === "create"
507 ? Agent.create(input.options)
508 : storePlatform === undefined
509 ? Agent.resume(input.agentId!, input.options)
510 : storePlatform.resumeAgent(input.agentId!, input.options),
511 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
512 });
513
514 yield* log({
515 direction: "incoming",
516 stage: "decoded",
517 payload: {
518 type: "agent.opened",
519 agentId: agent.agentId,
520 },
521 });
522
523 const cwd =
524 typeof input.options.local?.cwd === "string"
525 ? input.options.local.cwd
526 : input.options.local?.cwd?.[0];
527 const runOptions = {
528 runtime: "local" as const,
529 ...(cwd === undefined ? {} : { cwd }),
530 ...(input.options.local?.store === undefined ? {} : { store: input.options.local.store }),
531 };
532 let abandonedRunRecoveryAvailable = input.operation === "resume";
533 const storeView = async () =>
534 storePlatform ??
535 (await createAgentPlatform({
536 ...(cwd === undefined ? {} : { workspaceRef: cwd }),
537 ...(input.options.local?.store === undefined
538 ? {}
539 : { localStore: input.options.local.store }),
540 }));
541
542 return {
543 agentId: agent.agentId,
544 send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) {
545 const context = yield* Effect.context();
546 const options = loggedCursorSendOptions(sendInput.options);
547 yield* sendInput.resume === true
548 ? log({
549 direction: "outgoing",
550 stage: "decoded",
551 payload: { type: "run.resume", options },
552 })
553 : log({
554 direction: "outgoing",
555 stage: "decoded",
556 payload: { type: "run.start", message: sendInput.message, options },
557 });
558
559 let callbacksReady = false;
560 const pendingUpdates: Array<InteractionUpdate> = [];
561 let callbackFailure: { readonly cause: unknown } | undefined;
562 let callbackChain = Promise.resolve();
563 let runId = "";
564 const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
565 callbackChain = callbackChain
566 .then(() => {
567 if (callbackFailure !== undefined) {
568 return;
569 }
570 return Effect.runPromiseWith(context)(
571 log({
572 direction: "incoming",
573 stage: "decoded",
574 payload: {
575 type: "interaction.update",
576 runId,
577 update,
578 },
579 }).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)),
580 );
581 })
582 .catch((cause) => {
583 callbackFailure ??= { cause };
584 });
585 return callbackChain;
586 };
587
588 const startRun = () =>
589 Effect.tryPromise({
590 try: () => {
591 if (sendInput.summarize === true) return agent.summarize();
592 const options: SendOptions = {
593 ...sendInput.options,
594 onDelta: async ({ update }) => {
595 if (!callbacksReady) {
596 pendingUpdates.push(update);
597 return;
598 }
599 await dispatchUpdate(update);
600 },
601 };
602 if (sendInput.resume !== true) return agent.send(sendInput.message, options);
603 if (agent.resume === undefined) {
604 throw new Error("This Cursor SDK agent cannot resume.");
605 }
606 return agent.resume(options);
607 },
608 catch: (cause) =>
609 runnerError(cause, sendInput.resume === true ? "run.resume" : "run.start"),
610 });
611 const run = yield* startRun().pipe(
612 Effect.catchIf(
613 (error) => abandonedRunRecoveryAvailable && isActiveRunConflict(error.cause),
614 (error) =>
615 Effect.gen(function* () {
616 abandonedRunRecoveryAvailable = false;
617 // Local stores list runs oldest first, so the active run is on the
618 // last page and every page has to be read to reach it.
619 let activeRun: Run | undefined;
620 let cursor: string | undefined;
621 do {
622 const page = yield* Effect.tryPromise({
623 try: () =>
624 storePlatform === undefined
625 ? Agent.listRuns(agent.agentId, {
626 ...runOptions,
627 ...(cursor === undefined ? {} : { cursor }),
628 })
629 : storePlatform.listRuns(
630 agent.agentId,
631 cursor === undefined ? {} : { cursor },
632 ),
633 catch: (cause) => runnerError(cause, "agent.listRuns"),
634 });
635 activeRun =
636 page.items.findLast((candidate) => candidate.status === "running") ??
637 activeRun;
638 cursor = page.nextCursor;
639 } while (cursor !== undefined);
640 if (activeRun === undefined) {
641 return yield* error;
642 }
643 yield* log({
644 direction: "outgoing",
645 stage: "decoded",
646 payload: { type: "run.cancel", runId: activeRun.id },
647 });
648 yield* Effect.tryPromise({
649 try: () =>
650 storePlatform === undefined
651 ? Agent.cancelRun(activeRun.id, runOptions)
652 : storePlatform.cancelRun(activeRun.id),
653 catch: (cause) => runnerError(cause, "agent.cancelRun"),
654 });
655 return yield* startRun();
656 }),
657 ),
658 );
659 abandonedRunRecoveryAvailable = false;
660 runId = run.id;
661 yield* log({
662 direction: "incoming",
663 stage: "decoded",
664 payload: {
665 type: "run.started",
666 runId: run.id,
667 agentId: run.agentId,
668 },
669 });
670 callbacksReady = true;
671 const unsubscribeShellOutput = subscribeShellStreamOutput((output) => {
672 if (output.conversationId !== agent.agentId || typeof output.toolCallId !== "string") {
673 return;
674 }
675 void dispatchUpdate({
676 type: "shell-output-delta",
677 event: { ...output.event, toolCallId: output.toolCallId },
678 });
679 });
680 for (const update of pendingUpdates) {
681 yield* Effect.tryPromise({
682 try: () => dispatchUpdate(update),
683 catch: (cause) => runnerError(cause, "run.onDelta"),
684 });
685 }
686
687 return {
688 runId: run.id,
689 agentId: run.agentId,
690 wait: Effect.tryPromise({
691 try: async () => {
692 const result = await run.wait();
693 await callbackChain;
694 if (callbackFailure !== undefined) {
695 throw callbackFailure.cause;
696 }
697 return result;
698 },
699 catch: (cause) => runnerError(cause, "run.wait"),
700 }).pipe(
701 Effect.ensuring(Effect.sync(unsubscribeShellOutput)),
702 Effect.tap((result) =>
703 log({
704 direction: "incoming",
705 stage: "decoded",
706 payload: {
707 type: "run.completed",
708 result,
709 },
710 }),
711 ),
712 ),
713 steer: Effect.fn("CursorAgentSdkRun.steer")((text: string) =>
714 log({
715 direction: "outgoing",
716 stage: "decoded",
717 payload: {
718 type: "run.steer",
719 runId: run.id,
720 text,
721 },
722 }).pipe(
723 Effect.andThen(
724 Effect.tryPromise({
725 try: () => run.steer?.(text) ?? Promise.resolve("revert_to_followup" as const),
726 catch: (cause) => runnerError(cause, "run.steer"),
727 }),
728 ),
729 Effect.tap((outcome) =>
730 log({
731 direction: "incoming",
732 stage: "decoded",
733 payload: {
734 type: "run.steered",
735 runId: run.id,
736 outcome,
737 },
738 }),
739 ),
740 ),
741 ),
742 cancel: log({
743 direction: "outgoing",
744 stage: "decoded",
745 payload: {
746 type: "run.cancel",
747 runId: run.id,
748 },
749 }).pipe(
750 Effect.andThen(
751 Effect.tryPromise({
752 try: async () => {
753 try {
754 await run.cancel();
755 } catch (cause) {
756 if (!isCursorCancellationError(cause)) {
757 throw cause;
758 }
759 }
760 },
761 catch: (cause) => runnerError(cause, "run.cancel"),
762 }),
763 ),
764 ),
765 } satisfies CursorAgentSdkRun;
766 }),
767 listMessages: log({
768 direction: "outgoing",
769 stage: "decoded",
770 payload: {
771 type: "agent.messages.list",
772 agentId: agent.agentId,
773 },
774 }).pipe(
775 Effect.andThen(
776 Effect.tryPromise({
777 try: () =>
778 storePlatform === undefined
779 ? Agent.messages.list(agent.agentId, {
780 runtime: "local",
781 ...(cwd === undefined ? {} : { cwd }),
782 ...(input.options.local?.store === undefined
783 ? {}
784 : { store: input.options.local.store }),
785 })
786 : storePlatform.getAgentMessages(agent.agentId),
787 catch: (cause) => runnerError(cause, "agent.messages.list"),
788 }),
789 ),
790 Effect.tap((messages) =>
791 log({
792 direction: "incoming",
793 stage: "decoded",
794 payload: {
795 type: "agent.messages",
796 agentId: agent.agentId,
797 messages,
798 },
799 }),
800 ),
801 ),
802 readContextUsage: Effect.tryPromise({
803 try: async () => (await storeView()).checkpointStore.loadLatest(agent.agentId),
804 catch: (cause) => runnerError(cause, "agent.checkpoint.load"),
805 }).pipe(
806 Effect.map((checkpoint) => {
807 const usage = Option.getOrUndefined(decodeCursorCheckpoint(checkpoint))?.tokenDetails;
808 // An unset protobuf message reads as zeros.
809 return usage === undefined || usage.maxTokens === 0 ? undefined : usage;
810 }),
811 ),
812 runCheckpointed: (runId) =>
813 Effect.tryPromise({
814 try: async () => {
815 const { store } = await storeView();
816 let run: RunRecord | null | undefined;
817 if (runId !== undefined) {
818 run = await store.getRun(agent.agentId, runId);
819 } else {
820 let cursor: string | undefined;
821 do {
822 const page = await store.listRuns(
823 agent.agentId,
824 cursor === undefined ? {} : { cursor },
825 );
826 for (const candidate of page.items) {
827 if (!run || candidate.turnNumber >= run.turnNumber) run = candidate;
828 }
829 cursor = page.nextCursor;
830 } while (cursor !== undefined);
831 }
832 const checkpoint = run?.latestCheckpointRef?.blobId;
833 return checkpoint !== undefined && checkpoint !== run?.startCheckpointRef?.blobId;
834 },
835 catch: (cause) => runnerError(cause, "agent.run.get"),
836 }),
837 close: log({
838 direction: "outgoing",
839 stage: "decoded",
840 payload: {
841 type: "agent.close",
842 agentId: agent.agentId,
843 },
844 }).pipe(
845 Effect.andThen(
846 Effect.try({
847 try: () => agent.close(),
848 catch: (cause) => runnerError(cause, "agent.close"),
849 }),
850 ),
851 ),
852 } satisfies CursorAgentSdkSession;
853 }),
854 assertComplete: Effect.void,
855 });
856});
857
858export const layer = Layer.effect(
859 CursorAgentSdkRunner,
860 Effect.gen(function* () {
861 const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
862 return yield* makeCursorAgentSdkRunner((input) =>
863 makeCursorAgentSdkProtocolLogger({
864 nativeEventLogger,
865 threadId: input.threadId,
866 providerSessionId: input.providerSessionId,
867 }),
868 );
869 }),
870);