Documentation
¶
Overview ¶
Package statemachine provides a declarative state machine framework for orchestrating complex workflows.
Index ¶
- Constants
- Variables
- func SetConfigLoader(loader ConfigLoader)
- func WrapStateError(state string, err error) error
- func WrapTransitionError(from, to string, err error) error
- type Action
- type ActionBuilder
- type ActionConfig
- type ActionExecutionHook
- type ActionFactory
- type ActionState
- type BaseAction
- type Builder
- func (b *Builder) AddActionState(name string, action Action, next string) *Builder
- func (b *Builder) AddConditionalState(name string, cond func(*Context) (string, error)) *Builder
- func (b *Builder) AddState(config StateConfig) *Builder
- func (b *Builder) AddTransition(config TransitionConfig) *Builder
- func (b *Builder) Build() (*Engine, error)
- func (b *Builder) RegisterActionBuilder(actionType string, builder ActionBuilder) *Builder
- func (b *Builder) WithFinalStates(states ...string) *Builder
- func (b *Builder) WithInitialState(state string) *Builder
- type ConditionalAction
- type ConditionalState
- type ConditionalTransition
- type Config
- type ConfigLoader
- type Context
- func (c *Context) AddTransition(from, to string, data map[string]any)
- func (c *Context) AppendToPath(state string)
- func (c *Context) Clone() *Context
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) GetBool(key string) (bool, bool)
- func (c *Context) GetInt(key string) (int, bool)
- func (c *Context) GetString(key string) (string, bool)
- func (c *Context) Merge(data map[string]any)
- func (c *Context) Set(key string, value any)
- type DefaultLogger
- func (l *DefaultLogger) ActionCompleted(ctx context.Context, action string, duration time.Duration, err error)
- func (l *DefaultLogger) ActionStarted(ctx context.Context, action string)
- func (l *DefaultLogger) StateEntered(ctx context.Context, state string, data map[string]any)
- func (l *DefaultLogger) StateExited(ctx context.Context, state string, duration time.Duration, err error)
- func (l *DefaultLogger) TransitionExecuted(ctx context.Context, from, to string)
- type Engine
- func (e *Engine) AddExecutionHook(hook ActionExecutionHook)
- func (e *Engine) Execute(ctx context.Context, smCtx *Context) (err error)
- func (e *Engine) RegisterState(state State)
- func (e *Engine) RegisterTransition(transition Transition)
- func (e *Engine) SetActionTimeout(timeout time.Duration)
- func (e *Engine) SetCancellationEnabled(enabled bool)
- func (e *Engine) SetLogger(logger Logger)
- type ExpressionTransition
- type FinalState
- type Logger
- type LoggingAction
- type LoggingEngine
- type NoopAction
- type ObservabilityLabels
- type ParallelAction
- type RetryAction
- type SequenceAction
- type SimpleTransition
- type State
- type StateConfig
- type StateError
- type StateTransition
- type Transition
- type TransitionConfig
- type TransitionError
- type TransitionResult
- type ValidationAction
- type ValidatorFunc
Constants ¶
const (
// StateTypeConditional represents a conditional state type.
StateTypeConditional = "conditional"
)
Variables ¶
var ( ErrStateNotFound = errors.New("state not found") ErrTransitionNotFound = errors.New("no valid transition found") ErrInvalidConfig = errors.New("invalid configuration") ErrSamplingNotAvailable = errors.New("sampling not available") ErrElicitationNotAvailable = errors.New("elicitation not available") ErrValidationDataNotFound = errors.New("validation data not found in context") ErrActionFailed = errors.New("action execution failed") ErrTimeout = errors.New("state execution timeout") // ErrConfigNameRequired indicates that a configuration name is required. ErrConfigNameRequired = errors.New("config name is required") // ErrInitialStateRequired indicates that an initial state is required. ErrInitialStateRequired = errors.New("initial state is required") // ErrFinalStateRequired indicates that at least one final state is required. ErrFinalStateRequired = errors.New("at least one final state is required") // ErrStateRequired indicates that at least one state is required. ErrStateRequired = errors.New("at least one state is required") // ErrInitialStateNotFound indicates that the initial state does not exist. ErrInitialStateNotFound = errors.New("initial state does not exist") // ErrFinalStateNotFound indicates that a final state does not exist. ErrFinalStateNotFound = errors.New("final state does not exist") // ErrStateNameRequired indicates that a state name is required. ErrStateNameRequired = errors.New("state name is required") // ErrDuplicateStateName indicates that a duplicate state name was found. ErrDuplicateStateName = errors.New("duplicate state name") // ErrStateTypeRequired indicates that a state type is required. ErrStateTypeRequired = errors.New("state type is required") // ErrActionStateMissingAction indicates that an action state must have at least one action. ErrActionStateMissingAction = errors.New("action state must have at least one action") // ErrActionTypeRequired indicates that an action type is required. ErrActionTypeRequired = errors.New("action type is required") // ErrActionNameRequired indicates that an action name is required. ErrActionNameRequired = errors.New("action name is required") // ErrTransitionFromRequired indicates that a transition from state is required. ErrTransitionFromRequired = errors.New("transition from state is required") // ErrTransitionToRequired indicates that a transition to state is required. ErrTransitionToRequired = errors.New("transition to state is required") // ErrTransitionFromNotFound indicates that a transition from state does not exist. ErrTransitionFromNotFound = errors.New("transition from state does not exist") // ErrTransitionToNotFound indicates that a transition to state does not exist. ErrTransitionToNotFound = errors.New("transition to state does not exist") // ErrNoConfigLoader indicates that no config loader is registered. ErrNoConfigLoader = errors.New("no config loader registered; use SetConfigLoader() or provide a file path") // ErrConditionalNotImplemented indicates that conditional state types are not yet implemented. ErrConditionalNotImplemented = errors.New("conditional state type not yet implemented") // ErrUnknownStateType indicates that an unknown state type was encountered. ErrUnknownStateType = errors.New("unknown state type") // ErrUnknownActionType indicates that an unknown action type was encountered. ErrUnknownActionType = errors.New("unknown action type") // ErrInvalidActionFormat indicates that an action has an invalid format. ErrInvalidActionFormat = errors.New("invalid action format") // ErrSamplingUserRequired indicates that a sampling action requires a 'user' parameter. ErrSamplingUserRequired = errors.New("sampling action requires 'user' parameter") // ErrElicitationMessageRequired indicates that an elicitation action requires a 'message' parameter. ErrElicitationMessageRequired = errors.New("elicitation action requires 'message' parameter") // ErrElicitationSchemaRequired indicates that an elicitation action requires a 'schema' parameter. ErrElicitationSchemaRequired = errors.New("elicitation action requires 'schema' parameter") // ErrInvalidSchemaField indicates that a schema field is invalid. ErrInvalidSchemaField = errors.New("invalid schema field") // ErrValidationMustBeProgrammatic indicates that validation actions must be created programmatically. ErrValidationMustBeProgrammatic = errors.New( "validation actions must be created programmatically with NewValidationAction", ) // ErrSequenceActionsRequired indicates that a sequence action requires an 'actions' parameter. ErrSequenceActionsRequired = errors.New("sequence action requires 'actions' parameter") // ErrInvalidActionConfig indicates that an action config is invalid. ErrInvalidActionConfig = errors.New("invalid action config") // ErrConditionalMustBeProgrammatic indicates that conditional actions must be created programmatically. ErrConditionalMustBeProgrammatic = errors.New( "conditional actions must be created programmatically with NewConditionalAction", ) // ErrRetryActionRequired indicates that a retry action requires an 'action' parameter. ErrRetryActionRequired = errors.New("retry action requires 'action' parameter") // ErrSampleWithFallbackMustBeProgrammatic indicates that sample_with_fallback must be created programmatically. ErrSampleWithFallbackMustBeProgrammatic = errors.New( "sample_with_fallback must be created programmatically - see actions.SampleWithFallback", ) // ErrElicitFormMustBeProgrammatic indicates that elicit_form must be created programmatically. ErrElicitFormMustBeProgrammatic = errors.New( "elicit_form must be created programmatically - see actions.ElicitForm", ) // ErrElicitConfirmationMustBeProgrammatic indicates that elicit_confirmation must be created programmatically. ErrElicitConfirmationMustBeProgrammatic = errors.New( "elicit_confirmation must be created programmatically - see actions.ElicitConfirmation", ) // ErrValidateTransitionMustBeProgrammatic indicates that validate_transition must be created programmatically. ErrValidateTransitionMustBeProgrammatic = errors.New( "validate_transition must be created programmatically - see actions.ValidateTransition", ) // ErrTryWithFallbackMustBeProgrammatic indicates that try_with_fallback must be created programmatically. ErrTryWithFallbackMustBeProgrammatic = errors.New( "try_with_fallback must be created programmatically - see actions.TryWithFallback", ) // ErrValidatedSequenceMustBeProgrammatic indicates that validated_sequence must be created programmatically. ErrValidatedSequenceMustBeProgrammatic = errors.New( "validated_sequence must be created programmatically - see actions.ValidatedSequence", ) // ErrRetryWithBackoffMustBeProgrammatic indicates that retry_with_backoff must be created programmatically. ErrRetryWithBackoffMustBeProgrammatic = errors.New( "retry_with_backoff must be created programmatically - see actions.RetryWithBackoff", ) // ErrInvalidExpression indicates that an expression is invalid. ErrInvalidExpression = errors.New("invalid expression") // ErrUnsupportedExpression indicates that an expression is unsupported. ErrUnsupportedExpression = errors.New("unsupported expression") // ErrTestActionFailed is used in test files to indicate that an action failed. ErrTestActionFailed = errors.New("action failed") // ErrTestAction2Failed is used in test files to indicate that action2 failed. ErrTestAction2Failed = errors.New("action2 failed") // ErrTestTemporary is used in test files to indicate a temporary error. ErrTestTemporary = errors.New("temporary error") // ErrTestPermanent is used in test files to indicate a permanent error. ErrTestPermanent = errors.New("permanent error") )
Predefined error types.
Functions ¶
func SetConfigLoader ¶
func SetConfigLoader(loader ConfigLoader)
SetConfigLoader sets the default config loader for name-based loading. This allows applications to provide embedded configs or custom loading logic.
func WrapStateError ¶
WrapStateError wraps an error with state context.
func WrapTransitionError ¶
WrapTransitionError wraps an error with transition context.
Types ¶
type ActionBuilder ¶
ActionBuilder is a function that creates an action from configuration. The factory parameter allows reusing custom builders for nested actions.
type ActionConfig ¶
type ActionConfig struct {
Type string `json:"type" yaml:"type"`
Name string `json:"name" yaml:"name"`
Parameters map[string]any `json:"parameters" yaml:"parameters"`
}
ActionConfig defines the configuration for an action. Type can be: "sampling", "elicitation", "validation", "sequence", "conditional".
type ActionExecutionHook ¶
type ActionExecutionHook func(ctx context.Context, actionName string, stateName string, phase string, err error)
ActionExecutionHook is called before and after action execution.
type ActionFactory ¶
type ActionFactory struct {
// contains filtered or unexported fields
}
ActionFactory creates actions from configuration. Applications can register custom action builders to extend the framework.
func NewActionFactory ¶
func NewActionFactory() *ActionFactory
NewActionFactory creates a new action factory with default builders.
func (*ActionFactory) Create ¶
func (f *ActionFactory) Create(config ActionConfig) (Action, error)
Create creates an action from configuration.
func (*ActionFactory) Register ¶
func (f *ActionFactory) Register(actionType string, builder ActionBuilder)
Register registers a custom action builder.
type ActionState ¶
type ActionState struct {
// contains filtered or unexported fields
}
ActionState executes a single action.
func NewActionState ¶
func NewActionState(name string, action Action, next string) *ActionState
NewActionState creates a new action state.
func (*ActionState) Execute ¶
func (s *ActionState) Execute(ctx context.Context, smCtx *Context) (TransitionResult, error)
func (*ActionState) Name ¶
func (s *ActionState) Name() string
type BaseAction ¶
type BaseAction struct {
// contains filtered or unexported fields
}
BaseAction provides common functionality for actions.
func (*BaseAction) Name ¶
func (a *BaseAction) Name() string
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder provides a fluent API for constructing state machines.
func NewBuilder ¶
NewBuilder creates a new state machine builder.
func (*Builder) AddActionState ¶
AddActionState adds a simple action state.
func (*Builder) AddConditionalState ¶
AddConditionalState adds a conditional state.
func (*Builder) AddState ¶
func (b *Builder) AddState(config StateConfig) *Builder
AddState adds a state configuration.
func (*Builder) AddTransition ¶
func (b *Builder) AddTransition(config TransitionConfig) *Builder
AddTransition adds a transition configuration.
func (*Builder) RegisterActionBuilder ¶
func (b *Builder) RegisterActionBuilder(actionType string, builder ActionBuilder) *Builder
RegisterActionBuilder registers a custom action builder.
func (*Builder) WithFinalStates ¶
WithFinalStates sets the final states.
func (*Builder) WithInitialState ¶
WithInitialState sets the initial state.
type ConditionalAction ¶
type ConditionalAction struct {
BaseAction
// contains filtered or unexported fields
}
ConditionalAction executes action based on condition.
func NewConditionalAction ¶
func NewConditionalAction( name string, cond func(ctx context.Context, smCtx *Context) (bool, error), thenAction, elseAction Action, ) *ConditionalAction
NewConditionalAction creates a new conditional action.
type ConditionalState ¶
type ConditionalState struct {
// contains filtered or unexported fields
}
ConditionalState branches based on context data.
func NewConditionalState ¶
func NewConditionalState( name string, cond func(ctx context.Context, smCtx *Context) (string, error), ) *ConditionalState
NewConditionalState creates a new conditional state.
func (*ConditionalState) Execute ¶
func (s *ConditionalState) Execute(ctx context.Context, smCtx *Context) (TransitionResult, error)
func (*ConditionalState) Name ¶
func (s *ConditionalState) Name() string
type ConditionalTransition ¶
type ConditionalTransition struct {
// contains filtered or unexported fields
}
ConditionalTransition checks context before transitioning.
func NewConditionalTransition ¶
func NewConditionalTransition( from, to string, cond func(ctx context.Context, smCtx *Context) (bool, error), ) *ConditionalTransition
NewConditionalTransition creates a new conditional transition.
func (*ConditionalTransition) From ¶
func (t *ConditionalTransition) From() string
func (*ConditionalTransition) To ¶
func (t *ConditionalTransition) To() string
type Config ¶
type Config struct {
Name string `json:"name" yaml:"name"`
InitialState string `json:"initialState" yaml:"initialState"`
FinalStates []string `json:"finalStates" yaml:"finalStates"`
States []StateConfig `json:"states" yaml:"states"`
Transitions []TransitionConfig `json:"transitions" yaml:"transitions"`
}
Config defines the structure of a state machine configuration.
func LoadConfig ¶
LoadConfig loads a state machine configuration by path or name. Supports two modes:
- Path mode: Pass a file path (containing '/', '\', or ending in '.yaml') to load from filesystem Example: LoadConfig("examples/simple.yaml"), LoadConfig("testdata/config.yaml")
- Name mode: Pass a bare name to load via the registered ConfigLoader Example: LoadConfig("guided_setup")
For name mode to work, you must call SetConfigLoader() first with an implementation.
func LoadConfigFromBytes ¶
LoadConfigFromBytes loads a state machine configuration from YAML bytes.
func LoadConfigFromFS ¶
LoadConfigFromFS loads a configuration from an embedded filesystem. This is a convenience function for loading from embed.FS.
type ConfigLoader ¶
ConfigLoader is an interface for loading configurations by name. Applications can implement this to provide embedded or custom config loading.
type Context ¶
type Context struct {
SessionID string
ProjectID string
CurrentState string
Data map[string]any
History []StateTransition
Metadata map[string]any
CreatedAt time.Time
UpdatedAt time.Time
Provider string // Provider being configured (e.g., "salesforce", "hubspot")
ContextChunkID string // Unique ID for this conversation chunk/interaction
ToolName string // Tool name (e.g., "guided_setup", "integration_doctor")
PathHistory []string // Ordered list of states visited (append CurrentState on entry)
// contains filtered or unexported fields
}
Context is a thread-safe context object that carries data between states.
func NewContext ¶
NewContext creates a new state machine context.
func (*Context) AddTransition ¶
AddTransition records a state transition in the history.
func (*Context) AppendToPath ¶
AppendToPath adds the current state to the path history.
type DefaultLogger ¶
type DefaultLogger struct {
}
DefaultLogger implements Logger using amp-common/logger for trace correlation.
func NewDefaultLogger ¶
func NewDefaultLogger() *DefaultLogger
NewDefaultLogger creates a new default logger.
func (*DefaultLogger) ActionCompleted ¶
func (*DefaultLogger) ActionStarted ¶
func (l *DefaultLogger) ActionStarted(ctx context.Context, action string)
func (*DefaultLogger) StateEntered ¶
func (*DefaultLogger) StateExited ¶
func (*DefaultLogger) TransitionExecuted ¶
func (l *DefaultLogger) TransitionExecuted(ctx context.Context, from, to string)
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine orchestrates state machine execution.
func NewEngine ¶
func NewEngine(config *Config, factory *ActionFactory) (*Engine, error)
NewEngine creates a new state machine engine from a configuration. If factory is nil, a new default factory is created.
func (*Engine) AddExecutionHook ¶
func (e *Engine) AddExecutionHook(hook ActionExecutionHook)
AddExecutionHook adds a hook to be called before and after each action execution. Hooks are called with phase "start" before execution and "end" after execution.
func (*Engine) RegisterState ¶
RegisterState registers a state with the engine.
func (*Engine) RegisterTransition ¶
func (e *Engine) RegisterTransition(transition Transition)
RegisterTransition registers a transition with the engine.
func (*Engine) SetActionTimeout ¶
SetActionTimeout sets the maximum duration for action execution. A timeout of 0 means no timeout.
func (*Engine) SetCancellationEnabled ¶
SetCancellationEnabled enables or disables context cancellation handling.
type ExpressionTransition ¶
type ExpressionTransition struct {
// contains filtered or unexported fields
}
ExpressionTransition evaluates expression against context.
func NewExpressionTransition ¶
func NewExpressionTransition(from, to, expr string) *ExpressionTransition
NewExpressionTransition creates a new expression-based transition.
func (*ExpressionTransition) From ¶
func (t *ExpressionTransition) From() string
func (*ExpressionTransition) To ¶
func (t *ExpressionTransition) To() string
type FinalState ¶
type FinalState struct {
// contains filtered or unexported fields
}
FinalState marks completion.
func NewFinalState ¶
func NewFinalState(name string) *FinalState
NewFinalState creates a new final state.
func (*FinalState) Execute ¶
func (s *FinalState) Execute(ctx context.Context, smCtx *Context) (TransitionResult, error)
func (*FinalState) Name ¶
func (s *FinalState) Name() string
type Logger ¶
type Logger interface {
StateEntered(ctx context.Context, state string, data map[string]any)
StateExited(ctx context.Context, state string, duration time.Duration, err error)
TransitionExecuted(ctx context.Context, from, to string)
ActionStarted(ctx context.Context, action string)
ActionCompleted(ctx context.Context, action string, duration time.Duration, err error)
}
Logger provides logging hooks for state machine execution.
type LoggingAction ¶
type LoggingAction struct {
// contains filtered or unexported fields
}
LoggingAction wraps an action with logging.
func NewLoggingAction ¶
func NewLoggingAction(action Action, logger Logger) *LoggingAction
NewLoggingAction wraps an action with logging.
func (*LoggingAction) Execute ¶
func (a *LoggingAction) Execute(ctx context.Context, smCtx *Context) error
func (*LoggingAction) Name ¶
func (a *LoggingAction) Name() string
type LoggingEngine ¶
type LoggingEngine struct {
// contains filtered or unexported fields
}
LoggingEngine wraps an engine with logging.
func WithLogging ¶
func WithLogging(engine *Engine, logger Logger) *LoggingEngine
WithLogging wraps an engine with logging capabilities.
type NoopAction ¶
type NoopAction struct {
BaseAction
}
NoopAction is a no-operation action for testing workflows.
func NewNoopAction ¶
func NewNoopAction(name string) *NoopAction
NewNoopAction creates a new noop action.
type ObservabilityLabels ¶
type ObservabilityLabels struct {
SessionID string
ProjectID string
Provider string
ContextChunkID string
ToolName string
CurrentState string
PathHistory []string
}
ObservabilityLabels contains contextual labels for observability.
func GetObservabilityLabels ¶
func GetObservabilityLabels(ctx context.Context) ObservabilityLabels
GetObservabilityLabels extracts observability labels from the context. Returns an empty ObservabilityLabels struct if no Context is found.
type ParallelAction ¶
type ParallelAction struct {
BaseAction
// contains filtered or unexported fields
}
ParallelAction executes actions concurrently.
func NewParallelAction ¶
func NewParallelAction(name string, actions ...Action) *ParallelAction
NewParallelAction creates a new parallel action.
type RetryAction ¶
type RetryAction struct {
BaseAction
// contains filtered or unexported fields
}
RetryAction retries action on failure.
func NewRetryAction ¶
NewRetryAction creates a new retry action.
type SequenceAction ¶
type SequenceAction struct {
BaseAction
// contains filtered or unexported fields
}
SequenceAction executes actions in order.
func NewSequenceAction ¶
func NewSequenceAction(name string, actions ...Action) *SequenceAction
NewSequenceAction creates a new sequence action.
type SimpleTransition ¶
type SimpleTransition struct {
// contains filtered or unexported fields
}
SimpleTransition always transitions from A to B.
func NewSimpleTransition ¶
func NewSimpleTransition(from, to string) *SimpleTransition
NewSimpleTransition creates a new simple transition.
func (*SimpleTransition) From ¶
func (t *SimpleTransition) From() string
func (*SimpleTransition) To ¶
func (t *SimpleTransition) To() string
type State ¶
type State interface {
Name() string
Execute(ctx context.Context, smCtx *Context) (TransitionResult, error)
}
State represents a single state in the state machine.
type StateConfig ¶
type StateConfig struct {
Name string `json:"name" yaml:"name"`
Type string `json:"type" yaml:"type"` // "action", "composite", "conditional", "final"
Actions []ActionConfig `json:"actions" yaml:"actions"`
OnError string `json:"onError" yaml:"onError"`
Timeout string `json:"timeout" yaml:"timeout"`
Metadata map[string]any `json:"metadata" yaml:"metadata"`
}
StateConfig defines the configuration for a state.
type StateError ¶
StateError wraps an error with state context.
func (*StateError) Error ¶
func (e *StateError) Error() string
func (*StateError) Unwrap ¶
func (e *StateError) Unwrap() error
type StateTransition ¶
StateTransition records a transition in the state machine history.
type Transition ¶
type Transition interface {
From() string
To() string
Condition(ctx context.Context, smCtx *Context) (bool, error)
}
Transition represents a state transition rule.
type TransitionConfig ¶
type TransitionConfig struct {
From string `json:"from" yaml:"from"`
To string `json:"to" yaml:"to"`
Condition string `json:"condition" yaml:"condition"` // expression or "always"
Priority int `json:"priority" yaml:"priority"`
}
TransitionConfig defines the configuration for a transition.
type TransitionError ¶
TransitionError wraps an error with transition context.
func (*TransitionError) Error ¶
func (e *TransitionError) Error() string
func (*TransitionError) Unwrap ¶
func (e *TransitionError) Unwrap() error
type TransitionResult ¶
TransitionResult indicates the outcome of state execution.
type ValidationAction ¶
type ValidationAction struct {
BaseAction
// contains filtered or unexported fields
}
ValidationAction performs validation with optional sampling for feedback.
func NewValidationAction ¶
func NewValidationAction( name string, validator func(ctx context.Context, smCtx *Context) (bool, string, error), ) *ValidationAction
NewValidationAction creates a new validation action.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package actions provides composable actions for state machine workflows, including sampling, elicitation, validation, and error handling primitives.
|
Package actions provides composable actions for state machine workflows, including sampling, elicitation, validation, and error handling primitives. |
|
Package helpers provides utility functions for state machine operations.
|
Package helpers provides utility functions for state machine operations. |
|
Package testing provides testing utilities for state machine workflows.
|
Package testing provides testing utilities for state machine workflows. |
|
Package validator provides validation and auto-fixing for state machine configurations.
|
Package validator provides validation and auto-fixing for state machine configurations. |
|
Package visualizer generates visual diagrams from state machine configurations.
|
Package visualizer generates visual diagrams from state machine configurations. |