Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

add cursor agent provider

Raine Virtae659f72622f1
diff --git a/README.md b/README.md
index f09b119..a76de8b 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,8 @@
`claude-code-proxy` lets you use
[Claude Code](https://www.anthropic.com/claude-code) with your **ChatGPT
-Plus/Pro** subscription or your **Kimi Code** (kimi.com) account.
+Plus/Pro** subscription, your **Kimi Code** (kimi.com) account, or **Cursor
+Agent**.
<img src="meta/claude-code-screenshot.webp" alt="Claude Code running through claude-code-proxy" width="630" />
@@ -45,7 +46,7 @@ artifacts are published as `claude-code-proxy-windows-amd64.zip` and
### 2. Pick a provider and authenticate
-The proxy supports two upstream providers. Pick one and run its login flow; the
+The proxy supports three upstream providers. Pick one and run its login flow; the
proxy will refuse to start traffic until a token is stored.
**Codex (ChatGPT Plus/Pro):**
@@ -67,6 +68,18 @@ claude-code-proxy kimi auth login # device-code flow (prints URL + code)
Sign in with your **kimi.com account**. The verification URL is displayed; open
it in any browser, confirm the code, and the CLI polls until done.
+**Cursor Agent:**
+
+```sh
+cursor-agent login
+claude-code-proxy cursor auth status
+```
+
+Cursor authentication is managed by Cursor Agent. The proxy discovers the same
+stored credentials (`cursor-access-token` on macOS Keychain, or Cursor's
+`auth.json` on other platforms). You can also set `CCP_CURSOR_AUTH_TOKEN` for
+the proxy process.
+
On macOS credentials go to Keychain. On Windows they are written under
`%APPDATA%\claude-code-proxy\<provider>\auth.json`; on Linux they are written
under `${XDG_CONFIG_HOME:-$HOME/.config}/claude-code-proxy/<provider>/auth.json`
@@ -77,6 +90,7 @@ Verify:
```sh
claude-code-proxy codex auth status
claude-code-proxy kimi auth status
+claude-code-proxy cursor auth status
```
### 3. Start the proxy
@@ -95,6 +109,7 @@ upstream for each request is chosen from `ANTHROPIC_MODEL`.
- `gpt-5.5`, `gpt-5.4`, `gpt-5.3-codex`, `gpt-5.3-codex-spark`, `gpt-5.4-mini`, `gpt-5.2` → **codex**
- `kimi-for-coding`, `kimi-k2.6`, `k2.6` → **kimi**
+- `cursor`, `cursor-plan`, `cursor-ask`, `composer-2.5-fast`, `cursor:<raw-model>` → **cursor**
An unknown model returns a 400 listing the supported ids. There is no
implicit default provider.
@@ -122,6 +137,15 @@ ANTHROPIC_AUTH_TOKEN=unused \
ANTHROPIC_MODEL=kimi-for-coding[1m] \
ANTHROPIC_SMALL_FAST_MODEL=kimi-for-coding[1m] \
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 \
+CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK=1 \
+ claude
+
+# Cursor Agent
+ANTHROPIC_BASE_URL=http://localhost:18765 \
+ANTHROPIC_AUTH_TOKEN=unused \
+ANTHROPIC_MODEL=cursor \
+ANTHROPIC_SMALL_FAST_MODEL=cursor \
+CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 \
CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK=1 \
claude
```
@@ -291,6 +315,47 @@ Auth:
| `kimi auth status` | Show user ID + token expiry |
| `kimi auth logout` | Delete stored credentials |
+### Cursor Agent
+
+Upstream: `https://api2.cursor.sh/agent.v1.AgentService/Run` (Cursor Agent's
+HTTP/2 full-duplex Connect protocol). The captured HTTP/1 fallback is
+`RunSSE` plus `/aiserver.v1.BidiService/BidiAppend`; the provider now uses the
+primary HTTP/2 stream.
+
+Supported proxy model ids:
+
+- `cursor`, `cursor-agent`, `cursor-composer`, `cursor-composer-fast` — Cursor
+ Composer 2.5 fast mode
+- `cursor-plan` — same model with Cursor `AGENT_MODE_PLAN`
+- `cursor-ask` — same model with Cursor `AGENT_MODE_ASK`
+- `composer-2.5`, `composer-2.5-fast`
+- `cursor:<raw-model>` — send a raw Cursor model id, with a trailing `-fast`
+ converted into Cursor's `fast=true` model parameter
+
+Plan mode can also be selected per request with metadata:
+
+```json
+{
+ "metadata": {
+ "cursor_mode": "plan"
+ }
+}
+```
+
+Cursor continuation maps Claude Code's `x-claude-code-session-id` to a Cursor
+conversation id in memory. To resume an existing Cursor chat explicitly, set
+`metadata.cursor_chat_id`, `metadata.cursorChatId`, `metadata.cursor_resume`, or
+`metadata.cursorResume` to the Cursor chat id. The observed Cursor session id is
+recorded back into the session map when Cursor returns it.
+
+Auth:
+
+| Command | What it does |
+| -------------------- | ------------------------------------------------------------------- |
+| `cursor auth login` | Prints the required `cursor-agent login` command |
+| `cursor auth status` | Shows discovered Cursor credential source and token expiry |
+| `cursor auth logout` | Clears discovered Cursor credentials from Cursor's local auth store |
+
## How it works
```mermaid
@@ -298,8 +363,8 @@ sequenceDiagram
autonumber
participant CC as Claude Code
participant P as claude-code-proxy
- participant AUTH as OAuth host<br/>(auth.openai.com or<br/>auth.kimi.com)
- participant U as Upstream API<br/>(chatgpt.com/codex or<br/>api.kimi.com)
+ participant AUTH as OAuth host / credential store
+ participant U as Upstream API<br/>(Codex, Kimi, or Cursor)
Note over P,AUTH: One-time: PKCE / device OAuth<br/>tokens cached locally for reuse
@@ -312,7 +377,7 @@ sequenceDiagram
P->>P: translate request<br/>• strip Anthropic-only fields<br/>• system blocks → instructions / system message<br/>• tool_use / tool_result ↔ provider-specific shapes<br/>• prompt_cache_key = session id
P->>U: POST upstream<br/>Bearer + provider-specific headers
- U-->>P: provider SSE<br/>(Codex: output_item.*, output_text.delta, …)<br/>(Kimi: chat.completion.chunk, reasoning_content, …)
+ U-->>P: provider stream<br/>(Codex/Kimi SSE, Cursor Connect frames)
P->>P: reducer: typed events<br/>(thinking / text / tool start/delta/stop, finish)
P-->>CC: Anthropic SSE<br/>(message_start, content_block_*, message_delta, message_stop)
```
@@ -324,6 +389,7 @@ sequenceDiagram
| [`serve`](#serve) | Start the proxy on `PORT` |
| `codex auth login` / `device` / `status` / `logout` | Codex OAuth management |
| `kimi auth login` / `status` / `logout` | Kimi OAuth management |
+| `cursor auth login` / `status` / `logout` | Cursor credential status |
---
@@ -451,6 +517,40 @@ Removes stored auth credentials (Keychain entry on macOS, file elsewhere). Run
---
+### Cursor auth commands
+
+#### `cursor auth login`
+
+Cursor login is handled by Cursor Agent itself:
+
+```sh
+cursor-agent login
+```
+
+The proxy command prints that setup instruction and exits. This avoids using
+`cursor-agent` as a request upstream while still matching Cursor Agent's
+credential storage.
+
+#### `cursor auth status`
+
+```sh
+claude-code-proxy cursor auth status
+```
+
+Shows whether Cursor credentials were discovered, the source, user/email claims
+when present, and token expiry. Non-zero exit if no auth is present.
+
+#### `cursor auth logout`
+
+```sh
+claude-code-proxy cursor auth logout
+```
+
+Clears Cursor credentials from the discovered local auth store. Run
+`cursor-agent login` again to re-authenticate.
+
+---
+
### Endpoints
The proxy speaks enough of the Anthropic API for Claude Code:
@@ -491,6 +591,11 @@ Windows, and at
"oauthHost": "https://auth.kimi.com",
"baseUrl": "https://api.kimi.com/coding/v1"
},
+ "cursor": {
+ "baseUrl": "https://api2.cursor.sh",
+ "clientVersion": "cli-2026.06.04-5fd875e",
+ "agentBundle": "/path/to/cursor-agent/index.js"
+ },
"log": {
"stderr": false,
"verbose": false
@@ -517,6 +622,10 @@ Windows, and at
| `CCP_CODEX_ORIGINATOR` | `codex.originator` | `claude-code-proxy` | Override the `originator` header sent to Codex |
| `CCP_CODEX_USER_AGENT` | `codex.userAgent` | `claude-code-proxy/<version>` | Override the `User-Agent` header sent to Codex |
| `CCP_KIMI_USER_AGENT` | `kimi.userAgent` | `KimiCLI/1.37.0` | Override the `User-Agent` header sent to Kimi |
+| `CCP_CURSOR_BASE_URL` | `cursor.baseUrl` | `https://api2.cursor.sh` | Override Cursor's API base URL |
+| `CCP_CURSOR_CLIENT_VERSION` | `cursor.clientVersion` | `cli-2026.06.04-5fd875e` | Override Cursor client version headers |
+| `CCP_CURSOR_AGENT_BUNDLE` | `cursor.agentBundle` | auto-detected | Path to Cursor Agent's bundled `index.js` used only for protobuf schemas |
+| `CCP_CURSOR_AUTH_TOKEN` | — | unset | Use this Cursor bearer token instead of local Cursor Agent credential storage |
| `CCP_ORIGINATOR` | — | `claude-code-proxy` | Fallback for `CCP_CODEX_ORIGINATOR` |
| `CCP_USER_AGENT` | — | unset | Fallback for `CCP_CODEX_USER_AGENT` and `CCP_KIMI_USER_AGENT` |
@@ -570,10 +679,16 @@ sticky sessions or shared state before enabling continuation.
`${XDG_CONFIG_HOME:-$HOME/.config}/claude-code-proxy/kimi/device_id`; Windows
uses `%APPDATA%\claude-code-proxy\kimi\device_id`. Reused for the lifetime
of the install.
+- Cursor tokens — discovered from Cursor Agent's auth store, not stored under
+ `claude-code-proxy`. On macOS the provider reads Keychain account
+ `cursor-user` with services `cursor-access-token`, `cursor-refresh-token`,
+ and `cursor-api-key`. On Linux it reads
+ `${XDG_CONFIG_HOME:-$HOME/.config}/cursor/auth.json`; on Windows it reads
+ `%APPDATA%\Cursor\auth.json`. `CCP_CURSOR_AUTH_TOKEN` overrides discovery.
## Limitations
-- **Terms of service:** using the Codex or Kimi backends from a non-official
+- **Terms of service:** using the Codex, Kimi, or Cursor backends from a non-official
client is a gray area. Use at your own risk.
- **Rate limits:** shared across all clients of your upstream account. Codex's
`codex.rate_limits.limit_reached` and Kimi's HTTP 429 are both surfaced as
@@ -595,6 +710,14 @@ sticky sessions or shared state before enabling continuation.
- **Codex — `output_config.format`:** translated to Responses API `text.format`
(json_schema with `strict: true`); other Anthropic-specific `output_config`
fields are dropped.
+- **Cursor — protobuf bundle dependency:** the provider speaks Cursor's
+ underlying protocol directly, but reuses the installed Cursor Agent bundle's
+ generated protobuf classes. Set `CCP_CURSOR_AGENT_BUNDLE` if auto-detection
+ cannot find `cursor-agent`.
+- **Cursor — tool round-trips:** text, thinking, plan mode, ask mode, auth, and
+ session continuation are implemented. Full Cursor workspace/tool callbacks are
+ captured and documented under `history/`, but not yet implemented as Claude
+ tool round-trips.
## Development
diff --git a/src/cli.ts b/src/cli.ts
index e938432..6351306 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -7,6 +7,8 @@ import {
aliasProvider as configAliasProvider,
codexTransport,
codexPreviousResponseId,
+ cursorBaseUrl,
+ cursorClientVersion,
} from "./config.ts";
import { configDir } from "./paths.ts";
import { existsSync } from "node:fs";
@@ -181,6 +183,16 @@ function printConfigSummary(): void {
if (cfg.env.CCP_KIMI_BASE_URL) overrides.push("CCP_KIMI_BASE_URL (env)");
else if (fromFile.kimi?.baseUrl) overrides.push("kimi.baseUrl (config)");
+ if (cfg.env.CCP_CURSOR_BASE_URL) overrides.push(`CCP_CURSOR_BASE_URL=${cursorBaseUrl()} (env)`);
+ else if (fromFile.cursor?.baseUrl) overrides.push("cursor.baseUrl (config)");
+
+ if (cfg.env.CCP_CURSOR_CLIENT_VERSION)
+ overrides.push(`CCP_CURSOR_CLIENT_VERSION=${cursorClientVersion()} (env)`);
+ else if (fromFile.cursor?.clientVersion) overrides.push("cursor.clientVersion (config)");
+
+ if (cfg.env.CCP_CURSOR_AGENT_BUNDLE) overrides.push("CCP_CURSOR_AGENT_BUNDLE (env)");
+ else if (fromFile.cursor?.agentBundle) overrides.push("cursor.agentBundle (config)");
+
if (overrides.length > 0) {
console.log("Overrides:");
for (const o of overrides) {
diff --git a/src/config.test.ts b/src/config.test.ts
index 71be924..587ebe6 100644
--- a/src/config.test.ts
+++ b/src/config.test.ts
@@ -17,6 +17,9 @@ import {
kimiUserAgent,
kimiOauthHost,
kimiBaseUrl,
+ cursorBaseUrl,
+ cursorClientVersion,
+ cursorAgentBundle,
logVerbose,
logStderr,
} from "./config.ts";
@@ -56,6 +59,9 @@ describe("config defaults", () => {
expect(kimiUserAgent("default-kimi-ua")).toBe("default-kimi-ua");
expect(kimiOauthHost()).toBe("https://auth.kimi.com");
expect(kimiBaseUrl()).toBe("https://api.kimi.com/coding/v1");
+ expect(cursorBaseUrl()).toBe("https://api2.cursor.sh");
+ expect(cursorClientVersion()).toBe("cli-2026.06.04-5fd875e");
+ expect(cursorAgentBundle()).toBeUndefined();
expect(logVerbose()).toBe(false);
expect(logStderr()).toBe(false);
});
@@ -113,6 +119,23 @@ describe("file overrides default", () => {
expect(kimiOauthHost()).toBe("https://auth.example.com");
});
+ it("cursor config from config.json", () => {
+ writeFileSync(
+ configPath,
+ JSON.stringify({
+ cursor: {
+ baseUrl: "https://cursor.example.com",
+ clientVersion: "cli-test",
+ agentBundle: "/tmp/cursor-agent/index.js",
+ },
+ }),
+ );
+ setEnv({});
+ expect(cursorBaseUrl()).toBe("https://cursor.example.com");
+ expect(cursorClientVersion()).toBe("cli-test");
+ expect(cursorAgentBundle()).toBe("/tmp/cursor-agent/index.js");
+ });
+
it("log.verbose from config.json", () => {
writeFileSync(configPath, JSON.stringify({ log: { verbose: true } }));
setEnv({});
@@ -168,6 +191,27 @@ describe("env overrides file", () => {
expect(kimiUserAgent("default")).toBe("generic-env");
});
+ it("Cursor env vars win over config", () => {
+ writeFileSync(
+ configPath,
+ JSON.stringify({
+ cursor: {
+ baseUrl: "https://cursor-file.example.com",
+ clientVersion: "cli-file",
+ agentBundle: "/file/index.js",
+ },
+ }),
+ );
+ setEnv({
+ CCP_CURSOR_BASE_URL: "https://cursor-env.example.com",
+ CCP_CURSOR_CLIENT_VERSION: "cli-env",
+ CCP_CURSOR_AGENT_BUNDLE: "/env/index.js",
+ });
+ expect(cursorBaseUrl()).toBe("https://cursor-env.example.com");
+ expect(cursorClientVersion()).toBe("cli-env");
+ expect(cursorAgentBundle()).toBe("/env/index.js");
+ });
+
it("logStderr env-set forces true even when config sets false", () => {
writeFileSync(configPath, JSON.stringify({ log: { stderr: false } }));
setEnv({ CCP_LOG_STDERR: "1" });
diff --git a/src/config.ts b/src/config.ts
index bef4c00..96c8191 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -30,6 +30,11 @@ export interface FileConfig {
oauthHost?: string;
baseUrl?: string;
};
+ cursor?: {
+ baseUrl?: string;
+ clientVersion?: string;
+ agentBundle?: string;
+ };
log?: {
stderr?: boolean;
verbose?: boolean;
@@ -102,7 +107,7 @@ function validate(raw: unknown): FileConfig {
out.aliasProvider = parseAliasProvider("aliasProvider", r.aliasProvider);
- const validateStringSection = <K extends "codex" | "kimi" | "log">(
+ const validateStringSection = <K extends "codex" | "kimi" | "cursor" | "log">(
key: K,
keys: ReadonlyArray<keyof NonNullable<FileConfig[K]>>,
types: Record<string, "string" | "boolean">,
@@ -160,6 +165,13 @@ function validate(raw: unknown): FileConfig {
});
if (kimi) out.kimi = kimi;
+ const cursor = validateStringSection("cursor", ["baseUrl", "clientVersion", "agentBundle"], {
+ baseUrl: "string",
+ clientVersion: "string",
+ agentBundle: "string",
+ });
+ if (cursor) out.cursor = cursor;
+
const log = validateStringSection("log", ["stderr", "verbose"], {
stderr: "boolean",
verbose: "boolean",
@@ -299,6 +311,21 @@ export function kimiBaseUrl(): string {
return c.env.CCP_KIMI_BASE_URL ?? c.file.kimi?.baseUrl ?? "https://api.kimi.com/coding/v1";
}
+export function cursorBaseUrl(): string {
+ const c = getConfig();
+ return c.env.CCP_CURSOR_BASE_URL ?? c.file.cursor?.baseUrl ?? "https://api2.cursor.sh";
+}
+
+export function cursorClientVersion(): string {
+ const c = getConfig();
+ return c.env.CCP_CURSOR_CLIENT_VERSION ?? c.file.cursor?.clientVersion ?? "cli-2026.06.04-5fd875e";
+}
+
+export function cursorAgentBundle(): string | undefined {
+ const c = getConfig();
+ return emptyOrUnset(c.env.CCP_CURSOR_AGENT_BUNDLE) ?? emptyOrUnset(c.file.cursor?.agentBundle);
+}
+
// Additive: error/warn always go to stderr in log.ts; this getter only
// controls whether *all* levels are also mirrored to stderr. Matches the
// pre-existing `!!process.env.CCP_LOG_STDERR` semantics where any value
diff --git a/src/providers/cursor/auth/jwt.ts b/src/providers/cursor/auth/jwt.ts
new file mode 100644
index 0000000..8e94b26
--- /dev/null
+++ b/src/providers/cursor/auth/jwt.ts
@@ -0,0 +1,21 @@
+export interface CursorTokenClaims {
+ exp?: number;
+ sub?: string;
+ email?: string;
+ [key: string]: unknown;
+}
+
+export function parseJwtClaims(token: string): CursorTokenClaims | undefined {
+ const parts = token.split(".");
+ if (parts.length !== 3) return undefined;
+ try {
+ return JSON.parse(Buffer.from(parts[1]!, "base64url").toString()) as CursorTokenClaims;
+ } catch {
+ return undefined;
+ }
+}
+
+export function tokenExpiryMs(token: string): number | undefined {
+ const exp = parseJwtClaims(token)?.exp;
+ return typeof exp === "number" ? exp * 1000 : undefined;
+}
diff --git a/src/providers/cursor/auth/token-store.test.ts b/src/providers/cursor/auth/token-store.test.ts
new file mode 100644
index 0000000..e710b27
--- /dev/null
+++ b/src/providers/cursor/auth/token-store.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "bun:test";
+import { loadCursorAuth } from "./token-store.ts";
+import { parseJwtClaims, tokenExpiryMs } from "./jwt.ts";
+
+describe("Cursor auth token discovery", () => {
+ it("loads CCP_CURSOR_AUTH_TOKEN without reading Cursor storage", async () => {
+ const token = jwt({ sub: "user_1", email: "[email protected]", exp: 2_000_000_000 });
+
+ const auth = await loadCursorAuth({ CCP_CURSOR_AUTH_TOKEN: token });
+
+ expect(auth?.accessToken).toBe(token);
+ expect(auth?.source).toBe("environment");
+ expect(auth?.userId).toBe("user_1");
+ expect(auth?.email).toBe("[email protected]");
+ expect(auth?.expires).toBe(2_000_000_000_000);
+ });
+
+ it("parses JWT claims and expiration", () => {
+ const token = jwt({ sub: "user_2", exp: 123 });
+
+ expect(parseJwtClaims(token)?.sub).toBe("user_2");
+ expect(tokenExpiryMs(token)).toBe(123_000);
+ });
+});
+
+function jwt(payload: Record<string, unknown>): string {
+ return [
+ Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url"),
+ Buffer.from(JSON.stringify(payload)).toString("base64url"),
+ "signature",
+ ].join(".");
+}
diff --git a/src/providers/cursor/auth/token-store.ts b/src/providers/cursor/auth/token-store.ts
new file mode 100644
index 0000000..c56036f
--- /dev/null
+++ b/src/providers/cursor/auth/token-store.ts
@@ -0,0 +1,115 @@
+import { readFile, unlink } from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { keychainGet, keychainDelete } from "../../../keychain.ts";
+import { parseJwtClaims, tokenExpiryMs } from "./jwt.ts";
+
+export interface CursorAuth {
+ accessToken: string;
+ refreshToken?: string;
+ apiKey?: string;
+ expires?: number;
+ userId?: string;
+ email?: string;
+ source: string;
+}
+
+interface CursorAuthFile {
+ accessToken?: string;
+ refreshToken?: string;
+ apiKey?: string;
+}
+
+const CURSOR_KEYCHAIN_ACCOUNT = "cursor-user";
+const ACCESS_TOKEN_SERVICE = "cursor-access-token";
+const REFRESH_TOKEN_SERVICE = "cursor-refresh-token";
+const API_KEY_SERVICE = "cursor-api-key";
+
+export async function loadCursorAuth(env: NodeJS.ProcessEnv = process.env): Promise<CursorAuth | undefined> {
+ const envToken = env.CCP_CURSOR_AUTH_TOKEN || env.CURSOR_AUTH_TOKEN;
+ if (envToken) return authFromToken(envToken, "environment");
+
+ if (process.platform === "darwin") {
+ const accessToken = keychainGet(ACCESS_TOKEN_SERVICE, CURSOR_KEYCHAIN_ACCOUNT);
+ if (accessToken) {
+ return enrich({
+ accessToken,
+ refreshToken: keychainGet(REFRESH_TOKEN_SERVICE, CURSOR_KEYCHAIN_ACCOUNT),
+ apiKey: keychainGet(API_KEY_SERVICE, CURSOR_KEYCHAIN_ACCOUNT),
+ source: "macOS Keychain",
+ });
+ }
+ }
+
+ for (const path of cursorAuthFileCandidates(env)) {
+ try {
+ const raw = await readFile(path, "utf8");
+ const parsed = JSON.parse(raw) as CursorAuthFile;
+ if (parsed.accessToken) return enrich({ ...parsed, accessToken: parsed.accessToken, source: path });
+ } catch (err: any) {
+ if (err?.code !== "ENOENT") throw err;
+ }
+ }
+
+ return undefined;
+}
+
+export async function clearCursorAuth(): Promise<void> {
+ if (process.platform === "darwin") {
+ keychainDelete(ACCESS_TOKEN_SERVICE, CURSOR_KEYCHAIN_ACCOUNT);
+ keychainDelete(REFRESH_TOKEN_SERVICE, CURSOR_KEYCHAIN_ACCOUNT);
+ keychainDelete(API_KEY_SERVICE, CURSOR_KEYCHAIN_ACCOUNT);
+ return;
+ }
+
+ for (const path of cursorAuthFileCandidates(process.env)) {
+ try {
+ await unlink(path);
+ } catch (err: any) {
+ if (err?.code !== "ENOENT") throw err;
+ }
+ }
+}
+
+export function cursorAuthLocation(): string {
+ return process.platform === "darwin" ? "Cursor macOS Keychain" : cursorAuthFileCandidates(process.env)[0]!;
+}
+
+export function missingAuthMessage(): string {
+ return [
+ "Cursor authentication was not found.",
+ "Run `cursor-agent login` once, or set CCP_CURSOR_AUTH_TOKEN/CURSOR_AUTH_TOKEN.",
+ "On macOS the provider reads Keychain services cursor-access-token, cursor-refresh-token, and cursor-api-key for account cursor-user.",
+ ].join(" ");
+}
+
+export function expiredAuthMessage(auth: CursorAuth): string {
+ const expires = auth.expires ? new Date(auth.expires).toISOString() : "unknown";
+ return `Cursor access token from ${auth.source} is expired or near expiry (${expires}). Run \`cursor-agent login\` again or set CCP_CURSOR_AUTH_TOKEN.`;
+}
+
+function authFromToken(accessToken: string, source: string): CursorAuth {
+ return enrich({ accessToken, source });
+}
+
+function enrich(auth: Omit<CursorAuth, "expires" | "userId" | "email"> & Partial<CursorAuth>): CursorAuth {
+ const claims = parseJwtClaims(auth.accessToken);
+ return {
+ ...auth,
+ expires: tokenExpiryMs(auth.accessToken),
+ userId: typeof claims?.sub === "string" ? claims.sub : auth.userId,
+ email: typeof claims?.email === "string" ? claims.email : auth.email,
+ };
+}
+
+function cursorAuthFileCandidates(env: NodeJS.ProcessEnv): string[] {
+ if (process.platform === "win32") {
+ const appData = env.APPDATA || join(homedir(), "AppData", "Roaming");
+ return [join(appData, "Cursor", "auth.json")];
+ }
+ if (process.platform === "darwin") {
+ return [join(homedir(), ".cursor", "auth.json")];
+ }
+ const configHome = env.XDG_CONFIG_HOME || join(homedir(), ".config");
+ return [join(configHome, "cursor", "auth.json")];
+}
diff --git a/src/providers/cursor/client.test.ts b/src/providers/cursor/client.test.ts
new file mode 100644
index 0000000..61de59b
--- /dev/null
+++ b/src/providers/cursor/client.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it } from "bun:test";
+import { encodeConnectFrame, runCursorAgent } from "./client.ts";
+import type { CursorProto, ProtoClass, ProtoMessage } from "./proto-loader.ts";
+import type { RequestContext } from "../types.ts";
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+describe("Cursor protocol client", () => {
+ it("acks exec setup and KV messages on the HTTP/2 Run stream", async () => {
+ const sentFrames: Uint8Array[] = [];
+
+ const upstream = await runCursorAgent({
+ prompt: "hello",
+ mode: "AGENT_MODE_AGENT",
+ conversationId: "conversation",
+ model: { modelId: "composer-2.5" },
+ auth: { accessToken: "token", source: "test" },
+ ctx: fakeCtx(),
+ proto: fakeProto,
+ openRunStream: async () => ({
+ readable: streamFromChunks([
+ frame({
+ message: {
+ case: "execServerMessage",
+ value: { id: 0, message: { case: "requestContextArgs", value: {} } },
+ },
+ }),
+ frame({
+ message: {
+ case: "kvServerMessage",
+ value: { id: 0, message: { case: "setBlobArgs", value: {} } },
+ },
+ }),
+ frame({
+ message: {
+ case: "kvServerMessage",
+ value: { id: 2, message: { case: "getBlobArgs", value: {} } },
+ },
+ }),
+ encodeConnectFrame(jsonBytes({}), 2),
+ ]),
+ status: Promise.resolve({ status: 200 }),
+ async write(frame) {
+ sentFrames.push(frame);
+ },
+ close() {},
+ }),
+ });
+ await drain(upstream);
+
+ const clientMessages = sentFrames.map(decodeFrameJson) as Array<Record<string, any>>;
+ expect(clientMessages[0]?.runRequest.conversationId).toBe("conversation");
+ expect(clientMessages[1]).toEqual({ execClientControlMessage: { heartbeat: {} } });
+ expect(clientMessages[2]?.execClientMessage.requestContextResult.success.requestContext).toBeDefined();
+ expect(clientMessages[3]).toEqual({ execClientControlMessage: { streamClose: {} } });
+ expect(clientMessages[4]).toEqual({ kvClientMessage: { setBlobResult: {} } });
+ expect(clientMessages[5]).toEqual({ kvClientMessage: { getBlobResult: {}, id: 2 } });
+ });
+});
+
+const fakeProto: CursorProto = {
+ AgentServerMessage: jsonProtoClass(),
+ AgentClientMessage: jsonProtoClass(),
+};
+
+function jsonProtoClass(): ProtoClass {
+ return {
+ fromBinary(bytes: Uint8Array): ProtoMessage {
+ const json = JSON.parse(decoder.decode(bytes));
+ return messageFromJson(json);
+ },
+ fromJson(json: unknown): ProtoMessage {
+ return messageFromJson(json);
+ },
+ };
+}
+
+function messageFromJson(json: unknown): ProtoMessage {
+ return Object.assign(
+ {
+ toBinary(): Uint8Array {
+ return jsonBytes(json);
+ },
+ toJson(): unknown {
+ return json;
+ },
+ },
+ json && typeof json === "object" && !Array.isArray(json) ? json : {},
+ );
+}
+
+function frame(json: unknown): Uint8Array {
+ return encodeConnectFrame(jsonBytes(json));
+}
+
+function jsonBytes(json: unknown): Uint8Array {
+ return encoder.encode(JSON.stringify(json));
+}
+
+function decodeFrameJson(frame: Uint8Array): unknown {
+ const buf = Buffer.from(frame);
+ const len = buf.readUInt32BE(1);
+ return JSON.parse(decoder.decode(buf.subarray(5, 5 + len)));
+}
+
+function streamFromChunks(chunks: Uint8Array[]): ReadableStream<Uint8Array> {
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const chunk of chunks) controller.enqueue(chunk);
+ controller.close();
+ },
+ });
+}
+
+async function drain(stream: ReadableStream<Uint8Array>): Promise<void> {
+ const reader = stream.getReader();
+ try {
+ while (!(await reader.read()).done) {
+ // Drain.
+ }
+ } finally {
+ reader.releaseLock();
+ }
+}
+
+function fakeCtx(): RequestContext {
+ return {
+ reqId: "req",
+ signal: new AbortController().signal,
+ childLogger: () => ({
+ debug() {},
+ info() {},
+ warn() {},
+ error() {},
+ child() {
+ return this;
+ },
+ }),
+ };
+}
diff --git a/src/providers/cursor/client.ts b/src/providers/cursor/client.ts
new file mode 100644
index 0000000..7548c41
--- /dev/null
+++ b/src/providers/cursor/client.ts
@@ -0,0 +1,498 @@
+import { gunzipSync } from "node:zlib";
+import http2 from "node:http2";
+import { cursorBaseUrl, cursorClientVersion } from "../../config.ts";
+import type { RequestContext } from "../types.ts";
+import type { CursorProto } from "./proto-loader.ts";
+import { loadCursorProto } from "./proto-loader.ts";
+import type { CursorAuth } from "./auth/token-store.ts";
+
+export interface CursorRunOptions {
+ prompt: string;
+ mode: CursorAgentMode;
+ conversationId: string;
+ model: CursorModelRequest;
+ auth: CursorAuth;
+ ctx: RequestContext;
+ proto?: CursorProto;
+ openRunStream?: CursorRunStreamFactory;
+}
+
+export type CursorRunStreamFactory = (opts: {
+ requestId: string;
+ accessToken: string;
+ ctx: RequestContext;
+}) => Promise<CursorRunStream>;
+
+export interface CursorRunStream {
+ readable: ReadableStream<Uint8Array>;
+ status: Promise<{ status: number; detail?: string }>;
+ write(frame: Uint8Array): Promise<void>;
+ close(): void;
+}
+
+export type CursorAgentMode = "AGENT_MODE_AGENT" | "AGENT_MODE_PLAN" | "AGENT_MODE_ASK";
+
+export interface CursorModelRequest {
+ modelId: string;
+ parameters?: Array<{ id: string; value: string }>;
+}
+
+export interface CursorUsage {
+ inputTokens: string;
+ outputTokens: string;
+ cacheReadTokens?: string;
+ cacheWriteTokens?: string;
+}
+
+export type CursorStreamEvent =
+ | { type: "session"; sessionId: string }
+ | { type: "thinking_delta"; text: string }
+ | { type: "text_delta"; text: string }
+ | { type: "usage"; usage: CursorUsage }
+ | { type: "end" };
+
+export class CursorError extends Error {
+ constructor(
+ public status: number,
+ message: string,
+ public detail?: string,
+ ) {
+ super(message);
+ this.name = "CursorError";
+ }
+}
+
+const HEARTBEAT_INTERVAL_MS = 5_000;
+
+export async function runCursorAgent(opts: CursorRunOptions): Promise<ReadableStream<Uint8Array>> {
+ const proto = opts.proto ?? loadCursorProto();
+ const requestId = crypto.randomUUID();
+ const openRunStream = opts.openRunStream ?? openHttp2RunStream;
+ const runUrl = `${cursorBaseUrl().replace(/\/$/, "")}/agent.v1.AgentService/Run`;
+
+ opts.ctx.traffic?.writeJson("020-cursor-run-request", {
+ url: runUrl,
+ requestId,
+ conversationId: opts.conversationId,
+ mode: opts.mode,
+ model: opts.model,
+ });
+
+ const runStream = await openRunStream({
+ requestId,
+ accessToken: opts.auth.accessToken,
+ ctx: opts.ctx,
+ });
+
+ let appendQueue = Promise.resolve();
+ const append = async (messageJson: unknown) => {
+ appendQueue = appendQueue.then(async () => {
+ const messageBytes = proto.AgentClientMessage.fromJson(messageJson).toBinary();
+ const frame = encodeConnectFrame(messageBytes);
+ opts.ctx.traffic?.writeBytes("021-cursor-run-frame", frame);
+ await runStream.write(frame);
+ });
+ await appendQueue;
+ };
+
+ await append({
+ runRequest: {
+ conversationState: {},
+ action: {
+ userMessageAction: {
+ userMessage: {
+ text: opts.prompt,
+ messageId: crypto.randomUUID(),
+ selectedContext: {},
+ mode: opts.mode,
+ },
+ },
+ },
+ mcpTools: {},
+ conversationId: opts.conversationId,
+ requestedModel: opts.model,
+ excludeWorkspaceContext: false,
+ selectedSubagentModels: selectedSubagentModels(opts.model),
+ conversationGroupId: opts.conversationId,
+ },
+ });
+
+ const heartbeat = setInterval(() => {
+ append({ clientHeartbeat: {} }).catch((err) => {
+ opts.ctx.childLogger("cursor.client").warn("cursor heartbeat failed", {
+ err: String(err),
+ });
+ });
+ }, HEARTBEAT_INTERVAL_MS);
+
+ const abort = () => {
+ clearInterval(heartbeat);
+ runStream.close();
+ };
+ opts.ctx.signal.addEventListener("abort", abort, { once: true });
+
+ const response = await runStream.status;
+ if (response.status < 200 || response.status >= 300) {
+ abort();
+ throw new CursorError(response.status, `Cursor AgentService/Run failed with HTTP ${response.status}`, response.detail);
+ }
+
+ return runStream.readable.pipeThrough(
+ new TransformStream<Uint8Array, Uint8Array>({
+ async transform(chunk, controller) {
+ controller.enqueue(chunk);
+ await processServerControlFrames(chunk, proto, append);
+ },
+ flush() {
+ clearInterval(heartbeat);
+ opts.ctx.signal.removeEventListener("abort", abort);
+ runStream.close();
+ },
+ }),
+ );
+}
+
+export async function openHttp2RunStream(opts: {
+ requestId: string;
+ accessToken: string;
+ ctx: RequestContext;
+}): Promise<CursorRunStream> {
+ const base = new URL(cursorBaseUrl());
+ const session = http2.connect(base.origin);
+ await new Promise<void>((resolve, reject) => {
+ const cleanup = () => {
+ session.off("connect", onConnect);
+ session.off("error", onError);
+ };
+ const onConnect = () => {
+ cleanup();
+ resolve();
+ };
+ const onError = (err: Error) => {
+ cleanup();
+ reject(err);
+ };
+ session.once("connect", onConnect);
+ session.once("error", onError);
+ });
+
+ let closed = false;
+ let responseStatus = 0;
+ let errorDetail = "";
+ let resolveStatus!: (value: { status: number; detail?: string }) => void;
+ let rejectStatus!: (err: Error) => void;
+ const status = new Promise<{ status: number; detail?: string }>((resolve, reject) => {
+ resolveStatus = resolve;
+ rejectStatus = reject;
+ });
+
+ const stream = session.request({
+ ":method": "POST",
+ ":path": `${base.pathname.replace(/\/$/, "")}/agent.v1.AgentService/Run`,
+ "authorization": `Bearer ${opts.accessToken}`,
+ "content-type": "application/connect+proto",
+ "connect-protocol-version": "1",
+ "connect-accept-encoding": "gzip,br",
+ "user-agent": "connect-es/1.6.1",
+ "x-cursor-client-type": "cli",
+ "x-cursor-client-version": cursorClientVersion(),
+ "x-ghost-mode": "true",
+ "x-request-id": opts.requestId,
+ "x-original-request-id": opts.requestId,
+ "x-cursor-streaming": "true",
+ "te": "trailers",
+ });
+
+ stream.once("response", (headers) => {
+ responseStatus = Number(headers[":status"] ?? 0);
+ if (responseStatus >= 200 && responseStatus < 300) {
+ resolveStatus({ status: responseStatus });
+ }
+ });
+
+ const readable = new ReadableStream<Uint8Array>({
+ start(controller) {
+ stream.on("data", (chunk: Buffer) => {
+ if (responseStatus >= 400) {
+ errorDetail += chunk.toString("utf8");
+ return;
+ }
+ controller.enqueue(new Uint8Array(chunk));
+ });
+ stream.once("end", () => {
+ if (responseStatus >= 400) {
+ resolveStatus({ status: responseStatus, detail: errorDetail || undefined });
+ }
+ controller.close();
+ session.close();
+ });
+ stream.once("error", (err) => {
+ rejectStatus(err instanceof Error ? err : new Error(String(err)));
+ controller.error(err);
+ session.destroy();
+ });
+ session.once("error", (err) => {
+ rejectStatus(err instanceof Error ? err : new Error(String(err)));
+ controller.error(err);
+ });
+ },
+ cancel() {
+ close();
+ },
+ });
+
+ const close = () => {
+ if (closed) return;
+ closed = true;
+ stream.close();
+ session.close();
+ };
+
+ return {
+ readable,
+ status,
+ write(frame: Uint8Array) {
+ if (closed || stream.destroyed) {
+ return Promise.reject(new Error("Cursor HTTP/2 Run stream is closed"));
+ }
+ return new Promise<void>((resolve, reject) => {
+ stream.write(Buffer.from(frame), (err) => {
+ if (err) reject(err);
+ else resolve();
+ });
+ });
+ },
+ close,
+ };
+}
+
+async function processServerControlFrames(
+ chunk: Uint8Array,
+ proto: CursorProto,
+ append: (messageJson: unknown) => Promise<void>,
+): Promise<void> {
+ const state = controlFrameState.get(append) ?? {
+ buffer: Buffer.alloc(0),
+ execHeartbeatSent: false,
+ requestContextAcked: false,
+ };
+ controlFrameState.set(append, state);
+ state.buffer = Buffer.concat([state.buffer, Buffer.from(chunk)]);
+ while (state.buffer.byteLength >= 5) {
+ const flags = state.buffer[0]!;
+ const len = state.buffer.readUInt32BE(1);
+ if (state.buffer.byteLength < 5 + len) break;
+ let payload = state.buffer.subarray(5, 5 + len);
+ state.buffer = state.buffer.subarray(5 + len);
+ if (flags & 1) payload = gunzipSync(payload);
+ if (flags & 2) continue;
+ const message = proto.AgentServerMessage.fromBinary(payload) as unknown as CursorOneofMessage;
+ const oneof = message.message;
+ if (oneof?.case === "execServerMessage") {
+ if (!state.execHeartbeatSent) {
+ state.execHeartbeatSent = true;
+ await append({ execClientControlMessage: { heartbeat: {} } });
+ }
+ if (oneof.value?.message?.case === "requestContextArgs" && !state.requestContextAcked) {
+ state.requestContextAcked = true;
+ await append({ execClientMessage: buildRequestContextResult(oneof.value) });
+ await append({ execClientControlMessage: { streamClose: {} } });
+ }
+ } else if (oneof?.case === "kvServerMessage") {
+ const kv = oneof.value;
+ if (kv?.message?.case === "setBlobArgs") {
+ const msg: Record<string, unknown> = { setBlobResult: {} };
+ if (typeof kv.id === "number" && kv.id !== 0) msg.id = kv.id;
+ await append({ kvClientMessage: msg });
+ } else if (kv?.message?.case === "getBlobArgs") {
+ const msg: Record<string, unknown> = { getBlobResult: {} };
+ if (typeof kv.id === "number" && kv.id !== 0) msg.id = kv.id;
+ await append({ kvClientMessage: msg });
+ }
+ }
+ }
+}
+
+function buildRequestContextResult(exec: {
+ id?: number;
+ execId?: string;
+ message?: { case?: string; value?: unknown };
+}): Record<string, unknown> {
+ return {
+ ...(typeof exec.id === "number" ? { id: exec.id } : {}),
+ ...(typeof exec.execId === "string" ? { execId: exec.execId } : {}),
+ requestContextResult: {
+ success: {
+ requestContext: {
+ env: {
+ osVersion: `${process.platform} ${process.arch}`,
+ workspacePaths: [process.cwd()],
+ shell: process.env.SHELL || "",
+ sandboxEnabled: false,
+ projectFolder: process.cwd(),
+ processWorkingDirectory: process.cwd(),
+ },
+ repositoryInfoComplete: true,
+ rulesInfoComplete: true,
+ envInfoComplete: true,
+ customSubagentsInfoComplete: true,
+ mcpFileSystemInfoComplete: true,
+ mcpInfoComplete: true,
+ gitStatusInfoComplete: true,
+ agentSkillsInfoComplete: true,
+ },
+ },
+ },
+ };
+}
+
+const controlFrameState = new WeakMap<
+ (messageJson: unknown) => Promise<void>,
+ { buffer: Buffer; execHeartbeatSent: boolean; requestContextAcked: boolean }
+>();
+
+interface CursorOneofMessage {
+ message?: {
+ case?: string;
+ value?: {
+ id?: number;
+ execId?: string;
+ message?: { case?: string; value?: unknown };
+ };
+ };
+}
+
+export async function* decodeCursorStream(
+ body: ReadableStream<Uint8Array>,
+ proto: CursorProto = loadCursorProto(),
+): AsyncGenerator<CursorStreamEvent> {
+ let buffer = Buffer.alloc(0);
+ const reader = body.getReader();
+ try {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ if (!value?.byteLength) continue;
+ buffer = Buffer.concat([buffer, Buffer.from(value)]);
+ while (buffer.byteLength >= 5) {
+ const flags = buffer[0]!;
+ const len = buffer.readUInt32BE(1);
+ if (buffer.byteLength < 5 + len) break;
+ let payload = buffer.subarray(5, 5 + len);
+ buffer = buffer.subarray(5 + len);
+ if (flags & 1) payload = gunzipSync(payload);
+ if (flags & 2) {
+ yield { type: "end" };
+ continue;
+ }
+ const decoded = safeToJson(proto.AgentServerMessage.fromBinary(payload));
+ if (!decoded) continue;
+ yield* eventsFromServerMessage(decoded);
+ }
+ }
+ } finally {
+ reader.releaseLock();
+ }
+}
+
+function* eventsFromServerMessage(json: unknown): Generator<CursorStreamEvent> {
+ if (!isRecord(json)) return;
+ const exec = asRecord(json.execServerMessage);
+ const requestContextArgs = asRecord(exec?.requestContextArgs);
+ const notesSessionId = requestContextArgs?.notesSessionId;
+ if (typeof notesSessionId === "string" && notesSessionId) {
+ yield { type: "session", sessionId: notesSessionId };
+ }
+
+ const interaction = asRecord(json.interactionUpdate);
+ const thinkingDelta = asRecord(interaction?.thinkingDelta)?.text;
+ if (typeof thinkingDelta === "string" && thinkingDelta) {
+ yield { type: "thinking_delta", text: thinkingDelta };
+ }
+ const textDelta = asRecord(interaction?.textDelta)?.text;
+ if (typeof textDelta === "string" && textDelta) {
+ yield { type: "text_delta", text: textDelta };
+ }
+ const turnEnded = asRecord(interaction?.turnEnded);
+ if (turnEnded) {
+ yield {
+ type: "usage",
+ usage: {
+ inputTokens: stringToken(turnEnded.inputTokens),
+ outputTokens: stringToken(turnEnded.outputTokens),
+ cacheReadTokens: stringToken(turnEnded.cacheReadTokens),
+ cacheWriteTokens: stringToken(turnEnded.cacheWriteTokens),
+ },
+ };
+ }
+}
+
+export function encodeConnectFrame(payload: Uint8Array, flags = 0): Uint8Array {
+ const out = new Uint8Array(5 + payload.byteLength);
+ const view = new DataView(out.buffer);
+ view.setUint8(0, flags);
+ view.setUint32(1, payload.byteLength, false);
+ out.set(payload, 5);
+ return out;
+}
+
+function selectedSubagentModels(model: CursorModelRequest): CursorModelRequest[] {
+ return [
+ { modelId: "default" },
+ model,
+ {
+ modelId: "claude-opus-4-8",
+ parameters: [
+ { id: "thinking", value: "true" },
+ { id: "context", value: "300k" },
+ { id: "effort", value: "high" },
+ { id: "fast", value: "false" },
+ ],
+ },
+ {
+ modelId: "gpt-5.5",
+ parameters: [
+ { id: "context", value: "272k" },
+ { id: "reasoning", value: "extra-high" },
+ { id: "fast", value: "false" },
+ ],
+ },
+ {
+ modelId: "claude-sonnet-4-6",
+ parameters: [
+ { id: "thinking", value: "true" },
+ { id: "context", value: "200k" },
+ { id: "effort", value: "medium" },
+ ],
+ },
+ {
+ modelId: "gpt-5.3-codex",
+ parameters: [
+ { id: "reasoning", value: "medium" },
+ { id: "fast", value: "false" },
+ ],
+ },
+ ];
+}
+
+function safeToJson(message: { toJson(options?: unknown): unknown }): unknown | undefined {
+ try {
+ return message.toJson({ emitDefaultValues: false });
+ } catch {
+ return undefined;
+ }
+}
+
+function stringToken(value: unknown): string {
+ if (typeof value === "string") return value;
+ if (typeof value === "number") return String(value);
+ return "0";
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
+function asRecord(value: unknown): Record<string, unknown> | undefined {
+ return isRecord(value) ? value : undefined;
+}
diff --git a/src/providers/cursor/count-tokens.ts b/src/providers/cursor/count-tokens.ts
new file mode 100644
index 0000000..244b404
--- /dev/null
+++ b/src/providers/cursor/count-tokens.ts
@@ -0,0 +1,13 @@
+import { encode } from "gpt-tokenizer/model/gpt-4o";
+import type { AnthropicRequest } from "../../anthropic/schema.ts";
+import { renderCursorPrompt } from "./translate/request.ts";
+
+export function countCursorTokens(req: AnthropicRequest): number {
+ let total = encode(renderCursorPrompt(req)).length;
+ for (const tool of req.tools ?? []) {
+ total += encode(tool.name).length;
+ if (tool.description) total += encode(tool.description).length;
+ total += encode(JSON.stringify(tool.input_schema ?? {})).length;
+ }
+ return total;
+}
diff --git a/src/providers/cursor/index.test.ts b/src/providers/cursor/index.test.ts
new file mode 100644
index 0000000..e7dc04c
--- /dev/null
+++ b/src/providers/cursor/index.test.ts
@@ -0,0 +1,166 @@
+import { afterEach, describe, expect, it } from "bun:test";
+import { cursorProvider, createCursorProvider } from "./index.ts";
+import type { RequestContext } from "../types.ts";
+import { encodeConnectFrame } from "./client.ts";
+import type { CursorProto, ProtoClass, ProtoMessage } from "./proto-loader.ts";
+import { parseSseStream } from "../../sse.ts";
+
+const originalToken = process.env.CCP_CURSOR_AUTH_TOKEN;
+
+afterEach(() => {
+ if (originalToken === undefined) delete process.env.CCP_CURSOR_AUTH_TOKEN;
+ else process.env.CCP_CURSOR_AUTH_TOKEN = originalToken;
+});
+
+describe("Cursor provider auth errors", () => {
+ it("surfaces expired auth before calling Cursor", async () => {
+ process.env.CCP_CURSOR_AUTH_TOKEN = jwt({ exp: 1 });
+
+ const response = await cursorProvider.handleMessages(
+ {
+ model: "cursor",
+ messages: [{ role: "user", content: "hello" }],
+ },
+ fakeCtx(),
+ );
+ const body = (await response.json()) as {
+ error: { type: string; message: string };
+ };
+
+ expect(response.status).toBe(401);
+ expect(body.error.type).toBe("authentication_error");
+ expect(body.error.message).toContain("expired or near expiry");
+ });
+});
+
+describe("Cursor provider messages", () => {
+ it("returns assistant text for non-streaming requests", async () => {
+ const provider = createCursorProvider({
+ loadAuth: async () => ({ accessToken: "token", source: "test" }),
+ runAgent: async () =>
+ streamFromChunks([
+ frame({ interactionUpdate: { textDelta: { text: "hello" } } }),
+ frame({ interactionUpdate: { turnEnded: { inputTokens: "4", outputTokens: "1" } } }),
+ encodeConnectFrame(jsonBytes({}), 2),
+ ]),
+ proto: fakeProto,
+ });
+
+ const response = await provider.handleMessages(
+ {
+ model: "cursor",
+ messages: [{ role: "user", content: "hello" }],
+ },
+ fakeCtx(),
+ );
+ const body = (await response.json()) as { content: Array<{ type: string; text?: string }> };
+
+ expect(response.status).toBe(200);
+ expect(body.content).toEqual([{ type: "text", text: "hello" }]);
+ });
+
+ it("returns valid Anthropic SSE for streaming requests", async () => {
+ const provider = createCursorProvider({
+ loadAuth: async () => ({ accessToken: "token", source: "test" }),
+ runAgent: async () =>
+ streamFromChunks([
+ frame({ interactionUpdate: { textDelta: { text: "streamed" } } }),
+ frame({ interactionUpdate: { turnEnded: { inputTokens: "4", outputTokens: "2" } } }),
+ encodeConnectFrame(jsonBytes({}), 2),
+ ]),
+ proto: fakeProto,
+ });
+
+ const response = await provider.handleMessages(
+ {
+ model: "cursor",
+ stream: true,
+ messages: [{ role: "user", content: "hello" }],
+ },
+ fakeCtx(),
+ );
+ const events = [];
+ for await (const event of parseSseStream(response.body!)) {
+ events.push({ event: event.event, data: JSON.parse(event.data) });
+ }
+
+ expect(response.headers.get("content-type")).toBe("text/event-stream");
+ expect(events.map((event) => event.event)).toContain("message_start");
+ expect(events.find((event) => event.event === "content_block_delta")?.data.delta.text).toBe(
+ "streamed",
+ );
+ expect(events.at(-1)?.event).toBe("message_stop");
+ });
+});
+
+function fakeCtx(): RequestContext {
+ return {
+ reqId: "req",
+ sessionId: "session",
+ signal: new AbortController().signal,
+ childLogger: () => ({
+ debug() {},
+ info() {},
+ warn() {},
+ error() {},
+ child() {
+ return this;
+ },
+ }),
+ };
+}
+
+function jwt(payload: Record<string, unknown>): string {
+ return [
+ Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url"),
+ Buffer.from(JSON.stringify(payload)).toString("base64url"),
+ "signature",
+ ].join(".");
+}
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+const fakeProto: CursorProto = {
+ AgentServerMessage: jsonProtoClass(),
+ AgentClientMessage: jsonProtoClass(),
+};
+
+function jsonProtoClass(): ProtoClass {
+ return {
+ fromBinary(bytes: Uint8Array): ProtoMessage {
+ return messageFromJson(JSON.parse(decoder.decode(bytes)));
+ },
+ fromJson(json: unknown): ProtoMessage {
+ return messageFromJson(json);
+ },
+ };
+}
+
+function messageFromJson(json: unknown): ProtoMessage {
+ return {
+ toBinary(): Uint8Array {
+ return jsonBytes(json);
+ },
+ toJson(): unknown {
+ return json;
+ },
+ };
+}
+
+function frame(json: unknown): Uint8Array {
+ return encodeConnectFrame(jsonBytes(json));
+}
+
+function jsonBytes(json: unknown): Uint8Array {
+ return encoder.encode(JSON.stringify(json));
+}
+
+function streamFromChunks(chunks: Uint8Array[]): ReadableStream<Uint8Array> {
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const chunk of chunks) controller.enqueue(chunk);
+ controller.close();
+ },
+ });
+}
diff --git a/src/providers/cursor/index.ts b/src/providers/cursor/index.ts
new file mode 100644
index 0000000..f8c5db7
--- /dev/null
+++ b/src/providers/cursor/index.ts
@@ -0,0 +1,193 @@
+import type { AnthropicRequest } from "../../anthropic/schema.ts";
+import { wantsDownstreamStream } from "../../anthropic/stream.ts";
+import { logVerbose } from "../../config.ts";
+import type { CliHandlers, Provider, RequestContext } from "../types.ts";
+import {
+ CursorError,
+ runCursorAgent,
+ type CursorRunOptions,
+} from "./client.ts";
+import { countCursorTokens } from "./count-tokens.ts";
+import {
+ cursorAuthLocation,
+ expiredAuthMessage,
+ loadCursorAuth,
+ missingAuthMessage,
+ clearCursorAuth,
+} from "./auth/token-store.ts";
+import { renderCursorPrompt } from "./translate/request.ts";
+import { CURSOR_SUPPORTED_MODELS, resolveCursorModel } from "./translate/model.ts";
+import {
+ accumulateCursorResponse,
+ translateCursorStream,
+} from "./translate/response.ts";
+import {
+ cursorConversationForRequest,
+ recordCursorConversation,
+} from "./session.ts";
+import type { CursorAuth } from "./auth/token-store.ts";
+import type { CursorProto } from "./proto-loader.ts";
+
+const AUTH_EXPIRY_SKEW_MS = 60_000;
+
+export interface CursorProviderDeps {
+ loadAuth: () => Promise<CursorAuth | undefined>;
+ runAgent: (opts: CursorRunOptions) => Promise<ReadableStream<Uint8Array>>;
+ proto?: CursorProto;
+}
+
+const defaultDeps: CursorProviderDeps = {
+ loadAuth: () => loadCursorAuth(),
+ runAgent: runCursorAgent,
+};
+
+function jsonError(status: number, type: string, message: string): Response {
+ return new Response(JSON.stringify({ type: "error", error: { type, message } }), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+async function handleCountTokens(body: AnthropicRequest, ctx: RequestContext): Promise<Response> {
+ const tokens = countCursorTokens(body);
+ ctx.childLogger("provider.cursor").debug("count_tokens", { tokens });
+ return new Response(JSON.stringify({ input_tokens: tokens }), {
+ headers: { "content-type": "application/json" },
+ });
+}
+
+async function handleMessages(
+ body: AnthropicRequest,
+ ctx: RequestContext,
+ deps: CursorProviderDeps,
+): Promise<Response> {
+ const log = ctx.childLogger("provider.cursor");
+ const messageId = `msg_${crypto.randomUUID().replace(/-/g, "")}`;
+ const selection = resolveCursorModel(body);
+ const prompt = renderCursorPrompt(body);
+ const wantStream = wantsDownstreamStream(body);
+ const conversationId = cursorConversationForRequest(body, ctx.sessionId);
+
+ log.debug("cursor request", {
+ requestedModel: body.model,
+ resolvedModel: selection.requestedModel,
+ mode: selection.mode,
+ conversationId,
+ stream: wantStream,
+ messageCount: body.messages.length,
+ promptChars: prompt.length,
+ });
+ if (logVerbose()) log.debug("cursor prompt", { prompt });
+
+ const auth = await deps.loadAuth();
+ if (!auth) return jsonError(401, "authentication_error", missingAuthMessage());
+ if (auth.expires && auth.expires <= Date.now() + AUTH_EXPIRY_SKEW_MS) {
+ return jsonError(401, "authentication_error", expiredAuthMessage(auth));
+ }
+
+ let upstream: ReadableStream<Uint8Array>;
+ try {
+ upstream = await deps.runAgent({
+ prompt,
+ mode: selection.mode,
+ conversationId,
+ model: selection.requestedModel,
+ auth,
+ ctx,
+ });
+ } catch (err) {
+ if (err instanceof CursorError) {
+ log.warn("cursor upstream error", {
+ status: err.status,
+ message: err.message,
+ detail: err.detail,
+ });
+ const type = err.status === 401 || err.status === 403 ? "authentication_error" : "api_error";
+ return jsonError(err.status, type, err.detail || err.message);
+ }
+ throw err;
+ }
+
+ const onSession = (cursorSessionId: string) => {
+ recordCursorConversation(ctx.sessionId, cursorSessionId);
+ log.debug("cursor session observed", { cursorSessionId });
+ };
+
+ if (wantStream) {
+ const stream = translateCursorStream(upstream, {
+ messageId,
+ model: body.model,
+ log: ctx.childLogger("cursor.stream"),
+ signal: ctx.signal,
+ traffic: ctx.traffic,
+ proto: deps.proto,
+ onSession,
+ });
+ return new Response(stream, {
+ status: 200,
+ headers: {
+ "content-type": "text/event-stream",
+ "cache-control": "no-cache",
+ connection: "keep-alive",
+ },
+ });
+ }
+
+ try {
+ const result = await accumulateCursorResponse(upstream, {
+ messageId,
+ model: body.model,
+ log: ctx.childLogger("cursor.accumulate"),
+ traffic: ctx.traffic,
+ proto: deps.proto,
+ onSession,
+ });
+ return new Response(JSON.stringify(result.response), {
+ headers: { "content-type": "application/json" },
+ });
+ } catch (err) {
+ log.warn("cursor accumulate error", { err: String(err) });
+ return jsonError(502, "api_error", String(err));
+ }
+}
+
+const cli: CliHandlers = {
+ async login() {
+ console.log("Cursor login is managed by Cursor Agent.");
+ console.log("Run: cursor-agent login");
+ console.log("Or set CCP_CURSOR_AUTH_TOKEN/CURSOR_AUTH_TOKEN for this proxy.");
+ },
+ async status() {
+ const auth = await loadCursorAuth();
+ if (!auth) {
+ console.log("Not authenticated");
+ console.log(missingAuthMessage());
+ process.exit(1);
+ }
+ console.log(`Storage: ${auth.source}`);
+ if (auth.email) console.log(`Email: ${auth.email}`);
+ if (auth.userId) console.log(`User: ${auth.userId}`);
+ if (auth.expires) {
+ const ms = auth.expires - Date.now();
+ console.log(`Expires: ${new Date(auth.expires).toISOString()} (in ${Math.floor(ms / 1000)}s)`);
+ } else {
+ console.log("Expires: unknown");
+ }
+ },
+ async logout() {
+ await clearCursorAuth();
+ console.log(`Cleared Cursor auth from ${cursorAuthLocation()}`);
+ },
+};
+
+export function createCursorProvider(deps: CursorProviderDeps = defaultDeps): Provider {
+ return {
+ name: "cursor",
+ supportedModels: CURSOR_SUPPORTED_MODELS,
+ handleMessages: (body, ctx) => handleMessages(body, ctx, deps),
+ handleCountTokens,
+ cli,
+ };
+}
+
+export const cursorProvider: Provider = createCursorProvider();
diff --git a/src/providers/cursor/proto-loader.ts b/src/providers/cursor/proto-loader.ts
new file mode 100644
index 0000000..e9ea18e
--- /dev/null
+++ b/src/providers/cursor/proto-loader.ts
@@ -0,0 +1,122 @@
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { execFileSync } from "node:child_process";
+import vm from "node:vm";
+import { createRequire } from "node:module";
+import { cursorAgentBundle } from "../../config.ts";
+
+export interface CursorProto {
+ AgentClientMessage: ProtoClass;
+ AgentServerMessage: ProtoClass;
+}
+
+export interface ProtoClass {
+ typeName?: string;
+ fromBinary(bytes: Uint8Array): ProtoMessage;
+ fromJson(json: unknown): ProtoMessage;
+}
+
+export interface ProtoMessage {
+ toBinary(): Uint8Array;
+ toJson(options?: unknown): unknown;
+}
+
+let cached: CursorProto | undefined;
+
+export function loadCursorProto(): CursorProto {
+ if (cached) return cached;
+ const bundle = resolveCursorBundle();
+ const code = patchBundleMain(readFileSync(bundle, "utf8"));
+ const req = createRequire(bundle);
+ const ctx: Record<string, unknown> = {
+ require: req,
+ console,
+ process,
+ Buffer,
+ TextDecoder,
+ TextEncoder,
+ crypto,
+ performance,
+ URL,
+ Headers,
+ setTimeout,
+ clearTimeout,
+ __filename: bundle,
+ __dirname: dirname(bundle),
+ };
+ ctx.globalThis = ctx;
+ ctx.global = ctx;
+ vm.runInNewContext(code, ctx, { filename: bundle });
+ const webpackRequire = ctx.__wr as ((id: string) => Record<string, unknown>) | undefined;
+ if (!webpackRequire) {
+ throw new Error(`Cursor Agent protobuf loader failed: webpack require was not exposed from ${bundle}`);
+ }
+
+ const agent = webpackRequire("../proto/dist/generated/agent/v1/agent_service_pb.js");
+ cached = {
+ AgentClientMessage: requireProtoClass(agent.KS, "agent.v1.AgentClientMessage"),
+ AgentServerMessage: requireProtoClass(agent.Oy, "agent.v1.AgentServerMessage"),
+ };
+ return cached;
+}
+
+export function resolveCursorBundle(): string {
+ const configured = cursorAgentBundle();
+ if (configured) return normalizeBundlePath(configured);
+
+ const found = findOnPath("cursor-agent");
+ if (found) return normalizeBundlePath(found);
+
+ throw new Error(
+ "Cursor Agent bundle not found. Install cursor-agent or set CCP_CURSOR_AGENT_BUNDLE to its index.js path.",
+ );
+}
+
+function normalizeBundlePath(path: string): string {
+ const real = realpathSync(path);
+ if (real.endsWith("index.js")) return real;
+ const siblingIndex = join(dirname(real), "index.js");
+ if (existsSync(siblingIndex)) return siblingIndex;
+ throw new Error(`Cursor Agent bundle path does not point to index.js or a launcher beside index.js: ${path}`);
+}
+
+function findOnPath(bin: string): string | undefined {
+ try {
+ const out = execFileSync("which", [bin], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
+ return out.trim() || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function patchBundleMain(code: string): string {
+ const exact = 'var __webpack_exports__=__webpack_require__("./src/main.tsx")})();';
+ if (code.includes(exact)) {
+ return code.replace(
+ exact,
+ "globalThis.__wr=__webpack_require__; globalThis.__wm=__webpack_modules__;})();",
+ );
+ }
+ const fallback = new RegExp(
+ String.raw`var __webpack_exports__=__webpack_require__\(["']\./src/main\.tsx["']\)\}\)\(\);?\s*$`,
+ );
+ const patched = code.replace(
+ fallback,
+ "globalThis.__wr=__webpack_require__; globalThis.__wm=__webpack_modules__;})();",
+ );
+ if (patched !== code) return patched;
+ throw new Error("Cursor Agent bundle main entry pattern was not recognized");
+}
+
+function requireProtoClass(value: unknown, typeName: string): ProtoClass {
+ const candidate = value as Record<string, unknown> | undefined;
+ if (
+ candidate &&
+ typeof value === "function" &&
+ typeof candidate.fromBinary === "function" &&
+ typeof candidate.fromJson === "function"
+ ) {
+ return value as unknown as ProtoClass;
+ }
+ throw new Error(`Cursor protobuf class missing: ${typeName}`);
+}
diff --git a/src/providers/cursor/session.test.ts b/src/providers/cursor/session.test.ts
new file mode 100644
index 0000000..6956ad1
--- /dev/null
+++ b/src/providers/cursor/session.test.ts
@@ -0,0 +1,39 @@
+import { afterEach, describe, expect, it } from "bun:test";
+import {
+ clearCursorSessionsForTests,
+ cursorConversationForRequest,
+ recordCursorConversation,
+} from "./session.ts";
+
+afterEach(() => {
+ clearCursorSessionsForTests();
+});
+
+describe("Cursor session mapping", () => {
+ it("reuses a Cursor conversation for the same Claude session", () => {
+ const first = cursorConversationForRequest({ metadata: undefined }, "claude-session", 1000);
+ const second = cursorConversationForRequest({ metadata: undefined }, "claude-session", 2000);
+
+ expect(second).toBe(first);
+ });
+
+ it("uses explicit resume metadata and records it for continuation", () => {
+ const explicit = cursorConversationForRequest(
+ { metadata: { cursor_chat_id: "cursor-chat-1" } },
+ "claude-session",
+ 1000,
+ );
+ const continued = cursorConversationForRequest({ metadata: undefined }, "claude-session", 2000);
+
+ expect(explicit).toBe("cursor-chat-1");
+ expect(continued).toBe("cursor-chat-1");
+ });
+
+ it("records observed server session ids", () => {
+ recordCursorConversation("claude-session", "observed-cursor-session", 1000);
+
+ expect(cursorConversationForRequest({ metadata: undefined }, "claude-session", 2000)).toBe(
+ "observed-cursor-session",
+ );
+ });
+});
diff --git a/src/providers/cursor/session.ts b/src/providers/cursor/session.ts
new file mode 100644
index 0000000..20889ab
--- /dev/null
+++ b/src/providers/cursor/session.ts
@@ -0,0 +1,74 @@
+import type { AnthropicRequest } from "../../anthropic/schema.ts";
+
+interface CursorSessionState {
+ conversationId: string;
+ lastSeen: number;
+}
+
+const SESSION_IDLE_TTL_MS = 30 * 60 * 1000;
+const MAX_SESSIONS = 10_000;
+const sessions = new Map<string, CursorSessionState>();
+
+export function cursorConversationForRequest(
+ req: Pick<AnthropicRequest, "metadata">,
+ sessionId: string | undefined,
+ now = Date.now(),
+): string {
+ const explicit = explicitConversationId(req.metadata);
+ if (explicit) {
+ if (sessionId) recordCursorConversation(sessionId, explicit, now);
+ return explicit;
+ }
+
+ if (!sessionId) return crypto.randomUUID();
+
+ const existing = sessions.get(sessionId);
+ if (existing && now - existing.lastSeen <= SESSION_IDLE_TTL_MS) {
+ existing.lastSeen = now;
+ return existing.conversationId;
+ }
+
+ const conversationId = crypto.randomUUID();
+ recordCursorConversation(sessionId, conversationId, now);
+ return conversationId;
+}
+
+export function recordCursorConversation(
+ sessionId: string | undefined,
+ conversationId: string | undefined,
+ now = Date.now(),
+): void {
+ if (!sessionId || !conversationId) return;
+ sessions.set(sessionId, { conversationId, lastSeen: now });
+ evictOldestSessions();
+}
+
+export function clearCursorSessionsForTests(): void {
+ sessions.clear();
+}
+
+function explicitConversationId(metadata: unknown): string | undefined {
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return undefined;
+ const record = metadata as Record<string, unknown>;
+ for (const key of ["cursor_chat_id", "cursorChatId", "cursor_resume", "cursorResume"]) {
+ const value = record[key];
+ if (typeof value === "string" && value) return value;
+ }
+ const cursor = record.cursor;
+ if (cursor && typeof cursor === "object" && !Array.isArray(cursor)) {
+ const nested = cursor as Record<string, unknown>;
+ for (const key of ["chat_id", "chatId", "resume", "resumeId"]) {
+ const value = nested[key];
+ if (typeof value === "string" && value) return value;
+ }
+ }
+ return undefined;
+}
+
+function evictOldestSessions(): void {
+ while (sessions.size > MAX_SESSIONS) {
+ const oldest = sessions.keys().next().value;
+ if (!oldest) return;
+ sessions.delete(oldest);
+ }
+}
diff --git a/src/providers/cursor/translate/model.test.ts b/src/providers/cursor/translate/model.test.ts
new file mode 100644
index 0000000..60262b0
--- /dev/null
+++ b/src/providers/cursor/translate/model.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "bun:test";
+import { resolveCursorModel } from "./model.ts";
+
+describe("Cursor model selection", () => {
+ it("maps cursor aliases to composer fast", () => {
+ const selected = resolveCursorModel({ model: "cursor", metadata: undefined });
+
+ expect(selected.mode).toBe("AGENT_MODE_AGENT");
+ expect(selected.requestedModel).toEqual({
+ modelId: "composer-2.5",
+ parameters: [{ id: "fast", value: "true" }],
+ });
+ });
+
+ it("selects plan and ask modes from aliases", () => {
+ expect(resolveCursorModel({ model: "cursor-plan", metadata: undefined }).mode).toBe(
+ "AGENT_MODE_PLAN",
+ );
+ expect(resolveCursorModel({ model: "cursor-ask", metadata: undefined }).mode).toBe(
+ "AGENT_MODE_ASK",
+ );
+ });
+
+ it("supports raw cursor model prefix", () => {
+ const selected = resolveCursorModel({
+ model: "cursor:claude-sonnet-4-6-fast",
+ metadata: { cursor_mode: "plan" },
+ });
+
+ expect(selected.mode).toBe("AGENT_MODE_PLAN");
+ expect(selected.requestedModel).toEqual({
+ modelId: "claude-sonnet-4-6",
+ parameters: [{ id: "fast", value: "true" }],
+ });
+ });
+});
diff --git a/src/providers/cursor/translate/model.ts b/src/providers/cursor/translate/model.ts
new file mode 100644
index 0000000..5a02127
--- /dev/null
+++ b/src/providers/cursor/translate/model.ts
@@ -0,0 +1,70 @@
+import type { CursorAgentMode, CursorModelRequest } from "../client.ts";
+import type { AnthropicRequest } from "../../../anthropic/schema.ts";
+
+export interface CursorModelSelection {
+ requestedModel: CursorModelRequest;
+ mode: CursorAgentMode;
+}
+
+export const CURSOR_SUPPORTED_MODELS = new Set([
+ "cursor",
+ "cursor-agent",
+ "cursor-composer",
+ "cursor-composer-fast",
+ "cursor-plan",
+ "cursor-ask",
+ "composer-2.5",
+ "composer-2.5-fast",
+]);
+
+export function isCursorModel(model: string): boolean {
+ return CURSOR_SUPPORTED_MODELS.has(model) || model.startsWith("cursor:");
+}
+
+export function resolveCursorModel(req: Pick<AnthropicRequest, "model" | "metadata">): CursorModelSelection {
+ let mode = modeFromMetadata(req.metadata);
+ if (req.model === "cursor-plan") mode = "AGENT_MODE_PLAN";
+ else if (req.model === "cursor-ask") mode = "AGENT_MODE_ASK";
+ else mode ??= "AGENT_MODE_AGENT";
+
+ if (req.model.startsWith("cursor:")) {
+ return { requestedModel: parseRawCursorModel(req.model.slice("cursor:".length)), mode };
+ }
+
+ switch (req.model) {
+ case "cursor":
+ case "cursor-agent":
+ case "cursor-composer":
+ case "cursor-composer-fast":
+ case "cursor-plan":
+ case "cursor-ask":
+ case "composer-2.5-fast":
+ return {
+ requestedModel: { modelId: "composer-2.5", parameters: [{ id: "fast", value: "true" }] },
+ mode,
+ };
+ case "composer-2.5":
+ return { requestedModel: { modelId: "composer-2.5" }, mode };
+ default:
+ return { requestedModel: { modelId: req.model }, mode };
+ }
+}
+
+function parseRawCursorModel(raw: string): CursorModelRequest {
+ if (raw.endsWith("-fast")) {
+ return {
+ modelId: raw.slice(0, -"-fast".length),
+ parameters: [{ id: "fast", value: "true" }],
+ };
+ }
+ return { modelId: raw };
+}
+
+function modeFromMetadata(metadata: unknown): CursorAgentMode | undefined {
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return undefined;
+ const value = (metadata as Record<string, unknown>).cursor_mode ?? (metadata as Record<string, unknown>).cursorMode;
+ if (value === "plan" || value === "AGENT_MODE_PLAN") return "AGENT_MODE_PLAN";
+ if (value === "ask" || value === "AGENT_MODE_ASK") return "AGENT_MODE_ASK";
+ if (value === "agent" || value === "AGENT_MODE_AGENT") return "AGENT_MODE_AGENT";
+ return undefined;
+}
diff --git a/src/providers/cursor/translate/request.test.ts b/src/providers/cursor/translate/request.test.ts
new file mode 100644
index 0000000..895c632
--- /dev/null
+++ b/src/providers/cursor/translate/request.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from "bun:test";
+import { renderCursorPrompt } from "./request.ts";
+import type { AnthropicRequest } from "../../../anthropic/schema.ts";
+
+describe("Cursor prompt rendering", () => {
+ it("renders system, messages, tools, and tool results deterministically", () => {
+ const req: AnthropicRequest = {
+ model: "cursor",
+ system: "Follow instructions.",
+ messages: [
+ { role: "user", content: "Question" },
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Calling tool" },
+ { type: "tool_use", id: "toolu_1", name: "Read", input: { file: "package.json" } },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "toolu_1",
+ content: [{ type: "text", text: "package content" }],
+ },
+ ],
+ },
+ ],
+ tools: [{ name: "Read", input_schema: { type: "object" } }],
+ };
+
+ const prompt = renderCursorPrompt(req);
+
+ expect(prompt).toContain("<system>\nFollow instructions.\n</system>");
+ expect(prompt).toContain("<user>\nQuestion\n</user>");
+ expect(prompt).toContain('<tool_use id="toolu_1" name="Read">');
+ expect(prompt).toContain('<tool_result tool_use_id="toolu_1">');
+ expect(prompt).toContain('"name":"Read"');
+ });
+});
diff --git a/src/providers/cursor/translate/request.ts b/src/providers/cursor/translate/request.ts
new file mode 100644
index 0000000..4cd8055
--- /dev/null
+++ b/src/providers/cursor/translate/request.ts
@@ -0,0 +1,81 @@
+import type {
+ AnthropicContentBlock,
+ AnthropicMessage,
+ AnthropicRequest,
+ AnthropicTextBlock,
+ AnthropicToolResultContentBlock,
+} from "../../../anthropic/schema.ts";
+
+export function renderCursorPrompt(req: AnthropicRequest): string {
+ const sections: string[] = [];
+ const system = renderSystem(req.system);
+ if (system) sections.push(`<system>\n${system}\n</system>`);
+
+ for (const message of req.messages) {
+ const content = renderContent(message);
+ if (content) sections.push(`<${message.role}>\n${content}\n</${message.role}>`);
+ }
+
+ if (req.tools?.length) {
+ sections.push(
+ `<tools>\n${req.tools
+ .map((tool) =>
+ JSON.stringify({
+ name: tool.name,
+ description: tool.description,
+ input_schema: tool.input_schema,
+ }),
+ )
+ .join("\n")}\n</tools>`,
+ );
+ }
+
+ return sections.join("\n\n");
+}
+
+function renderSystem(system: AnthropicRequest["system"]): string | undefined {
+ if (!system) return undefined;
+ const blocks: AnthropicTextBlock[] =
+ typeof system === "string" ? [{ type: "text", text: system }] : system;
+ const text = blocks
+ .filter((block) => block.type === "text" && typeof block.text === "string")
+ .map((block) => block.text)
+ .filter((line) => !line.startsWith("x-anthropic-billing-header:"))
+ .join("\n\n");
+ return text || undefined;
+}
+
+function renderContent(message: AnthropicMessage): string {
+ const blocks: AnthropicContentBlock[] =
+ typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
+ return blocks.map(renderBlock).filter(Boolean).join("\n\n");
+}
+
+function renderBlock(block: AnthropicContentBlock): string {
+ switch (block.type) {
+ case "text":
+ return block.text;
+ case "thinking":
+ return `<thinking>\n${block.thinking}\n</thinking>`;
+ case "image":
+ if (block.source.type === "url") return `[image: ${block.source.url}]`;
+ return `[image: ${block.source.media_type}, ${block.source.data.length} base64 chars]`;
+ case "tool_use":
+ return `<tool_use id="${block.id}" name="${block.name}">\n${JSON.stringify(block.input ?? {})}\n</tool_use>`;
+ case "tool_result":
+ return `<tool_result tool_use_id="${block.tool_use_id}"${block.is_error ? " is_error=\"true\"" : ""}>\n${renderToolResult(block.content)}\n</tool_result>`;
+ }
+}
+
+function renderToolResult(content: AnthropicToolResultContentBlock[] | string): string {
+ if (typeof content === "string") return content;
+ return content.map(renderToolResultBlock).filter(Boolean).join("\n\n");
+}
+
+function renderToolResultBlock(block: AnthropicToolResultContentBlock): string {
+ if (block.type === "text" || block.type === "image" || block.type === "tool_use" || block.type === "tool_result" || block.type === "thinking") {
+ return renderBlock(block as AnthropicContentBlock);
+ }
+ const type = typeof block.type === "string" ? block.type : "unknown";
+ return `[unsupported tool result block: ${type}]`;
+}
diff --git a/src/providers/cursor/translate/response.test.ts b/src/providers/cursor/translate/response.test.ts
new file mode 100644
index 0000000..a0aaf3d
--- /dev/null
+++ b/src/providers/cursor/translate/response.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it } from "bun:test";
+import { gzipSync } from "node:zlib";
+import { parseSseStream } from "../../../sse.ts";
+import type { CursorProto, ProtoClass, ProtoMessage } from "../proto-loader.ts";
+import { decodeCursorStream, encodeConnectFrame } from "../client.ts";
+import {
+ accumulateCursorResponse,
+ cursorUsageToAnthropic,
+ translateCursorStream,
+} from "./response.ts";
+import { createLogger } from "../../../log.ts";
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+const fakeProto: CursorProto = {
+ AgentServerMessage: jsonProtoClass(),
+ AgentClientMessage: jsonProtoClass(),
+};
+
+describe("Cursor response translation", () => {
+ it("maps usage tokens including cache reads and writes", () => {
+ expect(
+ cursorUsageToAnthropic({
+ inputTokens: "100",
+ outputTokens: "7",
+ cacheReadTokens: "20",
+ cacheWriteTokens: "3",
+ }),
+ ).toEqual({
+ input_tokens: 77,
+ output_tokens: 7,
+ cache_creation_input_tokens: 3,
+ cache_read_input_tokens: 20,
+ });
+ });
+
+ it("decodes Connect-framed Cursor messages including gzip and end frames", async () => {
+ const stream = streamFromChunks([
+ frame({ interactionUpdate: { textDelta: { text: "hi" } } }),
+ encodeConnectFrame(gzipSync(jsonBytes({ interactionUpdate: { textDelta: { text: "!" } } })), 1),
+ encodeConnectFrame(jsonBytes({}), 2),
+ ]);
+
+ const events = [];
+ for await (const event of decodeCursorStream(stream, fakeProto)) events.push(event);
+
+ expect(events).toEqual([
+ { type: "text_delta", text: "hi" },
+ { type: "text_delta", text: "!" },
+ { type: "end" },
+ ]);
+ });
+
+ it("accumulates non-streaming thinking, text, usage, and session id", async () => {
+ let observedSession: string | undefined;
+ const result = await accumulateCursorResponse(
+ streamFromChunks([
+ frame({ execServerMessage: { requestContextArgs: { notesSessionId: "cursor-session" } } }),
+ frame({ interactionUpdate: { thinkingDelta: { text: "think" } } }),
+ frame({ interactionUpdate: { textDelta: { text: "hello" } } }),
+ frame({ interactionUpdate: { turnEnded: { inputTokens: "10", outputTokens: "2" } } }),
+ encodeConnectFrame(jsonBytes({}), 2),
+ ]),
+ {
+ messageId: "msg_1",
+ model: "cursor-plan",
+ log: createLogger("cursor.response.test"),
+ proto: fakeProto,
+ onSession: (session) => {
+ observedSession = session;
+ },
+ },
+ );
+
+ expect(observedSession).toBe("cursor-session");
+ expect(result.response.content).toEqual([
+ { type: "thinking", thinking: "think", signature: "" },
+ { type: "text", text: "hello" },
+ ]);
+ expect(result.response.usage.output_tokens).toBe(2);
+ });
+
+ it("emits valid Anthropic SSE for thinking and text deltas", async () => {
+ const downstream = translateCursorStream(
+ streamFromChunks([
+ frame({ interactionUpdate: { thinkingDelta: { text: "plan" } } }),
+ frame({ interactionUpdate: { textDelta: { text: "done" } } }),
+ frame({ interactionUpdate: { turnEnded: { inputTokens: "8", outputTokens: "3" } } }),
+ encodeConnectFrame(jsonBytes({}), 2),
+ ]),
+ {
+ messageId: "msg_2",
+ model: "cursor-plan",
+ log: createLogger("cursor.response.test"),
+ proto: fakeProto,
+ },
+ );
+
+ const events = [];
+ for await (const event of parseSseStream(downstream)) {
+ events.push({ event: event.event, data: JSON.parse(event.data) });
+ }
+
+ expect(events.map((event) => event.event)).toEqual([
+ "message_start",
+ "ping",
+ "content_block_start",
+ "content_block_delta",
+ "content_block_stop",
+ "content_block_start",
+ "content_block_delta",
+ "content_block_stop",
+ "message_delta",
+ "message_stop",
+ ]);
+ expect(events[2]?.data.content_block.type).toBe("thinking");
+ expect(events[3]?.data.delta).toEqual({ type: "thinking_delta", thinking: "plan" });
+ expect(events[6]?.data.delta).toEqual({ type: "text_delta", text: "done" });
+ expect(events[8]?.data.usage.output_tokens).toBe(3);
+ });
+});
+
+function jsonProtoClass(): ProtoClass {
+ return {
+ fromBinary(bytes: Uint8Array): ProtoMessage {
+ return messageFromJson(JSON.parse(decoder.decode(bytes)));
+ },
+ fromJson(json: unknown): ProtoMessage {
+ return messageFromJson(json);
+ },
+ };
+}
+
+function messageFromJson(json: unknown): ProtoMessage {
+ return {
+ toBinary(): Uint8Array {
+ return jsonBytes(json);
+ },
+ toJson(): unknown {
+ return json;
+ },
+ };
+}
+
+function frame(json: unknown): Uint8Array {
+ return encodeConnectFrame(jsonBytes(json));
+}
+
+function jsonBytes(json: unknown): Uint8Array {
+ return encoder.encode(JSON.stringify(json));
+}
+
+function streamFromChunks(chunks: Uint8Array[]): ReadableStream<Uint8Array> {
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const chunk of chunks) controller.enqueue(chunk);
+ controller.close();
+ },
+ });
+}
diff --git a/src/providers/cursor/translate/response.ts b/src/providers/cursor/translate/response.ts
new file mode 100644
index 0000000..fc51e33
--- /dev/null
+++ b/src/providers/cursor/translate/response.ts
@@ -0,0 +1,257 @@
+import { encodeSseEvent } from "../../../sse.ts";
+import type { Logger } from "../../../log.ts";
+import type { TrafficCapture } from "../../types.ts";
+import { decodeCursorStream, type CursorStreamEvent, type CursorUsage } from "../client.ts";
+import type { CursorProto } from "../proto-loader.ts";
+
+export interface AnthropicCursorResponse {
+ id: string;
+ type: "message";
+ role: "assistant";
+ model: string;
+ content: Array<{ type: "thinking"; thinking: string; signature: string } | { type: "text"; text: string }>;
+ stop_reason: "end_turn" | null;
+ stop_sequence: null;
+ usage: AnthropicUsage;
+}
+
+export interface AnthropicUsage {
+ input_tokens: number;
+ output_tokens: number;
+ cache_creation_input_tokens: number;
+ cache_read_input_tokens: number;
+}
+
+export function cursorUsageToAnthropic(usage?: CursorUsage): AnthropicUsage {
+ const input = toNumber(usage?.inputTokens);
+ const output = toNumber(usage?.outputTokens);
+ const cacheRead = toNumber(usage?.cacheReadTokens);
+ const cacheWrite = toNumber(usage?.cacheWriteTokens);
+ return {
+ input_tokens: Math.max(0, input - cacheRead - cacheWrite),
+ output_tokens: output,
+ cache_creation_input_tokens: cacheWrite,
+ cache_read_input_tokens: cacheRead,
+ };
+}
+
+export async function accumulateCursorResponse(
+ upstream: ReadableStream<Uint8Array>,
+ opts: {
+ messageId: string;
+ model: string;
+ log: Logger;
+ traffic?: TrafficCapture;
+ proto?: CursorProto;
+ onSession?: (sessionId: string) => void;
+ },
+): Promise<{ response: AnthropicCursorResponse; cursorSessionId?: string }> {
+ let text = "";
+ let thinking = "";
+ let usage: CursorUsage | undefined;
+ let cursorSessionId: string | undefined;
+
+ for await (const event of decodeCursorStream(upstream, opts.proto)) {
+ opts.traffic?.writeJsonEvent("040-cursor-event", event);
+ switch (event.type) {
+ case "session":
+ cursorSessionId = event.sessionId;
+ opts.onSession?.(event.sessionId);
+ break;
+ case "thinking_delta":
+ thinking += event.text;
+ break;
+ case "text_delta":
+ text += event.text;
+ break;
+ case "usage":
+ usage = event.usage;
+ break;
+ case "end":
+ break;
+ }
+ }
+
+ const content: AnthropicCursorResponse["content"] = [];
+ if (thinking) content.push({ type: "thinking", thinking, signature: "" });
+ if (text) content.push({ type: "text", text });
+ opts.log.debug("cursor accumulate finish", {
+ textChars: text.length,
+ thinkingChars: thinking.length,
+ cursorSessionId,
+ usage,
+ });
+
+ return {
+ cursorSessionId,
+ response: {
+ id: opts.messageId,
+ type: "message",
+ role: "assistant",
+ model: opts.model,
+ content,
+ stop_reason: "end_turn",
+ stop_sequence: null,
+ usage: cursorUsageToAnthropic(usage),
+ },
+ };
+}
+
+export function translateCursorStream(
+ upstream: ReadableStream<Uint8Array>,
+ opts: {
+ messageId: string;
+ model: string;
+ log: Logger;
+ signal?: AbortSignal;
+ traffic?: TrafficCapture;
+ proto?: CursorProto;
+ onSession?: (sessionId: string) => void;
+ },
+): ReadableStream<Uint8Array> {
+ const encoder = new TextEncoder();
+ return new ReadableStream<Uint8Array>({
+ async start(controller) {
+ let closed = false;
+ let started = false;
+ let thinkingOpen = false;
+ let textOpen = false;
+ let nextIndex = 0;
+ let thinkingIndex = -1;
+ let textIndex = -1;
+
+ const emit = (event: string, data: unknown) => {
+ if (closed || opts.signal?.aborted || controller.desiredSize === null) return false;
+ opts.traffic?.writeJsonEvent("050-downstream-event", { event, data });
+ controller.enqueue(encoder.encode(encodeSseEvent(event, data)));
+ return true;
+ };
+
+ const ensureStart = () => {
+ if (started) return;
+ started = true;
+ emit("message_start", {
+ type: "message_start",
+ message: {
+ id: opts.messageId,
+ type: "message",
+ role: "assistant",
+ model: opts.model,
+ content: [],
+ stop_reason: null,
+ stop_sequence: null,
+ usage: {
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ },
+ },
+ });
+ emit("ping", { type: "ping" });
+ };
+
+ const openThinking = () => {
+ if (thinkingOpen) return;
+ ensureStart();
+ thinkingOpen = true;
+ thinkingIndex = nextIndex++;
+ emit("content_block_start", {
+ type: "content_block_start",
+ index: thinkingIndex,
+ content_block: { type: "thinking", thinking: "", signature: "" },
+ });
+ };
+
+ const openText = () => {
+ if (textOpen) return;
+ ensureStart();
+ textOpen = true;
+ textIndex = nextIndex++;
+ emit("content_block_start", {
+ type: "content_block_start",
+ index: textIndex,
+ content_block: { type: "text", text: "" },
+ });
+ };
+
+ const closeOpenBlocks = () => {
+ if (thinkingOpen) {
+ emit("content_block_stop", { type: "content_block_stop", index: thinkingIndex });
+ thinkingOpen = false;
+ }
+ if (textOpen) {
+ emit("content_block_stop", { type: "content_block_stop", index: textIndex });
+ textOpen = false;
+ }
+ };
+
+ try {
+ let finalUsage: CursorUsage | undefined;
+ for await (const event of decodeCursorStream(upstream, opts.proto)) {
+ opts.traffic?.writeJsonEvent("040-cursor-event", event);
+ if (opts.signal?.aborted) return;
+ switch (event.type) {
+ case "session":
+ opts.onSession?.(event.sessionId);
+ break;
+ case "thinking_delta":
+ openThinking();
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index: thinkingIndex,
+ delta: { type: "thinking_delta", thinking: event.text },
+ });
+ break;
+ case "text_delta":
+ if (thinkingOpen) {
+ emit("content_block_stop", { type: "content_block_stop", index: thinkingIndex });
+ thinkingOpen = false;
+ }
+ openText();
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index: textIndex,
+ delta: { type: "text_delta", text: event.text },
+ });
+ break;
+ case "usage":
+ finalUsage = event.usage;
+ break;
+ case "end":
+ break;
+ }
+ }
+ ensureStart();
+ closeOpenBlocks();
+ emit("message_delta", {
+ type: "message_delta",
+ delta: { stop_reason: "end_turn", stop_sequence: null },
+ usage: cursorUsageToAnthropic(finalUsage),
+ });
+ emit("message_stop", { type: "message_stop" });
+ } catch (err) {
+ opts.log.warn("cursor stream error", { err: String(err) });
+ ensureStart();
+ closeOpenBlocks();
+ emit("error", {
+ type: "error",
+ error: { type: "api_error", message: String(err) },
+ });
+ } finally {
+ closed = true;
+ try {
+ controller.close();
+ } catch {
+ // Consumer cancellation can close the controller first.
+ }
+ }
+ },
+ });
+}
+
+function toNumber(value: string | undefined): number {
+ if (!value) return 0;
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : 0;
+}
diff --git a/src/providers/registry.test.ts b/src/providers/registry.test.ts
index 651aeba..9beedd4 100644
--- a/src/providers/registry.test.ts
+++ b/src/providers/registry.test.ts
@@ -89,5 +89,18 @@ describe("provider routing", () => {
expect(providerForModel("kimi-for-coding")?.name).toBe("kimi");
expect(providerForModel("gpt-5.4-fast")?.name).toBe("codex");
+ expect(providerForModel("cursor")?.name).toBe("cursor");
+ expect(providerForModel("cursor-plan")?.name).toBe("cursor");
+ expect(providerForModel("cursor:claude-sonnet-4-6")?.name).toBe("cursor");
+ });
+
+ it("lists Cursor aliases in supported models", () => {
+ const cursorModels = allSupportedModels()
+ .filter((entry) => entry.provider === "cursor")
+ .map((entry) => entry.model);
+
+ expect(cursorModels).toContain("cursor");
+ expect(cursorModels).toContain("cursor-plan");
+ expect(cursorModels).toContain("composer-2.5-fast");
});
});
diff --git a/src/providers/registry.ts b/src/providers/registry.ts
index f3e4aef..d4b0a98 100644
--- a/src/providers/registry.ts
+++ b/src/providers/registry.ts
@@ -2,6 +2,8 @@ import { aliasProvider, type AliasProvider } from "../config.ts";
import type { Provider } from "./types.ts";
import { codexProvider } from "./codex/index.ts";
import { kimiProvider } from "./kimi/index.ts";
+import { cursorProvider } from "./cursor/index.ts";
+import { isCursorModel } from "./cursor/translate/model.ts";
export const ANTHROPIC_STYLE_ALIASES = new Set([
"haiku",
@@ -16,6 +18,7 @@ export const ANTHROPIC_STYLE_ALIASES = new Set([
const PROVIDERS: Record<string, Provider> = {
codex: codexProvider,
kimi: kimiProvider,
+ cursor: cursorProvider,
};
export function getProvider(name: string): Provider {
@@ -40,6 +43,7 @@ export function providerForModel(
): Provider | undefined {
if (ANTHROPIC_STYLE_ALIASES.has(model))
return getProvider(aliasProviderOverride ?? aliasProvider());
+ if (isCursorModel(model)) return cursorProvider;
for (const p of allProviders()) {
if (p.supportedModels.has(model)) return p;
}