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

CursorAdapter.ts

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