Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CursorAdapter.ts

1,286 lines48.4 KB

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