detection

package
v1.35.0 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// EventRingCap is the maximum number of DetectionEvents retained per StatusDetector.
	// Increased from 500: ClaudeController and IdleDetector share one ring; detectFromLines
	// makes up to 50 appendDetectionEvent calls per status check at 1 Hz, draining a
	// 500-slot ring in ~5 seconds. 2000 slots = ~33 seconds of headroom at 1 Hz.
	EventRingCap = 2000
	// TailSnippetBytes is the maximum bytes captured in TailSnippet.
	TailSnippetBytes = 512
)
View Source
const StatusDetectionTailBytes = 4096

StatusDetectionTailBytes is the number of bytes scanned from the tail of terminal output when determining session status. Matches DefaultIdleDetectorConfig().BufferSize.

Variables

This section is empty.

Functions

func DetectedStatusToProto added in v1.35.0

func DetectedStatusToProto(s DetectedStatus) sessionv1.DetectedStatus

DetectedStatusToProto converts the internal detection.DetectedStatus iota to the proto enum sessionv1.DetectedStatus. This is the single authoritative mapping; do not duplicate this logic in adapters or converters.

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a duration in a human-readable way.

func HasActiveScreenRedraw added in v1.35.0

func HasActiveScreenRedraw(raw []byte) bool

HasActiveScreenRedraw reports whether raw PTY bytes contain evidence that the terminal screen is actively being redrawn: a bare carriage return (not part of \r\n) or a cursor-up sequence (\x1b[NA).

func HasClaudeSpinnerActivity added in v1.35.0

func HasClaudeSpinnerActivity(tail string) bool

HasClaudeSpinnerActivity reports whether tail contains Claude Code's active-thinking vocabulary as plaintext. This is more targeted than HasActiveScreenRedraw: cursor- positioning sequences appear in both active and idle sessions (from the tmux status bar), but spinner verbs only appear when Claude Code is actively running its spinner.

Use as fallback when filterTmuxMetadata has discarded all content (filtered_len == 0) or when pattern detection falls through to the Ready catch-all on a single-line tail.

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 BinaryDetector added in v1.35.0

type BinaryDetector = dtypes.BinaryDetector

BinaryDetector provides per-binary pattern sets and optional content filtering. This is a type alias for dtypes.BinaryDetector.

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.)
	StatusExecuting       // Actively executing commands (shows "esc to interrupt")
	StatusSuccess         // Task completed successfully
	StatusWaitingForAgent // Waiting for one or more background agents to finish
)

func (DetectedStatus) String

func (s DetectedStatus) String() string

StatusString converts DetectedStatus to a human-readable string.

type DetectionEvent added in v1.35.0

type DetectionEvent struct {
	SessionID       string
	Timestamp       time.Time
	MatchedPattern  string // Pattern Name field, or "<none>" if StatusUnknown
	MatchedCategory string // "active", "processing", "idle", etc., or "unknown"
	ResultStatus    DetectedStatus
	TailSnippet     string // Last TailSnippetBytes of cleaned terminal output
}

DetectionEvent records a single invocation of Detect() or DetectWithContext().

type DetectionEventSink added in v1.35.0

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

DetectionEventSink owns the ring buffer and session ID for detection events. StatusDetector delegates all event recording and retrieval to this component.

func (*DetectionEventSink) Recent added in v1.35.0

func (s *DetectionEventSink) Recent(n int) []DetectionEvent

Recent returns up to n most-recent DetectionEvents, newest-first.

func (*DetectionEventSink) Record added in v1.35.0

func (s *DetectionEventSink) Record(status DetectedStatus, patternName, cleanedText string)

Record appends a detection event to the ring buffer.

func (*DetectionEventSink) SetSessionID added in v1.35.0

func (s *DetectionEventSink) SetSessionID(id string)

SetSessionID sets the session identifier embedded in all future DetectionEvents.

type DetectorRegistry added in v1.35.0

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

DetectorRegistry maps binary name -> BinaryDetector.

func DefaultRegistry added in v1.35.0

func DefaultRegistry() *DetectorRegistry

DefaultRegistry returns a DetectorRegistry pre-populated with all built-in binary detectors.

func NewDetectorRegistry added in v1.35.0

func NewDetectorRegistry() *DetectorRegistry

NewDetectorRegistry creates a new empty DetectorRegistry.

func (*DetectorRegistry) Len added in v1.35.0

func (r *DetectorRegistry) Len() int

Len returns the number of registered detectors.

func (*DetectorRegistry) Lookup added in v1.35.0

func (r *DetectorRegistry) Lookup(name string) (BinaryDetector, bool)

Lookup returns the BinaryDetector for the given binary name, and whether it was found.

func (*DetectorRegistry) Names added in v1.35.0

func (r *DetectorRegistry) Names() []string

Names returns all registered binary names.

func (*DetectorRegistry) Register added in v1.35.0

func (r *DetectorRegistry) Register(d BinaryDetector)

Register adds a BinaryDetector to the registry. Panics if a detector with the same name has already been registered.

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 NewIdleDetectorWithDetector added in v1.35.0

func NewIdleDetectorWithDetector(sessionName string, ptyAccess PTYReader, config IdleDetectorConfig, detector TerminalDetector) *IdleDetector

NewIdleDetectorWithDetector creates a new idle detector that uses the provided TerminalDetector instead of creating its own. When detector is nil, falls back to creating a new StatusDetector (same as NewIdleDetectorWithConfig).

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) 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 IdleState

type IdleState int

IdleState represents the idle state of a Claude Code session.

const (
	IdleStateUnknown IdleState = iota // Unable to determine state
	IdleStateActive                   // Actively processing commands (shows "esc to interrupt")
	IdleStateWaiting                  // Waiting for user input (INSERT mode, command prompt)
	IdleStateTimeout                  // No activity for extended period
)

func (IdleState) String

func (s IdleState) String() string

String returns a human-readable string representation of the idle state.

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 PTYNormalizer added in v1.35.0

type PTYNormalizer struct{}

PTYNormalizer handles ANSI stripping and carriage-return collapsing for PTY output. It is a stateless struct; all methods are pure transformations.

func (PTYNormalizer) Normalize added in v1.35.0

func (n PTYNormalizer) Normalize(content string) string

Normalize strips ANSI escape sequences and collapses CR-overwritten segments. Equivalent to stripANSI(collapseCarriageReturns(content)).

func (PTYNormalizer) SplitLines added in v1.35.0

func (n PTYNormalizer) SplitLines(content string) []string

SplitLines splits normalized content into non-blank lines.

type PTYReader

type PTYReader interface {
	GetRecentOutput(n int) []byte
}

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 PatternSet added in v1.35.0

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

PatternSet holds compiled regex slices for all StatusPatterns categories. All field mutations after construction must acquire mu before writing.

func NewPatternSet added in v1.35.0

func NewPatternSet(p StatusPatterns) (*PatternSet, error)

NewPatternSet compiles all patterns in p. Returns an error if any regex is invalid.

func (*PatternSet) MatchLines added in v1.35.0

func (ps *PatternSet) MatchLines(text string, rawPTY []byte) (DetectedStatus, string, string)

MatchLines runs the pattern priority chain on the given text string and raw PTY bytes. Returns (status, patternName, description). Acquires mu.RLock.

func (*PatternSet) Patterns added in v1.35.0

func (ps *PatternSet) Patterns() StatusPatterns

Patterns returns the StatusPatterns used by this PatternSet.

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 output from a named program. When the program has a registered BinaryDetector, its per-binary pattern set is consulted first. If the per-binary detector returns StatusUnknown (no match), the generic Detect() is called as a fallback. For unregistered programs, only the generic Detect() is used.

func (*StatusDetector) DetectFromLines

func (sd *StatusDetector) DetectFromLines(lines []string) DetectedStatus

DetectFromLines analyzes multiple lines of output and returns the most relevant status. Lines are processed in reverse order (most recent first) so the current terminal state takes precedence over stale scrollback content.

Blank/whitespace-only lines are skipped. StatusReady results are noted but the scan continues looking for a more specific status — this prevents the `.*` Ready catch-all from stopping the scan on an unrelated line (e.g. "PR #66") before reaching a real status pattern on an earlier line. StatusReady is returned as a fallback if no more specific status is found.

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) DetectWithContextFromLines added in v1.35.0

func (sd *StatusDetector) DetectWithContextFromLines(lines []string) (DetectedStatus, string)

DetectWithContextFromLines analyzes lines in reverse order (most recent first) and returns the detected status with context. This ensures current terminal state (e.g. "? for shortcuts" on the last line) takes precedence over stale scrollback content (e.g. an old "esc to interrupt" from a previous turn that is still within the scanned window).

Blank/whitespace-only lines are skipped. StatusReady is treated as a low-confidence fallback — the scan continues past Ready results looking for a more specific status, preventing the `.*` catch-all from masking real patterns on earlier lines.

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.

func (*StatusDetector) RecentEvents added in v1.35.0

func (sd *StatusDetector) RecentEvents(n int) []DetectionEvent

RecentEvents returns up to n most-recent DetectionEvents, newest-first.

func (*StatusDetector) SetSessionID added in v1.35.0

func (sd *StatusDetector) SetSessionID(id string)

SetSessionID sets the session identifier embedded in all future DetectionEvents. Call this once after creating the detector, before any detections run.

type StatusPattern

type StatusPattern = dtypes.StatusPattern

StatusPattern represents a regex pattern for detecting a specific status. This is a type alias for dtypes.StatusPattern to avoid import cycles while keeping the type accessible from this package without qualification.

type StatusPatterns

type StatusPatterns = dtypes.StatusPatterns

StatusPatterns contains all patterns for status detection. This is a type alias for dtypes.StatusPatterns.

type TerminalDetector added in v1.35.0

type TerminalDetector interface {
	Detect(output []byte) DetectedStatus
	DetectWithContext(output []byte) (DetectedStatus, string)
	DetectWithContextFromLines(lines []string) (DetectedStatus, string)
	DetectFromLines(lines []string) DetectedStatus
	RecentEvents(n int) []DetectionEvent
	SetSessionID(id string)
}

TerminalDetector is the interface implemented by StatusDetector that consumer packages (session, server/services) depend on. Defined here (consumer-of-input pattern) so all call sites can use the interface without importing the concrete type.

Directories

Path Synopsis
Package binaries provides per-binary BinaryDetector implementations.
Package binaries provides per-binary BinaryDetector implementations.
Package dtypes contains shared types for the detection package and its sub-packages.
Package dtypes contains shared types for the detection package and its sub-packages.

Jump to

Keyboard shortcuts

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