session

package
v0.0.0-...-75ec8e3 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SessionStorageVersion = 1
)

Storage format version for forward compatibility

Variables

This section is empty.

Functions

func ExtractFilesList

func ExtractFilesList(filesRead map[string]string) []string

ExtractFilesList extracts just the file paths from the filesRead map

func GenerateID

func GenerateID() string

GenerateID creates a human-friendly session ID (e.g. "bright-silver-falcon").

func GenerateWordID

func GenerateWordID() string

GenerateWordID generates a human-friendly ID in the form "adjective-adjective-noun".

func GetSessionStorageDir

func GetSessionStorageDir() (string, error)

GetSessionStorageDir returns the platform-specific session storage directory (public API)

func GetWorkspaceFiles

func GetWorkspaceFiles(workingDir string, maxFiles int) []string

GetWorkspaceFiles returns a list of files in the workspace (up to maxFiles) This is a helper function that can be used to gather workspace context

Types

type BackgroundJob

type BackgroundJob struct {
	ID             string
	Command        string
	WorkingDir     string
	StartTime      time.Time
	Completed      bool
	ExitCode       int
	Stdout         []string
	Stderr         []string
	Process        *os.Process
	PID            int
	ProcessGroupID int
	Type           string
	CancelFunc     context.CancelFunc
	StopRequested  bool
	LastSignal     string
	Done           chan struct{}
	Mu             sync.RWMutex
}

BackgroundJob represents a running background process

type Message

type Message struct {
	Role            string                   `json:"role"` // "user", "assistant", "tool"
	Content         string                   `json:"content"`
	Reasoning       string                   `json:"reasoning,omitempty"` // Reasoning/thinking content (e.g., from extended thinking models)
	ToolCalls       []map[string]interface{} `json:"tool_calls,omitempty"`
	ToolID          string                   `json:"tool_id,omitempty"`
	ToolName        string                   `json:"tool_name,omitempty"`        // Name of the tool for tool responses
	ToolDescription string                   `json:"tool_description,omitempty"` // Description of the tool for tool responses
	Timestamp       time.Time                `json:"timestamp"`

	// Native format storage (for prompt caching)
	NativeFormat      interface{} `json:"native_format,omitempty"`       // Provider-specific message format
	NativeProvider    string      `json:"native_provider,omitempty"`     // e.g., "anthropic", "openai"
	NativeModelFamily string      `json:"native_model_family,omitempty"` // e.g., "claude-3", "gpt-4"
	NativeTimestamp   time.Time   `json:"native_timestamp,omitempty"`    // When native format was created
}

Message represents a conversation message

func (*Message) GetContent

func (m *Message) GetContent() string

GetContent returns the message content (implements loop.Message)

func (*Message) GetReasoning

func (m *Message) GetReasoning() string

GetReasoning returns the reasoning content (implements loop.Message)

func (*Message) GetRole

func (m *Message) GetRole() string

GetRole returns the role of the message (implements loop.Message)

func (*Message) GetToolCalls

func (m *Message) GetToolCalls() []map[string]interface{}

GetToolCalls returns the tool calls (implements loop.Message)

func (*Message) GetToolID

func (m *Message) GetToolID() string

GetToolID returns the tool ID (implements loop.Message)

func (*Message) GetToolName

func (m *Message) GetToolName() string

GetToolName returns the tool name (implements loop.Message)

type PlanningBoard

type PlanningBoard struct {
	PrimaryTasks []PlanningTask `json:"primary_tasks"`
	Description  string         `json:"description,omitempty"`
}

PlanningBoard represents a hierarchical planning board with primary tasks and subtasks

type PlanningTask

type PlanningTask struct {
	ID          string                `json:"id"`
	Text        string                `json:"text"`
	Subtasks    []PlanningTask        `json:"subtasks,omitempty"`
	Priority    string                `json:"priority,omitempty"` // "high", "medium", "low"
	Status      string                `json:"status,omitempty"`   // "pending", "in_progress", "completed"
	Description string                `json:"description,omitempty"`
	Summary     *TaskExecutionSummary `json:"summary,omitempty"` // Summary of work completed for this task
}

PlanningTask represents a task in the planning board

type QuestionAnswer

type QuestionAnswer struct {
	Question  string    `json:"question"`
	Answer    string    `json:"answer"`
	Timestamp time.Time `json:"timestamp"`
}

QuestionAnswer represents a question asked during planning and its answer

type Session

type Session struct {
	ID                        string
	Title                     string // Auto-generated title for the session
	WorkingDir                string
	Messages                  []*Message
	FilesRead                 map[string]string // path -> content
	FilesModified             map[string]bool
	BackgroundJobs            map[string]*BackgroundJob
	AuthorizedDomains         map[string]bool       // domain -> authorized (session-level)
	AuthorizedCommands        []string              // command prefixes that are authorized (session-level)
	PlanningActive            bool                  // whether planning phase is currently running
	PlanningObjective         string                // objective of current planning phase
	PlanningStartTime         time.Time             // when current planning phase started
	PlanningQuestionsAnswered []QuestionAnswer      // questions asked and answered during planning
	PlanningBoard             *PlanningBoard        // hierarchical planning board with primary tasks and subtasks
	LastSandboxExitCode       int                   // exit code from last sandbox execution
	LastSandboxStdout         string                // stdout from last sandbox execution
	LastSandboxStderr         string                // stderr from last sandbox execution
	CurrentProvider           string                // Current LLM provider for native message format
	CurrentModelFamily        string                // Current model family for native message format
	CurrentBranch             string                // Current Git branch (if in a repository)
	HasVCS                    bool                  // Whether a VCS (e.g., git) is available in the workspace
	TaskExecutionSummary      *TaskExecutionSummary // Summary of work completed in this task session

	// Verification retry tracking
	VerificationAttempt      int  // Current verification attempt number (1-3)
	VerificationInProgress   bool // Whether verification is currently running
	LastUserMessageCount     int  // User message count at start of verification
	HasQueuedUserPromptCount int  // Number of queued user prompts at start of verification

	// Cost and usage tracking (accumulated across all LLM calls in the session)
	TotalCost                float64 // Total cost in dollars (sum of all calls)
	TotalTokens              int     // Total tokens used
	TotalPromptTokens        int     // Total input/prompt tokens
	TotalCompletionTokens    int     // Total output/completion tokens
	TotalCachedTokens        int     // Total cached/read-from-cache tokens
	TotalCacheCreationTokens int     // Total cache creation tokens
	TotalCacheReadTokens     int     // Total cache read tokens

	// Shell temp directory - a random subdirectory in temp for shell command execution
	ShellTempDir string
	// SandboxOutputDir - directory for storing large sandbox output files that exceed context window limits
	SandboxOutputDir string

	CreatedAt   time.Time
	UpdatedAt   time.Time
	LastSavedAt time.Time
	Dirty       bool // true when there are unsaved changes
	// contains filtered or unexported fields
}

Session manages a conversation session

func NewSession

func NewSession(id, workingDir string) *Session

NewSession creates a new session

func (*Session) AccumulateUsage

func (s *Session) AccumulateUsage(usage map[string]interface{})

AccumulateUsage adds usage data from an LLM call to the session totals

func (*Session) AddBackgroundJob

func (s *Session) AddBackgroundJob(job *BackgroundJob)

AddBackgroundJob adds a background job

func (*Session) AddMessage

func (s *Session) AddMessage(msg *Message)

AddMessage adds a message to the session

func (*Session) AddPlanningQuestionAnswer

func (s *Session) AddPlanningQuestionAnswer(question, answer string)

AddPlanningQuestionAnswer adds a question and answer pair from the planning phase

func (*Session) AuthorizeCommand

func (s *Session) AuthorizeCommand(commandPrefix string)

AuthorizeCommand adds a command prefix to the authorized list for this session

func (*Session) AuthorizeDomain

func (s *Session) AuthorizeDomain(domain string)

AuthorizeDomain marks a domain as authorized for network access

func (*Session) CleanupShellTempDir

func (s *Session) CleanupShellTempDir()

CleanupShellTempDir removes the shell temp directory if it exists

func (*Session) Clear

func (s *Session) Clear()

Clear clears the session but keeps working directory

func (*Session) ClearPlanningQuestionsAnswered

func (s *Session) ClearPlanningQuestionsAnswered()

ClearPlanningQuestionsAnswered clears all stored planning questions and answers

func (*Session) CompactWithSummary

func (s *Session) CompactWithSummary(original []*Message, summary string) bool

CompactWithSummary replaces the oldest messages with a summary message. The original slice must correspond to the current head of the session when the compaction is applied; otherwise it will no-op and return false.

func (*Session) DecrementQueuedUserPromptCount

func (s *Session) DecrementQueuedUserPromptCount()

DecrementQueuedUserPromptCount decrements the count of queued user prompts

func (*Session) GetAuthorizedCommands

func (s *Session) GetAuthorizedCommands() []string

GetAuthorizedCommands returns a list of all authorized command prefixes

func (*Session) GetAuthorizedDomains

func (s *Session) GetAuthorizedDomains() []string

GetAuthorizedDomains returns a list of all authorized domains

func (*Session) GetBackgroundJob

func (s *Session) GetBackgroundJob(id string) (*BackgroundJob, bool)

GetBackgroundJob retrieves a background job

func (*Session) GetCurrentBranch

func (s *Session) GetCurrentBranch() string

GetCurrentBranch returns the current Git branch

func (*Session) GetCurrentProvider

func (s *Session) GetCurrentProvider() (provider, modelFamily string)

GetCurrentProvider returns the current provider/model family

func (*Session) GetFilesRead

func (s *Session) GetFilesRead() []string

GetFilesRead returns list of files that were read

func (*Session) GetHasVCS

func (s *Session) GetHasVCS() bool

GetHasVCS returns whether a VCS (e.g., git) is available in the workspace

func (*Session) GetLastSandboxOutput

func (s *Session) GetLastSandboxOutput() (exitCode int, stdout, stderr string)

GetLastSandboxOutput retrieves the output from the last sandbox execution

func (*Session) GetMessages

func (s *Session) GetMessages() []*Message

GetMessages returns all messages

func (*Session) GetModifiedFiles

func (s *Session) GetModifiedFiles() []string

GetModifiedFiles returns list of modified files

func (*Session) GetPlanningBoard

func (s *Session) GetPlanningBoard() *PlanningBoard

GetPlanningBoard returns the planning board for the current session

func (*Session) GetPlanningQuestionsAnswered

func (s *Session) GetPlanningQuestionsAnswered() []QuestionAnswer

GetPlanningQuestionsAnswered returns all questions and answers from the planning phase

func (*Session) GetPlanningStatus

func (s *Session) GetPlanningStatus() (active bool, objective string, startTime time.Time)

GetPlanningStatus returns the current planning status

func (*Session) GetQueuedUserPromptCount

func (s *Session) GetQueuedUserPromptCount() int

GetQueuedUserPromptCount returns the current count of queued user prompts

func (*Session) GetSandboxOutputDir

func (s *Session) GetSandboxOutputDir() string

GetSandboxOutputDir returns the directory for storing large sandbox output files

func (*Session) GetShellTempDir

func (s *Session) GetShellTempDir() string

GetShellTempDir returns the shell temp directory path

func (*Session) GetTaskExecutionSummary

func (s *Session) GetTaskExecutionSummary() *TaskExecutionSummary

GetTaskExecutionSummary retrieves the task execution summary from the session

func (*Session) GetTitle

func (s *Session) GetTitle() string

GetTitle returns the session title

func (*Session) GetTotalCost

func (s *Session) GetTotalCost() float64

GetTotalCost returns the total cost for the session

func (*Session) GetTotalTokens

func (s *Session) GetTotalTokens() int

GetTotalTokens returns the total tokens used in the session

func (*Session) GetUsageStats

func (s *Session) GetUsageStats() map[string]interface{}

GetUsageStats returns all usage statistics for the session

func (*Session) GetVerificationAttempt

func (s *Session) GetVerificationAttempt() int

GetVerificationAttempt returns the current verification attempt number

func (*Session) HasNewUserPrompt

func (s *Session) HasNewUserPrompt(previousCount int) bool

HasNewUserPrompt checks if a new user message was added since verification started

func (*Session) HasNewUserPromptOrQueued

func (s *Session) HasNewUserPromptOrQueued(previousCount int, previousQueuedCount int) bool

HasNewUserPromptOrQueued checks if a new user message was added or if there are queued prompts since verification started

func (*Session) IncrementQueuedUserPromptCount

func (s *Session) IncrementQueuedUserPromptCount()

IncrementQueuedUserPromptCount increments the count of queued user prompts

func (*Session) IsCommandAuthorized

func (s *Session) IsCommandAuthorized(command string) bool

IsCommandAuthorized checks if a command is authorized based on session-level authorized prefixes

func (*Session) IsDirty

func (s *Session) IsDirty() bool

IsDirty reports whether the session has unsaved changes.

func (*Session) IsDomainAuthorized

func (s *Session) IsDomainAuthorized(domain string) bool

IsDomainAuthorized checks if a domain is authorized for network access

func (*Session) IsVerificationInProgress

func (s *Session) IsVerificationInProgress() bool

IsVerificationInProgress returns whether verification is currently running

func (*Session) ListBackgroundJobs

func (s *Session) ListBackgroundJobs() []*BackgroundJob

ListBackgroundJobs returns all background jobs

func (*Session) MarkSaved

func (s *Session) MarkSaved(t time.Time)

MarkSaved updates bookkeeping after a successful save.

func (*Session) ModifyLastAssistantMessage

func (s *Session) ModifyLastAssistantMessage(modifier func(msg *Message) bool) bool

ModifyLastAssistantMessage walks messages backwards, finds the last assistant message, and applies the modifier function to it. Returns true if a message was found and modified.

func (*Session) NeedsConversion

func (s *Session) NeedsConversion(provider, modelFamily string) bool

NeedsConversion checks if messages need re-conversion for a new provider

func (*Session) ResetVerification

func (s *Session) ResetVerification()

ResetVerification resets verification tracking state

func (*Session) SetCurrentBranch

func (s *Session) SetCurrentBranch(branch string)

SetCurrentBranch sets the current Git branch

func (*Session) SetCurrentProvider

func (s *Session) SetCurrentProvider(provider, modelFamily string)

SetCurrentProvider updates the active provider/model family for native message storage

func (*Session) SetHasVCS

func (s *Session) SetHasVCS(hasVCS bool)

SetHasVCS sets whether a VCS (e.g., git) is available in the workspace

func (*Session) SetLastSandboxOutput

func (s *Session) SetLastSandboxOutput(exitCode int, stdout, stderr string)

SetLastSandboxOutput stores the output from the last sandbox execution

func (*Session) SetPlanningActive

func (s *Session) SetPlanningActive(active bool, objective string)

SetPlanningActive marks planning as active/inactive

func (*Session) SetPlanningBoard

func (s *Session) SetPlanningBoard(board *PlanningBoard)

SetPlanningBoard sets the planning board for the current session

func (*Session) SetTaskExecutionSummary

func (s *Session) SetTaskExecutionSummary(summary *TaskExecutionSummary)

SetTaskExecutionSummary stores the task execution summary in the session

func (*Session) SetTitle

func (s *Session) SetTitle(title string)

SetTitle updates the session title

func (*Session) StartVerificationAttempt

func (s *Session) StartVerificationAttempt() int

StartVerificationAttempt increments and returns the verification attempt counter

func (*Session) TrackFileModified

func (s *Session) TrackFileModified(path string)

TrackFileModified tracks that a file was modified

func (*Session) TrackFileRead

func (s *Session) TrackFileRead(path, content string)

TrackFileRead tracks that a file was read

func (*Session) UserMessageCount

func (s *Session) UserMessageCount() int

UserMessageCount returns how many user messages are present in the session.

func (*Session) WasFileRead

func (s *Session) WasFileRead(path string) bool

WasFileRead checks if a file was read in this session

type SessionMetadata

type SessionMetadata struct {
	ID           string    `json:"id"`
	Name         string    `json:"name"` // Deprecated, use Title
	Title        string    `json:"title"`
	WorkingDir   string    `json:"working_dir"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
	MessageCount int       `json:"message_count"`
}

SessionMetadata contains lightweight session information for listing

type SessionStorage

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

SessionStorage manages session persistence

func NewSessionStorage

func NewSessionStorage() (*SessionStorage, error)

NewSessionStorage creates a new SessionStorage instance

func NewSessionStorageWithConfig

func NewSessionStorageWithConfig(configFunc func() *config.AutoSaveConfig) (*SessionStorage, error)

NewSessionStorageWithConfig creates a new SessionStorage instance with auto-save configuration

func (*SessionStorage) DeleteSession

func (s *SessionStorage) DeleteSession(workingDir, sessionID string) error

DeleteSession removes a session from disk

func (*SessionStorage) FromStoredSession

func (s *SessionStorage) FromStoredSession(stored *StoredSession) *Session

FromStoredSession converts a stored session back to a runtime Session

func (*SessionStorage) GetMostRecentSession

func (s *SessionStorage) GetMostRecentSession(workingDir string) (*Session, error)

GetMostRecentSession returns the most recently updated session in a workspace

func (*SessionStorage) ListSessions

func (s *SessionStorage) ListSessions(workingDir string) ([]SessionMetadata, error)

ListSessions returns metadata for all sessions in a workspace

func (*SessionStorage) LoadSession

func (s *SessionStorage) LoadSession(workingDir, sessionID string) (*Session, error)

LoadSession loads a session from disk

func (*SessionStorage) RefreshAutoSaveConfig

func (s *SessionStorage) RefreshAutoSaveConfig() bool

RefreshAutoSaveConfig updates the auto-save configuration

func (*SessionStorage) SaveSession

func (s *SessionStorage) SaveSession(session *Session, name string) error

SaveSession saves a session to disk

func (*SessionStorage) StartAutoSave

func (s *SessionStorage) StartAutoSave(session *Session, name string)

StartAutoSave starts the automatic session saving process

func (*SessionStorage) StopAutoSave

func (s *SessionStorage) StopAutoSave()

StopAutoSave stops the automatic session saving process

func (*SessionStorage) ToStoredSession

func (s *SessionStorage) ToStoredSession(session *Session, name string) *StoredSession

ToStoredSession converts a runtime Session to a storable format

type StoredBackgroundJob

type StoredBackgroundJob struct {
	ID         string
	Command    string
	WorkingDir string
	StartTime  time.Time
	Completed  bool
	ExitCode   int
	Stdout     []string
	Stderr     []string
	Type       string
	LastSignal string
}

StoredBackgroundJob represents a background job in storage format

type StoredMessage

type StoredMessage struct {
	Role              string
	Content           string
	ToolCalls         []map[string]interface{}
	ToolID            string
	ToolName          string
	Timestamp         time.Time
	NativeFormat      interface{}
	NativeProvider    string
	NativeModelFamily string
	NativeTimestamp   time.Time
}

StoredMessage represents a message in storage format

type StoredSession

type StoredSession struct {
	Version             int
	ID                  string
	WorkingDir          string
	Name                string // Optional human-readable name (deprecated, use Title)
	Title               string // Auto-generated title for the session
	Messages            []*StoredMessage
	FilesRead           map[string]string
	FilesModified       map[string]bool
	BackgroundJobs      map[string]*StoredBackgroundJob
	AuthorizedDomains   map[string]bool
	AuthorizedCommands  []string
	PlanningActive      bool
	PlanningObjective   string
	LastSandboxExitCode int
	LastSandboxStdout   string
	LastSandboxStderr   string
	CurrentProvider     string
	CurrentModelFamily  string

	// Verification retry tracking
	VerificationAttempt    int  `json:"verification_attempt,omitempty"`
	VerificationInProgress bool `json:"verification_in_progress,omitempty"`
	LastUserMessageCount   int  `json:"last_user_message_count,omitempty"`

	CreatedAt   time.Time
	UpdatedAt   time.Time
	LastSavedAt time.Time
}

StoredSession represents a session in storage format

type TaskExecutionContext

type TaskExecutionContext struct {
	OriginalObjective string                 `json:"original_objective"`
	PreviousSummaries []TaskExecutionSummary `json:"previous_summaries,omitempty"`
	TaskIndex         int                    `json:"task_index"`
	TotalTasks        int                    `json:"total_tasks"`
}

TaskExecutionContext provides context for executing a task

type TaskExecutionSummary

type TaskExecutionSummary struct {
	TaskID        string            `json:"task_id"`
	TaskText      string            `json:"task_text"`
	Status        string            `json:"status"` // "completed", "failed", "partial"
	Summary       string            `json:"summary"`
	FilesRead     []string          `json:"files_read,omitempty"`
	FilesModified []string          `json:"files_modified,omitempty"`
	Errors        []string          `json:"errors,omitempty"`
	Timestamp     time.Time         `json:"timestamp"`
	Metadata      map[string]string `json:"metadata,omitempty"`
}

TaskExecutionSummary represents a summary of work completed during a task execution

type TitleGenerator

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

TitleGenerator generates concise titles for sessions based on conversation context

func NewTitleGenerator

func NewTitleGenerator(summarizeClient llm.Client) *TitleGenerator

NewTitleGenerator creates a new TitleGenerator

func (*TitleGenerator) GenerateTitle

func (tg *TitleGenerator) GenerateTitle(ctx context.Context, userPrompt string, workspaceFiles []string, filesRead map[string]string) (string, error)

GenerateTitle generates a concise title for a session based on the first user prompt, the list of files in the workspace, and any files that were read in the session

Jump to

Keyboard shortcuts

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