cursor

package
v0.194.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 34 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	ModeAsk     = "ask"
	ModeAutoRun = "autoRun"
)

Cursor's modes in the permission-mode vocabulary (api.PermissionModeView): Plan is Claude Code's plan; Ask answers and changes nothing, a mode Claude Code has no word for; Agent asks before a terminal command unless Cursor's auto-run is on, which only each command records.

View Source
const Agent = "cursor"

Agent is the value Cursor's sessions carry in sessions.agent.

View Source
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.

View Source
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.

View Source
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

View Source
var HookEvents = []string{"beforeSubmitPrompt", "afterAgentResponse", "postToolUse", "postToolUseFailure", "stop", "preCompact",
	"sessionStart", "sessionEnd", "subagentStop", "afterShellExecution", "afterFileEdit", "afterAgentThought"}

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).

sessionStart's reply could set environment variables and add context, and subagentStop's and stop's could send a follow-up message; {} does none of it. The observational ones added for the CLI's chats (sessionStart, sessionEnd, subagentStop, afterShellExecution, afterFileEdit, afterAgentThought) are documented as fire-and-forget or decide nothing (cursor.com/docs/agent/hooks, read 2026-11-17).

Functions

func CLIConfiguredModel

func CLIConfiguredModel(configDir string) string

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

func ChatDir(cwd, chatID string) string

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

func ChatExists(cwd, id string) bool

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 ChatIDs added in v0.182.0

func ChatIDs(ctx context.Context, db *sql.DB, c Composer) ([]string, error)

ChatIDs is a chat's messages in order, in either format.

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

func FolderHash(cwd string) string

FolderHash is the name cursor-agent gives a folder's chat directory.

func HeaderIDs

func HeaderIDs(ctx context.Context, db *sql.DB, composerID string) ([]string, error)

HeaderIDs is the chat's messages in order: fullConversationHeadersOnly's bubble ids.

func HookCommand

func HookCommand(shim string) string

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 HookMode added in v0.182.0

func HookMode(composer string) string

HookMode is the mode sessionStart's composer_mode names.

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

func NeutralReply(event string) []byte

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

func Open(path string) (*sql.DB, error)

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

func ToolInput(cursor string, in map[string]any, cwd string) map[string]any

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 ToolName

func ToolName(cursor string) string

ToolName is the name Caprock stores for a Cursor tool.

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

func Workspaces(ctx context.Context, userDir string) map[string]string

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 and ContextLimit are contextWindowStatusAtCreation on a
	// prompt: how full Cursor measured the chat's context window as the
	// prompt was written, and the window's size. Zero when it kept none.
	ContextUsed, ContextLimit int64
	// ContextPct is the same reading as a share of the window, when
	// HasContextPct: from the tokens when Cursor kept them, else 100 minus
	// its percentageRemainingFloat (percentageRemaining), the only figure
	// Cursor's November 2025 builds keep on a composer-1 or Auto prompt.
	ContextPct    float64
	HasContextPct bool
	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
	// ThinkingMs is thinkingDurationMs: how long the model thought before
	// this row, as Cursor timed it; 0 when it did not.
	ThinkingMs int64
	// SentAt and EndedAt are timingInfo's clientRpcSendTime and
	// clientEndTime (unix ms): when the request this row answers was sent
	// and when its reply finished; 0 when Cursor kept no timing.
	SentAt, EndedAt int64
	// Summary is set on the row where Cursor summarized the chat to make
	// room (conversationSummary with truncationLastBubbleIdInclusive): a
	// compaction.
	Summary *Summary
}

Bubble is one message of an editor chat.

func Bubbles

func Bubbles(ctx context.Context, db *sql.DB, composerID string, ids []string) ([]Bubble, error)

Bubbles reads the messages ids names, in that order (HeaderIDs). A message that is missing or unreadable is skipped. Only the rows asked for are read, by key, so a pass over a long chat that grew by two messages reads two.

func ChatBubbles added in v0.182.0

func ChatBubbles(ctx context.Context, db *sql.DB, c Composer, ids []string) ([]Bubble, error)

ChatBubbles is Bubbles for either format. A legacy chat's messages carry no createdAt, so each is dated by its request's timingInfo, else by the next dated message (a prompt is sent just before its reply starts), else the previous one, else the chat's creation (datedLegacy).

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.

func CLIChats

func CLIChats(ctx context.Context, configDir string, limit int) []ChatMeta

CLIChats lists the CLI's chats, newest first, at most limit of them. A chat whose meta cannot be read is skipped.

func ReadChatMeta

func ReadChatMeta(ctx context.Context, path string) (ChatMeta, error)

ReadChatMeta reads one store.db's meta row, read-only.

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
	// ContextPct is contextUsagePercent, the share of the window Cursor last
	// measured as used, when HasContextPct. Since Cursor's November 2025
	// builds (composer-1, Auto) it is the only reading a chat keeps:
	// contextTokensUsed and contextTokenLimit are no longer written.
	ContextPct    float64
	HasContextPct bool
	// Generating is how many messages Cursor is still writing
	// (generatingBubbleIds): non-zero while a turn runs.
	Generating int
	// Legacy is a chat in the format before fullConversationHeadersOnly
	// (Cursor's spring 2025 builds): its messages live inline in
	// composerData.conversation and its tool calls in the composer's
	// capabilities, not in bubbleId rows. Messages counts them.
	Legacy bool
}

Composer is one editor chat (a `composerData:` row), with what Caprock reads.

func Composers

func Composers(ctx context.Context, db *sql.DB) ([]Composer, error)

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

func (c Composer) Fingerprint() string

Fingerprint changes whenever anything Caprock reads from the chat changes.

func (Composer) Finished added in v0.182.0

func (c Composer) Finished() bool

Finished reports whether the chat's newest turn is over: Cursor writes nothing for it and its status says it stopped. "none" is what older builds left on a chat they did not track (107 of 171 chats on the owner's machine, 2026-11-17); a running chat has generatingBubbleIds.

type Getenv

type Getenv func(string) string

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
	// contains filtered or unexported fields
}

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"`
	// postToolUse and afterShellExecution: the call's time in ms.
	Duration float64 `json:"duration"`
	// sessionStart, sessionEnd, subagentStop, afterAgentThought.
	SessionID    string  `json:"session_id"`
	ComposerMode string  `json:"composer_mode"`
	IsBackground bool    `json:"is_background_agent"`
	Reason       string  `json:"reason"`
	FinalStatus  string  `json:"final_status"`
	DurationMs   float64 `json:"duration_ms"`
	// subagentStop. Cursor's docs name no id for the subagent; the fields
	// are read when a build sends them.
	SubagentID    string   `json:"subagent_id"`
	ToolCallID    string   `json:"tool_call_id"`
	SubagentType  string   `json:"subagent_type"`
	Task          string   `json:"task"`
	Description   string   `json:"description"`
	Summary       string   `json:"summary"`
	MessageCount  int      `json:"message_count"`
	ToolCallCount int      `json:"tool_call_count"`
	ModifiedFiles []string `json:"modified_files"`
	// afterShellExecution.
	Command string `json:"command"`
	Output  string `json:"output"`
	// afterFileEdit.
	FilePath string            `json:"file_path"`
	Edits    []json.RawMessage `json:"edits"`
}

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

func (in *Ingester) Known(id string) bool

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).

func (*Ingester) Once

func (in *Ingester) Once(ctx context.Context) error

Once reads everything that changed since the last pass.

func (*Ingester) Run

func (in *Ingester) Run(ctx context.Context) error

Run polls until the context is cancelled, importing once immediately.

func (*Ingester) Stats

func (in *Ingester) Stats() Stats

Stats returns a snapshot of what has been imported.

type ModelUsage

type ModelUsage struct {
	Requests int64
	Cents    float64
}

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 Summary added in v0.182.0

type Summary struct {
	Truncated string
	// Chars is the summary's length in characters.
	Chars int
}

Summary is a compaction Cursor recorded: the summary that replaced the conversation up to the message Truncated names.

type Tool

type Tool struct {
	ID     string
	Name   string
	Args   map[string]any
	Status string // completed, error, cancelled, loading
	Error  bool
	// Result is toolFormerData.result, the JSON text Cursor stores the
	// call's output as ({"output": …} for a terminal command, {"contents":
	// …} for a read…); "" while the call runs.
	Result string
	// ErrorText is what Cursor told the model went wrong, when it did.
	ErrorText string
	// Decision is userDecision: accepted or rejected, "" when nobody was
	// asked.
	Decision string
	// Approval is additionalData.reviewData.approvalType: "full_auto" when
	// Cursor ran the call without asking (its auto-run), "" when it kept
	// none.
	Approval string
	// MCPServer and MCPTool name an MCP call's server and tool, from
	// additionalData.reviewData (serverId, toolName) or the call's params
	// (tools[0].serverName, name); "" for any other call.
	MCPServer, MCPTool string
}

Tool is a tool call as Cursor recorded it (toolFormerData).

type TurnTokens

type TurnTokens struct {
	User    bool
	Model   string
	In, Out int64
}

TurnTokens is one message's share of the token figures: a prompt with its model, or a reply with its tokenCount.

func ChatTokens added in v0.182.0

func ChatTokens(ctx context.Context, db *sql.DB, c Composer, ids []string) ([]TurnTokens, error)

ChatTokens is TokensByTurn for either format.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL