feat: Cursor agent protocol — full chat + server-driven tool calling

Merged
CO
4mo ago
+30900-33

What

Completes the Cursor integration started in #905 (OAuth): Cursor subscription models are now fully usable — after /login cursor, the per-account model catalog is discovered automatically and chat runs over Cursor's native agent protocol with complete tool calling.

This is a port of the upstream can1357/oh-my-pi Cursor provider (~5,000 lines + protobuf schema), re-architected for this fork across three packages.

Architecture

Cursor's protocol is server-driven: the server streams the assistant turn and, mid-turn, sends exec frames asking the client to run a tool, blocking on an in-band reply. That forces a three-layer design:

  1. packages/ai — cursor-agent API (new KnownApi): one HTTP/2 Connect stream per turn against agent.v1.AgentService/Run (Connect envelope framing, 5s heartbeats, gRPC-trailer + end-stream error decoding, abort). Interaction updates map to assistant events (text/thinking deltas, streamed MCP tool calls with cumulative args snapshots + throttled partial-JSON parsing, turnEnded, tokenDelta usage). The exec channel dispatches onto injected CursorExecHandlers — legacy read/ls/grep/write/shell(+stream) frames, modern pi_* frames, MCP calls (incl. approval-only probes), kv blob store, tool-catalog handshake, mcpState, neutral hook replies — and every unsupported frame gets a typed refusal or ExecClientThrow so the server never blocks on a missing reply. Bridged calls are synthesized into the assistant message as already-resolved toolCall blocks (kCursorExecResolved) with results paired via onToolResult. Multi-turn history rebuilds per request into rootPromptMessagesJson blobs + display turns over a content-addressed blob store, with checkpoint caching and poisoned-conversation id rotation. GetUsableModels discovery powers the dynamic per-account catalog (max-mode 1M variants via Model.compat.cursorMaxMode).
  2. packages/agent — loop contract: the loop skips provider-resolved tool calls (no double execution of side-effecting tools), appends provider-buffered tool results right after the assistant message (also on error/abort paths so calls never end up unpaired), and the idle watchdog re-arms while the stream reports pending local work (EventStream.trackLocalWork) instead of killing a request that is silently running a tool.
  3. packages/coding-agent — exec bridge: maps exec frames onto the session's wrapped tool registry (read/bash/edit/write/grep/find/ls + MCP/extension tools by name), so approvals, sandboxing, truncation, and tool cards behave exactly like model-issued calls. Senpi's tools take plain kwargs, so mappings are direct (pi_edit → edits[{oldText,newText}] is 1:1; workingDirectory composes onto bash as a quoted cd prefix). Lifecycle events ride the new Agent.emitExternalEvent. The Bun binary build statically registers the module like bedrock.

Vendored schema: agent.proto + protoc-gen-es v2.13 codegen with TS enums rewritten to erasable const objects (transform-cursor-agent-proto.mjs documents regeneration) — the repo compiles with erasableSyntaxOnly and protobuf-es decodes through the embedded descriptor. New pinned dep @bufbuild/protobuf@2.13.0 (no lifecycle scripts); publish/install locks regenerated.

Deliberately not ported (typed refusals): computer use, subagents, Cursor-managed background shells, canvas, smart-mode classification, conversation search, native todo mirroring (summary-only pairing kept), Kimi-K3 thinking replay, proxy tunneling.

Tests

  • packages/ai/test/cursor-agent.test.ts (21): fake HTTP/2 Connect server round-trips — streaming/usage/event order, header sanitization, an end-to-end exec readArgs round-trip asserting the protobuf ReadResult on the wire + resolved block + paired result, MCP catalog handshake, Connect/gRPC error surfaces, incomplete-stream detection, abort, no-token fail-fast; plus exec-handler resolution, MCP arg merging, history encoding, pi-arg mapping units.
  • packages/agent/test/cursor-exec-loop.test.ts (5): resolved-call skip, buffered-result ordering incl. terminal error paths, mixed resolved+local execution, idle-watchdog re-arm under local work, genuine-idle abort.
  • packages/coding-agent/test/cursor-exec-bridge.test.ts (9): frame→tool arg mappings, cwd composition, zero-line read short-circuit, MCP dispatch/unknown-tool, validation, lifecycle events.

Full suites: ai 2075 passed, agent 497 passed, coding-agent 7818 passed (single remaining failure is a pre-existing auth-storage.test.ts timing flake that reproduces on clean main with identical node_modules; find-tool tests need the fd binary, installed locally as CI does). npm run check green incl. browser smoke (Node-only transport stays behind the bundler-opaque lazy boundary).

QA (evidence under local-ignore/qa-evidence/20260816-cursor-agent-protocol/, not committed per policy)

  • Targeted end-to-end, real CLI (9/9): a local fake Cursor server (real protobuf frames) registered as a models.json custom provider with api: "cursor-agent"; driven over --mode rpc in a sandbox. Proves a real prompt turn streams over the protocol, the server's mid-turn exec readArgs executes the session's real read tool and the file's actual bytes return inside the wire ReadResult, tool_execution_* events surface, the paired toolResult + synthesized resolved toolCall persist in the transcript, the assistant's final text echoes the tool output the server received, and the real auth.json checksum is unchanged.
  • Channel 3 mock loop --self-test: 48/48. Channel 4 CLI smoke --self-test: 8/8.
Open in Web Open in Cursor 

Summary by cubic

Enables full Cursor chat with server-driven tool calling via the new cursor-agent API. Previously Cursor was OAuth-only with no usable models; now the per-account model catalog is discovered and exec-channel tool calls run through the session’s real tools without double execution.

  • packages/ai: Adds cursor-agent (HTTP/2 Connect agent.v1.AgentService/Run) with streamed text/thinking/tool-call deltas, in-band exec-channel handling, and per-account catalog discovery (GetUsableModels). Vendors the protobuf schema and adds @bufbuild/protobuf.
  • packages/agent: Skips provider-resolved tool calls marked kCursorExecResolved, appends provider-buffered ToolResultMessages after the assistant message (including error/abort paths), and re-arms the idle watchdog while EventStream.trackLocalWork runs. Exposes AgentOptions.cursorExecHandlers and Agent.emitExternalEvent.
  • packages/coding-agent: Bridges Cursor exec frames to real tools (read/bash/edit/write/grep/find/ls and MCP tools) so approvals, sandboxing, and rendering match model-issued calls. Registers the provider statically for the Bun build.

Rollout

  • Run /login cursor, then refresh the catalog (e.g., senpi update --models); Cursor models now appear and work.
  • Library embedders using @earendil-works/pi-ai must pass cursorExecHandlers to Agent to enable exec-channel tool runs; the coding-agent CLI wires this by default.
  • No changes required for non-Cursor providers. Unsupported Cursor features (computer use, subagents, background shells, canvas, etc.) return typed refusals.