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

CursorAgentSdk.ts

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