workflow

package
v0.0.31 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 28 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Workflows and agent tools

LoadYAML compiles a descriptor into the same Compiled graph used by the Go builder. Version 1 supports mcp, api, human, agent, if_else, switch, delay, and javascript nodes. YAML is trusted application configuration: API nodes can make HTTP requests, and JavaScript executes in the host process.

Build nodes in Go

All built-in nodes have public constructors returning (workflow.Node, error). The YAML loader calls these same constructors, so both paths share validation and execution behavior.

Constructor Configuration
NewMCPNode MCPNodeConfig
NewAPINode APINodeConfig
NewHumanNode HumanNodeConfig
NewAgentNode AgentNodeConfig
NewIfElseNode IfElseNodeConfig
NewSwitchNode SwitchNodeConfig
NewDelayNode DelayNodeConfig
NewJavaScriptNode JavaScriptNodeConfig
review, err := workflow.NewHumanNode("review", workflow.HumanNodeConfig{
    Message: "${{ 'Approve payment of ' + input.amount + ' USD?' }}",
})
if err != nil { return err }

compiled, err := workflow.NewGraph("payment").
    AddNode("review", review).
    AddEdge(workflow.StartNode, "review").
    AddEdgeOnPort("review", "approved", workflow.EndNode).
    AddEdgeOnPort("review", "rejected", workflow.EndNode).
    Compile()
if err != nil { return err }

The constructor's node ID must match its AddNode key. Graph compilation checks IDs and output ports. Built-ins can be mixed with your own Node implementations. Expressions and outputs work as described below for YAML.

Pass an agent directly through AgentNodeConfig.Agent, and an MCP connector through MCPNodeConfig.Server; Go callers do not need a named dependency map. Timing fields use time.Duration, such as DelayNodeConfig{Duration: time.Second}. JSON configuration values are copied at construction; injected agents, connectors, and HTTP clients remain shared application dependencies.

The compiled graph can be executed, registered, or wrapped as an agent tool using the APIs below. See the runnable Go example (go run ./examples/workflow/programmatic).

Load and execute

compiled, err := workflow.LoadYAML(descriptorBytes, workflow.Dependencies{
    Agents: map[string]workflow.AgentRunner{"researcher": researcher},
    MCPServers: map[string]agents.MCPClient{"github": githubConnector},
    HTTPClient: httpClient, // optional; configure transport/auth/network policy here
})
if err != nil { return err }

state, err := compiled.Execute(ctx, &workflow.Input{
    RunContext: map[string]any{
        "input": map[string]any{"query": "release notes"},
        "context": applicationRunContext, // optional; forwarded to agents/MCP credentials
    },
    Metadata: map[string]any{"namespace": "tenant-123"},
})

A missing run ID is generated once and retained in state. Metadata carries the trusted namespace, thread_id, and session_id; namespace defaults to default for direct executions. Each agent node gets an isolated child thread derived from the workflow run ID and node ID.

Register and invoke independently

Workflows can share the SDK registry with agents; neither an agent nor a model is needed to invoke a registered workflow. Agent and workflow names are separate.

registry := hastekit.NewRegistry()
if err := registry.RegisterWorkflow("review", compiled); err != nil { return err }

state, err := registry.RunWorkflow(ctx, "review", &workflow.Input{
    RunContext: map[string]any{"input": map[string]any{"amount": 150}},
})
// If state.Pause != nil, persist state, obtain a decision, call SetResume,
// then registry.RunWorkflow(ctx, "review", state) to continue.

RegisterWorkflow accepts optional workflow.InvokeOption values for runtime, logger and step limits. Duplicate names return hastekit.ErrWorkflowAlreadyRegistered. Workflow(name) and WorkflowNames() expose registered graphs. For applications using only pkg/workflow, workflow.NewRegistry() provides Register, Execute, Workflow, and WorkflowNames without the top-level SDK registry. The caller owns execution state and must not execute the same Input concurrently.

Execute nodes with Temporal

NewTemporalExecutor runs either a Go-built or YAML-compiled graph as a Temporal workflow. Register it on a Temporal worker with the same graph and dependencies on every worker polling that task queue:

executor, err := workflow.NewTemporalExecutor("review", compiled,
    workflow.TemporalExecutorOptions{
        ActivityOptions: temporalworkflow.ActivityOptions{
            StartToCloseTimeout: 2 * time.Minute,
        },
        MaxSteps: 500,
    })
if err != nil { return err }

w := worker.New(temporalClient, "reviews", worker.Options{})
executor.Register(w)
if err := w.Start(); err != nil { return err }
defer w.Stop()

run, err := temporalClient.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
    ID: invocationID, TaskQueue: "reviews",
}, "review", &workflow.Input{
    RunContext: map[string]any{"input": map[string]any{"amount": 150}},
})
if err != nil { return err }
var state workflow.Input
if err := run.Get(ctx, &state); err != nil { return err }

Here temporalworkflow aliases go.temporal.io/sdk/workflow; worker and client are the Temporal SDK packages. This entry point uses Temporal's workflow context, so it is separate from the ordinary WithRuntime invocation option.

Nodes execute as activities, with parallel dispatch within each wave and stable result merging. Node objects and their agent/MCP/HTTP dependencies stay on the worker; inputs, outputs, and pause checkpoints must be serializable by Temporal. Built-in delay nodes use durable Temporal timers and occupy no activity worker while waiting. Conditional-edge Go routers run in the workflow itself and must be deterministic and free of I/O. Keep the graph stable for existing histories; use a new workflow type/version when changing its topology or behavior.

Defaults are a five-minute activity timeout, ten-second heartbeat timeout, and one attempt. Supply ActivityOptions.RetryPolicy to enable retries, and make external side effects idempotent before doing so. Activities heartbeat to receive cancellation and must honor their context. A failing node cancels its wave's other pending activities/timers. Cancelling a client Get context only stops waiting: use temporalClient.CancelWorkflow to cancel the server-side execution.

A human pause completes this Temporal invocation with a checkpoint. Persist the returned Input, call SetResume, and start another invocation with a new Temporal workflow ID and the saved state; completed nodes are skipped. Alternatively, a host Temporal workflow can call executor.Execute(ctx, state), wait for a signal when it pauses, set the decision, and call it again. Register the executor on that worker in either case. No approval signal protocol is imposed by this API.

On failure, normal Temporal error semantics apply: WorkflowRun.Get returns the error rather than partial state. A host workflow calling executor.Execute directly can capture its returned partial Input before deciding how to report the failure. Activity history remains available for diagnostics. This does not make the separate HTTP handler's checkpoint store persistent.

See the Temporal example. Start temporal server start-dev, then run go run ./examples/workflow/temporal.

Independent HTTP invocation

handler := hastekit.NewWorkflowHTTPHandler(registry, workflow.HTTPConfig{
    // Resolve the namespace from your application's authenticated request.
    NamespaceResolver: resolveNamespace,
    // Optional trusted context for MCP credential providers and nested agents.
    RunContextResolver: resolveApplicationRunContext,
})
// handler can be served directly or mounted on /workflows and /workflows/.

The handler provides these routes:

Method Path Purpose
GET /workflows List registered workflow names
POST /workflows/{name}/runs Start a run with {"input": {...}}
GET /workflows/{name}/runs/{run_id} Read status, output or interrupts
POST /workflows/{name}/runs/{run_id}/resume Submit interrupt resolutions

Start and resume execute synchronously until completion, pause or failure. Disconnecting/cancelling the request cancels execution. Start returns HTTP 201, resume returns 200, and both include X-Workflow-Run-ID. A response contains run_id, workflow, status (running, paused, completed, or failed), and output or interrupts as appropriate. Runtime failures return 500 and are logged server-side. Unknown/foreign-namespace runs return 404; concurrent or completed resumes return 409.

curl -X POST localhost:8080/workflows/review/runs \
  -H 'Content-Type: application/json' \
  -d '{"input":{"amount":150}}'

# Use run_id and interrupts[0].function_call_message.call_id from the response.
curl -X POST localhost:8080/workflows/review/runs/RUN_ID/resume \
  -H 'Content-Type: application/json' \
  -d '{"resolutions":[{"call_id":"INTERRUPT_ID","action":"approve","content":{"note":"Reviewed"}}]}'

Checkpoint state stays server-side: clients cannot set node statuses, continuation state, namespace, or application run context. Requests are limited to 1 MiB by default. The handler validates resolution IDs, actions and form content before resuming; malformed decisions leave the run paused. A missing/empty namespace resolver uses default; applications are responsible for authentication.

HTTP runs are stored in memory on one handler instance. Reuse that instance; restarting it loses checkpoints. Runs expire one hour after the latest execution, and the handler holds at most 1000 runs by default (RunTTL, MaxRuns). Running executions are never evicted; when capacity is full, new starts return 503. This API adds no cross-process persistence or crash-safe execution. For durable storage, use the registry's Go API and persist the complete Input in your application. The embedded chat UI is unchanged.

Provide a workflow to an agent as a tool

workflowTool, err := workflow.NewTool(
    "research", "Research a topic using the configured workflow",
    map[string]any{
        "type": "object",
        "properties": map[string]any{"query": map[string]any{"type": "string"}},
        "required": []string{"query"},
    },
    compiled,
)
if err != nil { return err }

agent, err := hastekit.NewAgent(&hastekit.AgentConfig{
    Name: "assistant",
    LLM: model,
    Tools: []agents.Tool{workflowTool},
})

The same wrapper accepts a graph built with NewGraph(...).Compile(). Optional InvokeOption arguments select the runtime, logger and maximum steps. Tool arguments become RunContext.input; the parent agent's run context is available as RunContext.context. Namespace/session/thread identity comes from the calling agent, not model-supplied arguments. The completed tool result contains workflow state excluding the application context field.

When a node pauses, the tool returns an agent interrupt and saves a JSON checkpoint through StateUpdates. The existing agent and AG-UI approval/form flow can resume it; completed nodes are not re-executed. Checkpoints include private continuation data and should be stored with the same access controls as conversation history. Keep a workflow definition and its named dependencies stable while runs are paused. This does not add crash-safe exactly-once execution: external effects made before a checkpoint can repeat if the enclosing tool execution fails and is retried.

Descriptor and expressions

version: 1
id: lookup
nodes:
  - id: search
    type: mcp
    config:
      server: github
      tool: search_issues
      arguments:
        query: '${{ input.query }}'
  - id: summarize
    type: agent
    config:
      agent: researcher
      message: '${{ "Summarize: " + JSON.stringify(nodes.search) }}'
edges:
  - {from: START, to: search}
  - {from: search, to: summarize}
  - {from: summarize, to: END}

Each node has id, type, and config. Edges have from, to, and optional port (defaults to default). START and END are reserved. Without START edges, nodes without incoming edges are roots. Cycles, duplicate node IDs, unknown dependencies, unknown fields and invalid output ports are rejected. The existing walker executes in waves; it does not provide a barrier join for branches of unequal length. Design joins accordingly.

Outputs live under RunContext.nodes.<node-id>. A whole YAML scalar of the form ${{ expression }} evaluates JavaScript and preserves the resulting JSON type. Use JavaScript template literals to construct strings. Expressions can read input, nodes, context (the whole RunContext), and metadata. They evaluate against copies and cannot mutate shared workflow state.

Node configuration

Type Configuration Output ports
mcp server, tool, optional arguments object default
api url, optional method, headers, JSON body, timeout default
human message, optional JSON schema for a form approved, rejected
agent agent, message default
if_else condition: JavaScript expression returning a boolean true, false
switch value, cases: ordered {value, port} entries matching port or default
delay duration: Go duration such as 500ms or 2m default
javascript code: synchronous function body with return default

api resolves URL, headers and body expressions. It fails on non-2xx responses, limits response size to 4 MiB by default, and applies a 30-second request timeout. Its output is {status, headers, body}; JSON bodies are decoded, others are text. Use Dependencies.MaxResponseBytes and node timeout to adjust limits. An injected HTTP client can impose additional limits, endpoint restrictions and authentication.

mcp matches the model-facing tool name from the named connector's tool list, including any configured prefix. It honors tool approval requirements and saves MCP elicitation continuations across pauses. Background-task tool results are not supported. agent invokes Run(ctx, ...), propagates child interrupts, and resumes the same child thread with the saved previous run ID.

human pauses until a decision is supplied. For direct execution:

if state.Pause != nil {
    // Persist the full state and await the user's answer before continuing.
    state.SetResume(state.Pause.NodeID, map[string]any{
        "action": "approve", // or "reject"
        "content": map[string]any{"note": "Looks good"},
    })
    state, err = compiled.Execute(ctx, state)
}

Form content is validated against the configured JSON schema. For directly resumed MCP/agent nodes, the decision's messages field carries the ordinary agent interrupt-resolution messages. The tool wrapper constructs these automatically. Parallel pauses retain separate continuations and are presented one at a time.

# Examples of the remaining node configurations:
nodes:
  - id: request
    type: api
    config:
      url: https://example.com/api/items
      method: POST
      body: {name: '${{ input.name }}'}
      timeout: 10s
  - id: decide
    type: if_else
    config: {condition: 'nodes.request.body.count > 0'}
  - id: route
    type: switch
    config:
      value: '${{ input.priority }}'
      cases:
        - {value: high, port: urgent}
        - {value: low, port: routine}
  - id: wait
    type: delay
    config: {duration: 2s}
  - id: transform
    type: javascript
    config:
      code: |
        return {names: nodes.request.body.items.map(item => item.name)};

JavaScript uses Goja with a fresh VM, a bounded call stack, context cancellation, and a one-second execution timeout by default (Dependencies.JavaScriptTimeout). No Node.js, filesystem, network, timer, or module bindings are installed. Async results are rejected. This is not a process sandbox and does not impose a heap limit; use trusted scripts. Delays are cancellable in-process timers, not durable scheduled timers. The existing runtime interface remains available for custom execution policies.

Run the self-contained approval example with go run ./examples/workflow/yaml. It fetches a review limit from a local HTTP API, pauses for review when needed, and calls a local MCP record_approval tool on the approved branch. The example starts both demo servers automatically; no external services or credentials are needed.

To serve the same demo as an independent workflow API instead of auto-approving it:

go run ./examples/workflow/yaml -listen localhost:8080

The local API and MCP demo servers are still started automatically. The workflow is registered as review and pauses until a resolution arrives over HTTP.

Documentation

Index

Constants

View Source
const (
	StartNode = "START"
	EndNode   = "END"
)

StartNode and EndNode are reserved, implicit node IDs that bookend a workflow. Neither needs to be registered via AddNode.

View Source
const DefaultPort = "default"

DefaultPort is the conventional name for a node's primary output port.

Variables

View Source
var (
	ErrAlreadyRegistered = errors.New("workflow already registered")
	ErrWorkflowNotFound  = errors.New("workflow not found")
)

Functions

func DecodeInput

func DecodeInput[T any](input map[string]any) (*T, error)

DecodeInput unmarshals the resolved input map into a typed struct via JSON round-tripping.

func EncodeOutput

func EncodeOutput[T any](v *T) (map[string]any, error)

EncodeOutput marshals a typed output struct into the map[string]any wire format every Node returns.

func Pause

func Pause(payload map[string]any) error

Pause builds a *PauseError carrying payload. Nodes call this from Execute to suspend the run.

func ResolvePath

func ResolvePath(in *Input, path string) (any, bool)

ResolvePath walks a dotted path against in.RunContext.

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

func (*BaseNode) Type

func (b *BaseNode) Type() NodeType

Type returns the node's kind.

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.

func LoadYAML added in v0.0.17

func LoadYAML(data []byte, deps Dependencies) (*Compiled, error)

LoadYAML strictly decodes one document and compiles it using the existing graph engine. Unknown fields, missing dependencies and invalid graphs fail here.

func (*Compiled) Execute

func (c *Compiled) Execute(ctx context.Context, in *Input, opts ...InvokeOption) (*Input, error)

Execute runs the compiled graph. The Runtime defaults to InProcessRuntime when WithRuntime is not supplied.

type ConditionalEdge

type ConditionalEdge struct {
	Router  Router
	Targets map[string]string
}

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 DelayNodeConfig struct {
	Duration time.Duration `yaml:"duration"`
}

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 Edge

type Edge struct {
	FromNode string
	FromPort string
	ToNode   string
}

Edge connects two nodes on a named output port of the source.

type EdgeSpec added in v0.0.17

type EdgeSpec struct {
	From string `yaml:"from"`
	To   string `yaml:"to"`
	Port string `yaml:"port,omitempty"`
}

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 NewGraph

func NewGraph(id string) *Graph

NewGraph constructs an empty Graph with the given id.

func (*Graph) AddConditionalEdge

func (g *Graph) AddConditionalEdge(src string, router Router, targets map[string]string) *Graph

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

func (g *Graph) AddEdge(src, dst string) *Graph

AddEdge wires src → dst on src's DefaultPort. Use AddEdgeOnPort for branching nodes.

func (*Graph) AddEdgeOnPort

func (g *Graph) AddEdgeOnPort(src, port, dst string) *Graph

AddEdgeOnPort wires src's named output port to dst.

func (*Graph) AddNode

func (g *Graph) AddNode(id string, node Node) *Graph

AddNode installs node under id. id must be non-empty and unique within the graph.

func (*Graph) Compile

func (g *Graph) Compile() (*Compiled, error)

Compile validates the graph and produces a runnable *Compiled. Surfaces accumulated build-time errors plus empty-id, failed Validate, dangling edges, and cycles.

func (*Graph) ID

func (g *Graph) ID() string

ID returns the graph's identifier.

func (*Graph) Invoke

func (g *Graph) Invoke(ctx context.Context, in *Input, opts ...InvokeOption) (*Input, error)

Invoke compiles this graph and executes it. For repeated invocations, compile once and call Compiled.Execute directly.

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 HumanNodeConfig struct {
	Message string         `yaml:"message"`
	Schema  map[string]any `yaml:"schema"`
	Timeout time.Duration  `yaml:"-"` // expression timeout
}

type IfElseNodeConfig added in v0.0.17

type IfElseNodeConfig struct {
	Condition string        `yaml:"condition"` // JavaScript expression returning a boolean
	Timeout   time.Duration `yaml:"-"`
}

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

func (in *Input) MergeContext(update map[string]any)

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

func (in *Input) Resume(nodeID string) (map[string]any, bool)

Resume returns the staged resume decision for nodeID, if any.

func (*Input) SetPort

func (in *Input) SetPort(nodeID, port string)

SetPort records the output port nodeID emitted, so a resume walk can follow its edges without re-executing it.

func (*Input) SetResume

func (in *Input) SetResume(nodeID string, decision map[string]any)

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

type Invocation struct {
	Node   Node
	NodeID string
	Input  *Input
}

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 MCPNodeConfig struct {
	Server    agents.MCPClient
	Tool      string
	Arguments any           // JSON object or an expression returning one
	Timeout   time.Duration // expression timeout
}

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

type NodeFactory func() (Node, error)

NodeFactory builds a Node. Host-side dependencies are captured in the closure.

type NodeSpec added in v0.0.17

type NodeSpec struct {
	ID     string    `yaml:"id"`
	Type   NodeType  `yaml:"type"`
	Config yaml.Node `yaml:"config"`
}

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 NodeType

type NodeType string

NodeType identifies the kind of node in a workflow.

type PauseError

type PauseError struct {
	Payload map[string]any
}

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) Workflow added in v0.0.17

func (r *Registry) Workflow(name string) (*Compiled, bool)

func (*Registry) WorkflowNames added in v0.0.17

func (r *Registry) WorkflowNames() []string

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

type Router func(in *Input) string

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

type RuntimeOptions struct {
	Logger   *slog.Logger
	MaxSteps int
}

RuntimeOptions carries run-level configuration into a Runtime call. A zero value picks defaults.

type SwitchCase added in v0.0.17

type SwitchCase struct {
	Value any    `yaml:"value"` // literal JSON value to compare
	Port  string `yaml:"port"`
}

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

func (e *TemporalExecutor) Execute(ctx tworkflow.Context, in *Input) (*Input, error)

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

type Tool struct {
	*agents.BaseTool
	// contains filtered or unexported fields
}

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

func (*Tool) Execute added in v0.0.17

func (t *Tool) Execute(ctx context.Context, call *agents.ToolCall) (*agents.ToolCallResponse, error)

type Walker

type Walker struct {
	Logger   *slog.Logger
	MaxSteps int
}

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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