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

CursorAgentSdk.ts

654 lines21.6 KB

1import type {
2 AgentMessage,
3 AgentOptions,
4 InteractionUpdate,
5 RunResult,
6 SDKUserMessage,
7 SendOptions,
8} from "@cursor/sdk";
9import {
10 type OrchestrationV2ProviderSession,
11 ProviderDriverKind,
12 type ThreadId,
13} from "@t3tools/contracts";
14import * as Context from "effect/Context";
15import * as Deferred from "effect/Deferred";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Ref from "effect/Ref";
19import * as Schema from "effect/Schema";
20​
21import * as CursorSdk from "./CursorSdk.ts";
22import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
23​
24export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const;
25export const CURSOR_PROVIDER = ProviderDriverKind.make("cursor");
26​
27export class CursorAgentSdkRunnerError extends Schema.TaggedError<CursorAgentSdkRunnerError>()(
28 "CursorAgentSdkRunnerError",
29 {
30 method: Schema.String,
31 cause: Schema.Defect(),
32 },
33) {
34 override get message(): string {
35 return `Cursor Agent SDK ${this.method} failed.`;
36 }
38​
39export function cursorSdkFailureMessage(error: CursorAgentSdkRunnerError): string {
40 const reason = sdkErrorReason(error.cause);
41 return reason === undefined
42 ? error.message
43 : `Cursor Agent SDK ${error.method} failed: ${reason}`;
45​
46// The SDK maps backend details to codes like PRO_USER_USAGE_LIMIT or RATE_LIMITED, without a status.
47const CURSOR_USAGE_LIMIT_CODE =
48 /^(?:resource_exhausted|rate_limited(?:_changeable)?|\w*_usage_limit|\w*_rate_limit(?:_exceeded)?)$/i;
49​
50export function isCursorUsageLimitError(cause: unknown): boolean {
51 const error = isCursorAgentSdkRunnerError(cause) ? cause.cause : cause;
52 if (typeof error !== "object" || error === null) return false;
53 const code = Reflect.get(error, "code");
54 return (
55 Reflect.get(error, "name") === "RateLimitError" ||
56 Reflect.get(error, "status") === 429 ||
57 (typeof code === "string" && CURSOR_USAGE_LIMIT_CODE.test(code))
58 );
60​
61const GENERIC_SDK_ERROR_CODES = new Set(["", "error", "unknown"]);
62​
63function sdkErrorReason(cause: unknown): string | undefined {
64 if (!(cause instanceof Error)) return undefined;
65 const message = cause.message.trim();
66 if (message.length === 0) return undefined;
67 const code = Reflect.get(cause, "code");
68 const status = Reflect.get(cause, "status");
69 const details = [
70 ...(typeof code === "string" && !GENERIC_SDK_ERROR_CODES.has(code) && !message.includes(code)
71 ? [code]
72 : []),
73 ...(typeof status === "number" ? [`HTTP ${status}`] : []),
74 ];
75 return details.length === 0 ? message : `${message} (${details.join(", ")})`;
77​
78export const isCursorAgentSdkRunnerError = Schema.is(CursorAgentSdkRunnerError);
79​
80export interface CursorAgentSdkOpenInput {
81 readonly operation: "create" | "resume";
82 readonly agentId?: string;
83 readonly options: AgentOptions;
84 readonly threadId: ThreadId;
85 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
87​
88export interface CursorAgentSdkSendInput<Error> {
89 readonly message: string | SDKUserMessage;
90 readonly options?: Omit<SendOptions, "onDelta">;
91 readonly onDelta?: (update: InteractionUpdate) => Effect.Effect<void, Error>;
92 /** Runs `agent.summarize()` instead, which takes no message or options. */
93 readonly summarize?: boolean;
95​
96export interface CursorAgentSdkRun {
97 readonly runId: string;
98 readonly agentId: string;
99 readonly wait: Effect.Effect<RunResult, CursorAgentSdkRunnerError>;
100 readonly cancel: Effect.Effect<void, CursorAgentSdkRunnerError>;
102​
103export interface CursorAgentSdkSession {
104 readonly agentId: string;
105 readonly send: <Error>(
106 input: CursorAgentSdkSendInput<Error>,
107 ) => Effect.Effect<CursorAgentSdkRun, CursorAgentSdkRunnerError>;
108 readonly listMessages: Effect.Effect<ReadonlyArray<AgentMessage>, CursorAgentSdkRunnerError>;
109 readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
111​
112export class CursorAgentSdkRunner extends Context.Service<
113 CursorAgentSdkRunner,
114 {
115 readonly open: (
116 input: CursorAgentSdkOpenInput,
117 ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;
118 readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;
119 }
120>()("@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner") {}
121​
122export interface CursorAgentSdkLoggedAgentOptions {
123 readonly model?: AgentOptions["model"];
124 readonly hasName?: boolean;
125 readonly mode?: AgentOptions["mode"];
126 readonly local?: {
127 readonly hasCwd?: boolean;
128 readonly autoReview?: boolean;
129 readonly settingSources?: AgentOptions["local"] extends infer Local
130 ? Local extends { readonly settingSources?: infer Sources }
131 ? Sources
132 : never
133 : never;
134 readonly sandboxEnabled?: boolean;
135 readonly enableAgentRetries?: boolean;
136 readonly hasCustomTools?: boolean;
137 };
138 readonly agents?: ReadonlyArray<string>;
140​
141export interface CursorAgentSdkLoggedSendOptions {
142 readonly model?: SendOptions["model"];
143 readonly mode?: SendOptions["mode"];
144 readonly hasMcpServers?: boolean;
145 readonly mcpServerNames?: ReadonlyArray<string>;
146 readonly local?: {
147 readonly force?: boolean;
148 readonly hasCustomTools?: boolean;
149 };
150 readonly idempotencyKey?: string;
152​
153export type CursorAgentSdkProtocolLogEvent =
154 | {
155 readonly direction: "outgoing";
156 readonly stage: "decoded";
157 readonly payload: {
158 readonly type: "agent.open";
159 readonly operation: CursorAgentSdkOpenInput["operation"];
160 readonly agentId?: string;
161 readonly options: CursorAgentSdkLoggedAgentOptions;
162 };
163 }
164 | {
165 readonly direction: "incoming";
166 readonly stage: "decoded";
167 readonly payload: {
168 readonly type: "agent.opened";
169 readonly agentId: string;
170 };
171 }
172 | {
173 readonly direction: "outgoing";
174 readonly stage: "decoded";
175 readonly payload: {
176 readonly type: "run.start";
177 readonly message: string | SDKUserMessage;
178 readonly options: CursorAgentSdkLoggedSendOptions;
179 };
180 }
181 | {
182 readonly direction: "incoming";
183 readonly stage: "decoded";
184 readonly payload: {
185 readonly type: "run.started";
186 readonly runId: string;
187 readonly agentId: string;
188 };
189 }
190 | {
191 readonly direction: "incoming";
192 readonly stage: "decoded";
193 readonly payload: {
194 readonly type: "interaction.update";
195 readonly runId: string;
196 readonly update: InteractionUpdate;
197 };
198 }
199 | {
200 readonly direction: "incoming";
201 readonly stage: "decoded";
202 readonly payload: {
203 readonly type: "run.completed";
204 readonly result: RunResult;
205 };
206 }
207 | {
208 readonly direction: "outgoing";
209 readonly stage: "decoded";
210 readonly payload: {
211 readonly type: "run.cancel";
212 readonly runId: string;
213 };
214 }
215 | {
216 readonly direction: "outgoing";
217 readonly stage: "decoded";
218 readonly payload: {
219 readonly type: "agent.messages.list";
220 readonly agentId: string;
221 };
222 }
223 | {
224 readonly direction: "incoming";
225 readonly stage: "decoded";
226 readonly payload: {
227 readonly type: "agent.messages";
228 readonly agentId: string;
229 readonly messages: ReadonlyArray<AgentMessage>;
230 };
231 }
232 | {
233 readonly direction: "outgoing";
234 readonly stage: "decoded";
235 readonly payload: {
236 readonly type: "agent.close";
237 readonly agentId: string;
238 };
239 };
240​
241export type CursorAgentSdkProtocolLogger = (
242 event: CursorAgentSdkProtocolLogEvent,
243) => Effect.Effect<void>;
244​
245function runnerError(cause: unknown, method: string): CursorAgentSdkRunnerError {
246 return isCursorAgentSdkRunnerError(cause)
247 ? cause
248 : new CursorAgentSdkRunnerError({ method, cause });
250​
251function isActiveRunConflict(cause: unknown): boolean {
252 return cause instanceof Error && /already has active run/i.test(cause.message);
254​
255export function isCursorCancellationError(cause: unknown): boolean {
256 let current = cause;
257 const seen = new Set<object>();
258​
259 while (typeof current === "object" && current !== null && !seen.has(current)) {
260 if (Reflect.get(current, "name") === "AbortError") {
261 return true;
262 }
263 seen.add(current);
264 current = Reflect.get(current, "cause");
265 }
266​
267 return false;
269​
270export function loggedCursorAgentOptions(options: AgentOptions): CursorAgentSdkLoggedAgentOptions {
271 return {
272 ...(options.model === undefined ? {} : { model: options.model }),
273 ...(options.name === undefined ? {} : { hasName: true }),
274 ...(options.mode === undefined ? {} : { mode: options.mode }),
275 ...(options.local === undefined
276 ? {}
277 : {
278 local: {
279 ...(options.local.cwd === undefined ? {} : { hasCwd: true }),
280 ...(options.local.autoReview === undefined
281 ? {}
282 : { autoReview: options.local.autoReview }),
283 ...(options.local.settingSources === undefined
284 ? {}
285 : { settingSources: options.local.settingSources }),
286 ...(options.local.sandboxOptions === undefined
287 ? {}
288 : { sandboxEnabled: options.local.sandboxOptions.enabled }),
289 ...(options.local.enableAgentRetries === undefined
290 ? {}
291 : { enableAgentRetries: options.local.enableAgentRetries }),
292 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
293 },
294 }),
295 ...(options.agents === undefined ? {} : { agents: Object.keys(options.agents).toSorted() }),
296 };
298​
299export function loggedCursorSendOptions(
300 options: Omit<SendOptions, "onDelta"> | undefined,
301): CursorAgentSdkLoggedSendOptions {
302 if (options === undefined) {
303 return {};
304 }
305 const mcpServerNames =
306 options.mcpServers === undefined ? undefined : Object.keys(options.mcpServers).toSorted();
307 return {
308 ...(options.model === undefined ? {} : { model: options.model }),
309 ...(options.mode === undefined ? {} : { mode: options.mode }),
310 ...(mcpServerNames === undefined ? {} : { hasMcpServers: true, mcpServerNames }),
311 ...(options.local === undefined
312 ? {}
313 : {
314 local: {
315 ...(options.local.force === undefined ? {} : { force: options.local.force }),
316 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
317 },
318 }),
319 ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
320 };
322​
323function makeCursorAgentSdkProtocolLogger(input: {
324 readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;
325 readonly threadId: ThreadId;
326 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
327}): CursorAgentSdkProtocolLogger | undefined {
328 if (input.nativeEventLogger === undefined) {
329 return undefined;
330 }
331 const nativeEventLogger = input.nativeEventLogger;
332 return (event) =>
333 nativeEventLogger
334 .write(
335 {
336 provider: CURSOR_PROVIDER,
337 protocol: CURSOR_AGENT_SDK_PROTOCOL,
338 kind: "protocol",
339 providerSessionId: input.providerSessionId,
340 event,
341 },
342 input.threadId,
343 )
344 .pipe(Effect.ignore);
346​
347export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
348 protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
349) {
350 const sdk = yield* CursorSdk.CursorSdk;
351​
352 // Prime with cursorsandbox before any Full access run; the SDK caches sandbox support per process.
353 const sandboxSupportPrimeStarted = yield* Ref.make(false);
354 const sandboxSupportPrimed = yield* Deferred.make<void>();
355 const primeCursorSandboxSupport = Effect.fn("CursorAgentSdkRunner.primeSandboxSupport")(
356 function* (options: AgentOptions) {
357 if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
358 return yield* Deferred.await(sandboxSupportPrimed);
359 }
360 yield* Effect.tryPromise({
361 try: async () => {
362 const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
363 const platform = await sdk
364 .load()
365 .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
366 const release = await platform.prewarmLocalWorkspace({
367 ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
368 local: {
369 ...(cwd === undefined ? {} : { cwd }),
370 settingSources: [],
371 sandboxOptions: { enabled: true },
372 },
373 });
374 await release();
375 },
376 catch: (cause) => runnerError(cause, "prewarmLocalWorkspace"),
377 }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
378 },
379 );
380​
381 return CursorAgentSdkRunner.of({
382 open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
383 const { Agent } = yield* Effect.try({
384 try: sdk.load,
385 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
386 });
387 if (input.options.local?.sandboxOptions?.enabled === false) {
388 yield* primeCursorSandboxSupport(input.options);
389 }
390 const protocolLogger = protocolLoggerFor(input);
391 const log = (event: CursorAgentSdkProtocolLogEvent) =>
392 protocolLogger === undefined ? Effect.void : protocolLogger(event);
393​
394 yield* log({
395 direction: "outgoing",
396 stage: "decoded",
397 payload: {
398 type: "agent.open",
399 operation: input.operation,
400 ...(input.agentId === undefined ? {} : { agentId: input.agentId }),
401 options: loggedCursorAgentOptions(input.options),
402 },
403 });
404​
405 const agent = yield* Effect.tryPromise({
406 try: () =>
407 input.operation === "create"
408 ? Agent.create(input.options)
409 : Agent.resume(input.agentId!, input.options),
410 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
411 });
412​
413 yield* log({
414 direction: "incoming",
415 stage: "decoded",
416 payload: {
417 type: "agent.opened",
418 agentId: agent.agentId,
419 },
420 });
421​
422 const cwd =
423 typeof input.options.local?.cwd === "string"
424 ? input.options.local.cwd
425 : input.options.local?.cwd?.[0];
426 const runOptions = {
427 runtime: "local" as const,
428 ...(cwd === undefined ? {} : { cwd }),
429 ...(input.options.local?.store === undefined ? {} : { store: input.options.local.store }),
430 };
431 let abandonedRunRecoveryAvailable = input.operation === "resume";
432​
433 return {
434 agentId: agent.agentId,
435 send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) {
436 const context = yield* Effect.context();
437 yield* log({
438 direction: "outgoing",
439 stage: "decoded",
440 payload: {
441 type: "run.start",
442 message: sendInput.message,
443 options: loggedCursorSendOptions(sendInput.options),
444 },
445 });
446​
447 let callbacksReady = false;
448 const pendingUpdates: Array<InteractionUpdate> = [];
449 let callbackFailure: { readonly cause: unknown } | undefined;
450 let callbackChain = Promise.resolve();
451 let runId = "";
452 const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
453 callbackChain = callbackChain
454 .then(() => {
455 if (callbackFailure !== undefined) {
456 return;
457 }
458 return Effect.runPromiseWith(context)(
459 log({
460 direction: "incoming",
461 stage: "decoded",
462 payload: {
463 type: "interaction.update",
464 runId,
465 update,
466 },
467 }).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)),
468 );
469 })
470 .catch((cause) => {
471 callbackFailure ??= { cause };
472 });
473 return callbackChain;
474 };
475​
476 const startRun = () =>
477 Effect.tryPromise({
478 try: () =>
479 sendInput.summarize === true
480 ? agent.summarize()
481 : agent.send(sendInput.message, {
482 ...sendInput.options,
483 onDelta: async ({ update }) => {
484 if (!callbacksReady) {
485 pendingUpdates.push(update);
486 return;
487 }
488 await dispatchUpdate(update);
489 },
490 }),
491 catch: (cause) => runnerError(cause, "run.start"),
492 });
493 const run = yield* startRun().pipe(
494 Effect.catchIf(
495 (error) => abandonedRunRecoveryAvailable && isActiveRunConflict(error.cause),
496 (error) =>
497 Effect.gen(function* () {
498 abandonedRunRecoveryAvailable = false;
499 const latestRun = yield* Effect.tryPromise({
500 try: () => Agent.listRuns(agent.agentId, { ...runOptions, limit: 1 }),
501 catch: (cause) => runnerError(cause, "agent.listRuns"),
502 });
503 const activeRun = latestRun.items.find(
504 (candidate) => candidate.status === "running",
505 );
506 if (activeRun === undefined) {
507 return yield* error;
508 }
509 yield* log({
510 direction: "outgoing",
511 stage: "decoded",
512 payload: { type: "run.cancel", runId: activeRun.id },
513 });
514 yield* Effect.tryPromise({
515 try: () => Agent.cancelRun(activeRun.id, runOptions),
516 catch: (cause) => runnerError(cause, "agent.cancelRun"),
517 });
518 return yield* startRun();
519 }),
520 ),
521 );
522 abandonedRunRecoveryAvailable = false;
523 runId = run.id;
524 yield* log({
525 direction: "incoming",
526 stage: "decoded",
527 payload: {
528 type: "run.started",
529 runId: run.id,
530 agentId: run.agentId,
531 },
532 });
533 callbacksReady = true;
534 for (const update of pendingUpdates) {
535 yield* Effect.tryPromise({
536 try: () => dispatchUpdate(update),
537 catch: (cause) => runnerError(cause, "run.onDelta"),
538 });
539 }
540​
541 return {
542 runId: run.id,
543 agentId: run.agentId,
544 wait: Effect.tryPromise({
545 try: async () => {
546 const result = await run.wait();
547 await callbackChain;
548 if (callbackFailure !== undefined) {
549 throw callbackFailure.cause;
550 }
551 return result;
552 },
553 catch: (cause) => runnerError(cause, "run.wait"),
554 }).pipe(
555 Effect.tap((result) =>
556 log({
557 direction: "incoming",
558 stage: "decoded",
559 payload: {
560 type: "run.completed",
561 result,
562 },
563 }),
564 ),
565 ),
566 cancel: log({
567 direction: "outgoing",
568 stage: "decoded",
569 payload: {
570 type: "run.cancel",
571 runId: run.id,
572 },
573 }).pipe(
574 Effect.andThen(
575 Effect.tryPromise({
576 try: async () => {
577 try {
578 await run.cancel();
579 } catch (cause) {
580 if (!isCursorCancellationError(cause)) {
581 throw cause;
582 }
583 }
584 },
585 catch: (cause) => runnerError(cause, "run.cancel"),
586 }),
587 ),
588 ),
589 } satisfies CursorAgentSdkRun;
590 }),
591 listMessages: log({
592 direction: "outgoing",
593 stage: "decoded",
594 payload: {
595 type: "agent.messages.list",
596 agentId: agent.agentId,
597 },
598 }).pipe(
599 Effect.andThen(
600 Effect.tryPromise({
601 try: () =>
602 Agent.messages.list(agent.agentId, {
603 runtime: "local",
604 ...(cwd === undefined ? {} : { cwd }),
605 }),
606 catch: (cause) => runnerError(cause, "agent.messages.list"),
607 }),
608 ),
609 Effect.tap((messages) =>
610 log({
611 direction: "incoming",
612 stage: "decoded",
613 payload: {
614 type: "agent.messages",
615 agentId: agent.agentId,
616 messages,
617 },
618 }),
619 ),
620 ),
621 close: log({
622 direction: "outgoing",
623 stage: "decoded",
624 payload: {
625 type: "agent.close",
626 agentId: agent.agentId,
627 },
628 }).pipe(
629 Effect.andThen(
630 Effect.try({
631 try: () => agent.close(),
632 catch: (cause) => runnerError(cause, "agent.close"),
633 }),
634 ),
635 ),
636 } satisfies CursorAgentSdkSession;
637 }),
638 assertComplete: Effect.void,
639 });
640});
641​
642export const layer = Layer.effect(
643 CursorAgentSdkRunner,
644 Effect.gen(function* () {
645 const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
646 return yield* makeCursorAgentSdkRunner((input) =>
647 makeCursorAgentSdkProtocolLogger({
648 nativeEventLogger,
649 threadId: input.threadId,
650 providerSessionId: input.providerSessionId,
651 }),
652 );
653 }),
654);