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

CursorAdapter.ts

1,289 lines47.7 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>;
121 readonly onAvailableCommands?: (
122 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
123 cwd: string,
124 ) => Effect.Effect<void>;
126​
127interface PendingApproval {
128 readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
129 readonly kind: string | "unknown";
131​
132interface PendingUserInput {
133 readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
135​
136interface CursorSessionContext {
137 readonly threadId: ThreadId;
138 session: ProviderSession;
139 readonly scope: Scope.Closeable;
140 readonly acp: AcpSessionRuntime.AcpSessionRuntime["Service"];
141 notificationFiber: Fiber.Fiber<void, never> | undefined;
142 readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
143 readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
144 readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
145 lastPlanFingerprint: string | undefined;
146 activeTurnId: TurnId | undefined;
147 cursorSkillNames: ReadonlySet<string> | undefined;
148 /** Number of sendTurn prompts currently in flight or being prepared.
149 * >0 means a turn is actively running, so a new sendTurn is a steer that
150 * continues it, and only the last remaining prompt settles the turn. */
151 promptsInFlight: number;
152 assistantReply: CursorTransportFailure;
153 stopped: boolean;
155​
156function settlePendingApprovalsAsCancelled(
157 pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
158): Effect.Effect<void> {
159 const pendingEntries = Array.from(pendingApprovals.values());
160 return Effect.forEach(
161 pendingEntries,
162 (pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
163 {
164 discard: true,
165 },
166 );
168​
169function settlePendingUserInputsAsEmptyAnswers(
170 pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
171): Effect.Effect<void> {
172 const pendingEntries = Array.from(pendingUserInputs.values());
173 return Effect.forEach(
174 pendingEntries,
175 (pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
176 {
177 discard: true,
178 },
179 );
181​
182function isRecord(value: unknown): value is Record<string, unknown> {
183 return typeof value === "object" && value !== null && !Array.isArray(value);
185​
186function parseCursorResume(raw: unknown): { sessionId: string } | undefined {
187 if (!isRecord(raw)) return undefined;
188 if (raw.schemaVersion !== CURSOR_RESUME_VERSION) return undefined;
189 if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined;
190 return { sessionId: raw.sessionId.trim() };
192​
193function normalizeModeSearchText(mode: AcpSessionMode): string {
194 return [mode.id, mode.name, mode.description]
195 .filter((value): value is string => typeof value === "string" && value.length > 0)
196 .join(" ")
197 .toLowerCase()
198 .replace(/[^a-z0-9]+/g, " ")
199 .trim();
201​
202function findModeByAliases(
203 modes: ReadonlyArray<AcpSessionMode>,
204 aliases: ReadonlyArray<string>,
205): AcpSessionMode | undefined {
206 const normalizedAliases = aliases.map((alias) => alias.toLowerCase());
207 for (const alias of normalizedAliases) {
208 const exact = modes.find((mode) => {
209 const id = mode.id.toLowerCase();
210 const name = mode.name.toLowerCase();
211 return id === alias || name === alias;
212 });
213 if (exact) {
214 return exact;
215 }
216 }
217 for (const alias of normalizedAliases) {
218 const partial = modes.find((mode) => normalizeModeSearchText(mode).includes(alias));
219 if (partial) {
220 return partial;
221 }
222 }
223 return undefined;
225​
226function isPlanMode(mode: AcpSessionMode): boolean {
227 return findModeByAliases([mode], ACP_PLAN_MODE_ALIASES) !== undefined;
229​
230function resolveRequestedModeId(input: {
231 readonly interactionMode: ProviderInteractionMode | undefined;
232 readonly runtimeMode: RuntimeMode;
233 readonly modeState: AcpSessionModeState | undefined;
234}): string | undefined {
235 const modeState = input.modeState;
236 if (!modeState) {
237 return undefined;
238 }
239​
240 if (input.interactionMode === "plan") {
241 return findModeByAliases(modeState.availableModes, ACP_PLAN_MODE_ALIASES)?.id;
242 }
243​
244 if (input.runtimeMode === "approval-required") {
245 return (
246 findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??
247 findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??
248 modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??
249 modeState.currentModeId
250 );
251 }
252​
253 return (
254 findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??
255 findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??
256 modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??
257 modeState.currentModeId
258 );
260​
261function applyRequestedSessionConfiguration<E>(input: {
262 readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"];
263 readonly runtimeMode: RuntimeMode;
264 readonly interactionMode: ProviderInteractionMode | undefined;
265 readonly modelSelection:
266 | {
267 readonly model: string;
268 readonly options?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
269 }
270 | undefined;
271 readonly mapError: (context: {
272 readonly cause: import("effect-acp/errors").AcpError;
273 readonly method: "session/set_config_option" | "session/set_mode";
274 }) => E;
275}): Effect.Effect<void, E> {
276 return Effect.gen(function* () {
277 if (input.modelSelection) {
278 yield* applyCursorAcpModelSelection({
279 runtime: input.runtime,
280 model: input.modelSelection.model,
281 selections: input.modelSelection.options,
282 mapError: ({ cause }) =>
283 input.mapError({
284 cause,
285 method: "session/set_config_option",
286 }),
287 });
288 }
289​
290 const requestedModeId = resolveRequestedModeId({
291 interactionMode: input.interactionMode,
292 runtimeMode: input.runtimeMode,
293 modeState: yield* input.runtime.getModeState,
294 });
295 if (!requestedModeId) {
296 return;
297 }
298​
299 yield* input.runtime.setMode(requestedModeId).pipe(
300 Effect.mapError((cause) =>
301 input.mapError({
302 cause,
303 method: "session/set_mode",
304 }),
305 ),
306 );
307 });
309​
310function selectAutoApprovedPermissionOption(
311 request: EffectAcpSchema.RequestPermissionRequest,
312): string | undefined {
313 const allowAlwaysOption = request.options.find((option) => option.kind === "allow_always");
314 if (typeof allowAlwaysOption?.optionId === "string" && allowAlwaysOption.optionId.trim()) {
315 return allowAlwaysOption.optionId.trim();
316 }
317​
318 const allowOnceOption = request.options.find((option) => option.kind === "allow_once");
319 if (typeof allowOnceOption?.optionId === "string" && allowOnceOption.optionId.trim()) {
320 return allowOnceOption.optionId.trim();
321 }
322​
323 return undefined;
325​
326export function makeCursorAdapter(
327 cursorSettings: CursorSettings,
328 options?: CursorAdapterLiveOptions,
329) {
330 return Effect.gen(function* () {
331 const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor");
332 const fileSystem = yield* FileSystem.FileSystem;
333 const path = yield* Path.Path;
334 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
335 const serverConfig = yield* Effect.service(ServerConfig);
336 const crypto = yield* Crypto.Crypto;
337 const nativeEventLogger =
338 options?.nativeEventLogger ??
339 (options?.nativeEventLogPath !== undefined
340 ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
341 stream: "native",
342 })
343 : undefined);
344 const managedNativeEventLogger =
345 options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
346 const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
347​
348 const sessions = new Map<ThreadId, CursorSessionContext>();
349 const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
350 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
351​
352 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
353 const randomUUIDv4 = crypto.randomUUIDv4.pipe(
354 Effect.mapError(
355 (cause) =>
356 new ProviderAdapterRequestError({
357 provider: PROVIDER,
358 method: "crypto/randomUUIDv4",
359 detail: "Failed to generate Cursor runtime identifier.",
360 cause,
361 }),
362 ),
363 );
364 const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));
365 const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
366 const mapExtensionFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
367 effect.pipe(
368 Effect.mapError(
369 (cause) =>
370 new EffectAcpErrors.AcpTransportError({
371 detail: "Failed to process Cursor ACP extension event.",
372 cause,
373 }),
374 ),
375 );
376​
377 const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
378 PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
379​
380 const getThreadSemaphore = (threadId: string) =>
381 SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
382 const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
383 current.get(threadId),
384 );
385 return Option.match(existing, {
386 onNone: () =>
387 Semaphore.make(1).pipe(
388 Effect.map((semaphore) => {
389 const next = new Map(current);
390 next.set(threadId, semaphore);
391 return [semaphore, next] as const;
392 }),
393 ),
394 onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
395 });
396 });
397​
398 const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
399 Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
400​
401 const logNative = (
402 threadId: ThreadId,
403 method: string,
404 payload: unknown,
405 _source: "acp.jsonrpc" | "acp.cursor.extension",
406 ) =>
407 Effect.gen(function* () {
408 if (!nativeEventLogger) return;
409 const observedAt = yield* nowIso;
410 yield* nativeEventLogger.write(
411 {
412 observedAt,
413 event: {
414 id: yield* randomUUIDv4,
415 kind: "notification",
416 provider: PROVIDER,
417 createdAt: observedAt,
418 method,
419 threadId,
420 payload,
421 },
422 },
423 threadId,
424 );
425 });
426​
427 const emitPlanUpdate = (
428 ctx: CursorSessionContext,
429 payload: {
430 readonly explanation?: string | null;
431 readonly plan: ReadonlyArray<{
432 readonly step: string;
433 readonly status: "pending" | "inProgress" | "completed";
434 }>;
435 },
436 rawPayload: unknown,
437 source: "acp.jsonrpc" | "acp.cursor.extension",
438 method: string,
439 ) =>
440 Effect.gen(function* () {
441 const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
442 if (ctx.lastPlanFingerprint === fingerprint) {
443 return;
444 }
445 ctx.lastPlanFingerprint = fingerprint;
446 yield* offerRuntimeEvent(
447 makeAcpPlanUpdatedEvent({
448 stamp: yield* makeEventStamp(),
449 provider: PROVIDER,
450 threadId: ctx.threadId,
451 turnId: ctx.activeTurnId,
452 payload,
453 source,
454 method,
455 rawPayload,
456 }),
457 );
458 });
459​
460 const requireSession = (
461 threadId: ThreadId,
462 ): Effect.Effect<CursorSessionContext, ProviderAdapterSessionNotFoundError> => {
463 const ctx = sessions.get(threadId);
464 if (!ctx || ctx.stopped) {
465 return Effect.fail(
466 new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),
467 );
468 }
469 return Effect.succeed(ctx);
470 };
471​
472 const stopSessionInternal = (ctx: CursorSessionContext) =>
473 Effect.gen(function* () {
474 if (ctx.stopped) return;
475 ctx.stopped = true;
476 yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
477 yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
478 if (ctx.notificationFiber) {
479 yield* Fiber.interrupt(ctx.notificationFiber);
480 }
481 yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
482 sessions.delete(ctx.threadId);
483 yield* offerRuntimeEvent({
484 type: "session.exited",
485 ...(yield* makeEventStamp()),
486 provider: PROVIDER,
487 threadId: ctx.threadId,
488 payload: { exitKind: "graceful" },
489 });
490 });
491​
492 const startSession: CursorAdapterShape["startSession"] = (input) =>
493 withThreadLock(
494 input.threadId,
495 Effect.gen(function* () {
496 if (input.provider !== undefined && input.provider !== PROVIDER) {
497 return yield* new ProviderAdapterValidationError({
498 provider: PROVIDER,
499 operation: "startSession",
500 issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
501 });
502 }
503 if (!input.cwd?.trim()) {
504 return yield* new ProviderAdapterValidationError({
505 provider: PROVIDER,
506 operation: "startSession",
507 issue: "cwd is required and must be non-empty.",
508 });
509 }
510​
511 const cwd = path.resolve(input.cwd.trim());
512 const cursorModelSelection =
513 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
514 const existing = sessions.get(input.threadId);
515 if (existing && !existing.stopped) {
516 yield* stopSessionInternal(existing);
517 }
518​
519 const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
520 const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
521 const sessionScope = yield* Scope.make("sequential");
522 let sessionScopeTransferred = false;
523 yield* Effect.addFinalizer(() =>
524 sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
525 );
526 let ctx!: CursorSessionContext;
527​
528 const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
529 const acpNativeLoggers = makeAcpNativeLoggers({
530 nativeEventLogger,
531 provider: PROVIDER,
532 threadId: input.threadId,
533 });
534​
535 // Resolve the CursorSettings used to spawn the ACP child. Production
536 // leaves `options.resolveSettings` undefined so we use the value
537 // captured at adapter construction — per-instance isolation is
538 // enforced by the hydration layer rebuilding this adapter whenever
539 // its config changes. Tests set `resolveSettings` to pull the latest
540 // snapshot from `ServerSettingsService` so that mid-suite
541 // `updateSettings({ providers: { cursor: { binaryPath } } })` calls
542 // actually take effect when the next session spawns.
543 const effectiveCursorSettings = options?.resolveSettings
544 ? yield* options.resolveSettings
545 : cursorSettings;
546​
547 const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
548 const acp = yield* makeCursorAcpRuntime({
549 cursorSettings: effectiveCursorSettings,
550 ...(options?.environment || mcpSession?.agentDeviceEnvironment
551 ? {
552 environment: McpProviderSession.withAgentDeviceEnvironment(
553 options?.environment ?? process.env,
554 mcpSession,
555 ),
556 }
557 : {}),
558 childProcessSpawner,
559 cwd,
560 runtimeMode: input.runtimeMode,
561 ...(resumeSessionId ? { resumeSessionId } : {}),
562 clientInfo: { name: "t3-code", version: "0.0.0" },
563 ...(mcpSession
564 ? {
565 mcpServers: [
566 {
567 type: "http" as const,
568 name: "t3-code",
569 url: mcpSession.endpoint,
570 headers: [
571 {
572 name: "Authorization",
573 value: mcpSession.authorizationHeader,
574 },
575 ],
576 },
577 ],
578 }
579 : {}),
580 ...acpNativeLoggers,
581 }).pipe(
582 Effect.provideService(Crypto.Crypto, crypto),
583 Effect.provideService(Scope.Scope, sessionScope),
584 Effect.mapError(
585 (cause) =>
586 new ProviderAdapterProcessError({
587 provider: PROVIDER,
588 threadId: input.threadId,
589 detail: cause.message,
590 cause,
591 }),
592 ),
593 );
594 const started = yield* Effect.gen(function* () {
595 yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
596 mapExtensionFailure(
597 Effect.gen(function* () {
598 yield* logNative(
599 input.threadId,
600 "cursor/ask_question",
601 params,
602 "acp.cursor.extension",
603 );
604 const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
605 const runtimeRequestId = RuntimeRequestId.make(requestId);
606 const answers = yield* Deferred.make<ProviderUserInputAnswers>();
607 pendingUserInputs.set(requestId, { answers });
608 yield* offerRuntimeEvent({
609 type: "user-input.requested",
610 ...(yield* makeEventStamp()),
611 provider: PROVIDER,
612 threadId: input.threadId,
613 turnId: ctx?.activeTurnId,
614 requestId: runtimeRequestId,
615 payload: { questions: extractAskQuestions(params) },
616 raw: {
617 source: "acp.cursor.extension",
618 method: "cursor/ask_question",
619 payload: params,
620 },
621 });
622 const resolved = yield* Deferred.await(answers);
623 pendingUserInputs.delete(requestId);
624 yield* offerRuntimeEvent({
625 type: "user-input.resolved",
626 ...(yield* makeEventStamp()),
627 provider: PROVIDER,
628 threadId: input.threadId,
629 turnId: ctx?.activeTurnId,
630 requestId: runtimeRequestId,
631 payload: { answers: resolved },
632 });
633 return { answers: resolved };
634 }),
635 ),
636 );
637 yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
638 mapExtensionFailure(
639 Effect.gen(function* () {
640 yield* logNative(
641 input.threadId,
642 "cursor/create_plan",
643 params,
644 "acp.cursor.extension",
645 );
646 yield* offerRuntimeEvent({
647 type: "turn.proposed.completed",
648 ...(yield* makeEventStamp()),
649 provider: PROVIDER,
650 threadId: input.threadId,
651 turnId: ctx?.activeTurnId,
652 payload: { planMarkdown: extractPlanMarkdown(params) },
653 raw: {
654 source: "acp.cursor.extension",
655 method: "cursor/create_plan",
656 payload: params,
657 },
658 });
659 return { accepted: true } as const;
660 }),
661 ),
662 );
663 yield* acp.handleExtNotification(
664 "cursor/update_todos",
665 CursorUpdateTodosRequest,
666 (params) =>
667 mapExtensionFailure(
668 Effect.gen(function* () {
669 yield* logNative(
670 input.threadId,
671 "cursor/update_todos",
672 params,
673 "acp.cursor.extension",
674 );
675 if (ctx) {
676 yield* emitPlanUpdate(
677 ctx,
678 extractTodosAsPlan(params),
679 params,
680 "acp.cursor.extension",
681 "cursor/update_todos",
682 );
683 }
684 }),
685 ),
686 );
687 yield* acp.handleRequestPermission((params) =>
688 mapExtensionFailure(
689 Effect.gen(function* () {
690 yield* logNative(
691 input.threadId,
692 "session/request_permission",
693 params,
694 "acp.jsonrpc",
695 );
696 if (input.runtimeMode === "full-access") {
697 const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
698 if (autoApprovedOptionId !== undefined) {
699 return {
700 outcome: {
701 outcome: "selected" as const,
702 optionId: autoApprovedOptionId,
703 },
704 };
705 }
706 }
707 const permissionRequest = parsePermissionRequest(params);
708 const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
709 const runtimeRequestId = RuntimeRequestId.make(requestId);
710 const decision = yield* Deferred.make<ProviderApprovalDecision>();
711 pendingApprovals.set(requestId, {
712 decision,
713 kind: permissionRequest.kind,
714 });
715 yield* offerRuntimeEvent(
716 makeAcpRequestOpenedEvent({
717 stamp: yield* makeEventStamp(),
718 provider: PROVIDER,
719 threadId: input.threadId,
720 turnId: ctx?.activeTurnId,
721 requestId: runtimeRequestId,
722 permissionRequest,
723 detail:
724 permissionRequest.detail ??
725 encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
726 "[unserializable params]",
727 args: params,
728 source: "acp.jsonrpc",
729 method: "session/request_permission",
730 rawPayload: params,
731 }),
732 );
733 const resolved = yield* Deferred.await(decision);
734 pendingApprovals.delete(requestId);
735 yield* offerRuntimeEvent(
736 makeAcpRequestResolvedEvent({
737 stamp: yield* makeEventStamp(),
738 provider: PROVIDER,
739 threadId: input.threadId,
740 turnId: ctx?.activeTurnId,
741 requestId: runtimeRequestId,
742 permissionRequest,
743 decision: resolved,
744 }),
745 );
746 return {
747 outcome:
748 resolved === "cancel"
749 ? ({ outcome: "cancelled" } as const)
750 : {
751 outcome: "selected" as const,
752 optionId: acpPermissionOutcome(resolved),
753 },
754 };
755 }),
756 ),
757 );
758 return yield* acp.start();
759 }).pipe(
760 Effect.mapError((error) =>
761 mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
762 ),
763 );
764​
765 yield* applyRequestedSessionConfiguration({
766 runtime: acp,
767 runtimeMode: input.runtimeMode,
768 interactionMode: undefined,
769 modelSelection: cursorModelSelection,
770 mapError: ({ cause, method }) =>
771 mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
772 });
773​
774 const now = yield* nowIso;
775 const session: ProviderSession = {
776 provider: PROVIDER,
777 providerInstanceId: boundInstanceId,
778 status: "ready",
779 runtimeMode: input.runtimeMode,
780 cwd,
781 model: cursorModelSelection?.model,
782 threadId: input.threadId,
783 resumeCursor: {
784 schemaVersion: CURSOR_RESUME_VERSION,
785 sessionId: started.sessionId,
786 },
787 createdAt: now,
788 updatedAt: now,
789 };
790​
791 ctx = {
792 threadId: input.threadId,
793 session,
794 scope: sessionScope,
795 acp,
796 notificationFiber: undefined,
797 pendingApprovals,
798 pendingUserInputs,
799 turns: [],
800 lastPlanFingerprint: undefined,
801 activeTurnId: undefined,
802 cursorSkillNames: undefined,
803 promptsInFlight: 0,
804 assistantReply: new CursorTransportFailure(),
805 stopped: false,
806 };
807​
808 const nf = yield* Stream.runDrain(
809 Stream.mapEffect(acp.getEvents(), (event) =>
810 Effect.gen(function* () {
811 switch (event._tag) {
812 case "EventStreamBarrier":
813 yield* Deferred.succeed(event.acknowledge, undefined);
814 return;
815 case "ModeChanged":
816 return;
817 case "AvailableCommandsUpdated":
818 yield* (
819 options?.onAvailableCommands?.(event.availableCommands, cwd) ?? Effect.void
820 );
821 return;
822 case "AssistantItemStarted":
823 ctx.assistantReply = new CursorTransportFailure();
824 yield* offerRuntimeEvent(
825 makeAcpAssistantItemEvent({
826 stamp: yield* makeEventStamp(),
827 provider: PROVIDER,
828 threadId: ctx.threadId,
829 turnId: ctx.activeTurnId,
830 itemId: event.itemId,
831 lifecycle: "item.started",
832 }),
833 );
834 return;
835 case "AssistantItemCompleted":
836 yield* offerRuntimeEvent(
837 makeAcpAssistantItemEvent({
838 stamp: yield* makeEventStamp(),
839 provider: PROVIDER,
840 threadId: ctx.threadId,
841 turnId: ctx.activeTurnId,
842 itemId: event.itemId,
843 lifecycle: "item.completed",
844 }),
845 );
846 return;
847 case "PlanUpdated":
848 yield* logNative(
849 ctx.threadId,
850 "session/update",
851 event.rawPayload,
852 "acp.jsonrpc",
853 );
854 yield* emitPlanUpdate(
855 ctx,
856 event.payload,
857 event.rawPayload,
858 "acp.jsonrpc",
859 "session/update",
860 );
861 return;
862 case "ToolCallUpdated":
863 yield* logNative(
864 ctx.threadId,
865 "session/update",
866 event.rawPayload,
867 "acp.jsonrpc",
868 );
869 yield* offerRuntimeEvent(
870 makeAcpToolCallEvent({
871 stamp: yield* makeEventStamp(),
872 provider: PROVIDER,
873 threadId: ctx.threadId,
874 turnId: ctx.activeTurnId,
875 toolCall: event.toolCall,
876 rawPayload: event.rawPayload,
877 }),
878 );
879 return;
880 case "ThoughtDelta":
881 // Thoughts are narration, not the reply: they stay out of
882 // `assistantReply` so a resumed turn replays only answers.
883 yield* logNative(
884 ctx.threadId,
885 "session/update",
886 event.rawPayload,
887 "acp.jsonrpc",
888 );
889 yield* offerRuntimeEvent(
890 makeAcpContentDeltaEvent({
891 stamp: yield* makeEventStamp(),
892 provider: PROVIDER,
893 threadId: ctx.threadId,
894 turnId: ctx.activeTurnId,
895 streamKind: "reasoning_text",
896 text: event.text,
897 rawPayload: event.rawPayload,
898 }),
899 );
900 return;
901 case "ContentDelta":
902 ctx.assistantReply.push(event.text);
903 yield* logNative(
904 ctx.threadId,
905 "session/update",
906 event.rawPayload,
907 "acp.jsonrpc",
908 );
909 yield* offerRuntimeEvent(
910 makeAcpContentDeltaEvent({
911 stamp: yield* makeEventStamp(),
912 provider: PROVIDER,
913 threadId: ctx.threadId,
914 turnId: ctx.activeTurnId,
915 ...(event.itemId ? { itemId: event.itemId } : {}),
916 text: event.text,
917 rawPayload: event.rawPayload,
918 }),
919 );
920 return;
921 }
922 }),
923 ),
924 ).pipe(
925 Effect.catch((cause) =>
926 Effect.logError("Failed to process Cursor runtime notification.", { cause }),
927 ),
928 // Fork into the session scope, not the calling fiber. `forkChild`
929 // makes this a child of `startSession`, and Effect interrupts a
930 // fiber's children when it completes, so the consumer died as soon
931 // as `startSession` returned and every later notification was
932 // dropped. The scope is created, stored on the context and closed
933 // on teardown already; only the fork target was wrong.
934 Effect.forkIn(ctx.scope),
935 );
936​
937 ctx.notificationFiber = nf;
938 sessions.set(input.threadId, ctx);
939 sessionScopeTransferred = true;
940​
941 yield* offerRuntimeEvent({
942 type: "session.started",
943 ...(yield* makeEventStamp()),
944 provider: PROVIDER,
945 threadId: input.threadId,
946 payload: { resume: started.initializeResult },
947 });
948 yield* offerRuntimeEvent({
949 type: "session.state.changed",
950 ...(yield* makeEventStamp()),
951 provider: PROVIDER,
952 threadId: input.threadId,
953 payload: { state: "ready", reason: "Cursor ACP session ready" },
954 });
955 yield* offerRuntimeEvent({
956 type: "thread.started",
957 ...(yield* makeEventStamp()),
958 provider: PROVIDER,
959 threadId: input.threadId,
960 payload: { providerThreadId: started.sessionId },
961 });
962​
963 return session;
964 }).pipe(Effect.scoped),
965 );
966​
967 const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
968 Effect.gen(function* () {
969 const ctx = yield* requireSession(input.threadId);
970 // A sendTurn while a prompt is in flight is a steer: the agent folds
971 // the new prompt into the ongoing work, so the active turn id is
972 // reused instead of opening a new turn.
973 const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
974 const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
975 // Count this prompt immediately so a superseded in-flight prompt
976 // resolving from here on does not settle the turn; the matching
977 // decrement is the `ensuring` below.
978 ctx.promptsInFlight += 1;
979​
980 return yield* Effect.gen(function* () {
981 const turnModelSelection =
982 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
983 const model = turnModelSelection?.model ?? ctx.session.model;
984 const resolvedModel = resolveCursorAcpBaseModelId(model);
985 yield* applyRequestedSessionConfiguration({
986 runtime: ctx.acp,
987 runtimeMode: ctx.session.runtimeMode,
988 interactionMode: input.interactionMode,
989 modelSelection:
990 model === undefined
991 ? undefined
992 : {
993 model,
994 options: turnModelSelection?.options,
995 },
996 mapError: ({ cause, method }) =>
997 mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
998 });
999 ctx.activeTurnId = turnId;
1000 if (steeringTurnId === undefined) {
1001 ctx.lastPlanFingerprint = undefined;
1002 ctx.assistantReply = new CursorTransportFailure();
1004 ctx.session = {
1005 ...ctx.session,
1006 activeTurnId: turnId,
1007 updatedAt: yield* nowIso,
1008 };
1009​
1010 if (steeringTurnId === undefined) {
1011 yield* offerRuntimeEvent({
1012 type: "turn.started",
1013 ...(yield* makeEventStamp()),
1014 provider: PROVIDER,
1015 threadId: input.threadId,
1016 turnId,
1017 payload: { model: resolvedModel },
1018 });
1020​
1021 const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
1022 const rawPrompt = input.input?.trim() ?? "";
1023 if (rawPrompt) {
1024 let cursorSkillNames = ctx.cursorSkillNames;
1025 if (hasCursorSkillMention(rawPrompt) && cursorSkillNames === undefined) {
1026 const skills = yield* discoverCursorSkills(
1027 ctx.session.cwd,
1028 options?.environment,
1029 ).pipe(
1030 Effect.provideService(FileSystem.FileSystem, fileSystem),
1031 Effect.provideService(Path.Path, path),
1032 );
1033 cursorSkillNames = new Set(
1034 skills
1035 .filter((skill) => skill.enabled && skill.userInvocable !== false)
1036 .map((skill) => skill.name),
1037 );
1038 ctx.cursorSkillNames = cursorSkillNames;
1040 const prompt = cursorSkillNames
1041 ? rewriteCursorSkillMentions(rawPrompt, cursorSkillNames)
1042 : rawPrompt;
1043 promptParts.push({ type: "text", text: prompt });
1045 if (input.attachments && input.attachments.length > 0) {
1046 for (const attachment of input.attachments) {
1047 // Cursor ingests images only. Generic files reach the agent
1048 // through the path line ProviderService puts in the prompt.
1049 if (attachment.type !== "image") {
1050 continue;
1052 const attachmentPath = resolveAttachmentPath({
1053 attachmentsDir: serverConfig.attachmentsDir,
1054 attachment,
1055 });
1056 if (!attachmentPath) {
1057 return yield* new ProviderAdapterRequestError({
1058 provider: PROVIDER,
1059 method: "session/prompt",
1060 detail: `Invalid attachment id '${attachment.id}'.`,
1061 });
1063 const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
1064 Effect.mapError(
1065 (cause) =>
1066 new ProviderAdapterRequestError({
1067 provider: PROVIDER,
1068 method: "session/prompt",
1069 detail: cause.message,
1070 cause,
1071 }),
1072 ),
1073 );
1074 promptParts.push({
1075 type: "image",
1076 data: Buffer.from(bytes).toString("base64"),
1077 mimeType: attachment.mimeType,
1078 });
1081​
1082 if (promptParts.length === 0) {
1083 return yield* new ProviderAdapterValidationError({
1084 provider: PROVIDER,
1085 operation: "sendTurn",
1086 issue: "Turn requires non-empty text or attachments.",
1087 });
1089​
1090 // ACP commands parse the complete text. Extra context can turn an exact
1091 // command into an ordinary model prompt or change its arguments.
1092 const result = yield* ctx.acp
1093 .prompt({
1094 prompt: /^\/[^\s/]+(?:\s|$)/.test(rawPrompt)
1095 ? promptParts
1096 : [
1097 ...promptParts,
1099 type: "text",
1100 text: buildRuntimeInstructions({ harness: "Cursor", model: resolvedModel }),
1101 },
1102 ],
1103 })
1104 .pipe(
1105 Effect.mapError((error) =>
1106 mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
1107 ),
1108 );
1109​
1110 yield* ctx.acp.drainEvents;
1111 const failure = ctx.assistantReply.failure;
1112 if (ctx.promptsInFlight === 1 && result.stopReason !== "cancelled" && failure) {
1113 return yield* new ProviderAdapterRequestError({
1114 provider: PROVIDER,
1115 method: "session/prompt",
1116 detail: "Cursor reported a transport failure.",
1117 cause: failure,
1118 });
1120​
1121 const turnRecord = ctx.turns.find((turn) => turn.id === turnId);
1122 if (turnRecord) {
1123 turnRecord.items.push({ prompt: promptParts, result });
1124 } else {
1125 ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
1127 ctx.session = {
1128 ...ctx.session,
1129 activeTurnId: turnId,
1130 updatedAt: yield* nowIso,
1131 model: resolvedModel,
1132 };
1133​
1134 // Only the last remaining prompt settles the turn — a steer-
1135 // superseded prompt resolving (usually cancelled) while another is
1136 // in flight or pending must leave the merged turn running.
1137 if (ctx.promptsInFlight === 1) {
1138 yield* offerRuntimeEvent({
1139 type: "turn.completed",
1140 ...(yield* makeEventStamp()),
1141 provider: PROVIDER,
1142 threadId: input.threadId,
1143 turnId,
1144 payload: {
1145 state: result.stopReason === "cancelled" ? "cancelled" : "completed",
1146 stopReason: result.stopReason ?? null,
1147 },
1148 });
1150​
1151 return {
1152 threadId: input.threadId,
1153 turnId,
1154 resumeCursor: ctx.session.resumeCursor,
1155 };
1156 }).pipe(
1157 Effect.ensuring(
1158 Effect.sync(() => {
1159 ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
1160 }),
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 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 return yield* new ProviderAdapterRequestError({
1232 provider: PROVIDER,
1233 method: "thread/rollback",
1234 detail: "Cursor ACP sessions do not support provider-side rollback.",
1235 });
1236 });
1237​
1238 const stopSession: CursorAdapterShape["stopSession"] = (threadId) =>
1239 withThreadLock(
1240 threadId,
1241 Effect.gen(function* () {
1242 const ctx = yield* requireSession(threadId);
1243 yield* stopSessionInternal(ctx);
1244 }),
1245 );
1246​
1247 const listSessions: CursorAdapterShape["listSessions"] = () =>
1248 Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
1249​
1250 const hasSession: CursorAdapterShape["hasSession"] = (threadId) =>
1251 Effect.sync(() => {
1252 const c = sessions.get(threadId);
1253 return c !== undefined && !c.stopped;
1254 });
1255​
1256 const stopAll: CursorAdapterShape["stopAll"] = () =>
1257 Effect.forEach(sessions.values(), stopSessionInternal, { discard: true });
1258​
1259 yield* Effect.addFinalizer(() =>
1260 Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
1261 Effect.catch((cause) =>
1262 Effect.logError("Failed to emit Cursor session shutdown event.", { cause }),
1263 ),
1264 Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
1265 Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
1266 ),
1267 );
1268​
1269 const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
1270​
1271 return {
1272 provider: PROVIDER,
1273 capabilities: { sessionModelSwitch: "in-session", supportsConversationRollback: false },
1274 compaction: { type: "slash-command", command: "/compress" },
1275 startSession,
1276 sendTurn,
1277 interruptTurn,
1278 readThread,
1279 rollbackThread,
1280 respondToRequest,
1281 respondToUserInput,
1282 stopSession,
1283 listSessions,
1284 hasSession,
1285 stopAll,
1286 streamEvents,
1287 } satisfies CursorAdapterShape;
1288 });