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

CursorAdapter.ts

1,247 lines46.0 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 DateTime from "effect/DateTime";
25import * as Crypto from "effect/Crypto";
26import * as Deferred from "effect/Deferred";
27import * as Effect from "effect/Effect";
28import * as Exit from "effect/Exit";
29import * as Fiber from "effect/Fiber";
30import * as FileSystem from "effect/FileSystem";
31import * as Option from "effect/Option";
32import * as Path from "effect/Path";
33import * as PubSub from "effect/PubSub";
34import * as Schema from "effect/Schema";
35import * as Scope from "effect/Scope";
36import * as Semaphore from "effect/Semaphore";
37import * as Stream from "effect/Stream";
38import * as SynchronizedRef from "effect/SynchronizedRef";
39import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
40import * as EffectAcpErrors from "effect-acp/errors";
41import type * as EffectAcpSchema from "effect-acp/schema";
42​
43import { resolveAttachmentPath } from "../../attachmentStore.ts";
44import { ServerConfig } from "../../config.ts";
45import { buildRuntimeInstructions } from "../RuntimeInstructions.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 { CursorTransportFailure } from "../acp/CursorTransportFailure.ts";
71import {
72 CursorAskQuestionRequest,
73 CursorCreatePlanRequest,
74 CursorUpdateTodosRequest,
75 extractAskQuestions,
76 extractPlanMarkdown,
77 extractTodosAsPlan,
78} from "../acp/CursorAcpExtension.ts";
79import { type CursorAdapterShape } from "../Services/CursorAdapter.ts";
80import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts";
81import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
82import {
83 discoverCursorSkills,
84 hasCursorSkillMention,
85 rewriteCursorSkillMentions,
86} from "../Drivers/CursorSkills.ts";
87const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
88​
89const PROVIDER = ProviderDriverKind.make("cursor");
90const CURSOR_RESUME_VERSION = 1 as const;
91const ACP_PLAN_MODE_ALIASES = ["plan", "architect"];
92const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"];
93const ACP_APPROVAL_MODE_ALIASES = ["ask"];
94​
95function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
96 const result = encodeUnknownJsonStringExit(input);
97 return Exit.isSuccess(result) ? result.value : undefined;
99​
100export interface CursorAdapterLiveOptions {
101 readonly environment?: NodeJS.ProcessEnv;
102 readonly nativeEventLogPath?: string;
103 readonly nativeEventLogger?: EventNdjsonLogger;
104 /**
105 * Selections are honored when `modelSelection.instanceId` matches this value.
106 * Defaults to the legacy built-in instance id (`cursor`).
107 */
108 readonly instanceId?: ProviderInstanceId;
109 /**
110 * Optional per-session settings resolver. When provided the adapter yields
111 * this effect at the start of every session and uses the result instead of
112 * the `cursorSettings` captured at construction.
113 *
114 * Production instances bind settings to the instance scope (the hydration
115 * layer rebuilds the adapter on config change) and leave this undefined.
116 * Test suites that mutate `ServerSettingsService` mid-flight — e.g. to
117 * swap `binaryPath` to a mock ACP wrapper — pass a resolver that reads
118 * the latest snapshot so the closure isn't stale.
119 */
120 readonly resolveSettings?: Effect.Effect<CursorSettings>;
122​
123interface PendingApproval {
124 readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
125 readonly kind: string | "unknown";
127​
128interface PendingUserInput {
129 readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
131​
132interface CursorSessionContext {
133 readonly threadId: ThreadId;
134 session: ProviderSession;
135 readonly scope: Scope.Closeable;
136 readonly acp: AcpSessionRuntime.AcpSessionRuntime["Service"];
137 notificationFiber: Fiber.Fiber<void, never> | undefined;
138 readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
139 readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
140 readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
141 lastPlanFingerprint: string | undefined;
142 activeTurnId: TurnId | undefined;
143 cursorSkillNames: ReadonlySet<string> | undefined;
144 /** Number of sendTurn prompts currently in flight or being prepared.
145 * >0 means a turn is actively running, so a new sendTurn is a steer that
146 * continues it, and only the last remaining prompt settles the turn. */
147 promptsInFlight: number;
148 assistantReply: CursorTransportFailure;
149 stopped: boolean;
151​
152function settlePendingApprovalsAsCancelled(
153 pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
154): Effect.Effect<void> {
155 const pendingEntries = Array.from(pendingApprovals.values());
156 return Effect.forEach(
157 pendingEntries,
158 (pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
159 {
160 discard: true,
161 },
162 );
164​
165function settlePendingUserInputsAsEmptyAnswers(
166 pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
167): Effect.Effect<void> {
168 const pendingEntries = Array.from(pendingUserInputs.values());
169 return Effect.forEach(
170 pendingEntries,
171 (pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
172 {
173 discard: true,
174 },
175 );
177​
178function isRecord(value: unknown): value is Record<string, unknown> {
179 return typeof value === "object" && value !== null && !Array.isArray(value);
181​
182function parseCursorResume(raw: unknown): { sessionId: string } | undefined {
183 if (!isRecord(raw)) return undefined;
184 if (raw.schemaVersion !== CURSOR_RESUME_VERSION) return undefined;
185 if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined;
186 return { sessionId: raw.sessionId.trim() };
188​
189function normalizeModeSearchText(mode: AcpSessionMode): string {
190 return [mode.id, mode.name, mode.description]
191 .filter((value): value is string => typeof value === "string" && value.length > 0)
192 .join(" ")
193 .toLowerCase()
194 .replace(/[^a-z0-9]+/g, " ")
195 .trim();
197​
198function findModeByAliases(
199 modes: ReadonlyArray<AcpSessionMode>,
200 aliases: ReadonlyArray<string>,
201): AcpSessionMode | undefined {
202 const normalizedAliases = aliases.map((alias) => alias.toLowerCase());
203 for (const alias of normalizedAliases) {
204 const exact = modes.find((mode) => {
205 const id = mode.id.toLowerCase();
206 const name = mode.name.toLowerCase();
207 return id === alias || name === alias;
208 });
209 if (exact) {
210 return exact;
211 }
212 }
213 for (const alias of normalizedAliases) {
214 const partial = modes.find((mode) => normalizeModeSearchText(mode).includes(alias));
215 if (partial) {
216 return partial;
217 }
218 }
219 return undefined;
221​
222function isPlanMode(mode: AcpSessionMode): boolean {
223 return findModeByAliases([mode], ACP_PLAN_MODE_ALIASES) !== undefined;
225​
226function resolveRequestedModeId(input: {
227 readonly interactionMode: ProviderInteractionMode | undefined;
228 readonly runtimeMode: RuntimeMode;
229 readonly modeState: AcpSessionModeState | undefined;
230}): string | undefined {
231 const modeState = input.modeState;
232 if (!modeState) {
233 return undefined;
234 }
235​
236 if (input.interactionMode === "plan") {
237 return findModeByAliases(modeState.availableModes, ACP_PLAN_MODE_ALIASES)?.id;
238 }
239​
240 if (input.runtimeMode === "approval-required") {
241 return (
242 findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??
243 findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??
244 modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??
245 modeState.currentModeId
246 );
247 }
248​
249 return (
250 findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??
251 findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??
252 modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??
253 modeState.currentModeId
254 );
256​
257function applyRequestedSessionConfiguration<E>(input: {
258 readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"];
259 readonly runtimeMode: RuntimeMode;
260 readonly interactionMode: ProviderInteractionMode | undefined;
261 readonly modelSelection:
262 | {
263 readonly model: string;
264 readonly options?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
265 }
266 | undefined;
267 readonly mapError: (context: {
268 readonly cause: import("effect-acp/errors").AcpError;
269 readonly method: "session/set_config_option" | "session/set_mode";
270 }) => E;
271}): Effect.Effect<void, E> {
272 return Effect.gen(function* () {
273 if (input.modelSelection) {
274 yield* applyCursorAcpModelSelection({
275 runtime: input.runtime,
276 model: input.modelSelection.model,
277 selections: input.modelSelection.options,
278 mapError: ({ cause }) =>
279 input.mapError({
280 cause,
281 method: "session/set_config_option",
282 }),
283 });
284 }
285​
286 const requestedModeId = resolveRequestedModeId({
287 interactionMode: input.interactionMode,
288 runtimeMode: input.runtimeMode,
289 modeState: yield* input.runtime.getModeState,
290 });
291 if (!requestedModeId) {
292 return;
293 }
294​
295 yield* input.runtime.setMode(requestedModeId).pipe(
296 Effect.mapError((cause) =>
297 input.mapError({
298 cause,
299 method: "session/set_mode",
300 }),
301 ),
302 );
303 });
305​
306function selectAutoApprovedPermissionOption(
307 request: EffectAcpSchema.RequestPermissionRequest,
308): string | undefined {
309 const allowAlwaysOption = request.options.find((option) => option.kind === "allow_always");
310 if (typeof allowAlwaysOption?.optionId === "string" && allowAlwaysOption.optionId.trim()) {
311 return allowAlwaysOption.optionId.trim();
312 }
313​
314 const allowOnceOption = request.options.find((option) => option.kind === "allow_once");
315 if (typeof allowOnceOption?.optionId === "string" && allowOnceOption.optionId.trim()) {
316 return allowOnceOption.optionId.trim();
317 }
318​
319 return undefined;
321​
322export function makeCursorAdapter(
323 cursorSettings: CursorSettings,
324 options?: CursorAdapterLiveOptions,
325) {
326 return Effect.gen(function* () {
327 const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor");
328 const fileSystem = yield* FileSystem.FileSystem;
329 const path = yield* Path.Path;
330 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
331 const serverConfig = yield* Effect.service(ServerConfig);
332 const crypto = yield* Crypto.Crypto;
333 const nativeEventLogger =
334 options?.nativeEventLogger ??
335 (options?.nativeEventLogPath !== undefined
336 ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
337 stream: "native",
338 })
339 : undefined);
340 const managedNativeEventLogger =
341 options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
342 const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
343​
344 const sessions = new Map<ThreadId, CursorSessionContext>();
345 const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
346 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
347​
348 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
349 const randomUUIDv4 = crypto.randomUUIDv4.pipe(
350 Effect.mapError(
351 (cause) =>
352 new ProviderAdapterRequestError({
353 provider: PROVIDER,
354 method: "crypto/randomUUIDv4",
355 detail: "Failed to generate Cursor runtime identifier.",
356 cause,
357 }),
358 ),
359 );
360 const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));
361 const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
362 const mapExtensionFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
363 effect.pipe(
364 Effect.mapError(
365 (cause) =>
366 new EffectAcpErrors.AcpTransportError({
367 detail: "Failed to process Cursor ACP extension event.",
368 cause,
369 }),
370 ),
371 );
372​
373 const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
374 PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
375​
376 const getThreadSemaphore = (threadId: string) =>
377 SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
378 const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
379 current.get(threadId),
380 );
381 return Option.match(existing, {
382 onNone: () =>
383 Semaphore.make(1).pipe(
384 Effect.map((semaphore) => {
385 const next = new Map(current);
386 next.set(threadId, semaphore);
387 return [semaphore, next] as const;
388 }),
389 ),
390 onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
391 });
392 });
393​
394 const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
395 Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
396​
397 const logNative = (
398 threadId: ThreadId,
399 method: string,
400 payload: unknown,
401 _source: "acp.jsonrpc" | "acp.cursor.extension",
402 ) =>
403 Effect.gen(function* () {
404 if (!nativeEventLogger) return;
405 const observedAt = yield* nowIso;
406 yield* nativeEventLogger.write(
407 {
408 observedAt,
409 event: {
410 id: yield* randomUUIDv4,
411 kind: "notification",
412 provider: PROVIDER,
413 createdAt: observedAt,
414 method,
415 threadId,
416 payload,
417 },
418 },
419 threadId,
420 );
421 });
422​
423 const emitPlanUpdate = (
424 ctx: CursorSessionContext,
425 payload: {
426 readonly explanation?: string | null;
427 readonly plan: ReadonlyArray<{
428 readonly step: string;
429 readonly status: "pending" | "inProgress" | "completed";
430 }>;
431 },
432 rawPayload: unknown,
433 source: "acp.jsonrpc" | "acp.cursor.extension",
434 method: string,
435 ) =>
436 Effect.gen(function* () {
437 const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
438 if (ctx.lastPlanFingerprint === fingerprint) {
439 return;
440 }
441 ctx.lastPlanFingerprint = fingerprint;
442 yield* offerRuntimeEvent(
443 makeAcpPlanUpdatedEvent({
444 stamp: yield* makeEventStamp(),
445 provider: PROVIDER,
446 threadId: ctx.threadId,
447 turnId: ctx.activeTurnId,
448 payload,
449 source,
450 method,
451 rawPayload,
452 }),
453 );
454 });
455​
456 const requireSession = (
457 threadId: ThreadId,
458 ): Effect.Effect<CursorSessionContext, ProviderAdapterSessionNotFoundError> => {
459 const ctx = sessions.get(threadId);
460 if (!ctx || ctx.stopped) {
461 return Effect.fail(
462 new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),
463 );
464 }
465 return Effect.succeed(ctx);
466 };
467​
468 const stopSessionInternal = (ctx: CursorSessionContext) =>
469 Effect.gen(function* () {
470 if (ctx.stopped) return;
471 ctx.stopped = true;
472 yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
473 yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
474 if (ctx.notificationFiber) {
475 yield* Fiber.interrupt(ctx.notificationFiber);
476 }
477 yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
478 sessions.delete(ctx.threadId);
479 yield* offerRuntimeEvent({
480 type: "session.exited",
481 ...(yield* makeEventStamp()),
482 provider: PROVIDER,
483 threadId: ctx.threadId,
484 payload: { exitKind: "graceful" },
485 });
486 });
487​
488 const startSession: CursorAdapterShape["startSession"] = (input) =>
489 withThreadLock(
490 input.threadId,
491 Effect.gen(function* () {
492 if (input.provider !== undefined && input.provider !== PROVIDER) {
493 return yield* new ProviderAdapterValidationError({
494 provider: PROVIDER,
495 operation: "startSession",
496 issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
497 });
498 }
499 if (!input.cwd?.trim()) {
500 return yield* new ProviderAdapterValidationError({
501 provider: PROVIDER,
502 operation: "startSession",
503 issue: "cwd is required and must be non-empty.",
504 });
505 }
506​
507 const cwd = path.resolve(input.cwd.trim());
508 const cursorModelSelection =
509 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
510 const existing = sessions.get(input.threadId);
511 if (existing && !existing.stopped) {
512 yield* stopSessionInternal(existing);
513 }
514​
515 const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
516 const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
517 const sessionScope = yield* Scope.make("sequential");
518 let sessionScopeTransferred = false;
519 yield* Effect.addFinalizer(() =>
520 sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
521 );
522 let ctx!: CursorSessionContext;
523​
524 const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
525 const acpNativeLoggers = makeAcpNativeLoggers({
526 nativeEventLogger,
527 provider: PROVIDER,
528 threadId: input.threadId,
529 });
530​
531 // Resolve the CursorSettings used to spawn the ACP child. Production
532 // leaves `options.resolveSettings` undefined so we use the value
533 // captured at adapter construction — per-instance isolation is
534 // enforced by the hydration layer rebuilding this adapter whenever
535 // its config changes. Tests set `resolveSettings` to pull the latest
536 // snapshot from `ServerSettingsService` so that mid-suite
537 // `updateSettings({ providers: { cursor: { binaryPath } } })` calls
538 // actually take effect when the next session spawns.
539 const effectiveCursorSettings = options?.resolveSettings
540 ? yield* options.resolveSettings
541 : cursorSettings;
542​
543 const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
544 const acp = yield* makeCursorAcpRuntime({
545 cursorSettings: effectiveCursorSettings,
546 ...(options?.environment ? { environment: options.environment } : {}),
547 childProcessSpawner,
548 cwd,
549 runtimeMode: input.runtimeMode,
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 cursorSkillNames: undefined,
792 promptsInFlight: 0,
793 assistantReply: new CursorTransportFailure(),
794 stopped: false,
795 };
796​
797 const nf = yield* Stream.runDrain(
798 Stream.mapEffect(acp.getEvents(), (event) =>
799 Effect.gen(function* () {
800 switch (event._tag) {
801 case "EventStreamBarrier":
802 yield* Deferred.succeed(event.acknowledge, undefined);
803 return;
804 case "ModeChanged":
805 return;
806 case "AssistantItemStarted":
807 ctx.assistantReply = new CursorTransportFailure();
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 ctx.assistantReply.push(event.text);
866 yield* logNative(
867 ctx.threadId,
868 "session/update",
869 event.rawPayload,
870 "acp.jsonrpc",
871 );
872 yield* offerRuntimeEvent(
873 makeAcpContentDeltaEvent({
874 stamp: yield* makeEventStamp(),
875 provider: PROVIDER,
876 threadId: ctx.threadId,
877 turnId: ctx.activeTurnId,
878 ...(event.itemId ? { itemId: event.itemId } : {}),
879 text: event.text,
880 rawPayload: event.rawPayload,
881 }),
882 );
883 return;
884 }
885 }),
886 ),
887 ).pipe(
888 Effect.catch((cause) =>
889 Effect.logError("Failed to process Cursor runtime notification.", { cause }),
890 ),
891 // Fork into the session scope, not the calling fiber. `forkChild`
892 // makes this a child of `startSession`, and Effect interrupts a
893 // fiber's children when it completes, so the consumer died as soon
894 // as `startSession` returned and every later notification was
895 // dropped. The scope is created, stored on the context and closed
896 // on teardown already; only the fork target was wrong.
897 Effect.forkIn(ctx.scope),
898 );
899​
900 ctx.notificationFiber = nf;
901 sessions.set(input.threadId, ctx);
902 sessionScopeTransferred = true;
903​
904 yield* offerRuntimeEvent({
905 type: "session.started",
906 ...(yield* makeEventStamp()),
907 provider: PROVIDER,
908 threadId: input.threadId,
909 payload: { resume: started.initializeResult },
910 });
911 yield* offerRuntimeEvent({
912 type: "session.state.changed",
913 ...(yield* makeEventStamp()),
914 provider: PROVIDER,
915 threadId: input.threadId,
916 payload: { state: "ready", reason: "Cursor ACP session ready" },
917 });
918 yield* offerRuntimeEvent({
919 type: "thread.started",
920 ...(yield* makeEventStamp()),
921 provider: PROVIDER,
922 threadId: input.threadId,
923 payload: { providerThreadId: started.sessionId },
924 });
925​
926 return session;
927 }).pipe(Effect.scoped),
928 );
929​
930 const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
931 Effect.gen(function* () {
932 const ctx = yield* requireSession(input.threadId);
933 // A sendTurn while a prompt is in flight is a steer: the agent folds
934 // the new prompt into the ongoing work, so the active turn id is
935 // reused instead of opening a new turn.
936 const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
937 const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
938 // Count this prompt immediately so a superseded in-flight prompt
939 // resolving from here on does not settle the turn; the matching
940 // decrement is the `ensuring` below.
941 ctx.promptsInFlight += 1;
942​
943 return yield* Effect.gen(function* () {
944 const turnModelSelection =
945 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
946 const model = turnModelSelection?.model ?? ctx.session.model;
947 const resolvedModel = resolveCursorAcpBaseModelId(model);
948 yield* applyRequestedSessionConfiguration({
949 runtime: ctx.acp,
950 runtimeMode: ctx.session.runtimeMode,
951 interactionMode: input.interactionMode,
952 modelSelection:
953 model === undefined
954 ? undefined
955 : {
956 model,
957 options: turnModelSelection?.options,
958 },
959 mapError: ({ cause, method }) =>
960 mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
961 });
962 ctx.activeTurnId = turnId;
963 if (steeringTurnId === undefined) {
964 ctx.lastPlanFingerprint = undefined;
965 ctx.assistantReply = new CursorTransportFailure();
966 }
967 ctx.session = {
968 ...ctx.session,
969 activeTurnId: turnId,
970 updatedAt: yield* nowIso,
971 };
972​
973 if (steeringTurnId === undefined) {
974 yield* offerRuntimeEvent({
975 type: "turn.started",
976 ...(yield* makeEventStamp()),
977 provider: PROVIDER,
978 threadId: input.threadId,
979 turnId,
980 payload: { model: resolvedModel },
981 });
982 }
983​
984 const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
985 const rawPrompt = input.input?.trim() ?? "";
986 if (rawPrompt) {
987 let cursorSkillNames = ctx.cursorSkillNames;
988 if (hasCursorSkillMention(rawPrompt) && cursorSkillNames === undefined) {
989 const skills = yield* discoverCursorSkills(
990 ctx.session.cwd,
991 options?.environment,
992 ).pipe(
993 Effect.provideService(FileSystem.FileSystem, fileSystem),
994 Effect.provideService(Path.Path, path),
995 );
996 cursorSkillNames = new Set(
997 skills
998 .filter((skill) => skill.enabled && skill.userInvocable !== false)
999 .map((skill) => skill.name),
1000 );
1001 ctx.cursorSkillNames = cursorSkillNames;
1003 const prompt = cursorSkillNames
1004 ? rewriteCursorSkillMentions(rawPrompt, cursorSkillNames)
1005 : rawPrompt;
1006 promptParts.push({ type: "text", text: prompt });
1008 if (input.attachments && input.attachments.length > 0) {
1009 for (const attachment of input.attachments) {
1010 // Cursor ingests images only. Generic files reach the agent
1011 // through the path line ProviderService puts in the prompt.
1012 if (attachment.type !== "image") {
1013 continue;
1015 const attachmentPath = resolveAttachmentPath({
1016 attachmentsDir: serverConfig.attachmentsDir,
1017 attachment,
1018 });
1019 if (!attachmentPath) {
1020 return yield* new ProviderAdapterRequestError({
1021 provider: PROVIDER,
1022 method: "session/prompt",
1023 detail: `Invalid attachment id '${attachment.id}'.`,
1024 });
1026 const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
1027 Effect.mapError(
1028 (cause) =>
1029 new ProviderAdapterRequestError({
1030 provider: PROVIDER,
1031 method: "session/prompt",
1032 detail: cause.message,
1033 cause,
1034 }),
1035 ),
1036 );
1037 promptParts.push({
1038 type: "image",
1039 data: Buffer.from(bytes).toString("base64"),
1040 mimeType: attachment.mimeType,
1041 });
1044​
1045 if (promptParts.length === 0) {
1046 return yield* new ProviderAdapterValidationError({
1047 provider: PROVIDER,
1048 operation: "sendTurn",
1049 issue: "Turn requires non-empty text or attachments.",
1050 });
1052​
1053 // ACP has no system-message field; keep runtime context separate from the user's text.
1054 const result = yield* ctx.acp
1055 .prompt({
1056 prompt: [
1057 ...promptParts,
1059 type: "text",
1060 text: buildRuntimeInstructions({ harness: "Cursor", model: resolvedModel }),
1061 },
1062 ],
1063 })
1064 .pipe(
1065 Effect.mapError((error) =>
1066 mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
1067 ),
1068 );
1069​
1070 yield* ctx.acp.drainEvents;
1071 const failure = ctx.assistantReply.failure;
1072 if (ctx.promptsInFlight === 1 && result.stopReason !== "cancelled" && failure) {
1073 return yield* new ProviderAdapterRequestError({
1074 provider: PROVIDER,
1075 method: "session/prompt",
1076 detail: "Cursor reported a transport failure.",
1077 cause: failure,
1078 });
1080​
1081 const turnRecord = ctx.turns.find((turn) => turn.id === turnId);
1082 if (turnRecord) {
1083 turnRecord.items.push({ prompt: promptParts, result });
1084 } else {
1085 ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
1087 ctx.session = {
1088 ...ctx.session,
1089 activeTurnId: turnId,
1090 updatedAt: yield* nowIso,
1091 model: resolvedModel,
1092 };
1093​
1094 // Only the last remaining prompt settles the turn — a steer-
1095 // superseded prompt resolving (usually cancelled) while another is
1096 // in flight or pending must leave the merged turn running.
1097 if (ctx.promptsInFlight === 1) {
1098 yield* offerRuntimeEvent({
1099 type: "turn.completed",
1100 ...(yield* makeEventStamp()),
1101 provider: PROVIDER,
1102 threadId: input.threadId,
1103 turnId,
1104 payload: {
1105 state: result.stopReason === "cancelled" ? "cancelled" : "completed",
1106 stopReason: result.stopReason ?? null,
1107 },
1108 });
1110​
1111 return {
1112 threadId: input.threadId,
1113 turnId,
1114 resumeCursor: ctx.session.resumeCursor,
1115 };
1116 }).pipe(
1117 Effect.ensuring(
1118 Effect.sync(() => {
1119 ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
1120 }),
1121 ),
1122 );
1123 });
1124​
1125 const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
1126 Effect.gen(function* () {
1127 const ctx = yield* requireSession(threadId);
1128 yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
1129 yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
1130 yield* Effect.ignore(
1131 ctx.acp.cancel.pipe(
1132 Effect.mapError((error) =>
1133 mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
1134 ),
1135 ),
1136 );
1137 });
1138​
1139 const respondToRequest: CursorAdapterShape["respondToRequest"] = (
1140 threadId,
1141 requestId,
1142 decision,
1143 ) =>
1144 Effect.gen(function* () {
1145 const ctx = yield* requireSession(threadId);
1146 const pending = ctx.pendingApprovals.get(requestId);
1147 if (!pending) {
1148 return yield* new ProviderAdapterRequestError({
1149 provider: PROVIDER,
1150 method: "session/request_permission",
1151 detail: `Unknown pending approval request: ${requestId}`,
1152 });
1154 yield* Deferred.succeed(pending.decision, decision);
1155 });
1156​
1157 const respondToUserInput: CursorAdapterShape["respondToUserInput"] = (
1158 threadId,
1159 requestId,
1160 answers,
1161 ) =>
1162 Effect.gen(function* () {
1163 const ctx = yield* requireSession(threadId);
1164 const pending = ctx.pendingUserInputs.get(requestId);
1165 if (!pending) {
1166 return yield* new ProviderAdapterRequestError({
1167 provider: PROVIDER,
1168 method: "cursor/ask_question",
1169 detail: `Unknown pending user-input request: ${requestId}`,
1170 });
1172 yield* Deferred.succeed(pending.answers, answers);
1173 });
1174​
1175 const readThread: CursorAdapterShape["readThread"] = (threadId) =>
1176 Effect.gen(function* () {
1177 const ctx = yield* requireSession(threadId);
1178 return { threadId, turns: ctx.turns };
1179 });
1180​
1181 const rollbackThread: CursorAdapterShape["rollbackThread"] = (threadId, numTurns) =>
1182 Effect.gen(function* () {
1183 const ctx = yield* requireSession(threadId);
1184 if (!Number.isInteger(numTurns) || numTurns < 1) {
1185 return yield* new ProviderAdapterValidationError({
1186 provider: PROVIDER,
1187 operation: "rollbackThread",
1188 issue: "numTurns must be an integer >= 1.",
1189 });
1191 const nextLength = Math.max(0, ctx.turns.length - numTurns);
1192 ctx.turns.splice(nextLength);
1193 return { threadId, turns: ctx.turns };
1194 });
1195​
1196 const stopSession: CursorAdapterShape["stopSession"] = (threadId) =>
1197 withThreadLock(
1198 threadId,
1199 Effect.gen(function* () {
1200 const ctx = yield* requireSession(threadId);
1201 yield* stopSessionInternal(ctx);
1202 }),
1203 );
1204​
1205 const listSessions: CursorAdapterShape["listSessions"] = () =>
1206 Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
1207​
1208 const hasSession: CursorAdapterShape["hasSession"] = (threadId) =>
1209 Effect.sync(() => {
1210 const c = sessions.get(threadId);
1211 return c !== undefined && !c.stopped;
1212 });
1213​
1214 const stopAll: CursorAdapterShape["stopAll"] = () =>
1215 Effect.forEach(sessions.values(), stopSessionInternal, { discard: true });
1216​
1217 yield* Effect.addFinalizer(() =>
1218 Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
1219 Effect.catch((cause) =>
1220 Effect.logError("Failed to emit Cursor session shutdown event.", { cause }),
1221 ),
1222 Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
1223 Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
1224 ),
1225 );
1226​
1227 const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
1228​
1229 return {
1230 provider: PROVIDER,
1231 capabilities: { sessionModelSwitch: "in-session" },
1232 compaction: { type: "slash-command", command: "/compress" },
1233 startSession,
1234 sendTurn,
1235 interruptTurn,
1236 readThread,
1237 rollbackThread,
1238 respondToRequest,
1239 respondToUserInput,
1240 stopSession,
1241 listSessions,
1242 hasSession,
1243 stopAll,
1244 streamEvents,
1245 } satisfies CursorAdapterShape;
1246 });