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