@devries-cameron20 / t3code-1 / commits / c165587702
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(provider-cursor): Cursor threads report token usage and context fill (#36323)

Julius Marminge committed Nov 13, 2026 at 12:13 UTC c165587702dae88d8e1d2236114f52e44cf2f205
4 files changed +152 -2
packages/provider-cursor/src/server/CursorAgentSdk.test.ts
+1
@@ -181,6 +181,7 @@ describe("CursorAgentSdkRunner", () => {
181 });
182 assert.equal(session.agentId, agent.agentId);
183 assert.deepStrictEqual(yield* session.listMessages, []);
184 + assert.strictEqual(yield* session.readContextUsage!, undefined);
185 yield* session.close;
186 }).pipe(Effect.provide(NodeServices.layer)),
187 );
packages/provider-cursor/src/server/CursorAgentSdk.ts
+38
@@ -9,6 +9,7 @@ import type {
9 SteerAckOutcome,
10 } from "@cursor/sdk";
11 import {
12 + NonNegativeInt,
13 type OrchestrationV2ProviderSession,
14 ProviderDriverKind,
15 type ThreadId,
@@ -17,6 +18,7 @@ import * as Context from "effect/Context";
18 import * as Deferred from "effect/Deferred";
19 import * as Effect from "effect/Effect";
20 import * as Layer from "effect/Layer";
21 +import * as Option from "effect/Option";
22 import * as Ref from "effect/Ref";
23 import * as Schema from "effect/Schema";
24
@@ -105,12 +107,28 @@ export interface CursorAgentSdkRun {
107 readonly steer?: (text: string) => Effect.Effect<SteerAckOutcome, CursorAgentSdkRunnerError>;
108 }
109
110 +export interface CursorContextUsage {
111 + readonly usedTokens: number;
112 + readonly maxTokens: number;
113 +}
114 +
115 +// The SDK types a checkpoint as `unknown`; Cursor keeps the conversation's context fill on it.
116 +const CursorCheckpoint = Schema.Struct({
117 + tokenDetails: Schema.Struct({ usedTokens: NonNegativeInt, maxTokens: NonNegativeInt }),
118 +});
119 +const decodeCursorCheckpoint = Schema.decodeUnknownOption(CursorCheckpoint);
120 +
121 export interface CursorAgentSdkSession {
122 readonly agentId: string;
123 readonly send: <Error>(
124 input: CursorAgentSdkSendInput<Error>,
125 ) => Effect.Effect<CursorAgentSdkRun, CursorAgentSdkRunnerError>;
126 readonly listMessages: Effect.Effect<ReadonlyArray<AgentMessage>, CursorAgentSdkRunnerError>;
127 + /** Context fill at the latest checkpoint, if Cursor saved one. Absent on test doubles. */
128 + readonly readContextUsage?: Effect.Effect<
129 + CursorContextUsage | undefined,
130 + CursorAgentSdkRunnerError
131 + >;
132 readonly close: Effect.Effect<void, CursorAgentSdkRunnerError>;
133 }
134
@@ -748,6 +766,26 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
766 }),
767 ),
768 ),
769 + readContextUsage: Effect.tryPromise({
770 + try: async () => {
771 + const platform =
772 + storePlatform ??
773 + (await createAgentPlatform({
774 + ...(cwd === undefined ? {} : { workspaceRef: cwd }),
775 + ...(input.options.local?.store === undefined
776 + ? {}
777 + : { localStore: input.options.local.store }),
778 + }));
779 + return platform.checkpointStore.loadLatest(agent.agentId);
780 + },
781 + catch: (cause) => runnerError(cause, "agent.checkpoint.load"),
782 + }).pipe(
783 + Effect.map((checkpoint) => {
784 + const usage = Option.getOrUndefined(decodeCursorCheckpoint(checkpoint))?.tokenDetails;
785 + // An unset protobuf message reads as zeros.
786 + return usage === undefined || usage.maxTokens === 0 ? undefined : usage;
787 + }),
788 + ),
789 close: log({
790 direction: "outgoing",
791 stage: "decoded",
packages/provider-cursor/src/server/adapter.test.ts
+46 -2
@@ -418,10 +418,44 @@ describe("CursorAdapterV2", () => {
418 failure: null,
419 answers: [],
420 },
421 - ])("ends the turn with $reason", ({ updates = [], wait, failure, answers }) =>
421 + {
422 + reason: "the token usage Cursor reported",
423 + // Cursor's inputTokens already include cache reads and writes.
424 + updates: [
425 + { type: "text-delta", text: "Done." },
426 + {
427 + type: "turn-ended",
428 + usage: {
429 + inputTokens: 31_961,
430 + outputTokens: 181,
431 + cacheReadTokens: 0,
432 + cacheWriteTokens: 31_955,
433 + },
434 + },
435 + ] satisfies ReadonlyArray<InteractionUpdate>,
436 + wait: Effect.succeed({
437 + id: "native-cursor-run",
438 + requestId: "native-request",
439 + status: "finished" as const,
440 + model: { id: "claude-fable-5" },
441 + durationMs: 1,
442 + }),
443 + failure: null,
444 + usage: {
445 + inputTokens: 31_961,
446 + cachedInputTokens: 0,
447 + cacheCreationTokens: 31_955,
448 + outputTokens: 181,
449 + },
450 + // The checkpoint holds the context fill; billed input counts every step.
451 + contextFill: { usedTokens: 8_304, maxTokens: 200_000 },
452 + },
453 + ])("ends the turn with $reason", ({ updates = [], wait, failure, answers, usage, contextFill }) =>
454 Effect.gen(function* () {
455 const fileSystem = yield* FileSystem.FileSystem;
424 - const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-failure-" });
456 + const workspace = yield* fileSystem.makeTempDirectoryScoped({
457 + prefix: "cursor-v2-failure-",
458 + });
459 const instanceId = ProviderInstanceId.make("cursor");
460 const threadId = ThreadId.make("cursor-failure-thread");
461 const modelSelection = { instanceId, model: "claude-fable-5" };
@@ -440,6 +474,7 @@ describe("CursorAdapterV2", () => {
474 Effect.succeed({
475 agentId: "native-cursor-failure",
476 listMessages: Effect.succeed([]),
477 + readContextUsage: Effect.succeed(contextFill),
478 close: Effect.void,
479 send: (input) =>
480 Effect.gen(function* () {
@@ -528,6 +563,15 @@ describe("CursorAdapterV2", () => {
563 answers,
564 );
565 }
566 + if (usage !== undefined) {
567 + const completedTurn = events.findLast(
568 + (event) =>
569 + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null,
570 + );
571 + assert(completedTurn?.type === "provider_turn.updated");
572 + assert.deepInclude(completedTurn.providerTurn.turnTokenUsage, usage);
573 + assert.deepInclude(completedTurn.providerTurn.tokenUsage, contextFill);
574 + }
575 }).pipe(
576 Effect.scoped,
577 Effect.provide(
packages/provider-cursor/src/server/adapter.ts
+67
@@ -964,8 +964,31 @@ interface ActiveCursorTurn {
964 finalized: boolean;
965 /** The agent's latest turn ended and no new work has started since. */
966 turnEnded: boolean;
967 + readonly session: CursorAgentSdk.CursorAgentSdkSession;
968 + /** What Cursor billed for this run, summed over its turn-ended updates. */
969 + usage: CursorTurnUsage | undefined;
970 }
971
972 +type CursorTurnUsage = NonNullable<Extract<InteractionUpdate, { type: "turn-ended" }>["usage"]>;
973 +
974 +const addCursorTurnUsage = (
975 + total: CursorTurnUsage | undefined,
976 + usage: CursorTurnUsage,
977 +): CursorTurnUsage => {
978 + if (total === undefined) return usage;
979 + const reasoningTokens =
980 + total.reasoningTokens === undefined && usage.reasoningTokens === undefined
981 + ? undefined
982 + : (total.reasoningTokens ?? 0) + (usage.reasoningTokens ?? 0);
983 + return {
984 + inputTokens: total.inputTokens + usage.inputTokens,
985 + outputTokens: total.outputTokens + usage.outputTokens,
986 + cacheReadTokens: total.cacheReadTokens + usage.cacheReadTokens,
987 + cacheWriteTokens: total.cacheWriteTokens + usage.cacheWriteTokens,
988 + ...(reasoningTokens === undefined ? {} : { reasoningTokens }),
989 + };
990 +};
991 +
992 interface CursorLiveAgent {
993 readonly nativeThreadId: string;
994 readonly storeCwd: string;
@@ -2020,6 +2043,9 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2043 }
2044 if (update.type === "turn-ended") {
2045 context.turnEnded = true;
2046 + if (update.usage !== undefined) {
2047 + context.usage = addCursorTurnUsage(context.usage, update.usage);
2048 + }
2049 } else if (
2050 update.type === "step-started" ||
2051 update.type === "user-message-appended" ||
@@ -2110,6 +2136,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2136 readonly context: ActiveCursorTurn;
2137 readonly status: OrchestrationV2ProviderTurn["status"];
2138 readonly completedAt: DateTime.Utc | null;
2139 + readonly tokenUsage?: OrchestrationV2ProviderTurn["tokenUsage"];
2140 }): OrchestrationV2ProviderTurn => ({
2141 id: input.context.providerTurnId,
2142 providerThreadId: input.context.input.providerThread.id,
@@ -2124,6 +2151,24 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2151 status: input.status,
2152 startedAt: input.context.startedAt,
2153 completedAt: input.completedAt,
2154 + ...(input.tokenUsage === undefined ? {} : { tokenUsage: input.tokenUsage }),
2155 + ...(input.completedAt === null || input.context.usage === undefined
2156 + ? {}
2157 + : {
2158 + turnTokenUsage: {
2159 + usageScope: "main_agent",
2160 + usageStatus: input.status === "completed" ? "complete" : "partial",
2161 + // Cursor's inputTokens already include cache reads and writes.
2162 + inputTokens: input.context.usage.inputTokens,
2163 + cachedInputTokens: input.context.usage.cacheReadTokens,
2164 + cacheCreationTokens: input.context.usage.cacheWriteTokens,
2165 + outputTokens: input.context.usage.outputTokens,
2166 + ...(input.context.usage.reasoningTokens === undefined
2167 + ? {}
2168 + : { reasoningTokens: input.context.usage.reasoningTokens }),
2169 + hasSubagents: input.context.subagents.size > 0,
2170 + },
2171 + }),
2172 });
2173
2174 const finalizeTurn = Effect.fnUntraced(function* (input: {
@@ -2161,6 +2206,17 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2206 }
2207 yield* completeReasoning(input.context);
2208 yield* completeAssistant(input.context);
2209 + // The turn's billed totals count every step; only the checkpoint knows the context fill.
2210 + const contextUsage = yield* (
2211 + input.context.session.readContextUsage ?? Effect.undefined
2212 + ).pipe(
2213 + Effect.catch((cause) =>
2214 + Effect.logWarning("orchestration-v2.cursor-context-usage-unavailable", {
2215 + providerTurnId: input.context.providerTurnId,
2216 + cause,
2217 + }).pipe(Effect.as(undefined)),
2218 + ),
2219 + );
2220 yield* emitProviderEvent({
2221 type: "provider_turn.updated",
2222 driver: CursorAgentSdk.CURSOR_PROVIDER,
@@ -2168,6 +2224,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2224 context: input.context,
2225 status: input.status,
2226 completedAt,
2227 + ...(contextUsage === undefined
2228 + ? {}
2229 + : {
2230 + tokenUsage: {
2231 + usedTokens: contextUsage.usedTokens,
2232 + maxTokens: contextUsage.maxTokens,
2233 + updatedAt: DateTime.formatIso(completedAt),
2234 + },
2235 + }),
2236 }),
2237 });
2238 yield* emitProviderEvent({
@@ -2543,6 +2608,8 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
2608 interrupted: false,
2609 finalized: false,
2610 turnEnded: false,
2611 + session: agent.session,
2612 + usage: undefined,
2613 };
2614 yield* Ref.set(activeTurn, context);
2615 yield* emitProviderEvent({