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

CursorAdapter.ts

1,383 lines51.8 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";
80import {
81 discoverCursorSkills,
82 hasCursorSkillMention,
83 rewriteCursorSkillMentions,
84} from "../Drivers/CursorSkills.ts";
85const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
86​
87const PROVIDER = ProviderDriverKind.make("cursor");
88const CURSOR_RESUME_VERSION = 1 as const;
89const ACP_PLAN_MODE_ALIASES = ["plan", "architect"];
90const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"];
91const ACP_APPROVAL_MODE_ALIASES = ["ask"];
92const CURSOR_TURN_ERROR_MAX_CHARS = 1_000;
93​
94function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
95 const result = encodeUnknownJsonStringExit(input);
96 return Exit.isSuccess(result) ? result.value : undefined;
98​
99export interface CursorAdapterLiveOptions {
100 readonly environment?: NodeJS.ProcessEnv;
101 readonly nativeEventLogPath?: string;
102 readonly nativeEventLogger?: EventNdjsonLogger;
103 /**
104 * Selections are honored when `modelSelection.instanceId` matches this value.
105 * Defaults to the legacy built-in instance id (`cursor`).
106 */
107 readonly instanceId?: ProviderInstanceId;
108 /**
109 * Optional per-session settings resolver. When provided the adapter yields
110 * this effect at the start of every session and uses the result instead of
111 * the `cursorSettings` captured at construction.
112 *
113 * Production instances bind settings to the instance scope (the hydration
114 * layer rebuilds the adapter on config change) and leave this undefined.
115 * Test suites that mutate `ServerSettingsService` mid-flight — e.g. to
116 * swap `binaryPath` to a mock ACP wrapper — pass a resolver that reads
117 * the latest snapshot so the closure isn't stale.
118 */
119 readonly resolveSettings?: Effect.Effect<CursorSettings>;
121​
122interface PendingApproval {
123 readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
124 readonly kind: string | "unknown";
126​
127interface PendingUserInput {
128 readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
130​
131interface CursorSessionContext {
132 readonly threadId: ThreadId;
133 session: ProviderSession;
134 readonly scope: Scope.Closeable;
135 readonly acp: AcpSessionRuntime.AcpSessionRuntime["Service"];
136 notificationFiber: Fiber.Fiber<void, never> | undefined;
137 readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
138 readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
139 /** Turns interrupted while sendTurn was still preparing (before the prompt
140 * reached the wire). acp.cancel is a no-op at that point, so sendTurn
141 * checks this set at its prompt checkpoints instead. Entries are removed
142 * when the turn settles. */
143 readonly cancelledTurnIds: Set<TurnId>;
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 stopped: boolean;
154​
155function settlePendingApprovalsAsCancelled(
156 pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
157): Effect.Effect<void> {
158 const pendingEntries = Array.from(pendingApprovals.values());
159 return Effect.forEach(
160 pendingEntries,
161 (pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
162 {
163 discard: true,
164 },
165 );
167​
168function settlePendingUserInputsAsEmptyAnswers(
169 pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
170): Effect.Effect<void> {
171 const pendingEntries = Array.from(pendingUserInputs.values());
172 return Effect.forEach(
173 pendingEntries,
174 (pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
175 {
176 discard: true,
177 },
178 );
180​
181function isRecord(value: unknown): value is Record<string, unknown> {
182 return typeof value === "object" && value !== null && !Array.isArray(value);
184​
185function parseCursorResume(raw: unknown): { sessionId: string } | undefined {
186 if (!isRecord(raw)) return undefined;
187 if (raw.schemaVersion !== CURSOR_RESUME_VERSION) return undefined;
188 if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined;
189 return { sessionId: raw.sessionId.trim() };
191​
192function normalizeModeSearchText(mode: AcpSessionMode): string {
193 return [mode.id, mode.name, mode.description]
194 .filter((value): value is string => typeof value === "string" && value.length > 0)
195 .join(" ")
196 .toLowerCase()
197 .replace(/[^a-z0-9]+/g, " ")
198 .trim();
200​
201function findModeByAliases(
202 modes: ReadonlyArray<AcpSessionMode>,
203 aliases: ReadonlyArray<string>,
204): AcpSessionMode | undefined {
205 const normalizedAliases = aliases.map((alias) => alias.toLowerCase());
206 for (const alias of normalizedAliases) {
207 const exact = modes.find((mode) => {
208 const id = mode.id.toLowerCase();
209 const name = mode.name.toLowerCase();
210 return id === alias || name === alias;
211 });
212 if (exact) {
213 return exact;
214 }
215 }
216 for (const alias of normalizedAliases) {
217 const partial = modes.find((mode) => normalizeModeSearchText(mode).includes(alias));
218 if (partial) {
219 return partial;
220 }
221 }
222 return undefined;
224​
225function isPlanMode(mode: AcpSessionMode): boolean {
226 return findModeByAliases([mode], ACP_PLAN_MODE_ALIASES) !== undefined;
228​
229function resolveRequestedModeId(input: {
230 readonly interactionMode: ProviderInteractionMode | undefined;
231 readonly runtimeMode: RuntimeMode;
232 readonly modeState: AcpSessionModeState | undefined;
233}): string | undefined {
234 const modeState = input.modeState;
235 if (!modeState) {
236 return undefined;
237 }
238​
239 if (input.interactionMode === "plan") {
240 return findModeByAliases(modeState.availableModes, ACP_PLAN_MODE_ALIASES)?.id;
241 }
242​
243 if (input.runtimeMode === "approval-required") {
244 return (
245 findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??
246 findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??
247 modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??
248 modeState.currentModeId
249 );
250 }
251​
252 return (
253 findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??
254 findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??
255 modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??
256 modeState.currentModeId
257 );
259​
260function applyRequestedSessionConfiguration<E>(input: {
261 readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"];
262 readonly runtimeMode: RuntimeMode;
263 readonly interactionMode: ProviderInteractionMode | undefined;
264 readonly modelSelection:
265 | {
266 readonly model: string;
267 readonly options?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
268 }
269 | undefined;
270 readonly mapError: (context: {
271 readonly cause: import("effect-acp/errors").AcpError;
272 readonly method: "session/set_config_option" | "session/set_mode";
273 }) => E;
274}): Effect.Effect<void, E> {
275 return Effect.gen(function* () {
276 if (input.modelSelection) {
277 yield* applyCursorAcpModelSelection({
278 runtime: input.runtime,
279 model: input.modelSelection.model,
280 selections: input.modelSelection.options,
281 mapError: ({ cause }) =>
282 input.mapError({
283 cause,
284 method: "session/set_config_option",
285 }),
286 });
287 }
288​
289 const requestedModeId = resolveRequestedModeId({
290 interactionMode: input.interactionMode,
291 runtimeMode: input.runtimeMode,
292 modeState: yield* input.runtime.getModeState,
293 });
294 if (!requestedModeId) {
295 return;
296 }
297​
298 yield* input.runtime.setMode(requestedModeId).pipe(
299 Effect.mapError((cause) =>
300 input.mapError({
301 cause,
302 method: "session/set_mode",
303 }),
304 ),
305 );
306 });
308​
309/**
310 * Maps an approval decision to the option id the agent actually advertised.
311 * ACP lets agents choose their own option ids — only the option kind is
312 * contractual — so the decision is mapped to a kind and matched against the
313 * request's own options (same style as selectAutoApprovedPermissionOption);
314 * the generic hyphenated fallback only applies when the agent offered no
315 * option of that kind.
316 */
317function selectCursorPermissionOptionId(
318 request: EffectAcpSchema.RequestPermissionRequest,
319 decision: Exclude<ProviderApprovalDecision, "cancel">,
320): string {
321 const kind =
322 decision === "acceptForSession"
323 ? "allow_always"
324 : decision === "accept"
325 ? "allow_once"
326 : "reject_once";
327 const match = request.options.find((option) => option.kind === kind);
328 if (typeof match?.optionId === "string" && match.optionId.trim()) {
329 return match.optionId.trim();
330 }
331 return acpPermissionOutcome(decision);
333​
334function selectAutoApprovedPermissionOption(
335 request: EffectAcpSchema.RequestPermissionRequest,
336): string | undefined {
337 const allowAlwaysOption = request.options.find((option) => option.kind === "allow_always");
338 if (typeof allowAlwaysOption?.optionId === "string" && allowAlwaysOption.optionId.trim()) {
339 return allowAlwaysOption.optionId.trim();
340 }
341​
342 const allowOnceOption = request.options.find((option) => option.kind === "allow_once");
343 if (typeof allowOnceOption?.optionId === "string" && allowOnceOption.optionId.trim()) {
344 return allowOnceOption.optionId.trim();
345 }
346​
347 return undefined;
349​
350export function makeCursorAdapter(
351 cursorSettings: CursorSettings,
352 options?: CursorAdapterLiveOptions,
353) {
354 return Effect.gen(function* () {
355 const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor");
356 const fileSystem = yield* FileSystem.FileSystem;
357 const path = yield* Path.Path;
358 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
359 const serverConfig = yield* Effect.service(ServerConfig);
360 const crypto = yield* Crypto.Crypto;
361 const nativeEventLogger =
362 options?.nativeEventLogger ??
363 (options?.nativeEventLogPath !== undefined
364 ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
365 stream: "native",
366 })
367 : undefined);
368 const managedNativeEventLogger =
369 options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
370 const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
371​
372 const sessions = new Map<ThreadId, CursorSessionContext>();
373 const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
374 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
375​
376 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
377 const randomUUIDv4 = crypto.randomUUIDv4.pipe(
378 Effect.mapError(
379 (cause) =>
380 new ProviderAdapterRequestError({
381 provider: PROVIDER,
382 method: "crypto/randomUUIDv4",
383 detail: "Failed to generate Cursor runtime identifier.",
384 cause,
385 }),
386 ),
387 );
388 const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));
389 const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
390 const mapExtensionFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
391 effect.pipe(
392 Effect.mapError(
393 (cause) =>
394 new EffectAcpErrors.AcpTransportError({
395 detail: "Failed to process Cursor ACP extension event.",
396 cause,
397 }),
398 ),
399 );
400​
401 const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
402 PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
403​
404 const getThreadSemaphore = (threadId: string) =>
405 SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
406 const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
407 current.get(threadId),
408 );
409 return Option.match(existing, {
410 onNone: () =>
411 Semaphore.make(1).pipe(
412 Effect.map((semaphore) => {
413 const next = new Map(current);
414 next.set(threadId, semaphore);
415 return [semaphore, next] as const;
416 }),
417 ),
418 onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
419 });
420 });
421​
422 const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
423 Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
424​
425 const logNative = (
426 threadId: ThreadId,
427 method: string,
428 payload: unknown,
429 _source: "acp.jsonrpc" | "acp.cursor.extension",
430 ) =>
431 Effect.gen(function* () {
432 if (!nativeEventLogger) return;
433 const observedAt = yield* nowIso;
434 yield* nativeEventLogger.write(
435 {
436 observedAt,
437 event: {
438 id: yield* randomUUIDv4,
439 kind: "notification",
440 provider: PROVIDER,
441 createdAt: observedAt,
442 method,
443 threadId,
444 payload,
445 },
446 },
447 threadId,
448 );
449 });
450​
451 const emitPlanUpdate = (
452 ctx: CursorSessionContext,
453 payload: {
454 readonly explanation?: string | null;
455 readonly plan: ReadonlyArray<{
456 readonly step: string;
457 readonly status: "pending" | "inProgress" | "completed";
458 }>;
459 },
460 rawPayload: unknown,
461 source: "acp.jsonrpc" | "acp.cursor.extension",
462 method: string,
463 ) =>
464 Effect.gen(function* () {
465 const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
466 if (ctx.lastPlanFingerprint === fingerprint) {
467 return;
468 }
469 ctx.lastPlanFingerprint = fingerprint;
470 yield* offerRuntimeEvent(
471 makeAcpPlanUpdatedEvent({
472 stamp: yield* makeEventStamp(),
473 provider: PROVIDER,
474 threadId: ctx.threadId,
475 turnId: ctx.activeTurnId,
476 payload,
477 source,
478 method,
479 rawPayload,
480 }),
481 );
482 });
483​
484 const requireSession = (
485 threadId: ThreadId,
486 ): Effect.Effect<CursorSessionContext, ProviderAdapterSessionNotFoundError> => {
487 const ctx = sessions.get(threadId);
488 if (!ctx || ctx.stopped) {
489 return Effect.fail(
490 new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),
491 );
492 }
493 return Effect.succeed(ctx);
494 };
495​
496 const stopSessionInternal = (ctx: CursorSessionContext) =>
497 Effect.gen(function* () {
498 if (ctx.stopped) return;
499 ctx.stopped = true;
500 yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
501 yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
502 if (ctx.notificationFiber) {
503 yield* Fiber.interrupt(ctx.notificationFiber);
504 }
505 yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
506 sessions.delete(ctx.threadId);
507 yield* offerRuntimeEvent({
508 type: "session.exited",
509 ...(yield* makeEventStamp()),
510 provider: PROVIDER,
511 threadId: ctx.threadId,
512 payload: { exitKind: "graceful" },
513 });
514 });
515​
516 const startSession: CursorAdapterShape["startSession"] = (input) =>
517 withThreadLock(
518 input.threadId,
519 Effect.gen(function* () {
520 if (input.provider !== undefined && input.provider !== PROVIDER) {
521 return yield* new ProviderAdapterValidationError({
522 provider: PROVIDER,
523 operation: "startSession",
524 issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
525 });
526 }
527 if (!input.cwd?.trim()) {
528 return yield* new ProviderAdapterValidationError({
529 provider: PROVIDER,
530 operation: "startSession",
531 issue: "cwd is required and must be non-empty.",
532 });
533 }
534​
535 const cwd = path.resolve(input.cwd.trim());
536 const cursorModelSelection =
537 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
538 const existing = sessions.get(input.threadId);
539 if (existing && !existing.stopped) {
540 yield* stopSessionInternal(existing);
541 }
542​
543 const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
544 const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
545 const sessionScope = yield* Scope.make("sequential");
546 let sessionScopeTransferred = false;
547 yield* Effect.addFinalizer(() =>
548 sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
549 );
550 let ctx!: CursorSessionContext;
551​
552 const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
553 const acpNativeLoggers = makeAcpNativeLoggers({
554 nativeEventLogger,
555 provider: PROVIDER,
556 threadId: input.threadId,
557 });
558​
559 // Resolve the CursorSettings used to spawn the ACP child. Production
560 // leaves `options.resolveSettings` undefined so we use the value
561 // captured at adapter construction — per-instance isolation is
562 // enforced by the hydration layer rebuilding this adapter whenever
563 // its config changes. Tests set `resolveSettings` to pull the latest
564 // snapshot from `ServerSettingsService` so that mid-suite
565 // `updateSettings({ providers: { cursor: { binaryPath } } })` calls
566 // actually take effect when the next session spawns.
567 const effectiveCursorSettings = options?.resolveSettings
568 ? yield* options.resolveSettings
569 : cursorSettings;
570​
571 const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
572 const acp = yield* makeCursorAcpRuntime({
573 cursorSettings: effectiveCursorSettings,
574 ...(options?.environment ? { environment: options.environment } : {}),
575 childProcessSpawner,
576 cwd,
577 runtimeMode: input.runtimeMode,
578 ...(resumeSessionId ? { resumeSessionId } : {}),
579 clientInfo: { name: "t3-code", version: "0.0.0" },
580 ...(mcpSession
581 ? {
582 mcpServers: [
583 {
584 type: "http" as const,
585 name: "t3-code",
586 url: mcpSession.endpoint,
587 headers: [
588 {
589 name: "Authorization",
590 value: mcpSession.authorizationHeader,
591 },
592 ],
593 },
594 ],
595 }
596 : {}),
597 ...acpNativeLoggers,
598 }).pipe(
599 Effect.provideService(Crypto.Crypto, crypto),
600 Effect.provideService(Scope.Scope, sessionScope),
601 Effect.mapError(
602 (cause) =>
603 new ProviderAdapterProcessError({
604 provider: PROVIDER,
605 threadId: input.threadId,
606 detail: cause.message,
607 cause,
608 }),
609 ),
610 );
611 const started = yield* Effect.gen(function* () {
612 yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
613 mapExtensionFailure(
614 Effect.gen(function* () {
615 yield* logNative(
616 input.threadId,
617 "cursor/ask_question",
618 params,
619 "acp.cursor.extension",
620 );
621 const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
622 const runtimeRequestId = RuntimeRequestId.make(requestId);
623 const answers = yield* Deferred.make<ProviderUserInputAnswers>();
624 pendingUserInputs.set(requestId, { answers });
625 yield* offerRuntimeEvent({
626 type: "user-input.requested",
627 ...(yield* makeEventStamp()),
628 provider: PROVIDER,
629 threadId: input.threadId,
630 turnId: ctx?.activeTurnId,
631 requestId: runtimeRequestId,
632 payload: { questions: extractAskQuestions(params) },
633 raw: {
634 source: "acp.cursor.extension",
635 method: "cursor/ask_question",
636 payload: params,
637 },
638 });
639 const resolved = yield* Deferred.await(answers);
640 pendingUserInputs.delete(requestId);
641 yield* offerRuntimeEvent({
642 type: "user-input.resolved",
643 ...(yield* makeEventStamp()),
644 provider: PROVIDER,
645 threadId: input.threadId,
646 turnId: ctx?.activeTurnId,
647 requestId: runtimeRequestId,
648 payload: { answers: resolved },
649 });
650 return { answers: resolved };
651 }),
652 ),
653 );
654 yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
655 mapExtensionFailure(
656 Effect.gen(function* () {
657 yield* logNative(
658 input.threadId,
659 "cursor/create_plan",
660 params,
661 "acp.cursor.extension",
662 );
663 yield* offerRuntimeEvent({
664 type: "turn.proposed.completed",
665 ...(yield* makeEventStamp()),
666 provider: PROVIDER,
667 threadId: input.threadId,
668 turnId: ctx?.activeTurnId,
669 payload: { planMarkdown: extractPlanMarkdown(params) },
670 raw: {
671 source: "acp.cursor.extension",
672 method: "cursor/create_plan",
673 payload: params,
674 },
675 });
676 return { accepted: true } as const;
677 }),
678 ),
679 );
680 yield* acp.handleExtNotification(
681 "cursor/update_todos",
682 CursorUpdateTodosRequest,
683 (params) =>
684 mapExtensionFailure(
685 Effect.gen(function* () {
686 yield* logNative(
687 input.threadId,
688 "cursor/update_todos",
689 params,
690 "acp.cursor.extension",
691 );
692 if (ctx) {
693 yield* emitPlanUpdate(
694 ctx,
695 extractTodosAsPlan(params),
696 params,
697 "acp.cursor.extension",
698 "cursor/update_todos",
699 );
700 }
701 }),
702 ),
703 );
704 yield* acp.handleRequestPermission((params) =>
705 mapExtensionFailure(
706 Effect.gen(function* () {
707 yield* logNative(
708 input.threadId,
709 "session/request_permission",
710 params,
711 "acp.jsonrpc",
712 );
713 if (input.runtimeMode === "full-access") {
714 const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
715 if (autoApprovedOptionId !== undefined) {
716 return {
717 outcome: {
718 outcome: "selected" as const,
719 optionId: autoApprovedOptionId,
720 },
721 };
722 }
723 }
724 const permissionRequest = parsePermissionRequest(params);
725 const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
726 const runtimeRequestId = RuntimeRequestId.make(requestId);
727 const decision = yield* Deferred.make<ProviderApprovalDecision>();
728 pendingApprovals.set(requestId, {
729 decision,
730 kind: permissionRequest.kind,
731 });
732 yield* offerRuntimeEvent(
733 makeAcpRequestOpenedEvent({
734 stamp: yield* makeEventStamp(),
735 provider: PROVIDER,
736 threadId: input.threadId,
737 turnId: ctx?.activeTurnId,
738 requestId: runtimeRequestId,
739 permissionRequest,
740 detail:
741 permissionRequest.detail ??
742 encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
743 "[unserializable params]",
744 args: params,
745 source: "acp.jsonrpc",
746 method: "session/request_permission",
747 rawPayload: params,
748 }),
749 );
750 const resolved = yield* Deferred.await(decision);
751 pendingApprovals.delete(requestId);
752 yield* offerRuntimeEvent(
753 makeAcpRequestResolvedEvent({
754 stamp: yield* makeEventStamp(),
755 provider: PROVIDER,
756 threadId: input.threadId,
757 turnId: ctx?.activeTurnId,
758 requestId: runtimeRequestId,
759 permissionRequest,
760 decision: resolved,
761 }),
762 );
763 return {
764 outcome:
765 resolved === "cancel"
766 ? ({ outcome: "cancelled" } as const)
767 : {
768 outcome: "selected" as const,
769 optionId: selectCursorPermissionOptionId(params, resolved),
770 },
771 };
772 }),
773 ),
774 );
775 return yield* acp.start();
776 }).pipe(
777 Effect.mapError((error) =>
778 mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
779 ),
780 );
781​
782 yield* applyRequestedSessionConfiguration({
783 runtime: acp,
784 runtimeMode: input.runtimeMode,
785 interactionMode: undefined,
786 modelSelection: cursorModelSelection,
787 mapError: ({ cause, method }) =>
788 mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
789 });
790​
791 const now = yield* nowIso;
792 const session: ProviderSession = {
793 provider: PROVIDER,
794 providerInstanceId: boundInstanceId,
795 status: "ready",
796 runtimeMode: input.runtimeMode,
797 cwd,
798 model: cursorModelSelection?.model,
799 threadId: input.threadId,
800 resumeCursor: {
801 schemaVersion: CURSOR_RESUME_VERSION,
802 sessionId: started.sessionId,
803 },
804 createdAt: now,
805 updatedAt: now,
806 };
807​
808 ctx = {
809 threadId: input.threadId,
810 session,
811 scope: sessionScope,
812 acp,
813 notificationFiber: undefined,
814 pendingApprovals,
815 pendingUserInputs,
816 cancelledTurnIds: new Set(),
817 turns: [],
818 lastPlanFingerprint: undefined,
819 activeTurnId: undefined,
820 cursorSkillNames: undefined,
821 promptsInFlight: 0,
822 stopped: false,
823 };
824​
825 const nf = yield* Stream.runDrain(
826 Stream.mapEffect(acp.getEvents(), (event) =>
827 Effect.gen(function* () {
828 switch (event._tag) {
829 case "EventStreamBarrier":
830 yield* Deferred.succeed(event.acknowledge, undefined);
831 return;
832 case "ModeChanged":
833 return;
834 case "AssistantItemStarted":
835 yield* offerRuntimeEvent(
836 makeAcpAssistantItemEvent({
837 stamp: yield* makeEventStamp(),
838 provider: PROVIDER,
839 threadId: ctx.threadId,
840 turnId: ctx.activeTurnId,
841 itemId: event.itemId,
842 lifecycle: "item.started",
843 }),
844 );
845 return;
846 case "AssistantItemCompleted":
847 yield* offerRuntimeEvent(
848 makeAcpAssistantItemEvent({
849 stamp: yield* makeEventStamp(),
850 provider: PROVIDER,
851 threadId: ctx.threadId,
852 turnId: ctx.activeTurnId,
853 itemId: event.itemId,
854 lifecycle: "item.completed",
855 }),
856 );
857 return;
858 case "PlanUpdated":
859 yield* logNative(
860 ctx.threadId,
861 "session/update",
862 event.rawPayload,
863 "acp.jsonrpc",
864 );
865 yield* emitPlanUpdate(
866 ctx,
867 event.payload,
868 event.rawPayload,
869 "acp.jsonrpc",
870 "session/update",
871 );
872 return;
873 case "ToolCallUpdated":
874 yield* logNative(
875 ctx.threadId,
876 "session/update",
877 event.rawPayload,
878 "acp.jsonrpc",
879 );
880 yield* offerRuntimeEvent(
881 makeAcpToolCallEvent({
882 stamp: yield* makeEventStamp(),
883 provider: PROVIDER,
884 threadId: ctx.threadId,
885 turnId: ctx.activeTurnId,
886 toolCall: event.toolCall,
887 rawPayload: event.rawPayload,
888 }),
889 );
890 return;
891 case "ContentDelta":
892 yield* logNative(
893 ctx.threadId,
894 "session/update",
895 event.rawPayload,
896 "acp.jsonrpc",
897 );
898 yield* offerRuntimeEvent(
899 makeAcpContentDeltaEvent({
900 stamp: yield* makeEventStamp(),
901 provider: PROVIDER,
902 threadId: ctx.threadId,
903 turnId: ctx.activeTurnId,
904 ...(event.itemId ? { itemId: event.itemId } : {}),
905 text: event.text,
906 rawPayload: event.rawPayload,
907 }),
908 );
909 return;
910 }
911 }),
912 ),
913 ).pipe(
914 Effect.catch((cause) =>
915 Effect.logError("Failed to process Cursor runtime notification.", { cause }),
916 ),
917 // Fork into the session scope, not the calling fiber. `forkChild`
918 // makes this a child of `startSession`, and Effect interrupts a
919 // fiber's children when it completes, so the consumer died as soon
920 // as `startSession` returned and every later notification was
921 // dropped. The scope is created, stored on the context and closed
922 // on teardown already; only the fork target was wrong.
923 Effect.forkIn(ctx.scope),
924 );
925​
926 ctx.notificationFiber = nf;
927 sessions.set(input.threadId, ctx);
928 sessionScopeTransferred = true;
929​
930 yield* offerRuntimeEvent({
931 type: "session.started",
932 ...(yield* makeEventStamp()),
933 provider: PROVIDER,
934 threadId: input.threadId,
935 payload: { resume: started.initializeResult },
936 });
937 yield* offerRuntimeEvent({
938 type: "session.state.changed",
939 ...(yield* makeEventStamp()),
940 provider: PROVIDER,
941 threadId: input.threadId,
942 payload: { state: "ready", reason: "Cursor ACP session ready" },
943 });
944 yield* offerRuntimeEvent({
945 type: "thread.started",
946 ...(yield* makeEventStamp()),
947 provider: PROVIDER,
948 threadId: input.threadId,
949 payload: { providerThreadId: started.sessionId },
950 });
951​
952 return session;
953 }).pipe(Effect.scoped),
954 );
955​
956 const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
957 Effect.gen(function* () {
958 const ctx = yield* requireSession(input.threadId);
959 // A sendTurn while a prompt is in flight is a steer: the agent folds
960 // the new prompt into the ongoing work, so the active turn id is
961 // reused instead of opening a new turn.
962 const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
963 const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
964 // Count this prompt immediately so a superseded in-flight prompt
965 // resolving from here on does not settle the turn; the matching
966 // decrement is the `ensuring` below. Bind the active turn id in the
967 // same synchronous stretch: after the increment, a concurrent
968 // sendTurn must already see this turn id or it would steer onto the
969 // previous one.
970 ctx.promptsInFlight += 1;
971 ctx.activeTurnId = turnId;
972​
973 // interruptTurn cannot reach a turn whose prompt has not been sent
974 // yet (acp.cancel is a no-op pre-prompt), so cancelled turn ids are
975 // checked at both checkpoints instead.
976 const settleIfCancelled = () =>
977 Effect.gen(function* () {
978 if (!ctx.cancelledTurnIds.has(turnId)) {
979 return false;
980 }
981 if (ctx.promptsInFlight !== 1) {
982 // A steered sibling prompt for this same turn is still in
983 // flight or preparing: skip the wire but keep the marker — the
984 // last draining prompt settles the turn (here once
985 // promptsInFlight === 1, or in the ensuring once it hits 0).
986 return true;
987 }
988 ctx.cancelledTurnIds.delete(turnId);
989 settled = true;
990 yield* offerRuntimeEvent({
991 type: "turn.completed",
992 ...(yield* makeEventStamp()),
993 provider: PROVIDER,
994 threadId: input.threadId,
995 turnId,
996 payload: { state: "cancelled", stopReason: "cancelled" },
997 });
998 return true;
999 });
1000​
1001 // Set once any path publishes this turn's terminal event, so the
1002 // ensuring below cannot republish it when a late interrupt re-adds
1003 // the cancel marker between the terminal publish and the drain.
1004 let settled = false;
1005 let turnStartedEmitted = false;
1006 return yield* Effect.gen(function* () {
1007 const turnModelSelection =
1008 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
1009 const model = turnModelSelection?.model ?? ctx.session.model;
1010 const resolvedModel = resolveCursorAcpBaseModelId(model);
1011 yield* applyRequestedSessionConfiguration({
1012 runtime: ctx.acp,
1013 runtimeMode: ctx.session.runtimeMode,
1014 interactionMode: input.interactionMode,
1015 modelSelection:
1016 model === undefined
1017 ? undefined
1018 : {
1019 model,
1020 options: turnModelSelection?.options,
1021 },
1022 mapError: ({ cause, method }) =>
1023 mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
1024 });
1025 if (steeringTurnId === undefined) {
1026 ctx.lastPlanFingerprint = undefined;
1028 ctx.session = {
1029 ...ctx.session,
1030 activeTurnId: turnId,
1031 updatedAt: yield* nowIso,
1032 };
1033​
1034 if (yield* settleIfCancelled()) {
1035 return {
1036 threadId: input.threadId,
1037 turnId,
1038 resumeCursor: ctx.session.resumeCursor,
1039 };
1041​
1042 if (steeringTurnId === undefined) {
1043 yield* offerRuntimeEvent({
1044 type: "turn.started",
1045 ...(yield* makeEventStamp()),
1046 provider: PROVIDER,
1047 threadId: input.threadId,
1048 turnId,
1049 payload: { model: resolvedModel },
1050 });
1051 turnStartedEmitted = true;
1053​
1054 const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
1055 const rawPrompt = input.input?.trim() ?? "";
1056 if (rawPrompt) {
1057 let cursorSkillNames = ctx.cursorSkillNames;
1058 if (hasCursorSkillMention(rawPrompt) && cursorSkillNames === undefined) {
1059 const skills = yield* discoverCursorSkills(
1060 ctx.session.cwd,
1061 options?.environment,
1062 ).pipe(
1063 Effect.provideService(FileSystem.FileSystem, fileSystem),
1064 Effect.provideService(Path.Path, path),
1065 );
1066 cursorSkillNames = new Set(
1067 skills
1068 .filter((skill) => skill.enabled && skill.userInvocable !== false)
1069 .map((skill) => skill.name),
1070 );
1071 ctx.cursorSkillNames = cursorSkillNames;
1073 const prompt = cursorSkillNames
1074 ? rewriteCursorSkillMentions(rawPrompt, cursorSkillNames)
1075 : rawPrompt;
1076 promptParts.push({ type: "text", text: prompt });
1078 if (input.attachments && input.attachments.length > 0) {
1079 for (const attachment of input.attachments) {
1080 // Cursor ingests images only. Generic files reach the agent
1081 // through the path line ProviderService puts in the prompt.
1082 if (attachment.type !== "image") {
1083 continue;
1085 const attachmentPath = resolveAttachmentPath({
1086 attachmentsDir: serverConfig.attachmentsDir,
1087 attachment,
1088 });
1089 if (!attachmentPath) {
1090 return yield* new ProviderAdapterRequestError({
1091 provider: PROVIDER,
1092 method: "session/prompt",
1093 detail: `Invalid attachment id '${attachment.id}'.`,
1094 });
1096 const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
1097 Effect.mapError(
1098 (cause) =>
1099 new ProviderAdapterRequestError({
1100 provider: PROVIDER,
1101 method: "session/prompt",
1102 detail: cause.message,
1103 cause,
1104 }),
1105 ),
1106 );
1107 promptParts.push({
1108 type: "image",
1109 data: Buffer.from(bytes).toString("base64"),
1110 mimeType: attachment.mimeType,
1111 });
1114​
1115 if (promptParts.length === 0) {
1116 return yield* new ProviderAdapterValidationError({
1117 provider: PROVIDER,
1118 operation: "sendTurn",
1119 issue: "Turn requires non-empty text or attachments.",
1120 });
1122​
1123 if (yield* settleIfCancelled()) {
1124 return {
1125 threadId: input.threadId,
1126 turnId,
1127 resumeCursor: ctx.session.resumeCursor,
1128 };
1130​
1131 const result = yield* ctx.acp
1132 .prompt({
1133 prompt: promptParts,
1134 })
1135 .pipe(
1136 Effect.mapError((error) =>
1137 mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
1138 ),
1139 );
1140​
1141 const turnRecord = ctx.turns.find((turn) => turn.id === turnId);
1142 if (turnRecord) {
1143 turnRecord.items.push({ prompt: promptParts, result });
1144 } else {
1145 ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
1147 ctx.session = {
1148 ...ctx.session,
1149 activeTurnId: turnId,
1150 updatedAt: yield* nowIso,
1151 model: resolvedModel,
1152 };
1153​
1154 // Only the last remaining prompt settles the turn — a steer-
1155 // superseded prompt resolving (usually cancelled) while another is
1156 // in flight or pending must leave the merged turn running.
1157 if (ctx.promptsInFlight === 1) {
1158 ctx.cancelledTurnIds.delete(turnId);
1159 settled = true;
1160 yield* offerRuntimeEvent({
1161 type: "turn.completed",
1162 ...(yield* makeEventStamp()),
1163 provider: PROVIDER,
1164 threadId: input.threadId,
1165 turnId,
1166 payload: {
1167 state: result.stopReason === "cancelled" ? "cancelled" : "completed",
1168 stopReason: result.stopReason ?? null,
1169 },
1170 });
1172​
1173 return {
1174 threadId: input.threadId,
1175 turnId,
1176 resumeCursor: ctx.session.resumeCursor,
1177 };
1178 }).pipe(
1179 // A failure after turn.started must still close the turn: surface
1180 // it as turn.completed(failed) before the error propagates so the
1181 // UI never waits on a dead turn. Same settle rule as the success
1182 // path — only the last remaining prompt may settle.
1183 Effect.tapError((error) =>
1184 ctx.promptsInFlight !== 1 ||
1185 ctx.stopped || // session torn down or replaced mid-flight; a late failure must not publish on a dead/new session
1186 (!turnStartedEmitted && steeringTurnId === undefined)
1187 ? Effect.void
1188 : Effect.gen(function* () {
1189 ctx.cancelledTurnIds.delete(turnId);
1190 settled = true;
1191 const rawMessage =
1192 typeof error === "object" && error !== null && "message" in error
1193 ? error.message
1194 : undefined;
1195 const collapsed = (typeof rawMessage === "string" ? rawMessage : String(error))
1196 .replace(/\s+/g, " ")
1197 .trim();
1198 yield* offerRuntimeEvent({
1199 type: "turn.completed",
1200 ...(yield* makeEventStamp()),
1201 provider: PROVIDER,
1202 threadId: input.threadId,
1203 turnId,
1204 payload: {
1205 state: "failed",
1206 stopReason: null,
1207 errorMessage:
1208 collapsed.length > CURSOR_TURN_ERROR_MAX_CHARS
1209 ? `${collapsed.slice(0, CURSOR_TURN_ERROR_MAX_CHARS - 1)}…`
1210 : collapsed,
1211 },
1212 });
1213 }),
1214 ),
1215 // The last draining prompt settles a cancelled turn whose
1216 // checkpoints all ran while a steered sibling was still in flight
1217 // (those skip the wire but leave the marker in place).
1218 Effect.ensuring(
1219 // Finalizers must be infallible; the decrement is a leading sync
1220 // step, so ignoring a failed settle publish cannot skip it.
1221 Effect.ignore(
1222 Effect.gen(function* () {
1223 ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
1224 if (
1225 !settled &&
1226 ctx.promptsInFlight === 0 &&
1227 !ctx.stopped &&
1228 ctx.cancelledTurnIds.delete(turnId)
1229 ) {
1230 yield* offerRuntimeEvent({
1231 type: "turn.completed",
1232 ...(yield* makeEventStamp()),
1233 provider: PROVIDER,
1234 threadId: input.threadId,
1235 turnId,
1236 payload: { state: "cancelled", stopReason: "cancelled" },
1237 });
1239 }),
1240 ),
1241 ),
1242 );
1243 });
1244​
1245 const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId, turnId) =>
1246 Effect.gen(function* () {
1247 const ctx = yield* requireSession(threadId);
1248 if (turnId !== undefined && turnId !== ctx.activeTurnId) {
1249 // A cancel addressed to a non-active turn must never reach the
1250 // wire: acp.cancel would kill whatever prompt IS active on this
1251 // session. While a prompt is in flight the addressed sendTurn may
1252 // not have become active yet, so record the cancel for its
1253 // checkpoints; a completed or unknown turn is ignored.
1254 if (ctx.promptsInFlight > 0) {
1255 ctx.cancelledTurnIds.add(turnId);
1257 return;
1259 // Pre-prompt cancellation cannot ride acp.cancel (a no-op until the
1260 // prompt is on the wire); sendTurn checks this set at its prompt
1261 // checkpoints and settles the turn as cancelled instead.
1262 if (ctx.activeTurnId !== undefined) {
1263 ctx.cancelledTurnIds.add(ctx.activeTurnId);
1265 yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
1266 yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
1267 yield* Effect.ignore(
1268 ctx.acp.cancel.pipe(
1269 Effect.mapError((error) =>
1270 mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
1271 ),
1272 ),
1273 );
1274 });
1275​
1276 const respondToRequest: CursorAdapterShape["respondToRequest"] = (
1277 threadId,
1278 requestId,
1279 decision,
1280 ) =>
1281 Effect.gen(function* () {
1282 const ctx = yield* requireSession(threadId);
1283 const pending = ctx.pendingApprovals.get(requestId);
1284 if (!pending) {
1285 return yield* new ProviderAdapterRequestError({
1286 provider: PROVIDER,
1287 method: "session/request_permission",
1288 detail: `Unknown pending approval request: ${requestId}`,
1289 });
1291 yield* Deferred.succeed(pending.decision, decision);
1292 });
1293​
1294 const respondToUserInput: CursorAdapterShape["respondToUserInput"] = (
1295 threadId,
1296 requestId,
1297 answers,
1298 ) =>
1299 Effect.gen(function* () {
1300 const ctx = yield* requireSession(threadId);
1301 const pending = ctx.pendingUserInputs.get(requestId);
1302 if (!pending) {
1303 return yield* new ProviderAdapterRequestError({
1304 provider: PROVIDER,
1305 method: "cursor/ask_question",
1306 detail: `Unknown pending user-input request: ${requestId}`,
1307 });
1309 yield* Deferred.succeed(pending.answers, answers);
1310 });
1311​
1312 const readThread: CursorAdapterShape["readThread"] = (threadId) =>
1313 Effect.gen(function* () {
1314 const ctx = yield* requireSession(threadId);
1315 return { threadId, turns: ctx.turns };
1316 });
1317​
1318 const rollbackThread: CursorAdapterShape["rollbackThread"] = (threadId, numTurns) =>
1319 Effect.gen(function* () {
1320 const ctx = yield* requireSession(threadId);
1321 if (!Number.isInteger(numTurns) || numTurns < 1) {
1322 return yield* new ProviderAdapterValidationError({
1323 provider: PROVIDER,
1324 operation: "rollbackThread",
1325 issue: "numTurns must be an integer >= 1.",
1326 });
1328 const nextLength = Math.max(0, ctx.turns.length - numTurns);
1329 ctx.turns.splice(nextLength);
1330 return { threadId, turns: ctx.turns };
1331 });
1332​
1333 const stopSession: CursorAdapterShape["stopSession"] = (threadId) =>
1334 withThreadLock(
1335 threadId,
1336 Effect.gen(function* () {
1337 const ctx = yield* requireSession(threadId);
1338 yield* stopSessionInternal(ctx);
1339 }),
1340 );
1341​
1342 const listSessions: CursorAdapterShape["listSessions"] = () =>
1343 Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
1344​
1345 const hasSession: CursorAdapterShape["hasSession"] = (threadId) =>
1346 Effect.sync(() => {
1347 const c = sessions.get(threadId);
1348 return c !== undefined && !c.stopped;
1349 });
1350​
1351 const stopAll: CursorAdapterShape["stopAll"] = () =>
1352 Effect.forEach(sessions.values(), stopSessionInternal, { discard: true });
1353​
1354 yield* Effect.addFinalizer(() =>
1355 Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
1356 Effect.catch((cause) =>
1357 Effect.logError("Failed to emit Cursor session shutdown event.", { cause }),
1358 ),
1359 Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
1360 Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
1361 ),
1362 );
1363​
1364 const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
1365​
1366 return {
1367 provider: PROVIDER,
1368 capabilities: { sessionModelSwitch: "in-session" },
1369 startSession,
1370 sendTurn,
1371 interruptTurn,
1372 readThread,
1373 rollbackThread,
1374 respondToRequest,
1375 respondToUserInput,
1376 stopSession,
1377 listSessions,
1378 hasSession,
1379 stopAll,
1380 streamEvents,
1381 } satisfies CursorAdapterShape;
1382 });