@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,179 lines 42.5 KB
Raw
1 import type {
2 AgentMessage,
3 AgentOptions,
4 InteractionUpdate,
5 Run,
6 RunRecord,
7 RunResult,
8 SDKUserMessage,
9 SendOptions,
10 SteerAckOutcome,
11 } from "@cursor/sdk";
12 import {
13 NonNegativeInt,
14 type OrchestrationV2ProviderSession,
15 ProviderDriverKind,
16 type ThreadId,
17 } from "@t3tools/contracts";
18 import * as Context from "effect/Context";
19 import * as Deferred from "effect/Deferred";
20 import * as Effect from "effect/Effect";
21 import * as Exit from "effect/Exit";
22 import * as Layer from "effect/Layer";
23 import * as Option from "effect/Option";
24 import * as Ref from "effect/Ref";
25 import * as Schema from "effect/Schema";
26 import * as Semaphore from "effect/Semaphore";
27
28 import * as CursorSdk from "./CursorSdk.ts";
29 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
30
31 export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const;
32 export const CURSOR_PROVIDER = ProviderDriverKind.make("cursor");
33
34 export class CursorAgentSdkRunnerError extends Schema.TaggedError<CursorAgentSdkRunnerError>()(
35 "CursorAgentSdkRunnerError",
36 {
37 method: Schema.String,
38 cause: Schema.Defect(),
39 },
40 ) {
41 override get message(): string {
42 return `Cursor Agent SDK ${this.method} failed.`;
43 }
44 }
45
46 export function cursorSdkFailureMessage(error: CursorAgentSdkRunnerError): string {
47 const reason = sdkErrorReason(error.cause);
48 return reason === undefined
49 ? error.message
50 : `Cursor Agent SDK ${error.method} failed: ${reason}`;
51 }
52
53 // The SDK maps backend details to codes like PRO_USER_USAGE_LIMIT or RATE_LIMITED, without a status.
54 const CURSOR_USAGE_LIMIT_CODE =
55 /^(?:resource_exhausted|rate_limited(?:_changeable)?|\w*_usage_limit|\w*_rate_limit(?:_exceeded)?)$/i;
56
57 export function isCursorUsageLimitError(cause: unknown): boolean {
58 const error = isCursorAgentSdkRunnerError(cause) ? cause.cause : cause;
59 if (typeof error !== "object" || error === null) return false;
60 const code = Reflect.get(error, "code");
61 return (
62 Reflect.get(error, "name") === "RateLimitError" ||
63 Reflect.get(error, "status") === 429 ||
64 (typeof code === "string" && CURSOR_USAGE_LIMIT_CODE.test(code))
65 );
66 }
67
68 const GENERIC_SDK_ERROR_CODES = new Set(["", "error", "unknown"]);
69
70 function sdkErrorReason(cause: unknown): string | undefined {
71 if (!(cause instanceof Error)) return undefined;
72 const message = cause.message.trim();
73 if (message.length === 0) return undefined;
74 const code = Reflect.get(cause, "code");
75 const status = Reflect.get(cause, "status");
76 const details = [
77 ...(typeof code === "string" && !GENERIC_SDK_ERROR_CODES.has(code) && !message.includes(code)
78 ? [code]
79 : []),
80 ...(typeof status === "number" ? [`HTTP ${status}`] : []),
81 ];
82 return details.length === 0 ? message : `${message} (${details.join(", ")})`;
83 }
84
85 export const isCursorAgentSdkRunnerError = Schema.is(CursorAgentSdkRunnerError);
86
87 export interface CursorAgentSdkOpenInput {
88 readonly operation: "create" | "resume";
89 readonly agentId?: string;
90 readonly storeCwd?: string;
91 readonly options: AgentOptions;
92 readonly threadId: ThreadId;
93 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
94 }
95
96 export interface CursorAgentSdkSendInput<Error> {
97 readonly message: string | SDKUserMessage;
98 readonly options?: Omit<SendOptions, "onDelta">;
99 readonly onDelta?: (update: InteractionUpdate) => Effect.Effect<void, Error>;
100 /** Runs `agent.summarize()` instead, which takes no message or options. */
101 readonly summarize?: boolean;
102 /** Runs `agent.resume()`: Cursor's ResumeAction from the latest checkpoint, with no message. */
103 readonly resume?: boolean;
104 /**
105 * Runs, in order, when a background shell this agent starts from now on starts and when it
106 * ends, which is often long after the run.
107 */
108 readonly onBackgroundShell?: (event: CursorBackgroundShellEvent) => Effect.Effect<void>;
109 }
110
111 interface CursorBackgroundShellRef {
112 /** The shell id Cursor gave the agent. */
113 readonly id: string;
114 readonly pid: number | undefined;
115 readonly command: string;
116 }
117
118 export type CursorBackgroundShellEvent =
119 | (CursorBackgroundShellRef & { readonly type: "started"; readonly stop: () => void })
120 | (CursorBackgroundShellRef & {
121 readonly type: "ended";
122 /** Killed by the agent or by `stop`, rather than exiting by itself. */
123 readonly stopped: boolean;
124 readonly exitCode: number | undefined;
125 /** The file Cursor logs the shell's output to. */
126 readonly outputPath: string | undefined;
127 });
128
129 export interface CursorAgentSdkRun {
130 readonly runId: string;
131 readonly agentId: string;
132 readonly wait: Effect.Effect<RunResult, CursorAgentSdkRunnerError>;
133 readonly cancel: Effect.Effect<void, CursorAgentSdkRunnerError>;
134 /** Absent on test doubles that never steer. The live runner always sets it. */
135 readonly steer?: (text: string) => Effect.Effect<SteerAckOutcome, CursorAgentSdkRunnerError>;
136 }
137
138 export interface CursorContextUsage {
139 readonly usedTokens: number;
140 readonly maxTokens: number;
141 }
142
143 // The SDK types a checkpoint as `unknown`; Cursor keeps the conversation's context fill on it.
144 const CursorCheckpoint = Schema.Struct({
145 tokenDetails: Schema.Struct({ usedTokens: NonNegativeInt, maxTokens: NonNegativeInt }),
146 });
147 const decodeCursorCheckpoint = Schema.decodeUnknownOption(CursorCheckpoint);
148
149 export interface CursorAgentSdkSession {
150 readonly agentId: string;
151 readonly send: <Error>(
152 input: CursorAgentSdkSendInput<Error>,
153 ) => Effect.Effect<CursorAgentSdkRun, CursorAgentSdkRunnerError>;
154 readonly listMessages: Effect.Effect<ReadonlyArray<AgentMessage>, CursorAgentSdkRunnerError>;
155 /** Context fill at the latest checkpoint, if Cursor saved one. Absent on test doubles. */
156 readonly readContextUsage?: Effect.Effect<
157 CursorContextUsage | undefined,
158 CursorAgentSdkRunnerError
159 >;
160 /**
161 * Whether a run (the latest when omitted) saved a checkpoint of its own. Cursor keeps a stopped
162 * run only from its first checkpoint on; before that the conversation lacks the run's request.
163 */
164 readonly runCheckpointed?: (runId?: string) => Effect.Effect<boolean, CursorAgentSdkRunnerError>;
165 /**
166 * Rewinds the conversation to just before the run after `runId`, as `cursor-agent` /rewind does.
167 * The open agent keeps its old conversation in memory, so reopen it before the next send.
168 */
169 readonly rewindAfterRun?: (runId: string) => Effect.Effect<void, CursorAgentSdkRunnerError>;
170 /** False once an out-of-process worker has terminated or started closing; absent on in-process sessions. */
171 readonly isAlive?: () => boolean;
172 readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
173 }
174
175 export interface CursorAgentSdkTextGenerateInput {
176 readonly prompt: string;
177 readonly apiKey: string;
178 readonly model: NonNullable<AgentOptions["model"]>;
179 readonly cwd: string;
180 readonly stateRoot: string;
181 }
182
183 export class CursorAgentSdkRunner extends Context.Service<
184 CursorAgentSdkRunner,
185 {
186 readonly open: (
187 input: CursorAgentSdkOpenInput,
188 ) => Effect.Effect<CursorAgentSdkSession, CursorAgentSdkRunnerError>;
189 readonly assertComplete: Effect.Effect<void, CursorAgentSdkRunnerError>;
190 /** Absent on in-process test doubles; the out-of-process runner provides it. */
191 readonly textGenerate?: (
192 input: CursorAgentSdkTextGenerateInput,
193 ) => Effect.Effect<RunResult, CursorAgentSdkRunnerError>;
194 }
195 >()("@t3tools/provider-cursor/server/CursorAgentSdk/CursorAgentSdkRunner") {}
196
197 export interface CursorAgentSdkLoggedAgentOptions {
198 readonly model?: AgentOptions["model"];
199 readonly hasName?: boolean;
200 readonly mode?: AgentOptions["mode"];
201 readonly local?: {
202 readonly hasCwd?: boolean;
203 readonly autoReview?: boolean;
204 readonly settingSources?: AgentOptions["local"] extends infer Local
205 ? Local extends { readonly settingSources?: infer Sources }
206 ? Sources
207 : never
208 : never;
209 readonly sandboxEnabled?: boolean;
210 readonly enableAgentRetries?: boolean;
211 readonly hasCustomTools?: boolean;
212 };
213 readonly agents?: ReadonlyArray<string>;
214 }
215
216 export interface CursorAgentSdkLoggedSendOptions {
217 readonly model?: SendOptions["model"];
218 readonly mode?: SendOptions["mode"];
219 readonly hasMcpServers?: boolean;
220 readonly mcpServerNames?: ReadonlyArray<string>;
221 readonly local?: {
222 readonly force?: boolean;
223 readonly hasCustomTools?: boolean;
224 };
225 readonly idempotencyKey?: string;
226 }
227
228 export type CursorAgentSdkProtocolLogEvent =
229 | {
230 readonly direction: "outgoing";
231 readonly stage: "decoded";
232 readonly payload: {
233 readonly type: "agent.open";
234 readonly operation: CursorAgentSdkOpenInput["operation"];
235 readonly agentId?: string;
236 readonly options: CursorAgentSdkLoggedAgentOptions;
237 };
238 }
239 | {
240 readonly direction: "incoming";
241 readonly stage: "decoded";
242 readonly payload: {
243 readonly type: "agent.opened";
244 readonly agentId: string;
245 };
246 }
247 | {
248 readonly direction: "outgoing";
249 readonly stage: "decoded";
250 readonly payload: {
251 readonly type: "run.start";
252 readonly message: string | SDKUserMessage;
253 readonly options: CursorAgentSdkLoggedSendOptions;
254 };
255 }
256 | {
257 readonly direction: "outgoing";
258 readonly stage: "decoded";
259 readonly payload: {
260 readonly type: "run.resume";
261 readonly options: CursorAgentSdkLoggedSendOptions;
262 };
263 }
264 | {
265 readonly direction: "incoming";
266 readonly stage: "decoded";
267 readonly payload: {
268 readonly type: "run.started";
269 readonly runId: string;
270 readonly agentId: string;
271 };
272 }
273 | {
274 readonly direction: "incoming";
275 readonly stage: "decoded";
276 readonly payload: {
277 readonly type: "interaction.update";
278 readonly runId: string;
279 readonly update: InteractionUpdate;
280 };
281 }
282 | {
283 readonly direction: "incoming";
284 readonly stage: "decoded";
285 readonly payload: {
286 readonly type: "run.completed";
287 readonly result: RunResult;
288 };
289 }
290 | {
291 readonly direction: "outgoing";
292 readonly stage: "decoded";
293 readonly payload: {
294 readonly type: "run.steer";
295 readonly runId: string;
296 readonly text: string;
297 };
298 }
299 | {
300 readonly direction: "incoming";
301 readonly stage: "decoded";
302 readonly payload: {
303 readonly type: "run.steered";
304 readonly runId: string;
305 readonly outcome: SteerAckOutcome;
306 };
307 }
308 | {
309 readonly direction: "outgoing";
310 readonly stage: "decoded";
311 readonly payload: {
312 readonly type: "run.cancel";
313 readonly runId: string;
314 };
315 }
316 | {
317 readonly direction: "outgoing";
318 readonly stage: "decoded";
319 readonly payload: {
320 readonly type: "agent.messages.list";
321 readonly agentId: string;
322 };
323 }
324 | {
325 readonly direction: "outgoing";
326 readonly stage: "decoded";
327 readonly payload: {
328 readonly type: "agent.rewind";
329 readonly agentId: string;
330 readonly afterRunId: string;
331 };
332 }
333 | {
334 readonly direction: "incoming";
335 readonly stage: "decoded";
336 readonly payload: {
337 readonly type: "agent.messages";
338 readonly agentId: string;
339 readonly messages: ReadonlyArray<AgentMessage>;
340 };
341 }
342 | {
343 readonly direction: "outgoing";
344 readonly stage: "decoded";
345 readonly payload: {
346 readonly type: "agent.close";
347 readonly agentId: string;
348 };
349 };
350
351 export type CursorAgentSdkProtocolLogger = (
352 event: CursorAgentSdkProtocolLogEvent,
353 ) => Effect.Effect<void>;
354
355 function runnerError(cause: unknown, method: string): CursorAgentSdkRunnerError {
356 return isCursorAgentSdkRunnerError(cause)
357 ? cause
358 : new CursorAgentSdkRunnerError({ method, cause });
359 }
360
361 function isActiveRunConflict(cause: unknown): boolean {
362 return cause instanceof Error && /already has active run/i.test(cause.message);
363 }
364
365 export function isCursorCancellationError(cause: unknown): boolean {
366 let current = cause;
367 const seen = new Set<object>();
368
369 while (typeof current === "object" && current !== null && !seen.has(current)) {
370 if (Reflect.get(current, "name") === "AbortError") {
371 return true;
372 }
373 seen.add(current);
374 current = Reflect.get(current, "cause");
375 }
376
377 return false;
378 }
379
380 export function loggedCursorAgentOptions(options: AgentOptions): CursorAgentSdkLoggedAgentOptions {
381 return {
382 ...(options.model === undefined ? {} : { model: options.model }),
383 ...(options.name === undefined ? {} : { hasName: true }),
384 ...(options.mode === undefined ? {} : { mode: options.mode }),
385 ...(options.local === undefined
386 ? {}
387 : {
388 local: {
389 ...(options.local.cwd === undefined ? {} : { hasCwd: true }),
390 ...(options.local.autoReview === undefined
391 ? {}
392 : { autoReview: options.local.autoReview }),
393 ...(options.local.settingSources === undefined
394 ? {}
395 : { settingSources: options.local.settingSources }),
396 ...(options.local.sandboxOptions === undefined
397 ? {}
398 : { sandboxEnabled: options.local.sandboxOptions.enabled }),
399 ...(options.local.enableAgentRetries === undefined
400 ? {}
401 : { enableAgentRetries: options.local.enableAgentRetries }),
402 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
403 },
404 }),
405 ...(options.agents === undefined ? {} : { agents: Object.keys(options.agents).toSorted() }),
406 };
407 }
408
409 export function loggedCursorSendOptions(
410 options: Omit<SendOptions, "onDelta"> | undefined,
411 ): CursorAgentSdkLoggedSendOptions {
412 if (options === undefined) {
413 return {};
414 }
415 const mcpServerNames =
416 options.mcpServers === undefined ? undefined : Object.keys(options.mcpServers).toSorted();
417 return {
418 ...(options.model === undefined ? {} : { model: options.model }),
419 ...(options.mode === undefined ? {} : { mode: options.mode }),
420 ...(mcpServerNames === undefined ? {} : { hasMcpServers: true, mcpServerNames }),
421 ...(options.local === undefined
422 ? {}
423 : {
424 local: {
425 ...(options.local.force === undefined ? {} : { force: options.local.force }),
426 ...(options.local.customTools === undefined ? {} : { hasCustomTools: true }),
427 },
428 }),
429 ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
430 };
431 }
432
433 export function makeCursorAgentSdkProtocolLogger(input: {
434 readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;
435 readonly threadId: ThreadId;
436 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
437 }): CursorAgentSdkProtocolLogger | undefined {
438 if (input.nativeEventLogger === undefined) {
439 return undefined;
440 }
441 const nativeEventLogger = input.nativeEventLogger;
442 return (event) =>
443 nativeEventLogger
444 .write(
445 {
446 provider: CURSOR_PROVIDER,
447 protocol: CURSOR_AGENT_SDK_PROTOCOL,
448 kind: "protocol",
449 providerSessionId: input.providerSessionId,
450 event,
451 },
452 input.threadId,
453 )
454 .pipe(Effect.ignore);
455 }
456
457 interface CursorShellStreamOutput {
458 readonly conversationId?: unknown;
459 readonly toolCallId?: unknown;
460 readonly event: {
461 readonly case: "stdout" | "stderr";
462 readonly value: { readonly data: unknown };
463 };
464 }
465
466 // The SDK reports shell-output-delta only for user-started shell commands, so
467 // patches/@cursor__sdk@1.2.0.patch publishes agent shell output on this hook.
468 const SHELL_STREAM_OUTPUT_HOOK = Symbol.for("@cursor/sdk.shellStreamOutput");
469 const shellStreamListeners = new Set<(output: CursorShellStreamOutput) => void>();
470
471 function subscribeShellStreamOutput(listener: (output: CursorShellStreamOutput) => void) {
472 const hooks = globalThis as Record<symbol, unknown>;
473 hooks[SHELL_STREAM_OUTPUT_HOOK] ??= (output: CursorShellStreamOutput) => {
474 for (const notify of shellStreamListeners) notify(output);
475 };
476 shellStreamListeners.add(listener);
477 return () => {
478 shellStreamListeners.delete(listener);
479 };
480 }
481
482 type CursorLocalStore = NonNullable<NonNullable<AgentOptions["local"]>["store"]>;
483
484 interface DisposableCursorLocalStore extends CursorLocalStore {
485 readonly dispose: () => Promise<void>;
486 }
487
488 function isDisposableCursorLocalStore(value: unknown): value is DisposableCursorLocalStore {
489 return (
490 typeof value === "object" &&
491 value !== null &&
492 "agents" in value &&
493 "runs" in value &&
494 "checkpoints" in value &&
495 "runEvents" in value &&
496 "dispose" in value &&
497 typeof value.dispose === "function"
498 );
499 }
500
501 // T3 persists its own event log and never tails SDK run_events; skipping per-delta SQLite
502 // run_events writes avoids synchronous BEGIN IMMEDIATE write locks and multi-GB index.db bloat.
503 export function withNoopCursorRunEvents(store: CursorLocalStore): CursorLocalStore {
504 if (
505 typeof store !== "object" ||
506 store === null ||
507 typeof store.runEvents?.append !== "function"
508 ) {
509 return store;
510 }
511 let seq = 0;
512 return {
513 agents: store.agents,
514 runs: store.runs,
515 checkpoints: store.checkpoints,
516 runEvents: {
517 append: async (event) => {
518 seq += 1;
519 return {
520 runId: event.runId,
521 seq,
522 offset: String(seq),
523 eventType: event.eventType,
524 payload: event.payload ?? null,
525 payloadRef: event.payloadRef ?? null,
526 idempotencyKey: event.idempotencyKey ?? null,
527 createdAt: 0,
528 };
529 },
530 list: async () => ({ items: [] }),
531 delete: async () => {},
532 },
533 };
534 }
535
536 interface CursorBackgroundShell {
537 readonly conversationId?: unknown;
538 readonly command?: unknown;
539 readonly shell: {
540 readonly id?: unknown;
541 readonly pid?: unknown;
542 readonly abort: () => void;
543 readonly onComplete: (
544 listener: (completion: {
545 readonly code?: unknown;
546 readonly aborted?: unknown;
547 readonly outputPath?: unknown;
548 }) => void,
549 ) => void;
550 };
551 }
552
553 // The SDK kills an agent's background shells when its run ends and reports their exit to no one.
554 // The @cursor/sdk patch offers each new one to this hook; true keeps it past the run.
555 const BACKGROUND_SHELL_HOOK = Symbol.for("@cursor/sdk.backgroundShell");
556 const backgroundShellListeners = new Map<string, (event: CursorBackgroundShellEvent) => void>();
557
558 function listenForBackgroundShells(
559 agentId: string,
560 listener: (event: CursorBackgroundShellEvent) => void,
561 ) {
562 const hooks = globalThis as Record<symbol, unknown>;
563 hooks[BACKGROUND_SHELL_HOOK] ??= ({ conversationId, command, shell }: CursorBackgroundShell) => {
564 const notify =
565 typeof conversationId === "string" ? backgroundShellListeners.get(conversationId) : undefined;
566 if (notify === undefined) return false;
567 const ref = {
568 id: String(shell.id),
569 pid: typeof shell.pid === "number" ? shell.pid : undefined,
570 command: typeof command === "string" ? command : "",
571 };
572 notify({ ...ref, type: "started", stop: () => shell.abort() });
573 shell.onComplete((completion) =>
574 notify({
575 ...ref,
576 type: "ended",
577 stopped: completion.aborted === true,
578 exitCode: typeof completion.code === "number" ? completion.code : undefined,
579 outputPath: typeof completion.outputPath === "string" ? completion.outputPath : undefined,
580 }),
581 );
582 return true;
583 };
584 backgroundShellListeners.set(agentId, listener);
585 }
586
587 export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
588 protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
589 ) {
590 const sdk = yield* CursorSdk.CursorSdk;
591
592 // Prime with cursorsandbox before any Full access run; the SDK caches sandbox support per process.
593 const sandboxSupportPrimeStarted = yield* Ref.make(false);
594 const sandboxSupportPrimed = yield* Deferred.make<void>();
595 const primeCursorSandboxSupport = Effect.fn("CursorAgentSdkRunner.primeSandboxSupport")(
596 function* (options: AgentOptions) {
597 if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
598 return yield* Deferred.await(sandboxSupportPrimed);
599 }
600 yield* Effect.tryPromise({
601 try: async () => {
602 const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
603 const platform = await sdk
604 .load()
605 .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
606 const release = await platform.prewarmLocalWorkspace({
607 ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
608 local: {
609 ...(cwd === undefined ? {} : { cwd }),
610 settingSources: [],
611 sandboxOptions: { enabled: true },
612 },
613 });
614 await release();
615 },
616 catch: (cause) => runnerError(cause, "prewarmLocalWorkspace"),
617 }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
618 },
619 );
620
621 // Ref-count one SqliteLocalAgentStore per workspace so concurrent sessions share a single
622 // index.db handle while still disposing handles, page caches, and FDs once the last one closes.
623 interface WorkspaceStoreLease {
624 readonly store: DisposableCursorLocalStore;
625 readonly wrapped: CursorLocalStore;
626 users: number;
627 }
628 const workspaceStores = new Map<string, WorkspaceStoreLease>();
629 const workspaceStoreLock = yield* Semaphore.make(1);
630 const acquireWorkspaceStore = (workspaceRef: string, method: string) =>
631 workspaceStoreLock.withPermits(1)(
632 Effect.suspend(() => {
633 const existing = workspaceStores.get(workspaceRef);
634 if (existing !== undefined) {
635 existing.users += 1;
636 return Effect.succeed(existing);
637 }
638 return Effect.tryPromise({
639 try: async () => {
640 const candidate = await sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef });
641 return isDisposableCursorLocalStore(candidate) ? candidate : undefined;
642 },
643 catch: (cause) => runnerError(cause, method),
644 }).pipe(
645 Effect.map((opened) => {
646 if (opened === undefined) return undefined;
647 const lease: WorkspaceStoreLease = {
648 store: opened,
649 wrapped: withNoopCursorRunEvents(opened),
650 users: 1,
651 };
652 workspaceStores.set(workspaceRef, lease);
653 return lease;
654 }),
655 );
656 }),
657 );
658 const releaseWorkspaceStore = (workspaceRef: string, lease: WorkspaceStoreLease) =>
659 workspaceStoreLock.withPermits(1)(
660 Effect.suspend(() => {
661 lease.users -= 1;
662 if (lease.users > 0) return Effect.void;
663 if (workspaceStores.get(workspaceRef) === lease) {
664 workspaceStores.delete(workspaceRef);
665 }
666 return Effect.tryPromise({
667 try: () => lease.store.dispose(),
668 catch: () => undefined,
669 }).pipe(Effect.ignore);
670 }),
671 );
672
673 return CursorAgentSdkRunner.of({
674 open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
675 const { Agent, createAgentPlatform } = yield* Effect.try({
676 try: sdk.load,
677 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
678 });
679 if (input.options.local?.sandboxOptions?.enabled === false) {
680 yield* primeCursorSandboxSupport(input.options);
681 }
682 const protocolLogger = protocolLoggerFor(input);
683 const log = (event: CursorAgentSdkProtocolLogEvent) =>
684 protocolLogger === undefined ? Effect.void : protocolLogger(event);
685
686 yield* log({
687 direction: "outgoing",
688 stage: "decoded",
689 payload: {
690 type: "agent.open",
691 operation: input.operation,
692 ...(input.agentId === undefined ? {} : { agentId: input.agentId }),
693 options: loggedCursorAgentOptions(input.options),
694 },
695 });
696
697 // Cursor uses cwd for both execution and store lookup; a moved thread keeps its original store.
698 const cwd =
699 typeof input.options.local?.cwd === "string"
700 ? input.options.local.cwd
701 : input.options.local?.cwd?.[0];
702 const storeCwd = input.storeCwd;
703 const storeWorkspace =
704 input.operation === "resume" && storeCwd !== undefined ? storeCwd : cwd;
705 const ownedStoreLease =
706 input.options.local?.store === undefined && storeWorkspace !== undefined
707 ? yield* acquireWorkspaceStore(storeWorkspace, `agent.${input.operation}`)
708 : undefined;
709 let storeReleased = false;
710 const disposeOwnedStore =
711 ownedStoreLease === undefined || storeWorkspace === undefined
712 ? Effect.void
713 : Effect.suspend(() => {
714 if (storeReleased) return Effect.void;
715 storeReleased = true;
716 return releaseWorkspaceStore(storeWorkspace, ownedStoreLease);
717 });
718 const effectiveStore =
719 ownedStoreLease === undefined ? input.options.local?.store : ownedStoreLease.wrapped;
720 const effectiveOptions: AgentOptions =
721 effectiveStore === undefined || effectiveStore === input.options.local?.store
722 ? input.options
723 : {
724 ...input.options,
725 local: {
726 ...input.options.local,
727 store: effectiveStore,
728 },
729 };
730
731 const { storePlatform, agent } = yield* Effect.gen(function* () {
732 const resolvedStorePlatform =
733 input.operation === "resume" &&
734 storeCwd !== undefined &&
735 storeCwd !== input.options.local?.cwd
736 ? yield* Effect.tryPromise({
737 try: () =>
738 createAgentPlatform({
739 workspaceRef: storeCwd,
740 ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),
741 }),
742 catch: (cause) => runnerError(cause, "agent.resume"),
743 })
744 : undefined;
745 const openedAgent = yield* Effect.tryPromise({
746 try: () =>
747 input.operation === "create"
748 ? Agent.create(effectiveOptions)
749 : resolvedStorePlatform === undefined
750 ? Agent.resume(input.agentId!, effectiveOptions)
751 : resolvedStorePlatform.resumeAgent(input.agentId!, effectiveOptions),
752 catch: (cause) => runnerError(cause, `agent.${input.operation}`),
753 });
754 yield* log({
755 direction: "incoming",
756 stage: "decoded",
757 payload: {
758 type: "agent.opened",
759 agentId: openedAgent.agentId,
760 },
761 });
762 return { storePlatform: resolvedStorePlatform, agent: openedAgent };
763 }).pipe(Effect.onExit((exit) => (Exit.isFailure(exit) ? disposeOwnedStore : Effect.void)));
764 let shellListener: ((event: CursorBackgroundShellEvent) => void) | undefined;
765
766 const runOptions = {
767 runtime: "local" as const,
768 ...(cwd === undefined ? {} : { cwd }),
769 ...(effectiveStore === undefined ? {} : { store: effectiveStore }),
770 };
771 let abandonedRunRecoveryAvailable = input.operation === "resume";
772 const storeView = async () =>
773 storePlatform ??
774 (await createAgentPlatform({
775 ...(cwd === undefined ? {} : { workspaceRef: cwd }),
776 ...(effectiveStore === undefined ? {} : { localStore: effectiveStore }),
777 }));
778
779 return {
780 agentId: agent.agentId,
781 send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) {
782 const context = yield* Effect.context();
783 const options = loggedCursorSendOptions(sendInput.options);
784 yield* sendInput.resume === true
785 ? log({
786 direction: "outgoing",
787 stage: "decoded",
788 payload: { type: "run.resume", options },
789 })
790 : log({
791 direction: "outgoing",
792 stage: "decoded",
793 payload: { type: "run.start", message: sendInput.message, options },
794 });
795
796 const onBackgroundShell = sendInput.onBackgroundShell;
797 if (onBackgroundShell !== undefined) {
798 let delivered = Promise.resolve();
799 shellListener = (event) => {
800 delivered = delivered
801 .then(() => Effect.runPromiseWith(context)(onBackgroundShell(event)))
802 .catch(() => undefined);
803 };
804 listenForBackgroundShells(agent.agentId, shellListener);
805 }
806
807 let callbacksReady = false;
808 const pendingUpdates: Array<InteractionUpdate> = [];
809 let callbackFailure: { readonly cause: unknown } | undefined;
810 let callbackChain = Promise.resolve();
811 let runId = "";
812 const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
813 callbackChain = callbackChain
814 .then(() => {
815 if (callbackFailure !== undefined) {
816 return;
817 }
818 return Effect.runPromiseWith(context)(
819 log({
820 direction: "incoming",
821 stage: "decoded",
822 payload: {
823 type: "interaction.update",
824 runId,
825 update,
826 },
827 }).pipe(Effect.andThen(sendInput.onDelta?.(update) ?? Effect.void)),
828 );
829 })
830 .catch((cause) => {
831 callbackFailure ??= { cause };
832 });
833 return callbackChain;
834 };
835
836 const startRun = () =>
837 Effect.tryPromise({
838 try: () => {
839 if (sendInput.summarize === true) return agent.summarize();
840 const options: SendOptions = {
841 ...sendInput.options,
842 onDelta: async ({ update }) => {
843 if (!callbacksReady) {
844 pendingUpdates.push(update);
845 return;
846 }
847 await dispatchUpdate(update);
848 },
849 };
850 if (sendInput.resume !== true) return agent.send(sendInput.message, options);
851 if (agent.resume === undefined) {
852 throw new Error("This Cursor SDK agent cannot resume.");
853 }
854 return agent.resume(options);
855 },
856 catch: (cause) =>
857 runnerError(cause, sendInput.resume === true ? "run.resume" : "run.start"),
858 });
859 const run = yield* startRun().pipe(
860 Effect.catchIf(
861 (error) => abandonedRunRecoveryAvailable && isActiveRunConflict(error.cause),
862 (error) =>
863 Effect.gen(function* () {
864 abandonedRunRecoveryAvailable = false;
865 // Local stores list runs oldest first, so the active run is on the
866 // last page and every page has to be read to reach it.
867 let activeRun: Run | undefined;
868 let cursor: string | undefined;
869 do {
870 const page = yield* Effect.tryPromise({
871 try: () =>
872 storePlatform === undefined
873 ? Agent.listRuns(agent.agentId, {
874 ...runOptions,
875 ...(cursor === undefined ? {} : { cursor }),
876 })
877 : storePlatform.listRuns(
878 agent.agentId,
879 cursor === undefined ? {} : { cursor },
880 ),
881 catch: (cause) => runnerError(cause, "agent.listRuns"),
882 });
883 activeRun =
884 page.items.findLast((candidate) => candidate.status === "running") ??
885 activeRun;
886 cursor = page.nextCursor;
887 } while (cursor !== undefined);
888 if (activeRun === undefined) {
889 return yield* error;
890 }
891 yield* log({
892 direction: "outgoing",
893 stage: "decoded",
894 payload: { type: "run.cancel", runId: activeRun.id },
895 });
896 yield* Effect.tryPromise({
897 try: () =>
898 storePlatform === undefined
899 ? Agent.cancelRun(activeRun.id, runOptions)
900 : storePlatform.cancelRun(activeRun.id),
901 catch: (cause) => runnerError(cause, "agent.cancelRun"),
902 });
903 return yield* startRun();
904 }),
905 ),
906 );
907 abandonedRunRecoveryAvailable = false;
908 runId = run.id;
909 yield* log({
910 direction: "incoming",
911 stage: "decoded",
912 payload: {
913 type: "run.started",
914 runId: run.id,
915 agentId: run.agentId,
916 },
917 });
918 callbacksReady = true;
919 const unsubscribeShellOutput = subscribeShellStreamOutput((output) => {
920 if (output.conversationId !== agent.agentId || typeof output.toolCallId !== "string") {
921 return;
922 }
923 void dispatchUpdate({
924 type: "shell-output-delta",
925 event: { ...output.event, toolCallId: output.toolCallId },
926 });
927 });
928 for (const update of pendingUpdates) {
929 yield* Effect.tryPromise({
930 try: () => dispatchUpdate(update),
931 catch: (cause) => runnerError(cause, "run.onDelta"),
932 });
933 }
934
935 return {
936 runId: run.id,
937 agentId: run.agentId,
938 wait: Effect.tryPromise({
939 try: async () => {
940 const result = await run.wait();
941 await callbackChain;
942 if (callbackFailure !== undefined) {
943 throw callbackFailure.cause;
944 }
945 return result;
946 },
947 catch: (cause) => runnerError(cause, "run.wait"),
948 }).pipe(
949 Effect.ensuring(Effect.sync(unsubscribeShellOutput)),
950 Effect.tap((result) =>
951 log({
952 direction: "incoming",
953 stage: "decoded",
954 payload: {
955 type: "run.completed",
956 result,
957 },
958 }),
959 ),
960 ),
961 steer: Effect.fn("CursorAgentSdkRun.steer")((text: string) =>
962 log({
963 direction: "outgoing",
964 stage: "decoded",
965 payload: {
966 type: "run.steer",
967 runId: run.id,
968 text,
969 },
970 }).pipe(
971 Effect.andThen(
972 Effect.tryPromise({
973 try: () => run.steer?.(text) ?? Promise.resolve("revert_to_followup" as const),
974 catch: (cause) => runnerError(cause, "run.steer"),
975 }),
976 ),
977 Effect.tap((outcome) =>
978 log({
979 direction: "incoming",
980 stage: "decoded",
981 payload: {
982 type: "run.steered",
983 runId: run.id,
984 outcome,
985 },
986 }),
987 ),
988 ),
989 ),
990 cancel: log({
991 direction: "outgoing",
992 stage: "decoded",
993 payload: {
994 type: "run.cancel",
995 runId: run.id,
996 },
997 }).pipe(
998 Effect.andThen(
999 Effect.tryPromise({
1000 try: async () => {
1001 try {
1002 await run.cancel();
1003 } catch (cause) {
1004 if (!isCursorCancellationError(cause)) {
1005 throw cause;
1006 }
1007 }
1008 },
1009 catch: (cause) => runnerError(cause, "run.cancel"),
1010 }),
1011 ),
1012 ),
1013 } satisfies CursorAgentSdkRun;
1014 }),
1015 listMessages: log({
1016 direction: "outgoing",
1017 stage: "decoded",
1018 payload: {
1019 type: "agent.messages.list",
1020 agentId: agent.agentId,
1021 },
1022 }).pipe(
1023 Effect.andThen(
1024 Effect.tryPromise({
1025 try: () =>
1026 storePlatform === undefined
1027 ? Agent.messages.list(agent.agentId, {
1028 runtime: "local",
1029 ...(cwd === undefined ? {} : { cwd }),
1030 ...(effectiveStore === undefined ? {} : { store: effectiveStore }),
1031 })
1032 : storePlatform.getAgentMessages(agent.agentId),
1033 catch: (cause) => runnerError(cause, "agent.messages.list"),
1034 }),
1035 ),
1036 Effect.tap((messages) =>
1037 log({
1038 direction: "incoming",
1039 stage: "decoded",
1040 payload: {
1041 type: "agent.messages",
1042 agentId: agent.agentId,
1043 messages,
1044 },
1045 }),
1046 ),
1047 ),
1048 readContextUsage: Effect.tryPromise({
1049 try: async () => (await storeView()).checkpointStore.loadLatest(agent.agentId),
1050 catch: (cause) => runnerError(cause, "agent.checkpoint.load"),
1051 }).pipe(
1052 Effect.map((checkpoint) => {
1053 const usage = Option.getOrUndefined(decodeCursorCheckpoint(checkpoint))?.tokenDetails;
1054 // An unset protobuf message reads as zeros.
1055 return usage === undefined || usage.maxTokens === 0 ? undefined : usage;
1056 }),
1057 ),
1058 runCheckpointed: (runId) =>
1059 Effect.tryPromise({
1060 try: async () => {
1061 const { store } = await storeView();
1062 let run: RunRecord | null | undefined;
1063 if (runId !== undefined) {
1064 run = await store.getRun(agent.agentId, runId);
1065 } else {
1066 let cursor: string | undefined;
1067 do {
1068 const page = await store.listRuns(
1069 agent.agentId,
1070 cursor === undefined ? {} : { cursor },
1071 );
1072 for (const candidate of page.items) {
1073 if (!run || candidate.turnNumber >= run.turnNumber) run = candidate;
1074 }
1075 cursor = page.nextCursor;
1076 } while (cursor !== undefined);
1077 }
1078 const checkpoint = run?.latestCheckpointRef?.blobId;
1079 return checkpoint !== undefined && checkpoint !== run?.startCheckpointRef?.blobId;
1080 },
1081 catch: (cause) => runnerError(cause, "agent.run.get"),
1082 }),
1083 rewindAfterRun: (runId) =>
1084 log({
1085 direction: "outgoing",
1086 stage: "decoded",
1087 payload: { type: "agent.rewind", agentId: agent.agentId, afterRunId: runId },
1088 }).pipe(
1089 Effect.andThen(
1090 Effect.tryPromise({
1091 try: async () => {
1092 const { store, checkpointStore } = await storeView();
1093 const runs: Array<RunRecord> = [];
1094 let cursor: string | undefined;
1095 do {
1096 const page = await store.listRuns(
1097 agent.agentId,
1098 cursor === undefined ? {} : { cursor },
1099 );
1100 runs.push(...page.items);
1101 cursor = page.nextCursor;
1102 } while (cursor !== undefined);
1103 const kept = runs.find((candidate) => candidate.runId === runId);
1104 if (kept === undefined) {
1105 throw new Error(`Cursor agent ${agent.agentId} has no run ${runId}.`);
1106 }
1107 const unwound = runs
1108 .filter((candidate) => candidate.turnNumber > kept.turnNumber)
1109 .toSorted((a, b) => a.turnNumber - b.turnNumber)[0];
1110 if (unwound === undefined) return;
1111 const anchor = unwound.startCheckpointRef?.blobId;
1112 if (anchor === undefined) {
1113 throw new Error(`Cursor run ${unwound.runId} has no starting checkpoint.`);
1114 }
1115 const blobStore = await checkpointStore.getBlobStore(agent.agentId);
1116 const getBlob =
1117 typeof blobStore === "object" && blobStore !== null
1118 ? Reflect.get(blobStore, "getBlob")
1119 : undefined;
1120 if (typeof getBlob !== "function") {
1121 throw new Error("Cursor's checkpoint store cannot read blobs.");
1122 }
1123 const bytes: unknown = await getBlob.call(
1124 blobStore,
1125 undefined,
1126 Buffer.from(anchor, "hex"),
1127 );
1128 if (!(bytes instanceof Uint8Array)) {
1129 throw new Error(`Cursor checkpoint ${anchor} is missing.`);
1130 }
1131 // Checkpoints are content-addressed, so re-saving the anchor's bytes moves the
1132 // agent's head back to that exact root, like cursor-agent's latestRootBlobId reset.
1133 await checkpointStore.saveCheckpoint(agent.agentId, { toBinary: () => bytes });
1134 },
1135 catch: (cause) => runnerError(cause, "agent.rewind"),
1136 }),
1137 ),
1138 ),
1139 close: log({
1140 direction: "outgoing",
1141 stage: "decoded",
1142 payload: {
1143 type: "agent.close",
1144 agentId: agent.agentId,
1145 },
1146 }).pipe(
1147 Effect.andThen(
1148 Effect.try({
1149 try: () => {
1150 // A resumed session may already listen for this agent.
1151 if (backgroundShellListeners.get(agent.agentId) === shellListener) {
1152 backgroundShellListeners.delete(agent.agentId);
1153 }
1154 agent.close();
1155 },
1156 catch: (cause) => runnerError(cause, "agent.close"),
1157 }),
1158 ),
1159 Effect.ensuring(disposeOwnedStore),
1160 ),
1161 } satisfies CursorAgentSdkSession;
1162 }),
1163 assertComplete: Effect.void,
1164 });
1165 });
1166
1167 export const layer = Layer.effect(
1168 CursorAgentSdkRunner,
1169 Effect.gen(function* () {
1170 const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
1171 return yield* makeCursorAgentSdkRunner((input) =>
1172 makeCursorAgentSdkProtocolLogger({
1173 nativeEventLogger,
1174 threadId: input.threadId,
1175 providerSessionId: input.providerSessionId,
1176 }),
1177 );
1178 }),
1179 );