Documentation
¶
Overview ¶
Package taskengine orchestrates an agent: it drives LLM turns, tool calls and routing in a loop, defined as a JSON chain. The TaskEvent stream is the contract clients consume.
Index ¶
- Constants
- Variables
- func ApprovalVerdictFromContext(ctx context.Context, approvalID string) (approved bool, ok bool)
- func AsksDetached(ctx context.Context) bool
- func ConvertToType(value interface{}, dataType DataType) (interface{}, error)
- func EdgeCountsFromContext(ctx context.Context) map[string]int
- func ExportedApplyAllowlist(allowlist []string, all []string) []string
- func ExportedResolveToolsNames(ctx context.Context, allowlist []string, provider ToolsProvider) ([]string, error)
- func ExtractJSONArray(s string) string
- func ExtractJSONObject(s string) string
- func GetPrimaryModel(llmCall *LLMExecutionConfig) string
- func HasCheckpointSaver(ctx context.Context) bool
- func IsAssistantProseHandler(handler string) bool
- func IsToolBearingHandler(handler string) bool
- func LintChain(chain *TaskChainDefinition, entryTypes ...DataType) error
- func MarshalCheckpoint(cp *Checkpoint) ([]byte, error)
- func MarshalGateResult(r GateResult) ([]byte, error)
- func MergeTemplateVars(ctx context.Context, overlay map[string]string) context.Context
- func RequestedContextLengthFromContext(ctx context.Context) int
- func RuntimeToolsAllowlistFromContext(ctx context.Context) ([]string, bool)
- func StateSubject(reqID string) string
- func StripCodeFences(s string) string
- func SupportedOperators() []string
- func TaskEventRequestSubject(requestID string) string
- func TemplateVarsFromContext(ctx context.Context) (map[string]string, error)
- func ToolCallSuspendable(ctx context.Context) bool
- func ToolsArgsFromContext(ctx context.Context, toolsName string) map[string]string
- func ToolsToolsUnavailable(toolsName string, cause error) error
- func WithApprovalVerdicts(ctx context.Context, verdicts map[string]bool) context.Context
- func WithAttentionAnswers(ctx context.Context, answers map[string]AttentionAnswer) context.Context
- func WithCheckpointSaver(ctx context.Context, saver CheckpointSaver) context.Context
- func WithDetachedAsks(ctx context.Context) context.Context
- func WithEdgeCounts(ctx context.Context, counts map[string]int) context.Context
- func WithGateResultRecorder(ctx context.Context, rec GateResultRecorder) context.Context
- func WithGateResultStore(ctx context.Context, store *GateResultStore) context.Context
- func WithRequestedContextLength(ctx context.Context, contextLength int) context.Context
- func WithResumeCheckpoint(ctx context.Context, cp *Checkpoint) context.Context
- func WithRetryOutcomeSink(ctx context.Context, sink *RetryOutcomeSink) context.Context
- func WithRuntimeToolsAllowlist(ctx context.Context, allowlist []string) context.Context
- func WithSuspendableToolCall(ctx context.Context) 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 WithToolsArgs(ctx context.Context, toolsName string, args map[string]string) context.Context
- type ApprovalPendingError
- type AttentionAnswer
- type AudioPart
- type BusInspector
- type BusTaskEventSink
- type CapturedPayloadSummary
- type CapturedStateUnit
- type ChainContext
- type ChainSuspendedError
- type ChainTerms
- type ChatHistory
- type Checkpoint
- type CheckpointSaver
- type DataType
- type EnvExecutor
- type ErrorResponse
- type EventScope
- type FunctionCall
- type FunctionCallObject
- type FunctionTool
- type GateResult
- type GateResultRecorder
- type GateResultStore
- type HandlerOutputMode
- type HandlerSignature
- type ImagePart
- type Inspector
- type KVInspector
- type KVJournalTaskEventSink
- type LLMExecutionConfig
- type MacroEnv
- type Message
- type MockTaskExecutor
- type NoopTaskEventSink
- type OperatorTerm
- type PendingToolCall
- type Prechecker
- type RetryOutcomeSink
- type SimpleEnv
- type SimpleExec
- type SimpleStackTrace
- type StackTrace
- type TaskChainDefinition
- type TaskDefinition
- type TaskEvent
- type TaskEventKind
- type TaskEventScope
- type TaskEventSink
- type TaskExecutor
- type TaskHandler
- type TaskTransition
- type TokenUsage
- type Tool
- type ToolCall
- type ToolWithResolution
- type ToolsCall
- type ToolsProvider
- type ToolsRegistry
- type ToolsRepo
- type ToolsWithSchema
- type TransitionBranch
Constants ¶
const ( ContextKeyOutputByteLimit contextKey = "output_byte_limit" ContextKeyToolCallID contextKey = "tool_call_id" )
const ( // TransitionExecuted: a chat_completion turn finished with no tool calls. TransitionExecuted = "executed" // TransitionToolCall: a chat_completion turn requested one or more tool calls. TransitionToolCall = "tool_call" // TransitionNoop: the noop handler ran, or execute_tool_calls saw empty history. TransitionNoop = "noop" // TransitionNoCallsFound: the model's last message carried no tool calls to run. TransitionNoCallsFound = "no_calls_found" // TransitionToolsExecuted: a tools task ran its tool successfully. TransitionToolsExecuted = "tools_executed" // TransitionFailed: a tools task failed. TransitionFailed = "failed" )
Transition-eval tokens are the control values a handler emits as its transition eval, matched by a TransitionBranch's When field via exact string equality.
const CheckpointSchemaVersion = 1
CheckpointSchemaVersion is the wire version MarshalCheckpoint writes; bump it together with a migration entry in checkpointMigrations, never alone.
const TaskEventSubjectAll = "taskengine.events"
const (
TermEnd = "end"
)
Variables ¶
var ErrChainLint = errors.New("chain failed load-time validation")
ErrChainLint marks every defect the load-time chain linter reports, so services can distinguish "this chain is invalid" (disable it, teach the author) from I/O failures (retry, propagate).
var ErrCheckpointVersion = errors.New("taskengine: unsupported checkpoint schema version")
ErrCheckpointVersion reports a checkpoint whose schema version this binary cannot load (newer than it knows, or older with no migration registered).
var ErrContextLengthExceeded = errors.New("exceeds context length")
ErrContextLengthExceeded is returned when the input or chat history exceeds the allowed context length.
var ErrGateRecordFailed = errors.New("taskengine: gated call executed but recording its result failed")
ErrGateRecordFailed marks a gated call that executed but whose exactly-once record could not be persisted. execute_tool_calls treats it as a hard failure.
var ErrToolsNotFound = errors.New("tools not found")
ErrToolsNotFound is returned when a named tools is not registered in any repo.
ErrToolsToolsUnavailable is returned when a registered tools's tool list cannot be loaded (e.g. MCP server unreachable).
var ErrUnsupportedTaskType = errors.New("executor does not support the task type")
ErrUnsupportedTaskType indicates unrecognized task type
Functions ¶
func ApprovalVerdictFromContext ¶
ApprovalVerdictFromContext reports the pre-loaded verdict for approvalID, ok=false when none was injected.
func AsksDetached ¶ added in v1.0.0
AsksDetached reports whether this run's human asks release the process rather than blocking on it — see WithDetachedAsks.
func ConvertToType ¶
ConvertToType converts a value to the specified DataType
func EdgeCountsFromContext ¶
EdgeCountsFromContext returns the edge counts attached via WithEdgeCounts, or nil if not set.
func ExportedApplyAllowlist ¶ added in v0.40.3
ExportedApplyAllowlist is a test-only export of applyAllowlist.
func ExportedResolveToolsNames ¶
func ExportedResolveToolsNames(ctx context.Context, allowlist []string, provider ToolsProvider) ([]string, error)
ExportedResolveToolsNames is a test-only export of resolveToolsNames.
func ExtractJSONArray ¶
ExtractJSONArray strips code fences then scans s for the outermost [...] block and returns it.
func ExtractJSONObject ¶
ExtractJSONObject strips code fences then scans s for the outermost {...} block and returns it.
func GetPrimaryModel ¶
func GetPrimaryModel(llmCall *LLMExecutionConfig) string
GetPrimaryModel returns llmCall's primary model name, falling back to "default" for token counting when none is configured.
func HasCheckpointSaver ¶
HasCheckpointSaver reports whether a durable checkpoint sink is installed on this run — the precondition for any park-and-release ask.
func IsAssistantProseHandler ¶
IsAssistantProseHandler reports whether a TaskEventStepChunk carrying this handler's streamed output is user-visible assistant narration.
func IsToolBearingHandler ¶
IsToolBearingHandler reports whether this handler already reports its own work through the dedicated tool-call events, so the generic step-lifecycle card can be suppressed for it.
func LintChain ¶
func LintChain(chain *TaskChainDefinition, entryTypes ...DataType) error
LintChain vets a chain at load time; entryTypes are the DataTypes the caller may feed the entry task (omitted treated as DataTypeAny), and all defects are collected and joined into one error wrapping ErrChainLint.
func MarshalCheckpoint ¶
func MarshalCheckpoint(cp *Checkpoint) ([]byte, error)
MarshalCheckpoint encodes cp as the current schema version. A var that cannot be marshalled fails the whole encode.
func MarshalGateResult ¶ added in v0.38.0
func MarshalGateResult(r GateResult) ([]byte, error)
MarshalGateResult encodes r for storage alongside a checkpoint, in the same typed wire form as checkpoint vars.
func MergeTemplateVars ¶
MergeTemplateVars overlays keys onto any template vars already in ctx and reattaches the combined map.
func RequestedContextLengthFromContext ¶
RequestedContextLengthFromContext returns the positive context window attached by WithRequestedContextLength, or 0 when the caller did not request one.
func RuntimeToolsAllowlistFromContext ¶
RuntimeToolsAllowlistFromContext returns the allowlist attached via WithRuntimeToolsAllowlist, or (nil, false) if none was attached.
func StateSubject ¶
func StripCodeFences ¶
func SupportedOperators ¶
func SupportedOperators() []string
func TaskEventRequestSubject ¶
func TemplateVarsFromContext ¶
TemplateVarsFromContext returns the template variables attached via WithTemplateVars, or an error if none were set.
func ToolCallSuspendable ¶
ToolCallSuspendable reports whether the current tool call may suspend the run — see WithSuspendableToolCall.
func ToolsArgsFromContext ¶
ToolsArgsFromContext returns the args stored for toolsName, or nil if none were set; the returned map must not be mutated.
func ToolsToolsUnavailable ¶
ToolsToolsUnavailable wraps cause as ErrToolsToolsUnavailable for toolsName (for errors.Is).
func WithApprovalVerdicts ¶
WithApprovalVerdicts pre-loads human verdicts keyed by approval ID for a resumed run, so the HITL wrapper does not gate an already-recorded call again.
func WithAttentionAnswers ¶
WithAttentionAnswers pre-loads operator answers keyed by ask ID for a resumed run, exactly as WithApprovalVerdicts pre-loads verdicts.
func WithCheckpointSaver ¶
func WithCheckpointSaver(ctx context.Context, saver CheckpointSaver) context.Context
WithCheckpointSaver installs the durable checkpoint sink for runs under ctx. Without one, a run that hits an approval park fails instead of suspending.
func WithDetachedAsks ¶ added in v1.0.0
WithDetachedAsks marks the run under ctx as one whose human asks must not hold the process: a gated tool call records its durable ask and suspends immediately instead of waiting for a verdict. Set it only where nobody is attached to answer — a relay- or event-triggered chain — because the default is to block on the ask, and blocking is what lets an answered ask continue the turn in place. A checkpoint saver is a precondition, not a trigger: a detached run without one fails loudly rather than dropping the gate.
func WithEdgeCounts ¶
WithEdgeCounts attaches the in-flight edge traversal counts (keyed "<fromTaskID>-><toTaskID>") for the current chain run to ctx.
func WithGateResultRecorder ¶ added in v0.38.0
func WithGateResultRecorder(ctx context.Context, rec GateResultRecorder) context.Context
WithGateResultRecorder installs the durable gate-result sink for a resumed run.
func WithGateResultStore ¶ added in v0.38.0
func WithGateResultStore(ctx context.Context, store *GateResultStore) context.Context
WithGateResultStore installs the shared record/replay table for a resumed run.
func WithRequestedContextLength ¶
WithRequestedContextLength attaches a per-request context window used as the resolver's minimum, without replacing the chain's token_limit guardrail.
func WithResumeCheckpoint ¶
func WithResumeCheckpoint(ctx context.Context, cp *Checkpoint) context.Context
WithResumeCheckpoint marks the run under ctx as a resume of cp: ExecEnv restores its state, re-enters at cp.TaskID, and feeds the checkpointed history verbatim into that task's first attempt.
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 ¶
WithRuntimeToolsAllowlist attaches a caller-supplied tools allowlist to ctx that is intersected with (never expands) each task's own allowlist.
func WithSuspendableToolCall ¶
WithSuspendableToolCall marks the current tool call as one the engine can suspend on. Set only at the model-batch execution site.
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 that MacroEnv expands {{var:name}} from.
Types ¶
type ApprovalPendingError ¶
type ApprovalPendingError struct {
// ApprovalID is the durable approval row's ID and the checkpoint key.
ApprovalID string
ToolName string
}
ApprovalPendingError is the HITL wrapper's third outcome beside allow and deny: the ask is durably recorded and unanswered, and this process is not the one that will wait for it — either it is shutting down, or the caller marked the run's asks detached (see WithDetachedAsks).
func (*ApprovalPendingError) Error ¶
func (e *ApprovalPendingError) Error() string
type AttentionAnswer ¶
AttentionAnswer is the text twin of an approval verdict: the operator's words, or Answered=false meaning the asking tool runs its blocker fallback.
func AttentionAnswerFromContext ¶
func AttentionAnswerFromContext(ctx context.Context, askID string) (ans AttentionAnswer, ok bool)
AttentionAnswerFromContext reports the pre-loaded answer for askID, ok=false when none was injected.
type AudioPart ¶ added in v0.40.0
type AudioPart struct {
// Data is the raw audio bytes. JSON encoding carries it as standard base64.
Data []byte `json:"data"`
// MimeType is the audio media type.
MimeType string `json:"mime_type" example:"audio/wav"`
}
AudioPart is a binary audio attachment on a Message, shaped exactly like ImagePart.
type BusInspector ¶
type BusInspector struct {
// contains filtered or unexported fields
}
func NewBusInspector ¶
func NewBusInspector(inner Inspector, bus libbus.Messenger, tracker libtracker.ActivityTracker) *BusInspector
func (*BusInspector) Start ¶
func (i *BusInspector) Start(ctx context.Context) StackTrace
type BusTaskEventSink ¶
type BusTaskEventSink struct {
// contains filtered or unexported fields
}
func NewBusTaskEventSink ¶
func NewBusTaskEventSink(bus libbus.Messenger) *BusTaskEventSink
func (*BusTaskEventSink) PublishTaskEvent ¶
func (s *BusTaskEventSink) PublishTaskEvent(ctx context.Context, event TaskEvent) error
func (*BusTaskEventSink) Wants ¶
func (s *BusTaskEventSink) Wants(TaskEventKind) bool
Wants accepts every kind while a bus is attached.
type CapturedPayloadSummary ¶
type CapturedPayloadSummary struct {
Truncated bool `json:"truncated"`
Reason string `json:"reason"`
OriginalType string `json:"originalType,omitempty"`
OriginalJSONBytes int `json:"originalJsonBytes,omitempty"`
SHA256 string `json:"sha256,omitempty"`
Preview string `json:"preview,omitempty"`
PreviewBytes int `json:"previewBytes,omitempty"`
}
CapturedPayloadSummary replaces oversized or non-JSON-marshallable payloads in persisted/streamed state; in-memory execution history keeps the originals.
type CapturedStateUnit ¶
type CapturedStateUnit struct {
// Scope is the unit's hierarchical address (chain + task), matching the address contract TaskEvent carries.
Scope EventScope `json:"scope,omitzero"`
TaskID string `json:"taskID" example:"validate_input"`
TaskHandler string `json:"taskHandler" example:"chat_completion"`
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"`
Error ErrorResponse `json:"error" openapi_include_type:"taskengine.ErrorResponse"`
Input any `json:"input,omitempty"`
Output any `json:"output,omitempty"`
InputVar string `json:"inputVar" example:"input"`
RetryIndex int `json:"retryIndex"`
Cancelled bool `json:"cancelled,omitempty"`
TimedOut bool `json:"timedOut,omitempty"`
ProviderType string `json:"providerType,omitempty"`
ModelName string `json:"modelName,omitempty"`
ToolNames []string `json:"toolNames,omitempty"`
TokenUsage *TokenUsage `json:"tokenUsage,omitempty"`
// FinishReason is the provider's verbatim finish reason for the model call this step captured, when the output was a chat history.
FinishReason string `json:"finishReason,omitempty"`
}
type ChainContext ¶
type ChainContext struct {
Tools map[string]ToolWithResolution
ClientTools []Tool
Debug bool
}
type ChainSuspendedError ¶
type ChainSuspendedError struct {
ApprovalID string
// Scope is the hierarchical address of the interrupt point.
Scope EventScope
}
ChainSuspendedError is ExecEnv's terminal for a suspended run: the checkpoint is persisted, and answering the approval resumes the chain.
func (*ChainSuspendedError) Error ¶
func (e *ChainSuspendedError) Error() string
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:"llama2:7b"`
// 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"`
// FinishReason is the provider's verbatim finish reason for the last model
// call ("length"-class means truncated); empty when none reported.
FinishReason string `json:"finishReason,omitempty" example:"stop"`
}
ChatHistory represents a conversation history with an LLM.
type Checkpoint ¶
type Checkpoint struct {
ApprovalID string
PendingCalls []PendingToolCall
// Chain is the full definition as executed, since a reference could dangle
// across a restart.
Chain *TaskChainDefinition
TaskID string
RetryIndex int
Scope EventScope
// Vars and VarTypes round-trip through the closed DataType enum.
Vars map[string]any
VarTypes map[string]DataType
EdgeCounts map[string]int
// History ends with the unanswered tool calls, the shape the tool-pairing
// repair path re-enters on.
History ChatHistory
TemplateVars map[string]string
ToolsAllowlist []string
HasToolsAllowlist bool
ContextLength int
SessionID string
MissionID string
RequestID string
ChainRef string
CreatedAt time.Time
}
Checkpoint is everything a suspended run needs to resume in any process. It is keyed by the one call awaiting a verdict; PendingCalls lists the batch's not-yet-started calls.
func UnmarshalCheckpoint ¶
func UnmarshalCheckpoint(raw []byte) (*Checkpoint, error)
UnmarshalCheckpoint decodes raw, migrating older schema versions forward. A version this binary cannot reach errors with ErrCheckpointVersion.
type CheckpointSaver ¶
type CheckpointSaver interface {
SaveCheckpoint(ctx context.Context, cp *Checkpoint) error
}
CheckpointSaver persists a suspension checkpoint. Save must be atomic per call: either the checkpoint is readable under its approval ID afterward, or the run fails instead of suspending.
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 ¶
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 EventScope ¶
type EventScope struct {
Chain string `json:"chain,omitempty"`
Task string `json:"task,omitempty"`
ToolCall string `json:"tool_call,omitempty"`
}
EventScope is the hierarchical address (chain/task/tool_call) of an event or captured state unit.
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 GateResult ¶ added in v0.38.0
GateResult is the durably recorded output of a resumed run's approved gate call, keeping the call exactly-once across partial resumes.
func RecordedGateResultFromContext ¶ added in v0.38.0
func RecordedGateResultFromContext(ctx context.Context, approvalID string) (GateResult, bool)
RecordedGateResultFromContext reports the recorded result for approvalID, ok=false when none was recorded on this run.
func UnmarshalGateResult ¶ added in v0.38.0
func UnmarshalGateResult(raw []byte) (GateResult, error)
UnmarshalGateResult decodes bytes MarshalGateResult produced, materializing the value through the closed DataType enum exactly as checkpoint vars do.
type GateResultRecorder ¶ added in v0.38.0
type GateResultRecorder func(ctx context.Context, approvalID string, result GateResult) error
GateResultRecorder persists the approved gate call's result under its approval ID before the resumed chain continues past it. Its failure fails the call.
func GateResultRecorderFromContext ¶ added in v0.38.0
func GateResultRecorderFromContext(ctx context.Context) GateResultRecorder
GateResultRecorderFromContext reports the installed recorder, nil when none.
type GateResultStore ¶ added in v0.38.0
type GateResultStore struct {
// contains filtered or unexported fields
}
GateResultStore is the mutable record/replay table a resumed run shares between its recorder and the HITL wrapper's replay lookup.
func NewGateResultStore ¶ added in v0.38.0
func NewGateResultStore() *GateResultStore
NewGateResultStore returns an empty store.
func (*GateResultStore) Get ¶ added in v0.38.0
func (s *GateResultStore) Get(approvalID string) (GateResult, bool)
Get reports the recorded result for approvalID, ok=false when none.
func (*GateResultStore) Set ¶ added in v0.38.0
func (s *GateResultStore) Set(approvalID string, r GateResult)
Set records approvalID's completed result for replay.
type HandlerOutputMode ¶
type HandlerOutputMode int
HandlerOutputMode names how a handler's success-output type derives from its input type.
const ( // HandlerOutputFixed: the handler always produces HandlerSignature.Output // on success, regardless of input type. HandlerOutputFixed HandlerOutputMode = iota // HandlerOutputPassthrough: the handler returns its input unchanged — // output type equals input type (noop, and route, whose product is the // transition label, not the data). HandlerOutputPassthrough // HandlerOutputDynamic: the output type is decided at runtime by the tool that // executes (the tools handler); the linter treats it as DataTypeAny unless the // task's OutputTemplate forces a rendered string. HandlerOutputDynamic // HandlerOutputNone: the handler never succeeds (raise_error); only its // on_failure edge can ever be taken, success branches are dead. HandlerOutputNone )
type HandlerSignature ¶
type HandlerSignature struct {
// Inputs is the closed set of DataTypes the handler accepts, in the order teaching
// errors name them; empty means every DataType is accepted.
Inputs []DataType
// Mode says how the success-output type derives from the input type.
Mode HandlerOutputMode
// Output is the produced type when Mode == HandlerOutputFixed.
Output DataType
// SuccessEvals is the closed transition-eval vocabulary the handler can emit on
// success — the only values a TransitionBranch can match; nil means the vocabulary
// is open and the linter cannot prove a branch dead.
SuccessEvals []string
}
HandlerSignature is the frozen I/O contract of one task handler.
func HandlerSignatureFor ¶
func HandlerSignatureFor(h TaskHandler) (HandlerSignature, bool)
HandlerSignatureFor returns the frozen contract for h; the bool is false for a handler the table does not know, which validateChain already rejects.
func (HandlerSignature) AcceptsInput ¶
func (s HandlerSignature) AcceptsInput(dt DataType) bool
AcceptsInput reports whether the handler's closed input set admits dt; DataTypeAny is never "admitted" here, callers must special-case it.
type ImagePart ¶
type ImagePart struct {
// Data is the raw image bytes. JSON encoding carries it as standard base64.
Data []byte `json:"data"`
// MimeType is the image media type.
MimeType string `json:"mime_type" example:"image/png"`
}
ImagePart is a binary image attachment on a Message.
type Inspector ¶
type Inspector interface {
Start(ctx context.Context) StackTrace
}
func NewSimpleInspector ¶
func NewSimpleInspector() Inspector
type KVInspector ¶
type KVInspector struct {
// contains filtered or unexported fields
}
func NewKVInspector ¶
func NewKVInspector(inner Inspector, kv libkv.KVManager, tracker libtracker.ActivityTracker) *KVInspector
func (*KVInspector) GetExecutionStateByRequestID ¶
func (i *KVInspector) GetExecutionStateByRequestID(ctx context.Context, reqID string) ([]CapturedStateUnit, error)
func (*KVInspector) GetStatefulRequests ¶
func (i *KVInspector) GetStatefulRequests(ctx context.Context) ([]string, error)
func (*KVInspector) Start ¶
func (i *KVInspector) Start(ctx context.Context) StackTrace
type KVJournalTaskEventSink ¶
type KVJournalTaskEventSink struct {
// contains filtered or unexported fields
}
KVJournalTaskEventSink journals task events durably per request ID into the KV store after forwarding them to the wrapped sink.
func NewKVJournalTaskEventSink ¶
func NewKVJournalTaskEventSink(inner TaskEventSink, kv libkv.KVManager, tracker libtracker.ActivityTracker) *KVJournalTaskEventSink
func (*KVJournalTaskEventSink) PublishTaskEvent ¶
func (s *KVJournalTaskEventSink) PublishTaskEvent(ctx context.Context, event TaskEvent) error
func (*KVJournalTaskEventSink) Wants ¶
func (s *KVJournalTaskEventSink) Wants(kind TaskEventKind) bool
Wants defers to the wrapped sink; with no inner sink it consumes every kind.
type LLMExecutionConfig ¶
type LLMExecutionConfig struct {
// Model is the primary model, placed first in the candidate list and used
// for token counting; Model plus Models form the full candidate set.
Model string `yaml:"model" json:"model" example:"llama2:7b"`
// Models is an additional candidate pool, considered alongside Model.
Models []string `yaml:"models,omitempty" json:"models,omitempty" example:"[\"gpt-4\", \"gpt-3.5-turbo\"]"`
// Provider is the primary provider, placed first in the candidate list;
// Providers supplies additional candidates.
Provider string `yaml:"provider,omitempty" json:"provider,omitempty" example:"ollama"`
Providers []string `yaml:"providers,omitempty" json:"providers,omitempty" example:"[\"ollama\", \"openai\"]"`
// Temperature is the sampling temperature; nil means unset (provider
// default for chat_completion, 0.0 for prompt/route).
Temperature *float32 `yaml:"temperature,omitempty" json:"temperature,omitempty" example:"0.7"`
// Tools is the allowlist of registry tool names this task may invoke
// ("*" exposes all, "*","!name" excludes name(s)); client-passed tools are
// governed separately by PassClientsTools.
Tools []string `yaml:"tools,omitempty" json:"tools,omitempty" example:"[\"local_shell\", \"nws\"]"`
// HideTools suppresses specific tools by (namespaced) name from BOTH the
// registry tools selected via Tools and the client-passed tools.
HideTools []string `yaml:"hide_tools,omitempty" json:"hide_tools,omitempty" example:"[\"tool1\", \"tools_name1.tool1\"]"`
// ToolsPolicies carries per-tools policy overrides for this task (tools
// name -> policy key -> value), injected into context before
// GetToolsForToolsByName.
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 controls reasoning mode (auto, off, minimal, low, medium, high,
// xhigh, or a boolean-style alias); empty uses the provider default.
Think string `yaml:"think,omitempty" json:"think,omitempty" example:"high"`
// MaxTokens caps the model's output tokens; unset sends no explicit cap
// and never falls back to the chain's TokenLimit, which bounds input+output.
MaxTokens *int `yaml:"max_tokens,omitempty" json:"max_tokens,omitempty" example:"8192"`
// MaxTokensTemplate stores a string max_tokens macro from chain JSON until
// MacroEnv expands it into MaxTokens.
MaxTokensTemplate string `yaml:"-" json:"-"`
// Shift allows the context window to slide on overflow instead of erroring.
Shift bool `yaml:"shift,omitempty" json:"shift,omitempty"`
// RetryPolicy wraps the chat/prompt call with classified retry and an
// optional model fallback; nil disables retry.
RetryPolicy *llmretry.RetryPolicy `yaml:"retry_policy,omitempty" json:"retry_policy,omitempty"`
}
LLMExecutionConfig represents configuration for executing tasks using Large Language Models (LLMs).
func (LLMExecutionConfig) MarshalJSON ¶
func (c LLMExecutionConfig) MarshalJSON() ([]byte, error)
func (*LLMExecutionConfig) UnmarshalJSON ¶
func (c *LLMExecutionConfig) UnmarshalJSON(data []byte) error
func (*LLMExecutionConfig) UnmarshalYAML ¶
func (c *LLMExecutionConfig) UnmarshalYAML(value *yaml.Node) error
type MacroEnv ¶
type MacroEnv struct {
// contains filtered or unexported fields
}
MacroEnv is a transparent decorator around EnvExecutor that expands macros (toolservice, var, date, now, chain) in task templates before execution.
type Message ¶
type Message struct {
// ID is not used by the engine; useful for tracking messages and diffing
// histories before storage.
ID string `json:"id" example:"msg_123456"`
Role string `json:"role" example:"user"`
Content string `json:"content,omitempty" example:"What is the capital of France?"`
// Images travel with Content to the model; image-bearing requests resolve
// only to vision-capable models.
Images []ImagePart `json:"images,omitempty" openapi_include_type:"taskengine.ImagePart"`
// Audio travels with Content to the model; audio-bearing requests resolve
// only to audio-capable models.
Audio []AudioPart `json:"audio,omitempty" openapi_include_type:"taskengine.AudioPart"`
// Thinking is the model's internal reasoning trace, populated only when
// thinking is enabled; never sent back to the model as history.
Thinking string `json:"thinking,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
CallTools []ToolCall `json:"callTools,omitempty"`
Timestamp time.Time `json:"timestamp" example:"2023-11-15T14:30:45Z"`
// RequestID and ChainRef are turn provenance (the run's X-Request-ID and
// the chain path that ran it), not used by the engine.
RequestID string `json:"requestId,omitempty"`
ChainRef string `json:"chainRef,omitempty"`
}
Message represents a single message in a chat conversation.
func SynthesizeHistory ¶
func SynthesizeHistory(prior []Message, units []CapturedStateUnit, chainErr error) []Message
SynthesizeHistory rebuilds a persisted-ready transcript from prior history and a chain run's captured step stream, including hard-failed turns and deduped by message identity.
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) PublishTaskEvent ¶
func (NoopTaskEventSink) PublishTaskEvent(context.Context, TaskEvent) error
func (NoopTaskEventSink) Wants ¶
func (NoopTaskEventSink) Wants(TaskEventKind) bool
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" OpDefault OperatorTerm = "default" // OpEdgeTraversedAtLeast fires when the edge in TransitionBranch.Edge has // been traversed at least the TransitionBranch.When threshold times in the // current chain run; reads engine state, not task output. OpEdgeTraversedAtLeast OperatorTerm = "edge_traversed_at_least" )
func ToOperatorTerm ¶
func ToOperatorTerm(s string) (OperatorTerm, error)
func (OperatorTerm) String ¶
func (t OperatorTerm) String() string
type PendingToolCall ¶
type PendingToolCall struct {
CallID string `json:"call_id"`
Name string `json:"name"`
Arguments string `json:"arguments"`
}
PendingToolCall records one model-requested tool call the suspended run has not answered yet, the awaiting-verdict call first.
type Prechecker ¶ added in v1.0.0
Prechecker refuses a call from static configuration alone, running and changing nothing; optional, a repo without it is gated unchanged. A repo that wraps another must forward it, or the inner refusal arrives only after the approval gate has already cost a human a decision.
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; safe for concurrent appenders.
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, executing chat completion, tools, route, raise_error, and noop tasks.
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, returning the trimmed response string.
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 execution to currentTask.Handler (chat_completion, execute_tool_calls, tools, route, raise_error, noop) and returns its output plus a transition-eval string (see TaskTransition).
type SimpleStackTrace ¶
type SimpleStackTrace struct {
// contains filtered or unexported fields
}
func (*SimpleStackTrace) GetExecutionHistory ¶
func (s *SimpleStackTrace) GetExecutionHistory() []CapturedStateUnit
func (*SimpleStackTrace) RecordStep ¶
func (s *SimpleStackTrace) RecordStep(step CapturedStateUnit)
type StackTrace ¶
type StackTrace interface {
RecordStep(step CapturedStateUnit)
GetExecutionHistory() []CapturedStateUnit
}
type TaskChainDefinition ¶
type TaskChainDefinition struct {
ID string `yaml:"id" json:"id" jsonschema:"required"`
// Debug enables capturing user input and output.
Debug bool `yaml:"debug" json:"debug"`
Description string `yaml:"description" json:"description"`
Tasks []TaskDefinition `yaml:"tasks" json:"tasks" openapi_include_type:"taskengine.TaskDefinition" jsonschema:"required,minItems=1"`
// 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, with branching logic, retry policies, and model preferences.
type TaskDefinition ¶
type TaskDefinition struct {
ID string `yaml:"id" json:"id" example:"validate_input" jsonschema:"required"`
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:"chat_completion" openapi_include_type:"string" jsonschema:"required"`
SystemInstruction string `` /* 158-byte string literal not displayed */
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, nil
// for all other types.
Tools *ToolsCall `yaml:"tools,omitempty" json:"tools,omitempty" openapi_include_type:"taskengine.ToolsCall"`
// Print optionally formats the output for display/logging, supporting
// template variables from previous task outputs.
Print string `yaml:"print,omitempty" json:"print,omitempty" example:"Validation result: {{.validate_input}}"`
// PromptTemplate, when set, overrides the resolved input as the prompt
// sent to the LLM.
PromptTemplate string `yaml:"prompt_template,omitempty" json:"prompt_template,omitempty" example:"Is this input valid? {{.input}}"`
// OutputTemplate, when set, renders a tools task's JSON output through
// this go template; the rendered string becomes the task's output.
OutputTemplate string `yaml:"output_template,omitempty" json:"output_template,omitempty" example:"Tools result: {{.status}}"`
// InputVar names the variable to use as this task's input; each task
// stores its own output in a variable named after its task id.
InputVar string `yaml:"input_var,omitempty" json:"input_var,omitempty" example:"input"`
// InputMaxBytes caps oversized string/chat-history inputs before this task runs.
InputMaxBytes int `yaml:"input_max_bytes,omitempty" json:"input_max_bytes,omitempty" example:"8192"`
// Transition defines what to do after this task completes.
Transition TaskTransition `yaml:"transition" json:"transition" openapi_include_type:"taskengine.TaskTransition"`
// Timeout is a Go duration string ("10s", "2m") bounding task execution.
Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty" example:"30s"`
// RetryOnFailure sets how many times to retry this task on failure (all
// task types); 0 means 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"`
// Scope is the event's hierarchical address (chain/task/tool-call); additive on the wire alongside the legacy flat fields below.
Scope EventScope `json:"scope,omitzero"`
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"`
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"`
HITLAction string `json:"hitl_action,omitempty"`
HITLReason string `json:"hitl_reason,omitempty"`
HITLPolicyName string `json:"hitl_policy_name,omitempty"`
HITLPolicyPath string `json:"hitl_policy_path,omitempty"`
HITLArgsSummary string `json:"hitl_args_summary,omitempty"`
HITLMatchedRule *int `json:"hitl_matched_rule,omitempty"`
HITLTimeoutS int `json:"hitl_timeout_s,omitempty"`
HITLApprovalRequested *bool `json:"hitl_approval_requested,omitempty"`
ToolDiffPath string `json:"tool_diff_path,omitempty"`
ToolDiffOldText string `json:"tool_diff_old_text,omitempty"`
ToolDiffNewText string `json:"tool_diff_new_text,omitempty"`
// For token_usage
TokenUsed int `json:"token_used,omitempty"`
TokenSize int `json:"token_size,omitempty"`
// step_stream_end bracket: ChunkCount counts step_chunk parcels seen, FinishReason is the provider's verbatim reason, Usage is provider-reported token usage.
ChunkCount int `json:"chunk_count,omitempty"`
FinishReason string `json:"finish_reason,omitempty"`
Usage *TokenUsage `json:"usage,omitempty"`
}
func GetJournaledEvents ¶
GetJournaledEvents returns the durably journaled events of a run in arrival order, or an empty slice if none exist.
func NewTaskEvent ¶
func NewTaskEvent(ctx context.Context, kind TaskEventKind) TaskEvent
NewTaskEvent builds an event of the given kind addressed from ctx (request ID, chain/task scope, and tool-call address when present).
type TaskEventKind ¶
type TaskEventKind string
const ( TaskEventChainStarted TaskEventKind = "chain_started" TaskEventStepStarted TaskEventKind = "step_started" TaskEventStepChunk TaskEventKind = "step_chunk" TaskEventStepStreamEnd TaskEventKind = "step_stream_end" TaskEventStepCompleted TaskEventKind = "step_completed" TaskEventStepFailed TaskEventKind = "step_failed" TaskEventChainCompleted TaskEventKind = "chain_completed" TaskEventChainFailed TaskEventKind = "chain_failed" // TaskEventChainSuspended terminates a run segment that left a recorded, unanswered approval behind rather than waiting for it; carries the interrupt address ({chain, task, tool_call}) and approval_id. TaskEventChainSuspended TaskEventKind = "chain_suspended" TaskEventApprovalRequested TaskEventKind = "approval_requested" TaskEventHITLDecision TaskEventKind = "hitl_decision" TaskEventToolCallPending TaskEventKind = "tool_call_pending" TaskEventToolCall TaskEventKind = "tool_call" TaskEventPrint TaskEventKind = "print" TaskEventTokenUsage TaskEventKind = "token_usage" )
func AllTaskEventKinds ¶
func AllTaskEventKinds() []TaskEventKind
AllTaskEventKinds enumerates every kind the engine can emit.
type TaskEventScope ¶
type TaskEventSink ¶
type TaskEventSink interface {
PublishTaskEvent(ctx context.Context, event TaskEvent) error
Wants(kind TaskEventKind) bool
}
TaskEventSink receives engine observation events; Wants gates whether events are built and published but must never select an execution path.
type TaskExecutor ¶
type TaskExecutor interface {
// TaskExec executes currentTask and returns its output, output type, and
// transition-eval string; ctxLength bounds token usage.
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 must handle every TaskHandler.
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 ( HandleRaiseError TaskHandler = "raise_error" HandleRoute TaskHandler = "route" 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 TokenUsage ¶
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 ToolsCall ¶
type ToolsCall struct {
// Name is the registered tools-PROVIDER (the service/server, e.g. "slack"),
// not the tool; required.
Name string `yaml:"name" json:"name" example:"slack"`
// ToolName is the specific TOOL to invoke on that provider
// (e.g. "send_slack_notification").
ToolName string `yaml:"tool_name" json:"tool_name" example:"send_slack_notification"`
// Args are key-value pairs passed to the tool call.
Args map[string]string `` /* 126-byte string literal not displayed */
}
ToolsCall configures a `tools` task: a direct, deterministic call to one tool of one registered tools-provider, distinct from the model-driven tool calls of chat_completion/execute_tool_calls.
type ToolsProvider ¶
type ToolsProvider interface {
ToolsRegistry
ToolsWithSchema
}
type ToolsRegistry ¶
type ToolsRepo ¶
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 ¶
type TransitionBranch ¶
type TransitionBranch struct {
// Operator defines how to compare the task's transition eval to When;
// required, must be one of SupportedOperators(), and is byte-exact and
// case-sensitive except for the `route` handler.
Operator OperatorTerm `yaml:"operator,omitempty" json:"operator,omitempty" example:"equals" openapi_include_type:"string"`
// When is the value this branch matches against the task's transition
// eval; its meaning depends on the handler (a control token, or the
// `route` handler's chosen label).
When string `yaml:"when" json:"when" example:"tool_call"`
// Goto specifies the target task ID if this branch is taken; empty or
// taskengine.TermEnd ends the chain.
Goto string `yaml:"goto" json:"goto" example:"positive_response"`
// Edge identifies a graph edge "fromTaskID->toTaskID" consulted by
// edge-state operators; required when Operator is one of those.
Edge string `yaml:"edge,omitempty" json:"edge,omitempty" example:"chat->run_tools"`
}
TransitionBranch defines a single possible path in the workflow, selected when the task's output matches the specified condition.
Source Files
¶
- chainlint.go
- checkpoint.go
- context.go
- converter.go
- errors.go
- events.go
- events_journal.go
- failurecontext.go
- handler_signatures.go
- input_cap.go
- inspector.go
- inspector_bus.go
- inspector_kv.go
- llmutil.go
- macroenv.go
- mockexec.go
- retry_outcome.go
- state_sanitize.go
- step_macros.go
- synthesizer.go
- taskengine.go
- taskenv.go
- taskenv_suspend.go
- taskexec.go
- tasktype.go
- toolpairing.go
- tools.go
- toolsctx.go