errors

package
v0.17.12 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package errors provides agent-specific error types and classification for intelligent retry/recovery logic.

This package defines a taxonomy of errors that the agent can use to make informed decisions about how to handle failures. Unlike the generic StructuredError in pkg/utils, these errors are specifically designed to support the agent's retry logic and recovery strategies.

Categories:

  • CategoryTransient: Temporary failures (network, timeout, provider overload) - retryable
  • CategoryRateLimited: Rate limit/quota exhaustion - retryable with backoff
  • CategorySecurity: Security violations (blocked commands, unauthorized access) - not retryable
  • CategoryInvalidInput: Invalid parameters, malformed requests - not retryable
  • CategoryProvider: Provider-specific failures (auth, model not found) - depends on cause
  • CategoryContext: Context window exceeded, compaction needed - retryable after compaction
  • CategoryPermanent: Non-recoverable errors - not retryable

Example usage:

err := errors.NewTransientError("network timeout", originalErr)
if errors.IsRetryable(err) {
    // Retry with backoff
}

if errors.IsContextError(err) {
    // Trigger conversation compaction
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsContextError

func IsContextError(err error) bool

IsContextError checks if an error is in the Context category.

func IsInvalidInput

func IsInvalidInput(err error) bool

IsInvalidInput checks if an error is in the InvalidInput category.

func IsPermanent

func IsPermanent(err error) bool

IsPermanent checks if an error is in the Permanent category.

func IsPermission added in v0.17.5

func IsPermission(err error) bool

IsPermission checks if an error is a TypedError with CodePermission. Permission errors arise from security approval denial, approval timeout, or no approval channel — none are retryable.

func IsProviderError

func IsProviderError(err error) bool

IsProviderError checks if an error is in the Provider category.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited checks if an error is in the RateLimited category.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if an error is retryable. Returns true if the error is an AgentError with Retryable=true.

func IsSecurity

func IsSecurity(err error) bool

IsSecurity checks if an error is in the Security category.

func IsTransient

func IsTransient(err error) bool

IsTransient checks if an error is in the Transient category.

func RetryableFor added in v0.16.19

func RetryableFor(code ErrorCode) bool

RetryableFor returns whether a given ErrorCode is considered retryable.

func StatusFor added in v0.16.19

func StatusFor(code ErrorCode) int

StatusFor returns the canonical HTTP status code for a given ErrorCode.

func Wrap added in v0.16.19

func Wrap(cause error, msg string) error

Wrap returns a *TypedError with Code=CodeAgent wrapping cause with msg. If cause is already a *TypedError, it is returned unchanged (no double-wrap). To add context to an existing TypedError, use WithDetail instead. If cause is nil, returns NewAgent("", msg, nil).

func Wrapf added in v0.16.19

func Wrapf(cause error, format string, args ...any) error

Wrapf is Wrap with a formatted message. If cause is already a *TypedError, it is returned unchanged (no double-wrap). To add context to an existing TypedError, use WithDetail instead.

Types

type AgentError

type AgentError struct {
	Category  ErrorCategory
	Message   string
	Cause     error
	Retryable bool
	Metadata  map[string]string
}

AgentError represents a structured error with classification for agent retry logic. It implements the error interface and supports error unwrapping for compatibility with errors.Is() and errors.As().

func NewContextError

func NewContextError(message string, cause error) *AgentError

NewContextError creates a retryable context error. Should be retried after conversation compaction.

func NewInvalidInputError

func NewInvalidInputError(message string, cause error) *AgentError

NewInvalidInputError creates a non-retryable invalid input error. Examples: invalid parameters, malformed requests.

func NewPermanentError

func NewPermanentError(message string, cause error) *AgentError

NewPermanentError creates a non-retryable permanent error. Examples: non-recoverable failures, configuration errors.

func NewProviderError

func NewProviderError(message string, cause error, provider, model string) *AgentError

NewProviderError creates a provider-specific error. Retryability depends on the underlying cause. Includes provider and model info. For auth errors, this is not retryable. For model not found, not retryable. For provider overload, may be retryable.

func NewRateLimitError

func NewRateLimitError(message string, cause error, provider string) *AgentError

NewRateLimitError creates a retryable rate limit error. Includes provider information for key rotation decisions.

func NewSecurityError

func NewSecurityError(message string, cause error) *AgentError

NewSecurityError creates a non-retryable security error. Examples: blocked commands, unauthorized access.

func NewSecurityErrorWithAssessment added in v0.16.18

func NewSecurityErrorWithAssessment(message string, assessment string, cause error) *AgentError

NewSecurityErrorWithAssessment creates a non-retryable security error that carries a RiskAssessment explanation for the --why diagnostic. The assessment is stored in the error's metadata under the "assessment" key.

func NewTransientError

func NewTransientError(message string, cause error) *AgentError

NewTransientError creates a retryable transient error for temporary failures. Examples: network timeout, connection reset, provider overload.

func WrapWithCategory

func WrapWithCategory(err error, category ErrorCategory, message string) *AgentError

WrapWithCategory wraps an existing error with a specific category and message. The original error is preserved as the cause, maintaining the error chain.

func (*AgentError) Error

func (e *AgentError) Error() string

Error returns a formatted error message. If a cause is present, it includes the wrapped error. The format is:

[Category] message: cause

If no cause is present:

[Category] message

func (*AgentError) GetMetadata

func (e *AgentError) GetMetadata(key string) string

GetMetadata returns the value for a metadata key, or empty string if not found.

func (*AgentError) Unwrap

func (e *AgentError) Unwrap() error

Unwrap returns the underlying error for compatibility with errors.Is and errors.As.

func (*AgentError) Why added in v0.16.18

func (e *AgentError) Why() string

Why returns the RiskAssessment explanation attached to this error, or "" if no assessment was attached. Used by the --why CLI flag.

func (*AgentError) WithMetadata

func (e *AgentError) WithMetadata(key, value string) *AgentError

WithMetadata adds or updates a metadata key-value pair.

func (*AgentError) WithModel

func (e *AgentError) WithModel(model string) *AgentError

WithModel sets the model in metadata.

func (*AgentError) WithProvider

func (e *AgentError) WithProvider(provider string) *AgentError

WithProvider sets the provider in metadata.

type ErrorCategory

type ErrorCategory int

ErrorCategory represents the classification of an error for retry/recovery logic.

const (
	// CategoryTransient indicates a temporary failure that should be retried.
	// Examples: network timeout, connection reset, 502 gateway errors.
	CategoryTransient ErrorCategory = iota

	// CategoryRateLimited indicates rate limit or quota exhaustion.
	// Should be retried with exponential backoff and key rotation if available.
	CategoryRateLimited

	// CategorySecurity indicates a security violation.
	// Should NOT be retried. Examples: blocked commands, unauthorized access.
	CategorySecurity

	// CategoryInvalidInput indicates invalid parameters or malformed requests.
	// Should NOT be retried without fixing the input.
	CategoryInvalidInput

	// CategoryProvider indicates provider-specific failures.
	// Retryability depends on the underlying cause. Examples: auth errors, model not found.
	CategoryProvider

	// CategoryContext indicates context window exceeded.
	// Should be retried after conversation compaction.
	CategoryContext

	// CategoryPermanent indicates non-recoverable errors.
	// Should NOT be retried.
	CategoryPermanent
)

func GetCategory

func GetCategory(err error) (ErrorCategory, bool)

GetCategory extracts the error category from an AgentError. Returns the category and true if the error is an AgentError, or zero and false otherwise.

func (ErrorCategory) String

func (c ErrorCategory) String() string

String returns a human-readable representation of the error category.

type ErrorCode added in v0.16.19

type ErrorCode string

ErrorCode is the stable wire-level identifier for an error type. Codes are stable strings suitable for serialization across process boundaries.

const (
	// CodeUnknown indicates an unrecognized or unclassified error.
	CodeUnknown ErrorCode = "unknown"
	// CodeValidation indicates the input failed validation (bad parameters, malformed request).
	CodeValidation ErrorCode = "validation"
	// CodeNotFound indicates the requested resource does not exist.
	CodeNotFound ErrorCode = "not_found"
	// CodePermission indicates the caller lacks authorization for the operation.
	CodePermission ErrorCode = "permission"
	// CodeTimeout indicates the operation exceeded its time limit.
	CodeTimeout ErrorCode = "timeout"
	// CodeNetwork indicates a network-level failure (connect, DNS, transport).
	CodeNetwork ErrorCode = "network"
	// CodeConfig indicates a configuration error (missing, invalid, or conflicting settings).
	CodeConfig ErrorCode = "config"
	// CodeAgent indicates an agent-level failure (runner crash, internal error).
	CodeAgent ErrorCode = "agent"
	// CodeTool indicates a tool execution failure.
	CodeTool ErrorCode = "tool"
	// CodeApproval indicates an approval gate blocked the operation.
	CodeApproval ErrorCode = "approval"
)

type Severity added in v0.16.19

type Severity string

Severity represents the operational severity of an error.

const (
	// SeverityInfo indicates informational events.
	// Reserved for future non-error informational events. No constructor currently emits this severity.
	SeverityInfo Severity = "info"
	// SeverityWarning indicates a recoverable issue that may need attention.
	SeverityWarning Severity = "warning"
	// SeverityError indicates a standard error condition.
	SeverityError Severity = "error"
	// SeverityCritical indicates a configuration or system-level failure requiring immediate attention.
	SeverityCritical Severity = "critical"
)

func SeverityFor added in v0.16.19

func SeverityFor(code ErrorCode) Severity

SeverityFor returns the canonical Severity for a given ErrorCode.

type TypedError added in v0.16.19

type TypedError struct {
	Code      ErrorCode      // stable wire-level identifier
	Severity  Severity       // operational severity
	Message   string         // human-readable message
	Cause     error          // wrapped cause (may be nil)
	Component string         // source attribution, e.g. "agent.Runner", "tool.shell_command"
	Retryable bool           // whether the operation may be retried
	Status    int            // HTTP status code (0 if not applicable)
	Time      time.Time      // when the error was created
	Details   map[string]any // structured context (operation IDs, attempt counts, etc.)
}

TypedError is the base of the new typed-error hierarchy added in SP-094. It complements the legacy AgentError (above) with a wire-stable ErrorCode, HTTP status code, structured Details, and a Component field for source attribution. Call sites should prefer TypedError for new code; migration of the legacy AgentError call sites is tracked separately.

func AsTypedError added in v0.16.19

func AsTypedError(err error) *TypedError

AsTypedError extracts a *TypedError from anywhere in the error chain. Returns nil if no TypedError is present.

func NewAgent added in v0.16.19

func NewAgent(component, msg string, cause error) *TypedError

NewAgent creates a TypedError for agent-level failures.

func NewApproval added in v0.16.19

func NewApproval(msg string, details map[string]any) *TypedError

NewApproval creates a TypedError for approval-related errors.

func NewConfig added in v0.16.19

func NewConfig(msg string, cause error) *TypedError

NewConfig creates a TypedError for configuration errors.

func NewNetwork added in v0.16.19

func NewNetwork(msg string, cause error) *TypedError

NewNetwork creates a TypedError for network-related failures.

func NewNotFound added in v0.16.19

func NewNotFound(what string) *TypedError

NewNotFound creates a TypedError indicating a resource was not found.

func NewNotFoundCause added in v0.17.5

func NewNotFoundCause(what string, cause error) *TypedError

NewNotFoundCause creates a TypedError indicating a resource was not found, preserving the original error as the cause for errors.Is/errors.As traversal. Use this when wrapping a *PathError, *os.LinkError, or other syscall-level error so the underlying errno and operation context remain accessible.

func NewPermission added in v0.16.19

func NewPermission(msg string, details map[string]any) *TypedError

NewPermission creates a TypedError for permission or authorization failures.

func NewTimeout added in v0.16.19

func NewTimeout(op string, dur time.Duration) *TypedError

NewTimeout creates a TypedError for operation timeouts.

func NewTool added in v0.16.19

func NewTool(toolName string, msg string, cause error) *TypedError

NewTool creates a TypedError for tool execution failures.

func NewValidation added in v0.16.19

func NewValidation(msg string, details map[string]any) *TypedError

NewValidation creates a TypedError for input validation failures.

func (*TypedError) Error added in v0.16.19

func (e *TypedError) Error() string

Error implements the error interface. Format:

[code] message

When a cause is present:

[code] message: <cause>

func (*TypedError) Is added in v0.16.19

func (e *TypedError) Is(target error) bool

Is enables errors.Is(err, sentinel) comparisons by Code. A TypedError matches a sentinel TypedError if their Codes are equal.

func (*TypedError) Unwrap added in v0.16.19

func (e *TypedError) Unwrap() error

Unwrap returns the wrapped cause for errors.Is / errors.As traversal.

func (*TypedError) WithComponent added in v0.16.19

func (e *TypedError) WithComponent(component string) *TypedError

WithComponent sets the Component field (chainable). Returns e.

func (*TypedError) WithDetail added in v0.16.19

func (e *TypedError) WithDetail(key string, value any) *TypedError

WithDetail sets a key/value on Details (chainable). Returns e.

Jump to

Keyboard shortcuts

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