types

package
v0.92.1 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2026 License: GPL-3.0 Imports: 15 Imported by: 0

Documentation

Overview

Package types provides core type definitions, interfaces, and value objects.

Index

Constants

View Source
const (
	// Assistant is the role of an assistant, means the message is returned by ChatModel.
	Assistant string = "assistant"
	// User is the role of a user, means the message is a user message.
	User string = "user"
	// System is the role of a system, means the message is a system message.
	System string = "system"
	// Tool is the role of a tool, means the message is a tool call output.
	Tool string = "tool"
)
View Source
const (
	MessageSendEvent  = "message:send"
	InstructPushEvent = "instruct:push"
	BotRunEvent       = "bot:event"
	ModuleRunEvent    = BotRunEvent
)
View Source
const (
	ExampleBotEventID         = "example"
	TaskCreateBotEventID      = "creteTask"
	BookmarkArchiveBotEventID = "archiveBookmark"
	BookmarkCreateBotEventID  = "createBookmark"
	ArchiveBoxAddBotEventID   = "archiveBoxAdd"
)
View Source
const (
	EventBookmarkCreated  = "bookmark.created"
	EventBookmarkUpdated  = "bookmark.updated"
	EventBookmarkArchived = "bookmark.archived"
	EventBookmarkDeleted  = "bookmark.deleted"

	EventArchiveItemCreated = "archive.item.created"

	EventReaderEntryNew   = "reader.entry.new"
	EventReaderEntrySaved = "reader.entry.saved"

	EventReaderEntryStarred = "reader.entry.starred"
	EventReaderEntryRead    = "reader.entry.read"

	EventKanbanTaskCreated   = "kanban.task.created"
	EventKanbanTaskUpdated   = "kanban.task.updated"
	EventKanbanTaskCompleted = "kanban.task.completed"
	EventKanbanTaskOpened    = "kanban.task.opened"
	EventKanbanTaskMoved     = "kanban.task.moved"

	EventInfraHostDown = "infra.host.down"
	EventInfraHostUp   = "infra.host.up"

	EventForgeIssueOpened   = "forge.issue.opened"
	EventForgeIssueClosed   = "forge.issue.closed"
	EventForgeIssueReopened = "forge.issue.reopened"
	EventForgeIssueEdited   = "forge.issue.edited"
	EventForgePush          = "forge.push"
)
View Source
const (
	MountTypeVolume string = "volume"
	MountTypeBind   string = "bind"
	MountTypeTmpfs  string = "tmpfs"
)
View Source
const (
	BackoffFixed       = "fixed"
	BackoffLinear      = "linear"
	BackoffExponential = "exponential"
)

Backoff constants for RetryConfig.Backoff.

View Source
const ApiVersion = 1

Variables

View Source
var (
	ErrInvalidArgument = errors.New("invalid argument")
	ErrUnauthorized    = errors.New("unauthorized")
	ErrForbidden       = errors.New("forbidden")
	ErrNotFound        = errors.New("not found")
	ErrAlreadyExists   = errors.New("already exists")
	ErrConflict        = errors.New("conflict")
	ErrRateLimited     = errors.New("rate limited")
	ErrUnavailable     = errors.New("unavailable")
	ErrTimeout         = errors.New("timeout")
	ErrNotImplemented  = errors.New("not implemented")
	ErrProvider        = errors.New("provider error")
	ErrInternal        = errors.New("internal error")
)
View Source
var EventFilterCache = NewFilterCache()

EventFilterCache is the global filter cache for event sources and types. Initialized by the web module on startup, updated by the store on event write.

Functions

func AppUrl

func AppUrl() string

func Errorf added in v0.92.0

func Errorf(kind error, format string, args ...any) error

Errorf creates a standard Flowbot error with a formatted message.

func Id

func Id() string

func TypeOf

func TypeOf(payload MsgPayload) string

func WrapError added in v0.92.0

func WrapError(kind error, message string, cause error) error

WrapError wraps a lower-level cause with a standard Flowbot error kind.

Types

type Action

type Action string
const (
	PullAction    Action = "pull"
	AckAction     Action = "ack"
	OnlineAction  Action = "online"
	OfflineAction Action = "offline"
	MessageAction Action = "message"
)

type AgentData

type AgentData struct {
	Action  Action `json:"action" validate:"required,oneof=pull ack online offline message"`
	Version int    `json:"version" validate:"gte=0"`
	Content KV     `json:"content"`
}

type BotEvent added in v0.23.1

type BotEvent struct {
	EventName string
	Uid       string
	Topic     string
	Param     KV
}

type ChartMsg

type ChartMsg struct {
	Title    string    `json:"title"`
	SubTitle string    `json:"sub_title"`
	XAxis    []string  `json:"x_axis"`
	Series   []float64 `json:"series"`
}

func (ChartMsg) Convert

func (t ChartMsg) Convert() any

type Context

type Context struct {

	// TraceCtx carries the OpenTelemetry trace context for span propagation.
	// Set via SetTraceContext before calling SetTimeout to inherit the trace parent.
	TraceCtx context.Context

	// Message ID denormalized
	Id string
	// chat platform
	Platform string
	// channel or group
	Topic string
	// Sender's UserId as string.
	AsUser Uid

	// form Rule id
	FormRuleId string
	// form id
	FormId string

	// workflow rule id
	WorkflowRuleId string

	// event rule id
	EventRuleId string

	// HTTP method
	Method string
	// HTTP headers
	Headers map[string][]string
	// contains filtered or unexported fields
}

func (*Context) Cancel

func (c *Context) Cancel() context.CancelFunc

func (*Context) Context

func (c *Context) Context() context.Context

Context returns the underlying context.Context.

Priority: c.ctx (set by SetTimeout or SetContext) > c.TraceCtx > context.Background(). This ensures that trace context from HTTP requests is not silently dropped when SetTimeout has not been called.

func (*Context) SetContext added in v0.92.0

func (c *Context) SetContext(ctx context.Context)

SetContext stores ctx as both the internal context and the trace context. Use this when you have a traced context (e.g., from an HTTP request or event message) but do not yet need a deadline.

func (*Context) SetTimeout

func (c *Context) SetTimeout(timeout time.Duration)

func (*Context) SetTraceContext added in v0.92.0

func (c *Context) SetTraceContext(traceCtx context.Context)

SetTraceContext stores traceCtx in the TraceCtx field without modifying the internal context. Call this before SetTimeout to ensure the timeout context inherits the trace parent.

type DataEvent added in v0.92.0

type DataEvent struct {
	EventID        string    `json:"event_id"`
	EventType      string    `json:"event_type"`
	Source         string    `json:"source"`
	Capability     string    `json:"capability"`
	Operation      string    `json:"operation"`
	Backend        string    `json:"backend"`
	App            string    `json:"app"`
	EntityID       string    `json:"entity_id"`
	CreatedAt      time.Time `json:"created_at"`
	IdempotencyKey string    `json:"idempotency_key"`
	UID            string    `json:"uid"`
	Topic          string    `json:"topic"`
	Data           KV        `json:"data"`
	Tags           KV        `json:"tags,omitempty"`
}

DataEvent is the durable business event contract emitted by ability write operations.

type DataFilter

type DataFilter struct {
	Prefix       *string
	CreatedStart *time.Time
	CreatedEnd   *time.Time
}

type DurationDistribution added in v0.92.0

type DurationDistribution struct {
	Pipeline []DurationEntry `json:"pipeline"`
	Step     []DurationEntry `json:"step"`
}

DurationDistribution holds pipeline and step duration bucket counts.

type DurationEntry added in v0.92.0

type DurationEntry struct {
	Bucket string `json:"bucket"`
	Count  int64  `json:"count"`
}

DurationEntry counts runs that fell into a named duration bucket.

type EmptyMsg added in v0.23.1

type EmptyMsg struct{}

func (EmptyMsg) Convert added in v0.23.1

func (t EmptyMsg) Convert() any

type Error added in v0.92.0

type Error struct {
	Kind       error
	Code       string
	Message    string
	Capability string
	Operation  string
	Provider   string
	Retryable  bool
	Cause      error
}

Error carries machine-readable domain error metadata across ability, hub, pipeline, workflow, and HTTP boundaries.

func (*Error) Error added in v0.92.0

func (e *Error) Error() string

func (*Error) Is added in v0.92.0

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

func (*Error) IsRetryableError added in v0.92.0

func (e *Error) IsRetryableError() bool

IsRetryableError returns true if the error is marked as retryable.

func (*Error) RetryableCode added in v0.92.0

func (e *Error) RetryableCode() string

RetryableCode returns the error code for retry filtering.

func (*Error) Unwrap added in v0.92.0

func (e *Error) Unwrap() error

type EventPayload

type EventPayload struct {
	Typ string
	Src []byte
}

type Executor added in v0.32.1

type Executor struct {
	Flag string
	Run  func(data KV) error
}

type FileDef

type FileDef struct {
	ObjHeader `bson:",inline"`
	// Name of the file
	Name string
	// Status of upload
	Status int
	// User who created the file
	User string
	// Type of the file.
	MimeType string
	// Size of the file in bytes.
	Size int64
	// Internal file location, i.e. path on disk or an S3 blob address.
	Location string
}

FileDef is a stored record of a file upload

func (*FileDef) Uid

func (i *FileDef) Uid() Uid

type FilterCache added in v0.92.0

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

FilterCache holds in-memory unique sets of sources and event types used to populate filter dropdowns without querying the database.

func NewFilterCache added in v0.92.0

func NewFilterCache() *FilterCache

NewFilterCache creates an empty FilterCache.

func (*FilterCache) EventTypes added in v0.92.0

func (fc *FilterCache) EventTypes() []string

EventTypes returns a copy of all cached event types.

func (*FilterCache) Hydrate added in v0.92.0

func (fc *FilterCache) Hydrate(sources, eventTypes []string)

Hydrate populates the cache from database lists (deduplicates with existing).

func (*FilterCache) SetEventType added in v0.92.0

func (fc *FilterCache) SetEventType(eventType string)

SetEventType adds an event type to the cache if not already present.

func (*FilterCache) SetSource added in v0.92.0

func (fc *FilterCache) SetSource(source string)

SetSource adds a source to the cache if not already present.

func (*FilterCache) Sources added in v0.92.0

func (fc *FilterCache) Sources() []string

Sources returns a copy of all cached sources.

type FormField

type FormField struct {
	Type        FormFieldType      `json:"type"`
	Key         string             `json:"key"`
	Value       any                `json:"value"`
	ValueType   FormFieldValueType `json:"value_type"`
	Label       string             `json:"label"`
	Placeholder string             `json:"placeholder"`
	Option      []string           `json:"option"`
	Rule        string             `json:"rule"`
}

type FormFieldType

type FormFieldType string
const (
	FormFieldText     FormFieldType = "text"
	FormFieldPassword FormFieldType = "password"
	FormFieldNumber   FormFieldType = "number"
	FormFieldColor    FormFieldType = "color"
	FormFieldFile     FormFieldType = "file"
	FormFieldMonth    FormFieldType = "month"
	FormFieldDate     FormFieldType = "date"
	FormFieldTime     FormFieldType = "time"
	FormFieldEmail    FormFieldType = "email"
	FormFieldUrl      FormFieldType = "url"
	FormFieldRadio    FormFieldType = "radio"
	FormFieldCheckbox FormFieldType = "checkbox"
	FormFieldRange    FormFieldType = "range"
	FormFieldSelect   FormFieldType = "select"
	FormFieldTextarea FormFieldType = "textarea"
	FormFieldHidden   FormFieldType = "hidden"
)

type FormFieldValueType

type FormFieldValueType string
const (
	FormFieldValueString       FormFieldValueType = "string"
	FormFieldValueBool         FormFieldValueType = "bool"
	FormFieldValueInt64        FormFieldValueType = "int64"
	FormFieldValueFloat64      FormFieldValueType = "float64"
	FormFieldValueStringSlice  FormFieldValueType = "string_slice"
	FormFieldValueInt64Slice   FormFieldValueType = "int64_slice"
	FormFieldValueFloat64Slice FormFieldValueType = "float64_slice"
)

type FormMsg

type FormMsg struct {
	ID    string      `json:"id"`
	Title string      `json:"title"`
	Field []FormField `json:"field"`
}

func (FormMsg) Convert

func (a FormMsg) Convert() any

type HtmlMsg

type HtmlMsg struct {
	Raw string
}

func (HtmlMsg) Convert

func (m HtmlMsg) Convert() any

type InfoMsg

type InfoMsg struct {
	Title string `json:"title"`
	Model any    `json:"model,omitempty"`
}

func (InfoMsg) Convert

func (i InfoMsg) Convert() any

type InstructMsg

type InstructMsg struct {
	No       string
	Object   schema.InstructObject
	Bot      string
	Flag     string
	Content  KV
	Priority schema.InstructPriority
	State    schema.InstructState
	ExpireAt time.Time
}

func (InstructMsg) Convert

func (t InstructMsg) Convert() any

type JobFilter

type JobFilter struct {
	EndedAt time.Time
}

type KV

type KV map[string]any

func (*KV) Any

func (j *KV) Any(key string) (any, bool)

func (*KV) Float64

func (j *KV) Float64(key string) (float64, bool)

func (*KV) Float64Value

func (j *KV) Float64Value() (float64, bool)

func (*KV) Int64

func (j *KV) Int64(key string) (int64, bool)

func (*KV) Int64Value

func (j *KV) Int64Value() (int64, bool)

func (*KV) List

func (j *KV) List(key string) ([]any, bool)

func (*KV) Map

func (j *KV) Map(key string) (map[string]any, bool)

func (*KV) Merge

func (j *KV) Merge(kvs ...KV) KV

func (*KV) Scan

func (j *KV) Scan(value any) error

func (*KV) String

func (j *KV) String(key string) (string, bool)

func (*KV) StringValue

func (j *KV) StringValue() (string, bool)

func (*KV) Uint64

func (j *KV) Uint64(key string) (uint64, bool)

func (*KV) Uint64Value

func (j *KV) Uint64Value() (uint64, bool)

func (*KV) Value

func (j *KV) Value() (driver.Value, error)

type KVMsg

type KVMsg map[string]any

func (KVMsg) Convert

func (t KVMsg) Convert() any

type LinkMsg

type LinkMsg struct {
	Title string `json:"title"`
	Cover string `json:"cover"`
	Url   string `json:"url"`
}

func (LinkMsg) Convert

func (a LinkMsg) Convert() any

type MarkdownMsg

type MarkdownMsg struct {
	Title string `json:"title"`
	Raw   string `json:"raw"`
}

func (MarkdownMsg) Convert

func (m MarkdownMsg) Convert() any

type Message

type Message struct {
	Platform string
	Topic    string
	Payload  EventPayload
}

type ModuleEvent added in v0.92.0

type ModuleEvent = BotEvent

ModuleEvent is the module-era name for the legacy BotEvent.

type Mount

type Mount struct {
	Type   string `json:"type,omitempty"`
	Source string `json:"source,omitempty"`
	Target string `json:"target,omitempty"`
}

type MsgPayload

type MsgPayload interface {
	Convert() any
}

func ToPayload

func ToPayload(typ string, src []byte) MsgPayload

type ObjHeader

type ObjHeader struct {
	// using string to get around rethinkdb's problems with uint64;
	// `bson:"_id"` tag is for mongodb to use as primary key '_id'.
	Id string `bson:"_id"`
	//id        Uid
	CreatedAt time.Time
	UpdatedAt time.Time
}

ObjHeader is the header shared by all stored objects.

type PipelineStats added in v0.92.0

type PipelineStats struct {
	SuccessRateTrend     []SuccessRatePoint   `json:"success_rate_trend"`
	DurationDistribution DurationDistribution `json:"duration_distribution"`
	TriggerSourcePie     []TriggerSourceCount `json:"trigger_source_pie"`
}

PipelineStats holds aggregated pipeline run statistics for chart rendering.

type Registry

type Registry struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
}

func (*Registry) Clone

func (r *Registry) Clone() *Registry

type RetryConfig added in v0.92.0

type RetryConfig struct {
	MaxAttempts int           `json:"max_attempts" yaml:"max_attempts"` // Total execution attempts; 0 or 1 means no retry.
	Delay       time.Duration `json:"delay" yaml:"delay"`
	Backoff     string        `json:"backoff" yaml:"backoff"` // fixed | linear | exponential
	MaxDelay    time.Duration `json:"max_delay" yaml:"max_delay"`
	Jitter      bool          `json:"jitter" yaml:"jitter"`
	RetryOn     []string      `json:"retry_on,omitempty" yaml:"retry_on,omitempty"`
}

RetryConfig defines the retry strategy for a pipeline step or workflow task.

func (*RetryConfig) BuildBackOff added in v0.92.0

func (r *RetryConfig) BuildBackOff() backoff.BackOff

BuildBackOff constructs a backoff.BackOff from the retry configuration. Returns a StopBackOff if the config is nil. Deprecated: Use ToBackoffConfig() and backoff.Do() instead.

func (*RetryConfig) RetryEnabled added in v0.92.0

func (r *RetryConfig) RetryEnabled() bool

RetryEnabled returns true if retries are configured with more than one attempt. Deprecated: Use backoff.Config.MaxAttempts > 1 directly.

func (*RetryConfig) ToBackoffConfig added in v0.92.0

func (r *RetryConfig) ToBackoffConfig() flowbackoff.Config

ToBackoffConfig converts the legacy RetryConfig to the unified backoff.Config.

type Ruler added in v0.30.1

type Ruler interface {
	ID() string
	TYPE() RulesetType
}

type RulesetType added in v0.30.1

type RulesetType string
const (
	ActionRule     RulesetType = "action"
	CommandRule    RulesetType = "command"
	FormRule       RulesetType = "form"
	TriggerRule    RulesetType = "trigger"
	WebserviceRule RulesetType = "webservice"
	WorkflowRule   RulesetType = "workflow"
)

type SuccessRatePoint added in v0.92.0

type SuccessRatePoint struct {
	Date    string  `json:"date"`
	Total   int64   `json:"total"`
	Success int64   `json:"success"`
	Rate    float64 `json:"rate"`
}

SuccessRatePoint is a single data point on the success rate trend chart.

type TableMsg

type TableMsg struct {
	Title  string   `json:"title"`
	Header []string `json:"header"`
	Row    [][]any  `json:"row"`
}

func (TableMsg) Convert

func (t TableMsg) Convert() any

type Task

type Task struct {
	ID          string            `json:"id,omitempty"`
	State       TaskState         `json:"state,omitempty"`
	CreatedAt   *time.Time        `json:"created_at,omitempty"`
	StartedAt   *time.Time        `json:"started_at,omitempty"`
	CompletedAt *time.Time        `json:"completed_at,omitempty"`
	FailedAt    *time.Time        `json:"failed_at,omitempty"`
	CMD         []string          `json:"cmd,omitempty"`
	Entrypoint  []string          `json:"entrypoint,omitempty"`
	Run         string            `json:"run,omitempty"`
	Image       string            `json:"image,omitempty"`
	Registry    *Registry         `json:"registry,omitempty"`
	Env         map[string]string `json:"env,omitempty"`
	Files       map[string]string `json:"files,omitempty"`
	Error       string            `json:"error,omitempty"`
	Pre         []*Task           `json:"pre,omitempty"`
	Post        []*Task           `json:"post,omitempty"`
	Mounts      []Mount           `json:"mounts,omitempty"`
	Networks    []string          `json:"networks,omitempty"`
	Retry       *TaskRetry        `json:"retry,omitempty"`
	Limits      *TaskLimits       `json:"limits,omitempty"`
	Timeout     string            `json:"timeout,omitempty"`
	Result      string            `json:"result,omitempty"`
	GPUs        string            `json:"gpus,omitempty"`
}

Task is the basic unit of work that a Worker can handle.

func CloneTasks

func CloneTasks(tasks []*Task) []*Task

func (*Task) Clone

func (t *Task) Clone() *Task

type TaskLimits

type TaskLimits struct {
	CPUs   string `json:"cpus,omitempty"`
	Memory string `json:"memory,omitempty"`
}

func (*TaskLimits) Clone

func (l *TaskLimits) Clone() *TaskLimits

type TaskRetry

type TaskRetry struct {
	Limit    int `json:"limit,omitempty"`
	Attempts int `json:"attempts,omitempty"`
}

func (*TaskRetry) Clone

func (r *TaskRetry) Clone() *TaskRetry

type TaskState

type TaskState string

TaskState State defines the list of states that a task can be in, at any given moment.

const (
	TaskStatePending   TaskState = "PENDING"
	TaskStateRunning   TaskState = "RUNNING"
	TaskStateCancelled TaskState = "CANCELED"
	TaskStateStopped   TaskState = "STOPPED"
	TaskStateCompleted TaskState = "COMPLETED"
	TaskStateFailed    TaskState = "FAILED"
)

func (TaskState) IsActive

func (s TaskState) IsActive() bool

type TextMsg

type TextMsg struct {
	Text string `json:"text"`
}

func (TextMsg) Convert

func (t TextMsg) Convert() any

type TriggerSourceCount added in v0.92.0

type TriggerSourceCount struct {
	Source string `json:"source"`
	Count  int64  `json:"count"`
}

TriggerSourceCount counts pipeline runs grouped by trigger source.

type Uid

type Uid string

Uid is a database-specific record id, suitable to be used as a primary key.

const ZeroUid Uid = ""

ZeroUid is a constant representing uninitialized Uid.

func (Uid) IsZero

func (uid Uid) IsZero() bool

IsZero checks if Uid is uninitialized.

func (Uid) String

func (uid Uid) String() string

stringer implements fmt.Stringer interface.

type WorkflowMetadata

type WorkflowMetadata struct {
	Name           string               `json:"name" yaml:"name"`
	Describe       string               `json:"describe" yaml:"describe"`
	Resumable      bool                 `json:"resumable" yaml:"resumable"`
	MaxConcurrency int                  `json:"max_concurrency" yaml:"max_concurrency"` // 0 or 1 = sequential; >1 enables DAG-based parallel execution
	Triggers       []WorkflowTriggerDef `json:"triggers" yaml:"triggers"`
	Pipeline       []string             `json:"pipeline" yaml:"pipeline"`
	Tasks          []WorkflowTask       `json:"tasks" yaml:"tasks"`
}

type WorkflowTask

type WorkflowTask struct {
	ID       string       `json:"id" yaml:"id"`
	Action   string       `json:"action" yaml:"action"`
	Describe string       `json:"describe,omitempty" yaml:"describe"`
	Params   KV           `json:"params,omitempty" yaml:"params"`
	Vars     []string     `json:"vars,omitempty" yaml:"vars"`
	Conn     []string     `json:"conn,omitempty" yaml:"conn"`
	Retry    *RetryConfig `json:"retry,omitempty" yaml:"retry,omitempty"`
}

type WorkflowTriggerDef added in v0.92.0

type WorkflowTriggerDef struct {
	Type string `json:"type" yaml:"type"`
	Rule KV     `json:"rule,omitempty" yaml:"rule"`
}

WorkflowTriggerDef defines a single trigger for a workflow.

Directories

Path Synopsis
Package audit provides the Auditor interface and supporting types for audit logging.
Package audit provides the Auditor interface and supporting types for audit logging.
Package model provides shared data types for UI views and transport.
Package model provides shared data types for UI views and transport.
Package protocol provides platform-agnostic protocol types for request/response handling.
Package protocol provides platform-agnostic protocol types for request/response handling.
ruleset
command
Package command implements the command ruleset type.
Package command implements the command ruleset type.
form
Package form implements the form ruleset type.
Package form implements the form ruleset type.
webservice
Package webservice implements the web service ruleset type.
Package webservice implements the web service ruleset type.

Jump to

Keyboard shortcuts

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