statemachine

package
v0.0.0-...-a14d088 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2026 License: MIT Imports: 21 Imported by: 0

README

State Machine Framework

A generic, reusable state machine framework for building declarative workflows in Go.

Overview

This package provides a declarative state machine framework that has been extracted from the server repository into amp-common for reusability across projects.

Architecture

Core Framework (in amp-common)

The core framework provides:

  • Engine: State machine orchestration and execution
  • Config Loading: Flexible configuration loading with pluggable loaders
  • States: Action, Conditional, and Final state types
  • Transitions: Rule-based state transitions with expression evaluation
  • Actions: Composable action system with sequence, conditional support
  • Context: Thread-safe data carrier for workflow state
  • Observability: Built-in metrics, logging, and OpenTelemetry tracing
  • Developer Tools: Validation, visualization, and testing utilities
Extensibility

The framework is designed to be extended by applications:

Config Loading:

// Applications implement ConfigLoader to provide embedded configs
type ConfigLoader interface {
    LoadByName(name string) ([]byte, error)
    ListAvailable() []string
}

// Register your loader
statemachine.SetConfigLoader(myLoader)

Custom Actions:

// Register custom action builders
factory := statemachine.NewActionFactory()
factory.Register("my_action", func(factory *ActionFactory, name string, params map[string]any) (Action, error) {
    // Create your custom action
    return myAction, nil
})

Usage

Basic Example
package main

import (
    "context"
    sm "github.com/amp-labs/amp-common/statemachine"
)

func main() {
    // Load configuration (requires a ConfigLoader to be registered)
    config, err := sm.LoadConfig("my_workflow")
    if err != nil {
        panic(err)
    }

    // Create engine
    engine, err := sm.NewEngine(config, nil)
    if err != nil {
        panic(err)
    }

    // Execute workflow
    ctx := context.Background()
    smCtx := sm.NewContext("session-123", "project-456")

    if err := engine.Execute(ctx, smCtx); err != nil {
        panic(err)
    }
}
Custom Actions
// Define your action type
type MyAction struct {
    sm.BaseAction
    // ... your fields
}

func (a *MyAction) Execute(ctx context.Context, smCtx *sm.Context) error {
    // ... your logic
    return nil
}

// Register it with the factory
factory.Register("my_action", func(f *sm.ActionFactory, name string, params map[string]any) (sm.Action, error) {
    return &MyAction{BaseAction: sm.BaseAction{name: name}}, nil
})

Dependencies

This package depends on github.com/amp-labs/server for sampling and elicitation packages. This is acceptable because:

  1. It's a local replace dependency (not published)
  2. The server is the primary consumer
  3. The framework remains generic - sampling/elicitation are just example actions

Migration from Server

If you're migrating code that used github.com/amp-labs/server/builder-mcp/statemachine:

  1. Update imports: github.com/amp-labs/server/builder-mcp/statemachinegithub.com/amp-labs/amp-common/statemachine
  2. If you used embedded configs, implement ConfigLoader in your application
  3. If you used custom actions with sampling/elicitation, keep those in your application

Documentation

For detailed documentation, see the original README and docs in the server repository at /builder-mcp/statemachine/.

Documentation

Overview

Package statemachine provides a declarative state machine framework for orchestrating complex workflows.

Index

Constants

View Source
const (
	// StateTypeConditional represents a conditional state type.
	StateTypeConditional = "conditional"
)

Variables

View Source
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

func WrapStateError(state string, err error) error

WrapStateError wraps an error with state context.

func WrapTransitionError

func WrapTransitionError(from, to string, err error) error

WrapTransitionError wraps an error with transition context.

Types

type Action

type Action interface {
	Execute(ctx context.Context, smCtx *Context) error
	Name() string
}

Action represents a composable unit of work.

type ActionBuilder

type ActionBuilder func(factory *ActionFactory, name string, params map[string]any) (Action, error)

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

func NewBuilder(name string) *Builder

NewBuilder creates a new state machine builder.

func (*Builder) AddActionState

func (b *Builder) AddActionState(name string, action Action, next string) *Builder

AddActionState adds a simple action state.

func (*Builder) AddConditionalState

func (b *Builder) AddConditionalState(name string, cond func(*Context) (string, error)) *Builder

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

func (b *Builder) Build() (*Engine, error)

Build constructs the state machine engine.

func (*Builder) RegisterActionBuilder

func (b *Builder) RegisterActionBuilder(actionType string, builder ActionBuilder) *Builder

RegisterActionBuilder registers a custom action builder.

func (*Builder) WithFinalStates

func (b *Builder) WithFinalStates(states ...string) *Builder

WithFinalStates sets the final states.

func (*Builder) WithInitialState

func (b *Builder) WithInitialState(state string) *Builder

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.

func (*ConditionalAction) Execute

func (a *ConditionalAction) Execute(ctx context.Context, smCtx *Context) error

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

func (t *ConditionalTransition) Condition(ctx context.Context, smCtx *Context) (bool, error)

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

func LoadConfig(pathOrName string) (*Config, error)

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

func LoadConfigFromBytes(data []byte) (*Config, error)

LoadConfigFromBytes loads a state machine configuration from YAML bytes.

func LoadConfigFromFS

func LoadConfigFromFS(fsys fs.FS, path string) (*Config, error)

LoadConfigFromFS loads a configuration from an embedded filesystem. This is a convenience function for loading from embed.FS.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid.

type ConfigLoader

type ConfigLoader interface {
	LoadByName(name string) ([]byte, error)
	ListAvailable() []string
}

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

func NewContext(sessionID, projectID string) *Context

NewContext creates a new state machine context.

func (*Context) AddTransition

func (c *Context) AddTransition(from, to string, data map[string]any)

AddTransition records a state transition in the history.

func (*Context) AppendToPath

func (c *Context) AppendToPath(state string)

AppendToPath adds the current state to the path history.

func (*Context) Clone

func (c *Context) Clone() *Context

Clone creates a deep copy of the context.

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

Get retrieves a value from the context data.

func (*Context) GetBool

func (c *Context) GetBool(key string) (bool, bool)

GetBool retrieves a boolean value from the context data.

func (*Context) GetInt

func (c *Context) GetInt(key string) (int, bool)

GetInt retrieves an integer value from the context data.

func (*Context) GetString

func (c *Context) GetString(key string) (string, bool)

GetString retrieves a string value from the context data.

func (*Context) Merge

func (c *Context) Merge(data map[string]any)

Merge merges a map of data into the context.

func (*Context) Set

func (c *Context) Set(key string, value any)

Set stores a value in the context data.

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 (l *DefaultLogger) ActionCompleted(ctx context.Context, action string, duration time.Duration, err error)

func (*DefaultLogger) ActionStarted

func (l *DefaultLogger) ActionStarted(ctx context.Context, action string)

func (*DefaultLogger) StateEntered

func (l *DefaultLogger) StateEntered(ctx context.Context, state string, data map[string]any)

func (*DefaultLogger) StateExited

func (l *DefaultLogger) StateExited(ctx context.Context, state string, duration time.Duration, err error)

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

func (e *Engine) Execute(ctx context.Context, smCtx *Context) (err error)

Execute runs the state machine to completion.

func (*Engine) RegisterState

func (e *Engine) RegisterState(state State)

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

func (e *Engine) SetActionTimeout(timeout time.Duration)

SetActionTimeout sets the maximum duration for action execution. A timeout of 0 means no timeout.

func (*Engine) SetCancellationEnabled

func (e *Engine) SetCancellationEnabled(enabled bool)

SetCancellationEnabled enables or disables context cancellation handling.

func (*Engine) SetLogger

func (e *Engine) SetLogger(logger Logger)

SetLogger sets the logger for state machine execution.

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

func (t *ExpressionTransition) Condition(ctx context.Context, smCtx *Context) (bool, error)

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.

func (*LoggingEngine) Execute

func (e *LoggingEngine) Execute(ctx context.Context, smCtx *Context) error

Execute runs the state machine with logging.

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.

func (*NoopAction) Execute

func (a *NoopAction) Execute(ctx context.Context, smCtx *Context) error

Execute does nothing and always succeeds.

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.

func (*ParallelAction) Execute

func (a *ParallelAction) Execute(ctx context.Context, smCtx *Context) error

type RetryAction

type RetryAction struct {
	BaseAction
	// contains filtered or unexported fields
}

RetryAction retries action on failure.

func NewRetryAction

func NewRetryAction(name string, action Action, maxRetries int, backoff time.Duration) *RetryAction

NewRetryAction creates a new retry action.

func (*RetryAction) Execute

func (a *RetryAction) Execute(ctx context.Context, smCtx *Context) error

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.

func (*SequenceAction) Execute

func (a *SequenceAction) Execute(ctx context.Context, smCtx *Context) error

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

func (t *SimpleTransition) Condition(ctx context.Context, smCtx *Context) (bool, error)

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

type StateError struct {
	State string
	Err   error
}

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

type StateTransition struct {
	From      string
	To        string
	Timestamp time.Time
	Data      map[string]any
}

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

type TransitionError struct {
	From string
	To   string
	Err  error
}

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

type TransitionResult struct {
	NextState string
	Data      map[string]any
	Complete  bool
}

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.

func (*ValidationAction) Execute

func (a *ValidationAction) Execute(ctx context.Context, smCtx *Context) error

type ValidatorFunc

type ValidatorFunc func(ctx context.Context, smCtx *Context) (bool, string, error)

ValidatorFunc is a function that validates context data.

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.

Jump to

Keyboard shortcuts

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