The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 08:30 UTC
feat(cursor): edit earlier messages by rewinding the Cursor agent (#38262)
Co-authored-by: Cursor <cursoragent@cursor.com>
Yash Singh committed
Nov 17, 2026 at 14:21 UTC
13ecf5b22ee9b135f75ad8b78cd120e3c5379037
7 files changed
+329
-28
docs/user/cursor.md
+6
-3
@@ -54,14 +54,17 @@ The adapter supports:
54
- Cursor `task` subagents, projected as read-only child app threads with their tool activity and
55
final result.
56
57
-The public SDK does not currently expose native agent fork, conversation rollback, or interactive
58
-approval callbacks. A text-only steer reaches the current run without restarting it.
57
+The public SDK does not currently expose native agent fork or interactive approval callbacks. A
58
+text-only steer reaches the current run without restarting it.
59
When Cursor cannot deliver the steer, the same message is queued for the next turn after
60
this run finishes. If you press Stop, that follow-up stays held until you resume the queue. Steers
61
with attachments and provider or runtime changes that must apply immediately interrupt and restart
62
the run.
63
Same-provider Cursor forks use the orchestrator's portable full-thread context handoff into a fresh
64
-Cursor agent. The SDK has in-process custom callback tools, but the V2 adapter intentionally uses the
64
+Cursor agent. **Edit from here** and checkpoint rollback rewind the same Cursor agent to just before
65
+the selected message, as `cursor-agent`'s `/rewind` does, so it keeps its exact earlier history.
66
+Rewinding to the thread's first message starts a fresh Cursor agent instead.
67
+The SDK has in-process custom callback tools, but the V2 adapter intentionally uses the
68
authenticated, thread-scoped MCP server instead.
69
70
Portable handoffs summarize eligible timeline items and can omit the end of long messages. Read
packages/provider-cursor/src/server/CursorAgentSdk.test.ts
+58
@@ -205,6 +205,64 @@ describe("CursorAgentSdkRunner", () => {
205
}).pipe(Effect.provide(NodeServices.layer)),
206
);
207
208
+ it.effect("rewinds the agent to the state its first unwound run started from", () =>
209
+ Effect.gen(function* () {
210
+ const fileSystem = yield* FileSystem.FileSystem;
211
+ const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-rewind-" });
212
+ const loaders = yield* Effect.promise(() =>
213
+ vi.importActual<typeof import("./sdk.ts")>("./sdk.ts"),
214
+ );
215
+ const sdk = loaders.loadCursorSdk();
216
+ const store = new sdk.JsonlLocalAgentStore(workspace);
217
+ const platform = yield* Effect.promise(() =>
218
+ sdk.createAgentPlatform({ localStore: store, workspaceRef: workspace }),
219
+ );
220
+ const { agent, run: first } = yield* Effect.promise(() =>
221
+ platform.store.createAgent({ agentId: "agent-rewind", workspaceRef: workspace }),
222
+ );
223
+ const finishRun = (runId: string, state: string) =>
224
+ Effect.promise(async () => {
225
+ const checkpoint = await platform.checkpointStore.saveCheckpoint(agent.agentId, {
226
+ toBinary: () => new TextEncoder().encode(state),
227
+ });
228
+ await platform.store.patchCheckpoint(agent.agentId, runId, checkpoint);
229
+ await platform.store.markRunTerminal(agent.agentId, runId, { status: "FINISHED" });
230
+ return checkpoint.blobId;
231
+ });
232
+ const followUp = Effect.promise(() => platform.store.createFollowUpRun(agent.agentId, {}));
233
+ const head = Effect.promise(
234
+ async () => (await platform.store.getAgent(agent.agentId))?.latestCheckpointRef?.blobId,
235
+ );
236
+
237
+ const afterFirst = yield* finishRun(first.runId, "after first");
238
+ const second = yield* followUp;
239
+ yield* finishRun(second.runId, "after second");
240
+ const third = yield* followUp;
241
+ const afterThird = yield* finishRun(third.runId, "after third");
242
+
243
+ const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe(
244
+ Effect.provideService(CursorSdk.CursorSdk, {
245
+ load: loaders.loadCursorSdk,
246
+ loadSqlite: loaders.loadCursorSqlite,
247
+ }),
248
+ );
249
+ const session = yield* runner.open({
250
+ operation: "resume",
251
+ agentId: agent.agentId,
252
+ storeCwd: workspace,
253
+ options: { apiKey: "synthetic-cursor-key", local: { cwd: workspace, store } },
254
+ threadId: ThreadId.make("rewind"),
255
+ providerSessionId: ProviderSessionId.make("rewind"),
256
+ });
257
+
258
+ yield* session.rewindAfterRun!(third.runId);
259
+ assert.strictEqual(yield* head, afterThird, "nothing ran after the kept run");
260
+ yield* session.rewindAfterRun!(first.runId);
261
+ assert.strictEqual(yield* head, afterFirst);
262
+ yield* session.close;
263
+ }).pipe(Effect.provide(NodeServices.layer)),
264
+ );
265
+
266
it.effect("constructs without loading and reports first-use load failures as runner errors", () =>
267
Effect.gen(function* () {
268
const failure = new Error("missing SDK chunk");
packages/provider-cursor/src/server/CursorAgentSdk.ts
+70
@@ -137,6 +137,11 @@ export interface CursorAgentSdkSession {
137
* run only from its first checkpoint on; before that the conversation lacks the run's request.
138
*/
139
readonly runCheckpointed?: (runId?: string) => Effect.Effect<boolean, CursorAgentSdkRunnerError>;
140
+ /**
141
+ * Rewinds the conversation to just before the run after `runId`, as `cursor-agent` /rewind does.
142
+ * The open agent keeps its old conversation in memory, so reopen it before the next send.
143
+ */
144
+ readonly rewindAfterRun?: (runId: string) => Effect.Effect<void, CursorAgentSdkRunnerError>;
145
readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
146
}
147
@@ -277,6 +282,15 @@ export type CursorAgentSdkProtocolLogEvent =
282
readonly agentId: string;
283
};
284
}
285
+ | {
286
+ readonly direction: "outgoing";
287
+ readonly stage: "decoded";
288
+ readonly payload: {
289
+ readonly type: "agent.rewind";
290
+ readonly agentId: string;
291
+ readonly afterRunId: string;
292
+ };
293
+ }
294
| {
295
readonly direction: "incoming";
296
readonly stage: "decoded";
@@ -834,6 +848,62 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
848
},
849
catch: (cause) => runnerError(cause, "agent.run.get"),
850
}),
851
+ rewindAfterRun: (runId) =>
852
+ log({
853
+ direction: "outgoing",
854
+ stage: "decoded",
855
+ payload: { type: "agent.rewind", agentId: agent.agentId, afterRunId: runId },
856
+ }).pipe(
857
+ Effect.andThen(
858
+ Effect.tryPromise({
859
+ try: async () => {
860
+ const { store, checkpointStore } = await storeView();
861
+ const runs: Array<RunRecord> = [];
862
+ let cursor: string | undefined;
863
+ do {
864
+ const page = await store.listRuns(
865
+ agent.agentId,
866
+ cursor === undefined ? {} : { cursor },
867
+ );
868
+ runs.push(...page.items);
869
+ cursor = page.nextCursor;
870
+ } while (cursor !== undefined);
871
+ const kept = runs.find((candidate) => candidate.runId === runId);
872
+ if (kept === undefined) {
873
+ throw new Error(`Cursor agent ${agent.agentId} has no run ${runId}.`);
874
+ }
875
+ const unwound = runs
876
+ .filter((candidate) => candidate.turnNumber > kept.turnNumber)
877
+ .toSorted((a, b) => a.turnNumber - b.turnNumber)[0];
878
+ if (unwound === undefined) return;
879
+ const anchor = unwound.startCheckpointRef?.blobId;
880
+ if (anchor === undefined) {
881
+ throw new Error(`Cursor run ${unwound.runId} has no starting checkpoint.`);
882
+ }
883
+ const blobStore = await checkpointStore.getBlobStore(agent.agentId);
884
+ const getBlob =
885
+ typeof blobStore === "object" && blobStore !== null
886
+ ? Reflect.get(blobStore, "getBlob")
887
+ : undefined;
888
+ if (typeof getBlob !== "function") {
889
+ throw new Error("Cursor's checkpoint store cannot read blobs.");
890
+ }
891
+ const bytes: unknown = await getBlob.call(
892
+ blobStore,
893
+ undefined,
894
+ Buffer.from(anchor, "hex"),
895
+ );
896
+ if (!(bytes instanceof Uint8Array)) {
897
+ throw new Error(`Cursor checkpoint ${anchor} is missing.`);
898
+ }
899
+ // Checkpoints are content-addressed, so re-saving the anchor's bytes moves the
900
+ // agent's head back to that exact root, like cursor-agent's latestRootBlobId reset.
901
+ await checkpointStore.saveCheckpoint(agent.agentId, { toBinary: () => bytes });
902
+ },
903
+ catch: (cause) => runnerError(cause, "agent.rewind"),
904
+ }),
905
+ ),
906
+ ),
907
close: log({
908
direction: "outgoing",
909
stage: "decoded",
packages/provider-cursor/src/server/adapter.test.ts
+86
-10
@@ -6,9 +6,11 @@ import { assert, describe, it } from "@effect/vitest";
6
import type { InteractionUpdate } from "@cursor/sdk";
7
import { toolOutputImages } from "@t3tools/shared/toolOutput";
8
import {
9
+ CheckpointId,
10
EnvironmentId,
11
MessageId,
12
NodeId,
13
+ type OrchestrationV2ProviderTurn,
14
ProjectId,
15
ProviderInstanceId,
16
ProviderSessionId,
@@ -757,6 +759,9 @@ describe("CursorAdapterV2", () => {
759
const fileSystem = yield* FileSystem.FileSystem;
760
const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-device-" });
761
const sentMessages: Array<string> = [];
762
+ const rewoundAfter: Array<string> = [];
763
+ let rewindFails = false;
764
+ let createdAgents = 0;
765
const instanceId = ProviderInstanceId.make("cursor");
766
const threadId = ThreadId.make("cursor-device-thread");
767
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
@@ -783,11 +788,21 @@ describe("CursorAdapterV2", () => {
788
}).pipe(
789
Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
790
assertComplete: Effect.void,
786
- open: () =>
787
- Effect.succeed({
788
- agentId: "native-cursor-device",
791
+ open: (openInput) => {
792
+ const agentId = openInput.agentId ?? `native-cursor-device-${++createdAgents}`;
793
+ return Effect.succeed({
794
+ agentId,
795
listMessages: Effect.succeed([]),
796
close: Effect.void,
797
+ rewindAfterRun: (runId) =>
798
+ rewindFails
799
+ ? Effect.fail(
800
+ new CursorAgentSdk.CursorAgentSdkRunnerError({
801
+ method: "agent.rewind",
802
+ cause: "store unavailable",
803
+ }),
804
+ )
805
+ : Effect.sync(() => void rewoundAfter.push(runId)),
806
send: (input) =>
807
Effect.sync(() => {
808
sentMessages.push(
@@ -795,7 +810,7 @@ describe("CursorAdapterV2", () => {
810
);
811
const runId = `native-cursor-run-${sentMessages.length}`;
812
return {
798
- agentId: "native-cursor-device",
813
+ agentId,
814
runId,
815
wait: Effect.succeed({
816
id: runId,
@@ -807,7 +822,8 @@ describe("CursorAdapterV2", () => {
822
cancel: Effect.void,
823
};
824
}),
810
- }),
825
+ });
826
+ },
827
}),
828
Effect.provide(TestProviderHost.layer({ cwd: workspace })),
829
);
@@ -817,7 +833,7 @@ describe("CursorAdapterV2", () => {
833
modelSelection,
834
runtimePolicy,
835
});
820
- const providerThread = yield* runtime.ensureThread({
836
+ let providerThread = yield* runtime.ensureThread({
837
threadId,
838
modelSelection,
839
runtimePolicy,
@@ -848,13 +864,15 @@ describe("CursorAdapterV2", () => {
864
};
865
// Starts at run 5: a conversation from before device instructions existed, now resumed.
866
let runOrdinal = 4;
851
- const send = Effect.fnUntraced(function* (compact = false) {
867
+ let lastProviderTurn: OrchestrationV2ProviderTurn | undefined;
868
+ const send = Effect.fnUntraced(function* (compact = false, nativeThreadHasTurns?: boolean) {
869
runOrdinal += 1;
870
const turnInput = {
871
threadId,
872
providerThread,
873
modelSelection,
874
runtimePolicy,
875
+ ...(nativeThreadHasTurns === undefined ? {} : { nativeThreadHasTurns }),
876
runId: RunId.make(`cursor-device-run-${runOrdinal}`),
877
runOrdinal,
878
providerTurnOrdinal: runOrdinal,
@@ -870,10 +888,13 @@ describe("CursorAdapterV2", () => {
888
},
889
};
890
yield* compact ? runtime.compactThread!(turnInput) : runtime.startTurn(turnInput);
873
- yield* runtime.events.pipe(
874
- Stream.filter((event) => event.type === "turn.terminal"),
875
- Stream.runHead,
891
+ const events = yield* runtime.events.pipe(
892
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
893
+ Stream.runCollect,
894
);
895
+ const providerTurn = events.findLast((event) => event.type === "provider_turn.updated");
896
+ if (providerTurn?.type === "provider_turn.updated")
897
+ lastProviderTurn = providerTurn.providerTurn;
898
const sent = sentMessages.at(-1)!;
899
return {
900
orchestration: sent.includes("## T3 Code orchestration"),
@@ -896,6 +917,61 @@ describe("CursorAdapterV2", () => {
917
yield* setDeviceAccess(true);
918
assert.deepEqual(yield* send(), told(false, true), "device access turned on later");
919
assert.deepEqual(yield* send(), told(false, false));
920
+
921
+ const keptTurn = lastProviderTurn!;
922
+ yield* send();
923
+ const rollbackToKept = runtime.rollbackThread({
924
+ providerThread,
925
+ target: {
926
+ type: "provider_turn",
927
+ checkpointId: CheckpointId.make("cursor-device-kept-checkpoint"),
928
+ appRunOrdinal: runOrdinal - 1,
929
+ providerTurn: keptTurn,
930
+ },
931
+ providerThreadTurns: [keptTurn],
932
+ });
933
+ rewindFails = true;
934
+ yield* Effect.flip(rollbackToKept);
935
+ rewindFails = false;
936
+ assert.deepEqual(
937
+ yield* send(false, true),
938
+ told(false, false),
939
+ "a failed rewind leaves the conversation, and what it was told, unchanged",
940
+ );
941
+ const rewound = yield* rollbackToKept;
942
+ assert.deepEqual(rewoundAfter, [keptTurn.nativeTurnRef?.nativeId]);
943
+ assert.deepEqual(
944
+ rewound.providerThread.nativeThreadRef,
945
+ providerThread.nativeThreadRef,
946
+ "Cursor rewinds the same agent",
947
+ );
948
+ assert.deepEqual(
949
+ yield* send(false, true),
950
+ told(true, true),
951
+ "the rewound conversation may have dropped instructions a later turn carried",
952
+ );
953
+
954
+ const rolledBack = yield* runtime.rollbackThread({
955
+ providerThread,
956
+ target: {
957
+ type: "thread_start",
958
+ checkpointId: CheckpointId.make("cursor-device-checkpoint"),
959
+ appRunOrdinal: 0,
960
+ },
961
+ providerThreadTurns: [],
962
+ });
963
+ assert.strictEqual(rolledBack.providerThread.id, providerThread.id);
964
+ assert.notStrictEqual(
965
+ rolledBack.providerThread.nativeThreadRef?.nativeId,
966
+ providerThread.nativeThreadRef?.nativeId,
967
+ "a rollback to the thread's start has no checkpoint to rewind onto",
968
+ );
969
+ providerThread = rolledBack.providerThread;
970
+ assert.deepEqual(
971
+ yield* send(false, false),
972
+ told(true, true),
973
+ "the fresh agent after a rollback has been told nothing",
974
+ );
975
}).pipe(
976
Effect.scoped,
977
Effect.provide(
packages/provider-cursor/src/server/adapter.ts
+107
-13
@@ -90,7 +90,7 @@ export const CursorProviderCapabilitiesV2 = {
90
threads: {
91
canCreateEmptyThread: true,
92
canReadThreadSnapshot: true,
93
- canRollbackThread: false,
93
+ canRollbackThread: true,
94
canForkThread: false,
95
canForkFromTurn: false,
96
canForkFromSubagentThread: false,
@@ -162,8 +162,8 @@ export const CursorProviderCapabilitiesV2 = {
162
checkpointing: {
163
appCanCheckpointFilesystem: true,
164
supportsNestedCheckpointScopes: true,
165
- providerCanRollbackConversation: false,
166
- providerRollbackReturnsSnapshot: false,
165
+ providerCanRollbackConversation: true,
166
+ providerRollbackReturnsSnapshot: true,
167
providerCanReadConversationSnapshot: true,
168
},
169
identity: {
@@ -2714,7 +2714,10 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2714
const delivered =
2715
known?.agent === agent.nativeThreadId
2716
? known
2717
- : { orchestration: turnInput.runOrdinal > 1, device: false };
2717
+ : {
2718
+ orchestration: turnInput.nativeThreadHasTurns ?? turnInput.runOrdinal > 1,
2719
+ device: false,
2720
+ };
2721
const interrupted = yield* Ref.get(interruptedPrompt);
2722
const runCheckpointed = (runId?: string) =>
2723
agent.session.runCheckpointed?.(runId) ?? Effect.succeed(false);
@@ -3245,15 +3248,106 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
3248
),
3249
),
3250
),
3248
- rollbackThread: (rollbackInput) =>
3249
- Effect.fail(
3250
- new ProviderAdapter.ProviderAdapterRollbackThreadError({
3251
- driver: CursorAgentSdk.CURSOR_PROVIDER,
3252
- providerThreadId: rollbackInput.providerThread.id,
3253
- checkpointId: rollbackInput.target.checkpointId,
3254
- cause: "Cursor Agent SDK does not expose conversation rollback.",
3255
- }),
3256
- ),
3251
+ rollbackThread: Effect.fn("CursorAdapterV2.rollbackThread")(
3252
+ function* (rollbackInput: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) {
3253
+ const current = yield* Ref.get(activeTurn);
3254
+ if (current !== null) {
3255
+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3256
+ driver: CursorAgentSdk.CURSOR_PROVIDER,
3257
+ detail: `Cannot roll back Cursor provider thread ${rollbackInput.providerThread.id} while turn ${current.providerTurnId} is active.`,
3258
+ });
3259
+ }
3260
+ const threadId = rollbackInput.providerThread.appThreadId ?? input.threadId;
3261
+ const { target } = rollbackInput;
3262
+ // The kept turns may predate a compaction, so the instructions are sent again.
3263
+ const forgetConversation = (agent: string) =>
3264
+ Effect.all([
3265
+ Ref.set(told, { agent, orchestration: false, device: false }),
3266
+ Ref.set(interruptedPrompt, null),
3267
+ Ref.set(resumedAgent, null),
3268
+ ]);
3269
+ const now = yield* DateTime.now;
3270
+ if (target.type === "provider_turn") {
3271
+ const keptRunId = target.providerTurn.nativeTurnRef?.nativeId;
3272
+ if (keptRunId == null) {
3273
+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3274
+ driver: CursorAgentSdk.CURSOR_PROVIDER,
3275
+ detail: `Provider turn ${target.providerTurn.id} has no Cursor run id.`,
3276
+ });
3277
+ }
3278
+ const agent = yield* openAgent({
3279
+ operation: "resume",
3280
+ agentId: nativeThreadId(rollbackInput.providerThread),
3281
+ storeCwd: rollbackInput.providerThread.nativeMetadata?.cursorStoreCwd,
3282
+ threadId,
3283
+ modelSelection: input.modelSelection,
3284
+ runtimePolicy: input.runtimePolicy,
3285
+ });
3286
+ if (agent.session.rewindAfterRun === undefined) {
3287
+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3288
+ driver: CursorAgentSdk.CURSOR_PROVIDER,
3289
+ detail: "This Cursor SDK session cannot rewind its conversation.",
3290
+ });
3291
+ }
3292
+ yield* agent.session.rewindAfterRun(keptRunId);
3293
+ yield* forgetConversation(agent.nativeThreadId);
3294
+ yield* agent.session.close.pipe(Effect.ignore);
3295
+ yield* Ref.set(liveAgent, null);
3296
+ return {
3297
+ providerThread: {
3298
+ ...rollbackInput.providerThread,
3299
+ providerSessionId: input.providerSessionId,
3300
+ status: "idle" as const,
3301
+ updatedAt: now,
3302
+ },
3303
+ providerTurns: [],
3304
+ messages: [],
3305
+ runtimeRequests: [],
3306
+ };
3307
+ }
3308
+ // The first run starts without a checkpoint, so there is nothing to rewind onto.
3309
+ const opened = yield* openAgent({
3310
+ operation: "create",
3311
+ threadId,
3312
+ modelSelection: input.modelSelection,
3313
+ runtimePolicy: input.runtimePolicy,
3314
+ });
3315
+ yield* forgetConversation(opened.nativeThreadId);
3316
+ return {
3317
+ providerThread: {
3318
+ ...rollbackInput.providerThread,
3319
+ providerSessionId: input.providerSessionId,
3320
+ nativeThreadRef: {
3321
+ driver: CursorAgentSdk.CURSOR_PROVIDER,
3322
+ nativeId: opened.nativeThreadId,
3323
+ strength: "strong" as const,
3324
+ },
3325
+ nativeConversationHeadRef: null,
3326
+ nativeMetadata: {
3327
+ ...rollbackInput.providerThread.nativeMetadata,
3328
+ cursorStoreCwd: opened.storeCwd,
3329
+ },
3330
+ status: "idle" as const,
3331
+ updatedAt: now,
3332
+ },
3333
+ providerTurns: [],
3334
+ messages: [],
3335
+ runtimeRequests: [],
3336
+ };
3337
+ },
3338
+ (effect, rollbackInput) =>
3339
+ effect.pipe(
3340
+ Effect.mapError(
3341
+ (cause) =>
3342
+ new ProviderAdapter.ProviderAdapterRollbackThreadError({
3343
+ driver: CursorAgentSdk.CURSOR_PROVIDER,
3344
+ providerThreadId: rollbackInput.providerThread.id,
3345
+ checkpointId: rollbackInput.target.checkpointId,
3346
+ cause,
3347
+ }),
3348
+ ),
3349
+ ),
3350
+ ),
3351
forkThread: (forkInput) =>
3352
Effect.fail(
3353
new ProviderAdapter.ProviderAdapterForkThreadError({
packages/provider-cursor/src/server/status.test.ts
+1
-1
@@ -129,7 +129,7 @@ describe("buildCursorProviderSnapshot", () => {
129
message: "Cursor SDK model discovery returned no built-in models.",
130
models: [],
131
slashCommands: [COMPACT_SLASH_COMMAND],
132
- supportsConversationRollback: false,
132
+ supportsConversationRollback: true,
133
});
134
});
135
});
packages/provider-cursor/src/server/status.ts
+1
-1
@@ -27,7 +27,7 @@ import * as CursorSdkCatalog from "./CursorSdkCatalog.ts";
27
28
const CURSOR_PRESENTATION = {
29
displayName: "Cursor",
30
- supportsConversationRollback: false,
30
+ supportsConversationRollback: true,
31
showInteractionModeToggle: true,
32
} as const;
33
const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({