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