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

CursorAgentSdk.ts

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