taskengine

package
v0.10.3 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package taskengine runs the steps inside a chain. Each step can call an LLM, invoke a tools, execute a shell command, or branch on output. Chains are defined in JSON you version in git.

Index

Constants

View Source
const (
	TaskEventSubjectAll = "taskengine.events"
)
View Source
const (
	TermEnd = "end"
)

Variables

View Source
var ErrToolsNotFound = errors.New("tools not found")

ErrToolsNotFound is returned when a named tools is not registered in any repo.

View Source
var ErrToolsToolsUnavailable = errors.New("tools tools unavailable")

ErrToolsToolsUnavailable is returned when a tools is registered but its tool list cannot be loaded (e.g. MCP server unreachable or list-tools failed). ExecEnv treats this like a missing tools for tool preload: skip tools, continue the chain.

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

Tools 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

func AppendWidgetHintTyped(ctx context.Context, kind string, payload any)

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

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

ConvertToType converts a value to the specified DataType

func ExportedResolveToolsNames added in v0.10.2

func ExportedResolveToolsNames(ctx context.Context, allowlist []string, provider ToolsProvider) ([]string, error)

ExportedResolveToolsNames is a test-only export of resolveToolsNames.

func ExtractJSONArray

func ExtractJSONArray(s string) string

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

func ExtractJSONObject(s string) string

ExtractJSONObject scans s for the outermost {...} block and returns it. It strips code fences first, same spirit as ExtractJSONArray.

func MergeTemplateVars

func MergeTemplateVars(ctx context.Context, overlay map[string]string) context.Context

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

func PlanStepContextFromContext(ctx context.Context) (string, string, bool)

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 RuntimeToolsAllowlistFromContext added in v0.10.2

func RuntimeToolsAllowlistFromContext(ctx context.Context) ([]string, bool)

RuntimeToolsAllowlistFromContext returns (allowlist, true) when an allowlist was attached via WithRuntimeToolsAllowlist. The returned slice follows the same grammar as TaskDefinition.Tools. Returns (nil, false) when no runtime allowlist is attached — callers should treat this as "no restriction".

func StripCodeFences

func StripCodeFences(s string) string

func SupportedOperators

func SupportedOperators() []string

func TaskEventRequestSubject

func TaskEventRequestSubject(requestID string) string

func TemplateVarsFromContext

func TemplateVarsFromContext(ctx context.Context) (map[string]string, error)

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 ToolsArgsFromContext added in v0.10.2

func ToolsArgsFromContext(ctx context.Context, toolsName string) map[string]string

ToolsArgsFromContext returns the args previously stored for toolsName, or nil if none were set. The returned map must not be mutated by the caller.

func ToolsToolsUnavailable added in v0.10.2

func ToolsToolsUnavailable(toolsName string, cause error) error

ToolsToolsUnavailable wraps cause as ErrToolsToolsUnavailable for toolsName (for errors.Is).

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 WithPlanStepContext

func WithPlanStepContext(ctx context.Context, planID, stepID string) context.Context

WithPlanStepContext attaches plan + step identity to ctx. Tools 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 / WithRuntimeToolsAllowlist 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 WithRuntimeToolsAllowlist added in v0.10.2

func WithRuntimeToolsAllowlist(ctx context.Context, allowlist []string) context.Context

WithRuntimeToolsAllowlist attaches a caller-supplied tools allowlist to ctx that is intersected with each task's own allowlist inside resolveToolsNames. A caller can only further restrict — never expand — what a chain JSON permits. Grammar matches TaskDefinition.Tools: 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

func WithTemplateVars(ctx context.Context, vars map[string]string) context.Context

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 WithToolsArgs added in v0.10.2

func WithToolsArgs(ctx context.Context, toolsName string, args map[string]string) context.Context

WithToolsArgs stores a copy of args for the named tools 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 tools implementations. This ensures no data races when the same context is read concurrently (e.g. during tool-list construction in ExecEnv).

func WithWidgetHintSink

func WithWidgetHintSink(ctx context.Context, sink *WidgetHintSink) context.Context

WithWidgetHintSink attaches sink to ctx so tools 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.

func (*CompactionStateRegistry) Get

func (r *CompactionStateRegistry) Get(taskID string) *compact.State

Get returns the state for taskID, creating it on first access.

type DataType

type DataType int

DataType represents the type of data passed between tasks.

const (
	DataTypeAny DataType = iota
	DataTypeString
	DataTypeInt
	DataTypeJSON
	DataTypeChatHistory
	DataTypeNil
)

func DataTypeFromString

func DataTypeFromString(s string) (DataType, error)

DataTypeFromString converts a string to DataType.

func InferDataType

func InferDataType(v any) DataType

InferDataType picks the narrowest concrete DataType for a runtime value.

func NormalizeDataType

func NormalizeDataType(v any, dt DataType) (any, DataType, error)

NormalizeDataType upgrades DataTypeAny to a concrete type and coerces the value with ConvertToType.

func NormalizeFinalChainOutput

func NormalizeFinalChainOutput(value any, dt DataType) (any, 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

String returns the string representation of the data type.

func (*DataType) UnmarshalJSON

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

func (*DataType) UnmarshalYAML

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

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,
	toolsProvider ToolsRepo,
) (EnvExecutor, error)

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

func NewMacroEnv

func NewMacroEnv(inner EnvExecutor, toolsProvider ToolsRepo) (EnvExecutor, error)

NewMacroEnv wraps an existing EnvExecutor with macro expansion.

type ErrorResponse

type ErrorResponse struct {
	ErrorInternal error  `json:"-"`
	Error         string `json:"error" example:"validation failed: input contains prohibited content"`
}

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 FunctionCallObject struct {
	Name      string `json:"name" example:"get_current_weather"`
	Arguments any    `json:"arguments"`
}

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

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" 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"`
	// Tools is the allowlist of tools names this task may invoke.
	//
	// Patterns supported:
	//   - absent/null   — all registered tools (backward-compatible default)
	//   - []            — no tools exposed to the model
	//   - ["*"]         — all registered tools (explicit)
	//   - ["a","b"]     — only the named tools (unknown names silently ignored)
	//   - ["*","!name"] — all tools except the excluded name(s)
	//
	// Exclusions ("!name") are only meaningful when combined with "*".
	Tools     []string `yaml:"tools,omitempty" json:"tools,omitempty" example:"[\"local_shell\", \"nws\"]"`
	HideTools []string `yaml:"hide_tools,omitempty" json:"hide_tools,omitempty" example:"[\"tool1\", \"tools_name1.tool1\"]"`
	// ToolsPolicies carries per-tools policy overrides for this task.
	// Keys are tools names; values are maps of policy key → value pairs.
	// These are injected into the context before GetToolsForToolsByName is called,
	// so tools can produce dynamic tool descriptions and enforce the policy at Exec time.
	//
	// Example (local_shell):
	//   tools_policies:
	//     local_shell:
	//       _allowed_commands: "git,go,ls,cat,grep"
	//       _denied_commands:  "sudo,su,dd,mkfs"
	ToolsPolicies    map[string]map[string]string `yaml:"tools_policies,omitempty" json:"tools_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:

  • {{toolservice:list}} -> JSON map of tools name -> tool names
  • {{toolservice:tools}} -> JSON array of tools names
  • {{toolservice:tools <tools_name>}} -> JSON array of tool names for that tools
  • {{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.

func (*MacroEnv) ExecEnv

func (m *MacroEnv) ExecEnv(
	ctx context.Context,
	chain *TaskChainDefinition,
	input any,
	dataType DataType,
) (any, DataType, []CapturedStateUnit, error)

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 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 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.

func (SimpleEnv) ExecEnv

func (env SimpleEnv) ExecEnv(ctx context.Context, chain *TaskChainDefinition, input any, dataType DataType) (result any, resultType DataType, history []CapturedStateUnit, retErr error)

ExecEnv executes the given chain with the provided input.

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 tools.

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 tools 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 tools) 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"`

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

	// Print optionally formats the output for display/logging.
	// Supports template variables from previous task outputs.
	// Optional for all task types except Tools 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 tools.
	// If specified, the tools'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:"Tools 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 Tools.
	// 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 tools 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
	// tools 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"`
	ToolsName    string         `json:"tools_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 TaskEventScope struct {
	ChainID     string
	TaskID      string
	TaskHandler string
	Retry       int
}

type TaskEventSink

type TaskEventSink interface {
	PublishTaskEvent(ctx context.Context, event TaskEvent) error
	Enabled() bool
}

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,
	toolsProvider ToolsRepo,
	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"
	HandleTools            TaskHandler = "tools"
)

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 ToolWithResolution struct {
	Tool
	ToolsName string
}

type ToolsCall added in v0.10.2

type ToolsCall struct {
	// Name is the registered tools-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 tools call.
	// Example: {"to": "user@example.com", "subject": "Notification"}
	Args map[string]string `yaml:"args" json:"args" example:"{\"channel\": \"#alerts\", \"message\": \"Task completed successfully\"}"`
}

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

type ToolsProvider added in v0.10.2

type ToolsProvider interface {
	ToolsRegistry
	ToolsWithSchema
}

type ToolsRegistry added in v0.10.2

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

type ToolsRepo added in v0.10.2

type ToolsRepo interface {
	Exec(ctx context.Context, startingTime time.Time, input any, debug bool, args *ToolsCall) (any, DataType, error)
	ToolsRegistry
	ToolsWithSchema
}

ToolsRepo defines interface for external system integrations and side effects.

type ToolsWithSchema added in v0.10.2

type ToolsWithSchema interface {
	GetSchemasForSupportedTools(ctx context.Context) (map[string]*openapi3.T, error)
	GetToolsForToolsByName(ctx context.Context, name string) ([]Tool, error)
}

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 tools (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 tools 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.

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.

Jump to

Keyboard shortcuts

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