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

CursorAdapter.ts

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