store

package
v0.0.0-...-bdea199 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventTypeMessage    = "message"
	EventTypeToolCall   = "tool_call"
	EventTypeToolResult = "tool_result"
	EventTypeSystem     = "system"
	EventTypeThinking   = "thinking"
)

EventType constants

View Source
const (
	ApprovalStatusPending  = "pending"
	ApprovalStatusApproved = "approved"
	ApprovalStatusDenied   = "denied"
	ApprovalStatusResolved = "resolved" // Generic resolved status for external resolutions
)

ApprovalStatus constants

View Source
const (
	SessionStatusDraft        = "draft"
	SessionStatusStarting     = "starting"
	SessionStatusRunning      = "running"
	SessionStatusCompleted    = "completed"
	SessionStatusFailed       = "failed"
	SessionStatusWaitingInput = "waiting_input"
	SessionStatusInterrupting = "interrupting" // Session received interrupt signal and is shutting down
	SessionStatusInterrupted  = "interrupted"  // Session was interrupted but can be resumed
	SessionStatusDiscarded    = "discarded"    // Draft session was discarded by the user
)

SessionStatus constants

Variables

View Source
var (
	// ErrNotFound is returned when a requested entity is not found
	ErrNotFound = errors.New("not found")

	// ErrAlreadyDecided is returned when attempting to decide an approval that has already been decided
	ErrAlreadyDecided = errors.New("approval already decided")

	// ErrInvalidStatus is returned when an invalid status is provided
	ErrInvalidStatus = errors.New("invalid status")
)

Sentinel errors for common store operations

Functions

This section is empty.

Types

type AlreadyDecidedError

type AlreadyDecidedError struct {
	ID     string
	Status string // current status
}

AlreadyDecidedError wraps ErrAlreadyDecided with additional context

func (*AlreadyDecidedError) Error

func (e *AlreadyDecidedError) Error() string

func (*AlreadyDecidedError) Unwrap

func (e *AlreadyDecidedError) Unwrap() error

type Approval

type Approval struct {
	ID          string          `json:"id"`
	RunID       string          `json:"run_id"`
	SessionID   string          `json:"session_id"`
	ToolUseID   *string         `json:"tool_use_id,omitempty"`
	Status      ApprovalStatus  `json:"status"`
	CreatedAt   time.Time       `json:"created_at"`
	RespondedAt *time.Time      `json:"responded_at,omitempty"`
	ToolName    string          `json:"tool_name"`
	ToolInput   json.RawMessage `json:"tool_input"`
	Comment     string          `json:"comment,omitempty"`
}

Approval represents a local approval request

type ApprovalStatus

type ApprovalStatus string

ApprovalStatus represents the status of an approval

const (
	ApprovalStatusLocalPending  ApprovalStatus = "pending"
	ApprovalStatusLocalApproved ApprovalStatus = "approved"
	ApprovalStatusLocalDenied   ApprovalStatus = "denied"
)

Valid approval statuses

func (ApprovalStatus) IsValid

func (s ApprovalStatus) IsValid() bool

IsValid checks if the status is valid

func (ApprovalStatus) String

func (s ApprovalStatus) String() string

String returns the string representation of the status

type ConversationEvent

type ConversationEvent struct {
	ID              int64
	SessionID       string
	ClaudeSessionID string
	Sequence        int
	EventType       string // 'message', 'tool_call', 'tool_result', 'system'
	CreatedAt       time.Time

	// Message fields
	Role    string // user, assistant, system
	Content string

	// Tool call fields
	ToolID          string
	ToolName        string
	ToolInputJSON   string
	ParentToolUseID string

	// Tool result fields
	ToolResultForID   string
	ToolResultContent string

	// Tool call tracking
	IsCompleted    bool   // TRUE when tool result received
	ApprovalStatus string // NULL, 'pending', 'approved', 'denied'
	ApprovalID     string // HumanLayer approval ID when correlated
}

ConversationEvent represents a single event in a conversation

type ConversationStore

type ConversationStore interface {
	// Session operations
	CreateSession(ctx context.Context, session *Session) error
	UpdateSession(ctx context.Context, sessionID string, updates SessionUpdate) error
	HardDeleteSession(ctx context.Context, sessionID string) error
	GetSession(ctx context.Context, sessionID string) (*Session, error)
	GetSessionByRunID(ctx context.Context, runID string) (*Session, error)
	ListSessions(ctx context.Context) ([]*Session, error)
	SearchSessionsByTitle(ctx context.Context, query string, limit int) ([]*Session, error)
	// GetExpiredDangerousPermissionsSessions returns sessions where dangerous permissions have expired
	GetExpiredDangerousPermissionsSessions(ctx context.Context) ([]*Session, error)

	// Conversation operations
	AddConversationEvent(ctx context.Context, event *ConversationEvent) error
	GetConversation(ctx context.Context, claudeSessionID string) ([]*ConversationEvent, error)
	GetSessionConversation(ctx context.Context, sessionID string) ([]*ConversationEvent, error)

	// Tool call operations
	GetPendingToolCall(ctx context.Context, sessionID string, toolName string) (*ConversationEvent, error)
	GetUncorrelatedPendingToolCall(ctx context.Context, sessionID string, toolName string) (*ConversationEvent, error)
	GetPendingToolCalls(ctx context.Context, sessionID string) ([]*ConversationEvent, error)
	GetToolCallByID(ctx context.Context, toolID string) (*ConversationEvent, error)
	MarkToolCallCompleted(ctx context.Context, toolID string, sessionID string) error
	CorrelateApproval(ctx context.Context, sessionID string, toolName string, approvalID string) error
	LinkConversationEventToApprovalUsingToolID(ctx context.Context, sessionID string, toolID string, approvalID string) error
	UpdateApprovalStatus(ctx context.Context, approvalID string, status string) error

	// MCP server operations
	StoreMCPServers(ctx context.Context, sessionID string, servers []MCPServer) error
	GetMCPServers(ctx context.Context, sessionID string) ([]MCPServer, error)

	// Raw event storage (for debugging)
	StoreRawEvent(ctx context.Context, sessionID string, eventJSON string) error

	// Approval operations for local approvals
	CreateApproval(ctx context.Context, approval *Approval) error
	GetApproval(ctx context.Context, id string) (*Approval, error)
	GetPendingApprovals(ctx context.Context, sessionID string) ([]*Approval, error)
	UpdateApprovalResponse(ctx context.Context, id string, status ApprovalStatus, comment string) error

	// File snapshot operations
	CreateFileSnapshot(ctx context.Context, snapshot *FileSnapshot) error
	GetFileSnapshots(ctx context.Context, sessionID string) ([]FileSnapshot, error)
	// Recent paths operations
	GetRecentWorkingDirs(ctx context.Context, limit int) ([]RecentPath, error)

	// User settings operations
	GetUserSettings(ctx context.Context) (*UserSettings, error)
	UpdateUserSettings(ctx context.Context, settings UserSettings) error

	// Database lifecycle
	Close() error
}

ConversationStore defines the interface for storing conversation data

type FileSnapshot

type FileSnapshot struct {
	ID        int64
	ToolID    string
	SessionID string
	FilePath  string // Relative path from tool call
	Content   string
	CreatedAt time.Time
}

FileSnapshot represents a snapshot of file content at Read time

type MCPServer

type MCPServer struct {
	ID        int64
	SessionID string
	Name      string
	Command   string
	ArgsJSON  string // JSON array
	EnvJSON   string // JSON object
}

MCPServer represents an MCP server configuration

func MCPServersFromConfig

func MCPServersFromConfig(sessionID string, config map[string]claudecode.MCPServer) ([]MCPServer, error)

Helper function to convert MCP config to store format

type NotFoundError

type NotFoundError struct {
	Type string // e.g., "approval", "session"
	ID   string
}

NotFoundError wraps ErrNotFound with additional context

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

type RecentPath

type RecentPath struct {
	Path       string    `json:"path"`
	LastUsed   time.Time `json:"last_used"`
	UsageCount int       `json:"usage_count"`
}

RecentPath represents a recently used working directory

type SQLiteStore

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

SQLiteStore implements ConversationStore using SQLite

func NewSQLiteStore

func NewSQLiteStore(dbPath string) (*SQLiteStore, error)

NewSQLiteStore creates a new SQLite-backed store

func (*SQLiteStore) AddConversationEvent

func (s *SQLiteStore) AddConversationEvent(ctx context.Context, event *ConversationEvent) error

AddConversationEvent adds a new conversation event

func (*SQLiteStore) Close

func (s *SQLiteStore) Close() error

Close closes the database connection

func (*SQLiteStore) CorrelateApproval

func (s *SQLiteStore) CorrelateApproval(ctx context.Context, sessionID string, toolName string, approvalID string) error

CorrelateApproval correlates an approval with a tool call

func (*SQLiteStore) CreateApproval

func (s *SQLiteStore) CreateApproval(ctx context.Context, approval *Approval) error

CreateApproval creates a new approval

func (*SQLiteStore) CreateFileSnapshot

func (s *SQLiteStore) CreateFileSnapshot(ctx context.Context, snapshot *FileSnapshot) error

CreateFileSnapshot stores a new file snapshot

func (*SQLiteStore) CreateSession

func (s *SQLiteStore) CreateSession(ctx context.Context, session *Session) error

CreateSession creates a new session

func (*SQLiteStore) GetApproval

func (s *SQLiteStore) GetApproval(ctx context.Context, id string) (*Approval, error)

GetApproval retrieves an approval by ID

func (*SQLiteStore) GetApprovalCount

func (s *SQLiteStore) GetApprovalCount(ctx context.Context) (int, error)

GetApprovalCount returns the total number of approvals

func (*SQLiteStore) GetConversation

func (s *SQLiteStore) GetConversation(ctx context.Context, claudeSessionID string) ([]*ConversationEvent, error)

GetConversation retrieves all events for a Claude session

func (*SQLiteStore) GetDB

func (s *SQLiteStore) GetDB() *sql.DB

GetDB returns the underlying database connection for testing purposes

func (*SQLiteStore) GetEventCount

func (s *SQLiteStore) GetEventCount(ctx context.Context) (int, error)

GetEventCount returns the total number of conversation events

func (*SQLiteStore) GetExpiredDangerousPermissionsSessions

func (s *SQLiteStore) GetExpiredDangerousPermissionsSessions(ctx context.Context) ([]*Session, error)

GetExpiredDangerousPermissionsSessions returns sessions where dangerous permissions have expired

func (*SQLiteStore) GetFileSnapshots

func (s *SQLiteStore) GetFileSnapshots(ctx context.Context, sessionID string) ([]FileSnapshot, error)

GetFileSnapshots retrieves all snapshots for a session

func (*SQLiteStore) GetMCPServers

func (s *SQLiteStore) GetMCPServers(ctx context.Context, sessionID string) ([]MCPServer, error)

GetMCPServers retrieves MCP servers for a session

func (*SQLiteStore) GetPendingApprovals

func (s *SQLiteStore) GetPendingApprovals(ctx context.Context, sessionID string) ([]*Approval, error)

GetPendingApprovals retrieves all pending approvals for a session

func (*SQLiteStore) GetPendingToolCall

func (s *SQLiteStore) GetPendingToolCall(ctx context.Context, sessionID string, toolName string) (*ConversationEvent, error)

GetPendingToolCall finds the most recent uncompleted tool call for a given session and tool name

func (*SQLiteStore) GetPendingToolCalls

func (s *SQLiteStore) GetPendingToolCalls(ctx context.Context, sessionID string) ([]*ConversationEvent, error)

GetPendingToolCalls finds all uncompleted tool calls for a given session

func (*SQLiteStore) GetRecentWorkingDirs

func (s *SQLiteStore) GetRecentWorkingDirs(ctx context.Context, limit int) ([]RecentPath, error)

GetRecentWorkingDirs retrieves recently used working directories

func (*SQLiteStore) GetSession

func (s *SQLiteStore) GetSession(ctx context.Context, sessionID string) (*Session, error)

GetSession retrieves a session by ID

func (*SQLiteStore) GetSessionByRunID

func (s *SQLiteStore) GetSessionByRunID(ctx context.Context, runID string) (*Session, error)

GetSessionByRunID retrieves a session by its run_id

func (*SQLiteStore) GetSessionConversation

func (s *SQLiteStore) GetSessionConversation(ctx context.Context, sessionID string) ([]*ConversationEvent, error)

GetSessionConversation retrieves all events for a session including parent history

func (*SQLiteStore) GetSessionCount

func (s *SQLiteStore) GetSessionCount(ctx context.Context) (int, error)

GetSessionCount returns the total number of sessions

func (*SQLiteStore) GetToolCallByID

func (s *SQLiteStore) GetToolCallByID(ctx context.Context, toolID string) (*ConversationEvent, error)

GetToolCallByID retrieves a specific tool call by its ID

func (*SQLiteStore) GetUncorrelatedPendingToolCall

func (s *SQLiteStore) GetUncorrelatedPendingToolCall(ctx context.Context, sessionID string, toolName string) (*ConversationEvent, error)

GetUncorrelatedPendingToolCall finds the most recent uncompleted tool call without approval correlation

func (*SQLiteStore) GetUserSettings

func (s *SQLiteStore) GetUserSettings(ctx context.Context) (*UserSettings, error)

GetUserSettings retrieves the user settings from the database

func (*SQLiteStore) HardDeleteSession

func (s *SQLiteStore) HardDeleteSession(ctx context.Context, sessionID string) error

HardDeleteSession permanently deletes a session from the database

func (*SQLiteStore) LinkConversationEventToApprovalUsingToolID

func (s *SQLiteStore) LinkConversationEventToApprovalUsingToolID(ctx context.Context, sessionID string, toolID string, approvalID string) error

LinkConversationEventToApprovalUsingToolID correlates an approval with a specific tool call by tool_id

func (*SQLiteStore) ListSessions

func (s *SQLiteStore) ListSessions(ctx context.Context) ([]*Session, error)

ListSessions retrieves all sessions

func (*SQLiteStore) MarkToolCallCompleted

func (s *SQLiteStore) MarkToolCallCompleted(ctx context.Context, toolID string, sessionID string) error

MarkToolCallCompleted marks a tool call as completed when its result is received

func (*SQLiteStore) SearchSessionsByTitle

func (s *SQLiteStore) SearchSessionsByTitle(ctx context.Context, query string, limit int) ([]*Session, error)

SearchSessionsByTitle searches for sessions by title using SQL LIKE

func (*SQLiteStore) StoreMCPServers

func (s *SQLiteStore) StoreMCPServers(ctx context.Context, sessionID string, servers []MCPServer) error

StoreMCPServers stores MCP server configurations

func (*SQLiteStore) StoreRawEvent

func (s *SQLiteStore) StoreRawEvent(ctx context.Context, sessionID string, eventJSON string) error

StoreRawEvent stores a raw event for debugging

func (*SQLiteStore) UpdateApprovalResponse

func (s *SQLiteStore) UpdateApprovalResponse(ctx context.Context, id string, status ApprovalStatus, comment string) error

UpdateApprovalResponse updates the status and comment of an approval

func (*SQLiteStore) UpdateApprovalStatus

func (s *SQLiteStore) UpdateApprovalStatus(ctx context.Context, approvalID string, status string) error

UpdateApprovalStatus updates the status of an approval

func (*SQLiteStore) UpdateSession

func (s *SQLiteStore) UpdateSession(ctx context.Context, sessionID string, updates SessionUpdate) error

UpdateSession updates session fields

func (*SQLiteStore) UpdateUserSettings

func (s *SQLiteStore) UpdateUserSettings(ctx context.Context, settings UserSettings) error

UpdateUserSettings updates the user settings in the database

type Session

type Session struct {
	ID                                  string
	RunID                               string
	ClaudeSessionID                     string
	ParentSessionID                     string
	Query                               string
	Summary                             string
	Title                               string // New field for user-editable title
	Model                               string
	ModelID                             string // Full model identifier (e.g., "claude-opus-4-1-20250805")
	WorkingDir                          string
	MaxTurns                            int
	SystemPrompt                        string
	AppendSystemPrompt                  string // NEW: Append to system prompt
	CustomInstructions                  string
	PermissionPromptTool                string // NEW: MCP tool for permission prompts
	AllowedTools                        string // NEW: JSON array of allowed tools
	DisallowedTools                     string // NEW: JSON array of disallowed tools
	AdditionalDirectories               string // NEW: JSON array of additional directories
	Status                              string
	CreatedAt                           time.Time
	LastActivityAt                      time.Time
	CompletedAt                         *time.Time
	CostUSD                             *float64
	InputTokens                         *int `db:"input_tokens"`
	OutputTokens                        *int `db:"output_tokens"`
	CacheCreationInputTokens            *int `db:"cache_creation_input_tokens"`
	CacheReadInputTokens                *int `db:"cache_read_input_tokens"`
	EffectiveContextTokens              *int `db:"effective_context_tokens"`
	DurationMS                          *int
	NumTurns                            *int
	ResultContent                       string
	ErrorMessage                        string
	AutoAcceptEdits                     bool       `db:"auto_accept_edits"`
	DangerouslySkipPermissions          bool       `db:"dangerously_skip_permissions"`
	DangerouslySkipPermissionsExpiresAt *time.Time `db:"dangerously_skip_permissions_expires_at"`
	DangerouslySkipPermissionsTimeoutMs *int64     `db:"dangerously_skip_permissions_timeout_ms"`
	Archived                            bool       // New field for session archiving

	// Proxy configuration
	ProxyEnabled       bool   `db:"proxy_enabled"`
	ProxyBaseURL       string `db:"proxy_base_url"`
	ProxyModelOverride string `db:"proxy_model_override"`
	ProxyAPIKey        string `db:"proxy_api_key"`

	// Editor state for draft sessions (JSON blob)
	EditorState *string `db:"editor_state"`
}

Session represents a Claude Code session

func NewSessionFromConfig

func NewSessionFromConfig(id, runID string, config claudecode.SessionConfig) *Session

NewSessionFromConfig creates a Session from Claude SessionConfig

type SessionUpdate

type SessionUpdate struct {
	ClaudeSessionID                     *string
	Query                               *string // For updating draft session queries
	Summary                             *string
	Title                               *string // New field for updating title
	Status                              *string
	LastActivityAt                      *time.Time
	CompletedAt                         *time.Time
	CostUSD                             *float64
	InputTokens                         *int
	OutputTokens                        *int
	CacheCreationInputTokens            *int
	CacheReadInputTokens                *int
	EffectiveContextTokens              *int
	DurationMS                          *int
	NumTurns                            *int
	ResultContent                       *string
	ErrorMessage                        *string
	AutoAcceptEdits                     *bool       `db:"auto_accept_edits"`
	DangerouslySkipPermissions          *bool       `db:"dangerously_skip_permissions"`
	DangerouslySkipPermissionsExpiresAt **time.Time `db:"dangerously_skip_permissions_expires_at"`
	DangerouslySkipPermissionsTimeoutMs *int64      `db:"dangerously_skip_permissions_timeout_ms"`
	Model                               *string
	ModelID                             *string // Full model identifier
	Archived                            *bool   // New field for updating archived status
	AdditionalDirectories               *string `db:"additional_directories"`
	// New proxy fields
	ProxyEnabled       *bool   `db:"proxy_enabled"`
	ProxyBaseURL       *string `db:"proxy_base_url"`
	ProxyModelOverride *string `db:"proxy_model_override"`
	ProxyAPIKey        *string `db:"proxy_api_key"`
	// Working directory field
	WorkingDir *string `db:"working_dir"`
	// Editor state field (JSON blob)
	EditorState *string `db:"editor_state"`
}

SessionUpdate contains fields that can be updated

type UserSettings

type UserSettings struct {
	AdvancedProviders bool      `json:"advanced_providers"`
	OptInTelemetry    *bool     `json:"opt_in_telemetry"` // Pointer to handle NULL (unset)
	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
}

UserSettings represents user preferences

Jump to

Keyboard shortcuts

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