Open History to see the last commit
1/**
2 * CursorAdapterLive — Cursor CLI (`agent acp`) via ACP.
3 *
4 * @module CursorAdapterLive
5 */
6
7import {
8 ApprovalRequestId,
9 type CursorSettings,
10 type ProviderOptionSelection,
11 EventId,
12 type ProviderApprovalDecision,
13 type ProviderInteractionMode,
14 type ProviderRuntimeEvent,
15 type ProviderSession,
16 type ProviderUserInputAnswers,
17 ProviderDriverKind,
18 ProviderInstanceId,
19 RuntimeRequestId,
20 type RuntimeMode,
21 type ThreadId,
22 TurnId,
23} from "@t3tools/contracts";
24import * as DateTime from "effect/DateTime";
25import * as Crypto from "effect/Crypto";
26import * as Deferred from "effect/Deferred";
27import * as Effect from "effect/Effect";
28import * as Exit from "effect/Exit";
29import * as Fiber from "effect/Fiber";
30import * as FileSystem from "effect/FileSystem";
31import * as Option from "effect/Option";
32import * as Path from "effect/Path";
33import * as PubSub from "effect/PubSub";
34import * as Schema from "effect/Schema";
35import * as Scope from "effect/Scope";
36import * as Semaphore from "effect/Semaphore";
37import * as Stream from "effect/Stream";
38import * as SynchronizedRef from "effect/SynchronizedRef";
39import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
40import * as EffectAcpErrors from "effect-acp/errors";
41import type * as EffectAcpSchema from "effect-acp/schema";
42
43import { resolveAttachmentPath } from "../../attachmentStore.ts";
44import { ServerConfig } from "../../config.ts";
45import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
46import {
47 ProviderAdapterProcessError,
48 ProviderAdapterRequestError,
49 ProviderAdapterSessionNotFoundError,
50 ProviderAdapterValidationError,
51} from "../Errors.ts";
52import { acpPermissionOutcome, mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
53import type * as AcpSessionRuntime from "../acp/AcpSessionRuntime.ts";
54import {
55 makeAcpAssistantItemEvent,
56 makeAcpContentDeltaEvent,
57 makeAcpPlanUpdatedEvent,
58 makeAcpRequestOpenedEvent,
59 makeAcpRequestResolvedEvent,
60 makeAcpToolCallEvent,
61} from "../acp/AcpCoreRuntimeEvents.ts";
62import {
63 type AcpSessionMode,
64 type AcpSessionModeState,
65 parsePermissionRequest,
66} from "../acp/AcpRuntimeModel.ts";
67import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
68import { applyCursorAcpModelSelection, makeCursorAcpRuntime } from "../acp/CursorAcpSupport.ts";
69import {
70 CursorAskQuestionRequest,
71 CursorCreatePlanRequest,
72 CursorUpdateTodosRequest,
73 extractAskQuestions,
74 extractPlanMarkdown,
75 extractTodosAsPlan,
76} from "../acp/CursorAcpExtension.ts";
77import { type CursorAdapterShape } from "../Services/CursorAdapter.ts";
78import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts";
79import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
80import {
81 discoverCursorSkills,
82 hasCursorSkillMention,
83 rewriteCursorSkillMentions,
84} from "../Drivers/CursorSkills.ts";
85const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
86
87const PROVIDER = ProviderDriverKind.make("cursor");
88const CURSOR_RESUME_VERSION = 1 as const;
89const ACP_PLAN_MODE_ALIASES = ["plan", "architect"];
90const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"];
91const ACP_APPROVAL_MODE_ALIASES = ["ask"];
92
93function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
94 const result = encodeUnknownJsonStringExit(input);
95 return Exit.isSuccess(result) ? result.value : undefined;
96}
97
98export interface CursorAdapterLiveOptions {
99 readonly environment?: NodeJS.ProcessEnv;
100 readonly nativeEventLogPath?: string;
101 readonly nativeEventLogger?: EventNdjsonLogger;
102 /**
103 * Selections are honored when `modelSelection.instanceId` matches this value.
104 * Defaults to the legacy built-in instance id (`cursor`).
105 */
106 readonly instanceId?: ProviderInstanceId;
107 /**
108 * Optional per-session settings resolver. When provided the adapter yields
109 * this effect at the start of every session and uses the result instead of
110 * the `cursorSettings` captured at construction.
111 *
112 * Production instances bind settings to the instance scope (the hydration
113 * layer rebuilds the adapter on config change) and leave this undefined.
114 * Test suites that mutate `ServerSettingsService` mid-flight — e.g. to
115 * swap `binaryPath` to a mock ACP wrapper — pass a resolver that reads
116 * the latest snapshot so the closure isn't stale.
117 */
118 readonly resolveSettings?: Effect.Effect<CursorSettings>;
119}
120
121interface PendingApproval {
122 readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
123 readonly kind: string | "unknown";
124}
125
126interface PendingUserInput {
127 readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
128}
129
130interface CursorSessionContext {
131 readonly threadId: ThreadId;
132 session: ProviderSession;
133 readonly scope: Scope.Closeable;
134 readonly acp: AcpSessionRuntime.AcpSessionRuntime["Service"];
135 notificationFiber: Fiber.Fiber<void, never> | undefined;
136 readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
137 readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
138 readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
139 lastPlanFingerprint: string | undefined;
140 activeTurnId: TurnId | undefined;
141 cursorSkillNames: ReadonlySet<string> | undefined;
142 /** Number of sendTurn prompts currently in flight or being prepared.
143 * >0 means a turn is actively running, so a new sendTurn is a steer that
144 * continues it, and only the last remaining prompt settles the turn. */
145 promptsInFlight: number;
146 stopped: boolean;
147}
148
149function settlePendingApprovalsAsCancelled(
150 pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
151): Effect.Effect<void> {
152 const pendingEntries = Array.from(pendingApprovals.values());
153 return Effect.forEach(
154 pendingEntries,
155 (pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
156 {
157 discard: true,
158 },
159 );
160}
161
162function settlePendingUserInputsAsEmptyAnswers(
163 pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
164): Effect.Effect<void> {
165 const pendingEntries = Array.from(pendingUserInputs.values());
166 return Effect.forEach(
167 pendingEntries,
168 (pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
169 {
170 discard: true,
171 },
172 );
173}
174
175function isRecord(value: unknown): value is Record<string, unknown> {
176 return typeof value === "object" && value !== null && !Array.isArray(value);
177}
178
179function parseCursorResume(raw: unknown): { sessionId: string } | undefined {
180 if (!isRecord(raw)) return undefined;
181 if (raw.schemaVersion !== CURSOR_RESUME_VERSION) return undefined;
182 if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined;
183 return { sessionId: raw.sessionId.trim() };
184}
185
186function normalizeModeSearchText(mode: AcpSessionMode): string {
187 return [mode.id, mode.name, mode.description]
188 .filter((value): value is string => typeof value === "string" && value.length > 0)
189 .join(" ")
190 .toLowerCase()
191 .replace(/[^a-z0-9]+/g, " ")
192 .trim();
193}
194
195function findModeByAliases(
196 modes: ReadonlyArray<AcpSessionMode>,
197 aliases: ReadonlyArray<string>,
198): AcpSessionMode | undefined {
199 const normalizedAliases = aliases.map((alias) => alias.toLowerCase());
200 for (const alias of normalizedAliases) {
201 const exact = modes.find((mode) => {
202 const id = mode.id.toLowerCase();
203 const name = mode.name.toLowerCase();
204 return id === alias || name === alias;
205 });
206 if (exact) {
207 return exact;
208 }
209 }
210 for (const alias of normalizedAliases) {
211 const partial = modes.find((mode) => normalizeModeSearchText(mode).includes(alias));
212 if (partial) {
213 return partial;
214 }
215 }
216 return undefined;
217}
218
219function isPlanMode(mode: AcpSessionMode): boolean {
220 return findModeByAliases([mode], ACP_PLAN_MODE_ALIASES) !== undefined;
221}
222
223function resolveRequestedModeId(input: {
224 readonly interactionMode: ProviderInteractionMode | undefined;
225 readonly runtimeMode: RuntimeMode;
226 readonly modeState: AcpSessionModeState | undefined;
227}): string | undefined {
228 const modeState = input.modeState;
229 if (!modeState) {
230 return undefined;
231 }
232
233 if (input.interactionMode === "plan") {
234 return findModeByAliases(modeState.availableModes, ACP_PLAN_MODE_ALIASES)?.id;
235 }
236
237 if (input.runtimeMode === "approval-required") {
238 return (
239 findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??
240 findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??
241 modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??
242 modeState.currentModeId
243 );
244 }
245
246 return (
247 findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??
248 findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??
249 modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??
250 modeState.currentModeId
251 );
252}
253
254function applyRequestedSessionConfiguration<E>(input: {
255 readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"];
256 readonly runtimeMode: RuntimeMode;
257 readonly interactionMode: ProviderInteractionMode | undefined;
258 readonly modelSelection:
259 | {
260 readonly model: string;
261 readonly options?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
262 }
263 | undefined;
264 readonly mapError: (context: {
265 readonly cause: import("effect-acp/errors").AcpError;
266 readonly method: "session/set_config_option" | "session/set_mode";
267 }) => E;
268}): Effect.Effect<void, E> {
269 return Effect.gen(function* () {
270 if (input.modelSelection) {
271 yield* applyCursorAcpModelSelection({
272 runtime: input.runtime,
273 model: input.modelSelection.model,
274 selections: input.modelSelection.options,
275 mapError: ({ cause }) =>
276 input.mapError({
277 cause,
278 method: "session/set_config_option",
279 }),
280 });
281 }
282
283 const requestedModeId = resolveRequestedModeId({
284 interactionMode: input.interactionMode,
285 runtimeMode: input.runtimeMode,
286 modeState: yield* input.runtime.getModeState,
287 });
288 if (!requestedModeId) {
289 return;
290 }
291
292 yield* input.runtime.setMode(requestedModeId).pipe(
293 Effect.mapError((cause) =>
294 input.mapError({
295 cause,
296 method: "session/set_mode",
297 }),
298 ),
299 );
300 });
301}
302
303function selectAutoApprovedPermissionOption(
304 request: EffectAcpSchema.RequestPermissionRequest,
305): string | undefined {
306 const allowAlwaysOption = request.options.find((option) => option.kind === "allow_always");
307 if (typeof allowAlwaysOption?.optionId === "string" && allowAlwaysOption.optionId.trim()) {
308 return allowAlwaysOption.optionId.trim();
309 }
310
311 const allowOnceOption = request.options.find((option) => option.kind === "allow_once");
312 if (typeof allowOnceOption?.optionId === "string" && allowOnceOption.optionId.trim()) {
313 return allowOnceOption.optionId.trim();
314 }
315
316 return undefined;
317}
318
319export function makeCursorAdapter(
320 cursorSettings: CursorSettings,
321 options?: CursorAdapterLiveOptions,
322) {
323 return Effect.gen(function* () {
324 const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor");
325 const fileSystem = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
328 const serverConfig = yield* Effect.service(ServerConfig);
329 const crypto = yield* Crypto.Crypto;
330 const nativeEventLogger =
331 options?.nativeEventLogger ??
332 (options?.nativeEventLogPath !== undefined
333 ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
334 stream: "native",
335 })
336 : undefined);
337 const managedNativeEventLogger =
338 options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
339 const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
340
341 const sessions = new Map<ThreadId, CursorSessionContext>();
342 const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
343 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
344
345 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
346 const randomUUIDv4 = crypto.randomUUIDv4.pipe(
347 Effect.mapError(
348 (cause) =>
349 new ProviderAdapterRequestError({
350 provider: PROVIDER,
351 method: "crypto/randomUUIDv4",
352 detail: "Failed to generate Cursor runtime identifier.",
353 cause,
354 }),
355 ),
356 );
357 const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));
358 const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
359 const mapExtensionFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
360 effect.pipe(
361 Effect.mapError(
362 (cause) =>
363 new EffectAcpErrors.AcpTransportError({
364 detail: "Failed to process Cursor ACP extension event.",
365 cause,
366 }),
367 ),
368 );
369
370 const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
371 PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
372
373 const getThreadSemaphore = (threadId: string) =>
374 SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
375 const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
376 current.get(threadId),
377 );
378 return Option.match(existing, {
379 onNone: () =>
380 Semaphore.make(1).pipe(
381 Effect.map((semaphore) => {
382 const next = new Map(current);
383 next.set(threadId, semaphore);
384 return [semaphore, next] as const;
385 }),
386 ),
387 onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
388 });
389 });
390
391 const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
392 Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
393
394 const logNative = (
395 threadId: ThreadId,
396 method: string,
397 payload: unknown,
398 _source: "acp.jsonrpc" | "acp.cursor.extension",
399 ) =>
400 Effect.gen(function* () {
401 if (!nativeEventLogger) return;
402 const observedAt = yield* nowIso;
403 yield* nativeEventLogger.write(
404 {
405 observedAt,
406 event: {
407 id: yield* randomUUIDv4,
408 kind: "notification",
409 provider: PROVIDER,
410 createdAt: observedAt,
411 method,
412 threadId,
413 payload,
414 },
415 },
416 threadId,
417 );
418 });
419
420 const emitPlanUpdate = (
421 ctx: CursorSessionContext,
422 payload: {
423 readonly explanation?: string | null;
424 readonly plan: ReadonlyArray<{
425 readonly step: string;
426 readonly status: "pending" | "inProgress" | "completed";
427 }>;
428 },
429 rawPayload: unknown,
430 source: "acp.jsonrpc" | "acp.cursor.extension",
431 method: string,
432 ) =>
433 Effect.gen(function* () {
434 const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
435 if (ctx.lastPlanFingerprint === fingerprint) {
436 return;
437 }
438 ctx.lastPlanFingerprint = fingerprint;
439 yield* offerRuntimeEvent(
440 makeAcpPlanUpdatedEvent({
441 stamp: yield* makeEventStamp(),
442 provider: PROVIDER,
443 threadId: ctx.threadId,
444 turnId: ctx.activeTurnId,
445 payload,
446 source,
447 method,
448 rawPayload,
449 }),
450 );
451 });
452
453 const requireSession = (
454 threadId: ThreadId,
455 ): Effect.Effect<CursorSessionContext, ProviderAdapterSessionNotFoundError> => {
456 const ctx = sessions.get(threadId);
457 if (!ctx || ctx.stopped) {
458 return Effect.fail(
459 new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),
460 );
461 }
462 return Effect.succeed(ctx);
463 };
464
465 const stopSessionInternal = (ctx: CursorSessionContext) =>
466 Effect.gen(function* () {
467 if (ctx.stopped) return;
468 ctx.stopped = true;
469 yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
470 yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
471 if (ctx.notificationFiber) {
472 yield* Fiber.interrupt(ctx.notificationFiber);
473 }
474 yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
475 sessions.delete(ctx.threadId);
476 yield* offerRuntimeEvent({
477 type: "session.exited",
478 ...(yield* makeEventStamp()),
479 provider: PROVIDER,
480 threadId: ctx.threadId,
481 payload: { exitKind: "graceful" },
482 });
483 });
484
485 const startSession: CursorAdapterShape["startSession"] = (input) =>
486 withThreadLock(
487 input.threadId,
488 Effect.gen(function* () {
489 if (input.provider !== undefined && input.provider !== PROVIDER) {
490 return yield* new ProviderAdapterValidationError({
491 provider: PROVIDER,
492 operation: "startSession",
493 issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
494 });
495 }
496 if (!input.cwd?.trim()) {
497 return yield* new ProviderAdapterValidationError({
498 provider: PROVIDER,
499 operation: "startSession",
500 issue: "cwd is required and must be non-empty.",
501 });
502 }
503
504 const cwd = path.resolve(input.cwd.trim());
505 const cursorModelSelection =
506 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
507 const existing = sessions.get(input.threadId);
508 if (existing && !existing.stopped) {
509 yield* stopSessionInternal(existing);
510 }
511
512 const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
513 const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
514 const sessionScope = yield* Scope.make("sequential");
515 let sessionScopeTransferred = false;
516 yield* Effect.addFinalizer(() =>
517 sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
518 );
519 let ctx!: CursorSessionContext;
520
521 const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
522 const acpNativeLoggers = makeAcpNativeLoggers({
523 nativeEventLogger,
524 provider: PROVIDER,
525 threadId: input.threadId,
526 });
527
528 // Resolve the CursorSettings used to spawn the ACP child. Production
529 // leaves `options.resolveSettings` undefined so we use the value
530 // captured at adapter construction — per-instance isolation is
531 // enforced by the hydration layer rebuilding this adapter whenever
532 // its config changes. Tests set `resolveSettings` to pull the latest
533 // snapshot from `ServerSettingsService` so that mid-suite
534 // `updateSettings({ providers: { cursor: { binaryPath } } })` calls
535 // actually take effect when the next session spawns.
536 const effectiveCursorSettings = options?.resolveSettings
537 ? yield* options.resolveSettings
538 : cursorSettings;
539
540 const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
541 const acp = yield* makeCursorAcpRuntime({
542 cursorSettings: effectiveCursorSettings,
543 ...(options?.environment ? { environment: options.environment } : {}),
544 childProcessSpawner,
545 cwd,
546 runtimeMode: input.runtimeMode,
547 ...(resumeSessionId ? { resumeSessionId } : {}),
548 clientInfo: { name: "t3-code", version: "0.0.0" },
549 ...(mcpSession
550 ? {
551 mcpServers: [
552 {
553 type: "http" as const,
554 name: "t3-code",
555 url: mcpSession.endpoint,
556 headers: [
557 {
558 name: "Authorization",
559 value: mcpSession.authorizationHeader,
560 },
561 ],
562 },
563 ],
564 }
565 : {}),
566 ...acpNativeLoggers,
567 }).pipe(
568 Effect.provideService(Crypto.Crypto, crypto),
569 Effect.provideService(Scope.Scope, sessionScope),
570 Effect.mapError(
571 (cause) =>
572 new ProviderAdapterProcessError({
573 provider: PROVIDER,
574 threadId: input.threadId,
575 detail: cause.message,
576 cause,
577 }),
578 ),
579 );
580 const started = yield* Effect.gen(function* () {
581 yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
582 mapExtensionFailure(
583 Effect.gen(function* () {
584 yield* logNative(
585 input.threadId,
586 "cursor/ask_question",
587 params,
588 "acp.cursor.extension",
589 );
590 const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
591 const runtimeRequestId = RuntimeRequestId.make(requestId);
592 const answers = yield* Deferred.make<ProviderUserInputAnswers>();
593 pendingUserInputs.set(requestId, { answers });
594 yield* offerRuntimeEvent({
595 type: "user-input.requested",
596 ...(yield* makeEventStamp()),
597 provider: PROVIDER,
598 threadId: input.threadId,
599 turnId: ctx?.activeTurnId,
600 requestId: runtimeRequestId,
601 payload: { questions: extractAskQuestions(params) },
602 raw: {
603 source: "acp.cursor.extension",
604 method: "cursor/ask_question",
605 payload: params,
606 },
607 });
608 const resolved = yield* Deferred.await(answers);
609 pendingUserInputs.delete(requestId);
610 yield* offerRuntimeEvent({
611 type: "user-input.resolved",
612 ...(yield* makeEventStamp()),
613 provider: PROVIDER,
614 threadId: input.threadId,
615 turnId: ctx?.activeTurnId,
616 requestId: runtimeRequestId,
617 payload: { answers: resolved },
618 });
619 return { answers: resolved };
620 }),
621 ),
622 );
623 yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
624 mapExtensionFailure(
625 Effect.gen(function* () {
626 yield* logNative(
627 input.threadId,
628 "cursor/create_plan",
629 params,
630 "acp.cursor.extension",
631 );
632 yield* offerRuntimeEvent({
633 type: "turn.proposed.completed",
634 ...(yield* makeEventStamp()),
635 provider: PROVIDER,
636 threadId: input.threadId,
637 turnId: ctx?.activeTurnId,
638 payload: { planMarkdown: extractPlanMarkdown(params) },
639 raw: {
640 source: "acp.cursor.extension",
641 method: "cursor/create_plan",
642 payload: params,
643 },
644 });
645 return { accepted: true } as const;
646 }),
647 ),
648 );
649 yield* acp.handleExtNotification(
650 "cursor/update_todos",
651 CursorUpdateTodosRequest,
652 (params) =>
653 mapExtensionFailure(
654 Effect.gen(function* () {
655 yield* logNative(
656 input.threadId,
657 "cursor/update_todos",
658 params,
659 "acp.cursor.extension",
660 );
661 if (ctx) {
662 yield* emitPlanUpdate(
663 ctx,
664 extractTodosAsPlan(params),
665 params,
666 "acp.cursor.extension",
667 "cursor/update_todos",
668 );
669 }
670 }),
671 ),
672 );
673 yield* acp.handleRequestPermission((params) =>
674 mapExtensionFailure(
675 Effect.gen(function* () {
676 yield* logNative(
677 input.threadId,
678 "session/request_permission",
679 params,
680 "acp.jsonrpc",
681 );
682 if (input.runtimeMode === "full-access") {
683 const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
684 if (autoApprovedOptionId !== undefined) {
685 return {
686 outcome: {
687 outcome: "selected" as const,
688 optionId: autoApprovedOptionId,
689 },
690 };
691 }
692 }
693 const permissionRequest = parsePermissionRequest(params);
694 const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
695 const runtimeRequestId = RuntimeRequestId.make(requestId);
696 const decision = yield* Deferred.make<ProviderApprovalDecision>();
697 pendingApprovals.set(requestId, {
698 decision,
699 kind: permissionRequest.kind,
700 });
701 yield* offerRuntimeEvent(
702 makeAcpRequestOpenedEvent({
703 stamp: yield* makeEventStamp(),
704 provider: PROVIDER,
705 threadId: input.threadId,
706 turnId: ctx?.activeTurnId,
707 requestId: runtimeRequestId,
708 permissionRequest,
709 detail:
710 permissionRequest.detail ??
711 encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
712 "[unserializable params]",
713 args: params,
714 source: "acp.jsonrpc",
715 method: "session/request_permission",
716 rawPayload: params,
717 }),
718 );
719 const resolved = yield* Deferred.await(decision);
720 pendingApprovals.delete(requestId);
721 yield* offerRuntimeEvent(
722 makeAcpRequestResolvedEvent({
723 stamp: yield* makeEventStamp(),
724 provider: PROVIDER,
725 threadId: input.threadId,
726 turnId: ctx?.activeTurnId,
727 requestId: runtimeRequestId,
728 permissionRequest,
729 decision: resolved,
730 }),
731 );
732 return {
733 outcome:
734 resolved === "cancel"
735 ? ({ outcome: "cancelled" } as const)
736 : {
737 outcome: "selected" as const,
738 optionId: acpPermissionOutcome(resolved),
739 },
740 };
741 }),
742 ),
743 );
744 return yield* acp.start();
745 }).pipe(
746 Effect.mapError((error) =>
747 mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
748 ),
749 );
750
751 yield* applyRequestedSessionConfiguration({
752 runtime: acp,
753 runtimeMode: input.runtimeMode,
754 interactionMode: undefined,
755 modelSelection: cursorModelSelection,
756 mapError: ({ cause, method }) =>
757 mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
758 });
759
760 const now = yield* nowIso;
761 const session: ProviderSession = {
762 provider: PROVIDER,
763 providerInstanceId: boundInstanceId,
764 status: "ready",
765 runtimeMode: input.runtimeMode,
766 cwd,
767 model: cursorModelSelection?.model,
768 threadId: input.threadId,
769 resumeCursor: {
770 schemaVersion: CURSOR_RESUME_VERSION,
771 sessionId: started.sessionId,
772 },
773 createdAt: now,
774 updatedAt: now,
775 };
776
777 ctx = {
778 threadId: input.threadId,
779 session,
780 scope: sessionScope,
781 acp,
782 notificationFiber: undefined,
783 pendingApprovals,
784 pendingUserInputs,
785 turns: [],
786 lastPlanFingerprint: undefined,
787 activeTurnId: undefined,
788 cursorSkillNames: undefined,
789 promptsInFlight: 0,
790 stopped: false,
791 };
792
793 const nf = yield* Stream.runDrain(
794 Stream.mapEffect(acp.getEvents(), (event) =>
795 Effect.gen(function* () {
796 switch (event._tag) {
797 case "EventStreamBarrier":
798 yield* Deferred.succeed(event.acknowledge, undefined);
799 return;
800 case "ModeChanged":
801 return;
802 case "AssistantItemStarted":
803 yield* offerRuntimeEvent(
804 makeAcpAssistantItemEvent({
805 stamp: yield* makeEventStamp(),
806 provider: PROVIDER,
807 threadId: ctx.threadId,
808 turnId: ctx.activeTurnId,
809 itemId: event.itemId,
810 lifecycle: "item.started",
811 }),
812 );
813 return;
814 case "AssistantItemCompleted":
815 yield* offerRuntimeEvent(
816 makeAcpAssistantItemEvent({
817 stamp: yield* makeEventStamp(),
818 provider: PROVIDER,
819 threadId: ctx.threadId,
820 turnId: ctx.activeTurnId,
821 itemId: event.itemId,
822 lifecycle: "item.completed",
823 }),
824 );
825 return;
826 case "PlanUpdated":
827 yield* logNative(
828 ctx.threadId,
829 "session/update",
830 event.rawPayload,
831 "acp.jsonrpc",
832 );
833 yield* emitPlanUpdate(
834 ctx,
835 event.payload,
836 event.rawPayload,
837 "acp.jsonrpc",
838 "session/update",
839 );
840 return;
841 case "ToolCallUpdated":
842 yield* logNative(
843 ctx.threadId,
844 "session/update",
845 event.rawPayload,
846 "acp.jsonrpc",
847 );
848 yield* offerRuntimeEvent(
849 makeAcpToolCallEvent({
850 stamp: yield* makeEventStamp(),
851 provider: PROVIDER,
852 threadId: ctx.threadId,
853 turnId: ctx.activeTurnId,
854 toolCall: event.toolCall,
855 rawPayload: event.rawPayload,
856 }),
857 );
858 return;
859 case "ContentDelta":
860 yield* logNative(
861 ctx.threadId,
862 "session/update",
863 event.rawPayload,
864 "acp.jsonrpc",
865 );
866 yield* offerRuntimeEvent(
867 makeAcpContentDeltaEvent({
868 stamp: yield* makeEventStamp(),
869 provider: PROVIDER,
870 threadId: ctx.threadId,
871 turnId: ctx.activeTurnId,
872 ...(event.itemId ? { itemId: event.itemId } : {}),
873 text: event.text,
874 rawPayload: event.rawPayload,
875 }),
876 );
877 return;
878 }
879 }),
880 ),
881 ).pipe(
882 Effect.catch((cause) =>
883 Effect.logError("Failed to process Cursor runtime notification.", { cause }),
884 ),
885 // Fork into the session scope, not the calling fiber. `forkChild`
886 // makes this a child of `startSession`, and Effect interrupts a
887 // fiber's children when it completes, so the consumer died as soon
888 // as `startSession` returned and every later notification was
889 // dropped. The scope is created, stored on the context and closed
890 // on teardown already; only the fork target was wrong.
891 Effect.forkIn(ctx.scope),
892 );
893
894 ctx.notificationFiber = nf;
895 sessions.set(input.threadId, ctx);
896 sessionScopeTransferred = true;
897
898 yield* offerRuntimeEvent({
899 type: "session.started",
900 ...(yield* makeEventStamp()),
901 provider: PROVIDER,
902 threadId: input.threadId,
903 payload: { resume: started.initializeResult },
904 });
905 yield* offerRuntimeEvent({
906 type: "session.state.changed",
907 ...(yield* makeEventStamp()),
908 provider: PROVIDER,
909 threadId: input.threadId,
910 payload: { state: "ready", reason: "Cursor ACP session ready" },
911 });
912 yield* offerRuntimeEvent({
913 type: "thread.started",
914 ...(yield* makeEventStamp()),
915 provider: PROVIDER,
916 threadId: input.threadId,
917 payload: { providerThreadId: started.sessionId },
918 });
919
920 return session;
921 }).pipe(Effect.scoped),
922 );
923
924 const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
925 Effect.gen(function* () {
926 const ctx = yield* requireSession(input.threadId);
927 // A sendTurn while a prompt is in flight is a steer: the agent folds
928 // the new prompt into the ongoing work, so the active turn id is
929 // reused instead of opening a new turn.
930 const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
931 const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
932 // Count this prompt immediately so a superseded in-flight prompt
933 // resolving from here on does not settle the turn; the matching
934 // decrement is the `ensuring` below.
935 ctx.promptsInFlight += 1;
936
937 return yield* Effect.gen(function* () {
938 const turnModelSelection =
939 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
940 const model = turnModelSelection?.model ?? ctx.session.model;
941 const resolvedModel = resolveCursorAcpBaseModelId(model);
942 yield* applyRequestedSessionConfiguration({
943 runtime: ctx.acp,
944 runtimeMode: ctx.session.runtimeMode,
945 interactionMode: input.interactionMode,
946 modelSelection:
947 model === undefined
948 ? undefined
949 : {
950 model,
951 options: turnModelSelection?.options,
952 },
953 mapError: ({ cause, method }) =>
954 mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
955 });
956 ctx.activeTurnId = turnId;
957 if (steeringTurnId === undefined) {
958 ctx.lastPlanFingerprint = undefined;
959 }
960 ctx.session = {
961 ...ctx.session,
962 activeTurnId: turnId,
963 updatedAt: yield* nowIso,
964 };
965
966 if (steeringTurnId === undefined) {
967 yield* offerRuntimeEvent({
968 type: "turn.started",
969 ...(yield* makeEventStamp()),
970 provider: PROVIDER,
971 threadId: input.threadId,
972 turnId,
973 payload: { model: resolvedModel },
974 });
975 }
976
977 const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
978 const rawPrompt = input.input?.trim() ?? "";
979 if (rawPrompt) {
980 let cursorSkillNames = ctx.cursorSkillNames;
981 if (hasCursorSkillMention(rawPrompt) && cursorSkillNames === undefined) {
982 const skills = yield* discoverCursorSkills(
983 ctx.session.cwd,
984 options?.environment,
985 ).pipe(
986 Effect.provideService(FileSystem.FileSystem, fileSystem),
987 Effect.provideService(Path.Path, path),
988 );
989 cursorSkillNames = new Set(
990 skills
991 .filter((skill) => skill.enabled && skill.userInvocable !== false)
992 .map((skill) => skill.name),
993 );
994 ctx.cursorSkillNames = cursorSkillNames;
995 }
996 const prompt = cursorSkillNames
997 ? rewriteCursorSkillMentions(rawPrompt, cursorSkillNames)
998 : rawPrompt;
999 promptParts.push({ type: "text", text: prompt });
1000 }
1001 if (input.attachments && input.attachments.length > 0) {
1002 for (const attachment of input.attachments) {
1003 // Cursor ingests images only. Generic files reach the agent
1004 // through the path line ProviderService puts in the prompt.
1005 if (attachment.type !== "image") {
1006 continue;
1007 }
1008 const attachmentPath = resolveAttachmentPath({
1009 attachmentsDir: serverConfig.attachmentsDir,
1010 attachment,
1011 });
1012 if (!attachmentPath) {
1013 return yield* new ProviderAdapterRequestError({
1014 provider: PROVIDER,
1015 method: "session/prompt",
1016 detail: `Invalid attachment id '${attachment.id}'.`,
1017 });
1018 }
1019 const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
1020 Effect.mapError(
1021 (cause) =>
1022 new ProviderAdapterRequestError({
1023 provider: PROVIDER,
1024 method: "session/prompt",
1025 detail: cause.message,
1026 cause,
1027 }),
1028 ),
1029 );
1030 promptParts.push({
1031 type: "image",
1032 data: Buffer.from(bytes).toString("base64"),
1033 mimeType: attachment.mimeType,
1034 });
1035 }
1036 }
1037
1038 if (promptParts.length === 0) {
1039 return yield* new ProviderAdapterValidationError({
1040 provider: PROVIDER,
1041 operation: "sendTurn",
1042 issue: "Turn requires non-empty text or attachments.",
1043 });
1044 }
1045
1046 const result = yield* ctx.acp
1047 .prompt({
1048 prompt: promptParts,
1049 })
1050 .pipe(
1051 Effect.mapError((error) =>
1052 mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
1053 ),
1054 );
1055
1056 const turnRecord = ctx.turns.find((turn) => turn.id === turnId);
1057 if (turnRecord) {
1058 turnRecord.items.push({ prompt: promptParts, result });
1059 } else {
1060 ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
1061 }
1062 ctx.session = {
1063 ...ctx.session,
1064 activeTurnId: turnId,
1065 updatedAt: yield* nowIso,
1066 model: resolvedModel,
1067 };
1068
1069 // Only the last remaining prompt settles the turn — a steer-
1070 // superseded prompt resolving (usually cancelled) while another is
1071 // in flight or pending must leave the merged turn running.
1072 if (ctx.promptsInFlight === 1) {
1073 yield* offerRuntimeEvent({
1074 type: "turn.completed",
1075 ...(yield* makeEventStamp()),
1076 provider: PROVIDER,
1077 threadId: input.threadId,
1078 turnId,
1079 payload: {
1080 state: result.stopReason === "cancelled" ? "cancelled" : "completed",
1081 stopReason: result.stopReason ?? null,
1082 },
1083 });
1084 }
1085
1086 return {
1087 threadId: input.threadId,
1088 turnId,
1089 resumeCursor: ctx.session.resumeCursor,
1090 };
1091 }).pipe(
1092 Effect.ensuring(
1093 Effect.sync(() => {
1094 ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
1095 }),
1096 ),
1097 );
1098 });
1099
1100 const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
1101 Effect.gen(function* () {
1102 const ctx = yield* requireSession(threadId);
1103 yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
1104 yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
1105 yield* Effect.ignore(
1106 ctx.acp.cancel.pipe(
1107 Effect.mapError((error) =>
1108 mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
1109 ),
1110 ),
1111 );
1112 });
1113
1114 const respondToRequest: CursorAdapterShape["respondToRequest"] = (
1115 threadId,
1116 requestId,
1117 decision,
1118 ) =>
1119 Effect.gen(function* () {
1120 const ctx = yield* requireSession(threadId);
1121 const pending = ctx.pendingApprovals.get(requestId);
1122 if (!pending) {
1123 return yield* new ProviderAdapterRequestError({
1124 provider: PROVIDER,
1125 method: "session/request_permission",
1126 detail: `Unknown pending approval request: ${requestId}`,
1127 });
1128 }
1129 yield* Deferred.succeed(pending.decision, decision);
1130 });
1131
1132 const respondToUserInput: CursorAdapterShape["respondToUserInput"] = (
1133 threadId,
1134 requestId,
1135 answers,
1136 ) =>
1137 Effect.gen(function* () {
1138 const ctx = yield* requireSession(threadId);
1139 const pending = ctx.pendingUserInputs.get(requestId);
1140 if (!pending) {
1141 return yield* new ProviderAdapterRequestError({
1142 provider: PROVIDER,
1143 method: "cursor/ask_question",
1144 detail: `Unknown pending user-input request: ${requestId}`,
1145 });
1146 }
1147 yield* Deferred.succeed(pending.answers, answers);
1148 });
1149
1150 const readThread: CursorAdapterShape["readThread"] = (threadId) =>
1151 Effect.gen(function* () {
1152 const ctx = yield* requireSession(threadId);
1153 return { threadId, turns: ctx.turns };
1154 });
1155
1156 const rollbackThread: CursorAdapterShape["rollbackThread"] = (threadId, numTurns) =>
1157 Effect.gen(function* () {
1158 const ctx = yield* requireSession(threadId);
1159 if (!Number.isInteger(numTurns) || numTurns < 1) {
1160 return yield* new ProviderAdapterValidationError({
1161 provider: PROVIDER,
1162 operation: "rollbackThread",
1163 issue: "numTurns must be an integer >= 1.",
1164 });
1165 }
1166 const nextLength = Math.max(0, ctx.turns.length - numTurns);
1167 ctx.turns.splice(nextLength);
1168 return { threadId, turns: ctx.turns };
1169 });
1170
1171 const stopSession: CursorAdapterShape["stopSession"] = (threadId) =>
1172 withThreadLock(
1173 threadId,
1174 Effect.gen(function* () {
1175 const ctx = yield* requireSession(threadId);
1176 yield* stopSessionInternal(ctx);
1177 }),
1178 );
1179
1180 const listSessions: CursorAdapterShape["listSessions"] = () =>
1181 Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
1182
1183 const hasSession: CursorAdapterShape["hasSession"] = (threadId) =>
1184 Effect.sync(() => {
1185 const c = sessions.get(threadId);
1186 return c !== undefined && !c.stopped;
1187 });
1188
1189 const stopAll: CursorAdapterShape["stopAll"] = () =>
1190 Effect.forEach(sessions.values(), stopSessionInternal, { discard: true });
1191
1192 yield* Effect.addFinalizer(() =>
1193 Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
1194 Effect.catch((cause) =>
1195 Effect.logError("Failed to emit Cursor session shutdown event.", { cause }),
1196 ),
1197 Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
1198 Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
1199 ),
1200 );
1201
1202 const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
1203
1204 return {
1205 provider: PROVIDER,
1206 capabilities: { sessionModelSwitch: "in-session" },
1207 startSession,
1208 sendTurn,
1209 interruptTurn,
1210 readThread,
1211 rollbackThread,
1212 respondToRequest,
1213 respondToUserInput,
1214 stopSession,
1215 listSessions,
1216 hasSession,
1217 stopAll,
1218 streamEvents,
1219 } satisfies CursorAdapterShape;
1220 });
1221}