agent

package
v0.8.3 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2025 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildBaseContextJSON added in v0.8.3

func BuildBaseContextJSON() string

BuildBaseContextJSON scans the workspace and returns a minimal JSON manifest to speed up discovery. It is conservative and ignores common build/vendor directories.

func DeleteSession

func DeleteSession(sessionID string) error

DeleteSession removes a session state file

func EstimateTokens added in v0.6.0

func EstimateTokens(text string) int

EstimateTokens provides a token estimation based on OpenAI's tiktoken approach

func GetEmbeddedSystemPrompt added in v0.8.3

func GetEmbeddedSystemPrompt() string

GetEmbeddedSystemPrompt returns the embedded system prompt

func GetEmbeddedSystemPromptWithProvider added in v0.8.3

func GetEmbeddedSystemPromptWithProvider(provider string) string

GetEmbeddedSystemPromptWithProvider returns the embedded system prompt with provider-specific enhancements

func GetSessionPreview added in v0.8.3

func GetSessionPreview(sessionID string) string

GetSessionPreview returns the first 50 characters of the first user message

func GetStateDir

func GetStateDir() (string, error)

GetStateDir returns the directory for storing conversation state

func ListSessions

func ListSessions() ([]string, error)

ListSessions returns all available session IDs

func RegenerateProjectValidationContext added in v0.6.0

func RegenerateProjectValidationContext() error

RegenerateProjectValidationContext forces regeneration of validation context

Types

type APIClient added in v0.6.0

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

APIClient handles all LLM API communication with retry logic

func NewAPIClient added in v0.6.0

func NewAPIClient(agent *Agent) *APIClient

NewAPIClient creates a new API client

func (*APIClient) SendWithRetry added in v0.6.0

func (ac *APIClient) SendWithRetry(messages []api.Message, tools []api.Tool, reasoning string) (*api.ChatResponse, error)

SendWithRetry sends a request to the LLM with retry logic

type Agent

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

func NewAgent

func NewAgent() (*Agent, error)

NewAgent creates a new agent with auto-detected provider

func NewAgentWithModel

func NewAgentWithModel(model string) (*Agent, error)

NewAgentWithModel creates a new agent with optional model override

func (*Agent) AddTaskAction

func (a *Agent) AddTaskAction(actionType, description, details string)

AddTaskAction records a completed task action for continuity

func (*Agent) ApplyState

func (a *Agent) ApplyState(state *ConversationState)

ApplyState applies a loaded state to the current agent

func (*Agent) CheckForInterrupt

func (a *Agent) CheckForInterrupt() bool

CheckForInterrupt checks if an interrupt was requested

func (*Agent) ClearConversationHistory

func (a *Agent) ClearConversationHistory()

ClearConversationHistory clears the conversation history

func (*Agent) ClearInputInjectionContext added in v0.8.3

func (a *Agent) ClearInputInjectionContext()

ClearInputInjectionContext clears any pending input injections

func (*Agent) ClearInterrupt

func (a *Agent) ClearInterrupt()

ClearInterrupt resets the interrupt state

func (*Agent) ClearTrackedChanges

func (a *Agent) ClearTrackedChanges()

ClearTrackedChanges clears all tracked changes (but keeps tracking enabled)

func (*Agent) CommitChanges

func (a *Agent) CommitChanges(llmResponse string) error

CommitChanges commits all tracked changes to the change tracker

func (*Agent) DisableAutoPruning added in v0.5.5

func (a *Agent) DisableAutoPruning()

DisableAutoPruning disables automatic conversation pruning

func (*Agent) DisableChangeTracking

func (a *Agent) DisableChangeTracking()

DisableChangeTracking disables change tracking

func (*Agent) DisableEscMonitoring

func (a *Agent) DisableEscMonitoring()

DisableEscMonitoring stops monitoring for Esc key

func (*Agent) DisableStreaming added in v0.6.0

func (a *Agent) DisableStreaming()

DisableStreaming disables response streaming

func (*Agent) EnableAutoPruning added in v0.5.5

func (a *Agent) EnableAutoPruning()

EnableAutoPruning enables automatic conversation pruning with default adaptive strategy

func (*Agent) EnableChangeTracking

func (a *Agent) EnableChangeTracking(instructions string)

EnableChangeTracking enables change tracking for this agent session

func (*Agent) EnableEscMonitoring

func (a *Agent) EnableEscMonitoring()

EnableEscMonitoring starts monitoring for Esc key using context cancellation

func (*Agent) EnableStreaming added in v0.6.0

func (a *Agent) EnableStreaming(callback func(string))

EnableStreaming enables response streaming with a callback

func (*Agent) ExportState

func (a *Agent) ExportState() ([]byte, error)

ExportState exports the current agent state for persistence

func (*Agent) GenerateActionSummary

func (a *Agent) GenerateActionSummary() string

GenerateActionSummary creates a summary of completed actions for continuity

func (*Agent) GenerateCompactSummary

func (a *Agent) GenerateCompactSummary() string

GenerateCompactSummary creates a compact summary for session continuity (max 5K context)

func (*Agent) GenerateConversationSummary

func (a *Agent) GenerateConversationSummary() string

GenerateConversationSummary creates a comprehensive summary of the conversation including todos

func (*Agent) GenerateResponse

func (a *Agent) GenerateResponse(messages []api.Message) (string, error)

GenerateResponse generates a simple response using the current model without tool calls

func (*Agent) GenerateSessionSummary

func (a *Agent) GenerateSessionSummary() string

GenerateSessionSummary creates a summary of previous actions for continuity

func (*Agent) GetAverageTPS added in v0.6.0

func (a *Agent) GetAverageTPS() float64

GetAverageTPS returns the average TPS across all requests

func (*Agent) GetChangeCount

func (a *Agent) GetChangeCount() int

GetChangeCount returns the number of file changes tracked in this session

func (*Agent) GetChangeTracker

func (a *Agent) GetChangeTracker() *ChangeTracker

GetChangeTracker returns the change tracker (can be nil)

func (*Agent) GetChangesSummary

func (a *Agent) GetChangesSummary() string

GetChangesSummary returns a summary of tracked changes

func (*Agent) GetConfig

func (a *Agent) GetConfig() *configuration.Config

GetConfig returns the configuration

func (*Agent) GetConfigManager

func (a *Agent) GetConfigManager() *configuration.Manager

GetConfigManager returns the configuration manager

func (*Agent) GetCurrentContextTokens added in v0.5.5

func (a *Agent) GetCurrentContextTokens() int

GetCurrentContextTokens returns the current context token count

func (*Agent) GetCurrentIteration

func (a *Agent) GetCurrentIteration() int

GetCurrentIteration returns the current iteration number

func (*Agent) GetCurrentTPS added in v0.6.0

func (a *Agent) GetCurrentTPS() float64

GetCurrentTPS returns the current TPS value (alias for GetLastTPS)

func (*Agent) GetDebugLogPath added in v0.7.0

func (a *Agent) GetDebugLogPath() string

GetDebugLogPath returns the path to the current debug log file (if any)

func (*Agent) GetInputInjectionContext added in v0.8.3

func (a *Agent) GetInputInjectionContext() <-chan string

GetInputInjectionContext returns the input injection channel for the new system

func (*Agent) GetLastMessages added in v0.7.0

func (a *Agent) GetLastMessages(n int) []api.Message

GetLastMessages returns the last N messages for preview

func (*Agent) GetLastTPS added in v0.6.0

func (a *Agent) GetLastTPS() float64

GetLastTPS returns the most recent TPS value from the provider

func (*Agent) GetMaxContextTokens added in v0.5.5

func (a *Agent) GetMaxContextTokens() int

GetMaxContextTokens returns the maximum context tokens for the current model

func (*Agent) GetMessages

func (a *Agent) GetMessages() []api.Message

GetMessages returns the current conversation messages

func (*Agent) GetModel

func (a *Agent) GetModel() string

GetModel gets the current model being used by the agent

func (*Agent) GetOptimizationStats

func (a *Agent) GetOptimizationStats() map[string]interface{}

GetOptimizationStats returns optimization statistics

func (*Agent) GetOrBuildBaseContext added in v0.8.3

func (a *Agent) GetOrBuildBaseContext() string

GetOrBuildBaseContext returns a cached base context for the session, building it once if needed.

func (*Agent) GetPreviousSummary

func (a *Agent) GetPreviousSummary() string

GetPreviousSummary returns the summary of previous actions

func (*Agent) GetProvider

func (a *Agent) GetProvider() string

GetProvider returns the current provider name

func (*Agent) GetProviderType

func (a *Agent) GetProviderType() api.ClientType

GetProviderType returns the current provider type

func (*Agent) GetPruningStats added in v0.5.5

func (a *Agent) GetPruningStats() map[string]interface{}

GetPruningStats returns information about the current pruning configuration

func (*Agent) GetRevisionID

func (a *Agent) GetRevisionID() string

GetRevisionID returns the current revision ID (if change tracking is enabled)

func (*Agent) GetSessionID

func (a *Agent) GetSessionID() string

GetSessionID returns the session identifier

func (*Agent) GetSystemPrompt added in v0.6.0

func (a *Agent) GetSystemPrompt() string

GetSystemPrompt returns the current system prompt

func (*Agent) GetTPSStats added in v0.6.0

func (a *Agent) GetTPSStats() map[string]float64

GetTPSStats returns comprehensive TPS statistics

func (*Agent) GetTaskActions added in v0.6.0

func (a *Agent) GetTaskActions() []TaskAction

GetTaskActions returns completed task actions

func (*Agent) GetTotalCost

func (a *Agent) GetTotalCost() float64

GetTotalCost returns the total cost of the conversation

func (*Agent) GetTotalTokens

func (a *Agent) GetTotalTokens() int

GetTotalTokens returns the total tokens used across all requests

func (*Agent) GetTrackedFiles

func (a *Agent) GetTrackedFiles() []string

GetTrackedFiles returns the list of files that have been modified in this session

func (*Agent) HandleInterrupt

func (a *Agent) HandleInterrupt() string

HandleInterrupt processes the interrupt request

func (*Agent) ImportState

func (a *Agent) ImportState(data []byte) error

ImportState imports agent state from JSON data

func (*Agent) InjectInputContext added in v0.8.3

func (a *Agent) InjectInputContext(input string) error

InjectInputContext injects a new user input using context-based interrupt system

func (*Agent) IsChangeTrackingEnabled

func (a *Agent) IsChangeTrackingEnabled() bool

IsChangeTrackingEnabled returns whether change tracking is enabled

func (*Agent) IsInteractiveMode added in v0.5.5

func (a *Agent) IsInteractiveMode() bool

IsInteractiveMode returns true if running in interactive mode

func (*Agent) IsInterrupted added in v0.7.0

func (a *Agent) IsInterrupted() bool

IsInterrupted returns true if an interrupt has been requested

func (*Agent) LoadState

func (a *Agent) LoadState(sessionID string) (*ConversationState, error)

LoadState loads a conversation state by session ID

func (*Agent) LoadStateFromFile

func (a *Agent) LoadStateFromFile(filename string) error

LoadStateFromFile loads agent state from a file

func (*Agent) LoadSummaryFromFile

func (a *Agent) LoadSummaryFromFile(filename string) error

LoadSummaryFromFile loads ONLY the compact summary from a state file for minimal continuity

func (*Agent) LogToolCall added in v0.7.0

func (a *Agent) LogToolCall(tc api.ToolCall, phase string)

LogToolCall appends a JSON line describing a tool call to a local file for quick debugging. File: ./tool_calls.log (in the current working directory)

func (*Agent) PrintCompactProgress added in v0.5.5

func (a *Agent) PrintCompactProgress()

PrintCompactProgress prints a minimal progress indicator for non-interactive mode Format: [iteration:(current-context-tokens/context-limit) | total-tokens | cost]

func (*Agent) PrintConciseSummary

func (a *Agent) PrintConciseSummary()

PrintConciseSummary displays a single line with essential token and cost information

func (*Agent) PrintConversationSummary

func (a *Agent) PrintConversationSummary(forceFull bool)

PrintConversationSummary displays a comprehensive conversation summary with formatting

func (*Agent) PrintLine added in v0.7.0

func (a *Agent) PrintLine(text string)

PrintLine prints a line of text to the console content area synchronously. It delegates to the internal renderer that handles streaming vs CLI output.

func (*Agent) PrintLineAsync added in v0.8.3

func (a *Agent) PrintLineAsync(text string)

PrintLineAsync enqueues a line for asynchronous output. Background goroutines (rate-limit handlers, streaming workers, etc.) should prefer this helper to avoid blocking on the UI mutex. If the queue is saturated, we fall back to bounded waiting and finally synchronous printing to avoid goroutine leaks while still preserving message ordering as much as possible.

func (*Agent) ProcessQuery

func (a *Agent) ProcessQuery(userQuery string) (string, error)

ProcessQuery handles the main conversation loop with the LLM

func (*Agent) ProcessQueryRefactored added in v0.6.0

func (a *Agent) ProcessQueryRefactored(userQuery string) (string, error)

ProcessQueryRefactored is the cleaned up version of ProcessQuery

func (*Agent) ProcessQueryWithContinuity

func (a *Agent) ProcessQueryWithContinuity(userQuery string) (string, error)

ProcessQueryWithContinuity processes a query with continuity from previous actions

func (*Agent) PromptChoice added in v0.7.0

func (a *Agent) PromptChoice(prompt string, choices []ChoiceOption) (string, error)

PromptChoice shows a dropdown selection of simple choices and returns the selected value

func (*Agent) RefreshMCPTools added in v0.6.0

func (a *Agent) RefreshMCPTools() error

RefreshMCPTools refreshes the MCP tools cache

func (*Agent) SaveConversationSummary

func (a *Agent) SaveConversationSummary() error

SaveConversationSummary saves the conversation summary to the state file

func (*Agent) SaveState

func (a *Agent) SaveState(sessionID string) error

SaveState saves the current conversation state

func (*Agent) SaveStateToFile

func (a *Agent) SaveStateToFile(filename string) error

SaveStateToFile saves the agent state to a file

func (*Agent) SelectProvider added in v0.6.0

func (a *Agent) SelectProvider() error

SelectProvider allows interactive provider selection

func (*Agent) SetConversationOptimization

func (a *Agent) SetConversationOptimization(enabled bool)

SetConversationOptimization enables or disables conversation optimization

func (*Agent) SetDebug added in v0.6.0

func (a *Agent) SetDebug(debug bool)

SetDebug enables or disables debug mode

func (*Agent) SetFlushCallback added in v0.6.0

func (a *Agent) SetFlushCallback(callback func())

SetFlushCallback sets a callback to flush buffered output

func (*Agent) SetInterruptHandler added in v0.6.0

func (a *Agent) SetInterruptHandler(ch chan struct{})

SetInterruptHandler sets the interrupt handler for UI mode

func (*Agent) SetMaxIterations added in v0.5.10

func (a *Agent) SetMaxIterations(max int)

SetMaxIterations sets the maximum number of iterations for the agent

func (*Agent) SetMessages added in v0.6.0

func (a *Agent) SetMessages(messages []api.Message)

SetMessages sets the conversation messages (for restore)

func (*Agent) SetModel

func (a *Agent) SetModel(model string) error

SetModel changes the current model and persists the choice

func (*Agent) SetOutputMutex

func (a *Agent) SetOutputMutex(mutex *sync.Mutex)

SetOutputMutex sets the output mutex for synchronized output

func (*Agent) SetPreviousSummary

func (a *Agent) SetPreviousSummary(summary string)

SetPreviousSummary sets the summary of previous actions for continuity

func (*Agent) SetProvider added in v0.6.0

func (a *Agent) SetProvider(provider api.ClientType) error

SetProvider switches to a specific provider with its default or current model

func (*Agent) SetPruningSlidingWindowSize added in v0.5.5

func (a *Agent) SetPruningSlidingWindowSize(size int)

SetPruningSlidingWindowSize sets the sliding window size for the sliding window strategy

func (*Agent) SetPruningStrategy added in v0.5.5

func (a *Agent) SetPruningStrategy(strategy PruningStrategy)

SetPruningStrategy sets the conversation pruning strategy

func (*Agent) SetPruningThreshold added in v0.5.5

func (a *Agent) SetPruningThreshold(threshold float64)

SetPruningThreshold sets the context usage threshold for triggering automatic pruning threshold should be between 0 and 1 (e.g., 0.7 = 70%)

func (*Agent) SetRecentMessagesToKeep added in v0.5.5

func (a *Agent) SetRecentMessagesToKeep(count int)

SetRecentMessagesToKeep sets how many recent messages to always preserve

func (*Agent) SetSessionID

func (a *Agent) SetSessionID(sessionID string)

SetSessionID sets the session identifier for continuity

func (*Agent) SetStatsUpdateCallback

func (a *Agent) SetStatsUpdateCallback(callback func(int, float64))

SetStatsUpdateCallback sets a callback for token/cost updates

func (*Agent) SetStreamingCallback added in v0.6.0

func (a *Agent) SetStreamingCallback(callback func(string))

SetStreamingCallback sets a custom callback for streaming output

func (*Agent) SetStreamingEnabled added in v0.6.0

func (a *Agent) SetStreamingEnabled(enabled bool)

SetStreamingEnabled enables or disables streaming responses

func (*Agent) SetSystemPrompt added in v0.6.0

func (a *Agent) SetSystemPrompt(prompt string)

SetSystemPrompt sets the system prompt for the agent

func (*Agent) SetSystemPromptFromFile added in v0.6.0

func (a *Agent) SetSystemPromptFromFile(filePath string) error

SetSystemPromptFromFile loads a custom system prompt from a file

func (*Agent) SetUI added in v0.7.0

func (a *Agent) SetUI(ui UI)

SetUI sets the UI provider for the agent

func (*Agent) ShowColoredDiff

func (a *Agent) ShowColoredDiff(oldContent, newContent string, maxLines int)

ShowColoredDiff displays a colored diff between old and new content, focusing on actual changes Uses Python's difflib for better diff quality when available, falls back to Go implementation

func (*Agent) ShowDropdown added in v0.7.0

func (a *Agent) ShowDropdown(items []ui.DropdownItem, options ui.DropdownOptions) (ui.DropdownItem, error)

ShowDropdown shows a dropdown if UI is available

func (*Agent) ShowQuickPrompt added in v0.7.0

func (a *Agent) ShowQuickPrompt(prompt string, options []ui.QuickOption, horizontal bool) (ui.QuickOption, error)

ShowQuickPrompt shows a quick prompt if UI is available

func (*Agent) Shutdown added in v0.8.3

func (a *Agent) Shutdown()

Shutdown attempts to gracefully stop background work and child processes (e.g., MCP servers), and releases resources. It is safe to call multiple times.

func (*Agent) ToolLog

func (a *Agent) ToolLog(action, target string)

ToolLog logs tool execution messages that are always visible with blue formatting

func (*Agent) TrackFileEdit

func (a *Agent) TrackFileEdit(filePath string, originalContent string, newContent string) error

TrackFileEdit is called by the EditFile tool to track file edits

func (*Agent) TrackFileWrite

func (a *Agent) TrackFileWrite(filePath string, content string) error

TrackFileWrite is called by the WriteFile tool to track file writes

type AgentState

type AgentState struct {
	Messages        []api.Message `json:"messages"`
	PreviousSummary string        `json:"previous_summary"`
	CompactSummary  string        `json:"compact_summary"` // New: 5K limit summary for continuity
	TaskActions     []TaskAction  `json:"task_actions"`
	SessionID       string        `json:"session_id"`
}

AgentState represents the state of an agent that can be persisted

type ChangeTracker

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

ChangeTracker manages change tracking for the agent workflow

func NewChangeTracker

func NewChangeTracker(agent *Agent, instructions string) *ChangeTracker

NewChangeTracker creates a new change tracker for an agent session

func (*ChangeTracker) Clear

func (ct *ChangeTracker) Clear()

Clear clears all tracked changes (but keeps the tracker enabled)

func (*ChangeTracker) Commit

func (ct *ChangeTracker) Commit(llmResponse string) error

Commit commits all tracked changes to the change tracker

func (*ChangeTracker) Disable

func (ct *ChangeTracker) Disable()

Disable disables change tracking

func (*ChangeTracker) Enable

func (ct *ChangeTracker) Enable()

Enable enables change tracking

func (*ChangeTracker) GenerateAISummary

func (ct *ChangeTracker) GenerateAISummary() (string, error)

GenerateAISummary creates an AI-generated summary of the changes

func (*ChangeTracker) GetChangeCount

func (ct *ChangeTracker) GetChangeCount() int

GetChangeCount returns the number of tracked changes

func (*ChangeTracker) GetChanges

func (ct *ChangeTracker) GetChanges() []TrackedFileChange

GetChanges returns a copy of the tracked changes

func (*ChangeTracker) GetRevisionID

func (ct *ChangeTracker) GetRevisionID() string

GetRevisionID returns the current revision ID

func (*ChangeTracker) GetSummary

func (ct *ChangeTracker) GetSummary() string

GetSummary returns a summary of tracked changes

func (*ChangeTracker) GetTrackedFiles

func (ct *ChangeTracker) GetTrackedFiles() []string

GetTrackedFiles returns a list of files that have been modified

func (*ChangeTracker) IsEnabled

func (ct *ChangeTracker) IsEnabled() bool

IsEnabled returns whether change tracking is enabled

func (*ChangeTracker) Reset

func (ct *ChangeTracker) Reset(instructions string)

Reset resets the change tracker with a new revision ID and instructions

func (*ChangeTracker) TrackFileEdit

func (ct *ChangeTracker) TrackFileEdit(filePath string, originalContent string, newContent string) error

TrackFileEdit tracks an edit operation (EditFile tool)

func (*ChangeTracker) TrackFileWrite

func (ct *ChangeTracker) TrackFileWrite(filePath string, newContent string) error

TrackFileWrite tracks a write operation (WriteFile tool)

type ChoiceOption added in v0.7.0

type ChoiceOption struct {
	Label string
	Value string
}

ChoiceOption represents a simple label/value option for UI prompts

type CircuitBreakerAction

type CircuitBreakerAction struct {
	ActionType string // "edit_file", "shell_command", etc.
	Target     string // file path, command, etc.
	Count      int    // number of times this action was performed
	LastUsed   int64  // unix timestamp of last use
}

CircuitBreakerAction tracks repetitive actions for circuit breaker logic

type CircuitBreakerState

type CircuitBreakerState struct {
	Actions map[string]*CircuitBreakerAction // key: actionType:target
}

CircuitBreakerState tracks repetitive actions across the session

type CompletionContextSummarizer added in v0.8.3

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

CompletionContextSummarizer handles aggressive summarization at completion time to prevent context contamination in follow-up questions

func NewCompletionContextSummarizer added in v0.8.3

func NewCompletionContextSummarizer(debug bool) *CompletionContextSummarizer

NewCompletionContextSummarizer creates a new summarizer with default settings

func (*CompletionContextSummarizer) ApplyCompletionSummarization added in v0.8.3

func (ccs *CompletionContextSummarizer) ApplyCompletionSummarization(messages []api.Message) []api.Message

ApplyCompletionSummarization replaces detailed execution logs with compact summaries to prevent context contamination in follow-up questions

func (*CompletionContextSummarizer) CreateCompletionSummary added in v0.8.3

func (ccs *CompletionContextSummarizer) CreateCompletionSummary(messages []api.Message) string

CreateCompletionSummary generates a compact summary of completed work that preserves continuity while eliminating execution baggage

func (*CompletionContextSummarizer) ShouldApplySummarization added in v0.8.3

func (ccs *CompletionContextSummarizer) ShouldApplySummarization(messages []api.Message) bool

ShouldApplySummarization determines if summarization should be applied

type ConversationHandler added in v0.6.0

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

ConversationHandler manages the high-level conversation flow

func NewConversationHandler added in v0.6.0

func NewConversationHandler(agent *Agent) *ConversationHandler

NewConversationHandler creates a new conversation handler

func (*ConversationHandler) ProcessQuery added in v0.6.0

func (ch *ConversationHandler) ProcessQuery(userQuery string) (string, error)

ProcessQuery handles a user query through the complete conversation flow

type ConversationOptimizer

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

ConversationOptimizer manages conversation history optimization

func NewConversationOptimizer

func NewConversationOptimizer(enabled bool, debug bool) *ConversationOptimizer

NewConversationOptimizer creates a new conversation optimizer

func (*ConversationOptimizer) AggressiveOptimization

func (co *ConversationOptimizer) AggressiveOptimization(messages []api.Message) []api.Message

AggressiveOptimization performs more aggressive optimization when approaching context limits

func (*ConversationOptimizer) GetOptimizationStats

func (co *ConversationOptimizer) GetOptimizationStats() map[string]interface{}

GetOptimizationStats returns statistics about optimization

func (*ConversationOptimizer) IsEnabled

func (co *ConversationOptimizer) IsEnabled() bool

IsEnabled returns whether optimization is enabled

func (*ConversationOptimizer) OptimizeConversation

func (co *ConversationOptimizer) OptimizeConversation(messages []api.Message) []api.Message

OptimizeConversation optimizes the conversation history by removing redundant content

func (*ConversationOptimizer) Reset

func (co *ConversationOptimizer) Reset()

Reset clears all optimization state

func (*ConversationOptimizer) SetEnabled

func (co *ConversationOptimizer) SetEnabled(enabled bool)

SetEnabled enables or disables optimization

type ConversationPruner added in v0.5.5

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

ConversationPruner handles automatic conversation pruning

func NewConversationPruner added in v0.5.5

func NewConversationPruner(debug bool) *ConversationPruner

NewConversationPruner creates a new conversation pruner with default settings

func (*ConversationPruner) PruneConversation added in v0.5.5

func (cp *ConversationPruner) PruneConversation(messages []api.Message, currentTokens, maxTokens int, optimizer *ConversationOptimizer, provider string) []api.Message

PruneConversation automatically prunes conversation based on strategy

func (*ConversationPruner) SetRecentMessagesToKeep added in v0.5.5

func (cp *ConversationPruner) SetRecentMessagesToKeep(count int)

SetRecentMessagesToKeep sets how many recent messages to always preserve

func (*ConversationPruner) SetSlidingWindowSize added in v0.5.5

func (cp *ConversationPruner) SetSlidingWindowSize(size int)

SetSlidingWindowSize sets the window size for sliding window strategy

func (*ConversationPruner) SetStrategy added in v0.5.5

func (cp *ConversationPruner) SetStrategy(strategy PruningStrategy)

SetStrategy sets the pruning strategy

func (*ConversationPruner) SetThreshold added in v0.5.5

func (cp *ConversationPruner) SetThreshold(threshold float64)

SetThreshold sets the context usage threshold for triggering pruning

func (*ConversationPruner) ShouldPrune added in v0.5.5

func (cp *ConversationPruner) ShouldPrune(currentTokens, maxTokens int, provider string) bool

ShouldPrune checks if pruning should occur based on context usage Default behavior: Hybrid approach (70K tokens OR 70% of context limit) For providers with significant cached-token discounts (e.g., OpenAI) use an alternative policy: allow the context to grow until the remaining tokens are within min(20k, 20% of max) then prune.

type ConversationState

type ConversationState struct {
	Messages          []api.Message `json:"messages"`
	TaskActions       []TaskAction  `json:"task_actions"`
	TotalCost         float64       `json:"total_cost"`
	TotalTokens       int           `json:"total_tokens"`
	PromptTokens      int           `json:"prompt_tokens"`
	CompletionTokens  int           `json:"completion_tokens"`
	CachedTokens      int           `json:"cached_tokens"`
	CachedCostSavings float64       `json:"cached_cost_savings"`
	LastUpdated       time.Time     `json:"last_updated"`
	SessionID         string        `json:"session_id"`
}

ConversationState represents the state of a conversation that can be persisted

func LoadSessionInfo added in v0.6.0

func LoadSessionInfo(sessionID string) (*ConversationState, error)

LoadSessionInfo loads session information including timestamp

type DiffChange

type DiffChange struct {
	OldStart  int
	OldLength int
	NewStart  int
	NewLength int
}

DiffChange represents a change region in the diff

type ErrorHandler added in v0.6.0

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

ErrorHandler handles API errors and failures

func NewErrorHandler added in v0.6.0

func NewErrorHandler(agent *Agent) *ErrorHandler

NewErrorHandler creates a new error handler

func (*ErrorHandler) HandleAPIFailure added in v0.6.0

func (eh *ErrorHandler) HandleAPIFailure(apiErr error, messages []api.Message) (string, error)

HandleAPIFailure handles API failures appropriately based on context

type FallbackParseResult added in v0.8.3

type FallbackParseResult struct {
	ToolCalls      []api.ToolCall
	CleanedContent string
}

FallbackParseResult captures the tool calls that were parsed from content along with cleaned content

type FallbackParser added in v0.8.3

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

FallbackParser handles parsing tool calls from content when they should have been structured tool_calls

func NewFallbackParser added in v0.8.3

func NewFallbackParser(agent *Agent) *FallbackParser

NewFallbackParser creates a new fallback parser

func (*FallbackParser) Parse added in v0.8.3

func (fp *FallbackParser) Parse(content string) *FallbackParseResult

Parse attempts to extract tool calls from content and returns both the calls and cleaned content

func (*FallbackParser) ShouldUseFallback added in v0.8.3

func (fp *FallbackParser) ShouldUseFallback(content string, hasStructuredToolCalls bool) bool

ShouldUseFallback checks if fallback parsing should be attempted

type FileReadRecord

type FileReadRecord struct {
	FilePath     string
	Content      string
	ContentHash  string
	Timestamp    time.Time
	MessageIndex int
}

FileReadRecord tracks file reads to detect redundancy

type MessageImportance added in v0.5.5

type MessageImportance struct {
	Index           int
	Role            string
	IsUserQuery     bool
	HasToolCalls    bool
	IsToolResult    bool
	IsError         bool
	ContentLength   int
	TokenEstimate   int
	Age             int // How many messages ago
	ImportanceScore float64
}

MessageImportance tracks the importance of a message

type MessageSender added in v0.6.0

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

MessageSender handles sending messages to the LLM with retry logic

func NewMessageSender added in v0.6.0

func NewMessageSender(agent *Agent) *MessageSender

NewMessageSender creates a new message sender

func (*MessageSender) SendMessage added in v0.6.0

func (ms *MessageSender) SendMessage(messages []api.Message, tools []api.Tool, reasoning string) (*api.ChatResponse, error)

SendMessage sends a message to the LLM with retry logic

type OutputBuffer

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

OutputBuffer captures agent output for controlled display

func NewOutputBuffer

func NewOutputBuffer() *OutputBuffer

NewOutputBuffer creates a new output buffer

func (*OutputBuffer) Clear

func (ob *OutputBuffer) Clear()

Clear clears the buffer

func (*OutputBuffer) GetAndClear

func (ob *OutputBuffer) GetAndClear() string

GetAndClear returns the output and clears the buffer

func (*OutputBuffer) GetOutput

func (ob *OutputBuffer) GetOutput() string

GetOutput returns the captured output

func (*OutputBuffer) Print

func (ob *OutputBuffer) Print(args ...interface{})

Print captures output

func (*OutputBuffer) Printf

func (ob *OutputBuffer) Printf(format string, args ...interface{})

Printf captures formatted output

func (*OutputBuffer) Println

func (ob *OutputBuffer) Println(args ...interface{})

Println captures output with newline

type ParameterConfig

type ParameterConfig struct {
	Name         string   `json:"name"`
	Type         string   `json:"type"` // "string", "int", "float64", "bool"
	Required     bool     `json:"required"`
	Alternatives []string `json:"alternatives"` // Alternative parameter names for backward compatibility
	Description  string   `json:"description"`
}

ParameterConfig defines parameter validation rules for a tool

type ProjectValidationContext added in v0.6.0

type ProjectValidationContext struct {
	BuildCommands     []string `json:"build_commands"`
	LintCommands      []string `json:"lint_commands"`
	TypeCheckCommands []string `json:"typecheck_commands"`
	TestCommands      []string `json:"test_commands"`
	PreCommitChecks   []string `json:"precommit_checks"`
}

ProjectValidationContext contains project-specific validation instructions

type PruningStrategy added in v0.5.5

type PruningStrategy string

PruningStrategy defines different pruning approaches

const (
	PruneStrategyNone          PruningStrategy = "none"
	PruneStrategySlidingWindow PruningStrategy = "sliding_window"
	PruneStrategyImportance    PruningStrategy = "importance"
	PruneStrategyHybrid        PruningStrategy = "hybrid"
	PruneStrategyAdaptive      PruningStrategy = "adaptive"
)

type RateLimitExceededError added in v0.8.3

type RateLimitExceededError struct {
	Attempts  int
	LastError error
}

RateLimitExceededError indicates repeated rate limit failures even after retries

func (*RateLimitExceededError) Error added in v0.8.3

func (e *RateLimitExceededError) Error() string

func (*RateLimitExceededError) Unwrap added in v0.8.3

func (e *RateLimitExceededError) Unwrap() error

type ResponseValidator added in v0.6.0

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

ResponseValidator validates LLM responses for completeness and quality

func NewResponseValidator added in v0.6.0

func NewResponseValidator(agent *Agent) *ResponseValidator

NewResponseValidator creates a new response validator

func (*ResponseValidator) IsComplete added in v0.6.0

func (rv *ResponseValidator) IsComplete(content string) bool

IsComplete checks if a response explicitly indicates completion

func (*ResponseValidator) IsIncomplete added in v0.6.0

func (rv *ResponseValidator) IsIncomplete(content string) bool

IsIncomplete checks if a response appears to be incomplete

func (*ResponseValidator) ValidateToolCalls added in v0.6.0

func (rv *ResponseValidator) ValidateToolCalls(content string) bool

ValidateToolCalls checks if tool calls in content are valid

type SessionInfo added in v0.6.0

type SessionInfo struct {
	SessionID   string    `json:"session_id"`
	LastUpdated time.Time `json:"last_updated"`
}

SessionInfo represents session information with timestamp

func ListSessionsWithTimestamps added in v0.6.0

func ListSessionsWithTimestamps() ([]SessionInfo, error)

ListSessionsWithTimestamps returns all available session IDs with their last updated timestamps

type ShellCommandRecord

type ShellCommandRecord struct {
	Command      string
	Output       string
	OutputHash   string
	Timestamp    time.Time
	MessageIndex int
	IsTransient  bool // Commands like ls, find that become less relevant over time
}

ShellCommandRecord tracks shell commands to detect redundancy

type ShellCommandResult

type ShellCommandResult struct {
	Command         string // The command that was run
	FullOutput      string // Complete output (for future reference)
	TruncatedOutput string // Truncated output (what was shown)
	Error           error  // Any error that occurred
	ExecutedAt      int64  // Unix timestamp
	MessageIndex    int    // Index in messages array where this result appears
	WasTruncated    bool   // Whether output was truncated
	FullOutputPath  string // Optional path to the saved full output
	TruncatedTokens int    // Number of tokens omitted from the middle section
	TruncatedLines  int    // Approximate number of lines omitted from the middle
}

ShellCommandResult tracks shell command execution for deduplication

type TaskAction

type TaskAction struct {
	Type        string // "file_created", "file_modified", "command_executed", "file_read"
	Description string // Human-readable description
	Details     string // Additional details like file path, command, etc.
}

TaskAction represents a completed action during task execution

type Theme added in v0.7.0

type Theme struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Colors      struct {
		Success   string `json:"success"`
		Warning   string `json:"warning"`
		Error     string `json:"error"`
		Info      string `json:"info"`
		Primary   string `json:"primary"`
		Secondary string `json:"secondary"`
		Accent    string `json:"accent"`
	} `json:"colors"`
}

Theme represents a color theme configuration

type ThemeManager added in v0.7.0

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

ThemeManager manages color themes

func NewThemeManager added in v0.7.0

func NewThemeManager() *ThemeManager

NewThemeManager creates a new theme manager with default theme

func (*ThemeManager) GetColor added in v0.7.0

func (tm *ThemeManager) GetColor(name string) string

GetColor returns a color by name

func (*ThemeManager) GetTheme added in v0.7.0

func (tm *ThemeManager) GetTheme() Theme

GetTheme returns the current theme

func (*ThemeManager) LoadDefaultTheme added in v0.7.0

func (tm *ThemeManager) LoadDefaultTheme()

LoadDefaultTheme loads the default theme

func (*ThemeManager) LoadThemeFromFile added in v0.7.0

func (tm *ThemeManager) LoadThemeFromFile(themePath string) error

LoadThemeFromFile loads a theme from a JSON file

type ToolConfig

type ToolConfig struct {
	Name        string            `json:"name"`
	Description string            `json:"description"`
	Parameters  []ParameterConfig `json:"parameters"`
	Handler     ToolHandler       `json:"-"` // Function reference, not serialized
}

ToolConfig holds configuration for a tool

type ToolExecutor added in v0.6.0

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

ToolExecutor handles tool execution logic

func NewToolExecutor added in v0.6.0

func NewToolExecutor(agent *Agent) *ToolExecutor

NewToolExecutor creates a new tool executor

func (*ToolExecutor) ExecuteTools added in v0.6.0

func (te *ToolExecutor) ExecuteTools(toolCalls []api.ToolCall) []api.Message

ExecuteTools executes a list of tool calls and returns the results

type ToolHandler

type ToolHandler func(ctx context.Context, a *Agent, args map[string]interface{}) (string, error)

ToolHandler represents a function that can handle a tool execution

type ToolRegistry

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

ToolRegistry manages tool configurations in a data-driven way

func GetToolRegistry

func GetToolRegistry() *ToolRegistry

GetToolRegistry returns the default tool registry

func (*ToolRegistry) ExecuteTool

func (r *ToolRegistry) ExecuteTool(ctx context.Context, toolName string, args map[string]interface{}, agent *Agent) (string, error)

ExecuteTool executes a tool with standardized parameter validation and error handling

func (*ToolRegistry) GetAvailableTools

func (r *ToolRegistry) GetAvailableTools() []string

GetAvailableTools returns a list of all registered tool names

func (*ToolRegistry) RegisterTool

func (r *ToolRegistry) RegisterTool(config ToolConfig)

RegisterTool adds a tool to the registry

type TrackedFileChange

type TrackedFileChange struct {
	FilePath     string    `json:"file_path"`
	OriginalCode string    `json:"original_code"`
	NewCode      string    `json:"new_code"`
	Operation    string    `json:"operation"` // "write", "edit", "create"
	Timestamp    time.Time `json:"timestamp"`
	ToolCall     string    `json:"tool_call"` // Which tool was used
}

TrackedFileChange represents a file change made during agent execution

type UI added in v0.7.0

type UI interface {
	// ShowDropdown displays a dropdown selection UI
	ShowDropdown(ctx context.Context, items []ui.DropdownItem, options ui.DropdownOptions) (ui.DropdownItem, error)

	// ShowQuickPrompt shows a small prompt with quick choices
	ShowQuickPrompt(ctx context.Context, prompt string, options []ui.QuickOption, horizontal bool) (ui.QuickOption, error)

	// IsInteractive returns true if UI is available
	IsInteractive() bool
}

UI provides UI capabilities to the agent

Jump to

Keyboard shortcuts

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