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.UnknownFromJsonString);
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(Scope.Scope, sessionScope),
562 Effect.mapError(
563 (cause) =>
564 new ProviderAdapterProcessError({
565 provider: PROVIDER,
566 threadId: input.threadId,
567 detail: cause.message,
568 cause,
569 }),
570 ),
571 );
572 const started = yield* Effect.gen(function* () {
573 yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
574 mapExtensionFailure(
575 Effect.gen(function* () {
576 yield* logNative(
577 input.threadId,
578 "cursor/ask_question",
579 params,
580 "acp.cursor.extension",
581 );
582 const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
583 const runtimeRequestId = RuntimeRequestId.make(requestId);
584 const answers = yield* Deferred.make<ProviderUserInputAnswers>();
585 pendingUserInputs.set(requestId, { answers });
586 yield* offerRuntimeEvent({
587 type: "user-input.requested",
588 ...(yield* makeEventStamp()),
589 provider: PROVIDER,
590 threadId: input.threadId,
591 turnId: ctx?.activeTurnId,
592 requestId: runtimeRequestId,
593 payload: { questions: extractAskQuestions(params) },
594 raw: {
595 source: "acp.cursor.extension",
596 method: "cursor/ask_question",
597 payload: params,
598 },
599 });
600 const resolved = yield* Deferred.await(answers);
601 pendingUserInputs.delete(requestId);
602 yield* offerRuntimeEvent({
603 type: "user-input.resolved",
604 ...(yield* makeEventStamp()),
605 provider: PROVIDER,
606 threadId: input.threadId,
607 turnId: ctx?.activeTurnId,
608 requestId: runtimeRequestId,
609 payload: { answers: resolved },
610 });
611 return { answers: resolved };
612 }),
613 ),
614 );
615 yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
616 mapExtensionFailure(
617 Effect.gen(function* () {
618 yield* logNative(
619 input.threadId,
620 "cursor/create_plan",
621 params,
622 "acp.cursor.extension",
623 );
624 yield* offerRuntimeEvent({
625 type: "turn.proposed.completed",
626 ...(yield* makeEventStamp()),
627 provider: PROVIDER,
628 threadId: input.threadId,
629 turnId: ctx?.activeTurnId,
630 payload: { planMarkdown: extractPlanMarkdown(params) },
631 raw: {
632 source: "acp.cursor.extension",
633 method: "cursor/create_plan",
634 payload: params,
635 },
636 });
637 return { accepted: true } as const;
638 }),
639 ),
640 );
641 yield* acp.handleExtNotification(
642 "cursor/update_todos",
643 CursorUpdateTodosRequest,
644 (params) =>
645 mapExtensionFailure(
646 Effect.gen(function* () {
647 yield* logNative(
648 input.threadId,
649 "cursor/update_todos",
650 params,
651 "acp.cursor.extension",
652 );
653 if (ctx) {
654 yield* emitPlanUpdate(
655 ctx,
656 extractTodosAsPlan(params),
657 params,
658 "acp.cursor.extension",
659 "cursor/update_todos",
660 );
661 }
662 }),
663 ),
664 );
665 yield* acp.handleRequestPermission((params) =>
666 mapExtensionFailure(
667 Effect.gen(function* () {
668 yield* logNative(
669 input.threadId,
670 "session/request_permission",
671 params,
672 "acp.jsonrpc",
673 );
674 if (input.runtimeMode === "full-access") {
675 const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
676 if (autoApprovedOptionId !== undefined) {
677 return {
678 outcome: {
679 outcome: "selected" as const,
680 optionId: autoApprovedOptionId,
681 },
682 };
683 }
684 }
685 const permissionRequest = parsePermissionRequest(params);
686 const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
687 const runtimeRequestId = RuntimeRequestId.make(requestId);
688 const decision = yield* Deferred.make<ProviderApprovalDecision>();
689 pendingApprovals.set(requestId, {
690 decision,
691 kind: permissionRequest.kind,
692 });
693 yield* offerRuntimeEvent(
694 makeAcpRequestOpenedEvent({
695 stamp: yield* makeEventStamp(),
696 provider: PROVIDER,
697 threadId: input.threadId,
698 turnId: ctx?.activeTurnId,
699 requestId: runtimeRequestId,
700 permissionRequest,
701 detail:
702 permissionRequest.detail ??
703 encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
704 "[unserializable params]",
705 args: params,
706 source: "acp.jsonrpc",
707 method: "session/request_permission",
708 rawPayload: params,
709 }),
710 );
711 const resolved = yield* Deferred.await(decision);
712 pendingApprovals.delete(requestId);
713 yield* offerRuntimeEvent(
714 makeAcpRequestResolvedEvent({
715 stamp: yield* makeEventStamp(),
716 provider: PROVIDER,
717 threadId: input.threadId,
718 turnId: ctx?.activeTurnId,
719 requestId: runtimeRequestId,
720 permissionRequest,
721 decision: resolved,
722 }),
723 );
724 return {
725 outcome:
726 resolved === "cancel"
727 ? ({ outcome: "cancelled" } as const)
728 : {
729 outcome: "selected" as const,
730 optionId: acpPermissionOutcome(resolved),
731 },
732 };
733 }),
734 ),
735 );
736 return yield* acp.start();
737 }).pipe(
738 Effect.mapError((error) =>
739 mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
740 ),
741 );
742
743 yield* applyRequestedSessionConfiguration({
744 runtime: acp,
745 runtimeMode: input.runtimeMode,
746 interactionMode: undefined,
747 modelSelection: cursorModelSelection,
748 mapError: ({ cause, method }) =>
749 mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
750 });
751
752 const now = yield* nowIso;
753 const session: ProviderSession = {
754 provider: PROVIDER,
755 providerInstanceId: boundInstanceId,
756 status: "ready",
757 runtimeMode: input.runtimeMode,
758 cwd,
759 model: cursorModelSelection?.model,
760 threadId: input.threadId,
761 resumeCursor: {
762 schemaVersion: CURSOR_RESUME_VERSION,
763 sessionId: started.sessionId,
764 },
765 createdAt: now,
766 updatedAt: now,
767 };
768
769 ctx = {
770 threadId: input.threadId,
771 session,
772 scope: sessionScope,
773 acp,
774 notificationFiber: undefined,
775 pendingApprovals,
776 pendingUserInputs,
777 turns: [],
778 lastPlanFingerprint: undefined,
779 activeTurnId: undefined,
780 promptsInFlight: 0,
781 stopped: false,
782 };
783
784 const nf = yield* Stream.runDrain(
785 Stream.mapEffect(acp.getEvents(), (event) =>
786 Effect.gen(function* () {
787 switch (event._tag) {
788 case "ModeChanged":
789 return;
790 case "AssistantItemStarted":
791 yield* offerRuntimeEvent(
792 makeAcpAssistantItemEvent({
793 stamp: yield* makeEventStamp(),
794 provider: PROVIDER,
795 threadId: ctx.threadId,
796 turnId: ctx.activeTurnId,
797 itemId: event.itemId,
798 lifecycle: "item.started",
799 }),
800 );
801 return;
802 case "AssistantItemCompleted":
803 yield* offerRuntimeEvent(
804 makeAcpAssistantItemEvent({
805 stamp: yield* makeEventStamp(),
806 provider: PROVIDER,
807 threadId: ctx.threadId,
808 turnId: ctx.activeTurnId,
809 itemId: event.itemId,
810 lifecycle: "item.completed",
811 }),
812 );
813 return;
814 case "PlanUpdated":
815 yield* logNative(
816 ctx.threadId,
817 "session/update",
818 event.rawPayload,
819 "acp.jsonrpc",
820 );
821 yield* emitPlanUpdate(
822 ctx,
823 event.payload,
824 event.rawPayload,
825 "acp.jsonrpc",
826 "session/update",
827 );
828 return;
829 case "ToolCallUpdated":
830 yield* logNative(
831 ctx.threadId,
832 "session/update",
833 event.rawPayload,
834 "acp.jsonrpc",
835 );
836 yield* offerRuntimeEvent(
837 makeAcpToolCallEvent({
838 stamp: yield* makeEventStamp(),
839 provider: PROVIDER,
840 threadId: ctx.threadId,
841 turnId: ctx.activeTurnId,
842 toolCall: event.toolCall,
843 rawPayload: event.rawPayload,
844 }),
845 );
846 return;
847 case "ContentDelta":
848 yield* logNative(
849 ctx.threadId,
850 "session/update",
851 event.rawPayload,
852 "acp.jsonrpc",
853 );
854 yield* offerRuntimeEvent(
855 makeAcpContentDeltaEvent({
856 stamp: yield* makeEventStamp(),
857 provider: PROVIDER,
858 threadId: ctx.threadId,
859 turnId: ctx.activeTurnId,
860 ...(event.itemId ? { itemId: event.itemId } : {}),
861 text: event.text,
862 rawPayload: event.rawPayload,
863 }),
864 );
865 return;
866 }
867 }),
868 ),
869 ).pipe(
870 Effect.catch((cause) =>
871 Effect.logError("Failed to process Cursor runtime notification.", { cause }),
872 ),
873 Effect.forkChild,
874 );
875
876 ctx.notificationFiber = nf;
877 sessions.set(input.threadId, ctx);
878 sessionScopeTransferred = true;
879
880 yield* offerRuntimeEvent({
881 type: "session.started",
882 ...(yield* makeEventStamp()),
883 provider: PROVIDER,
884 threadId: input.threadId,
885 payload: { resume: started.initializeResult },
886 });
887 yield* offerRuntimeEvent({
888 type: "session.state.changed",
889 ...(yield* makeEventStamp()),
890 provider: PROVIDER,
891 threadId: input.threadId,
892 payload: { state: "ready", reason: "Cursor ACP session ready" },
893 });
894 yield* offerRuntimeEvent({
895 type: "thread.started",
896 ...(yield* makeEventStamp()),
897 provider: PROVIDER,
898 threadId: input.threadId,
899 payload: { providerThreadId: started.sessionId },
900 });
901
902 return session;
903 }).pipe(Effect.scoped),
904 );
905
906 const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
907 Effect.gen(function* () {
908 const ctx = yield* requireSession(input.threadId);
909 // A sendTurn while a prompt is in flight is a steer: the agent folds
910 // the new prompt into the ongoing work, so the active turn id is
911 // reused instead of opening a new turn.
912 const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
913 const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
914 // Count this prompt immediately so a superseded in-flight prompt
915 // resolving from here on does not settle the turn; the matching
916 // decrement is the `ensuring` below.
917 ctx.promptsInFlight += 1;
918
919 return yield* Effect.gen(function* () {
920 const turnModelSelection =
921 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
922 const model = turnModelSelection?.model ?? ctx.session.model;
923 const resolvedModel = resolveCursorAcpBaseModelId(model);
924 yield* applyRequestedSessionConfiguration({
925 runtime: ctx.acp,
926 runtimeMode: ctx.session.runtimeMode,
927 interactionMode: input.interactionMode,
928 modelSelection:
929 model === undefined
930 ? undefined
931 : {
932 model,
933 options: turnModelSelection?.options,
934 },
935 mapError: ({ cause, method }) =>
936 mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
937 });
938 ctx.activeTurnId = turnId;
939 if (steeringTurnId === undefined) {
940 ctx.lastPlanFingerprint = undefined;
941 }
942 ctx.session = {
943 ...ctx.session,
944 activeTurnId: turnId,
945 updatedAt: yield* nowIso,
946 };
947
948 if (steeringTurnId === undefined) {
949 yield* offerRuntimeEvent({
950 type: "turn.started",
951 ...(yield* makeEventStamp()),
952 provider: PROVIDER,
953 threadId: input.threadId,
954 turnId,
955 payload: { model: resolvedModel },
956 });
957 }
958
959 const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
960 if (input.input?.trim()) {
961 promptParts.push({ type: "text", text: input.input.trim() });
962 }
963 if (input.attachments && input.attachments.length > 0) {
964 for (const attachment of input.attachments) {
965 const attachmentPath = resolveAttachmentPath({
966 attachmentsDir: serverConfig.attachmentsDir,
967 attachment,
968 });
969 if (!attachmentPath) {
970 return yield* new ProviderAdapterRequestError({
971 provider: PROVIDER,
972 method: "session/prompt",
973 detail: `Invalid attachment id '${attachment.id}'.`,
974 });
975 }
976 const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
977 Effect.mapError(
978 (cause) =>
979 new ProviderAdapterRequestError({
980 provider: PROVIDER,
981 method: "session/prompt",
982 detail: cause.message,
983 cause,
984 }),
985 ),
986 );
987 promptParts.push({
988 type: "image",
989 data: Buffer.from(bytes).toString("base64"),
990 mimeType: attachment.mimeType,
991 });
992 }
993 }
994
995 if (promptParts.length === 0) {
996 return yield* new ProviderAdapterValidationError({
997 provider: PROVIDER,
998 operation: "sendTurn",
999 issue: "Turn requires non-empty text or attachments.",
1000 });
1001 }
1002
1003 const result = yield* ctx.acp
1004 .prompt({
1005 prompt: promptParts,
1006 })
1007 .pipe(
1008 Effect.mapError((error) =>
1009 mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
1010 ),
1011 );
1012
1013 const turnRecord = ctx.turns.find((turn) => turn.id === turnId);
1014 if (turnRecord) {
1015 turnRecord.items.push({ prompt: promptParts, result });
1016 } else {
1017 ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
1018 }
1019 ctx.session = {
1020 ...ctx.session,
1021 activeTurnId: turnId,
1022 updatedAt: yield* nowIso,
1023 model: resolvedModel,
1024 };
1025
1026 // Only the last remaining prompt settles the turn — a steer-
1027 // superseded prompt resolving (usually cancelled) while another is
1028 // in flight or pending must leave the merged turn running.
1029 if (ctx.promptsInFlight === 1) {
1030 yield* offerRuntimeEvent({
1031 type: "turn.completed",
1032 ...(yield* makeEventStamp()),
1033 provider: PROVIDER,
1034 threadId: input.threadId,
1035 turnId,
1036 payload: {
1037 state: result.stopReason === "cancelled" ? "cancelled" : "completed",
1038 stopReason: result.stopReason ?? null,
1039 },
1040 });
1041 }
1042
1043 return {
1044 threadId: input.threadId,
1045 turnId,
1046 resumeCursor: ctx.session.resumeCursor,
1047 };
1048 }).pipe(
1049 Effect.ensuring(
1050 Effect.sync(() => {
1051 ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
1052 }),
1053 ),
1054 );
1055 });
1056
1057 const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
1058 Effect.gen(function* () {
1059 const ctx = yield* requireSession(threadId);
1060 yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
1061 yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
1062 yield* Effect.ignore(
1063 ctx.acp.cancel.pipe(
1064 Effect.mapError((error) =>
1065 mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
1066 ),
1067 ),
1068 );
1069 });
1070
1071 const respondToRequest: CursorAdapterShape["respondToRequest"] = (
1072 threadId,
1073 requestId,
1074 decision,
1075 ) =>
1076 Effect.gen(function* () {
1077 const ctx = yield* requireSession(threadId);
1078 const pending = ctx.pendingApprovals.get(requestId);
1079 if (!pending) {
1080 return yield* new ProviderAdapterRequestError({
1081 provider: PROVIDER,
1082 method: "session/request_permission",
1083 detail: `Unknown pending approval request: ${requestId}`,
1084 });
1085 }
1086 yield* Deferred.succeed(pending.decision, decision);
1087 });
1088
1089 const respondToUserInput: CursorAdapterShape["respondToUserInput"] = (
1090 threadId,
1091 requestId,
1092 answers,
1093 ) =>
1094 Effect.gen(function* () {
1095 const ctx = yield* requireSession(threadId);
1096 const pending = ctx.pendingUserInputs.get(requestId);
1097 if (!pending) {
1098 return yield* new ProviderAdapterRequestError({
1099 provider: PROVIDER,
1100 method: "cursor/ask_question",
1101 detail: `Unknown pending user-input request: ${requestId}`,
1102 });
1103 }
1104 yield* Deferred.succeed(pending.answers, answers);
1105 });
1106
1107 const readThread: CursorAdapterShape["readThread"] = (threadId) =>
1108 Effect.gen(function* () {
1109 const ctx = yield* requireSession(threadId);
1110 return { threadId, turns: ctx.turns };
1111 });
1112
1113 const rollbackThread: CursorAdapterShape["rollbackThread"] = (threadId, numTurns) =>
1114 Effect.gen(function* () {
1115 const ctx = yield* requireSession(threadId);
1116 if (!Number.isInteger(numTurns) || numTurns < 1) {
1117 return yield* new ProviderAdapterValidationError({
1118 provider: PROVIDER,
1119 operation: "rollbackThread",
1120 issue: "numTurns must be an integer >= 1.",
1121 });
1122 }
1123 const nextLength = Math.max(0, ctx.turns.length - numTurns);
1124 ctx.turns.splice(nextLength);
1125 return { threadId, turns: ctx.turns };
1126 });
1127
1128 const stopSession: CursorAdapterShape["stopSession"] = (threadId) =>
1129 withThreadLock(
1130 threadId,
1131 Effect.gen(function* () {
1132 const ctx = yield* requireSession(threadId);
1133 yield* stopSessionInternal(ctx);
1134 }),
1135 );
1136
1137 const listSessions: CursorAdapterShape["listSessions"] = () =>
1138 Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
1139
1140 const hasSession: CursorAdapterShape["hasSession"] = (threadId) =>
1141 Effect.sync(() => {
1142 const c = sessions.get(threadId);
1143 return c !== undefined && !c.stopped;
1144 });
1145
1146 const stopAll: CursorAdapterShape["stopAll"] = () =>
1147 Effect.forEach(sessions.values(), stopSessionInternal, { discard: true });
1148
1149 yield* Effect.addFinalizer(() =>
1150 Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
1151 Effect.catch((cause) =>
1152 Effect.logError("Failed to emit Cursor session shutdown event.", { cause }),
1153 ),
1154 Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
1155 Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
1156 ),
1157 );
1158
1159 const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
1160
1161 return {
1162 provider: PROVIDER,
1163 capabilities: { sessionModelSwitch: "in-session" },
1164 startSession,
1165 sendTurn,
1166 interruptTurn,
1167 readThread,
1168 rollbackThread,
1169 respondToRequest,
1170 respondToUserInput,
1171 stopSession,
1172 listSessions,
1173 hasSession,
1174 stopAll,
1175 streamEvents,
1176 } satisfies CursorAdapterShape;
1177 });
1178}