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