Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions docs/user/cursor.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
58 changes: 58 additions & 0 deletions packages/provider-cursor/src/server/CursorAgentSdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof import("./sdk.ts")>("./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");
Expand Down
70 changes: 70 additions & 0 deletions packages/provider-cursor/src/server/CursorAgentSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean, CursorAgentSdkRunnerError>;
/**
* 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<void, CursorAgentSdkRunnerError>;
readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
}

Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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<RunRecord> = [];
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",
Expand Down
96 changes: 86 additions & 10 deletions packages/provider-cursor/src/server/adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -757,6 +759,9 @@ describe("CursorAdapterV2", () => {
const fileSystem = yield* FileSystem.FileSystem;
const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-device-" });
const sentMessages: Array<string> = [];
const rewoundAfter: Array<string> = [];
let rewindFails = false;
let createdAgents = 0;
const instanceId = ProviderInstanceId.make("cursor");
const threadId = ThreadId.make("cursor-device-thread");
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
Expand All @@ -783,19 +788,29 @@ 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(
typeof input.message === "string" ? input.message : input.message.text,
);
const runId = `native-cursor-run-${sentMessages.length}`;
return {
agentId: "native-cursor-device",
agentId,
runId,
wait: Effect.succeed({
id: runId,
Expand All @@ -807,7 +822,8 @@ describe("CursorAdapterV2", () => {
cancel: Effect.void,
};
}),
}),
});
},
}),
Effect.provide(TestProviderHost.layer({ cwd: workspace })),
);
Expand All @@ -817,7 +833,7 @@ describe("CursorAdapterV2", () => {
modelSelection,
runtimePolicy,
});
const providerThread = yield* runtime.ensureThread({
let providerThread = yield* runtime.ensureThread({
threadId,
modelSelection,
runtimePolicy,
Expand Down Expand Up @@ -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,
Expand All @@ -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"),
Expand All @@ -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(
Expand Down
Loading
Loading