FlowBuilder and run it with the static
FlowExecutor.execute(flow, context, onEvent?).
llmCall step’s model is its own model, else the agent’s
settings.model, else the provider’s default (gpt-4o-mini above). Either
setting is the provider’s bare model id, such as 'gpt-4o', handed to
provider.generate() as is: not a 'openai/gpt-4o' spec, which only
resolveProvider() and createAgent({ model }) read. An llmCall returns
the reply text; it has no structured-output (schema) option. For a typed
result, parse the text in a later step, or call an agent that has a
structured output as a tool (see Running an agent in a flow).
Template values
A{{name}} placeholder in a prompt, a throw message or a tool argument
is replaced by the variable’s text:
- A string is used as is; a number or boolean is its text (
0is'0'); a variable that is not set, or isnull, is''. - An object whose only field is
text(an MCP tool result,{ text }) is that text, and so is a raw MCP result ({ content: [{ type: 'text', text }] }, its text parts joined by newlines). - Any other object or array is its JSON, so a
toolCallresult stored inoutputVariablereads{"city":"Oslo","temp":4}in the next prompt, not[object Object]. - A dotted path reads into an object or array:
{{weather.city}},{{results.0.title}}. Only own properties are read ({{res.constructor}}is''), and a missing step on the path is''.
evaluator step stores its result in outputVariable too, like
llmCall and toolCall.
Node types
FlowExecutor runs these node types:
oneOf conditions and evaluator expressions use a small, safe expression
language (no eval, no host code; {{name}} placeholders are bound as
values, never pasted into the expression). Its grammar and failure rules are
in Flow expressions.
Tool calls
AtoolCall step passes the same checks as a tool call in an agent run before
its tool runs:
- Its arguments, after
{{variable}}interpolation, are validated against the tool’s input schema. Arguments that do not match fail the step withLOUSHO_TOOL_ARGS_INVALID, listing each problem, and the tool is not called. - The flow context’s
permissions,permissionModeandonPermissionDecisionapply as they do forcreateAgent()(see Permission policies and Permission modes). - A call that needs approval (the tool’s
needsApproval, or anaskrule) is decided by the context’sapprovecallback, which has the same shape ascreateAgent({ approve }).true(or a note) runs the tool.falserefuses it withLOUSHO_FLOW_TOOL_DENIED. Whenapprovereturns'defer', or there is noapprovecallback, a durable run pauses until a person decides (see Pausing for approval). A run that is not durable refuses the call withLOUSHO_FLOW_TOOL_DENIED. The tool is never run unapproved.
Argument values
An argument string that is exactly one placeholder,'{{name}}' or
'$name', passes the variable’s value as it is: a number stays a number, an
object stays an object; '{{res.count}}' passes that field’s value. So arguments: { n: '{{n}}' } with n = 5 passes
5 to a tool whose schema is z.number(). This also applies inside arrays
and nested objects. Any other string is interpolated as text:
'n is {{n}}' becomes 'n is 5'. A placeholder of a variable that is not
set stays as before: '{{missing}}' is '', and '$USD' (no variable
named USD) is the literal string '$USD'.
required input, or a value of the wrong type, fails the flow with
LOUSHO_VALIDATION_FAILED.
Cancelling a flow
Passsignal in the context to cancel a run. It is checked before every step:
once it is aborted, no further step starts and the flow fails with the signal’s
reason. The step that is running gets the signal too: an llmCall passes it
to the model request, and a toolCall hands it to the tool as ctx.abortSignal.
parallel step fails, its sibling branches are cancelled
the same way: they start no further step, and their running llmCall or
toolCall gets an aborted signal. The flow returns the first branch’s error
only once every branch has settled, so no tool runs and no event is added to
result.events after the result is returned. A tool that ignores
ctx.abortSignal still runs to the end, and the flow waits for it.
result.usage sums the model usage (promptTokens, completionTokens,
totalTokens, and cachedInputTokens, reasoningTokens, costUsd when
reported) of every llmCall in the run, including a failed one.
A step without an id gets one that is unique within the run (step-1,
step-2, … in the order the steps start), so step-start and
step-complete events can be paired by stepId.
Retries and time limits
Any node can haveretry and timeoutMs. That includes llmCall,
toolCall, sequence, parallel and forEach.
retry: { maxAttempts, backoffMs? }runs a failing node again, up tomaxAttemptsattempts in all. It waitsbackoffMs * 2^(attempt - 1)ms before each retry (default0). Each failed attempt that is retried emits astep-retryevent with{ attempt, maxAttempts, delayMs }and the attempt’serror. Only the last failure emitsstep-error. A cancelled run (signal) is not retried, and neither is a model failure that retrying cannot fix (see below).timeoutMsfails an attempt that runs longer withLOUSHO_OPERATION_TIMEOUT(aTimeoutError). The attempt’s model request or tool call gets an aborted signal. A timed-out attempt is retried like any other failure. A tool that ignoresctx.abortSignalkeeps running in the background.
llmCall whose model request fails fails with the same
CompactedLLMProviderError an agent run rejects with, not the provider SDK’s
raw error: code is LOUSHO_PROVIDER_RATE_LIMITED for a 429 and
LOUSHO_PROVIDER_REQUEST_FAILED otherwise, and compacted holds
{ error, category, retryable, statusCode?, providerName? }. A failure with
retryable: false (an 'auth-failure' such as a 401 or a bad API key, a
'quota-exceeded', a 'context-length-exceeded') fails the step at once,
without using its remaining retry attempts; a rate limit, a timeout or a 5xx
is retried.
Invalid values (maxAttempts < 1 or not an integer, a negative backoffMs,
a timeoutMs <= 0) fail the step with LOUSHO_FLOW_INVALID.
Durable runs
Pass acheckpointStore and a runId to make a run durable. The run’s
variables, the nodes that completed (with their results), the branch each
oneOf took and the usage so far are saved under runId after every node
that completes, and again when the flow finishes. A new run is also saved
once before its first step (after its inputs are checked), so a run whose
first step fails can be resumed too. Any CheckpointStore works,
such as memoryStore().checkpoints or a SQLite store (see
Durable execution).
After a crash, or when a step failed, continue the run with
FlowExecutor.resume(flow, context). Pass the same checkpointStore and
runId. Completed nodes are not run again: each one returns its saved result,
and a oneOf takes the branch it took before. Everything else runs as usual,
from the saved variables. result.usage and result.steps include the
earlier attempts.
- A node is identified by its place in the flow, not its
id. Resume a run with the flow that started it. A resume with a flow of anothercodeis refused withLOUSHO_CONFIG_INVALID. The run also saves its flow’s structure (each node’s type,id, tool or agent, and their order); a resume with the samecodewhose steps were added, removed or moved is refused withLOUSHO_FLOW_CHANGED, since the saved results would land on the wrong steps. Editing a prompt, condition or other setting keeps the structure. Runs saved before this check resume without it. - Resuming a finished run returns its saved result with no events, and runs
nothing.
execute()with therunIdof a finished run starts a new run.execute()with therunIdof an unfinished run is refused withLOUSHO_CONFIG_INVALID; resume it instead, or use a newrunId. - A run with no checkpoint is refused with
LOUSHO_CHECKPOINT_NOT_FOUND. A run whose declared inputs were invalid saved none: callexecute()again with valid inputs. - Only one call runs a
runIdat a time. Whileexecute()orresume()runs, it holds a run lease on therunIdin the store, the same lease an agent run takes (see Durable execution). Anotherexecute()orresume()of thatrunIdis refused withLOUSHO_SESSION_BUSY, and runs nothing. That holds in this process, in another process or replica on the same store, and through another store object over the same data. The lease is renewed while a long step runs, and released when the call returns. If the process holding it died, the lease expires (in 60 s at most), and then the run can be resumed. A customCheckpointStorewithoutacquireLeaseruns without leases. - A node that completed is only skipped once its checkpoint was saved, and
its
step-completeevent is emitted after that save, so a step reported complete is never run again on resume. A node interrupted while running (anllmCallor atoolCall) runs again, so make side-effecting tools idempotent. - Variables and node results must survive
structuredClone, so no functions and no class instances. - The item and index of a
forEachiteration are not saved. An interrupted iteration runs again with its item. Completed iterations are skipped.
result.status is 'completed', 'failed', or 'awaiting-approval' (see
below).
Pausing for approval
In a durable run, atoolCall that needs approval pauses the flow when
approve returns 'defer' or there is no approve callback. The tool is not
run. The run is saved with status 'awaiting-approval', and execute() (or
resume()) returns:
status: 'awaiting-approval'andsuccess: false, with noerrorapprovalId: the id to decidependingApproval:{ approvalId, nodeId, toolName, args }, the call waiting for the decision
step-error or flow-error and is
not retried. If the paused step is in a parallel node, its sibling branches
are cancelled. Steps they completed are kept, and the rest run again on resume.
To continue, pass the decision to resume():
- Approved: the paused step runs its tool with the saved arguments, and
approveis not asked again. - Rejected: the step fails with
LOUSHO_FLOW_TOOL_DENIED, likeapprovereturningfalse. - Used once: after one resume, the run no longer waits for that approval. A later resume runs the step again, so it needs a new decision.
- A resume of a paused run without
approval:LOUSHO_SESSION_AWAITING_APPROVAL. - A resume with another
approvalId, or with an approval for a run that is not paused:LOUSHO_APPROVAL_NOT_FOUND.
approvalId (or read checkpoint.flow.pendingApproval from the store) to
decide later.
Approval steps
Anapproval step is a human gate of its own - no tool call needed. Its
message ({{variable}} placeholders interpolated) is what the approver is
asked, and the context’s approve callback decides, exactly as for a
toolCall that needs approval. The callback sees a call whose toolName is
'flow_approval' and whose args are { message, stepId } (stepId is the
node’s id, or its place in the flow).
approvereturningtrue(or a note) continues the flow;outputVariablegetstrue.falsefails the step withLOUSHO_FLOW_TOOL_DENIED, as do'defer'and a missingapprovein a run that is not durable (fail closed).- In a durable run,
'defer'or noapprovepauses the flow the same way atoolCallpause does (Pausing for approval):pendingApproval.toolNameis'flow_approval'andpendingApproval.args.messageis the interpolated message. Resume it with the decision:
Running an agent in a flow
Anagent step calls a createAgent() agent registered in the context’s
agents map, by name. The agent runs its own loop — its model, tools,
guardrails and approvals — and the step stores its reply text:
inputis the message sent to the agent;{{variable}}placeholders are replaced (default'{{input}}', the flow’sinputvariable).- An
agentstep emitsllm-callandllm-responseevents carryingdata.agent(notdata.model), and takesretryandtimeoutMslike any other step. Its reply is stored as text; the agent’s usage is in itssend()result, not the flow’sresult.usage. - A step naming an agent that is not in
agentsfails withLOUSHO_FLOW_INVALID, naming the keys that are registered. - An agent whose run pauses for an approval (a
needsApprovaltool with no approver) fails the step withLOUSHO_FLOW_EXECUTION_FAILED: agent steps cannot pause a flow. Decide the agent’s tools with permissions or anapprovecallback on the agent. - Traced, the agent’s
invoke_agentspan nests under the step’sflow.node agentspan.
agent config in the
context ({ name, prompt?, settings }); passing a createAgent() agent as
context.agent is refused with LOUSHO_CONFIG_INVALID.
Instead of an agent step, you can register a tool that calls
agent.send() and call it in a toolCall step — the call then goes
through the flow’s permission and approval gates, and its result can be a
typed value rather than text:
llmCall step is simpler.
The step node type (StepNode, { type: 'step', agent, input }) is a
shape that visual editors produce. FlowExecutor does not run it: a flow
that reaches one fails with LOUSHO_FLOW_INVALID — use an agent step.
Flows, sub-agents or skills?
Use a flow when the pipeline is known in advance; use sub-agents when the model should decide what to delegate, and skills when the same agent just needs extra instructions for some tasks. See Sub-agents, skills or flows?. Flows are traced like agent runs (see Tracing and observability).Flow expressions
oneOf branch conditions (and the Agent Forge router node’s branch conditions)
and evaluator node expressions are evaluated by a small built-in expression
evaluator. It never compiles or runs host code: there is no eval,
new Function or vm in src/flows. {{name}} placeholders are bound as
values, never pasted into the expression text: a bare {{score}} >= 90 uses the
variable’s value, and inside a string literal, '{{classify}}' === 'refund'
interpolates the value’s text into that literal after the expression has been
tokenized. A variable whose value contains quotes, backslashes or operators
(for example x' === 'x' || 'a) is therefore just data and cannot change the
condition’s logic. A missing or null variable is an empty string inside a
literal; used bare it contributes nothing, so {{missing}} >= 90 is a syntax
error and the condition counts as not matched. The expression is evaluated
against the flow’s variables.
Precedence, loosest to tightest:
||, &&, equality, relational, + -,
* / %, unary, member access.
Not supported, and rejected with an ExpressionError that names the
expression, the character position and this list of supported forms: any other
function or method call, assignment (=, +=, ++), ternaries, template
strings, object/array literals, access to constructor, __proto__ or
prototype, and globals (process, require, globalThis, …). Only a
flow’s own variables, and only their own properties, are reachable.
Failure behaviour is unchanged: a oneOf condition that cannot be evaluated
counts as not matched (false), and an evaluator expression that cannot be
evaluated fails the flow with Failed to evaluate expression: ..., including
the ExpressionError detail.