feat: Cursor agent protocol — full chat + server-driven tool calling
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:
packages/ai—cursor-agentAPI (newKnownApi): one HTTP/2 Connect stream per turn againstagent.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,tokenDeltausage). The exec channel dispatches onto injectedCursorExecHandlers— legacy read/ls/grep/write/shell(+stream) frames, modernpi_*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 orExecClientThrowso the server never blocks on a missing reply. Bridged calls are synthesized into the assistant message as already-resolvedtoolCallblocks (kCursorExecResolved) with results paired viaonToolResult. Multi-turn history rebuilds per request intorootPromptMessagesJsonblobs + display turns over a content-addressed blob store, with checkpoint caching and poisoned-conversation id rotation.GetUsableModelsdiscovery powers the dynamic per-account catalog (max-mode 1M variants viaModel.compat.cursorMaxMode).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.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;workingDirectorycomposes onto bash as a quotedcdprefix). Lifecycle events ride the newAgent.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 execreadArgsround-trip asserting the protobufReadResulton 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.jsoncustom provider withapi: "cursor-agent"; driven over--mode rpcin a sandbox. Proves a real prompt turn streams over the protocol, the server's mid-turn execreadArgsexecutes the session's realreadtool and the file's actual bytes return inside the wireReadResult,tool_execution_*events surface, the pairedtoolResult+ synthesized resolvedtoolCallpersist in the transcript, the assistant's final text echoes the tool output the server received, and the realauth.jsonchecksum is unchanged. - Channel 3 mock loop
--self-test: 48/48. Channel 4 CLI smoke--self-test: 8/8.


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: Addscursor-agent(HTTP/2 Connectagent.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 markedkCursorExecResolved, appends provider-bufferedToolResultMessages after the assistant message (including error/abort paths), and re-arms the idle watchdog whileEventStream.trackLocalWorkruns. ExposesAgentOptions.cursorExecHandlersandAgent.emitExternalEvent.packages/coding-agent: Bridges Cursor exec frames to real tools (read/bash/edit/write/grep/find/lsand 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-aimust passcursorExecHandlerstoAgentto 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.