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

CursorAdapter.ts

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