Documentation
¶
Index ¶
- func FormatDuration(d time.Duration) string
- type ApprovalDetector
- func (ad *ApprovalDetector) AddPattern(pattern *ApprovalPattern) error
- func (ad *ApprovalDetector) ClearHistory()
- func (ad *ApprovalDetector) Detect(output string) []*ApprovalRequest
- func (ad *ApprovalDetector) DetectInChunk(data []byte, err error) *ApprovalRequest
- func (ad *ApprovalDetector) GetHistory(limit int) []*ApprovalRequest
- func (ad *ApprovalDetector) GetMaxHistory() int
- func (ad *ApprovalDetector) GetPatterns() []*ApprovalPattern
- func (ad *ApprovalDetector) GetPendingRequests() []*ApprovalRequest
- func (ad *ApprovalDetector) GetRequestByID(id string) *ApprovalRequest
- func (ad *ApprovalDetector) GetStatistics() ApprovalStatistics
- func (ad *ApprovalDetector) RemovePattern(name string) bool
- func (ad *ApprovalDetector) SetMaxHistory(max int)
- func (ad *ApprovalDetector) Subscribe(subscriberID string) <-chan *ApprovalRequest
- func (ad *ApprovalDetector) Unsubscribe(subscriberID string)
- func (ad *ApprovalDetector) UpdateRequestStatus(id string, status ApprovalRequestStatus, response *ApprovalResponse) error
- type ApprovalPattern
- type ApprovalRequest
- type ApprovalRequestStatus
- type ApprovalResponse
- type ApprovalStatistics
- type ApprovalType
- type DetectedStatus
- type IdleDetector
- func (id *IdleDetector) DetectState() IdleState
- func (id *IdleDetector) DetectStateFromContent(content string) IdleState
- func (id *IdleDetector) GetIdleDuration() time.Duration
- func (id *IdleDetector) GetLastActivity() time.Time
- func (id *IdleDetector) GetState() IdleState
- func (id *IdleDetector) GetStateInfo() IdleStateInfo
- func (id *IdleDetector) InitializeFromTimestamp(timestamp time.Time)
- func (id *IdleDetector) IsActive() bool
- func (id *IdleDetector) IsIdle() bool
- func (id *IdleDetector) RecordActivity()
- func (id *IdleDetector) Reset()
- func (id *IdleDetector) UpdateConfig(config IdleDetectorConfig)
- type IdleDetectorConfig
- type IdleState
- type IdleStateInfo
- type PTYReader
- type StatusDetector
- func (sd *StatusDetector) Detect(output []byte) DetectedStatus
- func (sd *StatusDetector) DetectForProgram(output []byte, program string) DetectedStatus
- func (sd *StatusDetector) DetectFromLines(lines []string) DetectedStatus
- func (sd *StatusDetector) DetectFromString(output string) DetectedStatus
- func (sd *StatusDetector) DetectRecent(output []byte, n int) DetectedStatus
- func (sd *StatusDetector) DetectWithContext(output []byte) (DetectedStatus, string)
- func (sd *StatusDetector) ExportPatterns(path string) error
- func (sd *StatusDetector) GetPatternNames(status DetectedStatus) []string
- func (sd *StatusDetector) HasPattern(status DetectedStatus, name string) bool
- func (sd *StatusDetector) LoadPatterns(path string) error
- type StatusPattern
- type StatusPatterns
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FormatDuration ¶
FormatDuration formats a duration in a human-readable way.
Types ¶
type ApprovalDetector ¶
type ApprovalDetector struct {
// contains filtered or unexported fields
}
ApprovalDetector detects approval requests in command output.
func NewApprovalDetector ¶
func NewApprovalDetector() *ApprovalDetector
NewApprovalDetector creates a new approval detector with default patterns.
func (*ApprovalDetector) AddPattern ¶
func (ad *ApprovalDetector) AddPattern(pattern *ApprovalPattern) error
AddPattern adds a new approval detection pattern.
func (*ApprovalDetector) ClearHistory ¶
func (ad *ApprovalDetector) ClearHistory()
ClearHistory removes all approval detection history.
func (*ApprovalDetector) Detect ¶
func (ad *ApprovalDetector) Detect(output string) []*ApprovalRequest
Detect scans output for approval requests.
func (*ApprovalDetector) DetectInChunk ¶
func (ad *ApprovalDetector) DetectInChunk(data []byte, err error) *ApprovalRequest
DetectInChunk processes a single response chunk for approval patterns.
func (*ApprovalDetector) GetHistory ¶
func (ad *ApprovalDetector) GetHistory(limit int) []*ApprovalRequest
GetHistory returns recent approval detection history.
func (*ApprovalDetector) GetMaxHistory ¶
func (ad *ApprovalDetector) GetMaxHistory() int
GetMaxHistory returns the current max history setting.
func (*ApprovalDetector) GetPatterns ¶
func (ad *ApprovalDetector) GetPatterns() []*ApprovalPattern
GetPatterns returns all registered patterns.
func (*ApprovalDetector) GetPendingRequests ¶
func (ad *ApprovalDetector) GetPendingRequests() []*ApprovalRequest
GetPendingRequests returns all pending approval requests.
func (*ApprovalDetector) GetRequestByID ¶
func (ad *ApprovalDetector) GetRequestByID(id string) *ApprovalRequest
GetRequestByID retrieves a specific approval request by ID.
func (*ApprovalDetector) GetStatistics ¶
func (ad *ApprovalDetector) GetStatistics() ApprovalStatistics
GetStatistics returns statistics about approval detection.
func (*ApprovalDetector) RemovePattern ¶
func (ad *ApprovalDetector) RemovePattern(name string) bool
RemovePattern removes a pattern by name.
func (*ApprovalDetector) SetMaxHistory ¶
func (ad *ApprovalDetector) SetMaxHistory(max int)
SetMaxHistory sets the maximum number of history entries to keep.
func (*ApprovalDetector) Subscribe ¶
func (ad *ApprovalDetector) Subscribe(subscriberID string) <-chan *ApprovalRequest
Subscribe creates a subscription for approval detection events.
func (*ApprovalDetector) Unsubscribe ¶
func (ad *ApprovalDetector) Unsubscribe(subscriberID string)
Unsubscribe removes a subscription.
func (*ApprovalDetector) UpdateRequestStatus ¶
func (ad *ApprovalDetector) UpdateRequestStatus(id string, status ApprovalRequestStatus, response *ApprovalResponse) error
UpdateRequestStatus updates the status of an approval request.
type ApprovalPattern ¶
type ApprovalPattern struct {
Name string `json:"name"`
Type ApprovalType `json:"type"`
Pattern string `json:"pattern"` // Regex pattern
Confidence float64 `json:"confidence"` // Base confidence score
ContextSize int `json:"context_size"` // Lines of context to capture
CaptureKeys []string `json:"capture_keys"` // Names for regex capture groups
// contains filtered or unexported fields
}
ApprovalPattern defines a pattern for detecting approval requests.
type ApprovalRequest ¶
type ApprovalRequest struct {
ID string `json:"id"`
Type ApprovalType `json:"type"`
Timestamp time.Time `json:"timestamp"`
DetectedText string `json:"detected_text"` // The text that matched the pattern
Context string `json:"context"` // Surrounding context
ExtractedData map[string]string `json:"extracted_data"` // Pattern capture groups
Confidence float64 `json:"confidence"` // 0.0-1.0 confidence score
Status ApprovalRequestStatus `json:"status"`
Response *ApprovalResponse `json:"response,omitempty"`
}
ApprovalRequest represents a detected approval request from Claude.
type ApprovalRequestStatus ¶
type ApprovalRequestStatus string
ApprovalRequestStatus tracks the lifecycle of an approval request.
const ( ApprovalPending ApprovalRequestStatus = "pending" ApprovalApproved ApprovalRequestStatus = "approved" ApprovalRejected ApprovalRequestStatus = "rejected" ApprovalExpired ApprovalRequestStatus = "expired" ApprovalIgnored ApprovalRequestStatus = "ignored" )
type ApprovalResponse ¶
type ApprovalResponse struct {
Approved bool `json:"approved"`
Timestamp time.Time `json:"timestamp"`
UserInput string `json:"user_input,omitempty"` // Optional user comment
}
ApprovalResponse contains the user's response to an approval request.
type ApprovalStatistics ¶
type ApprovalStatistics struct {
TotalDetections int
PendingCount int
ApprovedCount int
RejectedCount int
ExpiredCount int
IgnoredCount int
CommandApprovals int
FileWriteApprovals int
FileReadApprovals int
ToolUseApprovals int
ConfirmationApprovals int
}
ApprovalStatistics provides summary statistics.
type ApprovalType ¶
type ApprovalType string
ApprovalType represents different types of approvals Claude might request.
const ( ApprovalCommand ApprovalType = "command" // Shell command approval ApprovalFileWrite ApprovalType = "file_write" // File write/edit approval ApprovalFileRead ApprovalType = "file_read" // File read approval ApprovalToolUse ApprovalType = "tool_use" // Tool/API usage approval ApprovalConfirmation ApprovalType = "confirmation" // Generic confirmation request ApprovalUnknown ApprovalType = "unknown" // Unrecognized approval pattern )
type DetectedStatus ¶
type DetectedStatus int
Status represents the current status of a Claude instance based on PTY output analysis. This extends the existing Status type in instance.go with additional detection capabilities.
const ( StatusUnknown DetectedStatus = iota StatusReady StatusProcessing StatusNeedsApproval StatusInputRequired // Explicit user input prompts (questions, "enter X:", etc.) StatusError StatusTestsFailing // Tests are failing StatusIdle // Waiting for user input (INSERT mode, command prompt, etc.) StatusActive // Actively executing commands (shows "esc to interrupt") StatusSuccess // Task completed successfully )
func (DetectedStatus) String ¶
func (s DetectedStatus) String() string
StatusString converts DetectedStatus to a human-readable string.
type IdleDetector ¶
type IdleDetector struct {
// contains filtered or unexported fields
}
IdleDetector monitors PTY output to determine if a Claude Code session is idle. It uses pattern matching on recent output and tracks state transitions with debouncing.
func NewIdleDetector ¶
func NewIdleDetector(sessionName string, ptyAccess PTYReader) *IdleDetector
NewIdleDetector creates a new idle detector for a session.
func NewIdleDetectorWithConfig ¶
func NewIdleDetectorWithConfig(sessionName string, ptyAccess PTYReader, config IdleDetectorConfig) *IdleDetector
NewIdleDetectorWithConfig creates a new idle detector with custom configuration.
func (*IdleDetector) DetectState ¶
func (id *IdleDetector) DetectState() IdleState
DetectState analyzes recent PTY output and returns the current idle state. This method applies pattern matching and debouncing logic. DEPRECATED: Use DetectStateFromContent for more reliable detection. This method uses the PTY circular buffer which may contain incomplete data.
func (*IdleDetector) DetectStateFromContent ¶
func (id *IdleDetector) DetectStateFromContent(content string) IdleState
DetectStateFromContent analyzes provided terminal content and returns the current idle state. This method should be preferred over DetectState() as it allows the caller to provide reliable terminal content (e.g., from tmux capture-pane) instead of using the PTY circular buffer.
func (*IdleDetector) GetIdleDuration ¶
func (id *IdleDetector) GetIdleDuration() time.Duration
GetIdleDuration returns how long the session has been idle.
func (*IdleDetector) GetLastActivity ¶
func (id *IdleDetector) GetLastActivity() time.Time
GetLastActivity returns the timestamp of the last detected activity.
func (*IdleDetector) GetState ¶
func (id *IdleDetector) GetState() IdleState
GetState returns the current idle state without triggering detection. Use this when you want the cached state without analyzing PTY output.
func (*IdleDetector) GetStateInfo ¶
func (id *IdleDetector) GetStateInfo() IdleStateInfo
GetStateInfo returns comprehensive state information for debugging and display.
func (*IdleDetector) InitializeFromTimestamp ¶
func (id *IdleDetector) InitializeFromTimestamp(timestamp time.Time)
InitializeFromTimestamp restores the idle detector state from a persisted timestamp. This should be called immediately after creation when restoring a session from storage to maintain temporal continuity across server restarts.
This method prevents false "timeout" detection after server restarts by preserving the historical activity timeline. Without this restoration, all sessions would show "Timed out after Xs" immediately after restart because the idle detector initializes with time.Now() by default.
Parameters:
- timestamp: The last known activity timestamp (typically Instance.LastMeaningfulOutput)
Thread-safety: Safe to call concurrently (uses mutex)
Validation:
- Zero timestamps are ignored (no restoration)
- Future timestamps are rejected (clock skew protection)
- Very old timestamps (>24h) are rejected to prevent misleading timeout messages
func (*IdleDetector) IsActive ¶
func (id *IdleDetector) IsActive() bool
IsActive returns true if the session is actively processing commands.
func (*IdleDetector) IsIdle ¶
func (id *IdleDetector) IsIdle() bool
IsIdle returns true if the session is currently idle (waiting or timed out).
func (*IdleDetector) RecordActivity ¶ added in v1.9.0
func (id *IdleDetector) RecordActivity()
RecordActivity updates lastActivity to now when PTY bytes arrive. It is debounced: if lastActivity was already updated within minActivityInterval, this is a no-op. This keeps the idle timer accurate while avoiding excessive cache invalidation in the review queue poller.
func (*IdleDetector) Reset ¶
func (id *IdleDetector) Reset()
Reset resets the idle detector's state tracking. Use this when reattaching to a session or after significant changes.
func (*IdleDetector) UpdateConfig ¶
func (id *IdleDetector) UpdateConfig(config IdleDetectorConfig)
UpdateConfig updates the idle detector configuration.
type IdleDetectorConfig ¶
type IdleDetectorConfig struct {
IdleThreshold time.Duration // Duration before considering session timed out
DebounceDelay time.Duration // Delay before changing state to prevent flickering
BufferSize int // Number of bytes to analyze from recent output
}
IdleDetectorConfig contains configuration for idle detection behavior.
func DefaultIdleDetectorConfig ¶
func DefaultIdleDetectorConfig() IdleDetectorConfig
DefaultIdleDetectorConfig returns sensible defaults for idle detection.
type IdleStateInfo ¶
type IdleStateInfo struct {
State IdleState
LastActivity time.Time
IdleDuration time.Duration
LastStateChange time.Time
SessionName string
}
IdleStateInfo contains comprehensive information about the current idle state.
func (IdleStateInfo) Description ¶
func (info IdleStateInfo) Description() string
Description returns a detailed description of the idle state info.
type PTYReader ¶
PTYReader provides access to recent terminal output. Implemented by *session.PTYAccess; defined here as an interface to avoid a circular import between session/detection and session.
type StatusDetector ¶
type StatusDetector struct {
// contains filtered or unexported fields
}
StatusDetector analyzes PTY output to determine the current status of a Claude instance.
func NewStatusDetector ¶
func NewStatusDetector() *StatusDetector
NewStatusDetector creates a new status detector with default patterns.
func NewStatusDetectorFromFile ¶
func NewStatusDetectorFromFile(path string) (*StatusDetector, error)
NewStatusDetectorFromFile creates a status detector with patterns loaded from a YAML file.
func (*StatusDetector) Detect ¶
func (sd *StatusDetector) Detect(output []byte) DetectedStatus
Detect analyzes the provided PTY output and returns the detected status. Patterns are checked in priority order: Error > TestsFailing > Success > NeedsApproval > InputRequired > Active > Processing > Idle > Ready. Returns StatusUnknown if no patterns match.
func (*StatusDetector) DetectForProgram ¶ added in v1.12.0
func (sd *StatusDetector) DetectForProgram(output []byte, program string) DetectedStatus
DetectForProgram detects the status for a specific program name. Currently delegates to Detect; reserved for future per-program pattern sets.
func (*StatusDetector) DetectFromLines ¶
func (sd *StatusDetector) DetectFromLines(lines []string) DetectedStatus
DetectFromLines analyzes multiple lines of output and returns the most relevant status. This is useful for analyzing scrollback history where multiple status indicators may be present. The most recent (last) matching pattern takes precedence.
func (*StatusDetector) DetectFromString ¶
func (sd *StatusDetector) DetectFromString(output string) DetectedStatus
DetectFromString is a convenience method that accepts a string instead of []byte.
func (*StatusDetector) DetectRecent ¶
func (sd *StatusDetector) DetectRecent(output []byte, n int) DetectedStatus
DetectRecent analyzes the most recent n bytes of output for status detection. This is optimized for real-time status monitoring.
func (*StatusDetector) DetectWithContext ¶
func (sd *StatusDetector) DetectWithContext(output []byte) (DetectedStatus, string)
DetectWithContext returns the detected status along with a user-friendly context message. Uses the pattern's Description field for human-readable messages instead of raw matched text.
func (*StatusDetector) ExportPatterns ¶
func (sd *StatusDetector) ExportPatterns(path string) error
ExportPatterns exports the current patterns to a YAML file.
func (*StatusDetector) GetPatternNames ¶
func (sd *StatusDetector) GetPatternNames(status DetectedStatus) []string
GetPatternNames returns the names of all loaded patterns for a given status.
func (*StatusDetector) HasPattern ¶
func (sd *StatusDetector) HasPattern(status DetectedStatus, name string) bool
HasPattern checks if a specific pattern name exists for the given status.
func (*StatusDetector) LoadPatterns ¶
func (sd *StatusDetector) LoadPatterns(path string) error
LoadPatterns loads patterns from a YAML file.
type StatusPattern ¶
type StatusPattern struct {
Name string `yaml:"name"`
Pattern string `yaml:"pattern"`
Description string `yaml:"description"`
Priority int `yaml:"priority"` // Higher priority patterns checked first
}
StatusPattern represents a regex pattern for detecting a specific status.
type StatusPatterns ¶
type StatusPatterns struct {
Ready []StatusPattern `yaml:"ready"`
Processing []StatusPattern `yaml:"processing"`
NeedsApproval []StatusPattern `yaml:"needs_approval"`
InputRequired []StatusPattern `yaml:"input_required"` // Explicit input prompts
Error []StatusPattern `yaml:"error"`
TestsFailing []StatusPattern `yaml:"tests_failing"` // Tests are failing
Idle []StatusPattern `yaml:"idle"` // Waiting for user input
Active []StatusPattern `yaml:"active"` // Actively executing commands
Success []StatusPattern `yaml:"success"` // Task completed successfully
}
StatusPatterns contains all patterns for status detection.