taskengine

package
v0.0.25 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2025 License: Apache-2.0 Imports: 20 Imported by: 9

Documentation

Overview

Package taskengine provides an engine for orchestrating chains of LLM-based tasks.

taskengine enables building AI workflows where tasks are linked in sequence, supporting conditional branching, numeric or scored evaluation, range resolution, and optional integration with external systems (hooks). Each task can invoke an LLM prompt or a custom hook function depending on its type.

Hooks are pluggable interfaces that allow tasks to perform side effects — calling APIs, saving data, or triggering custom business logic — outside of prompt-based processing.

Typical use cases:

  • Dynamic content generation (e.g. marketing copy, reports)
  • AI agent orchestration with branching logic
  • Decision trees based on LLM outputs
  • Automation pipelines involving prompts and external system calls

Index

Constants

View Source
const (
	StatusSuccess             = 1
	StatusUnknownHookProvider = 2
	StatusError               = 3
)
View Source
const (
	TermEnd = "end"
)

Variables

View Source
var ErrUnsupportedTaskType = errors.New("executor does not support the task type")

ErrUnsupportedTaskType indicates unrecognized task type

Functions

func ConvertToType added in v0.0.15

func ConvertToType(value interface{}, dataType DataType) (interface{}, error)

ConvertToType converts a value to the specified DataType

func SupportedOperators

func SupportedOperators() []string

Types

type Alert

type Alert struct {
	ID        string            `json:"id"`
	Message   string            `json:"message"`
	RequestID string            `json:"requestID"`
	Metadata  map[string]string `json:"metadata"`
	Timestamp time.Time         `json:"Timestamp"`
}

type AlertSink

type AlertSink interface {
	SendAlert(ctx context.Context, message string, kvPairMetadata ...string) error
	FetchAlerts(ctx context.Context, limit int) ([]*Alert, error)
}

func NewAlertSink

func NewAlertSink(kvManager libkv.KVManager) AlertSink

type CapturedStateUnit

type CapturedStateUnit struct {
	TaskID      string        `json:"taskID"`
	TaskHandler string        `json:"taskHandler"`
	InputType   DataType      `json:"inputType"`
	OutputType  DataType      `json:"outputType"`
	Transition  string        `json:"transition"`
	Duration    time.Duration `json:"duration"`
	Error       ErrorResponse `json:"error"`
	Input       string        `json:"input"`
	Output      string        `json:"output"`
}

func (*CapturedStateUnit) MarshalJSON

func (c *CapturedStateUnit) MarshalJSON() ([]byte, error)

func (*CapturedStateUnit) UnmarshalJSON added in v0.0.9

func (c *CapturedStateUnit) UnmarshalJSON(data []byte) error

type ChainDefinition

type ChainDefinition struct {
	// ID uniquely identifies the chain.
	ID string `yaml:"id" json:"id"`

	// Enables capturing user input and output.
	Debug bool `yaml:"debug" json:"debug"`

	// Description provides a human-readable summary of the chain's purpose.
	Description string `yaml:"description" json:"description"`

	// Tasks is the list of tasks to execute in sequence.
	Tasks []ChainTask `yaml:"tasks" json:"tasks"`

	// TokenLimit is the token limit for the context window (used during execution).
	TokenLimit int64 `yaml:"token_limit" json:"token_limit"`

	// RoutingStrategy defines how transitions should be evaluated (optional).
	RoutingStrategy string `yaml:"routing_strategy" json:"routing_strategy"`
}

ChainDefinition describes a sequence of tasks to execute in order, along with branching logic, retry policies, and model preferences.

ChainDefinition support dynamic routing based on LLM outputs or conditions, and can include hooks to perform external actions (e.g., sending emails).

type ChainTask

type ChainTask struct {
	// ID uniquely identifies the task within the chain.
	ID string `yaml:"id" json:"id"`

	// Description is a human-readable summary of what the task does.
	Description string `yaml:"description" json:"description"`

	// Handler determines how the LLM output (or hook) will be interpreted.
	Handler TaskHandler `yaml:"handler" json:"handler"`

	// SystemInstruction provides additional instructions to the LLM, if applicable system level will be used.
	SystemInstruction string `yaml:"system_instruction,omitempty" json:"system_instruction,omitempty"`

	// ValidConditions defines allowed values for ConditionKey tasks.
	// Required for ConditionKey tasks, ignored for all other types.
	// Example: {"yes": true, "no": true} for a yes/no condition.
	ValidConditions map[string]bool `yaml:"valid_conditions,omitempty" json:"valid_conditions,omitempty"`

	// ExecuteConfig defines the configuration for executing prompt or chat model tasks.
	ExecuteConfig *LLMExecutionConfig `yaml:"execute_config,omitempty" json:"execute_config,omitempty"`

	// Hook defines an external action to run.
	// Required for Hook tasks, must be nil/omitted for all other types.
	// Example: {type: "send_email", args: {"to": "user@example.com"}}
	Hook *HookCall `yaml:"hook,omitempty" json:"hook,omitempty"`

	// Print optionally formats the output for display/logging.
	// Supports template variables from previous task outputs.
	// Optional for all task types except Hook where it's rarely used.
	// Example: "The score is: {{.previous_output}}"
	Print string `yaml:"print,omitempty" json:"print,omitempty"`

	// PromptTemplate is the text prompt sent to the LLM.
	// It's Required and only applicable for the raw_string type.
	// Supports template variables from previous task outputs.
	// Example: "Rate the quality from 1-10: {{.input}}"
	PromptTemplate string `yaml:"prompt_template" json:"prompt_template"`

	// InputVar is the name of the variable to use as input for the task.
	// Example: "input" for the original input.
	// Each task stores its output in a variable named with it's task id.
	InputVar string `yaml:"input_var,omitempty" json:"input_var,omitempty"`

	// Compose merges the specified the output with the withVar side.
	// Optional. compose is applied before the input reaches the task execution,
	Compose *ComposeTask `yaml:"compose,omitempty" json:"compose,omitempty"`

	// Transition defines what to do after this task completes.
	Transition TaskTransition `yaml:"transition" json:"transition"`

	// Timeout optionally sets a timeout for task execution.
	// Format: "10s", "2m", "1h" etc.
	// Optional for all task types.
	Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"`

	// RetryOnFailure sets how many times to retry this task on failure.
	// Applies to all task types including Hooks.
	// Default: 0 (no retries)
	RetryOnFailure int `yaml:"retry_on_failure,omitempty" json:"retry_on_failure,omitempty"`
}

ChainTask represents a single step in a workflow. Each task has a handler that dictates how its prompt will be processed.

Field validity by task type: | Field | ConditionKey | ParseNumber | ParseScore | ParseRange | RawString | Hook | Noop | |---------------------|--------------|-------------|------------|------------|-----------|-------|-------| | ValidConditions | Required | - | - | - | - | - | - | | Hook | - | - | - | - | - | Req | - | | PromptTemplate | Required | Required | Required | Required | Required | - | Opt | | Print | Optional | Optional | Optional | Optional | Optional | Opt | Opt | | ExecuteConfig | Optional | Optional | Optional | Optional | Optional | - | - | | InputVar | Optional | Optional | Optional | Optional | Optional | Opt | Opt | | SystemInstruction | Optional | Optional | Optional | Optional | Optional | Opt | Opt | | Compose | Optional | Optional | Optional | Optional | Optional | Opt | Opt | | Transition | Required | Required | Required | Required | Required | Req | Req |

type ChainTerms

type ChainTerms string

type ChatHistory

type ChatHistory struct {
	Messages     []Message `json:"messages"`
	Model        string    `json:"model"`
	InputTokens  int       `json:"inputTokens"`
	OutputTokens int       `json:"outputTokens"`
}

type ComposeTask

type ComposeTask struct {
	WithVar string `yaml:"with_var,omitempty" json:"with_var,omitempty"`
	// Strategy defines how values should be merged ("override", "merge_chat_histories", "append_string_to_chat_history").
	// Optional; defaults to "override" or "merge_chat_histories" if both output and WithVar values are ChatHistory.
	// "merge_chat_histories": If both output and WithVar values are ChatHistory,
	// appends the WithVar's Messages to the output's Messages.
	Strategy string `yaml:"strategy,omitempty" json:"strategy,omitempty"`
}

ComposeTask is a task that composes multiple variables into a single output. the composed output is stored in a variable named after the task ID with "_composed" suffix. and is also directly mutating the task's output. example:

compose:

with_var: "chat2"
strategy: "override"

type DataType

type DataType int

DataType represents the type of data that can be passed between tasks

const (
	DataTypeAny DataType = iota
	DataTypeString
	DataTypeBool
	DataTypeInt
	DataTypeFloat
	DataTypeVector
	DataTypeSearchResults
	DataTypeJSON
	DataTypeChatHistory
	DataTypeOpenAIChat
	DataTypeOpenAIChatResponse
)

Constants representing hook execution status

func DataTypeFromString

func DataTypeFromString(s string) (DataType, error)

func (DataType) MarshalJSON

func (d DataType) MarshalJSON() ([]byte, error)

func (DataType) MarshalYAML

func (d DataType) MarshalYAML() ([]byte, error)

func (*DataType) String

func (d *DataType) String() string

func (*DataType) UnmarshalJSON added in v0.0.10

func (dt *DataType) UnmarshalJSON(data []byte) error

func (*DataType) UnmarshalYAML added in v0.0.10

func (dt *DataType) UnmarshalYAML(data []byte) error

type EnvExecutor

type EnvExecutor interface {
	// ExecEnv executes a chain with input and returns final output
	ExecEnv(ctx context.Context, chain *ChainDefinition, input any, dataType DataType) (any, DataType, []CapturedStateUnit, error)
}

EnvExecutor defines an environment for executing ChainDefinitions

func NewEnv

func NewEnv(
	_ context.Context,
	tracker activitytracker.ActivityTracker,
	alertCollector AlertSink,
	exec TaskExecutor,
	inspector Inspector,
) (EnvExecutor, error)

NewEnv creates a new SimpleEnv with the given tracker and task executor.

type ErrorResponse

type ErrorResponse struct {
	ErrorInternal error  `json:"-"`
	Error         string `json:"error"`
}

type ExecutionState

type ExecutionState struct {
	Variables   map[string]any
	DataTypes   map[string]DataType
	CurrentTask *ChainTask
}

type HookCall

type HookCall struct {
	// Name is the registered hook name to invoke (e.g., "send_email").
	Name string `yaml:"name" json:"name"`

	// Args are key-value pairs to parameterize the hook call.
	// Example: {"to": "user@example.com", "subject": "Notification"}
	Args map[string]string `yaml:"args" json:"args"`
}

HookCall represents an external integration or side-effect triggered during a task. Hooks allow tasks to interact with external systems (e.g., "send_email", "update_db").

type HookRegistry

type HookRegistry interface {
	Supports(ctx context.Context) ([]string, error)
}

type HookRepo

type HookRepo interface {
	// Exec runs a hook with input and returns results
	Exec(ctx context.Context, startingTime time.Time, input any, dataType DataType, transition string, args *HookCall) (any, DataType, string, error)
	HookRegistry
}

HookRepo defines an interface for external system integrations and to conduct side effects on internal state.

type Inspector

type Inspector interface {
	Start(ctx context.Context) StackTrace
}

type KVActivitySink

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

func NewKVActivityTracker

func NewKVActivityTracker(kvManager libkv.KVManager) *KVActivitySink

func (*KVActivitySink) GetActivityLogs

func (t *KVActivitySink) GetActivityLogs(ctx context.Context, limit int) ([]TrackedEvent, error)

func (*KVActivitySink) GetActivityLogsByRequestID

func (t *KVActivitySink) GetActivityLogsByRequestID(ctx context.Context, requestID string) ([]TrackedEvent, error)

func (*KVActivitySink) GetExecutionStateByRequestID

func (t *KVActivitySink) GetExecutionStateByRequestID(ctx context.Context, requestID string) ([]CapturedStateUnit, error)

func (*KVActivitySink) GetKnownOperations

func (t *KVActivitySink) GetKnownOperations(ctx context.Context) ([]Operation, error)

func (*KVActivitySink) GetRecentRequestIDs

func (t *KVActivitySink) GetRecentRequestIDs(ctx context.Context, limit int) ([]TrackedRequest, error)

func (*KVActivitySink) GetRequestIDByOperation

func (t *KVActivitySink) GetRequestIDByOperation(ctx context.Context, operation Operation) ([]TrackedRequest, error)

func (*KVActivitySink) GetStatefulRequests

func (t *KVActivitySink) GetStatefulRequests(ctx context.Context) ([]string, error)

func (*KVActivitySink) Start

func (t *KVActivitySink) Start(
	ctx context.Context,
	operation string,
	subject string,
	kvArgs ...any,
) (func(error), func(string, any), func())

type LLMExecutionConfig

type LLMExecutionConfig struct {
	Model       string   `yaml:"model" json:"model"`
	Models      []string `yaml:"models,omitempty" json:"models,omitempty"`
	Provider    string   `yaml:"provider,omitempty" json:"provider,omitempty"`
	Providers   []string `yaml:"providers,omitempty" json:"providers,omitempty"`
	Temperature float32  `yaml:"temperature,omitempty" json:"temperature,omitempty"`
}

type Message

type Message struct {
	ID        string    `json:"id"`
	Role      string    `json:"role"`
	Content   string    `json:"content"`
	Timestamp time.Time `json:"timestamp"`
}

type MessageConfig

type MessageConfig struct {
	Role    string `yaml:"role" json:"role"` // user/system/assistant
	Content string `yaml:"content,omitempty" json:"content,omitempty"`
}

type MockTaskExecutor

type MockTaskExecutor struct {
	// Single value responses
	MockOutput      any
	MockRawResponse string
	MockError       error

	// Sequence responses
	MockOutputSequence      []any
	MockRawResponseSequence []string
	ErrorSequence           []error

	// Tracking
	CalledWithTask   *ChainTask
	CalledWithInput  any
	CalledWithPrompt string
	// contains filtered or unexported fields
}

MockTaskExecutor is a mock implementation of taskengine.TaskExecutor.

func (*MockTaskExecutor) CallCount

func (m *MockTaskExecutor) CallCount() int

CallCount returns how many times TaskExec was called

func (*MockTaskExecutor) Reset

func (m *MockTaskExecutor) Reset()

Reset clears all mock state between tests

func (*MockTaskExecutor) TaskExec

func (m *MockTaskExecutor) TaskExec(ctx context.Context, startingTime time.Time, resolver llmresolver.Policy, tokenLimit int, currentTask *ChainTask, input any, dataType DataType) (any, DataType, string, error)

TaskExec is the mock implementation of the TaskExec method.

type NoopAlertSink

type NoopAlertSink struct{}

func (*NoopAlertSink) FetchAlerts

func (s *NoopAlertSink) FetchAlerts(ctx context.Context, limit int) ([]*Alert, error)

func (*NoopAlertSink) SendAlert

func (a *NoopAlertSink) SendAlert(ctx context.Context, msg string, kvs ...string) error

type NoopExecutionStack

type NoopExecutionStack struct{}

func (*NoopExecutionStack) ClearBreakpoints

func (s *NoopExecutionStack) ClearBreakpoints()

ClearBreakpoints implements StackTrace.

func (*NoopExecutionStack) GetCurrentState

func (s *NoopExecutionStack) GetCurrentState() ExecutionState

GetCurrentState implements StackTrace.

func (*NoopExecutionStack) GetExecutionHistory

func (s *NoopExecutionStack) GetExecutionHistory() []CapturedStateUnit

func (*NoopExecutionStack) HasBreakpoint

func (s *NoopExecutionStack) HasBreakpoint(taskID string) bool

func (*NoopExecutionStack) RecordStep

func (s *NoopExecutionStack) RecordStep(step CapturedStateUnit)

func (*NoopExecutionStack) SetBreakpoint

func (s *NoopExecutionStack) SetBreakpoint(taskID string)

SetBreakpoint implements StackTrace.

type NoopInspector

type NoopInspector struct{}

func (*NoopInspector) Start

func (i *NoopInspector) Start(ctx context.Context) StackTrace

type OpenAIChatRequest

type OpenAIChatRequest struct {
	Model            string                     `json:"model"`
	Messages         []OpenAIChatRequestMessage `json:"messages"`
	MaxTokens        int                        `json:"max_tokens,omitempty"`
	Temperature      float64                    `json:"temperature,omitempty"`
	TopP             float64                    `json:"top_p,omitempty"`
	Stop             []string                   `json:"stop,omitempty"`
	N                int                        `json:"n,omitempty"`
	Stream           bool                       `json:"stream,omitempty"`
	PresencePenalty  float64                    `json:"presence_penalty,omitempty"`
	FrequencyPenalty float64                    `json:"frequency_penalty,omitempty"`
	User             string                     `json:"user,omitempty"`
}

type OpenAIChatRequestMessage

type OpenAIChatRequestMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type OpenAIChatResponse

type OpenAIChatResponse struct {
	ID                string                     `json:"id"`
	Object            string                     `json:"object"`
	Created           int64                      `json:"created"`
	Model             string                     `json:"model"`
	Choices           []OpenAIChatResponseChoice `json:"choices"`
	Usage             OpenAITokenUsage           `json:"usage"`
	SystemFingerprint string                     `json:"system_fingerprint,omitempty"`
}

type OpenAIChatResponseChoice

type OpenAIChatResponseChoice struct {
	Index        int                      `json:"index"`
	Message      OpenAIChatRequestMessage `json:"message"`
	FinishReason string                   `json:"finish_reason"`
}

type OpenAITokenUsage

type OpenAITokenUsage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

type Operation

type Operation struct {
	Operation string `json:"operation"`
	Subject   string `json:"subject"`
}

type OperatorTerm

type OperatorTerm string

OperatorTerm represents logical operators used for task transition evaluation

const (
	OpEquals      OperatorTerm = "equals"
	OpContains    OperatorTerm = "contains"
	OpStartsWith  OperatorTerm = "starts_with"
	OpEndsWith    OperatorTerm = "ends_with"
	OpGreaterThan OperatorTerm = ">"
	OpGt          OperatorTerm = "gt"
	OpLessThan    OperatorTerm = "<"
	OpLt          OperatorTerm = "lt"
	OpInRange     OperatorTerm = "in_range"
	OpDefault     OperatorTerm = "default"
)

func ToOperatorTerm

func ToOperatorTerm(s string) (OperatorTerm, error)

func (OperatorTerm) String

func (t OperatorTerm) String() string

type SearchResult

type SearchResult struct {
	ID           string  `json:"id"`
	ResourceType string  `json:"type"`
	Distance     float32 `json:"distance"`
}

type SimpleAlertSink

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

func (*SimpleAlertSink) FetchAlerts

func (as *SimpleAlertSink) FetchAlerts(ctx context.Context, limit int) ([]*Alert, error)

func (*SimpleAlertSink) SendAlert

func (as *SimpleAlertSink) SendAlert(ctx context.Context, message string, kvPairMetadata ...string) error

type SimpleEnv

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

SimpleEnv is the default implementation of EnvExecutor. this is the default EnvExecutor implementation It executes tasks in order, using retry and timeout policies, and tracks execution progress using an ActivityTracker.

func (SimpleEnv) ExecEnv

func (exe SimpleEnv) ExecEnv(ctx context.Context, chain *ChainDefinition, input any, dataType DataType) (any, DataType, []CapturedStateUnit, error)

ExecEnv executes the given chain with the provided input.

It manages the full lifecycle of task execution: rendering prompts, calling the TaskExecutor, handling timeouts, retries, transitions, and collecting final output.

type SimpleExec

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

SimpleExec is a basic implementation of TaskExecutor. It supports prompt-to-string, number, score, range, boolean condition evaluation, and delegation to registered hooks.

func (*SimpleExec) Embed

func (exe *SimpleExec) Embed(ctx context.Context, resolver llmresolver.Policy, llmCall LLMExecutionConfig, prompt string) ([]float64, error)

Prompt resolves a model client using the resolver policy and sends the prompt to be executed. Returns the trimmed response string or an error.

func (*SimpleExec) Prompt

func (exe *SimpleExec) Prompt(ctx context.Context, resolver llmresolver.Policy, systemInstruction string, llmCall LLMExecutionConfig, prompt string) (string, error)

Prompt resolves a model client using the resolver policy and sends the prompt to be executed. Returns the trimmed response string or an error.

func (*SimpleExec) TaskExec

func (exe *SimpleExec) TaskExec(taskCtx context.Context, startingTime time.Time, resolver llmresolver.Policy, ctxLength int, currentTask *ChainTask, input any, dataType DataType) (any, DataType, string, error)

TaskExec dispatches task execution based on the task type.

type SimpleInspector

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

func NewSimpleInspector

func NewSimpleInspector(kvManager libkv.KVManager) *SimpleInspector

func (SimpleInspector) Start

type SimpleStackTrace

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

func (*SimpleStackTrace) ClearBreakpoints

func (s *SimpleStackTrace) ClearBreakpoints()

func (*SimpleStackTrace) GetCurrentState

func (s *SimpleStackTrace) GetCurrentState() ExecutionState

func (*SimpleStackTrace) GetExecutionHistory

func (s *SimpleStackTrace) GetExecutionHistory() []CapturedStateUnit

func (*SimpleStackTrace) HasBreakpoint

func (s *SimpleStackTrace) HasBreakpoint(taskID string) bool

func (*SimpleStackTrace) RecordStep

func (s *SimpleStackTrace) RecordStep(step CapturedStateUnit)

func (*SimpleStackTrace) SetBreakpoint

func (s *SimpleStackTrace) SetBreakpoint(taskID string)

type StackTrace

type StackTrace interface {
	// Observation
	RecordStep(step CapturedStateUnit)
	GetExecutionHistory() []CapturedStateUnit

	// // Control
	SetBreakpoint(taskID string)
	ClearBreakpoints()

	HasBreakpoint(taskID string) bool

	// Debugging
	GetCurrentState() ExecutionState
}

type TaskExecutor

type TaskExecutor interface {
	// TaskExec runs a single task and returns output
	// It consumes a prompt and resolver policy, and returns structured output
	// TODO: THIS IS NOT TRUE: alongside the raw LLM response.
	TaskExec(ctx context.Context, startingTime time.Time, resolver llmresolver.Policy, ctxLength int, currentTask *ChainTask, input any, dataType DataType) (any, DataType, string, error)
}

TaskExecutor defines the interface for executing a individual tasks.

func NewExec

func NewExec(
	_ context.Context,
	repo llmrepo.ModelRepo,
	embedRepo llmrepo.ModelRepo,
	hookProvider HookRepo,
	tracker activitytracker.ActivityTracker,
) (TaskExecutor, error)

NewExec creates a new SimpleExec instance

type TaskHandler

type TaskHandler string

TaskHandler defines the expected output format of a task. It determines how the LLM's response will be interpreted.

const (
	// HandleConditionKey interprets the response as a condition key,
	// used to determine which transition to follow.
	HandleConditionKey TaskHandler = "condition_key"

	// HandleParseNumber expects a numeric response and parses it into an integer.
	HandleParseNumber TaskHandler = "parse_number"

	// HandleParseScore expects a floating-point score (e.g., quality rating).
	HandleParseScore TaskHandler = "parse_score"

	// HandleParseRange expects a numeric range like "5-7", or defaults to N-N for single numbers.
	HandleParseRange TaskHandler = "parse_range"

	// HandleRawString returns the raw string result from the LLM.
	HandleRawString TaskHandler = "raw_string"

	HandleEmbedding TaskHandler = "embedding"

	// HandleRaiseError raises an error with the provided message.
	HandleRaiseError TaskHandler = "raise_error"

	// HandleModelExecution will execute the system default or specified model on a chathistory.
	HandleModelExecution TaskHandler = "model_execution"

	// HandleParseTransition will attempt to parse a transition command from the input and strip the transition prefix if it exists.
	HandleParseTransition TaskHandler = "parse_transition"

	HandleNoop TaskHandler = "noop"

	// HandleHook indicates this task should execute an external action rather than calling the LLM.
	HandleHook TaskHandler = "hook"
)

func (TaskHandler) String

func (t TaskHandler) String() string

type TaskTransition

type TaskTransition struct {
	// OnFailure is the task ID to jump to in case of failure.
	OnFailure string `yaml:"on_failure" json:"on_failure"`

	// OnFailureAlert specifies the alert message to send if the task fails.
	OnFailureAlert string `yaml:"on_failure_alert" json:"on_failure_alert"`

	// Branches defines conditional branches for successful task completion.
	Branches []TransitionBranch `yaml:"branches" json:"branches"`
}

TaskTransition defines what happens after a task completes, including which task to go to next and how to handle errors.

type TrackedEvent

type TrackedEvent struct {
	ID         string            `json:"id"`
	Operation  string            `json:"operation"`
	Subject    string            `json:"subject"`
	Start      time.Time         `json:"start"`
	End        *time.Time        `json:"end,omitempty"`
	Error      *string           `json:"error,omitempty"`
	EntityID   *string           `json:"entityID,omitempty"`
	EntityData any               `json:"entityData,omitempty"`
	Duration   float64           `json:"duration"` // Duration in milliseconds
	Metadata   map[string]string `json:"metadata,omitempty"`
	RequestID  string            `json:"requestID,omitempty"`
}

type TrackedRequest

type TrackedRequest struct {
	ID string `json:"id"`
}

type TransitionBranch

type TransitionBranch struct {
	// Operator defines how to compare the task's output to When.
	Operator OperatorTerm `yaml:"operator,omitempty" json:"operator,omitempty"`

	// When specifies the condition that must be met to follow this branch.
	// Format depends on the task type:
	// - For condition_key: exact string match
	// - For parse_number: numeric comparison (using Operator)
	When string `yaml:"when" json:"when"`

	// Goto specifies the target task ID if this branch is taken.
	// Leave empty or use taskengine.TermEnd to end the chain.
	Goto string `yaml:"goto" json:"goto"`

	// AlertOnMatch specifies the alert message to send if this branch is taken.
	AlertOnMatch string `yaml:"alert_on_match" json:"alert_on_match"`
}

TransitionBranch defines a single possible path in the workflow, selected when the task's output matches the specified condition.

Jump to

Keyboard shortcuts

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