Documentation
¶
Overview ¶
Package cursor reads Cursor's chats — the editor's Agent and Ask chats and the `cursor-agent` CLI's — and carries Cursor's hook events (ADR-095, .ai/25-cursor.md).
The editor keeps every chat in one SQLite key-value database, `<user dir>/globalStorage/state.vscdb`, table `cursorDiskKV`: a `composerData:<chat id>` row per chat (its name, model, the ordered list of its messages, and Cursor's own cost per model in `usageData`) and a `bubbleId:<chat id>:<message id>` row per message (the words, the tool call, and on the last reply of a turn `tokenCount`). The same database holds Cursor's sign-in tokens in another table; nothing here reads that table, and every query names its key range.
The database belongs to a program that may be writing to it. It is opened mode=ro with a busy timeout and one connection, never immutable=1 (Cursor runs it in WAL mode, and an immutable open would miss what sits in the WAL). Nothing here writes, creates or migrates anything.
Everything below was read from Cursor 2.3.41 (state.vscdb, workbench source) and cursor-agent 2025.09.12 (its bundled source) on 2026-11-16.
Index ¶
- Constants
- Variables
- func CLIConfiguredModel(configDir string) string
- func ChatDir(cwd, chatID string) string
- func ChatExists(cwd, id string) bool
- func ConfigDir() string
- func DBPath() string
- func FolderHash(cwd string) string
- func HeaderIDs(ctx context.Context, db *sql.DB, composerID string) ([]string, error)
- func HookCommand(shim string) string
- func HooksPath() string
- func NeutralReply(event string) []byte
- func Open(path string) (*sql.DB, error)
- func ToolInput(cursor string, in map[string]any, cwd string) map[string]any
- func ToolName(cursor string) string
- func UserDir() string
- func Workspaces(ctx context.Context, userDir string) map[string]string
- type Bubble
- type ChatMeta
- type Composer
- type Getenv
- type HookHandler
- type HookPayload
- type HookStatus
- type Ingester
- type ModelUsage
- type Overhead
- type Recorder
- type Stats
- type Tool
- type TurnTokens
Constants ¶
const Agent = "cursor"
Agent is the value Cursor's sessions carry in sessions.agent.
const BytesPerToken = 4
BytesPerToken is the estimate's exchange rate: four bytes of UTF-8 to a token. Close for English and code; text in a script that takes more bytes per letter counts as more tokens, which is also roughly how tokenizers treat it.
const EnvSession = "CAPROCK_CURSOR_SESSION"
EnvSession is the variable a Cursor CLI started by Caprock carries: the Caprock session it belongs to. Cursor runs hooks as its own children, and the shim sends it on, so the chat is linked exactly rather than by folder and time.
const HookTimeout = 5
HookTimeout is the per-hook timeout written, in seconds. The shim prints its reply before it does anything else and gives up on the daemon within a second (rule 3); the rest is headroom for a slow disk.
Variables ¶
var HookEvents = []string{"beforeSubmitPrompt", "afterAgentResponse", "postToolUse", "postToolUseFailure", "stop", "preCompact"}
HookEvents are the hooks Caprock registers in hooks.json, in the order written. None of them is a permission hook: Cursor blocks an action when a permission hook (preToolUse, beforeShellExecution, beforeMCPExecution, beforeReadFile, subagentStart) prints nothing valid, and an "allow" from one could pass something Cursor would have asked about. Caprock reads; it never stands in the way of a decision (rule 3).
Functions ¶
func CLIConfiguredModel ¶
CLIConfiguredModel is the model cursor-agent's own cli-config.json names, "" when it names none. The CLI writes it as {"model": {"modelId": …}}.
func ChatDir ¶
ChatDir is where cursor-agent keeps one chat: <config dir>/chats/<md5 of the folder it ran in>/<chat id>. The folder is hashed as the CLI's process.cwd() spells it.
func ChatExists ¶
ChatExists reports whether cursor-agent has a chat with this id for the folder, which is what `cursor-agent --resume <id>` started there needs.
func ConfigDir ¶
func ConfigDir() string
ConfigDir is cursor-agent's own directory, resolved as it resolves it (its bundled source, 2025.09.12): CURSOR_CONFIG_DIR, else $XDG_CONFIG_HOME/cursor, else ~/.cursor.
func DBPath ¶
func DBPath() string
DBPath is the editor's chat database when it exists, "" otherwise.
func FolderHash ¶
FolderHash is the name cursor-agent gives a folder's chat directory.
func HeaderIDs ¶
HeaderIDs is the chat's messages in order: fullConversationHeadersOnly's bubble ids.
func HookCommand ¶
HookCommand is the command registered for every hook: the shim, told it is answering Cursor. shim is what hooks.ShimCommand returns — the caprock-hook binary, or `<caprock> hook` where there is none.
func HooksPath ¶
func HooksPath() string
HooksPath is the user-level hooks file both the editor and the CLI read, ~/.cursor/hooks.json (cursor.com/docs/agent/hooks, read 2026-11-16).
func NeutralReply ¶
NeutralReply is what the shim prints for a hook: the answer that leaves Cursor doing exactly what it would have done without Caprock. beforeSubmitPrompt's is {"continue": true}; every other registered hook takes {} as "nothing to add".
func Open ¶
Open opens a Cursor SQLite database read-only, with a busy timeout and one connection. SQLite opens lazily: a file that is not a database is found out on the first query.
func ToolInput ¶
ToolInput reshapes a call's arguments into a Claude Code hook payload's tool_input: the file a file tool names becomes `file_path` (a relative path resolved against the chat's folder, so per-directory attribution places it), `contents` becomes `content`, and every other key is kept.
func UserDir ¶
func UserDir() string
UserDir is the editor's user directory: ~/Library/Application Support/Cursor/User on macOS, %APPDATA%\Cursor\User on Windows, and $XDG_CONFIG_HOME/Cursor/User (default ~/.config) on Linux — the VS Code layout Cursor inherits. "" when no home directory is known.
func Workspaces ¶
Workspaces maps editor chats to the folder their window had open, from each workspace's own database (workspaceStorage/<hash>/state.vscdb, key composer.composerData, which lists the window's chats) and its workspace.json. A chat whose window is gone maps to nothing.
Types ¶
type Bubble ¶
type Bubble struct {
ID string
User bool // type 1; otherwise an assistant step (type 2)
At time.Time
Text string
Thinking string
Model string // modelInfo.modelName, on the turn's first rows
// TokensIn and TokensOut are tokenCount, which Cursor fills on the last
// reply of a turn: the context of that turn's last request, and what
// that request wrote. Zero on every other row.
TokensIn, TokensOut int64
// ContextUsed is contextWindowStatusAtCreation.tokensUsed on a prompt.
ContextUsed int64
Tool *Tool
// Call is the model request this row belongs to (modelCallId of a tool
// call, else usageUuid), "" when Cursor kept none.
Call string
// TerminalCwd is lastTerminalCwd, the folder Cursor's terminal was in.
TerminalCwd string
// Visible is how many characters of the conversation this row adds that
// a person can read: words, thinking, a tool call's arguments and result.
Visible int
}
Bubble is one message of an editor chat.
type ChatMeta ¶
type ChatMeta struct {
ID string `json:"agentId"`
Name string `json:"name"`
Mode string `json:"mode"`
Model string `json:"lastUsedModel"`
CreatedMs float64 `json:"createdAt"`
Created time.Time `json:"-"`
// FolderHash is the md5 directory the chat sits under.
FolderHash string `json:"-"`
}
ChatMeta is a CLI chat's meta row.
type Composer ¶
type Composer struct {
ID string
Name string
Model string // modelConfig.modelName: the model picked now
MaxMode bool
Mode string // unifiedMode: agent, chat (Ask), plan…
Status string
Created time.Time
Updated time.Time
Messages int // entries in fullConversationHeadersOnly
Archived bool
// Usage is Cursor's own cost per model; nil when Cursor recorded none.
Usage map[string]ModelUsage
// ContextUsed and ContextLimit are Cursor's last reading of the chat's
// context window, 0 when it kept none.
ContextUsed, ContextLimit int64
}
Composer is one editor chat (a `composerData:` row), with what Caprock reads.
func Composers ¶
Composers lists the editor's chats. Only scalar fields are pulled out in SQL, so the rows that carry a whole conversation's headers are never copied into Go.
func (Composer) Fingerprint ¶
Fingerprint changes whenever anything Caprock reads from the chat changes.
type Getenv ¶
Getenv is the environment lookup the path functions take, so tests can give them a machine of their own.
type HookHandler ¶
type HookHandler struct {
Token string
Recorder Recorder
Log *slog.Logger
// Editor reports whether the editor's database holds a chat; nil when
// there is no editor database, so every hook is recorded.
Editor func(id string) bool
Link *sessionlink.Linker
Now func() time.Time
}
HookHandler serves POST /v1/hook/cursor.
An editor chat is the editor reader's: its database has the words, the tokens and the cost, and a second copy from hooks would show every prompt twice. So a hook for a chat the editor's database holds is answered and dropped, and hooks record only what no database of Cursor's gives Caprock — the `cursor-agent` CLI, whose chats are stored as content-addressed protobuf blobs (.ai/25-cursor.md § The CLI).
func (*HookHandler) ServeHTTP ¶
func (h *HookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP records one hook. It answers 204 whatever it did with it: the shim has already printed Cursor's neutral reply and is not waiting for a decision.
type HookPayload ¶
type HookPayload struct {
ConversationID string `json:"conversation_id"`
GenerationID string `json:"generation_id"`
Model string `json:"model"`
ModelID string `json:"model_id"`
Event string `json:"hook_event_name"`
CursorVersion string `json:"cursor_version"`
WorkspaceRoots []string `json:"workspace_roots"`
TranscriptPath string `json:"transcript_path"`
Prompt string `json:"prompt"` // beforeSubmitPrompt
Text string `json:"text"` // afterAgentResponse
ToolName string `json:"tool_name"` // postToolUse, postToolUseFailure
ToolInput json.RawMessage `json:"tool_input"` // an object, or a JSON string
ToolOutput json.RawMessage `json:"tool_output"` // a JSON string
ToolUseID string `json:"tool_use_id"`
Cwd string `json:"cwd"`
Error string `json:"error_message"`
Status string `json:"status"` // stop
LoopCount int `json:"loop_count"`
// preCompact
Trigger string `json:"trigger"`
ContextTokens int64 `json:"context_tokens"`
ContextWindow int64 `json:"context_window_size"`
}
HookPayload is the part of a Cursor hook's input Caprock reads, from cursor.com/docs/agent/hooks (read 2026-11-16). Every hook carries the common fields; the rest belong to one event each.
type HookStatus ¶
type HookStatus struct {
Path string `json:"path"`
Installed bool `json:"installed"`
Missing []string `json:"missing,omitempty"`
// Others is how many entries in the file are somebody else's.
Others int `json:"others"`
Exists bool `json:"exists"`
}
HookStatus is what hooks.json holds.
func InspectHooks ¶
func InspectHooks(path string) (HookStatus, error)
InspectHooks reports which of HookEvents carry Caprock's hook.
func InstallHooks ¶
func InstallHooks(path, shim string) (HookStatus, error)
InstallHooks merges Caprock's entries into hooks.json, creating it (with `"version": 1`) when there is none. An existing entry of Caprock's is replaced in place, so a moved data directory updates rather than doubles. The first install backs the file up beside itself.
func UninstallHooks ¶
func UninstallHooks(path string) (HookStatus, error)
UninstallHooks removes Caprock's entries and nothing else. An event list that held only Caprock's entry is removed with it.
type Ingester ¶
type Ingester struct {
// contains filtered or unexported fields
}
Ingester copies the editor's chats into Caprock's store.
It polls, as the Hermes and OpenCode readers do. A pass first compares the database's size and modification time (and its WAL's) with the last pass, so a Cursor that is closed costs one stat per tick; only a chat whose fingerprint moved is read, and only from its last prompt on.
Usage is reconciled, as Hermes's is. Cursor fills `tokenCount` on the last reply of a turn some time after that reply is first written, and keeps its cost as a running total per chat and model (`usageData`), so neither can be stored with the message it belongs to the first time the message is read. Each pass subtracts what Caprock holds for the chat from Cursor's totals and records the difference — on the newest reply the pass stores, or on a `turn.assistant` of its own marked `usage_only`, keyed by the totals it brings the chat to. Caprock's totals equal Cursor's and a re-read adds nothing.
func NewIngester ¶
func NewIngester(db *sql.DB, path, userDir string, rec *rollup.Recorder, log *slog.Logger, every time.Duration) *Ingester
NewIngester builds an ingester over an already-open editor database.
func (*Ingester) Known ¶
Known reports whether the editor's database holds a chat with this id, so the hook plane can leave an editor chat to this reader (hooks.go).
type ModelUsage ¶
ModelUsage is Cursor's own figure for one model in one chat: how many requests it counted and what it charged, in cents (composerData.usageData).
type Overhead ¶
type Overhead struct {
Model string
RequestTokens int64
TypedTokens int64
VisibleTokens int64
OverheadTokens int64
Requests int
// Clean is true when the conversation before the request was at most a
// quarter of it, so the difference is mostly Cursor's own and not an
// error in counting a long tool result.
Clean bool
}
Overhead is one chat's first-request estimate.
type Recorder ¶
type Recorder interface {
Record(ctx context.Context, ev *event.Event, info rollup.SessionInfo) (rollup.Result, error)
}
Recorder is what the hook handler needs from rollup.
type Stats ¶
type Stats struct {
Chats int `json:"chats"`
Events int `json:"events"`
Priced int `json:"priced_chats,omitempty"`
Unpriced int `json:"unpriced,omitempty"`
LastPoll int64 `json:"last_poll_ms,omitempty"`
}
Stats is what the daemon reports about the Cursor reader.
type TurnTokens ¶
TurnTokens is one message's share of the token figures: a prompt with its model, or a reply with its tokenCount.
func TokensByTurn ¶
func TokensByTurn(ctx context.Context, db *sql.DB, composerID string, ids []string) ([]TurnTokens, error)
TokensByTurn reads the fields token totals need from every message of a chat, in the order ids gives. Only those fields leave SQLite.