Documentation
¶
Overview ¶
Package taskengine provides a configurable workflow system for building AI-powered task chains. It supports LLM interactions, external integrations via hooks, complex branching logic, and robust error handling with retries and timeouts.
Key Features: - Multiple task handlers (condition keys, parsing, hooks, no-op) - Type-safe data passing between tasks - Conditional branching with various operators - External system integration via hooks - Comprehensive debugging and monitoring - Template-based prompt generation
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:
- Chatbot systems
- Data processing pipelines
- Automated decision-making systems
- 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
- Variables
- func AppendWidgetHint(ctx context.Context, hint WidgetHint)
- func AppendWidgetHintTyped(ctx context.Context, kind string, payload any)
- func ConvertToType(value interface{}, dataType DataType) (interface{}, error)
- func ExportedResolveHookNames(ctx context.Context, allowlist []string, provider HookProvider) ([]string, error)
- func ExtractJSONArray(s string) string
- func ExtractJSONObject(s string) string
- func HookArgsFromContext(ctx context.Context, hookName string) map[string]string
- func HookToolsUnavailable(hookName string, cause error) error
- func MergeTemplateVars(ctx context.Context, overlay map[string]string) context.Context
- func PlanStepContextFromContext(ctx context.Context) (string, string, bool)
- func PublishPlanRunEvent(ctx context.Context, sink TaskEventSink, kind TaskEventKind, content string)
- func PublishPlanRunFailed(ctx context.Context, sink TaskEventSink, err error)
- func RuntimeHookAllowlistFromContext(ctx context.Context) ([]string, bool)
- func StripCodeFences(s string) string
- func SupportedOperators() []string
- func TaskEventRequestSubject(requestID string) string
- func TemplateVarsFromContext(ctx context.Context) (map[string]string, error)
- func WithCompactionRegistry(ctx context.Context, reg *CompactionStateRegistry) context.Context
- func WithHookArgs(ctx context.Context, hookName string, args map[string]string) context.Context
- func WithPlanStepContext(ctx context.Context, planID, stepID string) context.Context
- func WithRetryOutcomeSink(ctx context.Context, sink *RetryOutcomeSink) context.Context
- func WithRuntimeHookAllowlist(ctx context.Context, allowlist []string) context.Context
- func WithTaskEventScope(ctx context.Context, scope TaskEventScope) context.Context
- func WithTaskEventSink(ctx context.Context, sink TaskEventSink) context.Context
- func WithTemplateVars(ctx context.Context, vars map[string]string) context.Context
- func WithWidgetHintSink(ctx context.Context, sink *WidgetHintSink) context.Context
- type BranchCompose
- type BusTaskEventSink
- type CapturedStateUnit
- type ChainContext
- type ChainTerms
- type ChatHistory
- type CompactionStateRegistry
- type DataType
- type EnvExecutor
- type ErrorResponse
- type ExecutionState
- type FunctionCall
- type FunctionCallObject
- type FunctionTool
- type HookCall
- type HookProvider
- type HookRegistry
- type HookRepo
- type HooksWithSchema
- type Inspector
- type KVActivitySink
- func (t *KVActivitySink) GetActivityLogs(ctx context.Context, limit int) ([]TrackedEvent, error)
- func (t *KVActivitySink) GetActivityLogsByRequestID(ctx context.Context, requestID string) ([]TrackedEvent, error)
- func (t *KVActivitySink) GetExecutionStateByRequestID(ctx context.Context, requestID string) ([]CapturedStateUnit, error)
- func (t *KVActivitySink) GetKnownOperations(ctx context.Context) ([]Operation, error)
- func (t *KVActivitySink) GetRecentRequestIDs(ctx context.Context, limit int) ([]TrackedRequest, error)
- func (t *KVActivitySink) GetRequestIDByOperation(ctx context.Context, operation Operation) ([]TrackedRequest, error)
- func (t *KVActivitySink) GetStatefulRequests(ctx context.Context) ([]string, error)
- func (t *KVActivitySink) Start(ctx context.Context, operation string, subject string, kvArgs ...any) (func(error), func(string, any), func())
- type LLMExecutionConfig
- type MacroEnv
- type Message
- type MockTaskExecutor
- type NoopTaskEventSink
- type Operation
- type OperatorTerm
- type RetryOutcomeSink
- type SimpleEnv
- type SimpleExec
- type SimpleStackTrace
- func (s *SimpleStackTrace) ClearBreakpoints()
- func (s *SimpleStackTrace) GetCurrentState() ExecutionState
- func (s *SimpleStackTrace) GetExecutionHistory() []CapturedStateUnit
- func (s *SimpleStackTrace) HasBreakpoint(taskID string) bool
- func (s *SimpleStackTrace) RecordStep(step CapturedStateUnit)
- func (s *SimpleStackTrace) SetBreakpoint(taskID string)
- type StackTrace
- type TaskChainDefinition
- type TaskDefinition
- type TaskEvent
- type TaskEventKind
- type TaskEventScope
- type TaskEventSink
- type TaskExecutor
- type TaskHandler
- type TaskTransition
- type Tool
- type ToolCall
- type ToolWithResolution
- type TrackedEvent
- type TrackedRequest
- type TransitionBranch
- type WidgetHint
- type WidgetHintSink
Constants ¶
const (
TaskEventSubjectAll = "taskengine.events"
)
const (
TermEnd = "end"
)
Variables ¶
var ErrHookNotFound = errors.New("hook not found")
ErrHookNotFound is returned when a named hook is not registered in any repo.
ErrHookToolsUnavailable is returned when a hook is registered but its tool list cannot be loaded (e.g. MCP server unreachable or list-tools failed). ExecEnv treats this like a missing hook for tool preload: skip tools, continue the chain.
var ErrUnsupportedTaskType = errors.New("executor does not support the task type")
ErrUnsupportedTaskType indicates unrecognized task type
Functions ¶
func AppendWidgetHint ¶
func AppendWidgetHint(ctx context.Context, hint WidgetHint)
AppendWidgetHint records hint on the context-bound sink, if one is attached. No-op when no sink is set so direct taskengine callers (and tests) work without ceremony.
Hooks call this AFTER successfully producing their primary tool-result content. Failure paths should NOT emit hints — the agent does not need a widget for an error that already lives in the tool message.
func AppendWidgetHintTyped ¶
AppendWidgetHintTyped is the typed variant: encodes payload to JSON and calls AppendWidgetHint. Errors are silent because UI hints are best-effort — a failed encode just means the user sees no widget for that tool call, not that the tool itself failed.
func ConvertToType ¶
ConvertToType converts a value to the specified DataType
func ExportedResolveHookNames ¶
func ExportedResolveHookNames(ctx context.Context, allowlist []string, provider HookProvider) ([]string, error)
ExportedResolveHookNames is a test-only export of resolveHookNames.
func ExtractJSONArray ¶
ExtractJSONArray scans s for the outermost [...] block and returns it. It first strips code fences, then skips any preamble text the LLM may have placed before the JSON array to be robust to inconsistent model output.
func ExtractJSONObject ¶
ExtractJSONObject scans s for the outermost {...} block and returns it. It strips code fences first, same spirit as ExtractJSONArray.
func HookArgsFromContext ¶
HookArgsFromContext returns the args previously stored for hookName, or nil if none were set. The returned map must not be mutated by the caller.
func HookToolsUnavailable ¶
HookToolsUnavailable wraps cause as ErrHookToolsUnavailable for hookName (for errors.Is).
func MergeTemplateVars ¶
MergeTemplateVars overlays keys onto any template vars already in ctx, then attaches the combined map. Use this when a nested step (e.g. plan execution) must add request_id / previous_output without dropping caller-supplied vars like model and provider.
func PlanStepContextFromContext ¶
PlanStepContextFromContext returns (planID, stepID, true) when attached. Returns ("", "", false) when not set — callers should fail cleanly in that case rather than write to an unknown row.
func PublishPlanRunEvent ¶
func PublishPlanRunEvent(ctx context.Context, sink TaskEventSink, kind TaskEventKind, content string)
PublishPlanRunEvent emits a plan run lifecycle event on the given sink (e.g. NewBusTaskEventSink). No-op when sink is nil or disabled. Uses request ID from ctx when present for per-request SSE subjects.
func PublishPlanRunFailed ¶
func PublishPlanRunFailed(ctx context.Context, sink TaskEventSink, err error)
PublishPlanRunFailed emits plan_run_failed with err.Error() on the Error field.
func RuntimeHookAllowlistFromContext ¶
RuntimeHookAllowlistFromContext returns (allowlist, true) when an allowlist was attached via WithRuntimeHookAllowlist. The returned slice follows the same grammar as TaskDefinition.Hooks. Returns (nil, false) when no runtime allowlist is attached — callers should treat this as "no restriction".
func StripCodeFences ¶
func SupportedOperators ¶
func SupportedOperators() []string
func TaskEventRequestSubject ¶
func TemplateVarsFromContext ¶
TemplateVarsFromContext returns the template variables map from the context. Returns nil if not set; a nil map is safe to read (key lookup returns false). MacroEnv will return an error for any {{var:key}} whose key is absent.
func WithCompactionRegistry ¶
func WithCompactionRegistry(ctx context.Context, reg *CompactionStateRegistry) context.Context
WithCompactionRegistry attaches reg to ctx so chat_completion tasks can look up persistent compact.State for compaction circuit-breaking.
func WithHookArgs ¶
WithHookArgs stores a copy of args for the named hook in ctx.
The map is copied on entry so the stored value is immutable — callers must not rely on mutating the original map being visible to hook implementations. This ensures no data races when the same context is read concurrently (e.g. during tool-list construction in ExecEnv).
func WithPlanStepContext ¶
WithPlanStepContext attaches plan + step identity to ctx. Hooks compiled into a plan's per-step DAG (e.g. plan_summary persist/fallback) read this to know which DB row to write, since the identity is chosen at ClaimNextPendingStep time — not at plancompile time — and cannot live in the compiled chain JSON. Mirrors the WithTemplateVars / WithRuntimeHookAllowlist pattern: unexported key struct, wrapper value, ok-convention getter.
func WithRetryOutcomeSink ¶
func WithRetryOutcomeSink(ctx context.Context, sink *RetryOutcomeSink) context.Context
WithRetryOutcomeSink attaches sink to ctx so chat_completion tasks can append outcomes via [appendRetryOutcome].
func WithRuntimeHookAllowlist ¶
WithRuntimeHookAllowlist attaches a caller-supplied hook allowlist to ctx that is intersected with each task's own allowlist inside resolveHookNames. A caller can only further restrict — never expand — what a chain JSON permits. Grammar matches TaskDefinition.Hooks: nil/[]/["*"]/exact names/["*","!name"].
Use this when a host (e.g. planservice) must enforce per-call policy (such as disabling local_shell for a step) regardless of what the chain JSON declares. Absent key means "no runtime restriction" — behavior matches pre-feature code.
func WithTaskEventScope ¶
func WithTaskEventScope(ctx context.Context, scope TaskEventScope) context.Context
func WithTaskEventSink ¶
func WithTaskEventSink(ctx context.Context, sink TaskEventSink) context.Context
func WithTemplateVars ¶
WithTemplateVars attaches a map of template variables to the context. MacroEnv expands {{var:name}} from this map. The engine never reads os.Getenv; callers (e.g. Contenox CLI, API) build the map and attach it here.
func WithWidgetHintSink ¶
func WithWidgetHintSink(ctx context.Context, sink *WidgetHintSink) context.Context
WithWidgetHintSink attaches sink to ctx so hooks reachable from this context can call AppendWidgetHint.
Types ¶
type BranchCompose ¶
type BranchCompose struct {
// Selects the variable to compose the current input with.
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"`
}
BranchCompose 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 BusTaskEventSink ¶
type BusTaskEventSink struct {
// contains filtered or unexported fields
}
func NewBusTaskEventSink ¶
func NewBusTaskEventSink(bus libbus.Messenger) *BusTaskEventSink
func (*BusTaskEventSink) Enabled ¶
func (s *BusTaskEventSink) Enabled() bool
func (*BusTaskEventSink) PublishTaskEvent ¶
func (s *BusTaskEventSink) PublishTaskEvent(ctx context.Context, event TaskEvent) error
type CapturedStateUnit ¶
type CapturedStateUnit struct {
TaskID string `json:"taskID" example:"validate_input"`
TaskHandler string `json:"taskHandler" example:"condition_key"`
InputType DataType `json:"inputType" example:"string" openapi_include_type:"string"`
OutputType DataType `json:"outputType" example:"string" openapi_include_type:"string"`
Transition string `json:"transition" example:"valid_input"`
Duration time.Duration `json:"duration" example:"452000000"` // in nanoseconds
Error ErrorResponse `json:"error" openapi_include_type:"taskengine.ErrorResponse"`
Input string `json:"input" example:"This is a test input that needs validation"`
Output string `json:"output" example:"valid"`
InputVar string `json:"inputVar" example:"input"` // Which variable was used as input
}
func (CapturedStateUnit) MarshalJSON ¶
func (c CapturedStateUnit) MarshalJSON() ([]byte, error)
value receiver so json.Marshal works on both CapturedStateUnit values and pointers. With a pointer receiver, marshal-by-value skips the custom method and stores Duration as a raw nanosecond integer.
func (*CapturedStateUnit) UnmarshalJSON ¶
func (c *CapturedStateUnit) UnmarshalJSON(data []byte) error
type ChainContext ¶
type ChainContext struct {
Tools map[string]ToolWithResolution
ClientTools []Tool
Debug bool
}
type ChainTerms ¶
type ChainTerms string
type ChatHistory ¶
type ChatHistory struct {
// Messages is the list of messages in the conversation.
Messages []Message `json:"messages"`
// Model is the name of the model to use for the conversation.
Model string `json:"model" example:"mistral:instruct"`
// InputTokens will be filled by the engine and will hold the number of tokens used for the input.
InputTokens int `json:"inputTokens" example:"15"`
// OutputTokens will be filled by the engine and will hold the number of tokens used for the output.
OutputTokens int `json:"outputTokens" example:"10"`
}
ChatHistory represents a conversation history with an LLM.
type CompactionStateRegistry ¶
type CompactionStateRegistry struct {
// contains filtered or unexported fields
}
CompactionStateRegistry holds per-task compact.State across multiple invocations of the same chat task within one chain run, so the circuit breaker carries between agentic-loop rounds.
planservice attaches a registry via WithCompactionRegistry before running a compiled plan chain. Each chat_completion task looks up state by task ID; missing entries are created lazily.
func NewCompactionStateRegistry ¶
func NewCompactionStateRegistry() *CompactionStateRegistry
NewCompactionStateRegistry returns an empty registry.
type DataType ¶
type DataType int
DataType represents the type of data passed between tasks.
func DataTypeFromString ¶
DataTypeFromString converts a string to DataType.
func InferDataType ¶
InferDataType picks the narrowest concrete DataType for a runtime value.
func NormalizeDataType ¶
NormalizeDataType upgrades DataTypeAny to a concrete type and coerces the value with ConvertToType.
func (DataType) MarshalJSON ¶
func (DataType) MarshalYAML ¶
func (*DataType) UnmarshalJSON ¶
func (*DataType) UnmarshalYAML ¶
type EnvExecutor ¶
type EnvExecutor interface {
ExecEnv(ctx context.Context, chain *TaskChainDefinition, input any, dataType DataType) (any, DataType, []CapturedStateUnit, error)
}
EnvExecutor executes complete task chains with input and environment management.
func NewEnv ¶
func NewEnv( ctx context.Context, tracker libtracker.ActivityTracker, exec TaskExecutor, inspector Inspector, hookProvider HookRepo, ) (EnvExecutor, error)
NewEnv creates a new SimpleEnv with the given tracker and task executor.
func NewMacroEnv ¶
func NewMacroEnv(inner EnvExecutor, hookProvider HookRepo) (EnvExecutor, error)
NewMacroEnv wraps an existing EnvExecutor with macro expansion.
type ErrorResponse ¶
type ExecutionState ¶
type ExecutionState struct {
Variables map[string]any
DataTypes map[string]DataType
CurrentTask *TaskDefinition
}
type FunctionCall ¶
type FunctionCall struct {
Name string `json:"name" example:"get_current_weather"`
Arguments string `json:"arguments" example:"{\n \"location\": \"San Francisco, CA\",\n \"unit\": \"celsius\"\n}"`
}
FunctionCall specifies the function name and arguments for a tool call.
type FunctionCallObject ¶
type FunctionTool ¶
type FunctionTool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters interface{} `json:"parameters,omitempty"` // JSON Schema object
}
FunctionTool defines the schema for a function-type tool.
type HookCall ¶
type HookCall struct {
// Name is the registered hook-service (e.g., "send_email").
Name string `yaml:"name" json:"name" example:"slack"`
// ToolName is the name of the tool to invoke (e.g., "send_slack_notification").
ToolName string `yaml:"tool_name" json:"tool_name" example:"send_slack_notification"`
// 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" example:"{\"channel\": \"#alerts\", \"message\": \"Task completed successfully\"}"`
}
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 HookProvider ¶
type HookProvider interface {
HookRegistry
HooksWithSchema
}
type HookRepo ¶
type HookRepo interface {
Exec(ctx context.Context, startingTime time.Time, input any, debug bool, args *HookCall) (any, DataType, error)
HookRegistry
HooksWithSchema
}
HookRepo defines interface for external system integrations and side effects.
type HooksWithSchema ¶
type Inspector ¶
type Inspector interface {
Start(ctx context.Context) StackTrace
}
func NewSimpleInspector ¶
func NewSimpleInspector() Inspector
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)
type LLMExecutionConfig ¶
type LLMExecutionConfig struct {
Model string `yaml:"model" json:"model" example:"mistral:instruct"`
Models []string `yaml:"models,omitempty" json:"models,omitempty" example:"[\"gpt-4\", \"gpt-3.5-turbo\"]"`
Provider string `yaml:"provider,omitempty" json:"provider,omitempty" example:"ollama"`
Providers []string `yaml:"providers,omitempty" json:"providers,omitempty" example:"[\"ollama\", \"openai\"]"`
Temperature float32 `yaml:"temperature,omitempty" json:"temperature,omitempty" example:"0.7"`
// Hooks is the allowlist of hook names this task may invoke.
//
// Patterns supported:
// - absent/null — all registered hooks (backward-compatible default)
// - [] — no hooks exposed to the model
// - ["*"] — all registered hooks (explicit)
// - ["a","b"] — only the named hooks (unknown names silently ignored)
// - ["*","!name"] — all hooks except the excluded name(s)
//
// Exclusions ("!name") are only meaningful when combined with "*".
Hooks []string `yaml:"hooks,omitempty" json:"hooks,omitempty" example:"[\"local_shell\", \"nws\"]"`
HideTools []string `yaml:"hide_tools,omitempty" json:"hide_tools,omitempty" example:"[\"tool1\", \"hook_name1.tool1\"]"`
// HookPolicies carries per-hook policy overrides for this task.
// Keys are hook names; values are maps of policy key → value pairs.
// These are injected into the context before GetToolsForHookByName is called,
// so hooks can produce dynamic tool descriptions and enforce the policy at Exec time.
//
// Example (local_shell):
// hook_policies:
// local_shell:
// _allowed_commands: "git,go,ls,cat,grep"
// _denied_commands: "sudo,su,dd,mkfs"
HookPolicies map[string]map[string]string `yaml:"hook_policies,omitempty" json:"hook_policies,omitempty"`
PassClientsTools bool `yaml:"pass_clients_tools" json:"pass_clients_tools"`
// Think enables reasoning mode for supported models.
// Accepts "true"/"false" or "high"/"medium"/"low". Empty = provider default (off).
Think string `yaml:"think,omitempty" json:"think,omitempty" example:"high"`
// Shift allows the context window to slide on overflow instead of erroring.
Shift bool `yaml:"shift,omitempty" json:"shift,omitempty"`
// RetryPolicy wraps the underlying chat/prompt call with classified retry
// (rate-limit / server-error / timeout) and an optional model fallback.
// Nil or zero-value disables retry — current default. See [llmretry.Do].
RetryPolicy *llmretry.RetryPolicy `yaml:"retry_policy,omitempty" json:"retry_policy,omitempty"`
// CompactPolicy enables mid-run conversation compaction at the head of a
// chat_completion task: when the running ChatHistory exceeds
// TriggerFraction * token_limit, older messages are summarized and replaced
// with a single synthetic <compact-summary> user message. Nil disables
// compaction (current default). See [compact.Maybe].
CompactPolicy *compact.Policy `yaml:"compact_policy,omitempty" json:"compact_policy,omitempty"`
}
LLMExecutionConfig represents configuration for executing tasks using Large Language Models (LLMs).
type MacroEnv ¶
type MacroEnv struct {
// contains filtered or unexported fields
}
MacroEnv is a transparent decorator around EnvExecutor that expands special macros in task templates before execution. Supported macros:
- {{hookservice:list}} -> JSON map of hook name -> tool names
- {{hookservice:hooks}} -> JSON array of hook names
- {{hookservice:tools <hook_name>}} -> JSON array of tool names for that hook
- {{var:<name>}} -> value from context template vars (set by caller via WithTemplateVars; engine never reads env); errors if key is missing
- {{now}} or {{now:<layout>}} -> current time (default RFC3339; layout e.g. 2006-01-02)
- {{chain:id}} -> chain ID of the chain being executed
The engine does not expand any env:VAR-style macro; var:* is populated only by the caller.
type Message ¶
type Message struct {
// ID is the unique identifier for the message.
// This field is not used by the engine. It can be filled as part of the Request, or left empty.
// The ID is useful for tracking messages and computing differences of histories before storage.
ID string `json:"id" example:"msg_123456"`
// Role is the role of the message sender.
Role string `json:"role" example:"user"`
// Content is the content of the message.
Content string `json:"content,omitempty" example:"What is the capital of France?"`
// Thinking is the model's internal reasoning trace.
// Only populated when thinking is enabled; never sent back to the model as history.
Thinking string `json:"thinking,omitempty"`
// ToolCallID is the ID of the tool call associated with the message.
ToolCallID string `json:"tool_call_id,omitempty"`
// CallTools is the tool call of the message sender.
CallTools []ToolCall `json:"callTools,omitempty"`
// Timestamp is the time the message was sent.
Timestamp time.Time `json:"timestamp" example:"2023-11-15T14:30:45Z"`
}
Message represents a single message in a chat conversation.
type MockTaskExecutor ¶
type MockTaskExecutor struct {
// Single value responses
MockOutput any
MockTransitionValue string
MockError error
// Sequence responses
MockOutputSequence []any
MockTaskTypeSequence []DataType
MockTransitionValueSequence []string
ErrorSequence []error
// Tracking
CalledWithTask *TaskDefinition
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, tokenLimit int, chainContext *ChainContext, currentTask *TaskDefinition, input any, dataType DataType) (any, DataType, string, error)
TaskExec is the mock implementation of the TaskExec method.
type NoopTaskEventSink ¶
type NoopTaskEventSink struct{}
func (NoopTaskEventSink) Enabled ¶
func (NoopTaskEventSink) Enabled() bool
func (NoopTaskEventSink) PublishTaskEvent ¶
func (NoopTaskEventSink) PublishTaskEvent(context.Context, TaskEvent) error
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 RetryOutcomeSink ¶
type RetryOutcomeSink struct {
// contains filtered or unexported fields
}
RetryOutcomeSink collects per-call retry outcomes from chat_completion tasks running inside one chain invocation. It is safe for concurrent appenders.
planservice attaches a sink via WithRetryOutcomeSink before running a compiled plan chain so it can observe whether any chat call retried, used fallback, or hit a non-retryable class (e.g. capacity) — used to decide auto-replan in §3.
func (*RetryOutcomeSink) Append ¶
func (s *RetryOutcomeSink) Append(o llmretry.Outcome)
Append records one outcome. Safe for concurrent use.
func (*RetryOutcomeSink) LastErrorClass ¶
func (s *RetryOutcomeSink) LastErrorClass() llmretry.ErrorClass
LastErrorClass returns the class of the most recent recorded outcome, or llmretry.ClassNone if no outcomes were recorded.
func (*RetryOutcomeSink) Outcomes ¶
func (s *RetryOutcomeSink) Outcomes() []llmretry.Outcome
Outcomes returns a snapshot of recorded outcomes in append order.
type SimpleEnv ¶
type SimpleEnv struct {
// contains filtered or unexported fields
}
SimpleEnv is the default implementation of EnvExecutor.
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) Prompt ¶
func (exe *SimpleExec) Prompt(ctx context.Context, systemInstruction string, llmCall LLMExecutionConfig, prompt string, ctxLength int) (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, ctxLength int, chainContext *ChainContext, currentTask *TaskDefinition, input any, dataType DataType) (any, DataType, string, error)
TaskExec dispatches task execution based on the task type.
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
}
type TaskChainDefinition ¶
type TaskChainDefinition 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 []TaskDefinition `yaml:"tasks" json:"tasks" openapi_include_type:"taskengine.TaskDefinition"`
// TokenLimit is the token limit for the context window (used during execution).
TokenLimit int64 `yaml:"token_limit" json:"token_limit"`
}
TaskChainDefinition describes a sequence of tasks to execute in order, along with branching logic, retry policies, and model preferences.
TaskChainDefinition support dynamic routing based on LLM outputs or conditions, and can include hooks to perform external actions (e.g., sending emails).
type TaskDefinition ¶
type TaskDefinition struct {
// ID uniquely identifies the task within the chain.
ID string `yaml:"id" json:"id" example:"validate_input"`
// Description is a human-readable summary of what the task does.
Description string `yaml:"description" json:"description" example:"Validates user input meets quality requirements"`
// Handler determines how the LLM output (or hook) will be interpreted.
Handler TaskHandler `yaml:"handler" json:"handler" example:"condition_key" openapi_include_type:"string"`
// SystemInstruction provides additional instructions to the LLM, if applicable system level will be used.
SystemInstruction string `` /* 158-byte string literal not displayed */
// ExecuteConfig defines the configuration for executing prompt or chat model tasks.
ExecuteConfig *LLMExecutionConfig `yaml:"execute_config,omitempty" json:"execute_config,omitempty" openapi_include_type:"taskengine.LLMExecutionConfig"`
// 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" openapi_include_type:"taskengine.HookCall"`
// 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" example:"Validation result: {{.validate_input}}"`
// PromptTemplate is the text prompt sent to the LLM.
// It's Required and only applicable for the prompt_to_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" example:"Is this input valid? {{.input}}"`
// OutputTemplate is an optional go template to format the output of a hook.
// If specified, the hook's JSON output will be used as data for the template.
// The final output of the task will be the rendered string.
// Example: "The weather is {{.weather}} with a temperature of {{.temperature}}."
OutputTemplate string `yaml:"output_template,omitempty" json:"output_template,omitempty" example:"Hook result: {{.status}}"`
// 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" example:"input"`
// Transition defines what to do after this task completes.
Transition TaskTransition `yaml:"transition" json:"transition" openapi_include_type:"taskengine.TaskTransition"`
// 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" example:"30s"`
// 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" example:"2"`
}
type TaskEvent ¶
type TaskEvent struct {
Kind TaskEventKind `json:"kind"`
Timestamp time.Time `json:"timestamp"`
RequestID string `json:"request_id,omitempty"`
ChainID string `json:"chain_id,omitempty"`
TaskID string `json:"task_id,omitempty"`
TaskHandler string `json:"task_handler,omitempty"`
Retry int `json:"retry"`
ModelName string `json:"model_name,omitempty"`
ProviderType string `json:"provider_type,omitempty"`
BackendID string `json:"backend_id,omitempty"`
OutputType string `json:"output_type,omitempty"`
Transition string `json:"transition,omitempty"`
Content string `json:"content,omitempty"`
Thinking string `json:"thinking,omitempty"`
Error string `json:"error,omitempty"`
// Attachments are widget hints produced by hooks during the step that just
// completed (Phase 5 of the canvas-vision plan). Drained from the
// context-bound [WidgetHintSink] at publish time. The Beam UI maps each
// hint to an inline attachment renderer (file_view, terminal_excerpt, …)
// shown adjacent to the assistant message that was streaming when the
// hook fired.
Attachments []WidgetHint `json:"attachments,omitempty"`
// Approval fields — populated only for TaskEventApprovalRequested events.
// ApprovalID is the unique key used to resume or cancel via POST /api/approvals/{id}.
ApprovalID string `json:"approval_id,omitempty"`
HookName string `json:"hook_name,omitempty"`
ToolName string `json:"tool_name,omitempty"`
ApprovalArgs map[string]any `json:"approval_args,omitempty"`
ApprovalDiff string `json:"approval_diff,omitempty"`
}
func NewTaskEvent ¶
func NewTaskEvent(ctx context.Context, kind TaskEventKind) TaskEvent
type TaskEventKind ¶
type TaskEventKind string
const ( TaskEventChainStarted TaskEventKind = "chain_started" TaskEventStepStarted TaskEventKind = "step_started" TaskEventStepChunk TaskEventKind = "step_chunk" TaskEventStepCompleted TaskEventKind = "step_completed" TaskEventStepFailed TaskEventKind = "step_failed" TaskEventChainCompleted TaskEventKind = "chain_completed" TaskEventChainFailed TaskEventKind = "chain_failed" // Plan run lifecycle (load/compile before chain execution); same bus + SSE as other task events. TaskEventPlanRunStarted TaskEventKind = "plan_run_started" TaskEventPlanRunCompiled TaskEventKind = "plan_run_compiled" TaskEventPlanRunFailed TaskEventKind = "plan_run_failed" // TaskEventApprovalRequested is emitted by the HITLWrapper before executing a // gated tool call. The execution goroutine blocks until the human responds via // POST /api/approvals/{approval_id}. The Beam UI renders an approval card. TaskEventApprovalRequested TaskEventKind = "approval_requested" )
type TaskEventScope ¶
type TaskEventSink ¶
type TaskExecutor ¶
type TaskExecutor interface {
// TaskExec executes a single task with the given input and data type.
// Returns:
// - output: The processed task result
// - outputType: The data type of the output
// - transitionEval: String used for transition evaluation
// - error: Any execution error encountered
//
// Parameters:
// - ctx: Context for cancellation and timeouts
// - startingTime: Chain start time for consistent timing
// - ctxLength: Token context length limit for LLM operations
// - chainContext: Immutable context of the chain
// - currentTask: The task definition to execute
// - input: Task input data
// - dataType: Type of the input data
TaskExec(ctx context.Context, startingTime time.Time, ctxLength int, chainContext *ChainContext, currentTask *TaskDefinition, input any, dataType DataType) (any, DataType, string, error)
}
TaskExecutor executes individual tasks within a workflow. Implementations should handle all task types and return appropriate outputs.
func NewExec ¶
func NewExec( ctx context.Context, repo llmrepo.ModelRepo, hookProvider HookRepo, tracker libtracker.ActivityTracker, ) (TaskExecutor, error)
NewExec creates a new SimpleExec instance
type TaskHandler ¶
type TaskHandler string
TaskHandler defines how task outputs are processed and interpreted.
const ( HandlePromptToString TaskHandler = "prompt_to_string" HandlePromptToInt TaskHandler = "prompt_to_int" HandleRaiseError TaskHandler = "raise_error" HandleChatCompletion TaskHandler = "chat_completion" HandleExecuteToolCalls TaskHandler = "execute_tool_calls" HandleNoop TaskHandler = "noop" 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" example:"error_handler"`
// Branches defines conditional branches for successful task completion.
Branches []TransitionBranch `yaml:"branches" json:"branches" openapi_include_type:"taskengine.TransitionBranch"`
}
TaskTransition defines what happens after a task completes, including which task to go to next and how to handle errors.
type Tool ¶
type Tool struct {
Type string `json:"type"`
Function FunctionTool `json:"function"`
}
Tool represents a tool that can be called by the model.
type ToolCall ¶
type ToolCall struct {
ID string `json:"id" example:"call_abc123"`
Type string `json:"type" example:"function"`
Function FunctionCall `json:"function" openapi_include_type:"taskengine.FunctionCall"`
// ProviderMeta carries opaque provider-specific data (e.g. Gemini thought_signature)
// that must be round-tripped back on the next turn.
ProviderMeta map[string]string `json:"provider_meta,omitempty" example:"{\"thought_signature\":\"123456\"}"`
}
ToolCall represents a tool call requested by the model.
type ToolWithResolution ¶
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" example:"equals" openapi_include_type:"string"`
// 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 prompt_to_int: numeric comparison (using Operator)
When string `yaml:"when" json:"when" example:"yes"`
// 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" example:"positive_response"`
// Compose defines how to transform data when taking this branch.
// Optional - if not specified, the current task output is passed as-is.
Compose *BranchCompose `yaml:"compose,omitempty" json:"compose,omitempty" openapi_include_type:"taskengine.BranchCompose"`
}
TransitionBranch defines a single possible path in the workflow, selected when the task's output matches the specified condition.
type WidgetHint ¶
type WidgetHint struct {
Kind string `json:"kind"`
Payload json.RawMessage `json:"payload,omitempty"`
}
WidgetHint is one inline-rendering hint emitted by a hook (or any code on the execution path) that the UI should render adjacent to an assistant message in the chat thread.
The shape mirrors [ContextArtifact] in chatsessionmodes — kind + opaque payload — so the frontend can reuse the same artifact→inline-attachment mapping for both directions of state flow:
- User → LLM: ChatContextPayload.artifacts[] (Phase 1)
- LLM → user: TaskEvent.Attachments[] (Phase 5, this file)
First-party kinds that the Beam UI knows how to render today: file_view, terminal_excerpt, plan_summary, dag, state_unit. The kind string is deliberately untyped here so a hook can emit experimental kinds without a coordinated taskengine release; the UI falls back to a JSON dump for unknown kinds.
type WidgetHintSink ¶
type WidgetHintSink struct {
// contains filtered or unexported fields
}
WidgetHintSink accumulates [WidgetHint]s emitted during a single chain run. The runtime drains it at task-event publish time (see TaskEvent.Attachments).
Safe for concurrent appenders — multiple tool calls in one HandleExecuteToolCalls turn each call AppendWidgetHint from their own goroutine equivalent.
func (*WidgetHintSink) Append ¶
func (s *WidgetHintSink) Append(hint WidgetHint)
Append records one hint. Safe for concurrent use; nil-safe.
func (*WidgetHintSink) Drain ¶
func (s *WidgetHintSink) Drain() []WidgetHint
Drain atomically returns all accumulated hints and clears the sink. Used by the task-event publisher to attach hints to the next outgoing event, guaranteeing each hint is reported exactly once.
func (*WidgetHintSink) Snapshot ¶
func (s *WidgetHintSink) Snapshot() []WidgetHint
Snapshot returns a copy without clearing — for tests / debugging.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package compact summarizes older messages of a running ChatHistory when it approaches the model's context window, replacing them with one synthetic user message of the form:
|
Package compact summarizes older messages of a running ChatHistory when it approaches the model's context window, replacing them with one synthetic user message of the form: |
|
Package llmretry wraps a single LLM call with classified retry, exponential backoff, and an optional model fallback.
|
Package llmretry wraps a single LLM call with classified retry, exponential backoff, and an optional model fallback. |