Documentation
¶
Index ¶
- Constants
- Variables
- func DecodeInput[T any](input map[string]any) (*T, error)
- func EncodeOutput[T any](v *T) (map[string]any, error)
- func Pause(payload map[string]any) error
- func ResolvePath(in *Input, path string) (any, bool)
- type APINodeConfig
- type AgentNodeConfig
- type AgentRunner
- type BaseNode
- type Compiled
- type ConditionalEdge
- type DelayNodeConfig
- type Dependencies
- type Descriptor
- type Edge
- type EdgeSpec
- type Graph
- func (g *Graph) AddConditionalEdge(src string, router Router, targets map[string]string) *Graph
- func (g *Graph) AddEdge(src, dst string) *Graph
- func (g *Graph) AddEdgeOnPort(src, port, dst string) *Graph
- func (g *Graph) AddNode(id string, node Node) *Graph
- func (g *Graph) Compile() (*Compiled, error)
- func (g *Graph) ID() string
- func (g *Graph) Invoke(ctx context.Context, in *Input, opts ...InvokeOption) (*Input, error)
- type HTTPConfig
- type HTTPHandler
- type HumanNodeConfig
- type IfElseNodeConfig
- type InProcessRuntime
- type Input
- type Invocation
- type InvokeOption
- type JavaScriptNodeConfig
- type MCPNodeConfig
- type Node
- func NewAPINode(id string, cfg APINodeConfig) (Node, error)
- func NewAgentNode(id string, cfg AgentNodeConfig) (Node, error)
- func NewDelayNode(id string, cfg DelayNodeConfig) (Node, error)
- func NewHumanNode(id string, cfg HumanNodeConfig) (Node, error)
- func NewIfElseNode(id string, cfg IfElseNodeConfig) (Node, error)
- func NewJavaScriptNode(id string, cfg JavaScriptNodeConfig) (Node, error)
- func NewMCPNode(id string, cfg MCPNodeConfig) (Node, error)
- func NewSwitchNode(id string, cfg SwitchNodeConfig) (Node, error)
- type NodeExecutor
- type NodeFactory
- type NodeSpec
- type NodeStatus
- type NodeType
- type PauseError
- type PauseState
- type Registry
- func (r *Registry) Execute(ctx context.Context, name string, in *Input, options ...InvokeOption) (*Input, error)
- func (r *Registry) Register(name string, compiled *Compiled, options ...InvokeOption) error
- func (r *Registry) Workflow(name string) (*Compiled, bool)
- func (r *Registry) WorkflowNames() []string
- type Result
- type Router
- type Runtime
- type RuntimeOptions
- type SwitchCase
- type SwitchNodeConfig
- type TemporalExecutor
- type TemporalExecutorOptions
- type Tool
- type Walker
Constants ¶
const ( StartNode = "START" EndNode = "END" )
StartNode and EndNode are reserved, implicit node IDs that bookend a workflow. Neither needs to be registered via AddNode.
const DefaultPort = "default"
DefaultPort is the conventional name for a node's primary output port.
Variables ¶
var ( ErrAlreadyRegistered = errors.New("workflow already registered") ErrWorkflowNotFound = errors.New("workflow not found") )
Functions ¶
func DecodeInput ¶
DecodeInput unmarshals the resolved input map into a typed struct via JSON round-tripping.
func EncodeOutput ¶
EncodeOutput marshals a typed output struct into the map[string]any wire format every Node returns.
Types ¶
type APINodeConfig ¶ added in v0.0.17
type APINodeConfig struct {
URL string `yaml:"url"`
Method string `yaml:"method"` // zero: GET
Headers map[string]string `yaml:"headers"`
Body any `yaml:"body"` // JSON value, optionally containing expressions
Timeout time.Duration `yaml:"timeout"` // zero: 30 seconds
HTTPClient *http.Client `yaml:"-"`
MaxResponseBytes int64 `yaml:"-"` // zero: 4 MiB
ExpressionTimeout time.Duration `yaml:"-"` // zero: one second
}
type AgentNodeConfig ¶ added in v0.0.17
type AgentNodeConfig struct {
Agent AgentRunner
Message string
Timeout time.Duration // expression timeout
}
type AgentRunner ¶ added in v0.0.17
type AgentRunner interface {
Run(context.Context, *agents.AgentInput) (*agents.AgentOutput, error)
}
AgentRunner is implemented by *agents.Agent. Run must honor cancellation.
type BaseNode ¶
type BaseNode struct {
NodeType NodeType
}
BaseNode is a convenience embedding that supplies Type().
type Compiled ¶
type Compiled struct {
Nodes map[string]Node
OutEdges map[string][]Edge
Conditionals map[string]ConditionalEdge
Roots []string
}
Compiled is a validated, prepared graph ready for execution. Read-only to Runtimes; mutable execution state lives on Input.
type ConditionalEdge ¶
ConditionalEdge attaches a runtime router to a node. Router returns a label the walker resolves against Targets to pick the next node.
type DelayNodeConfig ¶ added in v0.0.17
type Dependencies ¶ added in v0.0.17
type Dependencies struct {
Agents map[string]AgentRunner
MCPServers map[string]agents.MCPClient
HTTPClient *http.Client // nil: a client with a 30-second timeout
JavaScriptTimeout time.Duration // zero: one second per expression/code execution
MaxResponseBytes int64 // zero: 4 MiB per API response
}
Dependencies supplies trusted application resources. Descriptors refer to agents and MCP connectors by name; they never construct credentials or clients.
type Descriptor ¶ added in v0.0.17
type Descriptor struct {
Version int `yaml:"version"`
ID string `yaml:"id"`
Nodes []NodeSpec `yaml:"nodes"`
Edges []EdgeSpec `yaml:"edges"`
}
Descriptor is a versioned, declarative workflow graph.
func (Descriptor) Compile ¶ added in v0.0.17
func (d Descriptor) Compile(deps Dependencies) (*Compiled, error)
type Graph ¶
type Graph struct {
// contains filtered or unexported fields
}
Graph is a fluent builder for workflow graphs. Mutating methods return the graph for chaining. Builder-time errors are collected and surfaced as a joined error by Compile.
func (*Graph) AddConditionalEdge ¶
AddConditionalEdge registers a runtime router on src. A node may have either static edges or a conditional edge, not both. Targets must be known node ids or EndNode.
func (*Graph) AddEdge ¶
AddEdge wires src → dst on src's DefaultPort. Use AddEdgeOnPort for branching nodes.
func (*Graph) AddEdgeOnPort ¶
AddEdgeOnPort wires src's named output port to dst.
func (*Graph) AddNode ¶
AddNode installs node under id. id must be non-empty and unique within the graph.
type HTTPConfig ¶ added in v0.0.17
type HTTPConfig struct {
NamespaceResolver func(*http.Request) (string, error)
RunContextResolver func(*http.Request) (map[string]any, error)
MaxBodyBytes int64 // zero: 1 MiB
RunTTL time.Duration // zero: one hour after the latest execution finishes
MaxRuns int // zero: 1000; running executions are never evicted
}
HTTPConfig controls independently invoked workflows. NamespaceResolver must return the namespace authorized by the application; nil/empty uses "default". RunContextResolver supplies trusted context for MCP credentials/nested agents. Checkpoints are held by this handler instance, bounded by RunTTL and MaxRuns.
type HTTPHandler ¶ added in v0.0.17
type HTTPHandler struct {
// contains filtered or unexported fields
}
HTTPHandler exposes /workflows and /workflows/{name}/runs routes. It keeps checkpoints in memory; reuse one handler for all requests to those routes. Restarting the process loses runs. For durable persistence, use Registry.Execute with a persisted Input through an application-owned API.
func NewHTTPHandler ¶ added in v0.0.17
func NewHTTPHandler(registry *Registry, config HTTPConfig) *HTTPHandler
func (*HTTPHandler) ServeHTTP ¶ added in v0.0.17
func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
type HumanNodeConfig ¶ added in v0.0.17
type IfElseNodeConfig ¶ added in v0.0.17
type InProcessRuntime ¶
type InProcessRuntime struct{}
InProcessRuntime runs graphs through the shared Walker using a goroutine-per-node executor. Cancellation is cooperative: it cancels running nodes and waits for them to unwind before returning their shared Input. Nodes that ignore ctx can delay cancellation; goroutines cannot be killed.
func (InProcessRuntime) Execute ¶
func (InProcessRuntime) Execute(ctx context.Context, c *Compiled, in *Input, opts RuntimeOptions) (*Input, error)
Execute implements Runtime by delegating to the shared Walker with a goroutine-per-node executor.
type Input ¶
type Input struct {
RunID string `json:"run_id"`
RunContext map[string]any `json:"run_context,omitempty"`
Status map[string]NodeStatus `json:"status,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
// Pause is set by the walker when a node suspends the run. Nil
// means the run is not suspended. When set, the run stopped at
// Pause.NodeID and is awaiting an external decision.
Pause *PauseState `json:"pause,omitempty"`
// Suspended retains every paused node in a parallel wave, including private
// continuation data. Hosts may resolve one node at a time via SetResume.
Suspended map[string]*PauseState `json:"suspended,omitempty"`
// Ports records the output port each completed node emitted,
// keyed by node id. The walker uses it on resume to follow a
// completed node's outgoing edges without re-executing it.
Ports map[string]string `json:"ports,omitempty"`
// Resumes carries per-node resume decisions injected by the host
// (via SetResume) before a resume walk. A node reads its decision
// from the resolved input the runtime hands it; see SetResume.
Resumes map[string]map[string]any `json:"resumes,omitempty"`
}
Input is the run-level object a workflow invocation receives and accumulates into. RunContext is an opaque map the walker deep-merges node updates into; Status tracks per-node lifecycle markers; Metadata is a free-form host bag.
Pause/Ports/Resumes carry the state needed to suspend a run at a node and resume it later. The full Input is the run's durable memory: serialise it when a run pauses, restore it (with a resume decision injected via SetResume) to continue. On resume the walker re-walks from the roots but short-circuits any node already marked completed in Status — replaying its cached Ports entry instead of re-executing it — so resumes are idempotent and side-effect-free for already-finished nodes.
func (*Input) MergeContext ¶
MergeContext merges update into in.RunContext. Keys whose values are maps on both sides merge recursively (last writer wins at leaves); all other values replace.
func (*Input) SetPort ¶
SetPort records the output port nodeID emitted, so a resume walk can follow its edges without re-executing it.
func (*Input) SetResume ¶
SetResume stages a resume decision for nodeID. The host calls this after a pause — before re-running the workflow — to tell the previously suspended node how to proceed (e.g. {"decision": "approved"}). Setting a decision also clears any prior Pause so the run is no longer considered suspended.
func (*Input) SetStatus ¶
func (in *Input) SetStatus(nodeID string, s NodeStatus)
SetStatus records a node's lifecycle marker.
type Invocation ¶
Invocation is one unit of work the walker sends to the executor.
type InvokeOption ¶
type InvokeOption func(*invokeConfig)
InvokeOption configures a single Invoke call.
func WithLogger ¶
func WithLogger(l *slog.Logger) InvokeOption
WithLogger overrides the slog logger used during the run.
func WithMaxSteps ¶
func WithMaxSteps(n int) InvokeOption
WithMaxSteps caps how many node executions a single run may perform.
func WithRuntime ¶
func WithRuntime(rt Runtime) InvokeOption
WithRuntime selects the Runtime used for the invocation. Defaults to InProcessRuntime when unset.
type JavaScriptNodeConfig ¶ added in v0.0.17
type JavaScriptNodeConfig struct {
Code string `yaml:"code"`
Timeout time.Duration `yaml:"-"` // zero: one second
}
Node IDs must match their Graph.AddNode key. Configurations are copied at construction; supplied agents, connectors, and HTTP clients remain shared. Expression fields accept the same whole-scalar ${{ ... }} bindings as YAML.
type MCPNodeConfig ¶ added in v0.0.17
type Node ¶
type Node interface {
Type() NodeType
Validate() error
Execute(ctx context.Context, in *Input) (output map[string]any, port string, err error)
}
Node is the interface every workflow node implements. Validate runs at Compile time; Execute runs at run time and returns a partial RunContext update plus the port name edges should follow. Execute must honor ctx cancellation, pass ctx to blocking operations, and return promptly once cancelled. It must not mutate Input: return updates through output instead. Parallel nodes share the input for the current wave.
func NewAPINode ¶ added in v0.0.17
func NewAPINode(id string, cfg APINodeConfig) (Node, error)
NewAPINode constructs an HTTP API call node.
func NewAgentNode ¶ added in v0.0.17
func NewAgentNode(id string, cfg AgentNodeConfig) (Node, error)
NewAgentNode constructs a agent node using a directly supplied dependency.
func NewDelayNode ¶ added in v0.0.17
func NewDelayNode(id string, cfg DelayNodeConfig) (Node, error)
NewDelayNode constructs a delay node with the same behavior as YAML.
func NewHumanNode ¶ added in v0.0.17
func NewHumanNode(id string, cfg HumanNodeConfig) (Node, error)
NewHumanNode constructs an approval or form node with approved and rejected ports.
func NewIfElseNode ¶ added in v0.0.17
func NewIfElseNode(id string, cfg IfElseNodeConfig) (Node, error)
NewIfElseNode constructs a boolean branch with true and false ports.
func NewJavaScriptNode ¶ added in v0.0.17
func NewJavaScriptNode(id string, cfg JavaScriptNodeConfig) (Node, error)
NewJavaScriptNode constructs a synchronous JavaScript node.
func NewMCPNode ¶ added in v0.0.17
func NewMCPNode(id string, cfg MCPNodeConfig) (Node, error)
NewMCPNode constructs a mcp node using a directly supplied dependency.
func NewSwitchNode ¶ added in v0.0.17
func NewSwitchNode(id string, cfg SwitchNodeConfig) (Node, error)
NewSwitchNode constructs a switch node with the same behavior as YAML.
type NodeExecutor ¶
type NodeExecutor interface {
ExecuteWave(ctx context.Context, invocations []Invocation) []Result
}
NodeExecutor is the seam between the walker and a specific runtime. It must return one Result per Invocation in order and honour ctx cancellation.
type NodeFactory ¶
NodeFactory builds a Node. Host-side dependencies are captured in the closure.
type NodeStatus ¶
type NodeStatus string
NodeStatus tracks a node's lifecycle marker.
const ( NodeStatusRunning NodeStatus = "running" NodeStatusCancelled NodeStatus = "cancelled" NodeStatusCompleted NodeStatus = "completed" NodeStatusFailed NodeStatus = "failed" NodeStatusSkipped NodeStatus = "skipped" NodeStatusPaused NodeStatus = "paused" )
type PauseError ¶
PauseError is the sentinel a node's Execute returns to suspend the run instead of completing or failing. The walker catches it, records the node as paused, and returns the run as suspended (not failed) so an external decision can resume it later. Payload is an opaque, host-defined bag describing what the run is waiting on (e.g. an approval request's title and description); it is surfaced on Input.Pause for the caller to act on.
func IsPauseErr ¶
func IsPauseErr(err error) (*PauseError, bool)
IsPauseErr reports whether err is (or wraps) a *PauseError, returning it when so.
func (*PauseError) Error ¶
func (e *PauseError) Error() string
type PauseState ¶
type PauseState struct {
NodeID string `json:"node_id"`
Payload map[string]any `json:"payload,omitempty"`
}
PauseState marks where and why a run is suspended. Payload is the opaque bag the pausing node supplied (see PauseError).
type Registry ¶ added in v0.0.17
type Registry struct {
// contains filtered or unexported fields
}
Registry holds named, compiled workflows. Its zero value is ready to use. Registered graphs must not be mutated. Execution state belongs to the caller, so independent runs can execute concurrently and paused state can be persisted.
func NewRegistry ¶ added in v0.0.17
func NewRegistry() *Registry
func (*Registry) Execute ¶ added in v0.0.17
func (r *Registry) Execute(ctx context.Context, name string, in *Input, options ...InvokeOption) (*Input, error)
Execute invokes a workflow by name, using the options supplied at registration. Resume a paused run by calling Input.SetResume and passing that same state again. Callers must not execute the same Input concurrently.
func (*Registry) Register ¶ added in v0.0.17
func (r *Registry) Register(name string, compiled *Compiled, options ...InvokeOption) error
func (*Registry) WorkflowNames ¶ added in v0.0.17
type Result ¶
type Result struct {
NodeID string
Output map[string]any
Port string
Err error
// Pause, when non-nil, means the node suspended the run instead of
// completing. The walker records the node as paused, stamps
// Input.Pause, and stops the walk. Executors translate a node's
// PauseError into this field.
Pause *PauseState
}
Result is the outcome of one node execution. Output is the node's partial RunContext update.
type Router ¶
Router inspects the current Input after a node completes and returns a label the ConditionalEdge's target map resolves into the next node. Unknown labels (or labels mapped to EndNode) end the branch.
type Runtime ¶
type Runtime interface {
Execute(ctx context.Context, c *Compiled, in *Input, opts RuntimeOptions) (*Input, error)
}
Runtime executes a compiled workflow. Implementations must return the *Input even on error so callers can inspect partial state.
type RuntimeOptions ¶
RuntimeOptions carries run-level configuration into a Runtime call. A zero value picks defaults.
type SwitchCase ¶ added in v0.0.17
type SwitchNodeConfig ¶ added in v0.0.17
type SwitchNodeConfig struct {
Value any `yaml:"value"`
Cases []SwitchCase `yaml:"cases"`
Timeout time.Duration `yaml:"-"`
}
type TemporalExecutor ¶ added in v0.0.17
type TemporalExecutor struct {
// contains filtered or unexported fields
}
TemporalExecutor runs a graph as a Temporal workflow, dispatching nodes as activities. Dependencies stay on the worker; only node IDs and Input cross the activity boundary. Treat the compiled graph as immutable after construction. Conditional-edge routers run in workflow code and must be deterministic.
func NewTemporalExecutor ¶ added in v0.0.17
func NewTemporalExecutor(name string, graph *Compiled, options TemporalExecutorOptions) (*TemporalExecutor, error)
func (*TemporalExecutor) Execute ¶ added in v0.0.17
Execute may also be called inside a host Temporal workflow. A human pause returns a checkpoint; resume by passing that Input with SetResume into a new execution, or by calling Execute again after a host workflow receives a signal. Like any Temporal workflow, an error result does not deliver its return value through client.WorkflowRun.Get; a host workflow can capture partial state here.
func (*TemporalExecutor) Register ¶ added in v0.0.17
func (e *TemporalExecutor) Register(registry worker.Registry)
Register installs the workflow and its node activity on a worker before Start. The supplied name is the workflow type used with client.ExecuteWorkflow.
type TemporalExecutorOptions ¶ added in v0.0.17
type TemporalExecutorOptions struct {
ActivityOptions tworkflow.ActivityOptions
MaxSteps int
}
TemporalExecutorOptions configures node activities and the walker. Activity defaults are a five-minute start-to-close timeout, ten-second heartbeat timeout, and one attempt. Explicit retry policies require idempotent node side effects.
type Tool ¶ added in v0.0.17
Tool exposes a workflow through the agent tool/interrupt protocol. Mutable state is serialized into ToolCallResponse.StateUpdates, never kept on Tool.
func NewTool ¶ added in v0.0.17
func NewTool(name, description string, parameters map[string]any, compiled *Compiled, options ...InvokeOption) (*Tool, error)
NewTool wraps either a YAML-loaded workflow or a programmatically compiled graph. Parameters describes the JSON object exposed as RunContext["input"].
type Walker ¶
Walker drives wave-based graph execution: dedup, result merging, cycle-free visitation, and step-cap enforcement. The NodeExecutor plugs in per-runtime dispatch.
func NewWalker ¶
func NewWalker(opts RuntimeOptions) *Walker
NewWalker constructs a Walker using opts, filling in defaults for unset fields.
func (*Walker) Walk ¶
func (w *Walker) Walk(ctx context.Context, c *Compiled, in *Input, ne NodeExecutor) (out *Input, err error)
Walk executes the compiled graph through ne. It always returns the non-nil *Input, even on error, so observers can inspect partial state. Each Result.Output is deep-merged into in.RunContext; Status is recorded per node.