flow

package
v1.0.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: GPL-3.0 Imports: 31 Imported by: 0 modules, 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.

Documentation

Overview

Package flow provides the core data models and runtime for flow-based automation.

Package flow provides the core data models and runtime for flow-based automation.

Index

Constants

View Source
const (
	ChangeAdded   = "added"
	ChangeRemoved = "removed"
	ChangeChanged = "changed"
)

Changes of a node or field.

View Source
const (
	// AlertRiskRaised: the flow's risk (Risk) is higher than the base's.
	AlertRiskRaised = "risk_raised"
	// AlertPrivilegedNodeAdded: an enabled node is privileged (instance
	// risk) where the base had no enabled privileged node with its ID.
	AlertPrivilegedNodeAdded = "privileged_node_added"
	// AlertDestinationChanged: a Destination property was added, removed or
	// changed (on added and removed nodes too; enabling a node counts as
	// adding it, disabling one as removing it).
	AlertDestinationChanged = "destination_changed"
	// AlertDynamicDestination: a new or changed Destination value holds a
	// template other than {{secret.NAME}} references; or such an approved
	// value's node runs with something upstream of it changed (what feeds
	// it decides where it sends).
	AlertDynamicDestination = "dynamic_destination"
	// AlertNewHost: a host in a URL or host Destination value appears
	// nowhere in the base's (enabled nodes).
	AlertNewHost = "new_host"
	// AlertSecretAdded: a secret name is referenced that the base's
	// enabled nodes never reference.
	AlertSecretAdded = "secret_added"
	// AlertSecretMoved: a secret the base references is referenced at a
	// node and property where the base (an enabled node) did not.
	AlertSecretMoved = "secret_moved"
	// AlertRiskSwitchOn: a RiskSwitch property was turned on, or added on.
	AlertRiskSwitchOn = "risk_switch_on"
	// AlertSensitiveLiteral: a new or changed Sensitive value is a literal,
	// not a {{secret.NAME}} reference.
	AlertSensitiveLiteral = "sensitive_literal"
	// AlertCredentialedRequestChanged: on a node that uses a credential in
	// the base (a secret reference or a Sensitive value), an Operation
	// property changed (an HTTP method or body) or a connection into it was
	// added: the approved credential is used for something else.
	AlertCredentialedRequestChanged = "credentialed_request_changed"
	// AlertRateChanged: on a flow that reaches other services (its risk is
	// above safe), a Rate property of a running node was added, removed or
	// changed, or a running node with Rate properties was added or removed
	// (enabled or disabled): how often a trigger fires, or how many
	// messages a limiter lets through, changed. The direction is not
	// computed (a cron expression has none to compare).
	AlertRateChanged = "rate_changed"
)

Alert kinds, in the order alerts on one field are listed. They are stable: the low agent-deploy policy and the editor match on them.

View Source
const (
	// DryRunMaxNodes caps the nodes of a dry-run flow (disabled ones too).
	DryRunMaxNodes = 50
	// DryRunTimeout caps the wall-clock time of a dry-run.
	DryRunTimeout = 10 * time.Second
	// DryRunMaxExecutions caps the messages a dry-run routes (each is one
	// node execution), so its executions and the copies routing makes.
	DryRunMaxExecutions = 200
	// DryRunPreviewBytes caps each payload preview and error message.
	DryRunPreviewBytes = 2 << 10
	// DryRunMaxResultBytes caps the JSON of a whole result.
	DryRunMaxResultBytes = 64 << 10
	// DryRunMaxConnections caps the connections of a dry-run flow.
	DryRunMaxConnections = 4 * DryRunMaxNodes
	// DryRunMaxInputBytes caps the JSON of the payload, of each mock and of
	// the flow variables of a dry-run, and the input and config of a node
	// test.
	DryRunMaxInputBytes = 64 << 10
	// DryRunMaxValueBytes caps any single value a sandboxed node generates
	// (an output payload, a string an expression builds, a rendered
	// template).
	DryRunMaxValueBytes = 1 << 20
	// DryRunMaxDataBytes caps all the data a dry-run or node test generates:
	// the strings expressions build, rendered templates and every copy of a
	// routed message.
	DryRunMaxDataBytes = 32 << 20
)

Dry-run (docs/design/mcp.md §10): a flow runs once in a private runtime with every trigger and every node that is not safe replaced by a stub, and with isolated, empty secret and variable stores, so nothing it does leaves the sandbox. Limits:

View Source
const (
	LayoutNodeWidth  = 200
	LayoutNodeHeight = 80
	// LayoutColumnGap is the horizontal distance from a node to the next
	// column; LayoutRowGap the vertical distance between slots.
	LayoutColumnGap = 240
	LayoutRowGap    = 120
	// LayoutOrigin is where the first node of an empty canvas goes (x and y).
	LayoutOrigin = 100
	// MaxPosition bounds the coordinates of a node position an agent may
	// set (ApplyOps) or save (Lint): finite and within ±MaxPosition.
	MaxPosition = 1e6
)

Layout geometry, in canvas units. A node is drawn as a box of about LayoutNodeWidth × LayoutNodeHeight from its position (top-left).

View Source
const (
	// IssueEmptyNodeID: a node has no ID.
	IssueEmptyNodeID = "empty_node_id"
	// IssueDuplicateNodeID: two nodes share an ID.
	IssueDuplicateNodeID = "duplicate_node_id"
	// IssueNoTrigger: a non-empty flow has no enabled trigger.
	IssueNoTrigger = "no_trigger"
	// IssueDuplicateConnectionID: two connections share an ID.
	IssueDuplicateConnectionID = "duplicate_connection_id"
	// IssueConnectionUnknownNode: a connection names a node that does not exist.
	IssueConnectionUnknownNode = "connection_unknown_node"
	// IssueConnectionUnknownPort: a connection names a port its node lacks.
	IssueConnectionUnknownPort = "connection_unknown_port"
	// IssueSelfLoop: a connection connects a node to itself.
	IssueSelfLoop = "self_loop"
	// IssueCycle: the connections form a cycle.
	IssueCycle = "cycle"
	// IssueUnknownType: an enabled node's type is not registered.
	IssueUnknownType = "unknown_type"
	// IssueConfigType: a config value does not match its schema (type,
	// enum, bounds).
	IssueConfigType = "config_type"
	// IssueInvalidConfig: the node's factory or Validate rejected its
	// configuration.
	IssueInvalidConfig = "invalid_config"
	// IssueTriggerNotConnected: a callable trigger (trigger-tool) has no
	// active downstream connection.
	IssueTriggerNotConnected = "trigger_not_connected"
	// IssueInvalidPosition: a node position is not finite or not within
	// ±MaxPosition. Positions do not affect a run, so deploy does not check
	// them; Lint and ApplyOps do.
	IssueInvalidPosition = "invalid_position"
	// IssueUndefinedSecret: a setting that cannot work without its secrets
	// (node.SecretRequirer: a bot token, a notification URL, a DSN)
	// references a secret the store does not define. The message names the
	// secret, never a value. Unlike the other errors it depends on the
	// secret store, not on the definition: the admin may define the secret
	// later (see EnvironmentIssue).
	IssueUndefinedSecret = "undefined_secret"
	// IssueUndefinedConnection: a setting names a broker connection
	// (node.ConnectionRequirer, ADR-0026) the store does not define. Like
	// IssueUndefinedSecret it depends on the environment.
	IssueUndefinedConnection = "undefined_connection"
	// IssueUndefinedLLMConnection: a setting names an LLM connection
	// (node.LLMConnectionRequirer, ADR-0038) the store does not define. Like
	// IssueUndefinedConnection it depends on the environment.
	IssueUndefinedLLMConnection = "undefined_llm_connection"
	// IssueUnresolvedSecret (warning): a setting that resolves secrets but
	// works without them (node.SecretReferencer: an MQTT or SMTP username
	// or password, an HTTP request's URL or headers) references a secret
	// the store does not define. The flow deploys; when the node runs the
	// reference becomes an empty value (an optional credential) or fails
	// the request (HTTP). Like IssueUndefinedSecret it depends on the
	// environment, and the message names the secret, never a value.
	IssueUnresolvedSecret = "unresolved_secret"
)

Issue codes of the structural, registry and config checks. The tool risk rules have their own codes (risk.go). Codes are stable: agents and the editor match on them.

View Source
const (
	DataTypeAny     = types.DataTypeAny
	DataTypeString  = types.DataTypeString
	DataTypeNumber  = types.DataTypeNumber
	DataTypeBoolean = types.DataTypeBoolean
	DataTypeObject  = types.DataTypeObject
	DataTypeArray   = types.DataTypeArray

	NodeCategoryInput      = types.NodeCategoryInput
	NodeCategoryProcessing = types.NodeCategoryProcessing
	NodeCategoryOutput     = types.NodeCategoryOutput

	// ErrorPort is the output every node that processes messages has
	// besides its declared ones: its failures leave through it (ADR-0036).
	ErrorPort = types.ErrorPort
)

Re-export constants for backward compatibility.

View Source
const (
	OpAddNode    = "add_node"
	OpUpdateNode = "update_node"
	OpRemoveNode = "remove_node"
	OpConnect    = "connect"
	OpDisconnect = "disconnect"
)

Op kinds.

View Source
const (
	// IssueTooManyOps: more than MaxOps operations.
	IssueTooManyOps = "too_many_ops"
	// IssueUnknownOp: the op field names no operation.
	IssueUnknownOp = "unknown_op"
	// IssueInvalidOp: a required field is missing, or the fields conflict.
	IssueInvalidOp = "invalid_op"
	// IssueInvalidNodeID: a node ID given to add_node is not 1-64 letters,
	// digits, '-' or '_'.
	IssueInvalidNodeID = "invalid_node_id"
	// IssueNodeExists: add_node with the ID of an existing node.
	IssueNodeExists = "node_exists"
	// IssueNodeNotFound: an operation names a node that does not exist.
	IssueNodeNotFound = "node_not_found"
	// IssueConnectionExists: connect with the endpoints of an existing
	// connection.
	IssueConnectionExists = "connection_exists"
	// IssueConnectionNotFound: disconnect matches no connection.
	IssueConnectionNotFound = "connection_not_found"
)

Issue codes of ApplyOps (path "/ops/{index}", or "/ops" for the batch).

View Source
const (
	// IssueDynamicDestinationCredentials: a node whose destination comes
	// from message data or variables also carries static credentials
	// (headers, URL userinfo or secrets, a password), which an agent could
	// then send anywhere.
	IssueDynamicDestinationCredentials = "dynamic_destination_credentials"
	// IssueToolGlobalVariable: a set-var reachable from a tool writes a
	// global variable, which other flows read (their URLs, commands, …).
	IssueToolGlobalVariable = "tool_global_variable"
	// IssueToolAggregate: process-aggregate reachable from a tool would
	// batch the arguments of different calls together.
	IssueToolAggregate = "tool_stateful_aggregate"
	// IssueToolJoinKey: process-join reachable from a tool must be keyed by
	// meta.correlationID, or it would join different calls.
	IssueToolJoinKey = "tool_stateful_join"
	// IssueToolDelayExceedsTimeout (warning): a process-delay reachable from
	// a tool waits longer than the tool's timeout, so calls report running.
	IssueToolDelayExceedsTimeout = "tool_delay_exceeds_timeout"
	// IssueToolStrictArguments: an argument of a privileged tool is not
	// strict (toolschema.Schema.RequireStrictFor).
	IssueToolStrictArguments = "tool_strict_arguments"
	// IssueToolNoSchema: a tool node provides no input schema (a node bug).
	IssueToolNoSchema = "tool_no_schema"
)

Issue codes of the tool risk analysis.

View Source
const (
	DefaultSendTimeout  = 5 * time.Second
	DefaultOutputBuffer = 1000
)

Default router configuration values.

View Source
const (
	DefaultMaxRetries  = 3
	DefaultInitialWait = 100 * time.Millisecond
	DefaultMaxWait     = 5 * time.Second
	DefaultMultiplier  = 2.0
)

Default retry configuration values.

View Source
const (
	// DefaultMaxConcurrency bounds how many nodes execute simultaneously per flow.
	DefaultMaxConcurrency = 16
	// DefaultExecBuffer is the buffer size of the trigger seed channels.
	DefaultExecBuffer = 256
	// DefaultStopTimeout bounds how long Stop waits for the flow's goroutines.
	DefaultStopTimeout = 5 * time.Second
	// DefaultNodeQueueLimit caps how many messages may wait for one node. A
	// node whose backlog is full has further messages dropped (with a warning
	// and a dropped-message metric) instead of stalling the rest of the flow.
	DefaultNodeQueueLimit = 1000
)

Default concurrency configuration for node execution.

View Source
const (
	NodePhaseRunning = "running"
	NodePhaseSuccess = "success"
	NodePhaseError   = "error"
	// NodePhaseRunFinished is a run-level (not node-level) event emitted once, when
	// all in-flight work for a correlation ID drains. NodeID is empty; only FlowID
	// and CorrID are set. It lets the recorder finalize a run deterministically
	// instead of guessing via an idle timeout.
	NodePhaseRunFinished = "run-finished"
)

Node execution phases reported by a NodeEventHook. The string values match the events package phases so a recorder can forward them without translation.

View Source
const (
	// DefaultCallTimeout is used when CallRequest.Timeout is not positive.
	DefaultCallTimeout = 10 * time.Second
	// DefaultCallExpiryGrace is added to a call's timeout to get the hard
	// lifetime of its waiter: once it passes, an unfinished call reports
	// "expired" and its result is forgotten.
	DefaultCallExpiryGrace = 10 * time.Minute
	// DefaultMaxCallWaiters caps how many called runs a runtime tracks at once
	// (runs still executing plus results not collected yet).
	DefaultMaxCallWaiters = 64
	// DefaultMaxCallResultBytes caps the serialized payload of a reply. It is
	// well above what the service layer passes on to agents (max_result_bytes),
	// so the service can still truncate and flag; it bounds what a runtime
	// holds: DefaultMaxCallWaiters * DefaultMaxCallResultBytes = 16 MiB.
	DefaultMaxCallResultBytes = 256 << 10
)

Defaults for synchronous calls.

View Source
const AlertDataReadChanged = "data_read_changed"

AlertDataReadChanged: a running node that was added, enabled, retyped or reconfigured, or that gained an input, reads what agents may not read: variables (global or flow; $env holds them), message metadata (where the nodes before it record their settings: an HTTP URL, an expression, a topic), or what a node that uses a credential or reads variables produced (it runs downstream of one, through connections or flow variables), or the failures of a node, which leave its error port quoting its settings (ADR-0036). Runs of a flow are visible to agents (pw_list_runs, pw_get_run): such a node could hand that data back through an error it raises on purpose, or through which nodes run. One alert per node.

View Source
const AlertGlobalVariableRead = "global_variable_read"

AlertGlobalVariableRead: what a running tool's path reads from global variables goes back to the agent that calls it, and that path changed and reads global variables. The path is the running part of the flow its trigger reaches (through connections and flow variables) together with everything that feeds it (a join or an aggregate emits the call's message with what another branch sent); it changed when a node of it was added, enabled or reconfigured, or a connection into one was added.

View Source
const AlertGlobalVariableWrite = "global_variable_write"

AlertGlobalVariableWrite: a running set-var writes a global variable (its scope is not "flow"; an absent scope means global), which other flows read for their URLs, commands and conditions, and what it writes may have changed: the set-var was added or enabled, or its scope, key or value changed; or something upstream of it changed: a running node that feeds it (through connections, or through the flow variables a node feeding it reads) was added, enabled or reconfigured, or a connection into that part was added.

View Source
const AlertToolPathChanged = "tool_path_changed"

AlertToolPathChanged: what a running tool runs changed. A tool's path is the running part of the flow its trigger reaches (through connections and flow variables) together with everything that feeds that part; it changed when a node of it was added, enabled, retyped or reconfigured, a node left it, or a connection into it was added or removed, compared with the base's path of the same trigger (a trigger new or enabled here has no base path). A published tool is the admin's: wiring a confirm:none tool to the action behind a confirm:admin tool would run that action without the admin's approval, while the tool's name, grant and fingerprint stay the same. One alert per tool.

View Source
const HiddenValue = "<hidden>"

HiddenValue replaces the value of a Sensitive property in a diff.

View Source
const IssueHiddenSettings = "hidden_settings"

IssueHiddenSettings (warning, at /nodes/{nodeId}): a dry-run stubbed the node because the values DryRunInput.Redact hid make its settings invalid (an expression, an object-typed setting). It does not run; a mock gives its output.

View Source
const MaxOps = 200

MaxOps bounds the operations of one ApplyOps call.

View Source
const OpNodeIDPattern = `^[A-Za-z0-9_-]{1,64}$`

OpNodeIDPattern is the syntax of the node IDs an operation may choose: they appear in paths (/nodes/{id}) and URLs. The MCP endpoint advertises and checks it as it is.

View Source
const TestNodeTimeout = 5 * time.Second

TestNodeTimeout caps one node test.

Variables

View Source
var (
	// ErrDryRunInput marks a dry-run or node test refused because of what it
	// was asked (not because the flow is invalid): an unknown or unsuitable
	// trigger, a mock for a node that is not stubbed, a flow over the node or
	// connection caps or with duplicate connections, inputs over
	// DryRunMaxInputBytes.
	ErrDryRunInput = errors.New("invalid dry-run input")
	// ErrSandboxBusy (wraps ErrBusy): another dry-run or node test is
	// running. One runs at a time, process-wide.
	ErrSandboxBusy error = &busyError{"another dry-run or node test is in progress"}
)
View Source
var (
	// ErrNoTriggerNodes indicates a flow has no trigger/input nodes.
	ErrNoTriggerNodes = errors.New("flow must have at least one trigger node")

	// ErrFlowNotFound indicates the requested flow does not exist.
	ErrFlowNotFound = errors.New("flow not found")

	// ErrFlowAlreadyRunning indicates an attempt to start an already running flow.
	ErrFlowAlreadyRunning = errors.New("flow is already running")

	// ErrFlowNotRunning indicates an attempt to stop a flow that isn't running.
	ErrFlowNotRunning = node.ErrNotRunning

	// ErrNodeNotFound indicates the requested node does not exist.
	ErrNodeNotFound = errors.New("node not found")

	// ErrInvalidNodeType indicates an unregistered node type was referenced.
	ErrInvalidNodeType = errors.New("invalid node type")

	// ErrInvalidConnection indicates a connection configuration is invalid.
	ErrInvalidConnection = errors.New("invalid connection")

	// ErrRuntimeStopped indicates the runtime has been stopped.
	ErrRuntimeStopped = errors.New("runtime has been stopped")

	// ErrFlowStillStopping indicates a previous instance of the flow timed out
	// while stopping and still has goroutines executing; deploying again now
	// would run two instances side by side.
	ErrFlowStillStopping = errors.New("previous instance of the flow is still stopping")

	// ErrInvalidNodeConfig marks a node whose factory or Validate rejected its
	// configuration: the flow is invalid (HTTP 400, ADR-0006).
	ErrInvalidNodeConfig = errors.New("invalid node configuration")

	// ErrResourceConflict is node.ErrResourceConflict: a trigger could not
	// start because an exclusive resource is taken (HTTP 409, ADR-0006).
	ErrResourceConflict = node.ErrResourceConflict
)

Common errors for flow operations.

View Source
var (
	// ErrBusy is wrapped by every refusal that means "busy, retry later"
	// (ErrTooManyCalls, ErrTriggerBusy): callers map them with one errors.Is.
	ErrBusy = errors.New("busy")
	// ErrTriggerNotCallable: the trigger does not implement node.Emitter.
	ErrTriggerNotCallable = errors.New("trigger cannot be called synchronously")
	// ErrNoActiveTargets: the trigger has no connection to an enabled node, so
	// a run started from it could never do anything (or finish).
	ErrNoActiveTargets = errors.New("trigger has no active downstream connection")
	// ErrTooManyCalls (wraps ErrBusy): the runtime already tracks its maximum
	// of called runs and none of them is a finished result that could make
	// room.
	ErrTooManyCalls error = &busyError{"too many calls in progress"}
	// ErrTriggerBusy (wraps ErrBusy): the trigger did not accept the call
	// within its timeout (its output stayed full).
	ErrTriggerBusy error = &busyError{"trigger is busy"}
)

Errors returned by Call before a run is started.

View Source
var ErrTestNodeForbidden = errors.New("only safe processing nodes can be tested")

ErrTestNodeForbidden: only processing nodes whose type and instance risk are safe can be tested (the service maps it to forbidden).

View Source
var NewMessage = types.NewMessage

NewMessage is a convenience wrapper around types.NewMessage.

Functions

func AnalyzeTools

func AnalyzeTools(f *Flow, reg *node.Registry, specs map[string]node.ToolSpec) ([]ToolInfo, []Issue)

AnalyzeTools computes the ToolInfo of every enabled node of f listed in specs (keyed by node ID: the ToolSpec of each instantiated tool trigger) and returns every issue found, located by deploy's paths ("nodes[2].config.url") and sorted by path. Error issues must fail the deploy; issueError builds that error. Disabled nodes and connections touching them are ignored, as at runtime. Lint reports the same issues with its own paths.

func ApplyOps

func ApplyOps(base *Flow, ops []Op, reg *node.Registry) (*Flow, []Issue)

ApplyOps applies ops in order to a copy of base (nil: an empty flow) and returns it, with the nodes added without a position placed by AutoLayout. base is never modified. Every failing operation is reported (path "/ops/{index}"; later operations see the effect of the earlier ones that succeeded); any issue means no flow is returned. More than MaxOps operations is a single issue at "/ops". ApplyOps checks the operations only: Lint checks the resulting flow.

func AutoLayout

func AutoLayout(f *Flow, newNodeIDs []string)

AutoLayout positions the nodes listed in newNodeIDs that have no position (the zero position counts as none; listed nodes with a position, unknown IDs and unlisted nodes are left alone). Each goes LayoutColumnGap to the right of its rightmost upstream node that has a position (at that node's height), or, without one, into a new column right of every other node (at the top of the canvas), then down in LayoutRowGap steps to the first slot whose box overlaps no other node. Listed nodes are placed upstream first, otherwise in definition order, so the result is deterministic.

func EnvironmentIssue

func EnvironmentIssue(i Issue) bool

EnvironmentIssue reports whether an issue depends on the environment the flow is checked in (the secrets, broker and LLM connections defined) rather than on its definition: such an error still blocks a deploy, but not a dry-run (whose stores are empty by design) or the storing of a draft (the admin may define the secret or connection before approving it).

func InstanceRisk

func InstanceRisk(n *Node, reg *node.Registry) node.Risk

InstanceRisk returns the risk of one node: its type's declared risk, raised by the instance rules of the tool analysis (a dynamic destination or allowPrivate on HTTP and notify nodes, MQTT and files as shared state). An unregistered type, or one without a declared risk, is privileged. The dry-run uses it to decide which nodes it stubs.

func IsSecretReference

func IsSecretReference(s string) bool

IsSecretReference reports whether s is exactly one {{secret.NAME}} reference (whitespace inside the braces allowed).

func Risk

func Risk(f *Flow, reg *node.Registry) node.Risk

Risk returns the highest instance risk over the enabled nodes of f (safe for an empty or nil flow): each node's type risk, escalated to privileged by the same instance rules the tool risk analysis applies (instanceRisk).

func RiskCanRise

func RiskCanRise(info node.NodeTypeInfo) bool

RiskCanRise reports whether a setting can raise an instance of the type info describes above the type's risk, by instanceRisk's rules: a RiskSwitch property, or a destination that instanceRisk escalates when it is built from the message (the URL of HTTP Request and Notify, the broker of MQTT Publish, dynamicDestinationProp). A privileged type cannot rise. The editor says so in a node's settings (GET /api/node-types riskCanRise).

func ValidPosition

func ValidPosition(p Position) bool

ValidPosition reports whether p is finite and within ±MaxPosition on both axes.

Types

type Alert

type Alert struct {
	Kind    string `json:"kind"`
	NodeID  string `json:"nodeId,omitempty"`
	Path    string `json:"path,omitempty"`
	Message string `json:"message"`
	Before  any    `json:"before,omitempty"`
	After   any    `json:"after,omitempty"`
}

Alert is one change the approval page and the low agent-deploy policy flag. NodeID and Path ("config.<prop>") are empty for flow-level alerts (Path also for a new input of credentialed_request_changed). Alerts are agent-safe: Before and After hold a property's values only when agents may read it (AgentVisible and not Sensitive, the read views' rule), risks for risk_raised, the host for new_host, the secret name for the secret alerts and booleans for risk_switch_on; otherwise they are absent (the editor's field diffs have the values).

type Annotations

type Annotations struct {
	ReadOnlyHint    bool `json:"readOnlyHint"`
	DestructiveHint bool `json:"destructiveHint"`
	IdempotentHint  bool `json:"idempotentHint"`
	OpenWorldHint   bool `json:"openWorldHint"`
}

Annotations are the MCP tool hints PiWorker computes for a tool. They are always explicit (never omitted) and never lowered by the admin, except IdempotentHint, which is the admin's flag.

type CallError

type CallError struct {
	NodeID   string `json:"nodeId,omitempty"`
	NodeType string `json:"nodeType,omitempty"`
	Message  string `json:"message"`
}

CallError describes the first node error of a called run (or why the call was cancelled). Messages are raw node errors: callers redact them before showing them to agents.

type CallRequest

type CallRequest struct {
	TriggerNodeID string
	Args          map[string]any // already validated
	Actor         string         // "token:<name>", "editor", …
	Timeout       time.Duration
	// Waiting are the flows whose agent nodes wait for this call (an agent
	// node's call: its own flow and the flows waiting for the run it
	// serves). While the caller waits, the run's nodes read them
	// (node.WaitingFlows), so an agent node of the run never calls a tool
	// of a flow that waits for it.
	Waiting []string
}

CallRequest starts a run on a callable trigger (see node.Emitter).

type CallResult

type CallResult struct {
	Status     CallStatus      `json:"status"`
	RunID      string          `json:"runId"`
	Result     json.RawMessage `json:"result,omitempty"` // deep-copied, serialized
	Error      *CallError      `json:"error,omitempty"`
	DurationMs int64           `json:"durationMs"`
}

CallResult is the result of a synchronous call.

type CallStatus

type CallStatus string

CallStatus is the outcome of a synchronous call (FlowRuntime.Call / Wait).

const (
	CallStatusCompleted        CallStatus = "completed"
	CallStatusCompletedNoReply CallStatus = "completed_no_reply"
	CallStatusError            CallStatus = "error"
	CallStatusRunning          CallStatus = "running"
	CallStatusExpired          CallStatus = "expired"
	CallStatusApprovalRequired CallStatus = "approval_required"
	CallStatusRejected         CallStatus = "rejected"
)

Call statuses. approval_required and rejected are produced by the service layer (confirm: admin), never by the runtime itself.

type Connection

type Connection struct {
	ID         string `json:"id"`
	SourceNode string `json:"sourceNode"` // ID of the source node
	SourcePort string `json:"sourcePort"` // ID of the source port
	TargetNode string `json:"targetNode"` // ID of the target node
	TargetPort string `json:"targetPort"` // ID of the target port
}

Connection represents a link between two nodes.

func NewConnection

func NewConnection(sourceNode, sourcePort, targetNode, targetPort string) *Connection

NewConnection creates a new Connection with a generated UUID.

type ConnectionsDiff

type ConnectionsDiff struct {
	Added   []Connection `json:"added"`
	Removed []Connection `json:"removed"`
}

ConnectionsDiff lists the connections added and removed, compared by their endpoints (IDs may differ).

type DataType

type DataType = types.DataType

Type aliases for backward compatibility and convenience. These allow using flow.DataType, flow.NodeCategory, etc. without breaking existing code.

type DeployWarning

type DeployWarning struct {
	Issue
	Secret string `json:"secret,omitempty"`
}

DeployWarning is a warning a deploy went ahead with: the Issue as Lint renders it and, for an undefined secret (IssueUnresolvedSecret), the secret's name, so the editor need not read it out of the message. Only the editor's deploy response carries it: an agent sees Issues, whose messages are withheld where they name what it cannot read (ADR-0021).

type DiffOptions

type DiffOptions struct {
	// Written reports whether the agent wrote the value of property prop
	// of node nodeID of the proposed flow, as decided from what it sent
	// (ADR-0021), never by comparing. For a written value the alerts never
	// compare it with what the agent may not read: a written setting agents
	// may not read (not AgentVisible, Sensitive, undeclared, or of an
	// unregistered type) counts as changed whatever the base holds, and only
	// the hosts and secret names of base settings agents may read count as
	// known to a written value (new_host, secret_added, secret_moved). Nil:
	// every value is compared with the base (the editor's view).
	Written func(nodeID, prop string) bool
}

DiffOptions shape the alerts an agent gets back (DiffWith).

type DiffReport

type DiffReport struct {
	// Nodes lists the added, removed and changed nodes: next's in its
	// order, then the removed ones in base's order. Unchanged nodes are
	// omitted.
	Nodes       []NodeDiff      `json:"nodes"`
	Connections ConnectionsDiff `json:"connections"`
	RiskBefore  node.Risk       `json:"riskBefore"`
	RiskAfter   node.Risk       `json:"riskAfter"`
	Alerts      []Alert         `json:"alerts"`
}

DiffReport is what Diff found.

func Diff

func Diff(base, next *Flow, reg *node.Registry) DiffReport

Diff compares next with base (nil: an empty flow). The report is deterministic and never holds the value of a Sensitive property; its alerts hold no value an agent may not read. Nodes are paired by ID; a repeated ID is paired by occurrence, so a duplicate is reported as a node of its own. The alerts pair a node with its base node only when both have the same type: a retyped node is one removed and another added.

func DiffWith

func DiffWith(base, next *Flow, reg *node.Registry, opts DiffOptions) DiffReport

DiffWith is Diff whose alerts follow opts: the alerts of a proposal an agent wrote never depend on how what it wrote compares with what it may not read (DiffOptions.Written). The node and field diffs are Diff's.

type DryRunInput

type DryRunInput struct {
	// TriggerNodeID is the enabled input node at whose output Payload is
	// injected. It may be empty when the flow has exactly one enabled input
	// node.
	TriggerNodeID string `json:"triggerNodeId"`
	// Payload is the payload of the injected message.
	Payload any `json:"payload,omitempty"`
	// Mocks are, by node ID, the payloads stubbed nodes emit on their first
	// output port; a stubbed node without one emits nothing.
	Mocks map[string]any `json:"mocks,omitempty"`
	// FlowVars seed the isolated flow variable store.
	FlowVars map[string]any `json:"flowVars,omitempty"`
	// Redact, when set, hides config values from the run: every config
	// property of a node for which it returns true is replaced with
	// "<redacted>" before the flow is validated and run, so a value the
	// caller may not see reaches no preview, not even transformed by the
	// nodes it flows through. A redacted value that makes its node invalid
	// fails the dry-run like any invalid flow.
	Redact func(n *Node, prop string) bool `json:"-"`
}

DryRunInput says how to run a dry-run.

type DryRunResult

type DryRunResult struct {
	// Issues are Lint's issues of the flow as it would run (after Redact),
	// each message cut to DryRunPreviewBytes. An error other than an
	// EnvironmentIssue (undefined_secret) means the flow did not run: the
	// trace and wouldExecute are then empty.
	Issues       []Issue        `json:"issues"`
	Trace        []TraceStep    `json:"trace"`
	WouldExecute []WouldExecute `json:"wouldExecute"`
	// MissingSecrets are the secret names the nodes the run reached
	// reference: the sandbox has none of them.
	MissingSecrets []string `json:"missingSecrets"`
	// Truncated: a preview was cut or entries were left out to keep the
	// result within DryRunMaxResultBytes.
	Truncated bool `json:"truncated"`
	// TimedOut: the run was stopped after DryRunTimeout.
	TimedOut bool `json:"timedOut"`
	// Capped: the run was stopped at DryRunMaxExecutions routed messages
	// (each execution is one) or when its data budget (DryRunMaxDataBytes)
	// was spent.
	Capped bool `json:"capped"`
}

DryRunResult is what a dry-run did, in execution order.

func DryRun

func DryRun(ctx context.Context, f *Flow, reg *node.Registry, in DryRunInput) (DryRunResult, error)

DryRun runs f once in a sandbox and reports what happened. The flow is first linted (LintContext with ctx's secret store: deploy's own checks); its issues are the result's Issues, and an error issue other than an EnvironmentIssue (see BlockingIssues) means it does not run — the result then holds only the issues and DryRun returns no error. A valid flow is then instantiated in a private runtime that is never registered with a RuntimeManager, through reg.Derive: every node is wrapped so that triggers never start (Payload is injected at the chosen trigger's output) and every node whose type or instance risk is not safe is a stub that records itself in WouldExecute and emits its mock, if any. Nodes get isolated variable stores, an empty secret store and a node.Sandbox bounding the data they generate. The private runtime runs one node at a time, keeps out of the process metrics, and routes at most DryRunMaxExecutions messages. The run ends when all of its work is done, at that cap or when the data budget is spent (Capped), DryRunTimeout after DryRun was called (TimedOut), or when ctx ends (then the partial result is returned with ctx's error). Nodes are closed when DryRun returns; work still running then (a node ignoring cancellation, a goroutine a node started with node.Go) keeps the sandbox slot until it returns. One dry-run or node test runs at a time: otherwise the error wraps ErrBusy. f is not modified.

type FieldDiff

type FieldDiff struct {
	Path        string `json:"path"`
	Change      string `json:"change"`
	Before      any    `json:"before,omitempty"`
	After       any    `json:"after,omitempty"`
	Sensitive   bool   `json:"sensitive"`
	Destination bool   `json:"destination"`
}

FieldDiff is one changed field: "type", "enabled" or "config.<prop>". Before is absent when added, After when removed.

type Flow

type Flow struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	Nodes       []Node                 `json:"nodes"`
	Connections []Connection           `json:"connections"`
	State       FlowState              `json:"state"`
	Variables   map[string]interface{} `json:"variables,omitempty"` // Legacy definition metadata; runtime variables use the scoped variable store.
	// Version counts the saved definitions of the flow (1 when created). It
	// is server-controlled: storage assigns it on every definition change
	// (not on state changes) and ignores any value a client or agent sends.
	Version   int       `json:"version"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	// contains filtered or unexported fields
}

Flow represents a complete automation workflow.

func FromJSON

func FromJSON(data []byte) (*Flow, error)

FromJSON deserializes a flow from JSON.

func NewFlow

func NewFlow(name string) *Flow

NewFlow creates a new Flow with a generated UUID and timestamps.

func (*Flow) AddConnection

func (f *Flow) AddConnection(conn Connection)

AddConnection adds a connection to the flow.

func (*Flow) AddNode

func (f *Flow) AddNode(node Node)

AddNode adds a node to the flow.

func (*Flow) CheckConfig

func (f *Flow) CheckConfig(reg *node.Registry) error

CheckConfig returns a *ValidationError listing every ConfigIssues entry, or nil when all node configs match their schemas. Deploy calls it so a mistyped value fails visibly instead of a node silently using its default.

func (*Flow) ConfigIssues

func (f *Flow) ConfigIssues(reg *node.Registry) []node.ConfigIssue

ConfigIssues checks the config of every enabled node against its registered type's schema (node.CheckConfig: types, enums, bounds) and returns the problems with flow-level paths such as "nodes[3].config.interval". Disabled nodes are never instantiated and are skipped, as are unregistered types (instantiating them reports the unknown type). It is Lint's config check.

func (*Flow) GetNode

func (f *Flow) GetNode(nodeID string) *Node

GetNode returns a node by ID, or nil if not found.

func (*Flow) RemoveConnection

func (f *Flow) RemoveConnection(connID string)

RemoveConnection removes a connection from the flow.

func (*Flow) RemoveNode

func (f *Flow) RemoveNode(nodeID string)

RemoveNode removes a node and its connections from the flow.

func (*Flow) ToJSON

func (f *Flow) ToJSON() ([]byte, error)

ToJSON serializes the flow to JSON.

func (*Flow) Validate

func (f *Flow) Validate(reg *node.Registry) error

Validate checks the flow's structure (unique non-empty IDs, existing nodes and ports, no self-loops or cycles) and requires at least one enabled trigger. Whether a node is a trigger is decided by its registered type, never by the client-supplied Category field; unregistered types are never triggers.

type FlowRuntime

type FlowRuntime struct {
	// contains filtered or unexported fields
}

FlowRuntime manages the execution of a single flow. Each active flow runs in its own goroutine with message passing via channels.

func NewFlowRuntime

func NewFlowRuntime(f *Flow, registry *node.Registry, opts ...RuntimeOption) (*FlowRuntime, error)

NewFlowRuntime creates a new FlowRuntime for the given flow.

func (*FlowRuntime) ActiveTargets

func (r *FlowRuntime) ActiveTargets(nodeID string) int

ActiveTargets returns how many enabled nodes a message leaving nodeID (on any of its output ports) is routed to. Connections to disabled nodes do not count. Unknown or disabled nodes have none.

func (*FlowRuntime) Call

func (r *FlowRuntime) Call(ctx context.Context, req CallRequest) (CallResult, error)

Call starts a run on a callable trigger (one implementing node.Emitter, such as trigger-tool) and waits for its reply, the end of the run, the timeout, or ctx cancellation (whichever first). On timeout it returns Status "running"; the run continues and Wait can be used later. On ctx cancellation it returns the same "running" result together with ctx.Err().

The timeout counts from the start of Call and covers handing the message to the trigger: when the trigger does not accept it in time, no run is started and Call fails with ErrTriggerBusy.

A message of the run that is dropped before it executes (full node queue, unknown target, routing timeout) is recorded like a node error ("message dropped at node X: …"), so the call reports an error unless a reply won.

A final result returned by Call is handed over to the caller: the runtime forgets it as soon as the run is over (RunDone closed), so a later Wait for that run reports "expired". Only results Call could not return (status "running") stay retrievable with Wait, until the waiter's hard lifetime ends.

The run ID is a server-generated UUID set as the run's correlationID, with req.Actor as its "actor" meta. The payload is a deep copy of req.Args (an empty object when nil). An error without a run ID means no run was started.

func (*FlowRuntime) ConnectionsUsed

func (r *FlowRuntime) ConnectionsUsed() []string

ConnectionsUsed returns the broker connections (ADR-0026) the runtime's nodes name (node.ConnectionRequirer), sorted, each once: what a change to one of them must restart (ADR-0029). It asks the running instances, so it is the definition that runs, not a later stored one.

func (*FlowRuntime) Drained

func (r *FlowRuntime) Drained() bool

Drained reports whether every goroutine of the last started instance has exited (true for a runtime that was never started). After a Stop that timed out it stays false until the stragglers return.

func (*FlowRuntime) DroppedMessages

func (r *FlowRuntime) DroppedMessages() int64

DroppedMessages reports how many messages this runtime discarded.

func (*FlowRuntime) Errors

func (r *FlowRuntime) Errors() <-chan error

Errors returns the error channel for monitoring runtime errors.

func (*FlowRuntime) Flow

func (r *FlowRuntime) Flow() *Flow

Flow returns the flow being executed.

func (*FlowRuntime) GetTriggerNodeIDs

func (r *FlowRuntime) GetTriggerNodeIDs() []string

GetTriggerNodeIDs returns the IDs of all trigger nodes in this flow.

func (*FlowRuntime) Inflight

func (r *FlowRuntime) Inflight() int64

Inflight is how many messages the flow holds now: queued for a node or executing, over all its runs.

func (*FlowRuntime) InjectTrigger

func (r *FlowRuntime) InjectTrigger(nodeID string, payload interface{}) error

InjectTrigger triggers a manual trigger node by ID. Returns an error if the node doesn't exist, isn't a manual trigger, or isn't running.

func (*FlowRuntime) IsRunning

func (r *FlowRuntime) IsRunning() bool

IsRunning returns whether the flow is currently running.

func (*FlowRuntime) LLMConnectionsUsed

func (r *FlowRuntime) LLMConnectionsUsed() []string

LLMConnectionsUsed returns the LLM connections (ADR-0038) the runtime's nodes name (node.LLMConnectionRequirer), sorted, each once. A change to one restarts nothing (the nodes resolve it per call); the API refuses to delete one while a running flow uses it. It asks the running instances, so it is the definition that runs, not a later stored one.

func (*FlowRuntime) RunDone

func (r *FlowRuntime) RunDone(runID string) <-chan struct{}

RunDone returns a channel closed when the run identified by runID finishes (all of its in-flight work drained). It is also closed when the flow stops or the run's waiter expires, so a stuck run cannot hold a caller's resources forever, and it is already closed for runs that are not tracked.

func (*FlowRuntime) Start

func (r *FlowRuntime) Start(ctx context.Context) error

Start begins executing the flow. This method is non-blocking; the flow runs in background goroutines. Every trigger's Start is called synchronously, so when Start returns nil all triggers are running (and can e.g. be injected into immediately). If any trigger fails to start, the triggers already started are stopped, the runtime is torn down and the error is returned.

func (*FlowRuntime) State

func (r *FlowRuntime) State() FlowState

State returns the current state of the flow runtime.

func (*FlowRuntime) Stop

func (r *FlowRuntime) Stop() error

Stop gracefully stops the flow execution. A runtime that is not running, or that another Stop is stopping, returns ErrFlowNotRunning.

func (*FlowRuntime) Tools

func (r *FlowRuntime) Tools() []ToolInfo

Tools returns the tools this runtime publishes (computed at deploy), in definition order. The slice is a copy; Schema and OutputSchema are shared.

func (*FlowRuntime) ValidateCallTriggers

func (r *FlowRuntime) ValidateCallTriggers() error

ValidateCallTriggers fails when a callable trigger (node.Emitter) has no active downstream connection: calls to it could never do anything. Deploy runs it; the error is a *ValidationError.

func (*FlowRuntime) Wait

func (r *FlowRuntime) Wait(ctx context.Context, runID string) (CallResult, error)

Wait returns the final result of a run started by Call, blocking until it is final or ctx ends (then: the "running" result and ctx.Err()). It can be repeated until the waiter's hard lifetime ends. A run that is unknown, whose waiter expired, or whose result Call already returned reports "expired".

func (*FlowRuntime) Warnings

func (r *FlowRuntime) Warnings() []DeployWarning

Warnings returns the warnings the runtime deployed with (deployWarnings).

type FlowState

type FlowState string

FlowState represents the current state of a flow.

const (
	// FlowStateActive indicates the flow is saved and ready to be deployed.
	FlowStateActive FlowState = "active"
	// FlowStateInactive indicates the flow is disabled and won't run.
	FlowStateInactive FlowState = "inactive"
	// FlowStateRunning indicates the flow is currently executing.
	FlowStateRunning FlowState = "running"
	// FlowStateFailed indicates the flow encountered an error.
	FlowStateFailed FlowState = "failed"
)

type InjectableNode

type InjectableNode interface {
	Inject(customPayload interface{}) error
	IsRunning() bool
}

InjectableNode is an interface for nodes that can be manually triggered.

type Issue

type Issue struct {
	Path     string        `json:"path"`
	Code     string        `json:"code"`
	Severity IssueSeverity `json:"severity"`
	Message  string        `json:"message"`
}

Issue is one problem found in a flow. Lint locates it by a JSON-pointer-like path ("/nodes/{nodeId}/config/url"); AnalyzeTools and deploy messages by index ("nodes[2].config.url").

func BlockingIssues

func BlockingIssues(issues []Issue) []Issue

BlockingIssues returns the error issues of issues that are not EnvironmentIssues, in order (never nil): the problems of the definition itself, which stop a dry-run and the storing or approval of a draft.

func Lint

func Lint(f *Flow, reg *node.Registry) []Issue

Lint returns every issue deploy would find in f (errors) plus the warnings of the tool risk analysis and the positions out of range (IssueInvalidPosition, which deploy does not check), located by JSON-pointer-like paths ("/nodes", "/nodes/{nodeId}", "/nodes/{nodeId}/config/{prop}", "/connections/{id}"), in a deterministic order: flow-level issues first, then nodes in definition order, then connections in definition order; within one location by path, errors before warnings, then code and message. It never modifies f and never returns nil; the node instances it builds are closed before it returns. Messages never quote the values of Sensitive properties. The secrets strict settings require are checked against secrets.DefaultStore, the store deploy resolves them in (LintContext takes the context's). A flow without error issues deploys, except for what only starting it can tell (an exclusive resource already taken: 409).

func LintContext

func LintContext(ctx context.Context, f *Flow, reg *node.Registry) []Issue

LintContext is Lint checking the secrets strict settings require (IssueUndefinedSecret) against the store of ctx (secrets.FromContext, DefaultStore when ctx carries none), and the broker and LLM connections nodes name against the stores of ctx (brokers.FromContext, llm.FromContext), exactly as deploy checks them.

func (Issue) String

func (i Issue) String() string

String renders the issue as "path: message".

type IssueSeverity

type IssueSeverity string

IssueSeverity says whether an Issue fails the deploy.

const (
	// IssueError fails the deploy.
	IssueError IssueSeverity = "error"
	// IssueWarning is logged and shown, but the flow deploys.
	IssueWarning IssueSeverity = "warning"
)

type ManagerOption

type ManagerOption func(*RuntimeManager)

ManagerOption configures a RuntimeManager.

func WithManagerObserver

func WithManagerObserver(hook NodeEventHook) ManagerOption

WithManagerObserver sets a NodeEventHook applied to every flow this manager deploys, so the whole process shares one observability sink.

func WithRuntimeOptions

func WithRuntimeOptions(opts ...RuntimeOption) ManagerOption

WithRuntimeOptions applies extra RuntimeOptions to every flow this manager deploys.

type Message

type Message = types.Message

Type aliases for backward compatibility and convenience. These allow using flow.DataType, flow.NodeCategory, etc. without breaking existing code.

type MessageRouter

type MessageRouter struct {
	// contains filtered or unexported fields
}

MessageRouter handles message routing between nodes based on flow connections. It builds an adjacency map from connections and routes messages via channels.

Route delivers synchronously, in call order, onto a single output channel, so messages between the same (source, target) pair are always FIFO: every source node routes from one goroutine (its serial executor, or its trigger's forwarder), and that goroutine's sends land on the channel in order.

func NewMessageRouter

func NewMessageRouter(connections []Connection, logger zerolog.Logger, opts ...RouterOption) *MessageRouter

NewMessageRouter creates a new MessageRouter from the given connections.

func (*MessageRouter) Close

func (r *MessageRouter) Close()

Close stops the router and closes all channels.

func (*MessageRouter) CountTargets

func (r *MessageRouter) CountTargets(sourceNode, sourcePort string) int

CountTargets returns how many targets a (sourceNode, sourcePort) routes to, without allocating. Unlike GetTargets it copies nothing, so it's cheap to call on the per-message hot path (e.g. sizing the in-flight run counter). The adjacency map is immutable after construction; the nil-map indexing is safe.

func (*MessageRouter) GetInputChannel

func (r *MessageRouter) GetInputChannel(nodeID string) chan *types.Message

GetInputChannel returns or creates an input channel for a node. This is used by trigger nodes to send their initial messages.

func (*MessageRouter) GetTargets

func (r *MessageRouter) GetTargets(sourceNode, sourcePort string) []targetConnection

GetTargets returns all target nodes for a given source node and port.

func (*MessageRouter) MessagesDropped

func (r *MessageRouter) MessagesDropped() int64

MessagesDropped returns the number of messages dropped due to backpressure.

func (*MessageRouter) Output

func (r *MessageRouter) Output() <-chan RoutedMessage

Output returns the channel for receiving routed messages.

func (*MessageRouter) Route

func (r *MessageRouter) Route(sourceNode string, msg *types.Message)

Route sends a message from a source node to all connected target nodes.

type Node

type Node struct {
	ID       string                 `json:"id"`
	Type     string                 `json:"type"`     // The registered node type (e.g., "trigger-interval")
	Category NodeCategory           `json:"category"` // input, processing, or output
	Position Position               `json:"position"` // Visual position in the editor
	Config   map[string]interface{} `json:"config"`   // Node-specific configuration
	Inputs   []Port                 `json:"inputs"`   // Input ports
	Outputs  []Port                 `json:"outputs"`  // Output ports
	Enabled  bool                   `json:"enabled"`  // Whether this node is active; true when absent in JSON
}

Node represents a single processing unit in a flow.

func NewNode

func NewNode(nodeType string, category NodeCategory) *Node

NewNode creates a new Node with a generated UUID.

func (*Node) UnmarshalJSON

func (n *Node) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a node, treating an absent (or null) "enabled" field as true. Definitions written by hand, by older editors or by agents often omit it, and decoding that as false would silently drop the node.

type NodeCategory

type NodeCategory = types.NodeCategory

Type aliases for backward compatibility and convenience. These allow using flow.DataType, flow.NodeCategory, etc. without breaking existing code.

type NodeDiff

type NodeDiff struct {
	NodeID   string      `json:"nodeId"`
	Type     string      `json:"type"`
	TypeName string      `json:"typeName"`
	Change   string      `json:"change"`
	Fields   []FieldDiff `json:"fields"`
	Moved    bool        `json:"moved"`
}

NodeDiff is one added, removed or changed node. A node whose only change is its position is "changed" with Moved and no fields.

type NodeEvent

type NodeEvent struct {
	FlowID   string
	NodeID   string
	NodeType string
	CorrID   string
	// Actor is the run's "actor" meta (who started it, e.g. "token:bot"),
	// copied by the executor before the node runs so observers never read
	// Input's meta while the node may still change it. "" when unknown.
	Actor string
	// FlowVersion is the stored version of the definition the runtime runs
	// (Flow.Version when the runtime was built; 0 when unknown), so the
	// history records which version each run ran (ADR-0022).
	FlowVersion int
	Phase       string // NodePhaseRunning | NodePhaseSuccess | NodePhaseError
	Input       *types.Message
	Outputs     []*types.Message
	Err         error
	Duration    time.Duration
}

NodeEvent is a structured observation of a single node execution. Unlike the legacy before/after hooks it carries the node type, correlation ID, timing, the input message and (on success) the outputs, which is everything the observability layer needs to persist history and stream live state to the editor — including attributing process-debug output to a canvas node.

type NodeEventHook

type NodeEventHook func(NodeEvent)

NodeEventHook receives NodeEvents. It runs inline on the node executor goroutine while a semaphore slot is held, so it MUST NOT block: implementations are expected to do a non-blocking hand-off (e.g. a buffered channel send) and return immediately. Blocking here directly stalls node throughput.

type NodeExecutionError

type NodeExecutionError struct {
	NodeID   string
	NodeType string
	Err      error
}

NodeExecutionError represents an error that occurred during node execution.

func NewNodeExecutionError

func NewNodeExecutionError(nodeID, nodeType string, err error) *NodeExecutionError

NewNodeExecutionError creates a new NodeExecutionError.

func (*NodeExecutionError) Error

func (e *NodeExecutionError) Error() string

Error implements the error interface.

func (*NodeExecutionError) Unwrap

func (e *NodeExecutionError) Unwrap() error

Unwrap returns the underlying error.

type Op

type Op struct {
	Op           string         `json:"op"`
	Node         *OpNode        `json:"node,omitempty"`
	NodeID       string         `json:"nodeId,omitempty"`
	Config       map[string]any `json:"config,omitempty"`
	Enabled      *bool          `json:"enabled,omitempty"`
	Position     *Position      `json:"position,omitempty"`
	SourceNode   string         `json:"sourceNode,omitempty"`
	SourcePort   string         `json:"sourcePort,omitempty"`
	TargetNode   string         `json:"targetNode,omitempty"`
	TargetPort   string         `json:"targetPort,omitempty"`
	ConnectionID string         `json:"connectionId,omitempty"`
}

Op is one edit operation. Which fields apply depends on Op:

{"op":"add_node","node":{"id"?,"type","config"?,"enabled"?,"position"?}}
{"op":"update_node","nodeId","config"?,"enabled"?,"position"?}
{"op":"remove_node","nodeId"}
{"op":"connect","sourceNode","sourcePort","targetNode","targetPort"}
{"op":"disconnect","connectionId"} or with the four endpoint fields

update_node's config is a JSON merge patch (RFC 7386): a key set to null is deleted, an object is merged into an object, anything else replaces.

type OpNode

type OpNode struct {
	ID       string         `json:"id,omitempty"`
	Type     string         `json:"type"`
	Config   map[string]any `json:"config,omitempty"`
	Enabled  *bool          `json:"enabled,omitempty"`
	Position *Position      `json:"position,omitempty"`
}

OpNode is the node of an add_node operation. Its category and ports come from the registry; an absent ID is generated, an absent position is chosen by AutoLayout, and enabled defaults to true.

type Port

type Port = types.Port

Type aliases for backward compatibility and convenience. These allow using flow.DataType, flow.NodeCategory, etc. without breaking existing code.

type PortPreview

type PortPreview struct {
	Port    string `json:"port"`
	Preview string `json:"preview"`
}

PortPreview is one output of an execution: the port and a preview of the payload.

type Position

type Position struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

Position represents the X,Y coordinates of a node in the visual editor.

type Replier

type Replier = node.Replier

Replier delivers the reply of a called run (node.Replier).

func ReplyFromContext

func ReplyFromContext(ctx context.Context) Replier

ReplyFromContext returns the Replier of the flow runtime that owns ctx (node.ReplierFromContext). It is never nil.

type RetryConfig

type RetryConfig struct {
	// MaxRetries is the maximum number of retry attempts (0 = no retries).
	MaxRetries int
	// InitialWait is the initial wait time before the first retry.
	InitialWait time.Duration
	// MaxWait is the maximum wait time between retries.
	MaxWait time.Duration
	// Multiplier is the exponential backoff multiplier.
	Multiplier float64
}

RetryConfig configures retry behavior for node execution.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns a RetryConfig with sensible defaults.

type RoutedMessage

type RoutedMessage struct {
	Message    *types.Message
	TargetNode string
	TargetPort string
}

RoutedMessage represents a message being routed to a specific node.

type RouterError

type RouterError struct {
	SourceNode string
	TargetNode string
	Err        error
}

RouterError represents an error that occurred during message routing.

func NewRouterError

func NewRouterError(sourceNode, targetNode string, err error) *RouterError

NewRouterError creates a new RouterError.

func (*RouterError) Error

func (e *RouterError) Error() string

Error implements the error interface.

func (*RouterError) Unwrap

func (e *RouterError) Unwrap() error

Unwrap returns the underlying error.

type RouterOption

type RouterOption func(*MessageRouter)

RouterOption is a functional option for configuring the MessageRouter.

func WithContext

func WithContext(ctx context.Context) RouterOption

WithContext sets the context for the router.

func WithDropHandler

func WithDropHandler(fn func(RoutedMessage)) RouterOption

WithDropHandler registers a callback invoked (synchronously, on the routing goroutine) for each message dropped because the output stayed full past the send timeout. It must not block.

func WithSendTimeout

func WithSendTimeout(timeout time.Duration) RouterOption

WithSendTimeout sets the timeout for sending messages to the output channel. If a message cannot be sent within this timeout, it will be dropped.

type RuntimeManager

type RuntimeManager struct {
	// contains filtered or unexported fields
}

RuntimeManager manages multiple flow runtimes.

func NewRuntimeManager

func NewRuntimeManager(registry *node.Registry, logger zerolog.Logger, opts ...ManagerOption) *RuntimeManager

NewRuntimeManager creates a new RuntimeManager.

func (*RuntimeManager) Deploy

func (m *RuntimeManager) Deploy(ctx context.Context, f *Flow) error

Deploy creates and starts a runtime for the given flow. A node config that does not match its schema (Flow.CheckConfig) fails the deploy.

func (*RuntimeManager) GetRuntime

func (m *RuntimeManager) GetRuntime(flowID string) (*FlowRuntime, bool)

GetRuntime returns the runtime for the given flow ID.

func (*RuntimeManager) ListRunning

func (m *RuntimeManager) ListRunning() []string

ListRunning returns a list of all running flow IDs.

func (*RuntimeManager) Restore

func (m *RuntimeManager) Restore(ctx context.Context, f *Flow) ([]node.ConfigIssue, error)

Restore redeploys a flow that was running before the process restarted. Unlike Deploy it does not refuse node configs that fail the schema check: it returns those issues for the caller to log and starts the flow anyway, with the nodes clamping or defaulting such values exactly as they did before the check existed. A flow that ran before an upgrade therefore keeps running after it, while the next explicit Deploy asks for a fix. Any other error (unknown type, a node that cannot be created or validated) still fails the restore.

func (*RuntimeManager) SetToolCaller

func (m *RuntimeManager) SetToolCaller(tc node.ToolCaller)

SetToolCaller gives every flow deployed from now on tc as its nodes' tool caller (WithToolCaller; nil: none). The composition root sets it once the tool service exists, which needs the manager first, and before any flow is deployed or restored; flows already running keep the caller they were deployed with.

func (*RuntimeManager) StopAll

func (m *RuntimeManager) StopAll()

StopAll stops all running flows. The stopped runtimes stay in the manager (not running). As in Undeploy, they are stopped without m.mu held, one after the other.

func (*RuntimeManager) Tools

func (m *RuntimeManager) Tools() (version uint64, tools []ToolInfo)

Tools returns the tools published by the running flows, sorted by tool name, and a version that changes on every deploy, undeploy and stop, so a caller can cache what it derives from the list. The slice is a copy; its Schema and OutputSchema are shared and must not be modified.

func (*RuntimeManager) Undeploy

func (m *RuntimeManager) Undeploy(flowID string) error

Undeploy stops and removes the runtime for the given flow. The runtime leaves the manager under its lock, and is stopped once the lock is released: Stop waits (up to the stop timeout) for the flow's executors to drain, and a node that reads the manager while it runs (an agent node listing or calling tools, ADR-0039) must not wait behind that wait, or the flow could not drain. Until it has drained, the flow cannot be deployed again (ErrFlowStillStopping).

type RuntimeOption

type RuntimeOption func(*FlowRuntime)

RuntimeOption is a functional option for configuring the FlowRuntime.

func WithCallExpiryGrace

func WithCallExpiryGrace(d time.Duration) RuntimeOption

WithCallExpiryGrace sets how long a called run's waiter outlives the call's timeout before it expires (default DefaultCallExpiryGrace). Values <= 0 are ignored.

func WithFlowVariables

func WithFlowVariables(stores *flowvars.FlowStores) RuntimeOption

WithFlowVariables sets the per-flow variable stores the runtime takes its flow's persistent store from (shared with the API that manages them). Without it the runtime uses flowvars.DefaultFlows.

func WithLogger

func WithLogger(logger zerolog.Logger) RuntimeOption

WithLogger sets a custom logger for the runtime.

func WithMaxCallResultBytes

func WithMaxCallResultBytes(n int) RuntimeOption

WithMaxCallResultBytes caps the serialized payload of a called run's reply: a bigger reply is not stored and the call ends as an error. Default DefaultMaxCallResultBytes; values <= 0 are ignored.

func WithMaxCallWaiters

func WithMaxCallWaiters(n int) RuntimeOption

WithMaxCallWaiters caps how many called runs (see Call) the runtime tracks at once: runs still executing plus results not collected yet. Past it, the uncollected result closest to its expiry is evicted, or Call fails with ErrTooManyCalls. Default DefaultMaxCallWaiters; values <= 0 are ignored.

func WithMaxConcurrency

func WithMaxConcurrency(n int) RuntimeOption

WithMaxConcurrency sets the maximum number of nodes that may execute concurrently within the flow. Values <= 0 are ignored.

func WithMaxInflight

func WithMaxInflight(n int) RuntimeOption

WithMaxInflight bounds how many messages the flow holds before its triggers wait (ADR-0037). Without it the bound is the node queue limit, so a trigger alone never overflows a queue; 0 removes the bound (queues then drop what does not fit). Negative values are ignored.

func WithNodeContext

func WithNodeContext(wrap func(context.Context) context.Context) RuntimeOption

WithNodeContext wraps the context every node of the runtime gets, trigger Start and Process alike: wrap adds values (an isolated secret store, variable stores) to the runtime's context and returns it. It must keep its argument as the parent (the runtime cancels it on Stop) and should only add values. When the result carries a flow variable store (vars.WithFlowStore), the runtime uses it and does not load the flow's persistent store at all.

func WithNodeQueueLimit

func WithNodeQueueLimit(n int) RuntimeOption

WithNodeQueueLimit caps how many messages may wait for a single node before further ones are dropped. Values <= 0 are ignored.

func WithObserver

func WithObserver(hook NodeEventHook) RuntimeOption

WithObserver sets the structured per-execution observer hook. The hook must not block (see NodeEventHook).

func WithRetryConfig

func WithRetryConfig(config RetryConfig) RuntimeOption

WithRetryConfig sets the retry configuration for node execution.

func WithStopTimeout

func WithStopTimeout(d time.Duration) RuntimeOption

WithStopTimeout sets how long Stop waits for the flow's goroutines to exit. Values <= 0 are ignored.

func WithToolCaller

func WithToolCaller(tc node.ToolCaller) RuntimeOption

WithToolCaller gives the runtime's nodes tc as their tool caller (node.ToolCallerFromContext): agent nodes call the admin's flow tools through it (ADR-0039). Without it they get the one that lists nothing and refuses every call; a sandboxed node context (the dry-run's) never carries one.

type SecretReference

type SecretReference struct {
	Name     string `json:"name"`
	NodeID   string `json:"nodeId"`
	NodeType string `json:"nodeType"`
	Setting  string `json:"setting"`
	Enabled  bool   `json:"enabled"`
}

SecretReference is one {{secret.NAME}} reference written in a node's settings: which secret, where, and whether the node is enabled (a disabled node does not run, but its reference is still there).

func SecretReferences

func SecretReferences(f *Flow) []SecretReference

SecretReferences returns every secret reference of f's node settings (nested values included, any setting: whether the node resolves it there is the node's business), in node order, then setting name, then secret name, each (node, setting, name) once. It is what the Secrets dialog shows as "used by". Never nil.

type TestNodeResult

type TestNodeResult struct {
	// Issues are the config's problems deploy would refuse (config_type at
	// "/config/{prop}", invalid_config at "/config"); when there are any,
	// the node did not run.
	Issues  []Issue       `json:"issues"`
	Outputs []PortPreview `json:"outputs"`
	// Error is the node's error, cut to DryRunPreviewBytes.
	Error      string  `json:"error,omitempty"`
	DurationMs float64 `json:"durationMs"`
	// Truncated: a preview was cut or outputs were left out to keep the
	// result within DryRunMaxResultBytes.
	Truncated bool `json:"truncated"`
	// TimedOut: the node did not finish within TestNodeTimeout.
	TimedOut bool `json:"timedOut"`
}

TestNodeResult is the outcome of a node test, bounded like a dry-run.

func TestNode

func TestNode(ctx context.Context, reg *node.Registry, nodeType string, config map[string]any, input any) (TestNodeResult, error)

TestNode runs one processing node of a safe type once on input, in a sandbox: isolated, empty variable stores, an empty secret store, a node.Sandbox bounding the data it generates, a TestNodeTimeout deadline. The input and the config are at most DryRunMaxInputBytes of JSON each (else ErrDryRunInput). The config is checked as deploy checks it (Lint's collectors: node.CheckConfig, then the factory and Validate): its problems are the result's Issues (config_type at "/config/{prop}", invalid_config at "/config") and the node does not run then (no error). An unknown type wraps ErrInvalidNodeType; any other category or a risk that is not safe (type or instance) wraps ErrTestNodeForbidden. A node error or panic, an output over the per-value cap, is the result's Error, not an error of TestNode. TestNode returns at its deadline (plus a short grace) even if the node ignores cancellation. It shares the one-at-a-time sandbox slot with DryRun (busy: an error wrapping ErrBusy); work still running when it returns (the node, a goroutine it started with node.Go) keeps the slot until it returns. The node is closed once it returned.

type ToolInfo

type ToolInfo struct {
	FlowID, TriggerNodeID, ToolName, Title, Description string
	Schema                                              *toolschema.Schema
	OutputSchema                                        json.RawMessage
	Risk                                                node.Risk
	Annotations                                         Annotations
	// Fingerprint is "sha256:<hex>" over the canonical JSON of the risk, the
	// annotations, the advertised input schema, the confirm mode and the ID
	// and type of every node above safe the tool reaches (ADR-0022; never
	// their settings, which agents may not read): grants and approvals bind
	// to it, so any change of what the tool may do changes it.
	Fingerprint   string
	Confirm       string
	Timeout       time.Duration
	MaxConcurrent int // effective: the admin's value, or the read-only default
	Cooldown      time.Duration
}

ToolInfo is a published tool of a running flow, as computed at deploy. It is shared read-only: callers must not modify Schema or OutputSchema.

func (ToolInfo) RequiresUserInteraction

func (t ToolInfo) RequiresUserInteraction() bool

RequiresUserInteraction reports whether MCP clients are asked to confirm calls (_meta["anthropic/requiresUserInteraction"]): every destructive tool, and every tool whose confirm mode is not "none" (ADR-0012).

type TraceStep

type TraceStep struct {
	NodeID string `json:"nodeId"`
	Type   string `json:"type"`
	// Input previews the input payload; empty for the trigger, whose
	// output is the injected payload.
	Input      string        `json:"input,omitempty"`
	Outputs    []PortPreview `json:"outputs"`
	Error      string        `json:"error,omitempty"`
	DurationMs float64       `json:"durationMs"`
	// Stubbed: the node did not run; a stub emits its mock, if any.
	Stubbed bool `json:"stubbed"`
}

TraceStep is one node execution of a dry-run. Previews are the JSON of the payload, cut to DryRunPreviewBytes (a cut one ends with "…"); they are not redacted (the service layer does that for agents).

type ValidationError

type ValidationError struct {
	Message string
}

ValidationError represents a flow validation error with details.

func NewValidationError

func NewValidationError(format string, args ...interface{}) *ValidationError

NewValidationError creates a new ValidationError with a formatted message.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

type WouldExecute

type WouldExecute struct {
	NodeID string    `json:"nodeId"`
	Type   string    `json:"type"`
	Risk   node.Risk `json:"risk"`
	Input  string    `json:"input"`
}

WouldExecute is a stubbed node a message reached: what would have run.

Jump to

Keyboard shortcuts

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