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