Flow language¶
Flow composes actions into a new action. A host loads a document with application code or receives and checks it at runtime, then resolves it against the current action registry. Documents cannot import code or call capabilities outside that registry.
This page is the language reference and Python API. Start with
Compose actions through streamed data for a guided example.
a11.flow.REFERENCE provides a compact version suitable for model prompts.
Find a topic¶
Complete flow¶
flow research {
describe "Search, read the best hits, and answer from them."
in question: string required
out answer: string
out sources: string stream
header "x-a11-deadline" as deadline
search = run web-search(query: question, limit: 3)
brief = run llm-summarize(question: question)
with "x-a11-deadline": deadline
nodes fetched {
for hit in search.hits parallel 2 {
page = run web-fetch(url: hit.url)
hit.url -> sources
page.text | truncate 200 -> brief.pages
}
}
brief.summary -> answer
}
x = run action(port: source) runs a local action and binds its ports to x.
x = call action(...) dispatches an action on the flow's attached stream.
source -> destination pipes a stream into a node.
brief starts before pages arrive. The loop feeds its streaming pages port,
which A11 closes after the loop's last writer finishes. Steps run concurrently;
use after, wait, or close to require an order.
A port carries one value unless declared stream, and is optional unless
declared required. Keywords accept lower or upper case, such as for and
FOR. Mixed-case words are identifiers.
Port values¶
in question: string required
in frames: list[a11::NodeFragment] stream
out audio: a11::sdk::AudioBuffer stream
out raw: "application/x-msgpack"
Besides the primitive names — int, bool, number, string,
object, bytes, and null — a type may use an unquoted
host type such as a11::sdk::AudioBuffer. Its wire tag remains
a11.sdk.AudioBuffer; qualified host types are
preserved without importing the module that defines the type. Brackets specify
container contents, as in list[string] and list[a11::NodeFragment]. A quoted
type is a media type that describes the representation.
list is a prelude alias of std::list; prefer list[T] for types and
list(value) for conversion. Neither requires an import, and the qualified
spelling remains valid.
Descriptions¶
Descriptions help callers, including models, decide when to use a flow. They may follow a declaration or use a multiline string:
flow research {
describe """
Search the web, read the best hits, and answer from them.
Costs one search and up to `budget` fetches.
"""
in question: string required
"What to find out — as long as this needs to be, on its own line."
}
A """ string preserves line breaks after dedenting. Dedenting removes a blank
first line, a whitespace-only final line and its preceding break, and the common
indentation from all remaining lines. Additional indentation on individual
lines remains. Escapes match ordinary strings.
Both string forms decode \0 (NUL), \a (bell), \b (backspace),
\f (form feed), \n (newline), \r (carriage return), \t (tab),
\v (vertical tab), \", \', and \\. Other escapes yield the character
after the backslash. Native semantic tokens highlight escape sequences
separately from the surrounding string.
A description may also appear alone on the line below a port, header, or
describe declaration. A string followed by another token, such as
"a literal" -> out, remains a statement.
a11 flow fmt indents a description under its declaration and lines up the
columns of a run of declarations around it.
Constants¶
Use const [TYPE] name = VALUE in a flow to capture one scalar value when
execution reaches the declaration. The name cannot be reassigned. Lists and
records remain immutable as Flow values; projections do not provide a mutable
reference to their contents. A module-level declaration can use
const [TYPE] name [exported] = VALUE and can be imported like another public
member. Module initializers must be closed expressions built from literals,
lists, records, and other module constants, so they are available when types,
field constraints, and header defaults are resolved. kThisLetterCase is the
recommended naming style, not a parser rule.
const kRetryLimit = 3
struct Job { retries: int 0..kRetryLimit }
flow main {
in proposed: int
out result: int
const kSelected = proposed
kSelected -> result
}
Constructing typed values¶
A flow can construct a registered type such as Interaction or AudioBuffer
from fields with TYPE{...}:
a11::sdk::Interaction{
role: "user",
content: [std::to_chunk({"role": "user", "content": [{"type": "text", "text": said}]})]
}
EXPR as TYPE performs the same conversion and supports generic types such as
pieces as list[string]. Both forms validate the value, apply defaults, and
report incompatible fields.
to_chunk and from_chunk create and read a
Chunk. Content-bearing types store their content in
chunks.
Available types come from the host's serialisation registries. A flow cannot
import types. TYPE{...} is unavailable where { opens a block, including an
if condition or a for source. Parentheses permit a typed construction in
these positions: if (T{done: true}).done {.
Action composition¶
Local runs and remote calls¶
run some-action(...) executes a handler registered in the local process.
call some-action(...) dispatches the action on the flow's attached stream.
The verb selects the execution location:
run requires a local handler. call requires only a local schema for
resolution and always dispatches to the peer, even when a local handler has the
same name.
The deployment determines which verb is available.
flow_actions reports this through each entry's
runnable field.
try goes in front of either: try run, try call.
Either verb may name another flow in the same file without a registry entry:
flow ask-twice {
in question: string
out answers: string stream
first = run ask(question: question)
second = run ask(question: question)
first.answer then second.answer -> answers
}
flow ask {
in question: string
out answer: string stream
said = run answer-question(question: question)
said.text -> answer
}
A program is a set of flows, so declaration order does not affect execution.
Compilation checks calls between flows against their declared ports. This keeps
reusable compositions in one source file with a single entry point for
flow_run and the gateway.
Discarding stream values¶
An undrained output port stalls its producer. The runtime drains declared call outputs that the flow does not reference.
skip n port removes values from the node before fan-out. Every reader starts
after those values. In comparison, | drop 1 trims only its pipeline:
rows = run read-csv(path: path)
skip 1 rows.lines
rows.lines | count -> data-rows
rows.lines -> passed-through
Counts on one node are additive. skip 1 x and skip 2 x remove three values,
independent of statement order, because compilation sums the counts. The target
must be a port or node; pipelines are reader-specific.
-> _ executes a pipeline and discards its result:
Every page is summarised and every line is logged, but the result is discarded.
_ is valid only as a destination; it cannot be bound or read. _ = node(),
_ | count -> n, close _ and in _: string are each refused while the flow is
compiled. It may stand beside a real destination (a -> b, _), where it adds a
reader that discards its values.
Putting a stream back together¶
| group EXPR is batch with a question instead of a count: values gather into
a list, and the list closes when the expression holds of the value just added.
For example, it can assemble partial utterances into sentences:
Any partial final group is emitted when the stream ends.
| then SOURCE concatenates this stream with the source that follows.
then and where may omit the pipe: history then asked and
hits where it.ok. Every other stage requires |, which distinguishes stage
names from identically named ports.
| flatten expands a stream of lists into their values.
Lists are expanded and other values pass through unchanged, so flatten also
accepts a mixed stream.
| context PREDICATE before N after M emits lists of matching items and their
neighbors. The first match includes up to N preceding items. Each match among
the next M items resets the trailing count, extending the same excerpt until
M consecutive nonmatches arrive or the source ends:
The predicate runs once on every original item. Normal EOF flushes a shorter
excerpt; upstream failures propagate without flushing the active excerpt.
Separate excerpts may share preceding items when a later match falls outside
the earlier trailing window. With after 0, each match emits immediately.
Counts are expressions evaluated once outside it and must be nonnegative
signed 32-bit integers. Storage holds up to N preceding items plus the active
excerpt. A chain of nearby matches can grow that excerpt indefinitely; limit
potentially endless sources upstream.
Add numbered to wrap each item as {index, value}. Indices count every source
item, including unmatched items, from 1. base EXPR changes the starting index
and evaluates once outside it; it must be an integer. Negative bases are
accepted, and signed 64-bit index overflow fails the stage:
The stage supports try context ... failures into errors: predicate errors become
nonmatches, while their items remain available as context. Count, base, index,
and upstream errors still fail. Evaluation is sequential; parallel and
unordered are rejected.
| window N is batch with the lists overlapping: one list of the last N
values per value, once N have arrived.
Unlike batch, a window can detect patterns that span arbitrary batch
boundaries. It retains at most N values, so memory use remains bounded for an
unending stream. A stream shorter than N produces no window, while batch
may emit a shorter final list.
interleave(a, b, ...) reads all sources concurrently and emits each value on
arrival. zip reads its sources in step and emits one tuple per round:
Values retain their arrival order across sources. The combined stream ends when every source ends; a source failure ends it with that status.
Reducing a stream to one value¶
Arithmetic reducers calculate one result from a complete stream:
sum, min, max, and avg read the whole stream and yield one value. With no
expression they use each value directly; | sum it.price is equivalent to
| map it.price | sum. Durations add and average as durations. For an empty
stream, min, max, and avg emit no value, while sum emits 0.
| fold defines a custom reduction:
The name is bound to the previous accumulated value and it to the current
input. The starting value is a literal, not an expression: otherwise
fold 0 as total could be parsed as a cast of 0 to a type called total.
A record literal is allowed because its braces remove this ambiguity.
Carrying state along a stream¶
| scan uses the same syntax as fold. fold yields one value when the stream
ends; scan yields the current accumulator for each input value.
scan carries state forward for each stream value. repeat also carries state,
but rereads its stream from the start on each pass; for reads one value per
pass but does not carry state between passes. scan retains one state value,
not the complete stream.
The state may also be a record:
lines
| scan {"inside": false, "line": ""} as s,
{"inside": std::startswith(it, "BEGIN") or (s.inside and not std::startswith(it, "END")),
"line": it}
| where it.inside and not std::startswith(it.line, "BEGIN")
| map it.line
-> body
The stage uses constant memory by retaining only one state value.
| sort puts a stream in order:
sort buffers the complete stream before emitting values. Comparison follows
<; by selects the comparison value, desc reverses the order, and equal
values retain their input order.
Stream timing¶
Two stages control stream timing.
timeout limits the gap between values. A longer gap ends the flow with
deadline_exceeded. Use wait ... timeout to limit an entire step.
pace delays values to enforce a minimum interval without dropping them. The
producer blocks when the buffer is full.
Working on several values at once¶
A per-value stage can bound its concurrent work:
Downstream stages still receive values in input order. The parallel stage
reorders completed work before emitting it. Add unordered to emit results as
soon as they complete:
Use parallel for substantial per-value work such as host round trips,
coercions, or large chunks. It adds overhead to simple field access. Stages that
gather or order values do not accept parallel.
Text and time¶
strformat("%s of %s", got, wanted) uses printf conversions: %s for text;
%d, %f, and %x for numbers; flags and precision such as %-8s and
%06.2f; %2$s for a positional value; and %% for a literal percent.
| strformat "fmt" abbreviates | map strformat("fmt", it).
Flow uses printf-style conversions because str.format reads attributes, which
could escape sandboxing for untrusted expressions. A printf conversion operates
only on supplied values. A conversion with no corresponding value remains
unchanged to expose the invalid conversion.
utf8encode(text) produces bytes for an application/octet-stream input.
utf8decode(bytes) produces text for a text/plain input and fails with
invalid_argument when the bytes are malformed. These operations preserve the
distinction between binary ports and text ports; use b64encode and
b64decode when the representation itself is Base64.
Durations are written the way a timeout is — 500ns, 250ms, 30s, 2m,
1h, and compounded as 1m30s500ms — and are ordinary values. now() is the
clock, and the arithmetic is the arithmetic A11's own types allow:
started = node()
std::now() -> started
work = run slow-thing(input: pages)
done = wait work
took = take (std::now() - started)
std::strformat("took %s", took) -> log after done
Steps run concurrently, so source order alone does not delay a clock read.
now() -> started needs no barrier because it records the start. A clock read
that measures produced work requires after; otherwise the compiler reports
flow.barrier.unordered-clock.
An after applies to the complete statement, including arguments. In
run act(p: now() - started) after done, the argument is evaluated after
done.
+ and - are the language's only arithmetic operators. A bare number beside a
duration counts as seconds; seconds(d) returns the numeric value. Subtraction
can produce a negative duration and does not use A11's infinite-timeout
convention. - requires spaces because text-upper is an identifier.
Formatting: %s renders a duration as 1m30s and an instant as RFC 3339. A
unit in the parenthesised spec gives one number — %(ns)d, %(us)d, %(ms)d,
%(s)d, %(m)d, %(h)d — and %(%H:%M:%S)s or %(epoch)d formats an
instant.
duration(x) and time(x) parse the formats described above:
deadline = std::time(header-deadline) # "2026-08-11T09:14:22Z"
budget = std::duration(header-budget) # "1m30s", or a number of seconds
if std::now() + budget > deadline { fail deadline_exceeded "not enough time left" }
These functions accept text from headers, JSON fields, or model output without a separate format string.
Two statements writing to the same node interleave by arrival. Use then when
order matters, such as sending prior conversation turns before the current one.
Reducing data before serialization¶
| truncate 200 shortens each page before writing it to the summariser. Dropped
data is not serialized, sent to a peer, or included in model input. The same
applies to | first 3, | where it.ok, | mime "text/*", and | drop 1.
Value representation¶
| packb writes a value as application/x-msgpack instead of JSON. Existing
MessagePack chunks pass through unchanged, including their type tag. Other
representations are re-encoded.
Header propagation¶
Headers carry call metadata such as model selection, identity, and deadlines.
Nested actions automatically receive their parent's x-a11- headers. Use
forward headers for other headers:
answer = run interact_with_llm(interactions: asked, config: {})
forward headers "authorization", "x-tenant-*"
Names are forwarded unchanged, and * matches a family of names. Missing
optional headers are ignored. Use with "header": expr for computed values. A
with value overrides a forwarded header with the same name.
Local step traffic¶
nodes fetched { ... } gives its calls a private
NodeMap. Their ports and fragments remain
outside the session's node map. For example, four fetched pages can remain local
while one answer returns to the peer. A run step keeps its nodes local unless
it specifies tee; a nodes block also applies to call steps.
Nodes of the flow's own¶
x = node() creates a stream that several loop passes can write and another
step can read. Parentheses distinguish the constructor from an identifier named
node.
best = node()
for url in urls {
page = try run web-fetch(url: url)
page.text | truncate 120 -> best
}
best | first 1 -> text
The node uses the active node map: the enclosing nodes block's map or the
action's map. x = node(existing-id) attaches to an existing node, and x.id
passes its identifier to an action that writes to it:
seen = node()
reader = run take-notes(pages: page.text) with "x-a11-progress-node": seen.id
seen -> progress
close seen after reader
The final after delays close until reader finishes writing through
seen.id. Without the dependency, the node would close immediately. The
compiler reports flow.barrier.wait-lends-node for wait seen in this pattern.
Handle expected failures¶
try converts an expected step failure into a status the flow can handle. It
applies to either call verb:
page = try run web-fetch(url: url)
outcome = wait page
if outcome.ok {
page.text | truncate 120 -> text
} else {
fail unavailable outcome.message
}
wait holds until a call or flow-written node finishes. A bound wait also
returns the outcome. status x returns the same value in an expression, and
close node reads the outcome while ending the named node.
A status is data:
A flow can branch on a status, write it to an output, or raise it again. fail
accepts an Abseil canonical code in lower or upper case (not_found,
NOT_FOUND), a number computed at runtime, or a complete status record. fail
outcome preserves the status; fail invalid_argument outcome.message changes
the code while retaining its message.
Waiting on a failed step ends the flow with that status unless the step used
try.
wait first of a, b holds until the first call finishes and leaves the others
running. wait all of a, b holds until every call finishes. These forms accept
calls; node completion uses wait or close on the node.
A race also produces the zero-based index of the winning call:
won = wait first of primary, backup
wait first of primary, backup -> chosen
n = take (wait first of primary, backup)
wait all of has no single winner, so it is a barrier only.
A failure one value at a time¶
A try on a stage tolerates an item's evaluation failure while the stream
continues. Transform stages drop the failed item; context can retain it as
surrounding context.
The value is dropped and the failure logged once at warning. To handle each
failure, route it with failures into:
Routed failures have the status fields (code, message, and details), the
original item in it, and its zero-based stage input position in seq. A
status cast or status port retains the status fields. Without try, a stage
failure ends the flow.
Loops, branches, and state¶
repeat state = {"round": 0} max 6 {
step = run triage-step(state: state)
state <- step.next
if step.next.done {
step.next.verdict -> verdict
}
} until step.next.confidence >= 0.8
repeat carries one value from each pass to the next: state starts at the
literal and becomes whatever <- names. until (or while) ends the loop, and
max bounds it regardless. One of the two is required because repeat has no
default bound.
Struct field constraints written matching "pattern" use RE2 regular
expressions and search anywhere in the string; use ^ and $ to anchor a
whole value. RE2 supports inline flags and Unicode character classes, and
rejects lookaround and backreferences. matching /pattern/flags accepts the
same regex syntax with optional i, m, and s flags. Both forms are checked
when the Flow is parsed, so invalid patterns produce a declaration diagnostic.
match pulls named fields out of text, as a stage over a stream and as a
function over one value: lines | match "name={name} age={age:int}" turns
name=Alice age=27 into a record with name and age. Literal text matches
itself, a run of spaces or tabs matches any run, and a hole may say what to read
itself as (int, number, bool, word, line, rest, duration, time,
json). The pattern searches anywhere in the input, so it requires no
wildcards. A hole stays on its line unless specified otherwise. The stage drops a
value the pattern does not fit and the function answers null. Where the pattern
is written out, the fields are known: it.name is completed and a typo is
reported.
Slash-delimited /.../ literals are RE2 patterns, with optional i, m, and
s flags. They work with match /pattern/, match all /pattern/,
std::match(/pattern/, text), and std::matches(/pattern/, text).
std::matches_pattern(text, /pattern/) asks only whether a match exists.
std::split(text, /separator/) splits at regex matches, and
std::replace(text, /pattern/, replacement) substitutes every match. In a
regex replacement, $1 and ${name} insert captures; $$ writes $.
Quoted separators and search strings remain literal. Write /\W+/ for a
pattern: in "\W+", string decoding removes the backslash and reports a
warning. Flow uses and, or, and not; diagnostics suggest those forms for
&&, ||, and !.
std::casefold(value) renders a value as text and applies Unicode 17.0 default
full case folding. For example, std::casefold("Straße") is "strasse", and
std::casefold("Σς") is "σσ". It requires valid UTF-8. Folding can expand a
character, but does not normalize Unicode or use locale-specific rules.
std::lower and std::upper change ASCII letters only.
try also goes in front of a pipe. It converts a source or destination
failure into a value instead of ending the flow:
Bind a tried pipe to retain its status. An unbound failed pipe closes its
destination early without exposing the failure to a reader, so the compiler
reports it. A tried stage can route each tolerated failure with
failures into; a tried pipe fails once and stops.
A [s =] [try] { ... } block runs its statements as one step. Statements in a
flow body run concurrently, while a block groups their outcome. Reading a value
blocks only the statements inside the braces. A bound block yields a status like
a call. With try, the flow handles a block failure; otherwise the failure ends
the flow.
for v in [a, b, c] iterates the bare literal's elements one level deep. The
literal is evaluated once; empty literals make no passes. Nested lists remain
individual loop values. Named lists and list-valued pipelines require
| flatten to iterate their elements.
for v in stream runs its block once per value; parallel n runs up to n
passes concurrently. A stream read inside a loop or branch is materialised once
and replayed to every pass. Its buffer grows during reads, so each pass waits
only for the requested value. It does not wait for the source stream to finish.
parallel accepts expressions in loops and per-item stages, for example
parallel workers, parallel settings.workers, or parallel (workers + 1).
The expression is evaluated once when the loop or stage starts and must yield a
positive signed 32-bit integer. Stage results remain ordered unless unordered
is present. Dynamic loop counts retain parallel restrictions on conflicting
outer-variable updates and trailing until/while conditions.
A named loop returns its outcome in the same shape as s = try { .. }:
The loop counts as one writer of an outer node for its lifetime. Its final
release closes taken; the explicit close records that dependency in the
source. for and repeat also accept after.
A for can use until or while. The condition runs after each pass, so a nonempty
source includes the stopping value and finishes its pass. An empty source
evaluates no condition.
The loop stops reading without cancelling the producer, matching | first n.
This condition cannot be combined with parallel, because several passes in
flight would make the stopping point depend on scheduling. <- applies only to
repeat; a for obtains each value from its source stream.
Read successive items without a loop by using the same stream view:
The reads reserve successive positions in source order. Stream aliases share
that extraction cursor; independent pipeline subscriptions still see the whole
stream. An empty take fails. Use try take when EOF is an expected outcome:
Optional binding evaluates once and introduces a fresh success-branch name.
A present null item remains distinguishable from EOF. Explicit options expose
.has_value and .value; .value fails when absent. Upstream failure and
cancellation propagate through both forms.
T settings = try take options or T{} unwraps a present option or evaluates
the default when absent. The fallback is lazy, including constructors, calls
and stream reads. Present null, false, zero and empty values skip it. Stored
std::option[T] values support the same or expression. Errors propagate.
Ordinary values retain truthiness-based or behavior.
Stream completion and failure¶
close node writes both of the two facts that end a stream: the node is marked
final, so an ordered reader stops, and its writer is closed, so the store
admits nothing more. Then it reads what is left, and its name binds the outcome.
abort node ends a node with a failure:
Readers receive the failure status. abort accepts the same code and message as
fail and does not wait. Place it in an if, a loop body, or a statement with
after when ordering matters.
Only a node this flow writes can be aborted by it.
Flow unifies node completion into full endings (close or abort): marking a
node final also closes its writer to keep reader semantics consistent.
Ending a step early¶
cancel x aborts a step, ending the run with status cancelled.
To request graceful completion, send a stop command following standard action conventions:
Standard library actions treat {"command": "stop"} on their control port as
an end of input, closing their ports normally so downstream readers observe a
clean stream termination.
Stage limits (| first n and for with until) stop reading while leaving
the upstream producer undisturbed. An active step terminates via its control
port, cancel, or an assigned deadline. cancel evaluates immediately, so it
belongs within a conditional, loop body, or after clause.
Flow boundaries and sandbox limits¶
Beyond + and -, Flow provides no arithmetic, function definitions, or
direct calls to host code. Expressions read and compare values, access fields
with .field and [i], and construct records with built-in functions such as
len, lower, join, merge, and default. A flow operates only through
declared action streams.
Language tables¶
a11.flow
¶
Compose asynchronous, streaming actions as reusable actions.
Use run for a local handler and call for a peer. Steps overlap; data
and explicit after dependencies determine their order. Every output is
read, including outputs that the composition does not expose.
flow answer {
in question: string required
out text: string
work = run search(query: question) timeout 30s
work.results | collect | map std::join(it, "\\n") -> text
}
Initialize values with x = expression or T x = expression. Initializers
run once when their scope activates and dependencies are ready. Reassignment
uses source order; child scopes publish updates when they complete. Conflicting
updates in parallel loop passes are rejected. Capability and port names retain
their own categories and cannot be reassigned as ordinary values.
take stream consumes the next item. Successive reads consume successive
items in source order, and EOF fails. try take stream returns an option with
has_value and, when present, value. Null items remain distinct from EOF;
upstream failures propagate. Destructuring reads its RHS once.
T settings = try take options or T{} unwraps a present option and evaluates
the fallback only on absence. Present null, false, zero and empty values stay
present. Stored options support the same lazy or default.
Put loop postconditions after the closing brace:
flow forward {
in words: string stream
out result: string stream
for word in words {
word -> result
} until word == "stop"
}
The stopping pass finishes before the condition is tested. close node ends
an owned node normally; wait subject observes completion. cancel stops
an action and abort ends a node with an error. try makes an operation's
failure available through its status.
timeout accepts a positive std::duration expression.
deadline accepts
an absolute std::time expression, evaluated eagerly once per scope
activation. deadline std::now() + 30s after prepared evaluates the entire
expression after prepared finishes. Parentheses around the expression do
not change this. Both words are contextual and may name variables.
Use :: for module and type qualification, and . for runtime fields and
ports. Modules are declared with mod name { ... }; declare mod contains
contracts and complete struct definitions. Modules and their members are
private by default; exported exposes a declaration and
export symbol [as alias] exposes an accessible existing symbol.
import "path/library.flow" binds library; as alias selects another
name. from library import member and from library import * bind public
members in the current module or flow. The implicit reserved std module
needs no file import. Standard functions and nonprimitive types are lowercase
and qualified, such as std::now and std::duration. Primitive names
int, int, bool, number, string, bytes, object and
null are available directly, together with their conversions. object[V]
is a string-keyed homogeneous object; bare object has heterogeneous values.
Filesystem imports require explicit source_roots. The default permits no
filesystem imports; supplied in-memory modules remain available. Compilation
uses host-configurable byte, token, nesting, import, work and time limits.
The lexer, parser, resolver, tooling and runtime live in cpp/a11/flow.
Python, command-line tools and editors use that native implementation.
REFERENCE
module-attribute
¶
REFERENCE = 'A11 Flow composes streaming actions into actions.\nText uses \'...\' or "..."; bytes use b\'...\' or b"...". Triple quotes of\neither kind hold line breaks. Prefix r keeps backslashes literal; br and rb\ncombine both modifiers. Escapes include \\0, \\a, \\b, \\e, \\f, \\n, \\r,\n\\t, \\v, quotes, backslashes, octal, \\xHH, \\uHHHH, \\UHHHHHHHH, and\n\\u{H...}. Text must decode to valid UTF-8; byte literals require ASCII\nsource and can hold arbitrary escaped octets. Other escapes yield the\nfollowing character. std::escape writes a literal body; std::unescape\nreturns text and std::unescape_bytes returns bytes.\nKeywords are lower or UPPER\ncase. Statements overlap; data and after dependencies determine execution.\n\nflow NAME [exported] {\n in input: string [stream] [required]\n out output: string [stream]\n job = run local_action(input: input) timeout 30s\n job.output | map std::upper(it) -> output\n}\ncall invokes a peer; run invokes a local handler. All outputs are read.\nAn argument can omit `: source` when its port and source share a name:\nrun local_action(input) means run local_action(input: input). Arguments may\nappear in any order or mix shorthand with explicit port: expression values.\n\nx = expression or T x = expression initializes once per scope, eagerly.\nconst [T] kName = expression captures one scalar value when reached; the\nbinding and its Flow-owned list/record contents cannot be reassigned. At module\nscope, const [T] kName [exported] = value requires a closed expression of\nliterals, lists, records, and other module constants. kThisLetterCase is a\nnaming convention, not a requirement. Module constants may be imported and\nused in static defaults, patterns, enumerations, and bounds.\nReassignment follows source order, including child-scope updates. Parallel\nconflicting updates are rejected. Names and destructuring patterns are lvalues.\nx = take source consumes one successive item; EOF fails.\nx = try take source returns {has_value: bool, value: T when present}.\nErrors fail.\nA real null item has has_value=true. Prefer if item = try take source { ... }.\nif item = option evaluates once and binds its payload in the success branch.\nEOF is absence; false-like payloads remain present. The name must be fresh.\nExplicit option.has_value and option.value access remains available.\nT settings = try take options or T{} unwraps the option or lazily evaluates T{}.\nStored std::option[T] values support the same or default. Presence, including\nnull, false, zero and empty payloads, skips the fallback. Errors propagate.\nvalue?.field and value?[key] return an option. Missing fields or indices are\nabsent; a present null remains present. Safe projections chain through options.\nAn object field whose value is an absent option is omitted; a present option\ncontributes its payload, including null, false, zero and empty values.\nUse | present to remove absent options from a stream and emit present payloads.\nWith ordinary values, or keeps its truthiness-based short-circuit behavior.\nRead the RHS of destructuring only once.\n\nfor item in source [parallel N] { body }\n [until EXPR | while EXPR] [after subject]\nA bare list literal, for x in [a, b, c] { ... }, iterates its elements once,\none level deep. Empty literals make no passes. Other sources keep their stream\nvalues: use | flatten for named lists or list-valued pipelines.\nparallel accepts an integer expression, e.g. parallel workers or\nparallel (workers + 1), evaluated once per loop or stage activation. Dynamic\ncounts must be positive signed 32-bit integers and retain parallel safety\nrestrictions on loop updates and trailing conditions.\nrepeat [state = INITIAL] [max N] {\n body\n state <- NEXT\n} [until EXPR | while EXPR]\nPostconditions run after the entire pass, in that pass\'s scope. Postconditions\nrequire sequential loops. A repeat needs a condition or an explicit bound.\n\na -> b -> out associates right and forwards b, then a. A transfer returns a\ncontinuation sink: alias it without repeating work; attach streams on its right.\nIndependent attachments interleave after the prefix; wait/status include all\nattached writers. Virtual sinks and serial chain flattening are enabled\nby default.\nA terminal comma list broadcasts. Group ambiguous combinations explicitly.\n\nnode() creates a node. close NODE ends it normally; abort NODE [CODE [MESSAGE]]\nends it with an error. wait SUBJECT observes completion; status SUBJECT is its\nstatus. cancel ACTION cancels an action. fail [CODE [MESSAGE]] fails the scope.\ntry run/call or try { body } exposes a failure through the operation\'s status.\nwait first of a, b chooses a completion; wait all of a, b waits for every one.\nBare wait all is a scope-local execution barrier: work directly induced by\npreceding statements must complete successfully before any following statement\nactivates. This includes initializers, arguments, eager deadlines, owned calls,\nfeeds, reads activated before the barrier, automatic drains of unused call\noutputs, and child scopes. A partial\nread such as ``take`` does not exhaust its stream. Work within a phase remains\nconcurrent. Barriers inside branches, blocks, and loop passes affect only that\nscope or pass. A stream may first be read on either side of a barrier, and\ndifferent outputs of one call may be read in different phases. Independent\nreaders of the same stream must stay in one phase; successive value reads\nthrough one shared cursor may cross a barrier. Stream aliases do not read or\nexhaust streams.\nBare wait all accepts no modifiers or value binding. wait all of a, b remains\nan explicit-subject wait and does not gate following statements.\nafter a, b { body } gates a scope. Bound blocks and loops expose completion.\n\nCall and wait modifiers: timeout DURATION_EXPRESSION, deadline TIME_EXPRESSION,\nafter SUBJECTS. Deadlines evaluate once eagerly; an after clause delays the\nwhole expression. deadline std::now() + 30s after action and the parenthesized\nform have identical meaning. timeout timeout and deadline deadline are valid\nwhen the names hold the corresponding values. The earlier bound applies when\nboth modifiers are present. Expiry is DEADLINE_EXCEEDED.\nOther call modifiers: via MAP, tee, id EXPR, id-into DEST,\nwith "header": EXPR,\nforward headers "name". Local nodes stay off the wire.\n`id job` reads a run/call\'s action ID when it starts, without waiting for\ncompletion. `id-into DEST` forwards that ID once to a writable destination.\n\nsource | stage -> destination [, destination]; -> _ discards results.\nsource | run flow_name(config: value) | call module::flow_name() composes\nwhole-stream invocations. After supplied arguments, exactly one input must\nremain (optional inputs count too), and exactly one output must be declared.\nrun flow_name(input: source) | stage -> destination starts a pipeline when\nevery input is supplied (including optional inputs) and one output is declared.\nrun flow_name(input: source) -> destination forwards that output directly.\nAn unread pipeline does not start its invocations; use -> _ to execute and\ndiscard the output. Bare run/call statements still execute when unused.\nUnary inputs validate zero/one or exactly one item according to required.\nDeclare/import external interfaces before using them as stages. Calls retain\nordinary dispatch, modifiers, draining, failure, and cleanup semantics.\ntry run/call tolerates the invocation, not failures reading its output;\nuse a try block for the whole pipeline, or combine a try invocation with a\ntry pipe to tolerate transfer errors too. No item is dropped.\n\nStages include map EXPR, where EXPR, first N, drop N, collect, flatten, present,\nscan INITIAL as state, EXPR, fold INITIAL as state, EXPR, sum, count,\ntake while EXPR, take until EXPR, as TYPE, json, packb, timeout DURATION.\n`try STAGE failures into DEST` routes a tolerated failure as a record with\nstatus fields, its original value in `it`, and a zero-based `seq` at that\nstage. Casting or binding it to `std::status` keeps only status fields.\nUse ``node | read_with {max_ref_depth: 2, max_ref_breadth: 3}`` to open an\nindependent reader with explicit options. ``view: "fragments"`` exposes raw\nfragments; the default value view follows node references. The stage must come\nfirst, directly after a node or port. ``source | ref -> destination`` writes a\nreference to the source node, and ``ref(source, for: destination, offset: 1,\nlength: 2)`` produces a reference value. Reference windows count fragments.\nfirst, last, drop, truncate, batch, window and chunk accept scalar integer\nexpressions as their counts, including fields and grouped calculations. Counts\nevaluate once per pipeline activation, outside it.\ncontext PREDICATE before N after M emits excerpts with N preceding items.\nMatches within the M trailing items reset that count and extend the excerpt.\nNormal EOF flushes shorter lists; upstream failures propagate. Counts evaluate\nonce outside it and must be nonnegative signed 32-bit integers. Optional\nnumbered [base EXPR] returns {index, value} items, counting every source item\nfrom base (default 1). Base evaluates once and must be an integer; overflow\nfails. Storage holds N preceding items plus the active excerpt, which can grow\nwith chained matches; bound endless sources upstream. Parallel and unordered\nare unsupported.\nPrefer context for file/tool matches (tests, web, external systems). Feed\noriginal lines/items per source, keep neighborhoods small, cap groups with first\nand joined excerpts with truncate. Filtering first loses neighboring evidence.\nSpaces and indentation between tokens do not change meaning. Newlines inside\nexpression groups are whitespace. Incomplete constructs continue across lines;\noptional arguments and tails continue when the next syntax belongs to them.\nAfter a complete statement, a following complete statement keeps its boundary.\nUse grouping to attach an expression that also reads as a separate statement.\nAdjacent string literals concatenate; declaration descriptions retain their\nownership. The formatter targets 80 columns and orders declaration modifiers.\nEquivalent whitespace formats alike. Groups stay compact when they fit or\nexpand with indented contents and dedented closing delimiters; trailing commas\nrequest expanded item lists. Module bodies have no extra indentation. Long\nordinary strings split at spaces or character boundaries, preserving values and\nescapes. Triple-quoted strings and comments remain intact.\nPrefer list[T] and list(value). list is a prelude alias of std::list; neither\nform requires an import. The qualified spelling remains valid.\nStages stay unqualified. Functions are qualified: std::len, std::upper,\nstd::casefold, std::join, std::match, std::matches, std::matches_pattern,\nstd::strformat, std::now, std::duration, std::time.\nRegex literals use /.../ with optional i, m and s flags and RE2 syntax.\nNamed captures use (?<name>...). std::match returns the first match;\nstd::matches returns a list of nonoverlapping matches. A match stage emits\none result per input value; match all emits every result. An optional offset\nname wraps each capture as {value: captured, NAME: character_offset}.\nstd::split(text, /separator/) and std::replace(text, /pattern/, replacement)\naccept regex literals; quoted separators and search strings remain literal.\nRegex replacements support $1, ${name}, and $$ for a literal dollar sign.\nstd::matches_pattern(text, /pattern/) returns a boolean. A quoted "\\W+"\nis not a regex literal. Use and, or, not rather than &&, ||, !.\nstd::casefold(text) applies Unicode 17.0 default full case folding for\ncase-insensitive comparison: std::casefold("Straße") is "strasse". It requires\nvalid UTF-8; it neither normalizes Unicode nor applies locale-specific rules.\nstd::lower and std::upper change ASCII letters only.\nfrom std import now makes now() available without a prefix.\nstd::parse_time(text) and std::parse_duration(text) fail on invalid text;\nstd::time(text) and std::duration(text) retain permissive conversions.\n\nmod name [exported] { declarations }\ndeclare mod name [exported] { contracts, declared modules, full structs }\ndeclare flow company::search::find { interface }\nstruct Row [exported] {\n name: string required\n count: int\n}\nimport "path/library.flow" [as alias] loads a module; default name is library.\nfrom library import member [as alias], other; from library import *.\nexport library::member [as alias] publishes an accessible existing symbol.\nModules cannot be created inside flows or structs. std is reserved.\n:: qualifies static modules/types; . projects runtime fields/ports.\n?. and ?[] project optional fields and indexed items.\nHost type source a11::sdk::Interaction retains wire tag a11.sdk.Interaction.\n\nPrimitive prelude: int/integer (strict i64), i8/i16/i32/i64/i128,\nu8/u16/u32/u64/u128, f32/f64, bool, permissive number, string, bytes,\nobject, null;\nliterals true, false, null. Exposed types expose their conversions too.\nOther standard types: std::status, std::time, std::duration, std::list[T],\nstd::option[T], std::stream[T]. object[V] has string keys and one value type;\nbare object is heterogeneous. Typed initialization uses existing coercions and\nchecks the target invariant. Initializers may not be omitted.\nStrict integer conversions require a whole value in range; signed and unsigned\narithmetic checks overflow. Strict floats are finite and f32 rounds explicitly.\nFloating literals accept scientific notation such as 1e3 and 2.5E-2.\nUse decimal text with i128/u128 constructors beyond literal i64 range.\nCompatible numeric families support +, -, *, / and integer %. Integer division\nrequires an exact quotient. std::floor, std::ceil and std::round preserve\nnumeric width; std::round sends halfway values away from zero.\nTime +/- duration and duration +/- duration work;\ndurations support unary minus. std::infinite_future(),\nstd::infinite_past(), std::infinite_duration(), and std::zero_duration()\nconstruct temporal boundary values.\nDurations multiply by numeric scalars in either order. Overflow, underflow,\nand an infinite duration multiplied by zero fail.\nstd::nanoseconds(x), std::microseconds(x), std::milliseconds(x),\nstd::seconds(x), std::minutes(x), and std::hours(x) construct durations from\nnumbers. Given a duration, each returns its integral count in that unit,\ntruncated toward zero. Use std::parse_time(text) and\nstd::parse_duration(text) to parse temporal text explicitly; direct temporal\ncasts reject text. Declared temporal ports can decode their wire text values.\nConversion, arithmetic, and duration-construction failures propagate as Flow\nstatuses; `try` stages and blocks can handle them.\n\nFile imports require explicitly approved source_roots; none means filesystem\nimports are disallowed. Explicit in-memory modules remain available. Parsing\nand compilation have configurable depth, size, work and time limits.\n'
FAIL_CODES
module-attribute
¶
FAIL_CODES: tuple[str, ...] = tuple(sorted(code.upper() for code in _flow.vocabulary()['status_codes']))
Compiling¶
loads compiles source that arrived as a string,
load a .flow file, and register does
both and publishes the result as actions in one call. A problem raises
FlowSyntaxError, which carries the line and
column and converts to an A11 status.
a11.flow.loads
¶
loads(source: str, source_name: str = '', *, modules: dict[str, str] | None = None, source_roots: list[str] | None = None, limits: CompilationLimits | None = None, single_item_slots: bool = True) -> Program
Compile Flow source into a Program.
An anonymous flow { ... } is available as program.entry. Pass that
FlowPlan to runtime.start for live ports, or use
run_program for CLI-style execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
The text of one or more |
required |
source_name
|
str
|
A name for error messages, usually a file path. |
''
|
Raises:
| Type | Description |
|---|---|
FlowSyntaxError
|
On any problem, with the line and column it was at. |
a11.flow.load
¶
load(path: str | PathLike[str], *, source_roots: list[str] | None = None, limits: CompilationLimits | None = None, single_item_slots: bool = True) -> Program
Compile a .flow file.
a11.flow.register
¶
register(source: str, registry: Any, source_name: str = '') -> Program
Compile Flow source and register its root implementations as actions.
The one call a service needs to accept a composition from outside and make it runnable: after this the flows are in the registry, and a session dispatches them like any other action.
a11.flow.diagnostics.FlowSyntaxError
¶
Bases: Exception
Report the first compilation error from a strict Flow entry point.
a11.flow.loads raises this exception with the first native error diagnostic's message, line, and column. Editor entry points continue after recoverable errors and return the full diagnostic list.
Programs and flows¶
a11.flow.plan.Program
¶
The flows compiled from one Flow source file.
A program is self-contained: its flows may call each other by name, and anything else they call is looked up in the action registry of whatever runtime dispatches them.
entry
property
¶
entry: FlowPlan | None
The anonymous flow { ... } as a streaming FlowPlan, or None.
This does not make the entry flow callable by name or change CLI execution.
has_entry
property
¶
Whether the file declares a flow { ... } -- a program.
An entry flow has no name and cannot be accessed through program["..."],
run, or call. Use program.entry to run it as a streaming FlowPlan.
names
property
¶
Every named flow, in the order the file declares them. The entry flow -- flow { ... } -- is not here: it has no name, and it is run rather than called.
external_actions
¶
Runtime action identities reachable through external calls and contracts.
optimizations
¶
Explain verified single-item transport choices for this compilation.
register_all
¶
register_all(registry: ActionRegistry) -> Program
Register the root module's named implementations in registry.
a11.flow.plan.FlowPlan
¶
One compiled flow: an action schema, and the graph implementing it.
A handle onto the program it came from, which keeps the program -- and the syntax tree its graph borrows -- alive for as long as anything holds the flow. So a handler taken from one still runs after the program variable has gone.
handler
property
¶
The action handler that runs this flow.
inputs
property
¶
inputs: Mapping[str, ActionPortSchema]
The declared input ports, by name, as the action schema has them.
outputs
property
¶
outputs: Mapping[str, ActionPortSchema]
The declared output ports, by name, as the action schema has them.
registerable
property
¶
Whether bulk registration exposes this root or exported implementation.
schema
property
¶
schema: ActionSchema
The ActionSchema a flow presents.
A flow is an action: it has ports, headers and a name, so anything that can dispatch an action can dispatch a composition without being told it is one.
The native schema supplies ports and header defaults. Python attaches
the corresponding builtin typeinfo handles.
action_schema
¶
action_schema() -> ActionSchema
The selected native implementation's action schema, including header defaults.
describe
¶
The whole composition as plain data.
The flow.plan/v1 entry for this flow: its ports, headers, node maps and steps,
nested bodies and all.
invoke
async
¶
Run the flow once, here, and collect its outputs.
See a11.flow.runtime.invoke for what the keywords mean.
make_handler
¶
make_handler(dispatch_stream: WireStream | None = None, *, frame_cache_bytes: SupportsInt = 262144, frame_budget_bytes: SupportsInt | None = None) -> ActionHandler | NativeActionHandler | None
The action handler that runs this flow.
dispatch_stream is only for a flow a client runs over a session it already
holds: the calls that belong to the peer are bound to that stream, and the flow's
own action is not. An action that is run locally and holds a stream ends that
stream when it finishes, after which the session can dispatch nothing.
frame_cache_bytes caps cached frame capacity per runner; zero disables reuse.
frame_budget_bytes bounds reserved frame capacity across the invocation and
its local Flow calls. Payloads, fiber stacks and ordinary containers are excluded.
register
¶
register(registry: ActionRegistry, name: str | None = None) -> FlowPlan
Register this flow as an action in registry.
After this the composition is an action like any other: a session dispatches it, another flow calls it, and a model can be offered it as a tool, without any of them knowing it is a composition.
The compiled graph¶
A compiled flow is data: describe renders
the whole composition, which is what makes one reviewable before it is run.
a11.flow.plan
¶
Inspect, register, and run compiled Flow programs from Python.
Program and FlowPlan are
native classes with Python mapping and runtime methods. Use
FlowPlan.describe to read the
flow.plan/v1 shape printed by a11 flow describe.
Steps run concurrently. Use after, wait, or close to order them.
The runtime buffers an outer stream read inside a loop or branch once and
replays it for each reader.
TYPE_NAMES
module-attribute
¶
TYPE_NAMES: dict[str, type | str] = {'string': str, 'text': str, 'number': float, 'integer': int, 'int': int, 'bool': bool, 'boolean': bool, 'object': dict, 'json': dict, 'list': list, 'array': list, 'bytes': bytes, 'time': 'a11.Time', 'duration': 'a11.Duration', 'any': 'application/json'}
compile_source
¶
compile_source(source: str, source_name: str = '', *, modules: dict[str, str] | None = None, source_roots: list[str] | None = None, limits: CompilationLimits | None = None, single_item_slots: bool = True) -> Program
Compile Flow source into a Program.
Raises:
| Type | Description |
|---|---|
FlowSyntaxError
|
On any lexical, grammatical or naming problem, with the line and column it was found at. |
Runtime API¶
a11.flow.runtime
¶
Running a compiled Flow program on A11.
The runtime is native (cpp/a11/flow/runtime.{h,cc}): a flow becomes one
action, each call in it becomes a nested action on the same session, and each
pipe becomes a fiber copying one node into another as values arrive. What lives
here is the way a Python caller starts one and reads it back --
start for the streaming path,
invoke for the convenience of collecting the lot at
the end -- and nothing about the language itself.
The engine provides three behaviours required by streaming compositions:
- Every output is drained. An output port of a called action that the flow does not read is read and discarded anyway, because an unread output stalls the action producing it.
- A
runstep keeps its nodes off the wire. A step that runs in this process is bound to no stream unless it asks fortee, so the intermediate streams between two steps of a composition are never replicated to the peer that dispatched it. Anodesblock goes further and keeps them out of the session's node map entirely. Acallstep, by contrast, is exactly a step put on the stream this flow is attached to. - Inputs are closed. A port the flow feeds is closed when its last writer finishes, and one it never feeds is closed immediately, so a callee waiting for end-of-input is never left waiting on a port the composition was never going to write.
Running
¶
Running(flow: FlowPlan, action: Action, outputs: Mapping[str, AsyncNode], timeout: Duration | None, inputs: Mapping[str, AsyncNode] | None = None)
A flow that has been started, and the port nodes it is moving values on.
A flow's ports are AsyncNode values like any other action's. Read an output node to receive values as the flow produces them. invoke's dict of lists is a convenience on top of this for the callers that want the lot at the end (a tool call, a test, a script), not the other way round.
Inputs work the same way round when they are asked for: a port named in
start's open_inputs is handed back on
inputs for whoever wants to fill it while the flow runs.
publish
¶
Mirror the named outputs to stream, and say where they landed.
Returns the node id of each published port, which is what a peer needs
to read it: NodeMap.get(id) on the other side of the stream is the
same node. The action is not bound to the stream, preventing local
action completion from closing the session transport.
collect
async
¶
Wait for the flow, and gather every output port into a dict.
One value for a one port, a list for a many one. Reading starts
before the wait, because an output nobody reads stalls the flow filling
it -- the same rule that applies to any action's ports.
make_handler
¶
make_handler(flow: FlowPlan, dispatch_stream: Any = None, *, frame_cache_bytes: int = 256 * 1024, frame_budget_bytes: int | None = None) -> Callable
The action handler that runs flow.
Registering this makes the composition an action like any other: a peer can dispatch it, another flow can call it, and an LLM can be offered it as a tool, without any of them knowing it is a composition.
dispatch_stream is only for a flow a client runs itself over a session
it already holds; invoke passes it, and nothing
that registers a flow as an action needs it.
frame_cache_bytes=0 disables frame reuse. frame_budget_bytes bounds
reserved frame capacity, including local Flow calls; payloads, fiber stacks,
and ordinary containers are outside that budget.
start
async
¶
start(flow: FlowPlan, inputs: Mapping[str, Any] | None = None, *, registry: Any = None, session: Any = None, node_map: Any = None, stream: Any = None, dispatch_stream: Any = None, headers: Mapping[str, Any] | None = None, timeout: Duration | None = None, frame_cache_bytes: int = 256 * 1024, frame_budget_bytes: int | None = None, action_id: str | None = None, open_inputs: Iterable[str] = (), publish_to: Any = None, **keyword_inputs: Any) -> Running
Start flow and return its live input and output ports.
Provided inputs are written and closed before this returns. Read outputs
from Running.outputs, then await
Running.wait for the final status.
Ports named by open_inputs remain available through Running.inputs;
their writer must close them. Their node ids are <action_id>#<port>, so
a peer can stream chunks with their original media types into the flow.
publish_to attaches an output stream before execution, ensuring it sees
values produced immediately after startup. Use action_id when peers
need deterministic port node ids.
frame_cache_bytes caps cached frames per runner; zero disables reuse.
frame_budget_bytes bounds frame capacity across local Flow calls,
excluding payloads, fiber stacks, and ordinary containers.
See invoke for stream against
dispatch_stream.
invoke
async
¶
invoke(flow: FlowPlan, inputs: Mapping[str, Any] | None = None, *, registry: Any = None, session: Any = None, node_map: Any = None, stream: Any = None, dispatch_stream: Any = None, headers: Mapping[str, Any] | None = None, timeout: Duration | None = None, frame_cache_bytes: int = 256 * 1024, frame_budget_bytes: int | None = None, **keyword_inputs: Any) -> dict[str, Any]
Run flow and return its output values keyed by port name.
A one port returns one value; a many port returns a list. Inputs may
be keyword arguments or a mapping for names that collide with options.
registry, session and node_map place the flow in an existing
runtime. Use start to read live output nodes.
frame_cache_bytes and frame_budget_bytes configure frame storage as
described by start.
Use one stream argument: stream mirrors the flow's own ports to a peer
for server dispatch; dispatch_stream sends only the flow's peer calls
while keeping its ports local. A client with its own session uses
dispatch_stream so completing the flow leaves the session stream open.
Running a program¶
A file with a flow { ... } is a program, and running one is a different call
from running a flow: it gets argv, a policy, this process's standard streams,
and returns its exit code as a result.
a11 flow run greet.flow -- Helena
a11 flow run --root /var/log --timeout 30s watch.flow -- /var/log/system.log
a11 flow run and the standalone a11-flow-run use the same interpreter. Their
hosts expose different actions: the standalone binary provides the Flow standard
library, while the Python process can also provide registered Python actions.
a11 flow run ask.flow --allow-llm --allow-net \
--allow-env ANTHROPIC_API_KEY -- "why is the sky blue"
interact_with_llm requires a provider SDK and credential from Python, so
examples/006-flow-programs/ask.flow runs under the Python host. --allow-llm
is separate from --allow-net: flow policy does not bound host-registered
actions. Policy governs the standard library; registered Python handlers
retain their own capabilities. The host exposes no optional action by default.
From Python directly:
a11.flow.run_program
¶
run_program(source: str, source_name: str = '', *, arguments: Sequence[str] | None = None, roots: Sequence[str] | None = None, allow_write: bool = False, allow_run: bool = False, allow_net: bool = False, allow_local_net: bool = False, allow_env: Sequence[str] | None = None, unrestricted: bool = False, timeout_seconds: float | None = None, standard_streams: bool = True, registry: Any = None, session: Any = None, dispatch_stream: Any = None, source_roots: Sequence[str] | None = None, limits: CompilationLimits | None = None, single_item_slots: bool = True, frame_cache_bytes: int = 256 * 1024, frame_budget_bytes: int | None = None) -> dict[str, Any]
Run a Flow program's entry flow — the flow { ... } with no name.
This calls the a11-flow-run interpreter in process. Pass a registry to
expose actions from the host process:
from a11 import flow
from a11.actions import ActionRegistry
from a11.sdk import llm_tools
registry = ActionRegistry()
llm_tools.register(registry)
flow.run_program(
source,
"summarise.flow",
registry=registry,
arguments=["summarise.flow", "notes.txt"],
)
A name already in registry is never replaced by the standard library's: a
host that registered its own read_file meant its own read_file.
Run off-loop for async action handlers
This runs the program to completion, so it blocks the thread it is
called on. A Python action handler written async def has to be driven
by an asyncio loop — and if that loop is on this thread, it cannot run
while this call is blocking it, and the program waits forever on its own
handler. So call it in a thread:
A program that only uses the standard library needs none of this: those actions are native and take no GIL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
The program's text. |
required |
source_name
|
str
|
What diagnostics should call it, usually the path. |
''
|
arguments
|
Sequence[str] | None
|
The program's |
None
|
roots
|
Sequence[str] | None
|
Directories the program may reach. Defaults to the working directory. |
None
|
allow_write
|
bool
|
Whether it may write, inside those roots. |
False
|
allow_run
|
bool
|
Whether it may run programs, confined by the kernel where the platform can. |
False
|
allow_net
|
bool
|
Whether it may reach the network. Loopback, private and
link-local addresses stay refused unless |
False
|
allow_local_net
|
bool
|
Also allow loopback, private, and link-local addresses (e.g. cloud metadata services). |
False
|
allow_env
|
Sequence[str] | None
|
Environment variables it may read. |
None
|
unrestricted
|
bool
|
No filesystem sandbox. Use only with trusted source. |
False
|
timeout_seconds
|
float | None
|
A bound on the whole run, applied as the deadline header every standard-library action honours. |
None
|
standard_streams
|
bool
|
Whether to bind this process's stdin/stdout/stderr. Clear it in a host with no useful standard input. A read then fails instead of waiting indefinitely. |
True
|
registry
|
Any
|
An ActionRegistry whose actions the program may call. One is made when omitted. |
None
|
frame_cache_bytes
|
int
|
Cached frame capacity per runner; zero disables reuse. |
256 * 1024
|
frame_budget_bytes
|
int | None
|
Reserved frame capacity across local Flow calls. Excludes payloads, fiber stacks, and ordinary containers. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
an |
dict[str, Any]
|
that was not an error. |
Raises:
| Type | Description |
|---|---|
Exception
|
When the source will not compile, declares no entry flow, or the program itself failed. What the flow failed with is the message. |
a11.flow.check_program
¶
What a program's entry flow is, compiling it and running nothing.
Raises if the source will not compile or declares no flow { ... }.
Run off-loop for async action handlers
run_program runs the program to completion, so it blocks the thread it is
called on. An async def handler needs a loop to drive it, and if that loop
is on this thread it cannot run while the call is blocking it -- so the
program waits forever on its own handler. await asyncio.to_thread(...) is
the pattern, and it is what a11 flow run does.
Diagnostics¶
The CLI, editors, and CI integrations use one
Diagnostic shape. See
Checking flows from a toolchain for the envelopes it
travels in.
a11.flow.diagnostics
¶
Read and render Flow diagnostics in Python.
A Diagnostic carries a stable code, severity, family, source range, message, and optional source edits. Ranges contain byte offsets for edits and line and column positions for display.
Native Flow analysis produces versioned, additive envelopes. Readers check
the format field and ignore unknown fields. This module supplies Python
value types and text and SARIF renderers. The code catalogue is generated from
the native table into testdata/flow/codes.json.
Diagnostic
dataclass
¶
Diagnostic(code: str, message: str, range: Range, severity: Severity = ERROR, family: Family = SYNTAX, flow: str = '', fixes: tuple[Fix, ...] = (), source: str = '', related: tuple[RelatedDiagnostic, ...] = ())
Represent one Flow error or non-blocking finding.
Severity
¶
Bases: StrEnum
Classify whether a diagnostic blocks compilation or reports a finding.
ERROR blocks compilation. WARNING reports a possible behavior
mismatch. WEAK_WARNING marks an ineffective source element.
INFORMATION supplies a non-blocking finding.
Family
¶
Bases: StrEnum
Group diagnostics by syntax, form, name, sequence, barrier, or use.
Editors can expose families as separate inspections. Build gates can select families without parsing diagnostic codes.
Position
dataclass
¶
Locate source by byte offset and 1-based line and column.
Byte offsets support edits. Line and column remain available after serialization removes access to the original source text.
Edit
dataclass
¶
One replacement of a span of source. Empty text is a deletion.
Fix
dataclass
¶
Fix(label: str, edits: tuple[Edit, ...] = (), automatic: bool = True)
Carry source edits supplied by native analysis for a diagnostic.
Editors apply edits in source byte coordinates. automatic marks a
repair that can be applied without further user input.
CodeInfo
dataclass
¶
Describe a stable native diagnostic code.
LineIndex
¶
Convert UTF-8 byte offsets to source lines and columns.
Construct once per source document and reuse for diagnostic locations.
Offsets use UTF-8 bytes; columns count Unicode code points. For example,
§ occupies two bytes and one column. characters_of supplies the
character count required by SARIF.
known_codes
cached
¶
known_codes() -> tuple[CodeInfo, ...]
Return the native diagnostic catalogue sorted by code.
The same table generates testdata/flow/codes.json.
find_code
¶
find_code(code: str) -> CodeInfo | None
Return the entry for code, or None for an unknown code.
sort_diagnostics
¶
sort_diagnostics(diagnostics: Iterable[Diagnostic]) -> list[Diagnostic]
Sort by byte position, code, and message.
diagnostics_envelope
¶
diagnostics_envelope(source: str, diagnostics: Sequence[Diagnostic]) -> dict[str, Any]
Build a flow.diagnostics/v1 envelope with severity counts.
counts supports build gates without scanning the diagnostic list.
codes_envelope
¶
Build a flow.codes/v1 envelope from the native catalogue.
sarif_log
¶
sarif_log(source: str, diagnostics: Sequence[Diagnostic], index: LineIndex | None = None) -> dict[str, Any]
Build a SARIF 2.1.0 log for one source file.
Code-scanning services and CI annotators consume SARIF directly. Every rule in the log is documented from the published code table.
index maps diagnostic byte offsets to SARIF character offsets. When it
is absent, the log retains line and column locations and omits character
offsets. Non-ASCII characters require this conversion.