No description
  • TypeScript 99.4%
  • JavaScript 0.6%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Brandon Verkamp e794b22b75
Some checks failed
CI / Check (Node) (push) Has been cancelled
Correct name and note about the keepalive event/pi-provider-manager pairing
2026-11-18 16:54:02 -07:00
.github ci: enable Corepack before Yarn cache in GitHub Actions 2026-09-20 19:39:27 +05:30
docs release: v1.4.31 native Cursor tools on the open stream 2026-09-04 19:43:23 +05:30
proto fix(proto): model checkpoint field 46 so it stops flagging wire drift every turn 2026-11-18 13:41:44 -07:00
scripts release: v1.4.38 fix wire drift, 45s stalls, auto routing, and parameter rejection 2026-09-23 12:30:30 +05:30
src Emit keepalive when Cursor reports output tokens without text 2026-11-18 14:20:04 -07:00
tests Emit keepalive when Cursor reports output tokens without text 2026-11-18 14:20:04 -07:00
.gitignore release: v1.4.36 switch toolchain from Bun to Node.js and Yarn 4 2026-09-20 19:38:29 +05:30
.prettierignore release: v1.4.29 drop Node.js — Cursor transport runs in-process under Bun 2026-08-30 01:43:47 +05:30
.prettierrc.json feat: initial release v0.1.0 2026-07-23 01:47:51 +05:30
.yarnrc.yml release: v1.4.36 switch toolchain from Bun to Node.js and Yarn 4 2026-09-20 19:38:29 +05:30
AGENTS.md fix(src,tests): give clashing Pi MCP tools one name on every path 2026-10-08 03:48:44 +09:00
buf.gen.yaml feat: Add Cursor stream infrastructure with server message processing 2026-07-24 19:29:07 +05:30
CHANGELOG.md fix(context): keep an extension-triggered turn's wrapped message as the task instead of failing with no user message 2026-11-18 13:42:04 -07:00
CLAUDE.md release: v1.4.36 switch toolchain from Bun to Node.js and Yarn 4 2026-09-20 19:38:29 +05:30
CODE_OF_CONDUCT.md feat: initial release v0.1.0 2026-07-23 01:47:51 +05:30
CONTRIBUTING.md release: v1.4.36 switch toolchain from Bun to Node.js and Yarn 4 2026-09-20 19:38:29 +05:30
eslint.config.js release: v1.4.36 switch toolchain from Bun to Node.js and Yarn 4 2026-09-20 19:38:29 +05:30
LICENSE feat: initial release v0.1.0 2026-07-23 01:47:51 +05:30
package.json custom: load extension from src for git installs 2026-11-18 13:38:35 -07:00
README.md Correct name and note about the keepalive event/pi-provider-manager pairing 2026-11-18 16:54:02 -07:00
SECURITY.md fix: recover idle tool continuations and stop silent credential reuse 2026-08-19 17:08:22 +05:30
tsconfig.json release: v1.4.36 switch toolchain from Bun to Node.js and Yarn 4 2026-09-20 19:38:29 +05:30
tsup.config.ts release: v1.4.36 switch toolchain from Bun to Node.js and Yarn 4 2026-09-20 19:38:29 +05:30
vitest.config.ts ci: calibrate branch coverage threshold in vitest.config.ts 2026-09-23 12:35:35 +05:30
yarn.lock release: v1.4.36 switch toolchain from Bun to Node.js and Yarn 4 2026-09-20 19:38:29 +05:30

@rahularya01/pi-cursor

npm version license Sponsor

Use your Cursor subscription's models — Composer, Claude, GPT, Grok — inside the Pi Coding Agent. pi-cursor plugs in a cursor model provider that talks to Cursor's own backend directly (native Connect/protobuf streaming over HTTP/2), so there's no separate API key to buy and no Cursor CLI process running in the background for every chat turn. If you're already logged into Cursor's app or CLI, it just works — no setup beyond installing the package.

Unofficial integration. This project is not affiliated with or endorsed by Cursor / Anysphere. It uses reverse-engineered wire protocol details shared by community clients (see Attributions). Use it only with an account you are authorized to access, and review its source before granting OAuth permissions. Cursor may change wire protocol endpoints or formats at any time.

This fork

This tree is JadElClemens's fork of the archived upstream Rahularya01/pi-cursor at ef3cafb (v1.4.39). The package name is unchanged. Pi loads src/index.ts.

Cherry-picked from cartwmic/pi-cursor, skipping that fork's CallDynamicTool prompt text:

  • an extension turn whose only text is <injected-context> stays the user message
  • a stream that ends without turnEnded is transport loss, and an abort releases the tool-result bridge
  • reported cost is 0 unless PI_CURSOR_API_COST_ESTIMATE=1, with character-based token estimates
  • quota, rate-limit, and context-overflow errors are classified separately
  • checkpoint fields 38, 39, and 46, and interaction-update field 27, are modeled so they stop logging wire drift

Ported from Vzlentin/pi-cursor by hand, on top of v1.4.39 rather than that fork's v1.4.38 tree:

  • Cursor Read, Shell, Write, StrReplace, ls, and grep execs become Pi tool calls (read, bash, write or edit, ls). PI_CURSOR_NATIVE_TOOLS=native keeps the in-process handlers.
  • a finished shell exec sends ExecClientControlMessage.streamClose
  • the blob store is bounded by bytes only
  • a bridge waiting on tool results does not keep a headless process alive

The prompt combines those two designs. Local file and shell work uses the native tools above. Every other Pi tool is called with CallDynamicTool on namespace pi, with its schema printed in the rules, and without a GetDynamicTools lookup. History is not rewritten into CallDynamicTool calls. That recipe is the part taken from cartwmic and from GyroZepelix/pi-cursor. GyroZepelix's DeepSeek reasoning replay is not included.

Written here, not taken from those forks:

  • a tokenDelta that reports tokens, and no text yet, emits a keepalive stream event for interpretation by other plugins. For example, the pi-provider-manager plugin interprets this event to mean that the turn/active connection is still healthy even if not receiving tokens so that it can reset the mid-turn idle timeout.

Contents

Requirements

Pi Coding Agent / Pi AI version 0.80.0 or later
Node.js version 22 or later — the only supported runtime
A Cursor account with model access — signed in via the Cursor app, Cursor CLI, or browser login below

Install

pi install npm:@rahularya01/pi-cursor

Then restart Pi (or run /reload) so the new provider is picked up.

Other install options

Install the latest code straight from GitHub instead of npm:

pi install git:github.com/Rahularya01/pi-cursor

To update later:

pi update npm:@rahularya01/pi-cursor

Quick start

  1. Sign in. If Cursor's desktop app or CLI (cursor / agent) is already logged in on this machine, pi-cursor detects it automatically — skip to step 2. Otherwise, run:

    /login cursor
    

    This opens a browser tab to sign in with your Cursor account.

  2. Pick a model:

    /model cursor/composer-2
    
  3. Start chatting. If anything looks off, run /cursor.doctor — it prints which credential source is active, the current endpoint, and the last error, and is the first thing to check before filing an issue.

Authentication and resolution cascade

pi-cursor automatically resolves credentials using a 4-tier cascade:

1. CURSOR_ACCESS_TOKEN environment variable
2. Pi OAuth credentials store (~/.pi/agent/auth.json via /login cursor)
3. Cursor CLI credentials in macOS Keychain (cursor-access-token / cursor-refresh-token)
4. Cursor IDE local state DB (globalStorage/state.vscdb on macOS, Windows, Linux, or WSL)

/login cursor is preferred over Keychain/IDE harvest so an explicit Pi login is not silently overridden by another Cursor app account on the machine.

Automatic CLI & IDE login detection

If you are logged into the Cursor desktop app or Cursor CLI (cursor / agent), pi-cursor automatically extracts your session credentials so you can start chatting immediately without manual browser login.

On WSL (Windows Subsystem for Linux), pi-cursor reuses the current Windows user's Cursor IDE login (USERPROFILE / USERNAME → /mnt/c/Users/<you>/AppData/...). It does not scan other Windows profiles.

To opt out of Keychain / IDE / WSL credential reuse (OAuth or CURSOR_ACCESS_TOKEN only):

export PI_CURSOR_SYSTEM_CREDENTIALS=0

When no local credentials exist, running /login cursor initiates browser sign-in:

  1. /login cursor opens https://cursor.com/loginDeepControl?...
  2. Pi polls https://api2.cursor.sh/auth/poll until authentication completes.
  3. Access and refresh tokens are stored in Pi's auth store (~/.pi/agent/auth.json).
  4. Tokens are automatically refreshed via https://api2.cursor.sh/auth/exchange_user_api_key.

Use /cursor.doctor to inspect which source is active (tokenSource=cli_keychain, tokenSource=ide_vscdb, tokenSource=pi_oauth, tokenSource=env).

Commands

Command Description
/login cursor Sign in to Cursor via browser PKCE and refresh the live model catalog.
/model cursor/<id> Choose a registered Cursor model.
/cursor.models List active runtime models, context windows, and effort capabilities.
/cursor.models all Include tab/chat internal model variants normally hidden from the picker.
/cursor.usage Display visual TUI usage dashboard (included/auto/API quota bars, reset dates, on-demand spend).
/cursor.doctor Show sanitized provider diagnostics, active token source, endpoint, and last error.

Models and reasoning effort routing

pi-cursor discovers live account models via GetUsableModels and parameterized metadata. Reasoning effort levels (off, minimal, low, medium, high, xhigh, max) are mapped directly to Cursor's runtime model variants or reasoning parameters.

Public model ID Context Thinking Description / Routing
cursor/composer-2 200,000 Yes Cursor's agentic model with fast reasoning effort options.
cursor/composer-1.5 200,000 Yes Fast agent model optimized for code edit turns.
cursor/claude-sonnet-5 200,000 Yes Anthropic Claude Sonnet via Cursor infrastructure.
cursor/gpt-5.5 200,000 Yes OpenAI flagship model with parameterized reasoning levels.
cursor/grok-4.5 200,000 Yes xAI Grok model via Cursor infrastructure.

To restrict which models Pi displays, configure ~/.pi/agent/settings.json:

{
  "enabledModels": ["cursor/composer-2", "cursor/claude-sonnet-5", "cursor/gpt-5.5"]
}

Usage quota and visual TUI dashboard

Running /cursor.usage displays a formatted terminal interface showing your current billing cycle, progress bars for included plan quota, auto/API usage, reset dates, and on-demand spend:

Usage • Pro                                           Resets 5 Aug
Monthly plan and on-demand usage

Category        Current          Usage
Included        13% used         ███░░░░░░░░░░░░░░░░░
  Auto          12% used         ███░░░░░░░░░░░░░░░░░
  API           14% used         ███░░░░░░░░░░░░░░░░░
On-Demand       Disabled
------------------------------------------------------------
On-demand usage is off

View in dashboard: cursor.com/dashboard?tab=usage

Usage statistics are fetched directly from Cursor's native Connect period usage endpoint (POST https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage) using your active access token, with optional fallback to CURSOR_USAGE_SESSION_TOKEN.

Architecture & Wire Protocol

The rest of this README is reference material for troubleshooting, tuning, and contributing — nothing here is required for day-to-day use.

Pi Coding Agent  →  streamSimple (cursor-native)
                      → h2-session.ts (in-process HTTP/2 client)
                      → agent.v1.AgentService/Run (Connect + Protobuf over HTTP/2)
  • Transport: Native Connect/protobuf streaming over HTTP/2, in-process via h2-session.ts — no subprocess.
  • Infrastructure Context Normalization: Side-channel user messages (context-mode routing, post-compaction <session_state>, and explicit [pi-lens automated … not a user request] notices) are safely normalized into the system prompt so Cursor models stay focused on your primary task.
  • Local operations through Pi: File reads, searches, directory listings, writes, deletions, and shell commands run through the tools registered in Pi. Native Cursor local calls are rejected with guidance to call a Pi MCP tool using its own schema; this may require an extra model response. There is no built-in local fallback when Pi lacks a suitable tool. Eight rejected local requests without a Pi tool result stop the run at a receive-chunk boundary, unless Pi calls are already awaiting results. Pending Pi calls take priority; sending their results resets the counter. Web search and fetch are unchanged. This tool policy is sent even when PI_CURSOR_PROMPT_HISTORY=0.
  • Context-Efficient Tools: MCP schemas are compacted without changing callable constraints, and exact conversational-only turns (hi, thanks, etc.) omit tools entirely. Actionable prompts always retain tools.
  • Cross-Platform: Tested and fully compatible with macOS, Linux, Windows, and WSL.

Configuration

Everything below is optional — pi-cursor works out of the box. These environment variables exist for tuning timeouts, debugging, and edge-case overrides.

Full environment variable reference
Variable Purpose
PI_CURSOR_AGENT_URL / CURSOR_AGENT_URL Override agent base URL (default: https://agentn.us.api5.cursor.sh).
CURSOR_ACCESS_TOKEN Static access token override.
PI_CURSOR_CLIENT_VERSION Pin x-cursor-client-version header sent by the HTTP/2 bridge.
PI_PROXY_CURSOR / PI_PROXY / HTTPS_PROXY HTTP CONNECT proxy for Cursor HTTP/2. PI_PROXY_CURSOR wins, then PI_PROXY, then HTTPS_PROXY.
PI_CURSOR_SYSTEM_CREDENTIALS 0/false to disable Keychain/IDE credential reuse (default: allow).
PI_CURSOR_RAW_MODELS Disable effort-suffix model collapse.
PI_CURSOR_PROVIDER_DEBUG Enable verbose JSONL debug logging.
PI_CURSOR_LIFECYCLE_LOG Always-on compact lifecycle log path (default: $TMPDIR/pi-cursor-lifecycle.jsonl).
CURSOR_USAGE_SESSION_TOKEN Optional WorkosCursorSessionToken fallback cookie for /cursor.usage.
PI_OFFLINE Skip live model discovery entirely; always use the bundled fallback catalog.
PI_CURSOR_CACHE_DIR Where the model catalog and refresh back-off are cached (default: $XDG_CACHE_HOME/pi-cursor or ~/.cache/pi-cursor). Delete it to force a full rediscovery.
PI_CURSOR_UNARY_BRIDGE 1 forces unary RPCs (model discovery) through the general-purpose bridge transport instead of the dedicated one-shot in-process HTTP/2 client. Diagnostic escape hatch.
PI_CURSOR_STREAM_IDLE_TIMEOUT_MS Silence safety net: ms with no upstream work before recover/retry/error. Default 180000 (3 min); 0 disables (turns run unbounded). Text/thinking/token deltas, tool-call events, and answered execs/queries reset it; heartbeats only prove the socket and do not hide an unanswered exec. It is paused during tool execution. On timeout, recovery continues from checkpoint even after partial output.
PI_CURSOR_RESUME_IDLE_TIMEOUT_MS Same silence safety net after tool-result resume. Default 180000 (3 min); 0 disables.
PI_CURSOR_STREAM_IDLE_MAX_RETRIES Auto-recovery attempts after silence/transport loss. Blind restart is skipped once text/thinking streamed unless a checkpoint is available for continuation. Default 5; 0 disables.
PI_CURSOR_ACTIVE_BRIDGE_TTL_MS How long a mid-tool bridge stays parked waiting for tool results (default: 1 hour).
PI_CURSOR_H2_CONNECT_TIMEOUT_MS h2-bridge initial connect kill (default: 30000; 0 disables).
PI_CURSOR_H2_IDLE_TIMEOUT_MS h2-bridge activity idle kill. Default 0 (disabled). Parent heartbeats reset it when enabled.
PI_CURSOR_SLIM_TOOLS Compact Cursor MCP tool definitions: concise function purpose, no annotation-only parameter prose, full callable schema constraints preserved. Default on; set 0/false for verbatim schemas.
PI_CURSOR_MIDPAUSE_REBUILD_MAX_AGE_MS Max age of mid-pause metadata used for full-history rebuild (default: 15 min).
PI_CURSOR_CHARS_PER_TOKEN Characters per token for the context estimate Pi uses for its meter and auto-compaction. Cursor's usedTokens is chars / ~2.44, about 1.4-1.8x the real token count, so the provider divides the characters Cursor counted by this instead. Default 3.5. Reported input tokens are an estimate either way.
PI_CURSOR_API_COST_ESTIMATE 1 records API-rate cost estimates. Default off: Cursor bills plan quota, so cost is reported as 0.
PI_CURSOR_PROMPT_HISTORY Publish the system prompt and completed turns as Cursor prompt messages when a request is built without an upstream checkpoint. Default on; 0/false restores the pre-1.4.24 behavior, where a rebuilt conversation reached the model with no history and no Pi system prompt.

Architecture notes

Module layout (src/stream/)

Stream modules are split under src/stream/:

Module Responsibility
types.ts Shared structural types (no runtime code — safe for anyone to import)
config.ts Agent URL + client version resolution
tuning.ts Timeouts, retry budgets, and the stream idle watchdog
debug-log.ts Debug / lifecycle / metric sinks with secret redaction
images.ts Image decode + Cursor CLI format and size validation
model-routing.ts Effort suffix / requested model resolution
model-discovery.ts GetUsableModels unary RPCs + per-token model cache
model-cache.ts Cross-process catalog cache read synchronously at startup
context-normalize.ts Context-mode side-channel folding
message-parsing.ts Pi/OpenAI message list → Cursor turn structures
pi-adapter.ts Pi context/model types ↔ OpenAI-shaped request, usage accounting
request-build.ts AgentRunRequest protobuf construction + blob store
bridge-session.ts Active-bridge registry + h2-bridge lifecycle
session-state.ts Conversation store, checkpoints, key derivation, session locks
server-messages.ts Inbound KV / exec / interaction dispatch
thinking-filter.ts Strips inline <think>-style tags from the text channel
recovery.ts Tool-continuation recovery planner
protocol.ts Auth/protocol error enhancement
drift.ts Wire-drift detection (unknown message cases and protobuf fields)
native-core.ts Native streamSimple runtime that drives all of the above

Native streamSimple is the only chat path. The OpenAI-compatible local proxy that used to sit alongside it was removed in favour of a single code path.

Startup

Extension activation does no network and no credential lookup. Models are registered synchronously from the persisted catalog (PI_CURSOR_CACHE_DIR), falling back to the catalog bundled in src/models/catalog.json on a first-ever launch. Live discovery runs through pi's refreshModels hook — off the critical path, in the background, and again whenever /model is opened — then persists its result for the next launch.

All Cursor HTTP/2 transport runs in-process via node:http2 — no subprocess is spawned. Unary RPCs (both discovery calls) use a dedicated one-shot client (h2-unary.ts); the bidirectional chat stream uses a persistent session (h2-session.ts) that survives across turns. Unary calls fall back to the general-purpose bridge transport if the one-shot client fails.

src/proto/agent_pb.ts is a large generated Connect/protobuf surface used by the wire layer. Never hand-edit it — regenerate with yarn proto:gen (see proto/README.md) when Cursor changes the agent schema.

Troubleshooting

  • Pasted screenshot is permission denied: Pi Ctrl+V writes $TMPDIR/pi-clipboard-<uuid>.png and inserts that path as text. Clipboard images are still ingested as vision attachments. Native Cursor read is rejected and redirected to Pi tools; reading the path through a tool now depends on the active Pi tool's access rules. If the temporary file is gone, paste again. If Pi's read tool cannot access it, reattach the image for vision input or place it in a location that tool can read.
  • No API provider registered for api: cursor-native: Update to the latest pi-cursor (pi update npm:@rahularya01/pi-cursor) and restart Pi (or /reload). This means the Agent tried to stream via Pi's global streamSimple dispatcher before the Cursor transport was registered there. Current builds register cursor-native on that registry during extension load.
  • Not logged in / 401: Ensure Cursor CLI or app is logged in, or run /login cursor again. Check /cursor.doctor to verify your tokenSource. Tokens from CLI/IDE are re-resolved when near expiry; idle stream retries also force-refresh credentials.
  • Empty / hung stream: Cursor may have updated wire headers; verify network connectivity or bump PI_CURSOR_CLIENT_VERSION. /cursor.doctor prints the active clientVersion.
  • Wire-protocol drift: Cursor can change agent.v1 at any time. Unrecognized server messages and unknown protobuf fields are no longer skipped silently — they are counted, written to the lifecycle log as wire_drift, appended to the failing turn's error message, and listed by /cursor.doctor under wireDrift. wireDriftStranding=yes means an unanswered message could have parked the turn, which is the difference between "our schema is a bit behind" and "this is why it hung". Run CURSOR_ACCESS_TOKEN=... yarn smoke:wire to check the handshake and schema against the live endpoint without starting a chat turn, then see proto/README.md to resync the schema.
  • Stuck / dies after a few minutes of work: Cursor InteractionQuery prompts are answered so the stream does not park. Web/search and hosted fetch are approved by default. Inspect $TMPDIR/pi-cursor-lifecycle.jsonl for interaction_query / bridge_close events, and /cursor.doctor for lastStreamEvent. Full debug: PI_CURSOR_PROVIDER_DEBUG=1.
  • Tool continuation lost: The provider now prefers full-history rebuild when checkpoints are stale/mismatched. If recovery still skips, /cursor.doctor shows lastRecoverySkipReason. Retry the turn or start a new chat.
  • WSL credential detection: Set USERPROFILE or USERNAME so the Windows home directory is known, and ensure /mnt/c/Users/<you>/AppData/... is readable. Disable with PI_CURSOR_SYSTEM_CREDENTIALS=0 if undesired.
  • Slow startup: Activation should be a few milliseconds. /cursor.doctor reports catalogCache (none(using bundled fallback) means every launch is starting cold — check that catalogCacheDir is writable) and unaryTransport. A stale Cursor CLI keychain entry no longer blocks startup: a refresh token that fails is remembered for 10 minutes so it is not retried on the next launch, and any valid locally stored token is always preferred over a network exchange.
  • Token counts look off: Cursor sends no tokenizer counts, so input, context and output tokens are character estimates at PI_CURSOR_CHARS_PER_TOKEN (default 3.5). Prose runs closer to 4 characters per token and dense code or JSON closer to 3, so a code-heavy session can be up to ~17% larger than the meter shows. If auto-compaction comes too late for your work, set PI_CURSOR_CHARS_PER_TOKEN=3. Cursor's own maxTokens (300000) is not the limit it enforces: a request it counted at 380K of 300K was answered in full on 2026-10-30, so the provider does not clamp to it.
  • Model list looks stale: It is the last successfully discovered catalog. Open /model to trigger a background refresh, or delete PI_CURSOR_CACHE_DIR to force full rediscovery.

Runtime

pi-cursor targets Node.js >= 22. All Cursor HTTP/2 transport (the bidirectional chat stream and the unary discovery RPCs) runs in-process via node:http2 — no subprocess is spawned.

/cursor.doctor reports the host as runtime=node <version> (or runtime=bun <version> if the extension happens to be loaded under Bun).

Development

The toolchain is Yarn 4 + Node.js. tsc still does the typechecking; tests run on Vitest; tsup produces dist/.

yarn install
yarn check

yarn check runs TypeScript typechecking, ESLint, Prettier format verification, security checks, the protobuf staleness check, and unit tests.

Script Purpose
yarn proto:gen Regenerate src/proto/agent_pb.ts from proto/agent.proto.
yarn proto:sync Rebuild proto/agent.proto from an updated generated file obtained upstream.
yarn proto:check Fail if the generated protobuf is stale or hand-edited (part of yarn check).

Attributions

Wire protocol and authentication patterns adapted from MIT community client lineage:

Package structure mirrors pi-antigravity.

Support the project

If pi-cursor is useful to you, consider sponsoring the project on GitHub.

License

MIT