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

CursorAgentSdk.ts

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