node

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: 16 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 node provides the interface definitions and registry for flow nodes.

Index

Constants

View Source
const (
	// ToolCallOK: the run replied (or finished without a reply: Result is
	// then empty).
	ToolCallOK = "ok"
	// ToolCallError: the run failed; Error says why, as agents see errors.
	ToolCallError = "error"
	// ToolCallRunning: the tool's timeout passed before the reply; the run
	// goes on.
	ToolCallRunning = "running"
)

Statuses of a ToolCallOutcome.

View Source
const (
	OptionsConnections          = "connections"
	OptionsZigbeeDevices        = "zigbee-devices"
	OptionsZigbeeProperties     = "zigbee-properties"
	OptionsZigbeeSettable       = "zigbee-settable"
	OptionsLLMConnections       = "llm-connections"
	OptionsLLMModels            = "llm-models"
	OptionsTools                = "tools"
	OptionsKnowledgeCollections = "knowledge-collections"
)

Suggestion sources of ConfigProperty.Options.

View Source
const (
	// ToolConfirmNone: the tool runs when called.
	ToolConfirmNone = "none"
	// ToolConfirmClient asks MCP clients to confirm with their user first.
	// It is UX only: it does not stop an agent that calls /mcp directly.
	ToolConfirmClient = "client"
	// ToolConfirmAdmin holds every call until the admin approves it in the
	// editor (server-side gate).
	ToolConfirmAdmin = "admin"
)

Confirmation policies of a tool (ToolSpec.Confirm, ADR-0012).

View Source
const (
	// ToolDefaultMaxConcurrent: calls of a tool run one at a time.
	ToolDefaultMaxConcurrent = 1
	// ToolReadOnlyMaxConcurrent: a read-only tool runs up to 4 calls at once.
	ToolReadOnlyMaxConcurrent = 4
)

Defaults of ToolSpec.MaxConcurrent when the admin leaves it unset.

Variables

View Source
var DefaultRegistry = NewRegistry()

DefaultRegistry is the global node registry.

View Source
var ErrInvalidToolArguments = errors.New("invalid tool arguments")

ErrInvalidToolArguments is matched (errors.Is) by the error a tool trigger's Emit returns for arguments outside its input schema, through any wrapping (FlowRuntime.Call wraps it). errors.As with *ToolArgumentsError gives the problems.

View Source
var ErrNoToolCaller = errors.New("no flow tools are available here: agent nodes call tools only in a deployed flow (never in a dry-run or a node test)")

ErrNoToolCaller is what the tool caller of a context without one returns for every call.

View Source
var ErrNotRunning = errors.New("flow is not running")

ErrNotRunning is what a callable trigger returns when its flow is not running (flow.ErrFlowNotRunning is this error).

View Source
var ErrResourceConflict = errors.New("resource already in use")

ErrResourceConflict marks a trigger Start error caused by an exclusive resource that is already taken (a webhook path, a tool name, a GPIO line). Deploy fails with it and the API answers 409 (ADR-0006). Wrap it with fmt.Errorf("%w: ...", node.ErrResourceConflict, ...).

View Source
var ErrSandboxLimit = errors.New("sandbox limit exceeded")

ErrSandboxLimit marks work a sandboxed execution refused because it would generate more data than the sandbox allows.

Functions

func ConfigOutputs

func ConfigOutputs(info NodeTypeInfo, cfg map[string]any) []types.Port

ConfigOutputs returns the output ports a node of type info has with cfg: info.Outputs, then one port per item of the OutputsFrom setting (ID and name = the item, any data type, Multiple like a static output), in order. Items that could not be a port of their own are skipped: anything but a non-empty string, a repeated item, the ID of a static output and the runtime's error port (the node's Validate refuses such items; ConfigOutputs never fails). The result is never nil and never shares info.Outputs' array.

func EstimateSize

func EstimateSize(v any, limit int64) int64

EstimateSize returns roughly the size of v's JSON encoding, walking maps, slices, arrays, pointers and interfaces (a value shared by several references counts each time, as an encoding or a deep copy repeats it). It stops as soon as the size is over limit and then returns a value greater than limit, so the walk is bounded by limit, not by v.

func Go

func Go(ctx context.Context, fn func())

Go runs fn in a new goroutine. In a sandbox the goroutine is tracked until fn returns (see Sandbox.Wait).

func InSandbox

func InSandbox(ctx context.Context) bool

InSandbox reports whether ctx is the context of a sandboxed execution.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether err (or any error it wraps) is marked retryable. Unmarked errors are treated as permanent and are never retried.

func Register

func Register(info NodeTypeInfo, factory NodeFactory) error

Register adds a node type to the default registry.

func ToolConfirmModes

func ToolConfirmModes() []string

ToolConfirmModes lists the confirmation policies, least strict first.

func Transient

func Transient(err error) error

Transient marks err as a transient, retryable failure. It returns nil when err is nil so it can be used inline (e.g. return node.Transient(err)).

func WaitingFlows

func WaitingFlows(ctx context.Context, correlationID string) []string

WaitingFlows returns the flows waiting for the run correlationID of the flow runtime that owns ctx (CallWaiters); nil outside a runtime. An agent node passes them on in AgentCaller.Waiting.

func WithNodeInfo

func WithNodeInfo(ctx context.Context, info NodeInfo) context.Context

WithNodeInfo returns ctx carrying info.

func WithReplier

func WithReplier(ctx context.Context, r Replier) context.Context

WithReplier returns ctx carrying the Replier of the runtime that runs the node. The flow runtime puts its own on every node's context.

func WithSandbox

func WithSandbox(ctx context.Context, sb *Sandbox) context.Context

WithSandbox returns a context whose nodes run in sb.

func WithToolCaller

func WithToolCaller(ctx context.Context, tc ToolCaller) context.Context

WithToolCaller returns ctx carrying tc (nil: none). The flow runtime puts the one it was configured with on every node's context.

Types

type AgentCaller

type AgentCaller struct {
	// FlowID and NodeID are the agent node's (NodeInfoFromContext): a tool
	// of the node's own flow is refused, and each node has its own limits.
	FlowID, NodeID string
	// Tools are the tool names the node lists; no other tool is listed or
	// called.
	Tools []string
	// AllowPrivileged lets the node call privileged tools.
	AllowPrivileged bool
	// Waiting are the flows whose agent nodes wait, through tool calls, for
	// the run the node serves (WaitingFlows of its message's correlation
	// ID): a tool of one of them is refused, like one of the node's own
	// flow, because its run would wait for an agent node that waits for it.
	Waiting []string
}

AgentCaller identifies an agent node calling tools and what its settings allow.

type AgentTool

type AgentTool struct {
	Name        string
	Description string
	// InputSchema is the tool's advertised input schema (a JSON object
	// schema).
	InputSchema json.RawMessage
	Risk        Risk
	// Confirm is the tool's confirmation policy (ToolConfirmNone for every
	// tool an agent node may call).
	Confirm string
}

AgentTool is a published flow tool an agent node may call, as the model is shown it.

type BaseNode

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

BaseNode provides a common implementation for simple nodes. Embed this in your node implementations to get default behavior.

func NewBaseNode

func NewBaseNode(config map[string]interface{}) *BaseNode

NewBaseNode creates a new BaseNode with the given configuration.

func (*BaseNode) Configure

func (n *BaseNode) Configure(config map[string]interface{}) error

Configure applies configuration settings to the node.

func (*BaseNode) GetConfig

func (n *BaseNode) GetConfig() map[string]interface{}

GetConfig returns the current configuration.

func (*BaseNode) GetConfigBool

func (n *BaseNode) GetConfigBool(key string, defaultValue bool) bool

GetConfigBool retrieves a boolean configuration value.

func (*BaseNode) GetConfigFloat

func (n *BaseNode) GetConfigFloat(key string, defaultValue float64) float64

GetConfigFloat retrieves a float configuration value.

func (*BaseNode) GetConfigInt

func (n *BaseNode) GetConfigInt(key string, defaultValue int) int

GetConfigInt retrieves an integer configuration value.

func (*BaseNode) GetConfigString

func (n *BaseNode) GetConfigString(key string, defaultValue string) string

GetConfigString retrieves a string configuration value.

func (*BaseNode) Validate

func (n *BaseNode) Validate() error

Validate performs basic validation. Override in specific implementations.

type CallWaiters

type CallWaiters interface {
	// WaitingFlows returns the flows whose agent nodes wait, through tool
	// calls, for the called run correlationID, outermost first: nil when
	// the run was not started by an agent node's call, or its caller no
	// longer waits (it has the result).
	WaitingFlows(correlationID string) []string
}

CallWaiters is implemented by the Replier of a flow runtime: it knows which flows wait for a called run.

type Closer

type Closer interface {
	Close() error
}

Closer is an optional interface for nodes that hold resources such as network clients, open files or connections. The runtime calls Close when a flow stops, after the flow's executors have drained, on every node (trigger or not) that implements it. Errors are logged by the runtime; Close should release what it can and not block for long.

type ConfigIssue

type ConfigIssue struct {
	// Path of the value inside the node config, e.g. "interval".
	Path string `json:"path"`
	// Message says what was expected and what was found, e.g.
	// `expected number (milliseconds), got string "5s"`.
	Message string `json:"message"`
}

ConfigIssue is one configuration value that does not match its schema.

func CheckConfig

func CheckConfig(schema *ConfigSchema, cfg map[string]any) []ConfigIssue

CheckConfig checks the values in cfg against the types, enums and bounds declared by schema, and returns the problems sorted by path (nil when there are none). It lets a deploy fail with an actionable message instead of a node silently falling back to a default for a mistyped value.

Rules:

  • keys the schema does not declare, and properties without a Type, are not checked;
  • null, and "" for any non-string type or enum, mean "unset": nodes then use their default (the editor removes a cleared number field; older editors and hand-written definitions may store "");
  • "number" accepts any finite number, "integer" a whole number;
  • "json" accepts a JSON object: a map, or a string holding one object;
  • enum values match exactly, or in any case when the property is CaseInsensitive (the node normalises case itself);
  • Minimum/Maximum are inclusive;
  • Required is left to the node, which knows its defaults.

Values of Sensitive properties are never quoted in messages.

flow.RuntimeManager.Deploy refuses a flow with issues; Restore, used for flows that were running before a restart, only reports them, so values saved before this check existed do not stop an automation on upgrade.

func (ConfigIssue) String

func (i ConfigIssue) String() string

String renders the issue as "path: message".

type ConfigProperty

type ConfigProperty struct {
	Type        string      `json:"type"`                  // string, number, integer, boolean, array, object, json ("" = any)
	Title       string      `json:"title"`                 // Human-readable title
	Description string      `json:"description,omitempty"` // Help text; states the unit of numeric values
	Default     interface{} `json:"default,omitempty"`     // Default value
	Enum        []string    `json:"enum,omitempty"`        // For select inputs; matched exactly unless CaseInsensitive
	Minimum     *float64    `json:"minimum,omitempty"`     // For number inputs
	Maximum     *float64    `json:"maximum,omitempty"`     // For number inputs
	Unit        string      `json:"unit,omitempty"`        // Unit of a numeric value (e.g. "milliseconds"), quoted in errors
	// CaseInsensitive lets Enum values match in any case. Set it only when the
	// node itself normalises the value's case (e.g. strings.ToUpper).
	CaseInsensitive bool `json:"caseInsensitive,omitempty"`

	// Sensitive marks a credential (password, token, DSN, secret-bearing URL,
	// …). Its value is never echoed in errors, and agent-authored drafts may
	// only set it to a {{secret.NAME}} reference.
	Sensitive bool `json:"sensitive,omitempty"`
	// AgentVisible marks a value that is harmless to show to MCP agents.
	// The default (false) means the value is redacted in agent read views.
	AgentVisible bool `json:"agentVisible,omitempty"`
	// Destination marks where the node sends data or connects: URLs, hosts,
	// brokers, topics, recipients, chat ids, file paths written, webhook
	// paths, pins and buses written. The draft approval page and the low
	// agent-deploy policy flag changes to it (flow.Diff).
	Destination bool `json:"destination,omitempty"`
	// RiskSwitch marks an opt-in that widens what the node may do
	// (allowPrivate, allowDashArgs, TLS-verification bypasses, …). Turning
	// one on is flagged by flow.Diff, and agent drafts may not turn it on.
	RiskSwitch bool `json:"riskSwitch,omitempty"`
	// Operation marks what selects the action a request performs at its
	// destination (an HTTP method or body, an SQL statement), as opposed to
	// message content. flow.Diff flags a change to it on a node that uses a
	// credential (credentialed_request_changed): the approved credential
	// would be used for something else.
	Operation bool `json:"operation,omitempty"`
	// Rate marks what sets how often a trigger fires or how many messages
	// a node lets through: an interval, a cron expression, a rate limit, a
	// batch size, a cooldown. flow.Diff flags a change to it, or a node
	// with one added or removed, on a flow that reaches other services
	// (rate_changed): how often it sends is the admin's to approve.
	Rate bool `json:"rate,omitempty"`
	// Options names where the editor finds suggestions for a string value,
	// or for each item of an array (the value stays free text):
	// OptionsConnections (the broker connections), OptionsZigbeeDevices
	// (the devices of the node's connection), OptionsZigbeeProperties /
	// OptionsZigbeeSettable (what the node's device publishes / can be
	// set), OptionsLLMConnections, OptionsLLMModels (the models of the
	// node's LLM connection), OptionsTools (the published tool names) and
	// OptionsKnowledgeCollections. The registry refuses any other source.
	Options string `json:"options,omitempty"`
}

ConfigProperty describes a single configuration property. CheckConfig enforces Type, Enum, Minimum and Maximum when a flow is deployed.

Type "object" is a map of name/value pairs (the editor edits it as rows, e.g. HTTP headers); "json" is a free-form JSON object the editor edits as JSON text and stores parsed (e.g. a tool's input schema).

type ConfigSchema

type ConfigSchema struct {
	Properties map[string]ConfigProperty `json:"properties"`
	Required   []string                  `json:"required,omitempty"`
}

ConfigSchema describes the configuration options for a node.

type ConfigurableNode

type ConfigurableNode interface {
	Node

	// Configure applies configuration settings to the node.
	// This is called when the node is instantiated.
	Configure(config map[string]interface{}) error

	// GetConfig returns the current configuration of the node.
	GetConfig() map[string]interface{}

	// GetConfigSchema returns a JSON schema describing the configuration options.
	// This is used for UI rendering and validation.
	GetConfigSchema() ConfigSchema
}

ConfigurableNode is a node that can be configured with settings.

type ConnectionRequirer

type ConnectionRequirer interface {
	// RequiredConnections returns, by config property, the connection
	// name that property holds.
	RequiredConnections() map[string]string
}

ConnectionRequirer is implemented by nodes whose settings name a broker connection (brokers.Store, ADR-0026), such as the Zigbee nodes. Deploy refuses a flow (a validation error, 400) while a named connection is not defined; Lint reports it as undefined_connection, an environment issue the admin may still fix. The connection is resolved when the node runs, through its context (brokers.FromContext), never at deploy.

type Emitter

type Emitter interface {
	Emit(ctx context.Context, msg *types.Message) error
}

Emitter is an optional interface for trigger nodes that can start a run on request (e.g. trigger-tool), which is what makes them callable through the runtime's synchronous Call.

Emit sends msg into the trigger's output as a new run. It must block until the message is handed to the runtime and return early with an error when ctx (the caller's) or the trigger's own Start context ends, or when the trigger is not running. The runtime has already set the run's meta (correlationID, actor) and owns the payload; the trigger may add its own meta and must set SourcePort when it has more than one output.

type LLMConnectionRequirer

type LLMConnectionRequirer interface {
	// RequiredLLMConnections returns, by config property, the LLM
	// connection name that property holds.
	RequiredLLMConnections() map[string]string
}

LLMConnectionRequirer is implemented by nodes whose settings name an LLM connection (llm.Store, ADR-0038), such as process-llm. Deploy refuses a flow (a validation error, 400) while a named connection is not defined; Lint reports it as undefined_llm_connection, an environment issue the admin may still fix. The connection is resolved when the node runs, through its context (llm.FromContext), never at deploy.

type Node

type Node interface {
	// Process handles an incoming message and returns zero or more output messages.
	// The context can be used for cancellation and timeout handling.
	// Returning an error will stop the message from being propagated further.
	Process(ctx context.Context, msg *types.Message) ([]*types.Message, error)

	// Ports returns the input and output port definitions for this node.
	// This is used for flow validation and UI rendering.
	Ports() (inputs []types.Port, outputs []types.Port)

	// Validate checks if the node's configuration is valid.
	// This is called before the flow is deployed.
	Validate() error
}

Node is the base interface that all nodes must implement. A Node processes incoming messages and produces output messages.

func Create

func Create(nodeType string, config map[string]interface{}) (Node, error)

Create instantiates a node from the default registry.

type NodeFactory

type NodeFactory func(config map[string]interface{}) (Node, error)

NodeFactory is a function that creates a new instance of a node.

type NodeInfo

type NodeInfo struct {
	FlowID string
	NodeID string
}

NodeInfo identifies the node a context belongs to: the flow runtime puts the running flow's and node's IDs on the context of every node (Process and trigger Start). Agent nodes name themselves with it when they call tools (AgentCaller).

func NodeInfoFromContext

func NodeInfoFromContext(ctx context.Context) NodeInfo

NodeInfoFromContext returns the node ctx belongs to, or the zero NodeInfo outside a flow runtime (a node test, a nil ctx).

type NodeTypeInfo

type NodeTypeInfo struct {
	Type          string             `json:"type"`                    // Unique identifier (e.g., "trigger-interval")
	Name          string             `json:"name"`                    // Human-readable name (e.g., "Interval Timer")
	Description   string             `json:"description"`             // Brief description of what the node does
	Documentation string             `json:"documentation,omitempty"` // Detailed markdown documentation
	Category      types.NodeCategory `json:"category"`                // input, processing, or output
	Inputs        []types.Port       `json:"inputs"`                  // Input port definitions
	Outputs       []types.Port       `json:"outputs"`                 // Output port definitions
	Config        *ConfigSchema      `json:"config,omitempty"`        // Configuration schema
	Icon          string             `json:"icon,omitempty"`          // Icon name for UI
	Risk          Risk               `json:"risk"`                    // What the node can affect; every registered type declares it
	// OutputsFrom names an array-of-strings setting whose items are extra
	// output ports (ID and name = the item) after Outputs (ADR-0040; see
	// ConfigOutputs). The registry refuses a name that is not an "array"
	// setting of Config.
	OutputsFrom string `json:"outputsFrom,omitempty"`
}

NodeTypeInfo contains metadata about a registered node type.

func List

func List() []NodeTypeInfo

List returns all node types from the default registry.

type Registry

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

Registry manages node type registration and instantiation.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new empty Registry.

func (*Registry) Count

func (r *Registry) Count() int

Count returns the number of registered node types.

func (*Registry) Create

func (r *Registry) Create(nodeType string, config map[string]interface{}) (Node, error)

Create instantiates a new node of the given type with the provided configuration.

func (*Registry) Derive

func (r *Registry) Derive(override func(info NodeTypeInfo, factory NodeFactory) NodeFactory) *Registry

Derive returns a new registry with the same node types and infos, whose factories are chosen by override: it is called once per type with the type's info and registered factory and returns the factory the new registry uses, or nil to keep the original (a nil override keeps every original). The infos are copied as registered (no factory is called again), and r is never modified, before or after: the dry-run builds its stubs this way without touching the global registry.

func (*Registry) Get

func (r *Registry) Get(nodeType string) (NodeTypeInfo, bool)

Get returns information about a registered node type.

func (*Registry) Has

func (r *Registry) Has(nodeType string) bool

Has checks if a node type is registered.

func (*Registry) List

func (r *Registry) List() []NodeTypeInfo

List returns information about all registered node types.

func (*Registry) ListByCategory

func (r *Registry) ListByCategory(category types.NodeCategory) []NodeTypeInfo

ListByCategory returns all node types in the specified category.

func (*Registry) Register

func (r *Registry) Register(info NodeTypeInfo, factory NodeFactory) error

Register adds a new node type to the registry. The factory function will be called to create new instances of the node.

func (*Registry) Unregister

func (r *Registry) Unregister(nodeType string)

Unregister removes a node type from the registry.

type Replier

type Replier interface {
	Reply(correlationID string, payload any, isError bool) bool
}

Replier delivers the reply of a called run (a tool call). Reply reports whether the payload became the call's result: only the first reply of a run that is still waiting wins; replies for unknown or finished correlation IDs (e.g. a run not started by a call) return false. The payload is serialized inside the call, so the caller may keep mutating it afterwards. A payload that cannot be serialized, or whose JSON exceeds the runtime's maximum result size, is not a result: Reply returns false and, unless a later reply wins, the call ends as an error explaining why.

func ReplierFromContext

func ReplierFromContext(ctx context.Context) Replier

ReplierFromContext returns the Replier of the flow runtime that owns ctx (the context nodes receive in Process). It is never nil: outside a runtime it returns a Replier whose Reply always reports false.

type Retryable

type Retryable interface {
	Retryable() bool
}

Retryable is implemented by errors that the flow runtime is allowed to retry.

By default an error is NOT retryable: the runtime only re-executes a node when its error explicitly reports Retryable() == true. This makes retries opt-in so that side-effecting actions (HTTP POST, shell commands, etc.) are never blindly re-run — preventing duplicate side effects — while genuinely transient failures (network blips, 5xx on idempotent requests) can still be retried by wrapping them with Transient.

type Risk

type Risk string

Risk classifies what a node type can affect outside the flow. It drives the risk of MCP tools built from flows and the agent policies.

const (
	// RiskSafe nodes only compute, read local state or log.
	RiskSafe Risk = "safe"
	// RiskExternal nodes send data to other services (HTTP, MQTT, e-mail,
	// chat/notification services).
	RiskExternal Risk = "external"
	// RiskPrivileged nodes act on the host itself: shell commands, files,
	// databases and hardware (GPIO, I2C).
	RiskPrivileged Risk = "privileged"
)

func (Risk) Valid

func (r Risk) Valid() bool

Valid reports whether r is one of the declared risk levels.

type Sandbox

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

Sandbox is carried by the context of a sandboxed execution (a dry-run or a node test, see flow.DryRun) and lets the nodes bound what they do there:

  • data: no single value a node generates may exceed the per-value cap, and all of them together (strings an expression builds, rendered templates, outputs and their copies) draw on one budget (Charge, ChargeValue, CheckValue). Once a charge fails the sandbox is Exceeded and the caller ends the execution;
  • goroutines: work a node runs in a goroutine that may outlive its call (an expression evaluation it stopped waiting for) is started with Go, so the caller can wait for it (Wait) before it lets another sandboxed execution start.

Outside a sandbox (SandboxFrom returns nil) nodes behave as usual.

func NewSandbox

func NewSandbox(maxValue, budget int64) *Sandbox

NewSandbox returns a sandbox where no value may exceed maxValue bytes and all charges together may not exceed budget bytes.

func SandboxFrom

func SandboxFrom(ctx context.Context) *Sandbox

SandboxFrom returns the sandbox ctx runs in, or nil outside one (or for a nil ctx).

func (*Sandbox) Busy

func (s *Sandbox) Busy() bool

Busy reports whether a goroutine started with Go is still running.

func (*Sandbox) Charge

func (s *Sandbox) Charge(n int64) error

Charge spends n bytes of generated data: it fails with ErrSandboxLimit (and marks the sandbox exceeded) when n is over the per-value cap or the budget is spent. Call it before generating the data.

func (*Sandbox) ChargeValue

func (s *Sandbox) ChargeValue(v any) error

ChargeValue is Charge for the estimated size of v.

func (*Sandbox) CheckValue

func (s *Sandbox) CheckValue(v any) error

CheckValue fails with ErrSandboxLimit when v (sized like its JSON, see EstimateSize) is over the per-value cap. It spends nothing.

func (*Sandbox) Exceeded

func (s *Sandbox) Exceeded() bool

Exceeded reports whether a charge or a limit was refused: the execution went over a limit and its caller should end it.

func (*Sandbox) Go

func (s *Sandbox) Go(fn func())

Go runs fn in a goroutine that Wait waits for.

func (*Sandbox) Limit

func (s *Sandbox) Limit(n int64) error

Limit fails with ErrSandboxLimit, and marks the sandbox exceeded, when a value of n bytes would be over the per-value cap (a value growing in pieces, each of them charged). It spends nothing.

func (*Sandbox) MaxValueBytes

func (s *Sandbox) MaxValueBytes() int64

MaxValueBytes is the largest value, in bytes, a node may generate.

func (*Sandbox) Refusals

func (s *Sandbox) Refusals() int64

Refusals counts the charges and limits refused so far: a caller compares it before and after a node ran to tell whether that node went over a limit (a node that cannot return an error, such as a template that stopped expanding, is caught this way).

func (*Sandbox) Wait

func (s *Sandbox) Wait()

Wait blocks until every goroutine started with Go has returned.

type SecretReferencer

type SecretReferencer interface {
	// SecretReferences returns, by config property, the names of the
	// secrets that property references, in order of appearance.
	SecretReferences() map[string][]string
}

SecretReferencer is implemented by nodes with settings that resolve the secrets they reference ({{secret.NAME}}) when they run, but that a deploy does not refuse without them: optional credentials (an MQTT or SMTP username and password), where an undefined secret becomes an empty value, and an HTTP request's URL and headers, where it fails the request when it runs. Lint warns about each undefined one (flow.IssueUnresolvedSecret) and the deploy response carries the warning, so the admin learns at deploy time rather than from a failed or unauthenticated run. Settings whose secrets are required are SecretRequirer's, not listed here. Generic templates never resolve secrets and are not listed either.

type SecretRequirer

type SecretRequirer interface {
	// RequiredSecrets returns, by config property, the names of the
	// secrets that property references, in order of appearance.
	RequiredSecrets() map[string][]string
}

SecretRequirer is implemented by nodes with settings that cannot work without the secrets they reference ({{secret.NAME}}): a bot token, a webhook URL, a database DSN. Deploy refuses a flow (a validation error, 400) while one of these secrets is not defined, instead of deploying it and failing every execution. The values are resolved when the node runs, through its context (secrets.FromContext), never at deploy; the dry-run does not check (its secret store is empty by design and it reports the referenced names instead).

type ToolArgumentsError

type ToolArgumentsError struct {
	Issues []toolschema.Issue
}

ToolArgumentsError lists why a tool's arguments were refused, each issue located by a JSON pointer into the arguments ("" for the whole value).

func (*ToolArgumentsError) Error

func (e *ToolArgumentsError) Error() string

func (*ToolArgumentsError) Unwrap

func (e *ToolArgumentsError) Unwrap() error

Unwrap makes errors.Is(err, ErrInvalidToolArguments) hold.

type ToolCallOutcome

type ToolCallOutcome struct {
	// Status is ToolCallOK, ToolCallError or ToolCallRunning.
	Status string
	// Result is the reply, redacted and capped as agents see results.
	Result json.RawMessage
	// Error is the run's error (Status ToolCallError), redacted as agents
	// see errors.
	Error string
}

ToolCallOutcome is the outcome of a run an agent node's call started.

type ToolCaller

type ToolCaller interface {
	// AgentTools returns the tools caller may call now, in the order its
	// Tools lists them; a listed name that is not published, or that the
	// rules refuse, is left out.
	AgentTools(caller AgentCaller) []AgentTool
	// CallAgentTool calls the tool name with args and waits, at most until
	// ctx ends, for the outcome of the run it starts. An error means no
	// outcome: the call was refused before any run started (an unknown or
	// unlisted tool, a forbidden one, invalid arguments, a limit or a
	// cooldown), or ctx ended. Its message never quotes a secret and may
	// be shown to the model.
	CallAgentTool(ctx context.Context, caller AgentCaller, name string, args map[string]any) (ToolCallOutcome, error)
}

ToolCaller lists and calls the flow tools of agent nodes.

func ToolCallerFromContext

func ToolCallerFromContext(ctx context.Context) ToolCaller

ToolCallerFromContext returns the tool caller of the runtime that runs the node. It is never nil: outside a runtime that has one, and in a sandboxed execution (a dry-run or a node test) whatever its context carries, it lists nothing and refuses every call with ErrNoToolCaller.

type ToolProvider

type ToolProvider interface {
	ToolSpec() ToolSpec
}

ToolProvider is implemented by nodes that publish an MCP tool.

type ToolSpec

type ToolSpec struct {
	// Name is the MCP tool name, unique across running flows.
	Name string
	// Title and Description are shown to agents.
	Title       string
	Description string
	// InputSchema validates the call arguments (the closed subset).
	InputSchema *toolschema.Schema
	// OutputSchema is the optional JSON Schema (an object schema) of the
	// reply, advertised as is; nil when the tool declares none.
	OutputSchema json.RawMessage
	// Timeout is how long a call waits for the reply before it reports
	// "running".
	Timeout time.Duration
	// Confirm is one of ToolConfirmNone, ToolConfirmClient, ToolConfirmAdmin.
	Confirm string
	// Idempotent is the admin's idempotentHint.
	Idempotent bool
	// MaxConcurrent caps the calls of this tool running at once. 0 means
	// the admin left it unset: the default is ToolDefaultMaxConcurrent, or
	// ToolReadOnlyMaxConcurrent for read-only tools, decided by the flow's
	// risk analysis (see EffectiveMaxConcurrent).
	MaxConcurrent int
	// Cooldown is the minimum time between the end of a call and the next.
	Cooldown time.Duration
}

ToolSpec is what a callable trigger (trigger-tool) publishes about itself: the tool an agent sees and the limits the service layer applies to calls. It is read from a node instance after the flow validated its config. The effective risk and annotations of the tool are computed per flow, not declared here (ADR-0013).

func (ToolSpec) EffectiveMaxConcurrent

func (s ToolSpec) EffectiveMaxConcurrent(readOnly bool) int

EffectiveMaxConcurrent returns the concurrency limit of the tool: the admin's MaxConcurrent, or the default for a read-only tool (readOnly comes from the flow's risk analysis) or any other tool when it is unset.

type TransientError

type TransientError struct {
	Err error
}

TransientError wraps an error to mark it as retryable by the runtime.

func (*TransientError) Error

func (e *TransientError) Error() string

Error implements the error interface.

func (*TransientError) Retryable

func (e *TransientError) Retryable() bool

Retryable reports that this error is safe to retry.

func (*TransientError) Unwrap

func (e *TransientError) Unwrap() error

Unwrap exposes the wrapped error for errors.Is/errors.As.

type TriggerNode

type TriggerNode interface {
	Node

	// Start begins the trigger's activity.
	// Messages should be sent to the provided channel.
	// The context is used for cancellation.
	// This method should return quickly; long-running operations should be in goroutines.
	Start(ctx context.Context, out chan<- *types.Message) error

	// Stop gracefully stops the trigger.
	// This should clean up any resources and stop any goroutines.
	Stop() error
}

TriggerNode is a specialized node that can initiate flow execution. Trigger nodes are typically input nodes like timers, webhooks, or event listeners.

Directories

Path Synopsis
Package builtin provides the standard set of built-in nodes for PiWorker.
Package builtin provides the standard set of built-in nodes for PiWorker.

Jump to

Keyboard shortcuts

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