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