Documentation
¶
Overview ¶
Package context provides context window monitoring for AI agent orchestration. compact.go implements graceful degradation strategies before rotation.
Package context provides context window monitoring for AI agent orchestration. handoff_trigger.go implements proactive handoff generation before context compaction.
This implements the "Compound, Don't Compact" philosophy: instead of losing information through compaction, we generate handoffs to preserve context that can be passed to a new session.
Package context provides context window monitoring for AI agent orchestration. history.go implements rotation history and audit logging.
Package context provides context window monitoring for AI agent orchestration. monitor.go implements multi-source estimation of context window usage.
Package context provides context pack building for agent task assignment.
Package context provides context window monitoring for AI agent orchestration. pending.go implements persistent storage for pending rotation confirmations.
Package context provides context window monitoring for AI agent orchestration. predictor.go implements context window exhaustion prediction based on token velocity.
Package context provides context window monitoring for AI agent orchestration. rotation.go implements seamless agent rotation when context window is exhausted.
Package context provides context window monitoring for AI agent orchestration. summary.go implements handoff summary generation for context window rotation.
Package context provides context window monitoring for AI agent orchestration. trigger.go implements proactive compaction triggering based on prediction thresholds.
Index ¶
- Constants
- Variables
- func AddPendingRotation(pending *PendingRotation) error
- func EstimateTokens(chars int) int64
- func GetContextLimit(model string) int64
- func ParseTokenCount(text string) (int64, bool)
- func PendingRotationStoragePath() string
- func RecordRotation(record *RotationRecord) error
- func RemovePendingRotation(agentID string) error
- func RotationHistoryStoragePath() string
- type AgentCapabilities
- type AgentContextInfo
- type BudgetAllocation
- type BuildOptions
- type CompactionCommand
- type CompactionMethod
- type CompactionResult
- type CompactionState
- type CompactionStatus
- type CompactionTrigger
- func (t *CompactionTrigger) GetCompactionStatus() map[string]CompactionStatus
- func (t *CompactionTrigger) SetCompactionCompleteHandler(handler func(CompactionTriggerEvent))
- func (t *CompactionTrigger) SetCompactionTriggeredHandler(handler func(CompactionTriggerEvent))
- func (t *CompactionTrigger) Start()
- func (t *CompactionTrigger) Stop()
- func (t *CompactionTrigger) TriggerCompactionNow(agentID string) (*CompactionResult, error)
- type CompactionTriggerConfig
- type CompactionTriggerEvent
- type Compactor
- func (c *Compactor) EvaluateCompactionResult(before, after *ContextEstimate) *CompactionResult
- func (c *Compactor) FinishCompaction(state *CompactionState) (*CompactionResult, error)
- func (c *Compactor) GenerateCompactionPrompt() string
- func (c *Compactor) GetCompactionCommands(agentType string) []CompactionCommand
- func (c *Compactor) NewCompactionState(agentID string) (*CompactionState, error)
- func (c *Compactor) PreRotationCheck(agentID string, rotateThreshold float64, ...) (shouldRotate bool, reason string)
- func (c *Compactor) ShouldTryCompaction(agentID string, warningThreshold float64) (bool, string)
- type CompactorConfig
- type ConfirmAction
- type ContextEstimate
- type ContextEstimator
- type ContextMonitor
- func (m *ContextMonitor) AgentsAboveThreshold(threshold float64) []AgentContextInfo
- func (m *ContextMonitor) Clear()
- func (m *ContextMonitor) Count() int
- func (m *ContextMonitor) GetAllEstimates() map[string]*ContextEstimate
- func (m *ContextMonitor) GetEstimate(agentID string) *ContextEstimate
- func (m *ContextMonitor) GetState(agentID string) *ContextState
- func (m *ContextMonitor) RecordMessage(agentID string, inputTokens, outputTokens int64)
- func (m *ContextMonitor) RegisterAgent(agentID, paneID, model string) *ContextState
- func (m *ContextMonitor) RegisterAgentWithTranscript(agentID, paneID, model, agentType, sessionName, transcriptPath string) *ContextState
- func (m *ContextMonitor) ResetAgent(agentID string)
- func (m *ContextMonitor) SetAgentType(agentID, agentType string)
- func (m *ContextMonitor) ShouldTriggerHandoff(agentID string, predictor *ContextPredictor) *HandoffRecommendation
- func (m *ContextMonitor) UnregisterAgent(agentID string)
- func (m *ContextMonitor) UpdateFromRobotMode(agentID, output string)
- func (m *ContextMonitor) UpdateFromTranscript(agentID string) (int64, error)
- type ContextPackBuilder
- type ContextPackFull
- type ContextPredictor
- func (p *ContextPredictor) AddSample(tokens int64)
- func (p *ContextPredictor) AddSampleAt(tokens int64, timestamp time.Time)
- func (p *ContextPredictor) LatestSample() *TokenSample
- func (p *ContextPredictor) PredictExhaustion(modelLimit int64) *Prediction
- func (p *ContextPredictor) Reset()
- func (p *ContextPredictor) SampleCount() int
- func (p *ContextPredictor) VelocityTrend() (velocity float64, accelerating bool)
- type ContextState
- type CumulativeTokenEstimator
- type DefaultPaneSpawner
- func (s *DefaultPaneSpawner) GetPanes(session string) ([]tmux.Pane, error)
- func (s *DefaultPaneSpawner) KillPane(paneID string) error
- func (s *DefaultPaneSpawner) SendKeys(paneID, text string, enter bool) error
- func (s *DefaultPaneSpawner) SpawnAgent(session, agentType string, index int, variant string, workDir string) (string, error)
- type DurationActivityEstimator
- type EstimationMethod
- type HandoffRecommendation
- type HandoffStatus
- type HandoffSummary
- type HandoffTrigger
- func (t *HandoffTrigger) Check() ([]string, error)
- func (t *HandoffTrigger) GetStatus() map[string]HandoffStatus
- func (t *HandoffTrigger) SetTriggeredHandler(handler func(HandoffTriggerEvent))
- func (t *HandoffTrigger) SetWarningHandler(handler func(HandoffTriggerEvent))
- func (t *HandoffTrigger) Start()
- func (t *HandoffTrigger) Stop()
- func (t *HandoffTrigger) TriggerForAgent(agentID string) (string, error)
- type HandoffTriggerConfig
- type HandoffTriggerEvent
- type MessageCountEstimator
- type MonitorConfig
- type PackComponent
- type PaneSpawner
- type PendingRotation
- type PendingRotationOutput
- type PendingRotationStore
- func (s *PendingRotationStore) Add(pending *PendingRotation) error
- func (s *PendingRotationStore) CleanExpired() (int, error)
- func (s *PendingRotationStore) Clear() error
- func (s *PendingRotationStore) Count() (int, error)
- func (s *PendingRotationStore) Get(agentID string) (*PendingRotation, error)
- func (s *PendingRotationStore) GetAll() ([]*PendingRotation, error)
- func (s *PendingRotationStore) GetExpired() ([]*PendingRotation, error)
- func (s *PendingRotationStore) GetForSession(session string) ([]*PendingRotation, error)
- func (s *PendingRotationStore) Remove(agentID string) error
- func (s *PendingRotationStore) StoragePath() string
- type Prediction
- type PredictorConfig
- type RobotModeEstimator
- type RotationEvent
- type RotationHistoryStore
- func (s *RotationHistoryStore) Append(record *RotationRecord) error
- func (s *RotationHistoryStore) Clear() error
- func (s *RotationHistoryStore) Count() (int, error)
- func (s *RotationHistoryStore) Exists() bool
- func (s *RotationHistoryStore) GetStats() (*RotationStats, error)
- func (s *RotationHistoryStore) Prune(keep int) (int, error)
- func (s *RotationHistoryStore) PruneByTime(cutoff time.Time) (int, error)
- func (s *RotationHistoryStore) ReadAll() ([]RotationRecord, error)
- func (s *RotationHistoryStore) ReadFailed() ([]RotationRecord, error)
- func (s *RotationHistoryStore) ReadForSession(session string) ([]RotationRecord, error)
- func (s *RotationHistoryStore) ReadRecent(n int) ([]RotationRecord, error)
- func (s *RotationHistoryStore) StoragePath() string
- type RotationMethod
- type RotationRecord
- type RotationResult
- type RotationState
- type RotationStats
- type Rotator
- func (r *Rotator) CancelPendingRotation(agentID string) bool
- func (r *Rotator) CheckAndRotate(sessionName, workDir string) ([]RotationResult, error)
- func (r *Rotator) ClearHistory()
- func (r *Rotator) ClearPending()
- func (r *Rotator) ConfirmRotation(agentID string, action ConfirmAction, postponeMinutes int) RotationResult
- func (r *Rotator) GetHistory() []RotationEvent
- func (r *Rotator) GetPendingRotation(agentID string) *PendingRotation
- func (r *Rotator) GetPendingRotations() []*PendingRotation
- func (r *Rotator) HasPendingRotation(agentID string) bool
- func (r *Rotator) ManualRotate(session, agentID, workDir string) RotationResult
- func (r *Rotator) NeedsRotation() ([]string, string)
- func (r *Rotator) NeedsWarning() ([]string, string)
- type RotatorConfig
- type StoredPendingRotation
- type SummaryGenerator
- type SummaryGeneratorConfig
- type TokenSample
Constants ¶
const CompactionPromptTemplate = `` /* 460-byte string literal not displayed */
CompactionPromptTemplate is the prompt for requesting a summarization compaction.
const SummaryPromptTemplate = `` /* 695-byte string literal not displayed */
SummaryPromptTemplate is the template for requesting a handoff summary from an agent.
Variables ¶
var ContextLimits = map[string]int64{
"claude-sonnet-4": 200000,
"claude-opus-4": 200000,
"claude-opus-4.5": 200000,
"claude-haiku": 200000,
"claude-3-opus": 200000,
"claude-3-sonnet": 200000,
"claude-3-haiku": 200000,
"claude-3.5-sonnet": 200000,
"claude-3.5-haiku": 200000,
"claude-sonnet-4-5": 200000,
"claude-opus-4-5": 200000,
"gpt-4": 128000,
"gpt-4-turbo": 128000,
"gpt-4o": 128000,
"gpt-4o-mini": 128000,
"gpt-5": 256000,
"gpt-5-codex": 256000,
"o1": 128000,
"o1-mini": 128000,
"o1-preview": 128000,
"o3-mini": 200000,
"gemini-2.0-flash": 1000000,
"gemini-2.0-flash-lite": 1000000,
"gemini-1.5-pro": 1000000,
"gemini-1.5-flash": 1000000,
"gemini-pro": 32000,
"default": 128000,
}
ContextLimits maps model names to their context window sizes in tokens. These are approximate values based on published specifications.
var DefaultPendingRotationStore = NewPendingRotationStore()
DefaultPendingRotationStore is the default global pending rotation store.
var DefaultRotationHistoryStore = NewRotationHistoryStore()
DefaultRotationHistoryStore is the default global history store.
var TokenBudgets = map[string]int{
"cc": 180000,
"cod": 120000,
"gmi": 100000,
"default": 100000,
}
TokenBudgets defines context limits per agent type
Functions ¶
func AddPendingRotation ¶
func AddPendingRotation(pending *PendingRotation) error
AddPendingRotation adds a pending rotation to the default store.
func EstimateTokens ¶
EstimateTokens provides a simple token estimation from character count. Uses the standard ~3.5-4 characters per token approximation.
func GetContextLimit ¶
GetContextLimit returns the context limit for a model. Returns the default limit if the model is not found.
func ParseTokenCount ¶
ParseTokenCount extracts a token count from text that might contain numbers. Handles formats like "145000", "145,000", "145k", "1.5M".
func PendingRotationStoragePath ¶
func PendingRotationStoragePath() string
PendingRotationStoragePath returns the path to the pending rotation file.
func RecordRotation ¶
func RecordRotation(record *RotationRecord) error
RecordRotation is a convenience function to append a rotation to the default store.
func RemovePendingRotation ¶
RemovePendingRotation removes a pending rotation from the default store.
func RotationHistoryStoragePath ¶
func RotationHistoryStoragePath() string
RotationHistoryStoragePath returns the path to the rotation history file.
Types ¶
type AgentCapabilities ¶
type AgentCapabilities struct {
SupportsBuiltinCompact bool
SupportsHistoryClear bool
BuiltinCompactCommand string // e.g., "/compact"
HistoryClearCommand string // e.g., "/clear"
}
AgentCapabilities describes what compaction features an agent supports.
func GetAgentCapabilities ¶
func GetAgentCapabilities(agentType string) AgentCapabilities
GetAgentCapabilities returns the compaction capabilities for an agent type.
type AgentContextInfo ¶
type AgentContextInfo struct {
AgentID string `json:"agent_id"`
PaneID string `json:"pane_id"`
Model string `json:"model"`
Estimate *ContextEstimate `json:"estimate"`
NeedsWarn bool `json:"needs_warning"`
NeedsRotate bool `json:"needs_rotation"`
}
AgentContextInfo provides context info for an agent.
type BudgetAllocation ¶
BudgetAllocation defines percentage allocation per component
func DefaultBudgetAllocation ¶
func DefaultBudgetAllocation() BudgetAllocation
DefaultBudgetAllocation returns the standard allocation
type BuildOptions ¶
type BuildOptions struct {
BeadID string
AgentType string // cc, cod, gmi
RepoRev string
Task string // Task description for CM context
Files []string // Files for S2P context
CorrelationID string
ProjectDir string
SessionID string // For CM client connection
}
BuildOptions configures how a context pack is built
type CompactionCommand ¶
type CompactionCommand struct {
Command string // The command/text to send
IsPrompt bool // True if this is a prompt, false if a slash command
WaitTime time.Duration
Description string
}
CompactionCommand represents a command to send to an agent for compaction.
type CompactionMethod ¶
type CompactionMethod string
CompactionMethod identifies the compaction strategy used.
const ( // CompactionBuiltin uses the agent's built-in /compact command CompactionBuiltin CompactionMethod = "builtin" // CompactionSummarize asks the agent to summarize conversation CompactionSummarize CompactionMethod = "summarize" // CompactionClearHistory clears non-essential history CompactionClearHistory CompactionMethod = "clear_history" // CompactionFailed indicates compaction was attempted but failed CompactionFailed CompactionMethod = "failed" )
type CompactionResult ¶
type CompactionResult struct {
Success bool `json:"success"`
Method CompactionMethod `json:"method"`
TokensBefore int64 `json:"tokens_before"`
TokensAfter int64 `json:"tokens_after"`
TokensReclaimed int64 `json:"tokens_reclaimed"`
UsageBefore float64 `json:"usage_before"`
UsageAfter float64 `json:"usage_after"`
Duration time.Duration `json:"duration"`
Error string `json:"error,omitempty"`
}
CompactionResult contains the outcome of a compaction attempt.
func (*CompactionResult) FormatForDisplay ¶
func (r *CompactionResult) FormatForDisplay() string
FormatCompactionResult formats the result for display.
type CompactionState ¶
type CompactionState struct {
AgentID string
StartedAt time.Time
Method CompactionMethod
CommandsSent int
LastCommand string
WaitingUntil time.Time
EstimateBefore *ContextEstimate
}
CompactionState tracks the state of a compaction attempt.
func (*CompactionState) UpdateState ¶
func (state *CompactionState) UpdateState(cmd CompactionCommand, method CompactionMethod)
UpdateState updates the compaction state after sending a command.
type CompactionStatus ¶
type CompactionStatus struct {
LastCompaction time.Time `json:"last_compaction"`
IsCompacting bool `json:"is_compacting"`
CooldownUntil time.Time `json:"cooldown_until"`
}
CompactionStatus represents the compaction status for an agent.
type CompactionTrigger ¶
type CompactionTrigger struct {
// contains filtered or unexported fields
}
CompactionTrigger monitors agents and triggers compaction proactively.
func NewCompactionTrigger ¶
func NewCompactionTrigger( config CompactionTriggerConfig, monitor *ContextMonitor, compactor *Compactor, predictor *ContextPredictor, ) *CompactionTrigger
NewCompactionTrigger creates a new proactive compaction trigger.
func (*CompactionTrigger) GetCompactionStatus ¶
func (t *CompactionTrigger) GetCompactionStatus() map[string]CompactionStatus
GetCompactionStatus returns the current compaction status for all agents.
func (*CompactionTrigger) SetCompactionCompleteHandler ¶
func (t *CompactionTrigger) SetCompactionCompleteHandler(handler func(CompactionTriggerEvent))
SetCompactionCompleteHandler sets the handler called when compaction completes.
func (*CompactionTrigger) SetCompactionTriggeredHandler ¶
func (t *CompactionTrigger) SetCompactionTriggeredHandler(handler func(CompactionTriggerEvent))
SetCompactionTriggeredHandler sets the handler called when compaction is triggered.
func (*CompactionTrigger) Start ¶
func (t *CompactionTrigger) Start()
Start begins the background monitoring loop.
func (*CompactionTrigger) Stop ¶
func (t *CompactionTrigger) Stop()
Stop halts the background monitoring loop.
func (*CompactionTrigger) TriggerCompactionNow ¶
func (t *CompactionTrigger) TriggerCompactionNow(agentID string) (*CompactionResult, error)
TriggerCompactionNow forces an immediate compaction check for a specific agent. This can be called manually to force compaction regardless of cooldown.
type CompactionTriggerConfig ¶
type CompactionTriggerConfig struct {
// PollInterval is how often to check predictions for compaction triggers
PollInterval time.Duration
// AutoCompact enables automatic compaction triggering
AutoCompact bool
// CompactionCooldown is minimum time between compaction attempts per agent
CompactionCooldown time.Duration
// WaitAfterCommand is how long to wait for compaction to complete
WaitAfterCommand time.Duration
// EnableRecoveryInjection controls whether to inject recovery context post-compaction
EnableRecoveryInjection bool
}
CompactionTriggerConfig configures the proactive compaction trigger.
func DefaultCompactionTriggerConfig ¶
func DefaultCompactionTriggerConfig() CompactionTriggerConfig
DefaultCompactionTriggerConfig returns sensible defaults.
type CompactionTriggerEvent ¶
type CompactionTriggerEvent struct {
AgentID string `json:"agent_id"`
PaneID string `json:"pane_id"`
AgentType tmux.AgentType `json:"agent_type"`
Prediction *Prediction `json:"prediction"`
TriggeredAt time.Time `json:"triggered_at"`
CompactionResult *CompactionResult `json:"compaction_result,omitempty"`
}
CompactionTriggerEvent represents a compaction trigger event.
type Compactor ¶
type Compactor struct {
// contains filtered or unexported fields
}
Compactor handles graceful degradation of context before rotation.
func NewCompactor ¶
func NewCompactor(monitor *ContextMonitor, cfg CompactorConfig) *Compactor
NewCompactor creates a new Compactor with the given configuration.
func (*Compactor) EvaluateCompactionResult ¶
func (c *Compactor) EvaluateCompactionResult(before, after *ContextEstimate) *CompactionResult
EvaluateCompactionResult determines if the compaction was successful.
func (*Compactor) FinishCompaction ¶
func (c *Compactor) FinishCompaction(state *CompactionState) (*CompactionResult, error)
FinishCompaction completes a compaction attempt and returns the result.
func (*Compactor) GenerateCompactionPrompt ¶
GenerateCompactionPrompt returns the prompt for requesting summarization.
func (*Compactor) GetCompactionCommands ¶
func (c *Compactor) GetCompactionCommands(agentType string) []CompactionCommand
GetCompactionCommands returns the sequence of commands to try for compaction.
func (*Compactor) NewCompactionState ¶
func (c *Compactor) NewCompactionState(agentID string) (*CompactionState, error)
NewCompactionState creates a new state for tracking a compaction attempt.
func (*Compactor) PreRotationCheck ¶
func (c *Compactor) PreRotationCheck( agentID string, rotateThreshold float64, lastCompactionResult *CompactionResult, ) (shouldRotate bool, reason string)
PreRotationCheck performs a final check before rotation is executed. Returns true if rotation should proceed, false if compaction helped enough. rotateThreshold is a decimal (e.g., 0.95 for 95%).
type CompactorConfig ¶
type CompactorConfig struct {
MinReduction float64 // Minimum usage reduction to consider success (default: 0.10)
BuiltinTimeout time.Duration // Timeout for builtin compaction (default: 10s)
SummarizeTimeout time.Duration // Timeout for summarization (default: 30s)
}
CompactorConfig holds configuration for the Compactor.
func DefaultCompactorConfig ¶
func DefaultCompactorConfig() CompactorConfig
DefaultCompactorConfig returns sensible defaults.
type ConfirmAction ¶
type ConfirmAction string
ConfirmAction represents the action to take for a pending rotation.
const ( // ConfirmRotate proceeds with the rotation. ConfirmRotate ConfirmAction = "rotate" // ConfirmCompact tries compaction instead of rotation. ConfirmCompact ConfirmAction = "compact" // ConfirmIgnore cancels the rotation and continues as-is. ConfirmIgnore ConfirmAction = "ignore" // ConfirmPostpone delays the rotation by a specified duration. ConfirmPostpone ConfirmAction = "postpone" )
type ContextEstimate ¶
type ContextEstimate struct {
TokensUsed int64 `json:"tokens_used"`
ContextLimit int64 `json:"context_limit"`
UsagePercent float64 `json:"usage_percent"` // 0.0-100.0
Confidence float64 `json:"confidence"` // 0.0-1.0
Method EstimationMethod `json:"method"`
Model string `json:"model,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
ContextEstimate represents an estimate of context window usage.
func ParseRobotModeContext ¶
func ParseRobotModeContext(output string) *ContextEstimate
ParseRobotModeContext attempts to parse context info from robot mode JSON output. Returns nil if context info is not present in the output.
type ContextEstimator ¶
type ContextEstimator interface {
// Estimate computes a context usage estimate for the given agent.
Estimate(state *ContextState) (*ContextEstimate, error)
// Confidence returns the base confidence level for this strategy.
Confidence() float64
// Name returns the strategy name for logging.
Name() string
}
ContextEstimator defines the interface for estimation strategies.
type ContextMonitor ¶
type ContextMonitor struct {
// contains filtered or unexported fields
}
ContextMonitor manages context tracking for multiple agents.
func NewContextMonitor ¶
func NewContextMonitor(cfg MonitorConfig) *ContextMonitor
NewContextMonitor creates a new context monitor with default estimators.
func (*ContextMonitor) AgentsAboveThreshold ¶
func (m *ContextMonitor) AgentsAboveThreshold(threshold float64) []AgentContextInfo
AgentsAboveThreshold returns agents above the given usage percentage. Results are sorted by confidence (higher first), then by AgentID (lexicographically).
func (*ContextMonitor) Clear ¶
func (m *ContextMonitor) Clear()
Clear removes all agents from monitoring.
func (*ContextMonitor) Count ¶
func (m *ContextMonitor) Count() int
Count returns the number of monitored agents.
func (*ContextMonitor) GetAllEstimates ¶
func (m *ContextMonitor) GetAllEstimates() map[string]*ContextEstimate
GetAllEstimates returns estimates for all monitored agents.
func (*ContextMonitor) GetEstimate ¶
func (m *ContextMonitor) GetEstimate(agentID string) *ContextEstimate
GetEstimate computes the current context estimate for an agent. Uses the highest-confidence available strategy.
func (*ContextMonitor) GetState ¶
func (m *ContextMonitor) GetState(agentID string) *ContextState
GetState returns the current state for an agent.
func (*ContextMonitor) RecordMessage ¶
func (m *ContextMonitor) RecordMessage(agentID string, inputTokens, outputTokens int64)
RecordMessage records a message for an agent.
func (*ContextMonitor) RegisterAgent ¶
func (m *ContextMonitor) RegisterAgent(agentID, paneID, model string) *ContextState
RegisterAgent registers or updates an agent for monitoring.
func (*ContextMonitor) RegisterAgentWithTranscript ¶
func (m *ContextMonitor) RegisterAgentWithTranscript(agentID, paneID, model, agentType, sessionName, transcriptPath string) *ContextState
RegisterAgentWithTranscript registers an agent with extended info including transcript path. This is used for pre-compact handoff generation that needs to read the transcript.
func (*ContextMonitor) ResetAgent ¶
func (m *ContextMonitor) ResetAgent(agentID string)
ResetAgent resets the context tracking for an agent (e.g., after rotation).
func (*ContextMonitor) SetAgentType ¶
func (m *ContextMonitor) SetAgentType(agentID, agentType string)
SetAgentType updates the agent type for a monitored agent.
func (*ContextMonitor) ShouldTriggerHandoff ¶
func (m *ContextMonitor) ShouldTriggerHandoff(agentID string, predictor *ContextPredictor) *HandoffRecommendation
ShouldTriggerHandoff checks if an agent should generate a handoff. Returns a recommendation with reason explaining why. Uses configured thresholds (RotateThreshold, WarningThreshold).
func (*ContextMonitor) UnregisterAgent ¶
func (m *ContextMonitor) UnregisterAgent(agentID string)
UnregisterAgent removes an agent from monitoring.
func (*ContextMonitor) UpdateFromRobotMode ¶
func (m *ContextMonitor) UpdateFromRobotMode(agentID, output string)
UpdateFromRobotMode updates context estimate from robot mode output.
func (*ContextMonitor) UpdateFromTranscript ¶
func (m *ContextMonitor) UpdateFromTranscript(agentID string) (int64, error)
UpdateFromTranscript reads the agent's transcript file and estimates tokens from file size. Uses ~4 bytes per token as approximation (conservative for safety). Returns the estimated tokens, or 0 if the file doesn't exist or can't be read.
type ContextPackBuilder ¶
type ContextPackBuilder struct {
// contains filtered or unexported fields
}
ContextPackBuilder builds context packs from multiple sources
func NewContextPackBuilder ¶
func NewContextPackBuilder(store *state.Store) *ContextPackBuilder
NewContextPackBuilder creates a new context pack builder
func (*ContextPackBuilder) Build ¶
func (b *ContextPackBuilder) Build(ctx context.Context, opts BuildOptions) (*ContextPackFull, error)
Build constructs a context pack for a task
func (*ContextPackBuilder) CacheStats ¶
func (b *ContextPackBuilder) CacheStats() (size int, keys []string)
CacheStats returns cache statistics
func (*ContextPackBuilder) ClearCache ¶
func (b *ContextPackBuilder) ClearCache()
ClearCache clears the context pack cache
func (*ContextPackBuilder) SetAllocation ¶
func (b *ContextPackBuilder) SetAllocation(alloc BudgetAllocation)
SetAllocation overrides the default budget allocation
type ContextPackFull ¶
type ContextPackFull struct {
state.ContextPack
Components map[string]*PackComponent `json:"components,omitempty"`
}
ContextPackFull extends the basic state.ContextPack with component data
type ContextPredictor ¶
type ContextPredictor struct {
// contains filtered or unexported fields
}
ContextPredictor tracks token velocity and predicts context exhaustion.
func NewContextPredictor ¶
func NewContextPredictor(cfg PredictorConfig) *ContextPredictor
NewContextPredictor creates a new predictor with the given configuration.
func (*ContextPredictor) AddSample ¶
func (p *ContextPredictor) AddSample(tokens int64)
AddSample records a new token count sample. This is thread-safe for concurrent access.
func (*ContextPredictor) AddSampleAt ¶
func (p *ContextPredictor) AddSampleAt(tokens int64, timestamp time.Time)
AddSampleAt records a token sample at a specific timestamp. Useful for testing and historical data replay.
func (*ContextPredictor) LatestSample ¶
func (p *ContextPredictor) LatestSample() *TokenSample
LatestSample returns the most recent sample, or nil if no samples exist.
func (*ContextPredictor) PredictExhaustion ¶
func (p *ContextPredictor) PredictExhaustion(modelLimit int64) *Prediction
PredictExhaustion calculates the predicted time to context exhaustion. Returns nil if insufficient data is available for prediction.
func (*ContextPredictor) Reset ¶
func (p *ContextPredictor) Reset()
Reset clears all samples from the predictor.
func (*ContextPredictor) SampleCount ¶
func (p *ContextPredictor) SampleCount() int
SampleCount returns the current number of samples stored.
func (*ContextPredictor) VelocityTrend ¶
func (p *ContextPredictor) VelocityTrend() (velocity float64, accelerating bool)
VelocityTrend returns the recent velocity trend. Returns velocity in tokens/minute and whether it's accelerating.
type ContextState ¶
type ContextState struct {
AgentID string `json:"agent_id"`
PaneID string `json:"pane_id"`
Model string `json:"model"`
AgentType string `json:"agent_type,omitempty"` // cc, cod, gmi
SessionName string `json:"session_name,omitempty"`
TranscriptPath string `json:"transcript_path,omitempty"` // Path to agent's transcript file
Estimate *ContextEstimate `json:"estimate"`
MessageCount int `json:"message_count"`
SessionStart time.Time `json:"session_start"`
LastActivity time.Time `json:"last_activity"`
// contains filtered or unexported fields
}
ContextState holds the full context tracking state for an agent.
type CumulativeTokenEstimator ¶
type CumulativeTokenEstimator struct {
CompactionDiscount float64 // Factor to apply for expected compaction, default 0.7
}
CumulativeTokenEstimator sums input+output tokens with compaction discount.
func (*CumulativeTokenEstimator) Confidence ¶
func (e *CumulativeTokenEstimator) Confidence() float64
Confidence returns the base confidence for this strategy.
func (*CumulativeTokenEstimator) Estimate ¶
func (e *CumulativeTokenEstimator) Estimate(state *ContextState) (*ContextEstimate, error)
Estimate computes context usage from cumulative token counts.
func (*CumulativeTokenEstimator) Name ¶
func (e *CumulativeTokenEstimator) Name() string
Name returns the estimator name.
type DefaultPaneSpawner ¶
type DefaultPaneSpawner struct {
// contains filtered or unexported fields
}
DefaultPaneSpawner implements PaneSpawner using the tmux package.
func NewDefaultPaneSpawner ¶
func NewDefaultPaneSpawner(cfg *config.Config) *DefaultPaneSpawner
NewDefaultPaneSpawner creates a PaneSpawner using the tmux package.
func (*DefaultPaneSpawner) GetPanes ¶
func (s *DefaultPaneSpawner) GetPanes(session string) ([]tmux.Pane, error)
GetPanes returns all panes in a session.
func (*DefaultPaneSpawner) KillPane ¶
func (s *DefaultPaneSpawner) KillPane(paneID string) error
KillPane terminates a pane.
func (*DefaultPaneSpawner) SendKeys ¶
func (s *DefaultPaneSpawner) SendKeys(paneID, text string, enter bool) error
SendKeys sends text to a pane.
func (*DefaultPaneSpawner) SpawnAgent ¶
func (s *DefaultPaneSpawner) SpawnAgent(session, agentType string, index int, variant string, workDir string) (string, error)
SpawnAgent creates a new agent pane.
type DurationActivityEstimator ¶
type DurationActivityEstimator struct {
TokensPerMinuteActive int // Tokens consumed per minute of active conversation
TokensPerMinuteInactive int // Tokens for inactive time (system overhead)
}
DurationActivityEstimator estimates from session duration and activity level.
func (*DurationActivityEstimator) Confidence ¶
func (e *DurationActivityEstimator) Confidence() float64
Confidence returns the base confidence for this strategy.
func (*DurationActivityEstimator) Estimate ¶
func (e *DurationActivityEstimator) Estimate(state *ContextState) (*ContextEstimate, error)
Estimate computes context usage from duration and activity.
func (*DurationActivityEstimator) Name ¶
func (e *DurationActivityEstimator) Name() string
Name returns the estimator name.
type EstimationMethod ¶
type EstimationMethod string
EstimationMethod identifies how the estimate was computed.
const ( MethodRobotMode EstimationMethod = "robot_mode" // Direct report from agent MethodMessageCount EstimationMethod = "message_count" // Estimated from message count MethodCumulativeTokens EstimationMethod = "cumulative_tokens" // Sum of input+output tokens MethodDurationActivity EstimationMethod = "duration_activity" // Time + activity heuristic MethodUnknown EstimationMethod = "unknown" )
type HandoffRecommendation ¶
type HandoffRecommendation struct {
ShouldTrigger bool // True if handoff should be triggered
ShouldWarn bool // True if warning threshold exceeded
Reason string // Human-readable reason for the recommendation
UsagePercent float64 // Current usage percentage
TokenVelocity float64 // Tokens per minute (if available)
}
HandoffRecommendation contains the result of ShouldTriggerHandoff.
type HandoffStatus ¶
type HandoffStatus struct {
LastHandoff time.Time `json:"last_handoff"`
IsGenerating bool `json:"is_generating"`
CooldownUntil time.Time `json:"cooldown_until"`
}
HandoffStatus represents the handoff status for an agent.
type HandoffSummary ¶
type HandoffSummary struct {
GeneratedAt time.Time `json:"generated_at"`
OldAgentID string `json:"old_agent_id"`
OldAgentType string `json:"old_agent_type,omitempty"`
SessionName string `json:"session_name,omitempty"`
CurrentTask string `json:"current_task"`
Progress string `json:"progress"`
KeyDecisions []string `json:"key_decisions,omitempty"`
ActiveFiles []string `json:"active_files,omitempty"`
Blockers []string `json:"blockers,omitempty"`
RawSummary string `json:"raw_summary"`
TokenEstimate int `json:"token_estimate"`
}
HandoffSummary contains the information needed to continue work in a new agent.
func (*HandoffSummary) FormatForNewAgent ¶
func (s *HandoffSummary) FormatForNewAgent() string
FormatForNewAgent formats the summary as context for the new agent.
type HandoffTrigger ¶
type HandoffTrigger struct {
// contains filtered or unexported fields
}
HandoffTrigger monitors agents and generates handoffs proactively before context exhaustion.
func NewHandoffTrigger ¶
func NewHandoffTrigger( config HandoffTriggerConfig, monitor *ContextMonitor, predictor *ContextPredictor, ) *HandoffTrigger
NewHandoffTrigger creates a new proactive handoff trigger.
func (*HandoffTrigger) Check ¶
func (t *HandoffTrigger) Check() ([]string, error)
Check evaluates all agents and triggers handoffs as needed. Returns list of generated handoff paths.
func (*HandoffTrigger) GetStatus ¶
func (t *HandoffTrigger) GetStatus() map[string]HandoffStatus
GetStatus returns the current status for all tracked agents.
func (*HandoffTrigger) SetTriggeredHandler ¶
func (t *HandoffTrigger) SetTriggeredHandler(handler func(HandoffTriggerEvent))
SetTriggeredHandler sets the callback for handoff trigger events.
func (*HandoffTrigger) SetWarningHandler ¶
func (t *HandoffTrigger) SetWarningHandler(handler func(HandoffTriggerEvent))
SetWarningHandler sets the callback for warning events (70% threshold).
func (*HandoffTrigger) Start ¶
func (t *HandoffTrigger) Start()
Start begins the background monitoring loop.
func (*HandoffTrigger) Stop ¶
func (t *HandoffTrigger) Stop()
Stop halts the background monitoring loop.
func (*HandoffTrigger) TriggerForAgent ¶
func (t *HandoffTrigger) TriggerForAgent(agentID string) (string, error)
TriggerForAgent forces handoff generation for a specific agent. This can be called manually to force a handoff regardless of cooldown.
type HandoffTriggerConfig ¶
type HandoffTriggerConfig struct {
// PollInterval is how often to check agents for handoff triggers
PollInterval time.Duration
// WarnThreshold is the usage percentage for warning callbacks (default 70%)
WarnThreshold float64
// TriggerThreshold is the usage percentage for handoff generation (default 75%)
TriggerThreshold float64
// Cooldown is minimum time between handoffs per agent
Cooldown time.Duration
// ProjectDir is the project directory for handoff generation
ProjectDir string
}
HandoffTriggerConfig configures the proactive handoff trigger.
func DefaultHandoffTriggerConfig ¶
func DefaultHandoffTriggerConfig() HandoffTriggerConfig
DefaultHandoffTriggerConfig returns sensible defaults.
type HandoffTriggerEvent ¶
type HandoffTriggerEvent struct {
AgentID string `json:"agent_id"`
PaneID string `json:"pane_id"`
AgentType string `json:"agent_type"`
SessionName string `json:"session_name"`
UsagePercent float64 `json:"usage_percent"`
Reason string `json:"reason"`
HandoffPath string `json:"handoff_path,omitempty"`
TriggeredAt time.Time `json:"triggered_at"`
Error string `json:"error,omitempty"`
}
HandoffTriggerEvent represents a handoff trigger event.
type MessageCountEstimator ¶
type MessageCountEstimator struct {
TokensPerMessage int // Average tokens per message, default 1500
}
MessageCountEstimator estimates context from message count.
func (*MessageCountEstimator) Confidence ¶
func (e *MessageCountEstimator) Confidence() float64
Confidence returns the base confidence for this strategy.
func (*MessageCountEstimator) Estimate ¶
func (e *MessageCountEstimator) Estimate(state *ContextState) (*ContextEstimate, error)
Estimate computes context usage from message count.
func (*MessageCountEstimator) Name ¶
func (e *MessageCountEstimator) Name() string
Name returns the estimator name.
type MonitorConfig ¶
type MonitorConfig struct {
WarningThreshold float64 // Percentage at which to warn (default 70)
RotateThreshold float64 // Percentage at which to rotate (default 75)
TokensPerMessage int // For message count estimation (default 1500)
}
MonitorConfig holds configuration for the context monitor.
func DefaultMonitorConfig ¶
func DefaultMonitorConfig() MonitorConfig
DefaultMonitorConfig returns sensible defaults.
type PackComponent ¶
type PackComponent struct {
Type string `json:"type"`
Data json.RawMessage `json:"data,omitempty"`
TokenCount int `json:"token_count"`
Error string `json:"error,omitempty"`
}
PackComponent represents a component of the context pack
type PaneSpawner ¶
type PaneSpawner interface {
// SpawnAgent creates a new agent pane and returns its ID.
SpawnAgent(session, agentType string, index int, variant string, workDir string) (paneID string, err error)
// KillPane terminates a pane.
KillPane(paneID string) error
// SendKeys sends text to a pane.
SendKeys(paneID, text string, enter bool) error
// GetPanes returns all panes in a session.
GetPanes(session string) ([]tmux.Pane, error)
}
PaneSpawner abstracts pane creation for testing.
type PendingRotation ¶
type PendingRotation struct {
AgentID string `json:"agent_id"`
SessionName string `json:"session_name"`
PaneID string `json:"pane_id"`
ContextPercent float64 `json:"context_percent"`
CreatedAt time.Time `json:"created_at"`
TimeoutAt time.Time `json:"timeout_at"`
DefaultAction ConfirmAction `json:"default_action"`
WorkDir string `json:"-"` // Not serialized
}
PendingRotation represents a rotation awaiting user confirmation.
func GetAllPendingRotations ¶
func GetAllPendingRotations() ([]*PendingRotation, error)
GetAllPendingRotations retrieves all pending rotations from the default store.
func GetPendingRotationByID ¶
func GetPendingRotationByID(agentID string) (*PendingRotation, error)
GetPendingRotationByID retrieves a pending rotation from the default store.
func GetPendingRotationsForSession ¶
func GetPendingRotationsForSession(session string) ([]*PendingRotation, error)
GetPendingRotationsForSession retrieves pending rotations for a session.
func (*PendingRotation) IsExpired ¶
func (p *PendingRotation) IsExpired() bool
IsExpired returns true if the pending rotation has timed out.
func (*PendingRotation) RemainingSeconds ¶
func (p *PendingRotation) RemainingSeconds() int
RemainingSeconds returns the seconds remaining before timeout.
type PendingRotationOutput ¶
type PendingRotationOutput struct {
Type string `json:"type"`
AgentID string `json:"agent_id"`
SessionName string `json:"session_name"`
ContextPercent float64 `json:"context_percent"`
AwaitingConfirm bool `json:"awaiting_confirmation"`
TimeoutSeconds int `json:"timeout_seconds"`
DefaultAction string `json:"default_action"`
AvailableActions []string `json:"available_actions"`
GeneratedAt string `json:"generated_at"`
}
PendingRotationOutput provides robot mode JSON output for pending rotations.
func NewPendingRotationOutput ¶
func NewPendingRotationOutput(p *PendingRotation) PendingRotationOutput
NewPendingRotationOutput creates a robot mode output for a pending rotation.
type PendingRotationStore ¶
type PendingRotationStore struct {
// contains filtered or unexported fields
}
PendingRotationStore provides persistent storage for pending rotations.
func NewPendingRotationStore ¶
func NewPendingRotationStore() *PendingRotationStore
NewPendingRotationStore creates a new pending rotation store with default path.
func NewPendingRotationStoreWithPath ¶
func NewPendingRotationStoreWithPath(path string) *PendingRotationStore
NewPendingRotationStoreWithPath creates a store with a custom path.
func (*PendingRotationStore) Add ¶
func (s *PendingRotationStore) Add(pending *PendingRotation) error
Add adds or updates a pending rotation in the store.
func (*PendingRotationStore) CleanExpired ¶
func (s *PendingRotationStore) CleanExpired() (int, error)
CleanExpired removes all expired entries.
func (*PendingRotationStore) Clear ¶
func (s *PendingRotationStore) Clear() error
Clear removes all pending rotations.
func (*PendingRotationStore) Count ¶
func (s *PendingRotationStore) Count() (int, error)
Count returns the number of pending rotations.
func (*PendingRotationStore) Get ¶
func (s *PendingRotationStore) Get(agentID string) (*PendingRotation, error)
Get retrieves a pending rotation by agent ID.
func (*PendingRotationStore) GetAll ¶
func (s *PendingRotationStore) GetAll() ([]*PendingRotation, error)
GetAll retrieves all non-expired pending rotations.
func (*PendingRotationStore) GetExpired ¶
func (s *PendingRotationStore) GetExpired() ([]*PendingRotation, error)
GetExpired retrieves all expired pending rotations.
func (*PendingRotationStore) GetForSession ¶
func (s *PendingRotationStore) GetForSession(session string) ([]*PendingRotation, error)
GetForSession retrieves pending rotations for a specific session.
func (*PendingRotationStore) Remove ¶
func (s *PendingRotationStore) Remove(agentID string) error
Remove removes a pending rotation by agent ID.
func (*PendingRotationStore) StoragePath ¶
func (s *PendingRotationStore) StoragePath() string
StoragePath returns the path to the pending rotation file.
type Prediction ¶
type Prediction struct {
CurrentUsage float64 // Current usage as percentage (0.0-1.0)
CurrentTokens int64 // Current token count
ContextLimit int64 // Model context limit
TokenVelocity float64 // Tokens per minute (positive = growing)
MinutesToExhaustion float64 // Estimated minutes until exhaustion (0 if stable/decreasing)
ShouldWarn bool // True if warning threshold met
ShouldCompact bool // True if compaction threshold met
SampleCount int // Number of samples used for prediction
WindowDuration float64 // Actual window duration in minutes
}
Prediction represents the predicted context window exhaustion.
type PredictorConfig ¶
type PredictorConfig struct {
Window time.Duration // Velocity averaging window
PollInterval time.Duration // Polling interval
MaxSamples int // Maximum samples to retain
WarnMinutes float64 // Minutes threshold for warning
WarnUsage float64 // Usage threshold for warning
CompactMinutes float64 // Minutes threshold for compaction
CompactUsage float64 // Usage threshold for compaction
MinSamples int // Minimum samples for valid prediction
}
PredictorConfig configures the ContextPredictor.
func DefaultPredictorConfig ¶
func DefaultPredictorConfig() PredictorConfig
DefaultPredictorConfig returns the default configuration for ContextPredictor.
type RobotModeEstimator ¶
type RobotModeEstimator struct{}
RobotModeEstimator parses context info from robot mode output.
func (*RobotModeEstimator) Confidence ¶
func (e *RobotModeEstimator) Confidence() float64
Confidence returns the base confidence for this strategy.
func (*RobotModeEstimator) Estimate ¶
func (e *RobotModeEstimator) Estimate(state *ContextState) (*ContextEstimate, error)
Estimate extracts context usage from robot mode output.
func (*RobotModeEstimator) Name ¶
func (e *RobotModeEstimator) Name() string
Name returns the estimator name.
type RotationEvent ¶
type RotationEvent struct {
SessionName string `json:"session_name"`
OldAgentID string `json:"old_agent_id"`
NewAgentID string `json:"new_agent_id"`
AgentType string `json:"agent_type"`
Method RotationMethod `json:"method"`
ContextBefore float64 `json:"context_before"` // Usage percentage before
ContextAfter float64 `json:"context_after"` // Usage percentage after (should be ~0)
SummaryTokens int `json:"summary_tokens"`
Duration time.Duration `json:"duration"`
Timestamp time.Time `json:"timestamp"`
Error string `json:"error,omitempty"`
}
RotationEvent represents a rotation for audit/history purposes.
type RotationHistoryStore ¶
type RotationHistoryStore struct {
// contains filtered or unexported fields
}
RotationHistoryStore provides persistent storage for rotation records.
func NewRotationHistoryStore ¶
func NewRotationHistoryStore() *RotationHistoryStore
NewRotationHistoryStore creates a new history store with default storage path.
func NewRotationHistoryStoreWithPath ¶
func NewRotationHistoryStoreWithPath(path string) *RotationHistoryStore
NewRotationHistoryStoreWithPath creates a history store with a custom path.
func (*RotationHistoryStore) Append ¶
func (s *RotationHistoryStore) Append(record *RotationRecord) error
Append adds a rotation record to the history file.
func (*RotationHistoryStore) Clear ¶
func (s *RotationHistoryStore) Clear() error
Clear removes all rotation history.
func (*RotationHistoryStore) Count ¶
func (s *RotationHistoryStore) Count() (int, error)
Count returns the number of rotation records.
func (*RotationHistoryStore) Exists ¶
func (s *RotationHistoryStore) Exists() bool
Exists checks if rotation history file exists and has content.
func (*RotationHistoryStore) GetStats ¶
func (s *RotationHistoryStore) GetStats() (*RotationStats, error)
GetStats returns rotation history statistics.
func (*RotationHistoryStore) Prune ¶
func (s *RotationHistoryStore) Prune(keep int) (int, error)
Prune keeps only the last n records, removing older ones.
func (*RotationHistoryStore) PruneByTime ¶
func (s *RotationHistoryStore) PruneByTime(cutoff time.Time) (int, error)
PruneByTime removes records older than the cutoff time.
func (*RotationHistoryStore) ReadAll ¶
func (s *RotationHistoryStore) ReadAll() ([]RotationRecord, error)
ReadAll reads all rotation records from the history file.
func (*RotationHistoryStore) ReadFailed ¶
func (s *RotationHistoryStore) ReadFailed() ([]RotationRecord, error)
ReadFailed reads only failed rotation records.
func (*RotationHistoryStore) ReadForSession ¶
func (s *RotationHistoryStore) ReadForSession(session string) ([]RotationRecord, error)
ReadForSession reads rotation records for a specific session.
func (*RotationHistoryStore) ReadRecent ¶
func (s *RotationHistoryStore) ReadRecent(n int) ([]RotationRecord, error)
ReadRecent reads the last n rotation records.
func (*RotationHistoryStore) StoragePath ¶
func (s *RotationHistoryStore) StoragePath() string
StoragePath returns the path to the rotation history file.
type RotationMethod ¶
type RotationMethod string
RotationMethod identifies how the rotation was triggered.
const ( // RotationThresholdExceeded indicates rotation due to context threshold. RotationThresholdExceeded RotationMethod = "threshold_exceeded" // RotationManual indicates a manually triggered rotation. RotationManual RotationMethod = "manual" // RotationCompactionFailed indicates rotation after compaction failed. RotationCompactionFailed RotationMethod = "compaction_failed" )
type RotationRecord ¶
type RotationRecord struct {
ID string `json:"id"` // Unique ID for the record
Timestamp time.Time `json:"timestamp"` // When rotation occurred
// Session and Agent Info
SessionName string `json:"session_name"`
AgentID string `json:"agent_id"`
AgentType string `json:"agent_type"`
Profile string `json:"profile,omitempty"` // Profile/persona name if any
// Context state before rotation
ContextBefore float64 `json:"context_before_percent"` // Usage % before
EstimationMethod string `json:"estimation_method"` // How usage was estimated
// Compaction attempt
CompactionTried bool `json:"compaction_tried"`
CompactionResult string `json:"compaction_result,omitempty"` // "success", "failed", "skipped"
CompactionMethod string `json:"compaction_method,omitempty"` // "builtin", "summarize", etc.
// Rotation result
Method RotationMethod `json:"method"` // threshold, manual, etc.
Success bool `json:"success"`
FailureReason string `json:"failure_reason,omitempty"`
SummaryTokens int `json:"summary_tokens"`
ContextAfter float64 `json:"context_after_percent"` // Usage % after (should be ~0)
// Duration
DurationMs int64 `json:"duration_ms"`
}
RotationRecord contains detailed information about a rotation event for audit/analysis.
func GetFailedRotations ¶
func GetFailedRotations() ([]RotationRecord, error)
GetFailedRotations is a convenience function to get failed rotations.
func GetRecentRotations ¶
func GetRecentRotations(n int) ([]RotationRecord, error)
GetRecentRotations is a convenience function to get recent rotations from the default store.
func GetRotationsForSession ¶
func GetRotationsForSession(session string) ([]RotationRecord, error)
GetRotationsForSession is a convenience function to get rotations for a session.
func NewRotationRecord ¶
func NewRotationRecord(result *RotationResult, session, profile, estimationMethod string) *RotationRecord
NewRotationRecord creates a new rotation record from a RotationResult.
type RotationResult ¶
type RotationResult struct {
Success bool `json:"success"`
OldAgentID string `json:"old_agent_id"`
NewAgentID string `json:"new_agent_id,omitempty"`
OldPaneID string `json:"old_pane_id"`
NewPaneID string `json:"new_pane_id,omitempty"`
Method RotationMethod `json:"method"`
State RotationState `json:"state"`
SummaryTokens int `json:"summary_tokens,omitempty"`
Duration time.Duration `json:"duration"`
Error string `json:"error,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
RotationResult contains the outcome of a rotation attempt.
func (*RotationResult) FormatForDisplay ¶
func (r *RotationResult) FormatForDisplay() string
FormatRotationResult formats a rotation result for display.
type RotationState ¶
type RotationState string
RotationState tracks the current state of a rotation.
const ( RotationStatePending RotationState = "pending" RotationStateInProgress RotationState = "in_progress" RotationStateCompleted RotationState = "completed" RotationStateFailed RotationState = "failed" RotationStateAborted RotationState = "aborted" )
type RotationStats ¶
type RotationStats struct {
TotalRotations int `json:"total_rotations"`
SuccessCount int `json:"success_count"`
FailureCount int `json:"failure_count"`
UniqueSessions int `json:"unique_sessions"`
AvgContextBefore float64 `json:"avg_context_before_percent"`
AvgDurationMs int64 `json:"avg_duration_ms"`
FileSizeBytes int64 `json:"file_size_bytes"`
// By method
ThresholdRotations int `json:"threshold_rotations"`
ManualRotations int `json:"manual_rotations"`
// Compaction stats
CompactionAttempts int `json:"compaction_attempts"`
CompactionSuccesses int `json:"compaction_successes"`
// By agent type
RotationsByAgentType map[string]int `json:"rotations_by_agent_type"`
// By profile
RotationsByProfile map[string]int `json:"rotations_by_profile,omitempty"`
}
RotationStats contains summary statistics about rotation history.
func GetRotationStats ¶
func GetRotationStats() (*RotationStats, error)
GetRotationStats is a convenience function to get stats from the default store.
type Rotator ¶
type Rotator struct {
// contains filtered or unexported fields
}
Rotator coordinates agent rotation when context window is exhausted.
func NewRotator ¶
func NewRotator(cfg RotatorConfig) *Rotator
NewRotator creates a new Rotator with the given configuration.
func (*Rotator) CancelPendingRotation ¶
CancelPendingRotation removes a pending rotation without taking any action.
func (*Rotator) CheckAndRotate ¶
func (r *Rotator) CheckAndRotate(sessionName, workDir string) ([]RotationResult, error)
CheckAndRotate checks all agents and rotates those above the threshold. Returns the results of all rotation attempts. If RequireConfirm is enabled, agents needing rotation are added to pending and results have State=RotationStatePending until confirmed.
func (*Rotator) ClearHistory ¶
func (r *Rotator) ClearHistory()
ClearHistory clears the rotation history.
func (*Rotator) ClearPending ¶
func (r *Rotator) ClearPending()
ClearPending removes all pending rotations.
func (*Rotator) ConfirmRotation ¶
func (r *Rotator) ConfirmRotation(agentID string, action ConfirmAction, postponeMinutes int) RotationResult
ConfirmRotation handles user confirmation of a pending rotation. Returns the result of the action taken.
func (*Rotator) GetHistory ¶
func (r *Rotator) GetHistory() []RotationEvent
GetHistory returns the rotation history.
func (*Rotator) GetPendingRotation ¶
func (r *Rotator) GetPendingRotation(agentID string) *PendingRotation
GetPendingRotation returns a specific pending rotation by agent ID.
func (*Rotator) GetPendingRotations ¶
func (r *Rotator) GetPendingRotations() []*PendingRotation
GetPendingRotations returns all pending rotations awaiting confirmation.
func (*Rotator) HasPendingRotation ¶
HasPendingRotation returns true if there is a pending rotation for the agent.
func (*Rotator) ManualRotate ¶
func (r *Rotator) ManualRotate(session, agentID, workDir string) RotationResult
ManualRotate triggers a rotation for a specific agent regardless of threshold.
func (*Rotator) NeedsRotation ¶
NeedsRotation checks if any agent needs rotation. Returns agent IDs that need rotation and a reason string.
func (*Rotator) NeedsWarning ¶
NeedsWarning checks if any agent is above the warning threshold. Returns agent IDs that need warning and a reason string.
type RotatorConfig ¶
type RotatorConfig struct {
Monitor *ContextMonitor
Compactor *Compactor
Summary *SummaryGenerator
Spawner PaneSpawner
Config config.ContextRotationConfig
}
RotatorConfig holds configuration for creating a Rotator.
type StoredPendingRotation ¶
type StoredPendingRotation struct {
AgentID string `json:"agent_id"`
SessionName string `json:"session_name"`
PaneID string `json:"pane_id"`
ContextPercent float64 `json:"context_percent"`
CreatedAt time.Time `json:"created_at"`
TimeoutAt time.Time `json:"timeout_at"`
DefaultAction ConfirmAction `json:"default_action"`
WorkDir string `json:"work_dir"`
}
StoredPendingRotation is the serialized form of PendingRotation for persistence.
func FromPendingRotation ¶
func FromPendingRotation(p *PendingRotation) *StoredPendingRotation
FromPendingRotation creates a StoredPendingRotation from PendingRotation.
func (*StoredPendingRotation) ToPendingRotation ¶
func (s *StoredPendingRotation) ToPendingRotation() *PendingRotation
ToPendingRotation converts a StoredPendingRotation to PendingRotation.
type SummaryGenerator ¶
type SummaryGenerator struct {
// contains filtered or unexported fields
}
SummaryGenerator handles the generation of handoff summaries.
func NewSummaryGenerator ¶
func NewSummaryGenerator(cfg SummaryGeneratorConfig) *SummaryGenerator
NewSummaryGenerator creates a new SummaryGenerator with the given config.
func (*SummaryGenerator) GenerateFallbackSummary ¶
func (g *SummaryGenerator) GenerateFallbackSummary( agentID, agentType, sessionName string, recentOutput []string, ) *HandoffSummary
GenerateFallbackSummary creates a summary from recent agent output when the agent doesn't respond to the summary request.
func (*SummaryGenerator) GeneratePrompt ¶
func (g *SummaryGenerator) GeneratePrompt() string
GeneratePrompt returns the prompt to send to an agent for summary generation.
func (*SummaryGenerator) ParseAgentResponse ¶
func (g *SummaryGenerator) ParseAgentResponse(agentID, agentType, sessionName, response string) *HandoffSummary
ParseAgentResponse parses an agent's response to the summary prompt.
type SummaryGeneratorConfig ¶
type SummaryGeneratorConfig struct {
MaxTokens int // Maximum tokens for summary (default: 2000)
PromptTimeout time.Duration // Timeout for agent response (default: 30s)
}
SummaryGeneratorConfig holds configuration for the SummaryGenerator.
func DefaultSummaryGeneratorConfig ¶
func DefaultSummaryGeneratorConfig() SummaryGeneratorConfig
DefaultSummaryGeneratorConfig returns sensible defaults.
type TokenSample ¶
TokenSample represents a single token count sample at a point in time.