feat: add Cursor adapter #178
Closedjuliusmarmingewants to merge 73 commits into
main fromcodething/648ca884-cursoropened View on GitHub- apps/server/src/provider/Layers/CursorAdapter.ts line 833Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +813,21 @@813+ ? "request"814+ : typeof message.method === "string"815+ ? "notification"816+ : "session";817+ Effect.runFork(818+ nativeEventLogger819+ .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,apps/server/src/provider/Layers/CursorAdapter.ts line 1091Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1071,21 @@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+ });
- @@ -0,0 +201,21 @@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+}@@ -0,0 +959,21 @@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({
- apps/web/src/appSettings.ts lines 29 to 34Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -24,3 +26,9 @@2426 customCodexModels: Schema.Array(Schema.String).pipe(2527 Schema.withConstructorDefault(() => Option.some([])),2628 ),29+ customClaudeModels: Schema.Array(Schema.String).pipe(30+ Schema.withConstructorDefault(() => Option.some([])),31+ ),32+ customCursorModels: Schema.Array(Schema.String).pipe(33+ Schema.withConstructorDefault(() => Option.some([])),34+ ),
- @@ -0,0 +70,21 @@70+ this.#child = spawn("agent", ["acp"], {71+ stdio: ["pipe", "pipe", "pipe"],72+ env: {73+ ...process.env,74+ NO_COLOR: "1",75+ },76+ });77+78+ this.#stdoutRl = readline.createInterface({ input: this.#child.stdout });79+ this.#stderrRl = readline.createInterface({ input: this.#child.stderr });80+81+ this.#stdoutRl.on("line", (line) => this.#handleStdoutLine(line));82+ this.#stderrRl.on("line", (line) => {83+ this.#onMessage({84+ ts: nowIso(),85+ channel: "stderr",86+ line,87+ });88+ });89+90+ this.#child.once("exit", (code, signal) => {
- @@ -5285,20 +5443 @@5285- {UNAVAILABLE_PROVIDER_OPTIONS.length > 0 && <MenuDivider />}5286- {UNAVAILABLE_PROVIDER_OPTIONS.map((option) => {5287- const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];5288- return (5289- <MenuItem key={option.value} disabled>5290- <OptionIcon5291- aria-hidden="true"5292- className={cn(5293- "size-4 shrink-0 opacity-80",5294- option.value === "claudeCode" ? "" : "text-muted-foreground/85",5295- )}5296- />5297- <span>{option.label}</span>5298- <span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">5299- Coming soon5300- </span>5301- </MenuItem>5302- );5303- })}5304- {UNAVAILABLE_PROVIDER_OPTIONS.length === 0 && <MenuDivider />}5443+ <MenuDivider />@@ -0,0 +1340,21 @@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+ };@@ -0,0 +748,21 @@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+ : {}),
- @@ -173,7 +417,12 @@173417 }174418175419 export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {176- private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();420+ private readonly sessions = new Map<ThreadId, CodexSessionContext>();177421178- async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {179- const sessionId = ProviderSessionId.makeUnsafe(randomUUID());422+ private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;423+ constructor(services?: ServiceMap.ServiceMap<never>) {424+ super();425+ this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;426+ }427+428+ async startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {@@ -428,7 +1241,21 @@1241+ ? [1242+ {1243+ type: "runtime.warning" as const,1244+ ...runtimeEventBase(event, canonicalThreadId),1245+ payload: {1246+ message: failureMessage,1247+ ...(event.payload !== undefined ? { detail: event.payload } : {}),1248+ },1249+ },1250+ ]1251+ : []),1252+ ];1253+ }1254+4281255 return [];4291256 }43012574311258 const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>4321259 Effect.gen(function* () {4331260 const fileSystem = yield* FileSystem.FileSystem;4341261 const serverConfig = yield* Effect.service(ServerConfig);@@ -232,3 +235,4 @@232235 projectId: ProjectId,233236 title: TrimmedNonEmptyString,234237 model: TrimmedNonEmptyString,238+ runtimeMode: RuntimeMode,@@ -195,3 +294,21 @@294+295+function toUserInputQuestions(payload: Record<string, unknown> | undefined) {296+ const questions = asArray(payload?.questions);297+ if (!questions) {195298 return undefined;196299 }197300301+ const parsedQuestions = questions302+ .map((entry) => {303+ const question = asObject(entry);304+ if (!question) return undefined;305+ const options = asArray(question.options)306+ ?.map((option) => {307+ const optionRecord = asObject(option);308+ if (!optionRecord) return undefined;309+ const label = asString(optionRecord.label)?.trim();310+ const description = asString(optionRecord.description)?.trim();311+ if (!label || !description) {312+ return undefined;313+ }314+ return { label, description };@@ -159,3 +413,19 @@159413 });160414 }161415416+function compareActivitiesByOrder(417+ left: OrchestrationThreadActivity,418+ right: OrchestrationThreadActivity,419+): number {420+ if (left.sequence !== undefined && right.sequence !== undefined) {421+ if (left.sequence !== right.sequence) {422+ return left.sequence - right.sequence;423+ }424+ } else if (left.sequence !== undefined) {425+ return 1;426+ } else if (right.sequence !== undefined) {427+ return -1;428+ }429+430+ return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);431+}@@ -475,5 +804,17 @@475804 });476805 }477806478- stopSession(sessionId: ProviderSessionId): void {479- const context = this.sessions.get(sessionId);807+ async respondToUserInput(808+ threadId: ThreadId,809+ requestId: ApprovalRequestId,810+ answers: ProviderUserInputAnswers,811+ ): Promise<void> {812+ const context = this.requireSession(threadId);813+ const pendingRequest = context.pendingUserInputs.get(requestId);814+ if (!pendingRequest) {815+ throw new Error(`Unknown pending user input request: ${requestId}`);816+ }817+818+ context.pendingUserInputs.delete(requestId);819+ const codexAnswers = toCodexUserInputAnswers(answers);820+ this.writeMessage(context, {
maria-rcks closed this
maria-rcks reopened this
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge closed this
Sign in to join this conversation.



Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
cbc2e528-7f64-461f-a2fa-bbe17861ba0fYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.