cursoragentv1

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 48 Imported by: 0

Documentation

Overview

Package cursoragentv1 implements the private Cursor Agent v1 transport used by BeefAPI's subscription-OAuth CPA provider. It is not the official type-62 @cursor/sdk runtime.

Index

Constants

View Source
const (
	EnvStateDir        = "CURSOR_AGENT_V1_STATE_DIR"
	EnvStateTTL        = "CURSOR_AGENT_V1_STATE_TTL"
	HeaderUsageReceipt = "X-Cursor-Agent-V1-Usage-Receipt"
	HeaderUsageReplay  = "X-Cursor-Agent-V1-Usage-Replay"
	ProviderID         = "cursor-agent-v1"
)

Variables

View Source
var (
	ErrSessionActive       = errors.New("Cursor Agent v1 session is already active")
	ErrSessionPending      = errors.New("Cursor Agent v1 session is waiting for tool results")
	ErrSessionNotPending   = errors.New("Cursor Agent v1 session has no matching pending tool")
	ErrMixedToolFollowUp   = errors.New("Cursor Agent v1 cannot mix a new user message with tool results")
	ErrCallerToolsDisabled = errors.New("Cursor Agent v1 caller tools are disabled")
)
View Source
var (
	ErrRetiredOwner       = errors.New("Cursor Agent v1 state owner is retired")
	ErrCredentialMismatch = errors.New("Cursor Agent v1 credential does not own the session state")
	ErrStateLeaseHeld     = errors.New("Cursor Agent v1 session state is leased by another runtime")
	ErrStatePending       = errors.New("Cursor Agent v1 session state is waiting for tool results")
	ErrPendingAmbiguous   = errors.New("Cursor Agent v1 tool results match multiple pending sessions")
	ErrToolResultConflict = errors.New("Cursor Agent v1 tool result conflicts with the completed snapshot")
)
View Source
var DefaultModels = []string{
	"claude-fable-5-1",
	"claude-fable-5",
	"claude-opus-5",
	"claude-opus-4-6",
	"claude-opus-4-7",
	"claude-opus-4-8",
	"claude-sonnet-4-6",
	"claude-sonnet-5",
	"composer-2.5-fast",
	"glm-5.2",
	"kimi-k3",
}

DefaultModels is the Agent v1 catalog this provider accepts for the default runtime profile. It mirrors the calibrated list BeefAPI type 64 publishes.

View Source
var SandModels = []string{
	"grok-4.6",
}

SandModels are only reachable through the Sand inference runtime, selected per credential with "runtime_profile": "sand" in the auth file.

Functions

func CredentialFingerprint

func CredentialFingerprint(credentialScope, accountKey string) (string, error)

func ModelsForRuntimeProfile

func ModelsForRuntimeProfile(profile string) []string

ModelsForRuntimeProfile returns the catalog for one credential's runtime profile.

func SandSignatureRetryCount

func SandSignatureRetryCount() int64

Types

type ClaimOptions

type ClaimOptions struct {
	RuntimeProfile        string
	HistoryRequestKey     string
	AllowPending          bool
	RequireExisting       bool
	AllowCredentialChange bool
	ToolCatalogDigest     string
	ToolCatalog           []ToolDefinition
	RequireToolCatalog    bool
	NewBillingRunID       string
	ReuseBillingRun       bool
}

type ClaimResult

type ClaimResult struct {
	Replay      *CompletedReplay
	Owner       OwnerLease
	Snapshot    StateSnapshot
	ColdRebuild bool
}

type CompletedReplay

type CompletedReplay struct {
	RequestSegmentID string
	SessionID        string
	ConversationID   string
	BillingRunID     string
	OriginalBatch    []string
	Events           []Event
	HasPending       bool
	FollowUpText     string
}

type CompletedToolResult

type CompletedToolResult struct {
	ToolCallID string      `json:"tool_call_id"`
	Content    string      `json:"content"`
	IsError    bool        `json:"is_error,omitempty"`
	Media      []MediaPart `json:"media,omitempty"`
}

type ContentPart

type ContentPart struct {
	Text  string
	Media *MediaPart
}

ContentPart is one element of a mixed user or tool-result payload: exactly one of Text or Media is populated.

type Event

type Event struct {
	Type EventType
	Text string
	// Signature is the provider thinking signature attached to a completed
	// reasoning block (Sand thinking_part.signature). Empty for Agent v1.
	Signature string
	// ProgressEvents preserves the original thinking-delta count when a
	// completed snapshot coalesces adjacent deltas. Zero means one live event.
	ProgressEvents int
	Tokens         int64
	Usage          *UsageObservation
	Checkpoint     []byte
	Blobs          map[string][]byte
	ToolCall       *ToolCall
	ToolResult     *ToolResult
	HostedSearch   *HostedSearch
}

type EventType

type EventType int
const (
	EventText EventType = iota + 1
	EventThinking
	EventUsage
	EventCheckpoint
	EventToolCall
	EventToolResultAccepted
	EventTurnEnded
	EventHostedSearchCall
	EventDone
	EventHostedSearchStarted
	EventHostedSearchCompleted
	EventThinkingCompleted
	EventUsageObservation
)

type Executor

type Executor struct {
	// contains filtered or unexported fields
}

func NewExecutor

func NewExecutor(stateDir string) (*Executor, error)

func (*Executor) HttpRequest

func (*Executor) Identifier

func (*Executor) Identifier() string

func (*Executor) Refresh

func (e *Executor) Refresh(ctx context.Context, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error)

type FileStateStore

type FileStateStore struct {
	// contains filtered or unexported fields
}

func NewFileStateStore

func NewFileStateStore(root string) (*FileStateStore, error)

func (*FileStateStore) Claim

func (s *FileStateStore) Claim(sessionID, conversationID, credentialFingerprint string, options ClaimOptions) (ClaimResult, error)

func (*FileStateStore) Delete

func (s *FileStateStore) Delete(owner OwnerLease) error

func (*FileStateStore) DeleteSession

func (s *FileStateStore) DeleteSession(sessionID, credentialFingerprint string) error

func (*FileStateStore) LookupCompleted

func (s *FileStateStore) LookupCompleted(credentialFingerprint string, results []ToolResult, followUp string) (CompletedReplay, error)

func (*FileStateStore) LookupHistory

func (s *FileStateStore) LookupHistory(fingerprint, key string) (CompletedReplay, error)

func (*FileStateStore) OriginalPendingBatch

func (s *FileStateStore) OriginalPendingBatch(credentialFingerprint string, toolCallIDs []string) ([]string, error)

func (*FileStateStore) Release

func (s *FileStateStore) Release(owner OwnerLease) error

func (*FileStateStore) ResolvePending

func (s *FileStateStore) ResolvePending(credentialFingerprint string, toolCallIDs []string) (string, error)

func (*FileStateStore) SaveCheckpoint

func (s *FileStateStore) SaveCheckpoint(owner OwnerLease, checkpoint []byte, blobs map[string][]byte) error

func (*FileStateStore) SaveCompleted

func (s *FileStateStore) SaveCompleted(owner OwnerLease, results []ToolResult, events []Event, ephemeral bool, followUp string) error

func (*FileStateStore) SaveFollowUp

func (s *FileStateStore) SaveFollowUp(owner OwnerLease, followUp string) error

func (*FileStateStore) SaveHistory

func (s *FileStateStore) SaveHistory(owner OwnerLease, key string, events []Event) error

func (*FileStateStore) SavePending

func (s *FileStateStore) SavePending(owner OwnerLease, pending []PendingTool) error

func (*FileStateStore) SaveUsageCarry

func (s *FileStateStore) SaveUsageCarry(owner OwnerLease, events []Event) error

func (*FileStateStore) SetBillingRunID

func (s *FileStateStore) SetBillingRunID(owner OwnerLease, billingRunID string) error

type HostedSearch

type HostedSearch struct {
	CallID     string
	Kind       HostedSearchKind
	Query      string
	URL        string
	ArgsJSON   string
	References []HostedSearchReference
	Content    string
	Error      string
}

type HostedSearchKind

type HostedSearchKind string
const (
	HostedSearchKindWebSearch HostedSearchKind = "web_search"
	HostedSearchKindWebFetch  HostedSearchKind = "web_fetch"
	HostedSearchKindExaSearch HostedSearchKind = "exa_search"
	HostedSearchKindExaFetch  HostedSearchKind = "exa_fetch"
)

type HostedSearchReference

type HostedSearchReference struct {
	Title string
	URL   string
	Chunk string
}

type InferenceRunner

type InferenceRunner struct {
	// contains filtered or unexported fields
}

func NewInferenceRunner

func NewInferenceRunner() *InferenceRunner

func (*InferenceRunner) Run

func (r *InferenceRunner) Run(ctx context.Context, request RunRequest, emit func(Event)) error

type ManagedOutput

type ManagedOutput struct {
	RequestSegmentID string
	Events           <-chan Event
	Result           <-chan error
	SessionID        string
	BillingRunID     string
	ConversationID   string
	OriginalBatch    []string
	Replay           bool
	HasPending       bool
	FollowUpApplied  bool
}

type ManagedRequest

type ManagedRequest struct {
	TurnMetering       bool
	RequestSegmentID   string
	SessionID          string
	BillingRunID       string
	CredentialScope    string
	AccountKey         string
	ToolCatalogDigest  string
	FollowUpText       string
	ActiveResults      []ToolResult
	CarryUsage         []Event
	RequireExisting    bool
	ReuseBillingRun    bool
	Context            context.Context
	Run                RunRequest
	DisableCallerTools bool
}

type MediaPart

type MediaPart struct {
	Kind     string `json:"kind"` // "image" or "document"
	MimeType string `json:"mime_type"`
	Data     string `json:"data"`
	Filename string `json:"filename,omitempty"`
}

MediaPart is a caller-supplied binary attachment (screenshot, pasted image, PDF) that must reach the upstream model as native media rather than as text. Data is standard base64 without a data: prefix so both Cursor data planes can encode it directly (InferenceImagePart/InferenceFilePart carry base64 strings; Agent v1 SelectedImage/McpImageContent carry raw bytes).

type ObservedCount

type ObservedCount struct {
	Present bool
	Invalid bool
	Value   int64
}

ObservedCount records proto presence separately from the numeric value. Missing, explicit 0, and invalid/negative are distinct.

type OwnerLease

type OwnerLease struct {
	RequestSegmentID string
	SessionID        string
	Generation       uint64
	Token            string
	CredentialHash   string
	ConversationID   string
	BillingRunID     string
	// contains filtered or unexported fields
}

type PendingTool

type PendingTool struct {
	MessageID          uint32 `json:"message_id"`
	ExecID             string `json:"exec_id,omitempty"`
	ToolCallID         string `json:"tool_call_id"`
	UpstreamToolCallID string `json:"upstream_tool_call_id,omitempty"`
	Name               string `json:"name"`
	Arguments          string `json:"arguments"`
}

type RunRequest

type RunRequest struct {
	RuntimeProfile    string
	HistoryRequestKey string // finite full-history generation; never sent upstream
	BaseURL           string
	ProxyURL          string
	AccessToken       string
	ClientVersion     string
	RouteChannelID    int
	RouteUserID       int
	Model             string
	ConversationID    string
	UserText          string
	// UserMedia holds images/documents attached to the active user turn.
	UserMedia []MediaPart
	// ThinkingEnabled mirrors the caller's Anthropic thinking.type=enabled.
	ThinkingEnabled bool

	SystemText           string
	Tools                []ToolDefinition
	HistoryMessages      [][]byte
	AllowHostedSearch    bool
	AllowHostedFetch     bool
	RequireHostedSearch  bool
	RequireHostedFetch   bool
	RequireHostedTool    bool
	HostedSearchMaxUses  *int
	HostedFetchMaxUses   *int
	HostedSearchDomains  hostedDomainPolicy
	HostedFetchDomains   hostedDomainPolicy
	RequireToolCall      bool
	MaxParallelTools     int
	DeleteCompletedState bool
	FollowUpText         string
	InitialCheckpoint    []byte
	InitialBlobs         map[string][]byte
	Resume               bool
	ToolResults          <-chan ToolResult
	// contains filtered or unexported fields
}

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

func NewRunner

func NewRunner() *Runner

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, request RunRequest, onEvent func(Event)) error

type SessionManager

type SessionManager struct {
	// contains filtered or unexported fields
}

func NewSessionManager

func NewSessionManager(runner *Runner, store StateStore) (*SessionManager, error)

func (*SessionManager) Cancel

func (m *SessionManager) Cancel(request ManagedRequest) error

func (*SessionManager) CancelState

func (m *SessionManager) CancelState(request ManagedRequest) error

CancelState removes a persisted session even when no live H2 owner remains, such as after a sidecar restart. The credential scope prevents one channel from deleting another channel's continuation state.

func (*SessionManager) Park

func (m *SessionManager) Park(request ManagedRequest) error

Park closes the current downstream turn after the protocol adapter has emitted the complete tool-call batch. It never decides batching by timer.

func (*SessionManager) ResumeTool

func (m *SessionManager) ResumeTool(request ManagedRequest, result ToolResult) (*ManagedOutput, error)

func (*SessionManager) ResumeTools

func (m *SessionManager) ResumeTools(request ManagedRequest, results []ToolResult) (*ManagedOutput, error)

func (*SessionManager) Start

func (m *SessionManager) Start(request ManagedRequest) (*ManagedOutput, error)

func (*SessionManager) StartFollowUp

func (m *SessionManager) StartFollowUp(request ManagedRequest, covering []ToolResult) (*ManagedOutput, error)

func (*SessionManager) StartHistory

func (m *SessionManager) StartHistory(request ManagedRequest) (*ManagedOutput, error)

Reuse the existing reservation and file lease. A concurrent retry waits for the committed snapshot, not a second model invocation.

type StateSnapshot

type StateSnapshot struct {
	Version               int               `json:"version"`
	RuntimeProfile        string            `json:"runtime_profile,omitempty"`
	SessionID             string            `json:"session_id"`
	ConversationID        string            `json:"conversation_id"`
	CredentialFingerprint string            `json:"credential_fingerprint"`
	ToolCatalogDigest     string            `json:"tool_catalog_digest,omitempty"`
	ToolCatalog           []ToolDefinition  `json:"tool_catalog,omitempty"`
	BillingRunID          string            `json:"billing_run_id,omitempty"`
	UsageCarry            []Event           `json:"usage_carry,omitempty"`
	OwnerGeneration       uint64            `json:"owner_generation"`
	OwnerToken            string            `json:"owner_token"`
	Checkpoint            []byte            `json:"checkpoint,omitempty"`
	Blobs                 map[string][]byte `json:"blobs,omitempty"`
	PendingTools          []PendingTool     `json:"pending_tools,omitempty"`
	PendingBatchIDs       []string          `json:"pending_batch_ids,omitempty"`
	FollowUpText          string            `json:"follow_up_text,omitempty"`
	EphemeralComplete     bool              `json:"ephemeral_complete,omitempty"`
	CompletedAt           time.Time         `json:"completed_at,omitempty"`
	UpdatedAt             time.Time         `json:"updated_at"`
}

type StateStore

type StateStore interface {
	LookupHistory(fingerprint, key string) (CompletedReplay, error)
	SaveHistory(owner OwnerLease, key string, events []Event) error
	Claim(sessionID, conversationID, credentialFingerprint string, options ClaimOptions) (ClaimResult, error)
	SaveCheckpoint(owner OwnerLease, checkpoint []byte, blobs map[string][]byte) error
	SavePending(owner OwnerLease, pending []PendingTool) error
	SaveCompleted(owner OwnerLease, results []ToolResult, events []Event, ephemeral bool, followUp string) error
	SaveFollowUp(owner OwnerLease, followUp string) error
	SetBillingRunID(owner OwnerLease, billingRunID string) error
	SaveUsageCarry(owner OwnerLease, events []Event) error
	Delete(owner OwnerLease) error
	DeleteSession(sessionID, credentialFingerprint string) error
	Release(owner OwnerLease) error
	ResolvePending(credentialFingerprint string, toolCallIDs []string) (string, error)
	OriginalPendingBatch(credentialFingerprint string, toolCallIDs []string) ([]string, error)
	LookupCompleted(credentialFingerprint string, results []ToolResult, followUp string) (CompletedReplay, error)
}

type ToolCall

type ToolCall struct {
	MessageID  uint32
	ExecID     string
	ToolCallID string
	Name       string
	Arguments  string
}

type ToolDefinition

type ToolDefinition struct {
	Name        string
	Description string
	InputSchema []byte
}

type ToolResult

type ToolResult struct {
	ToolCallID string
	Content    string
	IsError    bool
	// Media carries screenshots/documents returned by caller tools (for
	// example chrome-devtools) so they reach the model as native images.
	Media []MediaPart
}

type UsageKind

type UsageKind int

UsageKind distinguishes TokenDeltaUpdate from TurnEndedUpdate counters. TokenDelta is a heuristic progress counter. TurnEnded covers an Agent turn, which can span several client tool-result requests.

const (
	UsageKindUnknown UsageKind = iota
	UsageKindTokenDelta
	UsageKindTurnEnded
)

type UsageObservation

type UsageObservation struct {
	Carried    bool // internal: a completed earlier native turn, not this run's terminal
	Kind       UsageKind
	TokenDelta ObservedCount
	Input      ObservedCount
	Output     ObservedCount
	CacheRead  ObservedCount
	CacheWrite ObservedCount
	Reasoning  ObservedCount
}

UsageObservation is the typed decode of Agent v1 usage counters. It is the only facts source for those counters. Projection may read it; it must not invent per-request measured attribution.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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