diff --git a/docs/user/cursor.md b/docs/user/cursor.md index a71080de9308b..f10ca24fb596f 100644 --- a/docs/user/cursor.md +++ b/docs/user/cursor.md @@ -54,14 +54,17 @@ The adapter supports: - Cursor `task` subagents, projected as read-only child app threads with their tool activity and final result. -The public SDK does not currently expose native agent fork, conversation rollback, or interactive -approval callbacks. A text-only steer reaches the current run without restarting it. +The public SDK does not currently expose native agent fork or interactive approval callbacks. A +text-only steer reaches the current run without restarting it. When Cursor cannot deliver the steer, the same message is queued for the next turn after this run finishes. If you press Stop, that follow-up stays held until you resume the queue. Steers with attachments and provider or runtime changes that must apply immediately interrupt and restart the run. Same-provider Cursor forks use the orchestrator's portable full-thread context handoff into a fresh -Cursor agent. The SDK has in-process custom callback tools, but the V2 adapter intentionally uses the +Cursor agent. **Edit from here** and checkpoint rollback rewind the same Cursor agent to just before +the selected message, as `cursor-agent`'s `/rewind` does, so it keeps its exact earlier history. +Rewinding to the thread's first message starts a fresh Cursor agent instead. +The SDK has in-process custom callback tools, but the V2 adapter intentionally uses the authenticated, thread-scoped MCP server instead. Portable handoffs summarize eligible timeline items and can omit the end of long messages. Read diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts index 8809849c53b61..842fcd59a2722 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts @@ -205,6 +205,64 @@ describe("CursorAgentSdkRunner", () => { }).pipe(Effect.provide(NodeServices.layer)), ); + it.effect("rewinds the agent to the state its first unwound run started from", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-rewind-" }); + const loaders = yield* Effect.promise(() => + vi.importActual("./sdk.ts"), + ); + const sdk = loaders.loadCursorSdk(); + const store = new sdk.JsonlLocalAgentStore(workspace); + const platform = yield* Effect.promise(() => + sdk.createAgentPlatform({ localStore: store, workspaceRef: workspace }), + ); + const { agent, run: first } = yield* Effect.promise(() => + platform.store.createAgent({ agentId: "agent-rewind", workspaceRef: workspace }), + ); + const finishRun = (runId: string, state: string) => + Effect.promise(async () => { + const checkpoint = await platform.checkpointStore.saveCheckpoint(agent.agentId, { + toBinary: () => new TextEncoder().encode(state), + }); + await platform.store.patchCheckpoint(agent.agentId, runId, checkpoint); + await platform.store.markRunTerminal(agent.agentId, runId, { status: "FINISHED" }); + return checkpoint.blobId; + }); + const followUp = Effect.promise(() => platform.store.createFollowUpRun(agent.agentId, {})); + const head = Effect.promise( + async () => (await platform.store.getAgent(agent.agentId))?.latestCheckpointRef?.blobId, + ); + + const afterFirst = yield* finishRun(first.runId, "after first"); + const second = yield* followUp; + yield* finishRun(second.runId, "after second"); + const third = yield* followUp; + const afterThird = yield* finishRun(third.runId, "after third"); + + const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe( + Effect.provideService(CursorSdk.CursorSdk, { + load: loaders.loadCursorSdk, + loadSqlite: loaders.loadCursorSqlite, + }), + ); + const session = yield* runner.open({ + operation: "resume", + agentId: agent.agentId, + storeCwd: workspace, + options: { apiKey: "synthetic-cursor-key", local: { cwd: workspace, store } }, + threadId: ThreadId.make("rewind"), + providerSessionId: ProviderSessionId.make("rewind"), + }); + + yield* session.rewindAfterRun!(third.runId); + assert.strictEqual(yield* head, afterThird, "nothing ran after the kept run"); + yield* session.rewindAfterRun!(first.runId); + assert.strictEqual(yield* head, afterFirst); + yield* session.close; + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect("constructs without loading and reports first-use load failures as runner errors", () => Effect.gen(function* () { const failure = new Error("missing SDK chunk"); diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts index e76d5cf4a6ea8..c70ad22145de4 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts @@ -137,6 +137,11 @@ export interface CursorAgentSdkSession { * run only from its first checkpoint on; before that the conversation lacks the run's request. */ readonly runCheckpointed?: (runId?: string) => Effect.Effect; + /** + * Rewinds the conversation to just before the run after `runId`, as `cursor-agent` /rewind does. + * The open agent keeps its old conversation in memory, so reopen it before the next send. + */ + readonly rewindAfterRun?: (runId: string) => Effect.Effect; readonly close: Effect.Effect; } @@ -277,6 +282,15 @@ export type CursorAgentSdkProtocolLogEvent = readonly agentId: string; }; } + | { + readonly direction: "outgoing"; + readonly stage: "decoded"; + readonly payload: { + readonly type: "agent.rewind"; + readonly agentId: string; + readonly afterRunId: string; + }; + } | { readonly direction: "incoming"; readonly stage: "decoded"; @@ -834,6 +848,62 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu }, catch: (cause) => runnerError(cause, "agent.run.get"), }), + rewindAfterRun: (runId) => + log({ + direction: "outgoing", + stage: "decoded", + payload: { type: "agent.rewind", agentId: agent.agentId, afterRunId: runId }, + }).pipe( + Effect.andThen( + Effect.tryPromise({ + try: async () => { + const { store, checkpointStore } = await storeView(); + const runs: Array = []; + let cursor: string | undefined; + do { + const page = await store.listRuns( + agent.agentId, + cursor === undefined ? {} : { cursor }, + ); + runs.push(...page.items); + cursor = page.nextCursor; + } while (cursor !== undefined); + const kept = runs.find((candidate) => candidate.runId === runId); + if (kept === undefined) { + throw new Error(`Cursor agent ${agent.agentId} has no run ${runId}.`); + } + const unwound = runs + .filter((candidate) => candidate.turnNumber > kept.turnNumber) + .toSorted((a, b) => a.turnNumber - b.turnNumber)[0]; + if (unwound === undefined) return; + const anchor = unwound.startCheckpointRef?.blobId; + if (anchor === undefined) { + throw new Error(`Cursor run ${unwound.runId} has no starting checkpoint.`); + } + const blobStore = await checkpointStore.getBlobStore(agent.agentId); + const getBlob = + typeof blobStore === "object" && blobStore !== null + ? Reflect.get(blobStore, "getBlob") + : undefined; + if (typeof getBlob !== "function") { + throw new Error("Cursor's checkpoint store cannot read blobs."); + } + const bytes: unknown = await getBlob.call( + blobStore, + undefined, + Buffer.from(anchor, "hex"), + ); + if (!(bytes instanceof Uint8Array)) { + throw new Error(`Cursor checkpoint ${anchor} is missing.`); + } + // Checkpoints are content-addressed, so re-saving the anchor's bytes moves the + // agent's head back to that exact root, like cursor-agent's latestRootBlobId reset. + await checkpointStore.saveCheckpoint(agent.agentId, { toBinary: () => bytes }); + }, + catch: (cause) => runnerError(cause, "agent.rewind"), + }), + ), + ), close: log({ direction: "outgoing", stage: "decoded", diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 9fa8bfe26489c..919e5f3de6666 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -6,9 +6,11 @@ import { assert, describe, it } from "@effect/vitest"; import type { InteractionUpdate } from "@cursor/sdk"; import { toolOutputImages } from "@t3tools/shared/toolOutput"; import { + CheckpointId, EnvironmentId, MessageId, NodeId, + type OrchestrationV2ProviderTurn, ProjectId, ProviderInstanceId, ProviderSessionId, @@ -757,6 +759,9 @@ describe("CursorAdapterV2", () => { const fileSystem = yield* FileSystem.FileSystem; const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-device-" }); const sentMessages: Array = []; + const rewoundAfter: Array = []; + let rewindFails = false; + let createdAgents = 0; const instanceId = ProviderInstanceId.make("cursor"); const threadId = ThreadId.make("cursor-device-thread"); const mcpSessions = yield* McpProviderSessions.McpProviderSessions; @@ -783,11 +788,21 @@ describe("CursorAdapterV2", () => { }).pipe( Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { assertComplete: Effect.void, - open: () => - Effect.succeed({ - agentId: "native-cursor-device", + open: (openInput) => { + const agentId = openInput.agentId ?? `native-cursor-device-${++createdAgents}`; + return Effect.succeed({ + agentId, listMessages: Effect.succeed([]), close: Effect.void, + rewindAfterRun: (runId) => + rewindFails + ? Effect.fail( + new CursorAgentSdk.CursorAgentSdkRunnerError({ + method: "agent.rewind", + cause: "store unavailable", + }), + ) + : Effect.sync(() => void rewoundAfter.push(runId)), send: (input) => Effect.sync(() => { sentMessages.push( @@ -795,7 +810,7 @@ describe("CursorAdapterV2", () => { ); const runId = `native-cursor-run-${sentMessages.length}`; return { - agentId: "native-cursor-device", + agentId, runId, wait: Effect.succeed({ id: runId, @@ -807,7 +822,8 @@ describe("CursorAdapterV2", () => { cancel: Effect.void, }; }), - }), + }); + }, }), Effect.provide(TestProviderHost.layer({ cwd: workspace })), ); @@ -817,7 +833,7 @@ describe("CursorAdapterV2", () => { modelSelection, runtimePolicy, }); - const providerThread = yield* runtime.ensureThread({ + let providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy, @@ -848,13 +864,15 @@ describe("CursorAdapterV2", () => { }; // Starts at run 5: a conversation from before device instructions existed, now resumed. let runOrdinal = 4; - const send = Effect.fnUntraced(function* (compact = false) { + let lastProviderTurn: OrchestrationV2ProviderTurn | undefined; + const send = Effect.fnUntraced(function* (compact = false, nativeThreadHasTurns?: boolean) { runOrdinal += 1; const turnInput = { threadId, providerThread, modelSelection, runtimePolicy, + ...(nativeThreadHasTurns === undefined ? {} : { nativeThreadHasTurns }), runId: RunId.make(`cursor-device-run-${runOrdinal}`), runOrdinal, providerTurnOrdinal: runOrdinal, @@ -870,10 +888,13 @@ describe("CursorAdapterV2", () => { }, }; yield* compact ? runtime.compactThread!(turnInput) : runtime.startTurn(turnInput); - yield* runtime.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), - Stream.runHead, + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, ); + const providerTurn = events.findLast((event) => event.type === "provider_turn.updated"); + if (providerTurn?.type === "provider_turn.updated") + lastProviderTurn = providerTurn.providerTurn; const sent = sentMessages.at(-1)!; return { orchestration: sent.includes("## T3 Code orchestration"), @@ -896,6 +917,61 @@ describe("CursorAdapterV2", () => { yield* setDeviceAccess(true); assert.deepEqual(yield* send(), told(false, true), "device access turned on later"); assert.deepEqual(yield* send(), told(false, false)); + + const keptTurn = lastProviderTurn!; + yield* send(); + const rollbackToKept = runtime.rollbackThread({ + providerThread, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("cursor-device-kept-checkpoint"), + appRunOrdinal: runOrdinal - 1, + providerTurn: keptTurn, + }, + providerThreadTurns: [keptTurn], + }); + rewindFails = true; + yield* Effect.flip(rollbackToKept); + rewindFails = false; + assert.deepEqual( + yield* send(false, true), + told(false, false), + "a failed rewind leaves the conversation, and what it was told, unchanged", + ); + const rewound = yield* rollbackToKept; + assert.deepEqual(rewoundAfter, [keptTurn.nativeTurnRef?.nativeId]); + assert.deepEqual( + rewound.providerThread.nativeThreadRef, + providerThread.nativeThreadRef, + "Cursor rewinds the same agent", + ); + assert.deepEqual( + yield* send(false, true), + told(true, true), + "the rewound conversation may have dropped instructions a later turn carried", + ); + + const rolledBack = yield* runtime.rollbackThread({ + providerThread, + target: { + type: "thread_start", + checkpointId: CheckpointId.make("cursor-device-checkpoint"), + appRunOrdinal: 0, + }, + providerThreadTurns: [], + }); + assert.strictEqual(rolledBack.providerThread.id, providerThread.id); + assert.notStrictEqual( + rolledBack.providerThread.nativeThreadRef?.nativeId, + providerThread.nativeThreadRef?.nativeId, + "a rollback to the thread's start has no checkpoint to rewind onto", + ); + providerThread = rolledBack.providerThread; + assert.deepEqual( + yield* send(false, false), + told(true, true), + "the fresh agent after a rollback has been told nothing", + ); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 04c6aa780e7d0..a72773c18ea3c 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -90,7 +90,7 @@ export const CursorProviderCapabilitiesV2 = { threads: { canCreateEmptyThread: true, canReadThreadSnapshot: true, - canRollbackThread: false, + canRollbackThread: true, canForkThread: false, canForkFromTurn: false, canForkFromSubagentThread: false, @@ -162,8 +162,8 @@ export const CursorProviderCapabilitiesV2 = { checkpointing: { appCanCheckpointFilesystem: true, supportsNestedCheckpointScopes: true, - providerCanRollbackConversation: false, - providerRollbackReturnsSnapshot: false, + providerCanRollbackConversation: true, + providerRollbackReturnsSnapshot: true, providerCanReadConversationSnapshot: true, }, identity: { @@ -2714,7 +2714,10 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const delivered = known?.agent === agent.nativeThreadId ? known - : { orchestration: turnInput.runOrdinal > 1, device: false }; + : { + orchestration: turnInput.nativeThreadHasTurns ?? turnInput.runOrdinal > 1, + device: false, + }; const interrupted = yield* Ref.get(interruptedPrompt); const runCheckpointed = (runId?: string) => agent.session.runCheckpointed?.(runId) ?? Effect.succeed(false); @@ -3245,15 +3248,106 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ), ), ), - rollbackThread: (rollbackInput) => - Effect.fail( - new ProviderAdapter.ProviderAdapterRollbackThreadError({ - driver: CursorAgentSdk.CURSOR_PROVIDER, - providerThreadId: rollbackInput.providerThread.id, - checkpointId: rollbackInput.target.checkpointId, - cause: "Cursor Agent SDK does not expose conversation rollback.", - }), - ), + rollbackThread: Effect.fn("CursorAdapterV2.rollbackThread")( + function* (rollbackInput: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) { + const current = yield* Ref.get(activeTurn); + if (current !== null) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CursorAgentSdk.CURSOR_PROVIDER, + detail: `Cannot roll back Cursor provider thread ${rollbackInput.providerThread.id} while turn ${current.providerTurnId} is active.`, + }); + } + const threadId = rollbackInput.providerThread.appThreadId ?? input.threadId; + const { target } = rollbackInput; + // The kept turns may predate a compaction, so the instructions are sent again. + const forgetConversation = (agent: string) => + Effect.all([ + Ref.set(told, { agent, orchestration: false, device: false }), + Ref.set(interruptedPrompt, null), + Ref.set(resumedAgent, null), + ]); + const now = yield* DateTime.now; + if (target.type === "provider_turn") { + const keptRunId = target.providerTurn.nativeTurnRef?.nativeId; + if (keptRunId == null) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CursorAgentSdk.CURSOR_PROVIDER, + detail: `Provider turn ${target.providerTurn.id} has no Cursor run id.`, + }); + } + const agent = yield* openAgent({ + operation: "resume", + agentId: nativeThreadId(rollbackInput.providerThread), + storeCwd: rollbackInput.providerThread.nativeMetadata?.cursorStoreCwd, + threadId, + modelSelection: input.modelSelection, + runtimePolicy: input.runtimePolicy, + }); + if (agent.session.rewindAfterRun === undefined) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CursorAgentSdk.CURSOR_PROVIDER, + detail: "This Cursor SDK session cannot rewind its conversation.", + }); + } + yield* agent.session.rewindAfterRun(keptRunId); + yield* forgetConversation(agent.nativeThreadId); + yield* agent.session.close.pipe(Effect.ignore); + yield* Ref.set(liveAgent, null); + return { + providerThread: { + ...rollbackInput.providerThread, + providerSessionId: input.providerSessionId, + status: "idle" as const, + updatedAt: now, + }, + providerTurns: [], + messages: [], + runtimeRequests: [], + }; + } + // The first run starts without a checkpoint, so there is nothing to rewind onto. + const opened = yield* openAgent({ + operation: "create", + threadId, + modelSelection: input.modelSelection, + runtimePolicy: input.runtimePolicy, + }); + yield* forgetConversation(opened.nativeThreadId); + return { + providerThread: { + ...rollbackInput.providerThread, + providerSessionId: input.providerSessionId, + nativeThreadRef: { + driver: CursorAgentSdk.CURSOR_PROVIDER, + nativeId: opened.nativeThreadId, + strength: "strong" as const, + }, + nativeConversationHeadRef: null, + nativeMetadata: { + ...rollbackInput.providerThread.nativeMetadata, + cursorStoreCwd: opened.storeCwd, + }, + status: "idle" as const, + updatedAt: now, + }, + providerTurns: [], + messages: [], + runtimeRequests: [], + }; + }, + (effect, rollbackInput) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterRollbackThreadError({ + driver: CursorAgentSdk.CURSOR_PROVIDER, + providerThreadId: rollbackInput.providerThread.id, + checkpointId: rollbackInput.target.checkpointId, + cause, + }), + ), + ), + ), forkThread: (forkInput) => Effect.fail( new ProviderAdapter.ProviderAdapterForkThreadError({ diff --git a/packages/provider-cursor/src/server/status.test.ts b/packages/provider-cursor/src/server/status.test.ts index 0ce81df747e30..8a979b51eb818 100644 --- a/packages/provider-cursor/src/server/status.test.ts +++ b/packages/provider-cursor/src/server/status.test.ts @@ -129,7 +129,7 @@ describe("buildCursorProviderSnapshot", () => { message: "Cursor SDK model discovery returned no built-in models.", models: [], slashCommands: [COMPACT_SLASH_COMMAND], - supportsConversationRollback: false, + supportsConversationRollback: true, }); }); }); diff --git a/packages/provider-cursor/src/server/status.ts b/packages/provider-cursor/src/server/status.ts index 570a7ac34f453..df50b25799393 100644 --- a/packages/provider-cursor/src/server/status.ts +++ b/packages/provider-cursor/src/server/status.ts @@ -27,7 +27,7 @@ import * as CursorSdkCatalog from "./CursorSdkCatalog.ts"; const CURSOR_PRESENTATION = { displayName: "Cursor", - supportsConversationRollback: false, + supportsConversationRollback: true, showInteractionModeToggle: true, } as const; const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({