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