| ... | ... | @@ -1,1566 +0,0 @@ |
| 1 | | /** |
| 2 | | * CursorAdapterLive - Scoped live implementation for the Cursor ACP provider adapter. |
| 3 | | * |
| 4 | | * Spawns `agent acp` over stdio, manages JSON-RPC session lifecycle, and maps |
| 5 | | * ACP notifications/requests into canonical provider runtime events. |
| 6 | | * |
| 7 | | * @module CursorAdapterLive |
| 8 | | */ |
| 9 | | import { randomUUID } from "node:crypto"; |
| 10 | | import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; |
| 11 | | import readline from "node:readline"; |
| 12 | | |
| 13 | | import { |
| 14 | | ApprovalRequestId, |
| 15 | | EventId, |
| 16 | | type CanonicalItemType, |
| 17 | | type CanonicalRequestType, |
| 18 | | ProviderItemId, |
| 19 | | type ProviderRuntimeEvent, |
| 20 | | type ProviderSession, |
| 21 | | type ProviderTurnStartResult, |
| 22 | | type RuntimeMode, |
| 23 | | RuntimeItemId, |
| 24 | | RuntimeRequestId, |
| 25 | | ThreadId, |
| 26 | | TurnId, |
| 27 | | } from "@t3tools/contracts"; |
| 28 | | import { DateTime, Effect, Layer, Queue, Random, Schema, Stream } from "effect"; |
| 29 | | |
| 30 | | import { |
| 31 | | ProviderAdapterProcessError, |
| 32 | | ProviderAdapterRequestError, |
| 33 | | ProviderAdapterSessionClosedError, |
| 34 | | ProviderAdapterSessionNotFoundError, |
| 35 | | ProviderAdapterValidationError, |
| 36 | | type ProviderAdapterError, |
| 37 | | } from "../Errors.ts"; |
| 38 | | import { |
| 39 | | CursorAdapter, |
| 40 | | type CursorAdapterShape, |
| 41 | | CursorAcpInitializeResult, |
| 42 | | CursorAcpPermissionRequest, |
| 43 | | CursorAcpSessionNewResult, |
| 44 | | CursorAcpSessionPromptResult, |
| 45 | | CursorAcpSessionUpdateNotification, |
| 46 | | } from "../Services/CursorAdapter.ts"; |
| 47 | | import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; |
| 48 | | |
| 49 | | const PROVIDER = "cursor" as const; |
| 50 | | const DEFAULT_REQUEST_TIMEOUT_MS = 120_000; |
| 51 | | const CURSOR_ACP_PROTOCOL_VERSION = 1; |
| 52 | | |
| 53 | | interface CursorResumeState { |
| 54 | | readonly acpSessionId?: string; |
| 55 | | } |
| 56 | | |
| 57 | | interface PendingRequest { |
| 58 | | readonly method: string; |
| 59 | | readonly timeout: ReturnType<typeof setTimeout>; |
| 60 | | readonly resolve: (value: unknown) => void; |
| 61 | | readonly reject: (error: Error) => void; |
| 62 | | } |
| 63 | | |
| 64 | | interface PendingPermission { |
| 65 | | readonly jsonRpcId: string | number; |
| 66 | | readonly requestType: CanonicalRequestType; |
| 67 | | readonly options: ReadonlyArray<{ optionId: string }>; |
| 68 | | } |
| 69 | | |
| 70 | | interface CursorTurnState { |
| 71 | | readonly turnId: TurnId; |
| 72 | | readonly assistantItemId: ReturnType<typeof ProviderItemId.makeUnsafe>; |
| 73 | | readonly startedToolCalls: Set<string>; |
| 74 | | readonly toolCalls: Map<string, { itemType: CanonicalItemType; title: string }>; |
| 75 | | readonly items: Array<unknown>; |
| 76 | | } |
| 77 | | |
| 78 | | interface CursorSessionContext { |
| 79 | | session: ProviderSession; |
| 80 | | runtimeMode: RuntimeMode; |
| 81 | | readonly child: ChildProcessWithoutNullStreams; |
| 82 | | readonly output: readline.Interface; |
| 83 | | readonly pending: Map<string, PendingRequest>; |
| 84 | | readonly pendingPermissions: Map<ApprovalRequestId, PendingPermission>; |
| 85 | | readonly turns: Array<{ |
| 86 | | id: TurnId; |
| 87 | | items: Array<unknown>; |
| 88 | | }>; |
| 89 | | turnState: CursorTurnState | undefined; |
| 90 | | acpSessionId: string; |
| 91 | | nextRpcId: number; |
| 92 | | stopping: boolean; |
| 93 | | } |
| 94 | | |
| 95 | | export interface CursorAdapterLiveOptions { |
| 96 | | readonly createProcess?: (input: { |
| 97 | | readonly binaryPath: string; |
| 98 | | readonly cwd: string; |
| 99 | | readonly env: NodeJS.ProcessEnv; |
| 100 | | readonly model?: string; |
| 101 | | }) => ChildProcessWithoutNullStreams; |
| 102 | | readonly nativeEventLogPath?: string; |
| 103 | | readonly nativeEventLogger?: EventNdjsonLogger; |
| 104 | | } |
| 105 | | |
| 106 | | function toMessage(cause: unknown, fallback: string): string { |
| 107 | | if (cause instanceof Error && cause.message.length > 0) { |
| 108 | | return cause.message; |
| 109 | | } |
| 110 | | return fallback; |
| 111 | | } |
| 112 | | |
| 113 | | function asRuntimeItemId(value: string): RuntimeItemId { |
| 114 | | return RuntimeItemId.makeUnsafe(value); |
| 115 | | } |
| 116 | | |
| 117 | | function asProviderItemId(value: string): ProviderItemId { |
| 118 | | return ProviderItemId.makeUnsafe(value); |
| 119 | | } |
| 120 | | |
| 121 | | function asRuntimeRequestId(value: ApprovalRequestId): RuntimeRequestId { |
| 122 | | return RuntimeRequestId.makeUnsafe(value); |
| 123 | | } |
| 124 | | |
| 125 | | function toSessionError( |
| 126 | | threadId: ThreadId, |
| 127 | | cause: unknown, |
| 128 | | ): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined { |
| 129 | | const normalized = toMessage(cause, "").toLowerCase(); |
| 130 | | if (normalized.includes("unknown session") || normalized.includes("not found")) { |
| 131 | | return new ProviderAdapterSessionNotFoundError({ |
| 132 | | provider: PROVIDER, |
| 133 | | threadId, |
| 134 | | cause, |
| 135 | | }); |
| 136 | | } |
| 137 | | if (normalized.includes("closed")) { |
| 138 | | return new ProviderAdapterSessionClosedError({ |
| 139 | | provider: PROVIDER, |
| 140 | | threadId, |
| 141 | | cause, |
| 142 | | }); |
| 143 | | } |
| 144 | | return undefined; |
| 145 | | } |
| 146 | | |
| 147 | | function toRequestError( |
| 148 | | threadId: ThreadId, |
| 149 | | method: string, |
| 150 | | cause: unknown, |
| 151 | | ): ProviderAdapterError { |
| 152 | | const sessionError = toSessionError(threadId, cause); |
| 153 | | if (sessionError) { |
| 154 | | return sessionError; |
| 155 | | } |
| 156 | | return new ProviderAdapterRequestError({ |
| 157 | | provider: PROVIDER, |
| 158 | | method, |
| 159 | | detail: toMessage(cause, `${method} failed`), |
| 160 | | cause, |
| 161 | | }); |
| 162 | | } |
| 163 | | |
| 164 | | function asObject(value: unknown): Record<string, unknown> | undefined { |
| 165 | | if (!value || typeof value !== "object") { |
| 166 | | return undefined; |
| 167 | | } |
| 168 | | return value as Record<string, unknown>; |
| 169 | | } |
| 170 | | |
| 171 | | function asString(value: unknown): string | undefined { |
| 172 | | return typeof value === "string" ? value : undefined; |
| 173 | | } |
| 174 | | |
| 175 | | function normalizeToolItemType(kind: unknown, title: unknown): CanonicalItemType { |
| 176 | | const normalizedKind = asString(kind)?.toLowerCase(); |
| 177 | | const normalizedTitle = asString(title)?.toLowerCase(); |
| 178 | | |
| 179 | | if (normalizedKind === "execute") { |
| 180 | | return "command_execution"; |
| 181 | | } |
| 182 | | if (normalizedKind === "edit" || normalizedKind === "write") { |
| 183 | | return "file_change"; |
| 184 | | } |
| 185 | | if (normalizedKind === "mcp") { |
| 186 | | return "mcp_tool_call"; |
| 187 | | } |
| 188 | | if (normalizedTitle?.includes("terminal")) { |
| 189 | | return "command_execution"; |
| 190 | | } |
| 191 | | return "dynamic_tool_call"; |
| 192 | | } |
| 193 | | |
| 194 | | function normalizeRequestType(toolCall: unknown): CanonicalRequestType { |
| 195 | | const record = asObject(toolCall); |
| 196 | | const kind = asString(record?.kind)?.toLowerCase(); |
| 197 | | if (kind === "execute") { |
| 198 | | return "command_execution_approval"; |
| 199 | | } |
| 200 | | if (kind === "edit" || kind === "write") { |
| 201 | | return "file_change_approval"; |
| 202 | | } |
| 203 | | return "unknown"; |
| 204 | | } |
| 205 | | |
| 206 | | function selectCursorPermissionOption( |
| 207 | | options: ReadonlyArray<{ optionId: string }>, |
| 208 | | decision: "acceptForSession" | "accept" | "decline" | "cancel", |
| 209 | | ): string | undefined { |
| 210 | | const allowAlways = options.find((option) => option.optionId === "allow-always"); |
| 211 | | const allowOnce = options.find((option) => option.optionId === "allow-once"); |
| 212 | | const rejectOnce = options.find((option) => option.optionId === "reject-once"); |
| 213 | | |
| 214 | | if (decision === "acceptForSession") { |
| 215 | | return allowAlways?.optionId ?? allowOnce?.optionId; |
| 216 | | } |
| 217 | | if (decision === "accept") { |
| 218 | | return allowOnce?.optionId ?? allowAlways?.optionId; |
| 219 | | } |
| 220 | | return rejectOnce?.optionId ?? options[0]?.optionId; |
| 221 | | } |
| 222 | | |
| 223 | | function selectCursorAutoApprovalOption( |
| 224 | | options: ReadonlyArray<{ optionId: string }>, |
| 225 | | ): { optionId: string; decision: "acceptForSession" | "accept" } | undefined { |
| 226 | | const allowAlways = options.find((option) => option.optionId === "allow-always"); |
| 227 | | if (allowAlways) { |
| 228 | | return { |
| 229 | | optionId: allowAlways.optionId, |
| 230 | | decision: "acceptForSession", |
| 231 | | }; |
| 232 | | } |
| 233 | | const allowOnce = options.find((option) => option.optionId === "allow-once"); |
| 234 | | if (allowOnce) { |
| 235 | | return { |
| 236 | | optionId: allowOnce.optionId, |
| 237 | | decision: "accept", |
| 238 | | }; |
| 239 | | } |
| 240 | | return undefined; |
| 241 | | } |
| 242 | | |
| 243 | | function titleForItemType(itemType: CanonicalItemType): string { |
| 244 | | switch (itemType) { |
| 245 | | case "command_execution": |
| 246 | | return "Command run"; |
| 247 | | case "file_change": |
| 248 | | return "File change"; |
| 249 | | case "mcp_tool_call": |
| 250 | | return "MCP tool call"; |
| 251 | | case "dynamic_tool_call": |
| 252 | | return "Tool call"; |
| 253 | | default: |
| 254 | | return "Item"; |
| 255 | | } |
| 256 | | } |
| 257 | | |
| 258 | | function summarizeToolOutput(rawOutput: unknown): string | undefined { |
| 259 | | const output = asObject(rawOutput); |
| 260 | | if (!output) return undefined; |
| 261 | | |
| 262 | | const stdout = asString(output.stdout); |
| 263 | | if (stdout && stdout.trim().length > 0) { |
| 264 | | return stdout.trim().slice(0, 400); |
| 265 | | } |
| 266 | | |
| 267 | | const summary = JSON.stringify(output); |
| 268 | | return summary.length > 400 ? `${summary.slice(0, 397)}...` : summary; |
| 269 | | } |
| 270 | | |
| 271 | | function mapStopReasonToTurnState( |
| 272 | | stopReason: string | undefined, |
| 273 | | ): "completed" | "failed" | "interrupted" | "cancelled" { |
| 274 | | if (stopReason === "cancelled") return "cancelled"; |
| 275 | | if (stopReason === "interrupted") return "interrupted"; |
| 276 | | return "completed"; |
| 277 | | } |
| 278 | | |
| 279 | | function readCursorResumeState(resumeCursor: unknown): CursorResumeState | undefined { |
| 280 | | if (!resumeCursor || typeof resumeCursor !== "object") { |
| 281 | | return undefined; |
| 282 | | } |
| 283 | | |
| 284 | | const cursor = resumeCursor as { |
| 285 | | acpSessionId?: unknown; |
| 286 | | sessionId?: unknown; |
| 287 | | }; |
| 288 | | |
| 289 | | const acpSessionId = |
| 290 | | typeof cursor.acpSessionId === "string" |
| 291 | | ? cursor.acpSessionId |
| 292 | | : typeof cursor.sessionId === "string" |
| 293 | | ? cursor.sessionId |
| 294 | | : undefined; |
| 295 | | |
| 296 | | if (!acpSessionId) { |
| 297 | | return {}; |
| 298 | | } |
| 299 | | return { acpSessionId }; |
| 300 | | } |
| 301 | | |
| 302 | | function writeCursorMessage(context: CursorSessionContext, message: unknown): void { |
| 303 | | if (!context.child.stdin.writable) { |
| 304 | | throw new Error("Cannot write to Cursor ACP stdin."); |
| 305 | | } |
| 306 | | context.child.stdin.write(`${JSON.stringify(message)}\n`); |
| 307 | | } |
| 308 | | |
| 309 | | function makeCursorAdapter(options?: CursorAdapterLiveOptions) { |
| 310 | | return Effect.gen(function* () { |
| 311 | | const nativeEventLogger = |
| 312 | | options?.nativeEventLogger ?? |
| 313 | | (options?.nativeEventLogPath !== undefined |
| 314 | | ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { |
| 315 | | stream: "native", |
| 316 | | }) |
| 317 | | : undefined); |
| 318 | | |
| 319 | | const nowIso = Effect.map(DateTime.now, DateTime.formatIso); |
| 320 | | const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.makeUnsafe(id)); |
| 321 | | const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso }); |
| 322 | | |
| 323 | | const sessions = new Map<ThreadId, CursorSessionContext>(); |
| 324 | | const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>(); |
| 325 | | |
| 326 | | const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> => |
| 327 | | Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid); |
| 328 | | |
| 329 | | const spawnCursorAcp = (input: { |
| 330 | | readonly binaryPath: string; |
| 331 | | readonly cwd: string; |
| 332 | | readonly env: NodeJS.ProcessEnv; |
| 333 | | readonly model?: string; |
| 334 | | }): ChildProcessWithoutNullStreams => { |
| 335 | | if (options?.createProcess) { |
| 336 | | return options.createProcess(input); |
| 337 | | } |
| 338 | | const args = input.model ? ["--model", input.model, "acp"] : ["acp"]; |
| 339 | | return spawn(input.binaryPath, args, { |
| 340 | | cwd: input.cwd, |
| 341 | | env: input.env, |
| 342 | | stdio: ["pipe", "pipe", "pipe"], |
| 343 | | }); |
| 344 | | }; |
| 345 | | |
| 346 | | const sendRequest = ( |
| 347 | | context: CursorSessionContext, |
| 348 | | method: string, |
| 349 | | params: unknown, |
| 350 | | timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, |
| 351 | | ): Promise<unknown> => { |
| 352 | | const id = context.nextRpcId; |
| 353 | | context.nextRpcId += 1; |
| 354 | | |
| 355 | | return new Promise((resolve, reject) => { |
| 356 | | const timeout = setTimeout(() => { |
| 357 | | context.pending.delete(String(id)); |
| 358 | | reject(new Error(`Timed out waiting for ${method}.`)); |
| 359 | | }, timeoutMs); |
| 360 | | |
| 361 | | context.pending.set(String(id), { |
| 362 | | method, |
| 363 | | timeout, |
| 364 | | resolve, |
| 365 | | reject, |
| 366 | | }); |
| 367 | | |
| 368 | | writeCursorMessage(context, { |
| 369 | | jsonrpc: "2.0", |
| 370 | | id, |
| 371 | | method, |
| 372 | | params, |
| 373 | | }); |
| 374 | | }); |
| 375 | | }; |
| 376 | | |
| 377 | | const resolvePendingRequest = ( |
| 378 | | context: CursorSessionContext, |
| 379 | | message: Record<string, unknown>, |
| 380 | | ) => { |
| 381 | | const id = message.id; |
| 382 | | if (typeof id !== "string" && typeof id !== "number") { |
| 383 | | return; |
| 384 | | } |
| 385 | | const pending = context.pending.get(String(id)); |
| 386 | | if (!pending) { |
| 387 | | return; |
| 388 | | } |
| 389 | | |
| 390 | | clearTimeout(pending.timeout); |
| 391 | | context.pending.delete(String(id)); |
| 392 | | |
| 393 | | const error = asObject(message.error); |
| 394 | | if (error) { |
| 395 | | pending.reject(new Error(`${pending.method} failed: ${JSON.stringify(error)}`)); |
| 396 | | return; |
| 397 | | } |
| 398 | | |
| 399 | | pending.resolve(message.result); |
| 400 | | }; |
| 401 | | |
| 402 | | const decodePermissionRequest = Schema.decodeUnknownSync(CursorAcpPermissionRequest); |
| 403 | | const decodeSessionUpdateNotification = Schema.decodeUnknownSync( |
| 404 | | CursorAcpSessionUpdateNotification, |
| 405 | | ); |
| 406 | | |
| 407 | | const emitRuntimeWarning = ( |
| 408 | | context: CursorSessionContext, |
| 409 | | message: string, |
| 410 | | detail?: unknown, |
| 411 | | ): Effect.Effect<void> => |
| 412 | | Effect.gen(function* () { |
| 413 | | const stamp = yield* makeEventStamp(); |
| 414 | | yield* offerRuntimeEvent({ |
| 415 | | type: "runtime.warning", |
| 416 | | eventId: stamp.eventId, |
| 417 | | provider: PROVIDER, |
| 418 | | createdAt: stamp.createdAt, |
| 419 | | threadId: context.session.threadId, |
| 420 | | ...((context.turnState ? { turnId: context.turnState.turnId } : {})), |
| 421 | | payload: { |
| 422 | | message, |
| 423 | | ...(detail !== undefined ? { detail } : {}), |
| 424 | | }, |
| 425 | | ...(context.turnState |
| 426 | | ? { providerRefs: { providerTurnId: String(context.turnState.turnId) } } |
| 427 | | : {}), |
| 428 | | }); |
| 429 | | }); |
| 430 | | |
| 431 | | const completeTurn = ( |
| 432 | | context: CursorSessionContext, |
| 433 | | state: "completed" | "failed" | "interrupted" | "cancelled", |
| 434 | | errorMessage?: string, |
| 435 | | stopReason?: string, |
| 436 | | ): Effect.Effect<void> => |
| 437 | | Effect.gen(function* () { |
| 438 | | const turnState = context.turnState; |
| 439 | | if (!turnState) { |
| 440 | | return; |
| 441 | | } |
| 442 | | |
| 443 | | const itemStamp = yield* makeEventStamp(); |
| 444 | | yield* offerRuntimeEvent({ |
| 445 | | type: "item.completed", |
| 446 | | eventId: itemStamp.eventId, |
| 447 | | provider: PROVIDER, |
| 448 | | createdAt: itemStamp.createdAt, |
| 449 | | threadId: context.session.threadId, |
| 450 | | turnId: turnState.turnId, |
| 451 | | itemId: asRuntimeItemId(turnState.assistantItemId), |
| 452 | | payload: { |
| 453 | | itemType: "assistant_message", |
| 454 | | status: "completed", |
| 455 | | title: "Assistant message", |
| 456 | | }, |
| 457 | | providerRefs: { |
| 458 | | providerTurnId: String(turnState.turnId), |
| 459 | | providerItemId: turnState.assistantItemId, |
| 460 | | }, |
| 461 | | }); |
| 462 | | |
| 463 | | context.turns.push({ |
| 464 | | id: turnState.turnId, |
| 465 | | items: [...turnState.items], |
| 466 | | }); |
| 467 | | |
| 468 | | const stamp = yield* makeEventStamp(); |
| 469 | | yield* offerRuntimeEvent({ |
| 470 | | type: "turn.completed", |
| 471 | | eventId: stamp.eventId, |
| 472 | | provider: PROVIDER, |
| 473 | | createdAt: stamp.createdAt, |
| 474 | | threadId: context.session.threadId, |
| 475 | | turnId: turnState.turnId, |
| 476 | | payload: { |
| 477 | | state, |
| 478 | | ...(stopReason ? { stopReason } : {}), |
| 479 | | ...(errorMessage ? { errorMessage } : {}), |
| 480 | | }, |
| 481 | | providerRefs: { |
| 482 | | providerTurnId: String(turnState.turnId), |
| 483 | | }, |
| 484 | | }); |
| 485 | | |
| 486 | | context.turnState = undefined; |
| 487 | | context.session = { |
| 488 | | ...context.session, |
| 489 | | status: state === "failed" ? "error" : "ready", |
| 490 | | activeTurnId: undefined, |
| 491 | | ...(errorMessage ? { lastError: errorMessage } : {}), |
| 492 | | updatedAt: yield* nowIso, |
| 493 | | }; |
| 494 | | }); |
| 495 | | |
| 496 | | const handlePermissionRequest = ( |
| 497 | | context: CursorSessionContext, |
| 498 | | request: unknown, |
| 499 | | ): Effect.Effect<void> => { |
| 500 | | let decoded: ReturnType<typeof decodePermissionRequest>; |
| 501 | | try { |
| 502 | | decoded = decodePermissionRequest(request); |
| 503 | | } catch (error) { |
| 504 | | return emitRuntimeWarning( |
| 505 | | context, |
| 506 | | "Failed to decode Cursor ACP permission request.", |
| 507 | | error, |
| 508 | | ); |
| 509 | | } |
| 510 | | |
| 511 | | return Effect.gen(function* () { |
| 512 | | const requestId = ApprovalRequestId.makeUnsafe(randomUUID()); |
| 513 | | const requestType = normalizeRequestType(decoded.params.toolCall); |
| 514 | | const options = decoded.params.options.map((entry) => ({ optionId: entry.optionId })); |
| 515 | | const detail = asString(asObject(decoded.params.toolCall)?.title); |
| 516 | | |
| 517 | | if (context.runtimeMode === "full-access") { |
| 518 | | const selection = |
| 519 | | selectCursorAutoApprovalOption(options) ?? |
| 520 | | (options[0] |
| 521 | | ? { |
| 522 | | optionId: options[0].optionId, |
| 523 | | decision: "accept", |
| 524 | | } |
| 525 | | : undefined); |
| 526 | | if (!selection) { |
| 527 | | return yield* emitRuntimeWarning( |
| 528 | | context, |
| 529 | | "Cursor ACP permission request contained no selectable options.", |
| 530 | | decoded.params, |
| 531 | | ); |
| 532 | | } |
| 533 | | |
| 534 | | writeCursorMessage(context, { |
| 535 | | jsonrpc: "2.0", |
| 536 | | id: decoded.id, |
| 537 | | result: { |
| 538 | | outcome: { |
| 539 | | outcome: "selected", |
| 540 | | optionId: selection.optionId, |
| 541 | | }, |
| 542 | | }, |
| 543 | | }); |
| 544 | | |
| 545 | | const stamp = yield* makeEventStamp(); |
| 546 | | yield* offerRuntimeEvent({ |
| 547 | | type: "request.resolved", |
| 548 | | eventId: stamp.eventId, |
| 549 | | provider: PROVIDER, |
| 550 | | createdAt: stamp.createdAt, |
| 551 | | threadId: context.session.threadId, |
| 552 | | ...((context.turnState ? { turnId: context.turnState.turnId } : {})), |
| 553 | | requestId: asRuntimeRequestId(requestId), |
| 554 | | payload: { |
| 555 | | requestType, |
| 556 | | decision: selection.decision, |
| 557 | | resolution: { |
| 558 | | optionId: selection.optionId, |
| 559 | | autoApproved: true, |
| 560 | | }, |
| 561 | | }, |
| 562 | | providerRefs: { |
| 563 | | ...(context.turnState ? { providerTurnId: String(context.turnState.turnId) } : {}), |
| 564 | | providerRequestId: String(decoded.id), |
| 565 | | }, |
| 566 | | raw: { |
| 567 | | source: "cursor.acp.response", |
| 568 | | method: "session/request_permission", |
| 569 | | payload: { |
| 570 | | optionId: selection.optionId, |
| 571 | | autoApproved: true, |
| 572 | | }, |
| 573 | | }, |
| 574 | | }); |
| 575 | | return; |
| 576 | | } |
| 577 | | |
| 578 | | context.pendingPermissions.set(requestId, { |
| 579 | | jsonRpcId: decoded.id, |
| 580 | | requestType, |
| 581 | | options, |
| 582 | | }); |
| 583 | | |
| 584 | | const stamp = yield* makeEventStamp(); |
| 585 | | yield* offerRuntimeEvent({ |
| 586 | | type: "request.opened", |
| 587 | | eventId: stamp.eventId, |
| 588 | | provider: PROVIDER, |
| 589 | | createdAt: stamp.createdAt, |
| 590 | | threadId: context.session.threadId, |
| 591 | | ...((context.turnState ? { turnId: context.turnState.turnId } : {})), |
| 592 | | requestId: asRuntimeRequestId(requestId), |
| 593 | | payload: { |
| 594 | | requestType, |
| 595 | | ...(detail ? { detail } : {}), |
| 596 | | args: decoded.params, |
| 597 | | }, |
| 598 | | providerRefs: { |
| 599 | | ...(context.turnState ? { providerTurnId: String(context.turnState.turnId) } : {}), |
| 600 | | providerRequestId: String(decoded.id), |
| 601 | | }, |
| 602 | | raw: { |
| 603 | | source: "cursor.acp.request", |
| 604 | | method: decoded.method, |
| 605 | | payload: decoded, |
| 606 | | }, |
| 607 | | }); |
| 608 | | }); |
| 609 | | }; |
| 610 | | |
| 611 | | const handleSessionUpdateNotification = ( |
| 612 | | context: CursorSessionContext, |
| 613 | | notification: unknown, |
| 614 | | ): Effect.Effect<void> => { |
| 615 | | let decoded: ReturnType<typeof decodeSessionUpdateNotification>; |
| 616 | | try { |
| 617 | | decoded = decodeSessionUpdateNotification(notification); |
| 618 | | } catch (error) { |
| 619 | | return emitRuntimeWarning( |
| 620 | | context, |
| 621 | | "Failed to decode Cursor ACP session/update notification.", |
| 622 | | error, |
| 623 | | ); |
| 624 | | } |
| 625 | | |
| 626 | | return Effect.gen(function* () { |
| 627 | | const update = decoded.params.update; |
| 628 | | |
| 629 | | const base = { |
| 630 | | provider: PROVIDER, |
| 631 | | threadId: context.session.threadId, |
| 632 | | ...((context.turnState ? { turnId: context.turnState.turnId } : {})), |
| 633 | | ...(context.turnState |
| 634 | | ? { providerRefs: { providerTurnId: String(context.turnState.turnId) } } |
| 635 | | : {}), |
| 636 | | raw: { |
| 637 | | source: "cursor.acp.notification" as const, |
| 638 | | method: decoded.method, |
| 639 | | messageType: update.sessionUpdate, |
| 640 | | payload: decoded, |
| 641 | | }, |
| 642 | | }; |
| 643 | | |
| 644 | | switch (update.sessionUpdate) { |
| 645 | | case "available_commands_update": { |
| 646 | | const stamp = yield* makeEventStamp(); |
| 647 | | yield* offerRuntimeEvent({ |
| 648 | | ...base, |
| 649 | | type: "session.configured", |
| 650 | | eventId: stamp.eventId, |
| 651 | | createdAt: stamp.createdAt, |
| 652 | | payload: { |
| 653 | | config: { |
| 654 | | availableCommands: update.availableCommands, |
| 655 | | }, |
| 656 | | }, |
| 657 | | }); |
| 658 | | return; |
| 659 | | } |
| 660 | | |
| 661 | | case "agent_thought_chunk": { |
| 662 | | if (!context.turnState) return; |
| 663 | | if (update.content.text.length === 0) return; |
| 664 | | const stamp = yield* makeEventStamp(); |
| 665 | | yield* offerRuntimeEvent({ |
| 666 | | ...base, |
| 667 | | type: "content.delta", |
| 668 | | eventId: stamp.eventId, |
| 669 | | createdAt: stamp.createdAt, |
| 670 | | turnId: context.turnState.turnId, |
| 671 | | itemId: asRuntimeItemId(context.turnState.assistantItemId), |
| 672 | | payload: { |
| 673 | | streamKind: "reasoning_text", |
| 674 | | delta: update.content.text, |
| 675 | | }, |
| 676 | | }); |
| 677 | | return; |
| 678 | | } |
| 679 | | |
| 680 | | case "agent_message_chunk": { |
| 681 | | if (!context.turnState) return; |
| 682 | | if (update.content.text.length === 0) return; |
| 683 | | const stamp = yield* makeEventStamp(); |
| 684 | | yield* offerRuntimeEvent({ |
| 685 | | ...base, |
| 686 | | type: "content.delta", |
| 687 | | eventId: stamp.eventId, |
| 688 | | createdAt: stamp.createdAt, |
| 689 | | turnId: context.turnState.turnId, |
| 690 | | itemId: asRuntimeItemId(context.turnState.assistantItemId), |
| 691 | | payload: { |
| 692 | | streamKind: "assistant_text", |
| 693 | | delta: update.content.text, |
| 694 | | }, |
| 695 | | }); |
| 696 | | return; |
| 697 | | } |
| 698 | | |
| 699 | | case "tool_call": { |
| 700 | | if (!context.turnState) return; |
| 701 | | const seen = context.turnState.startedToolCalls.has(update.toolCallId); |
| 702 | | const itemType = normalizeToolItemType(update.kind, update.title); |
| 703 | | const title = update.title ?? titleForItemType(itemType); |
| 704 | | context.turnState.toolCalls.set(update.toolCallId, { itemType, title }); |
| 705 | | const detail = asString(asObject(update.rawInput)?.command); |
| 706 | | |
| 707 | | if (!seen) { |
| 708 | | context.turnState.startedToolCalls.add(update.toolCallId); |
| 709 | | const stamp = yield* makeEventStamp(); |
| 710 | | yield* offerRuntimeEvent({ |
| 711 | | ...base, |
| 712 | | type: "item.started", |
| 713 | | eventId: stamp.eventId, |
| 714 | | createdAt: stamp.createdAt, |
| 715 | | turnId: context.turnState.turnId, |
| 716 | | itemId: asRuntimeItemId(update.toolCallId), |
| 717 | | payload: { |
| 718 | | itemType, |
| 719 | | status: "inProgress", |
| 720 | | title, |
| 721 | | ...(detail ? { detail } : {}), |
| 722 | | ...(update.rawInput !== undefined ? { data: update.rawInput } : {}), |
| 723 | | }, |
| 724 | | }); |
| 725 | | return; |
| 726 | | } |
| 727 | | |
| 728 | | const stamp = yield* makeEventStamp(); |
| 729 | | yield* offerRuntimeEvent({ |
| 730 | | ...base, |
| 731 | | type: "item.updated", |
| 732 | | eventId: stamp.eventId, |
| 733 | | createdAt: stamp.createdAt, |
| 734 | | turnId: context.turnState.turnId, |
| 735 | | itemId: asRuntimeItemId(update.toolCallId), |
| 736 | | payload: { |
| 737 | | itemType, |
| 738 | | status: "inProgress", |
| 739 | | title, |
| 740 | | ...(detail ? { detail } : {}), |
| 741 | | ...(update.rawInput !== undefined ? { data: update.rawInput } : {}), |
| 742 | | }, |
| 743 | | }); |
| 744 | | return; |
| 745 | | } |
| 746 | | |
| 747 | | case "tool_call_update": { |
| 748 | | if (!context.turnState) return; |
| 749 | | const status = update.status === "completed" ? "completed" : "inProgress"; |
| 750 | | const trackedTool = context.turnState.toolCalls.get(update.toolCallId); |
| 751 | | const itemType = trackedTool?.itemType ?? "dynamic_tool_call"; |
| 752 | | const title = trackedTool?.title ?? titleForItemType(itemType); |
| 753 | | const stamp = yield* makeEventStamp(); |
| 754 | | const eventType = update.status === "completed" ? "item.completed" : "item.updated"; |
| 755 | | yield* offerRuntimeEvent({ |
| 756 | | ...base, |
| 757 | | type: eventType, |
| 758 | | eventId: stamp.eventId, |
| 759 | | createdAt: stamp.createdAt, |
| 760 | | turnId: context.turnState.turnId, |
| 761 | | itemId: asRuntimeItemId(update.toolCallId), |
| 762 | | payload: { |
| 763 | | itemType, |
| 764 | | status, |
| 765 | | title, |
| 766 | | ...(summarizeToolOutput(update.rawOutput) |
| 767 | | ? { detail: summarizeToolOutput(update.rawOutput) } |
| 768 | | : {}), |
| 769 | | ...(update.rawOutput !== undefined ? { data: update.rawOutput } : {}), |
| 770 | | }, |
| 771 | | }); |
| 772 | | if (update.status === "completed") { |
| 773 | | context.turnState.toolCalls.delete(update.toolCallId); |
| 774 | | } |
| 775 | | return; |
| 776 | | } |
| 777 | | } |
| 778 | | }); |
| 779 | | }; |
| 780 | | |
| 781 | | const handleStdoutLine = (context: CursorSessionContext, line: string): void => { |
| 782 | | let parsed: unknown; |
| 783 | | try { |
| 784 | | parsed = JSON.parse(line); |
| 785 | | } catch { |
| 786 | | Effect.runFork( |
| 787 | | emitRuntimeWarning(context, "Received invalid JSON from Cursor ACP.", { |
| 788 | | line, |
| 789 | | }), |
| 790 | | ); |
| 791 | | return; |
| 792 | | } |
| 793 | | |
| 794 | | const message = asObject(parsed); |
| 795 | | if (!message) { |
| 796 | | Effect.runFork( |
| 797 | | emitRuntimeWarning(context, "Received non-object protocol message from Cursor ACP."), |
| 798 | | ); |
| 799 | | return; |
| 800 | | } |
| 801 | | |
| 802 | | if (nativeEventLogger) { |
| 803 | | try { |
| 804 | | const nativeMethod = |
| 805 | | typeof message.method === "string" |
| 806 | | ? message.method |
| 807 | | : typeof message.id === "string" || typeof message.id === "number" |
| 808 | | ? "cursor/acp/response" |
| 809 | | : "cursor/acp/message"; |
| 810 | | const nativeKind = |
| 811 | | typeof message.method === "string" && |
| 812 | | (typeof message.id === "string" || typeof message.id === "number") |
| 813 | | ? "request" |
| 814 | | : typeof message.method === "string" |
| 815 | | ? "notification" |
| 816 | | : "session"; |
| 817 | | Effect.runFork( |
| 818 | | nativeEventLogger |
| 819 | | .write( |
| 820 | | { |
| 821 | | observedAt: new Date().toISOString(), |
| 822 | | event: { |
| 823 | | id: EventId.makeUnsafe(randomUUID()), |
| 824 | | kind: nativeKind, |
| 825 | | provider: PROVIDER, |
| 826 | | createdAt: new Date().toISOString(), |
| 827 | | method: nativeMethod, |
| 828 | | threadId: context.session.threadId, |
| 829 | | ...(context.turnState ? { turnId: String(context.turnState.turnId) } : {}), |
| 830 | | payload: message, |
| 831 | | }, |
| 832 | | }, |
| 833 | | null, |
| 834 | | ), |
| 835 | | ); |
| 836 | | } catch { |
| 837 | | // Native logging must never block or break protocol handling. |
| 838 | | } |
| 839 | | } |
| 840 | | |
| 841 | | if ( |
| 842 | | (typeof message.id === "string" || typeof message.id === "number") && |
| 843 | | typeof message.method === "string" |
| 844 | | ) { |
| 845 | | if (message.method === "session/request_permission") { |
| 846 | | Effect.runFork(handlePermissionRequest(context, message)); |
| 847 | | return; |
| 848 | | } |
| 849 | | |
| 850 | | writeCursorMessage(context, { |
| 851 | | jsonrpc: "2.0", |
| 852 | | id: message.id, |
| 853 | | error: { |
| 854 | | code: -32601, |
| 855 | | message: `Unsupported server request: ${message.method}`, |
| 856 | | }, |
| 857 | | }); |
| 858 | | return; |
| 859 | | } |
| 860 | | |
| 861 | | if ( |
| 862 | | (typeof message.id === "string" || typeof message.id === "number") && |
| 863 | | ("result" in message || "error" in message) |
| 864 | | ) { |
| 865 | | resolvePendingRequest(context, message); |
| 866 | | return; |
| 867 | | } |
| 868 | | |
| 869 | | if (typeof message.method === "string") { |
| 870 | | if (message.method === "session/update") { |
| 871 | | Effect.runFork(handleSessionUpdateNotification(context, message)); |
| 872 | | return; |
| 873 | | } |
| 874 | | |
| 875 | | Effect.runFork( |
| 876 | | emitRuntimeWarning( |
| 877 | | context, |
| 878 | | `Unhandled Cursor ACP notification '${message.method}'.`, |
| 879 | | message, |
| 880 | | ), |
| 881 | | ); |
| 882 | | return; |
| 883 | | } |
| 884 | | |
| 885 | | Effect.runFork( |
| 886 | | emitRuntimeWarning(context, "Received unrecognized protocol message from Cursor ACP.", { |
| 887 | | message, |
| 888 | | }), |
| 889 | | ); |
| 890 | | }; |
| 891 | | |
| 892 | | const stopSessionInternal = ( |
| 893 | | context: CursorSessionContext, |
| 894 | | options?: { readonly emitExitEvent?: boolean }, |
| 895 | | ): Effect.Effect<void> => |
| 896 | | Effect.gen(function* () { |
| 897 | | if (context.stopping) return; |
| 898 | | context.stopping = true; |
| 899 | | |
| 900 | | for (const pending of context.pending.values()) { |
| 901 | | clearTimeout(pending.timeout); |
| 902 | | pending.reject(new Error("Cursor session stopped before request completion.")); |
| 903 | | } |
| 904 | | context.pending.clear(); |
| 905 | | |
| 906 | | if (context.turnState) { |
| 907 | | yield* completeTurn(context, "interrupted", "Session stopped.", "cancelled"); |
| 908 | | } |
| 909 | | |
| 910 | | context.output.close(); |
| 911 | | if (!context.child.killed) { |
| 912 | | context.child.kill(); |
| 913 | | } |
| 914 | | |
| 915 | | context.session = { |
| 916 | | ...context.session, |
| 917 | | status: "closed", |
| 918 | | activeTurnId: undefined, |
| 919 | | updatedAt: yield* nowIso, |
| 920 | | }; |
| 921 | | |
| 922 | | if (options?.emitExitEvent !== false) { |
| 923 | | const stamp = yield* makeEventStamp(); |
| 924 | | yield* offerRuntimeEvent({ |
| 925 | | type: "session.exited", |
| 926 | | eventId: stamp.eventId, |
| 927 | | provider: PROVIDER, |
| 928 | | createdAt: stamp.createdAt, |
| 929 | | threadId: context.session.threadId, |
| 930 | | payload: { |
| 931 | | reason: "Session stopped", |
| 932 | | exitKind: "graceful", |
| 933 | | }, |
| 934 | | }); |
| 935 | | } |
| 936 | | |
| 937 | | sessions.delete(context.session.threadId); |
| 938 | | }); |
| 939 | | |
| 940 | | const requireSession = ( |
| 941 | | threadId: ThreadId, |
| 942 | | ): Effect.Effect<CursorSessionContext, ProviderAdapterError> => { |
| 943 | | const context = sessions.get(threadId); |
| 944 | | if (!context) { |
| 945 | | return Effect.fail( |
| 946 | | new ProviderAdapterSessionNotFoundError({ |
| 947 | | provider: PROVIDER, |
| 948 | | threadId, |
| 949 | | }), |
| 950 | | ); |
| 951 | | } |
| 952 | | if (context.stopping || context.session.status === "closed") { |
| 953 | | return Effect.fail( |
| 954 | | new ProviderAdapterSessionClosedError({ |
| 955 | | provider: PROVIDER, |
| 956 | | threadId, |
| 957 | | }), |
| 958 | | ); |
| 959 | | } |
| 960 | | return Effect.succeed(context); |
| 961 | | }; |
| 962 | | |
| 963 | | const startSession: CursorAdapterShape["startSession"] = (input) => |
| 964 | | Effect.gen(function* () { |
| 965 | | if (input.provider !== undefined && input.provider !== PROVIDER) { |
| 966 | | return yield* new ProviderAdapterValidationError({ |
| 967 | | provider: PROVIDER, |
| 968 | | operation: "startSession", |
| 969 | | issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, |
| 970 | | }); |
| 971 | | } |
| 972 | | |
| 973 | | const startedAt = yield* nowIso; |
| 974 | | const cwd = input.cwd ?? process.cwd(); |
| 975 | | const cursorOptions = input.providerOptions?.cursor as { binaryPath?: string } | undefined; |
| 976 | | const binaryPath = cursorOptions?.binaryPath ?? "agent"; |
| 977 | | const resumeState = readCursorResumeState(input.resumeCursor); |
| 978 | | |
| 979 | | const child = yield* Effect.try({ |
| 980 | | try: () => |
| 981 | | spawnCursorAcp({ |
| 982 | | binaryPath, |
| 983 | | cwd, |
| 984 | | env: process.env, |
| 985 | | ...(input.model ? { model: input.model } : {}), |
| 986 | | }), |
| 987 | | catch: (cause) => |
| 988 | | new ProviderAdapterProcessError({ |
| 989 | | provider: PROVIDER, |
| 990 | | threadId: input.threadId, |
| 991 | | detail: toMessage(cause, "Failed to spawn Cursor ACP process."), |
| 992 | | cause, |
| 993 | | }), |
| 994 | | }); |
| 995 | | |
| 996 | | const output = readline.createInterface({ input: child.stdout }); |
| 997 | | |
| 998 | | const session: ProviderSession = { |
| 999 | | threadId: input.threadId, |
| 1000 | | provider: PROVIDER, |
| 1001 | | status: "connecting", |
| 1002 | | runtimeMode: input.runtimeMode, |
| 1003 | | ...(input.cwd ? { cwd: input.cwd } : {}), |
| 1004 | | ...(input.model ? { model: input.model } : {}), |
| 1005 | | createdAt: startedAt, |
| 1006 | | updatedAt: startedAt, |
| 1007 | | }; |
| 1008 | | |
| 1009 | | const context: CursorSessionContext = { |
| 1010 | | session, |
| 1011 | | runtimeMode: input.runtimeMode, |
| 1012 | | child, |
| 1013 | | output, |
| 1014 | | pending: new Map(), |
| 1015 | | pendingPermissions: new Map(), |
| 1016 | | turns: [], |
| 1017 | | turnState: undefined, |
| 1018 | | acpSessionId: resumeState?.acpSessionId ?? "", |
| 1019 | | nextRpcId: 1, |
| 1020 | | stopping: false, |
| 1021 | | }; |
| 1022 | | |
| 1023 | | output.on("line", (line) => { |
| 1024 | | handleStdoutLine(context, line); |
| 1025 | | }); |
| 1026 | | |
| 1027 | | child.stderr.on("data", (chunk: Buffer) => { |
| 1028 | | const message = chunk.toString().trim(); |
| 1029 | | if (message.length === 0) { |
| 1030 | | return; |
| 1031 | | } |
| 1032 | | Effect.runFork( |
| 1033 | | emitRuntimeWarning(context, "Cursor ACP stderr output", { |
| 1034 | | message, |
| 1035 | | }), |
| 1036 | | ); |
| 1037 | | }); |
| 1038 | | |
| 1039 | | child.on("error", (error) => { |
| 1040 | | Effect.runFork( |
| 1041 | | Effect.gen(function* () { |
| 1042 | | const stamp = yield* makeEventStamp(); |
| 1043 | | yield* offerRuntimeEvent({ |
| 1044 | | type: "runtime.error", |
| 1045 | | eventId: stamp.eventId, |
| 1046 | | provider: PROVIDER, |
| 1047 | | createdAt: stamp.createdAt, |
| 1048 | | threadId: context.session.threadId, |
| 1049 | | ...((context.turnState ? { turnId: context.turnState.turnId } : {})), |
| 1050 | | payload: { |
| 1051 | | message: error.message || "Cursor ACP process error.", |
| 1052 | | class: "transport_error", |
| 1053 | | detail: error, |
| 1054 | | }, |
| 1055 | | }); |
| 1056 | | }), |
| 1057 | | ); |
| 1058 | | }); |
| 1059 | | |
| 1060 | | child.on("exit", (code, signal) => { |
| 1061 | | if (context.stopping) { |
| 1062 | | return; |
| 1063 | | } |
| 1064 | | Effect.runFork( |
| 1065 | | Effect.gen(function* () { |
| 1066 | | if (context.turnState) { |
| 1067 | | yield* completeTurn( |
| 1068 | | context, |
| 1069 | | "failed", |
| 1070 | | `Cursor ACP exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`, |
| 1071 | | ); |
| 1072 | | } |
| 1073 | | |
| 1074 | | const stamp = yield* makeEventStamp(); |
| 1075 | | yield* offerRuntimeEvent({ |
| 1076 | | type: "session.exited", |
| 1077 | | eventId: stamp.eventId, |
| 1078 | | provider: PROVIDER, |
| 1079 | | createdAt: stamp.createdAt, |
| 1080 | | threadId: context.session.threadId, |
| 1081 | | payload: { |
| 1082 | | reason: `Cursor ACP exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`, |
| 1083 | | exitKind: code === 0 ? "graceful" : "error", |
| 1084 | | recoverable: code === 0, |
| 1085 | | }, |
| 1086 | | }); |
| 1087 | | |
| 1088 | | sessions.delete(context.session.threadId); |
| 1089 | | }), |
| 1090 | | ); |
| 1091 | | }); |
| 1092 | | |
| 1093 | | sessions.set(input.threadId, context); |
| 1094 | | |
| 1095 | | const initializeResult = yield* Effect.tryPromise({ |
| 1096 | | try: async () => |
| 1097 | | sendRequest(context, "initialize", { |
| 1098 | | protocolVersion: CURSOR_ACP_PROTOCOL_VERSION, |
| 1099 | | }), |
| 1100 | | catch: (cause) => toRequestError(input.threadId, "initialize", cause), |
| 1101 | | }); |
| 1102 | | const decodedInitialize = yield* Effect.try({ |
| 1103 | | try: () => Schema.decodeUnknownSync(CursorAcpInitializeResult)(initializeResult), |
| 1104 | | catch: (cause) => |
| 1105 | | new ProviderAdapterValidationError({ |
| 1106 | | provider: PROVIDER, |
| 1107 | | operation: "startSession", |
| 1108 | | issue: "Cursor initialize response did not match expected schema.", |
| 1109 | | cause, |
| 1110 | | }), |
| 1111 | | }); |
| 1112 | | |
| 1113 | | const initStamp = yield* makeEventStamp(); |
| 1114 | | yield* offerRuntimeEvent({ |
| 1115 | | type: "session.configured", |
| 1116 | | eventId: initStamp.eventId, |
| 1117 | | provider: PROVIDER, |
| 1118 | | createdAt: initStamp.createdAt, |
| 1119 | | threadId: input.threadId, |
| 1120 | | payload: { |
| 1121 | | config: decodedInitialize, |
| 1122 | | }, |
| 1123 | | raw: { |
| 1124 | | source: "cursor.acp.response", |
| 1125 | | method: "initialize", |
| 1126 | | payload: initializeResult, |
| 1127 | | }, |
| 1128 | | }); |
| 1129 | | |
| 1130 | | const authenticateRequest = { methodId: "cursor_login" }; |
| 1131 | | const authStartStamp = yield* makeEventStamp(); |
| 1132 | | yield* offerRuntimeEvent({ |
| 1133 | | type: "auth.status", |
| 1134 | | eventId: authStartStamp.eventId, |
| 1135 | | provider: PROVIDER, |
| 1136 | | createdAt: authStartStamp.createdAt, |
| 1137 | | threadId: input.threadId, |
| 1138 | | payload: { |
| 1139 | | isAuthenticating: true, |
| 1140 | | }, |
| 1141 | | raw: { |
| 1142 | | source: "cursor.acp.request", |
| 1143 | | method: "authenticate", |
| 1144 | | payload: authenticateRequest, |
| 1145 | | }, |
| 1146 | | }); |
| 1147 | | |
| 1148 | | const authenticateResult = yield* Effect.tryPromise({ |
| 1149 | | try: async () => sendRequest(context, "authenticate", authenticateRequest), |
| 1150 | | catch: (cause) => toRequestError(input.threadId, "authenticate", cause), |
| 1151 | | }).pipe( |
| 1152 | | Effect.match({ |
| 1153 | | onFailure: (error) => ({ ok: false as const, error }), |
| 1154 | | onSuccess: (value) => ({ ok: true as const, value }), |
| 1155 | | }), |
| 1156 | | ); |
| 1157 | | const authEndStamp = yield* makeEventStamp(); |
| 1158 | | if (!authenticateResult.ok) { |
| 1159 | | yield* offerRuntimeEvent({ |
| 1160 | | type: "auth.status", |
| 1161 | | eventId: authEndStamp.eventId, |
| 1162 | | provider: PROVIDER, |
| 1163 | | createdAt: authEndStamp.createdAt, |
| 1164 | | threadId: input.threadId, |
| 1165 | | payload: { |
| 1166 | | isAuthenticating: false, |
| 1167 | | error: toMessage(authenticateResult.error, "Cursor authentication failed."), |
| 1168 | | }, |
| 1169 | | raw: { |
| 1170 | | source: "cursor.acp.response", |
| 1171 | | method: "authenticate", |
| 1172 | | payload: { |
| 1173 | | error: toMessage(authenticateResult.error, "Cursor authentication failed."), |
| 1174 | | }, |
| 1175 | | }, |
| 1176 | | }); |
| 1177 | | } else { |
| 1178 | | yield* offerRuntimeEvent({ |
| 1179 | | type: "auth.status", |
| 1180 | | eventId: authEndStamp.eventId, |
| 1181 | | provider: PROVIDER, |
| 1182 | | createdAt: authEndStamp.createdAt, |
| 1183 | | threadId: input.threadId, |
| 1184 | | payload: { |
| 1185 | | isAuthenticating: false, |
| 1186 | | }, |
| 1187 | | raw: { |
| 1188 | | source: "cursor.acp.response", |
| 1189 | | method: "authenticate", |
| 1190 | | payload: authenticateResult.value, |
| 1191 | | }, |
| 1192 | | }); |
| 1193 | | } |
| 1194 | | |
| 1195 | | const acpSessionId = yield* Effect.tryPromise({ |
| 1196 | | try: async () => { |
| 1197 | | if (resumeState?.acpSessionId) { |
| 1198 | | await sendRequest(context, "session/load", { |
| 1199 | | sessionId: resumeState.acpSessionId, |
| 1200 | | cwd, |
| 1201 | | mcpServers: [], |
| 1202 | | }); |
| 1203 | | return resumeState.acpSessionId; |
| 1204 | | } |
| 1205 | | |
| 1206 | | const sessionNewParams: { |
| 1207 | | cwd: string; |
| 1208 | | mcpServers: []; |
| 1209 | | model?: string; |
| 1210 | | } = { |
| 1211 | | cwd, |
| 1212 | | mcpServers: [], |
| 1213 | | }; |
| 1214 | | if (input.model) { |
| 1215 | | sessionNewParams.model = input.model; |
| 1216 | | } |
| 1217 | | const result = await sendRequest(context, "session/new", sessionNewParams); |
| 1218 | | const decoded = Schema.decodeUnknownSync(CursorAcpSessionNewResult)(result); |
| 1219 | | return decoded.sessionId; |
| 1220 | | }, |
| 1221 | | catch: (cause) => toRequestError(input.threadId, "session/new|session/load", cause), |
| 1222 | | }); |
| 1223 | | |
| 1224 | | context.acpSessionId = acpSessionId; |
| 1225 | | context.session = { |
| 1226 | | ...context.session, |
| 1227 | | status: "ready", |
| 1228 | | resumeCursor: { |
| 1229 | | acpSessionId, |
| 1230 | | }, |
| 1231 | | updatedAt: yield* nowIso, |
| 1232 | | }; |
| 1233 | | |
| 1234 | | const sessionStartedStamp = yield* makeEventStamp(); |
| 1235 | | yield* offerRuntimeEvent({ |
| 1236 | | type: "session.started", |
| 1237 | | eventId: sessionStartedStamp.eventId, |
| 1238 | | provider: PROVIDER, |
| 1239 | | createdAt: sessionStartedStamp.createdAt, |
| 1240 | | threadId: input.threadId, |
| 1241 | | payload: resumeState?.acpSessionId ? { resume: input.resumeCursor } : {}, |
| 1242 | | }); |
| 1243 | | |
| 1244 | | const threadStartedStamp = yield* makeEventStamp(); |
| 1245 | | yield* offerRuntimeEvent({ |
| 1246 | | type: "thread.started", |
| 1247 | | eventId: threadStartedStamp.eventId, |
| 1248 | | provider: PROVIDER, |
| 1249 | | createdAt: threadStartedStamp.createdAt, |
| 1250 | | threadId: input.threadId, |
| 1251 | | payload: { |
| 1252 | | providerThreadId: acpSessionId, |
| 1253 | | }, |
| 1254 | | }); |
| 1255 | | |
| 1256 | | const readyStamp = yield* makeEventStamp(); |
| 1257 | | yield* offerRuntimeEvent({ |
| 1258 | | type: "session.state.changed", |
| 1259 | | eventId: readyStamp.eventId, |
| 1260 | | provider: PROVIDER, |
| 1261 | | createdAt: readyStamp.createdAt, |
| 1262 | | threadId: input.threadId, |
| 1263 | | payload: { |
| 1264 | | state: "ready", |
| 1265 | | }, |
| 1266 | | }); |
| 1267 | | |
| 1268 | | return { |
| 1269 | | ...context.session, |
| 1270 | | }; |
| 1271 | | }); |
| 1272 | | |
| 1273 | | const sendTurn: CursorAdapterShape["sendTurn"] = (input) => |
| 1274 | | Effect.gen(function* () { |
| 1275 | | const context = yield* requireSession(input.threadId); |
| 1276 | | |
| 1277 | | if (context.turnState) { |
| 1278 | | return yield* new ProviderAdapterValidationError({ |
| 1279 | | provider: PROVIDER, |
| 1280 | | operation: "sendTurn", |
| 1281 | | issue: `Thread '${input.threadId}' already has an active turn '${context.turnState.turnId}'.`, |
| 1282 | | }); |
| 1283 | | } |
| 1284 | | |
| 1285 | | const promptText = input.input?.trim(); |
| 1286 | | if (!promptText || promptText.length === 0) { |
| 1287 | | return yield* new ProviderAdapterValidationError({ |
| 1288 | | provider: PROVIDER, |
| 1289 | | operation: "sendTurn", |
| 1290 | | issue: "Turn input must be non-empty.", |
| 1291 | | }); |
| 1292 | | } |
| 1293 | | |
| 1294 | | const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4); |
| 1295 | | const turnState: CursorTurnState = { |
| 1296 | | turnId, |
| 1297 | | assistantItemId: asProviderItemId(yield* Random.nextUUIDv4), |
| 1298 | | startedToolCalls: new Set(), |
| 1299 | | toolCalls: new Map(), |
| 1300 | | items: [], |
| 1301 | | }; |
| 1302 | | |
| 1303 | | context.turnState = turnState; |
| 1304 | | context.session = { |
| 1305 | | ...context.session, |
| 1306 | | status: "running", |
| 1307 | | activeTurnId: turnId, |
| 1308 | | updatedAt: yield* nowIso, |
| 1309 | | }; |
| 1310 | | |
| 1311 | | const startedStamp = yield* makeEventStamp(); |
| 1312 | | yield* offerRuntimeEvent({ |
| 1313 | | type: "turn.started", |
| 1314 | | eventId: startedStamp.eventId, |
| 1315 | | provider: PROVIDER, |
| 1316 | | createdAt: startedStamp.createdAt, |
| 1317 | | threadId: context.session.threadId, |
| 1318 | | turnId, |
| 1319 | | payload: input.model ? { model: input.model } : {}, |
| 1320 | | providerRefs: { |
| 1321 | | providerTurnId: String(turnId), |
| 1322 | | }, |
| 1323 | | }); |
| 1324 | | |
| 1325 | | const promptResultRaw = yield* Effect.tryPromise({ |
| 1326 | | try: async () => |
| 1327 | | sendRequest(context, "session/prompt", { |
| 1328 | | sessionId: context.acpSessionId, |
| 1329 | | prompt: [{ type: "text", text: promptText }], |
| 1330 | | }), |
| 1331 | | catch: (cause) => toRequestError(input.threadId, "session/prompt", cause), |
| 1332 | | }); |
| 1333 | | |
| 1334 | | const promptResult = yield* Effect.try({ |
| 1335 | | try: () => Schema.decodeUnknownSync(CursorAcpSessionPromptResult)(promptResultRaw), |
| 1336 | | catch: (cause) => |
| 1337 | | new ProviderAdapterValidationError({ |
| 1338 | | provider: PROVIDER, |
| 1339 | | operation: "sendTurn", |
| 1340 | | issue: "Cursor session/prompt response did not match expected schema.", |
| 1341 | | cause, |
| 1342 | | }), |
| 1343 | | }); |
| 1344 | | const turnStateValue = mapStopReasonToTurnState(promptResult.stopReason); |
| 1345 | | yield* completeTurn( |
| 1346 | | context, |
| 1347 | | turnStateValue, |
| 1348 | | turnStateValue === "failed" ? "Cursor prompt failed." : undefined, |
| 1349 | | promptResult.stopReason, |
| 1350 | | ); |
| 1351 | | |
| 1352 | | context.session = { |
| 1353 | | ...context.session, |
| 1354 | | status: "ready", |
| 1355 | | activeTurnId: undefined, |
| 1356 | | updatedAt: yield* nowIso, |
| 1357 | | resumeCursor: { |
| 1358 | | acpSessionId: context.acpSessionId, |
| 1359 | | }, |
| 1360 | | }; |
| 1361 | | |
| 1362 | | return { |
| 1363 | | threadId: context.session.threadId, |
| 1364 | | turnId, |
| 1365 | | ...(context.session.resumeCursor !== undefined |
| 1366 | | ? { resumeCursor: context.session.resumeCursor } |
| 1367 | | : {}), |
| 1368 | | } satisfies ProviderTurnStartResult; |
| 1369 | | }); |
| 1370 | | |
| 1371 | | const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId, _turnId) => |
| 1372 | | Effect.gen(function* () { |
| 1373 | | const context = yield* requireSession(threadId); |
| 1374 | | if (!context.turnState) { |
| 1375 | | return; |
| 1376 | | } |
| 1377 | | |
| 1378 | | const cancelResult = yield* Effect.tryPromise({ |
| 1379 | | try: async () => |
| 1380 | | sendRequest(context, "session/cancel", { sessionId: context.acpSessionId }, 15_000), |
| 1381 | | catch: (cause) => toRequestError(threadId, "session/cancel", cause), |
| 1382 | | }).pipe( |
| 1383 | | Effect.match({ |
| 1384 | | onFailure: (error) => ({ ok: false as const, error }), |
| 1385 | | onSuccess: () => ({ ok: true as const }), |
| 1386 | | }), |
| 1387 | | ); |
| 1388 | | |
| 1389 | | if (!cancelResult.ok) { |
| 1390 | | yield* emitRuntimeWarning( |
| 1391 | | context, |
| 1392 | | "Cursor ACP session/cancel is unavailable; marking turn as interrupted.", |
| 1393 | | cancelResult.error, |
| 1394 | | ); |
| 1395 | | } |
| 1396 | | |
| 1397 | | yield* completeTurn(context, "interrupted", "Turn interrupted by user.", "cancelled"); |
| 1398 | | }); |
| 1399 | | |
| 1400 | | const readThread: CursorAdapterShape["readThread"] = (threadId) => |
| 1401 | | Effect.gen(function* () { |
| 1402 | | const context = yield* requireSession(threadId); |
| 1403 | | return { |
| 1404 | | threadId: context.session.threadId, |
| 1405 | | turns: context.turns.map((turn) => ({ |
| 1406 | | id: turn.id, |
| 1407 | | items: [...turn.items], |
| 1408 | | })), |
| 1409 | | }; |
| 1410 | | }); |
| 1411 | | |
| 1412 | | const rollbackThread: CursorAdapterShape["rollbackThread"] = (threadId, _numTurns) => |
| 1413 | | Effect.fail( |
| 1414 | | new ProviderAdapterRequestError({ |
| 1415 | | provider: PROVIDER, |
| 1416 | | method: "thread/rollback", |
| 1417 | | detail: `Cursor ACP does not support thread rollback for thread '${threadId}'.`, |
| 1418 | | }), |
| 1419 | | ); |
| 1420 | | |
| 1421 | | const respondToRequest: CursorAdapterShape["respondToRequest"] = ( |
| 1422 | | threadId, |
| 1423 | | requestId, |
| 1424 | | decision, |
| 1425 | | ) => |
| 1426 | | Effect.gen(function* () { |
| 1427 | | const context = yield* requireSession(threadId); |
| 1428 | | const pending = context.pendingPermissions.get(requestId); |
| 1429 | | if (!pending) { |
| 1430 | | return yield* new ProviderAdapterRequestError({ |
| 1431 | | provider: PROVIDER, |
| 1432 | | method: "session/request_permission", |
| 1433 | | detail: `Unknown pending permission request: ${requestId}`, |
| 1434 | | }); |
| 1435 | | } |
| 1436 | | |
| 1437 | | const optionId = selectCursorPermissionOption(pending.options, decision); |
| 1438 | | |
| 1439 | | if (!optionId) { |
| 1440 | | return yield* new ProviderAdapterRequestError({ |
| 1441 | | provider: PROVIDER, |
| 1442 | | method: "session/request_permission", |
| 1443 | | detail: `No selectable permission options for request: ${requestId}`, |
| 1444 | | }); |
| 1445 | | } |
| 1446 | | |
| 1447 | | writeCursorMessage(context, { |
| 1448 | | jsonrpc: "2.0", |
| 1449 | | id: pending.jsonRpcId, |
| 1450 | | result: { |
| 1451 | | outcome: { |
| 1452 | | outcome: "selected", |
| 1453 | | optionId, |
| 1454 | | }, |
| 1455 | | }, |
| 1456 | | }); |
| 1457 | | |
| 1458 | | context.pendingPermissions.delete(requestId); |
| 1459 | | |
| 1460 | | const stamp = yield* makeEventStamp(); |
| 1461 | | yield* offerRuntimeEvent({ |
| 1462 | | type: "request.resolved", |
| 1463 | | eventId: stamp.eventId, |
| 1464 | | provider: PROVIDER, |
| 1465 | | createdAt: stamp.createdAt, |
| 1466 | | threadId: context.session.threadId, |
| 1467 | | ...((context.turnState ? { turnId: context.turnState.turnId } : {})), |
| 1468 | | requestId: asRuntimeRequestId(requestId), |
| 1469 | | payload: { |
| 1470 | | requestType: pending.requestType, |
| 1471 | | decision, |
| 1472 | | resolution: { |
| 1473 | | optionId, |
| 1474 | | }, |
| 1475 | | }, |
| 1476 | | providerRefs: { |
| 1477 | | ...(context.turnState ? { providerTurnId: String(context.turnState.turnId) } : {}), |
| 1478 | | providerRequestId: String(pending.jsonRpcId), |
| 1479 | | }, |
| 1480 | | raw: { |
| 1481 | | source: "cursor.acp.response", |
| 1482 | | method: "session/request_permission", |
| 1483 | | payload: { |
| 1484 | | optionId, |
| 1485 | | }, |
| 1486 | | }, |
| 1487 | | }); |
| 1488 | | }); |
| 1489 | | |
| 1490 | | const respondToUserInput: CursorAdapterShape["respondToUserInput"] = ( |
| 1491 | | threadId, |
| 1492 | | requestId, |
| 1493 | | _answers, |
| 1494 | | ) => |
| 1495 | | Effect.fail( |
| 1496 | | new ProviderAdapterRequestError({ |
| 1497 | | provider: PROVIDER, |
| 1498 | | method: "cursor/ask_question", |
| 1499 | | detail: `Cursor does not yet support structured user-input responses for thread '${threadId}' and request '${requestId}'.`, |
| 1500 | | }), |
| 1501 | | ); |
| 1502 | | |
| 1503 | | const stopSession: CursorAdapterShape["stopSession"] = (threadId) => |
| 1504 | | Effect.gen(function* () { |
| 1505 | | const context = yield* requireSession(threadId); |
| 1506 | | yield* stopSessionInternal(context, { |
| 1507 | | emitExitEvent: true, |
| 1508 | | }); |
| 1509 | | }); |
| 1510 | | |
| 1511 | | const listSessions: CursorAdapterShape["listSessions"] = () => |
| 1512 | | Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session }))); |
| 1513 | | |
| 1514 | | const hasSession: CursorAdapterShape["hasSession"] = (threadId) => |
| 1515 | | Effect.sync(() => { |
| 1516 | | const context = sessions.get(threadId); |
| 1517 | | return context !== undefined && !context.stopping; |
| 1518 | | }); |
| 1519 | | |
| 1520 | | const stopAll: CursorAdapterShape["stopAll"] = () => |
| 1521 | | Effect.forEach( |
| 1522 | | sessions, |
| 1523 | | ([, context]) => |
| 1524 | | stopSessionInternal(context, { |
| 1525 | | emitExitEvent: true, |
| 1526 | | }), |
| 1527 | | { discard: true }, |
| 1528 | | ); |
| 1529 | | |
| 1530 | | yield* Effect.addFinalizer(() => |
| 1531 | | Effect.forEach( |
| 1532 | | sessions, |
| 1533 | | ([, context]) => |
| 1534 | | stopSessionInternal(context, { |
| 1535 | | emitExitEvent: false, |
| 1536 | | }), |
| 1537 | | { discard: true }, |
| 1538 | | ).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))), |
| 1539 | | ); |
| 1540 | | |
| 1541 | | return { |
| 1542 | | provider: PROVIDER, |
| 1543 | | capabilities: { |
| 1544 | | sessionModelSwitch: "unsupported", |
| 1545 | | }, |
| 1546 | | startSession, |
| 1547 | | sendTurn, |
| 1548 | | interruptTurn, |
| 1549 | | readThread, |
| 1550 | | rollbackThread, |
| 1551 | | respondToRequest, |
| 1552 | | respondToUserInput, |
| 1553 | | stopSession, |
| 1554 | | listSessions, |
| 1555 | | hasSession, |
| 1556 | | stopAll, |
| 1557 | | streamEvents: Stream.fromQueue(runtimeEventQueue), |
| 1558 | | } satisfies CursorAdapterShape; |
| 1559 | | }); |
| 1560 | | } |
| 1561 | | |
| 1562 | | export const CursorAdapterLive = Layer.effect(CursorAdapter, makeCursorAdapter()); |
| 1563 | | |
| 1564 | | export function makeCursorAdapterLive(options?: CursorAdapterLiveOptions) { |
| 1565 | | return Layer.effect(CursorAdapter, makeCursorAdapter(options)); |
| 1566 | | } |