SPB Git

Repository Public License

FLOW_LANGUAGE.md 14.1 KB

# The Flow language (version 1)

Flow is the declarative workflow language of ORIX Navigator. A workflow is text (Workflow.source), interpreted by FlowEngine over a fixed set of actions. It is data, not a program: it cannot define functions, cannot load or download code, has no unbounded loop and no recursion, and every effect goes through the host application after capability, domain and confirmation checks.

Module: Packages/NavigatorKit/Sources/FlowEngine. Extension points and platform rules: SDK.md.

# Example

text
# Reads an encyclopedia article and a few of the pages it links to,
# then writes a summary with citations.
flow "Research brief" version 1

param topic: text

allow domains "wikipedia.org", "arxiv.org"
limit steps 40, duration 300s, timeout 30s

space "Research" {
    open "https://en.wikipedia.org/wiki/{topic}" as wiki
    extract article from wiki as overview
    collect overview into sources
    # Only links that stay on the allowed domains are followed.
    for link in allowed(overview.links) limit 5 parallel 3 {
        open link as page
        extract article from page as item
        collect item into sources
        close page
    }
    if count(sources) > 0 {
        summarize sources with citations as report
        export report as markdown to downloads
    }
}

Four examples ship in FlowEngine.examples; a test validates each of them.

# Grammar (EBNF)

text
program      = { trivia } header { trivia | declaration } body { trivia } ;
header       = "flow" plain-string "version" integer ;
declaration  = parameter | domains | limits ;
parameter    = "param" identifier ":" type [ "=" literal ] ;
type         = "text" | "number" | "bool" | "url" ;
domains      = "allow" "domains" plain-string { "," plain-string } ;
limits       = "limit" limit-item { "," limit-item } ;
limit-item   = "steps" integer | "duration" duration | "timeout" duration ;
body         = "space" plain-string block            (* nothing may follow the block *)
             | { statement-line } ;

block        = "{" { statement-line } "}" ;
statement-line = { trivia } statement { ";" statement } ;
statement    = action | let | for | parallel | if | collect ;

let          = "let" identifier "=" expression ;
for          = "for" identifier "in" expression "limit" integer [ "parallel" integer ] block ;
parallel     = "parallel" "limit" integer block ;       (* each statement of the block is one branch *)
if           = "if" expression block [ "else" ( if | block ) ] ;   (* "else" may start the next line *)
collect      = "collect" expression "into" identifier ;
action       = action-name [ expression ] { label argument } [ "as" identifier ] ;
action-name  = word | word word ;                        (* names registered in the action registry *)
label        = word ;                                    (* a parameter label of that action *)
argument     = expression | word ;                       (* a bare word for an option parameter *)

expression   = or ;
or           = and { "or" and } ;
and          = not { "and" not } ;
not          = "not" not | comparison ;
comparison   = primary [ ( "==" | "!=" | "<" | "<=" | ">" | ">=" ) primary ] ;
primary      = ( literal | call | identifier | "(" expression ")" | "[" [ expression { "," expression } ] "]" )
               { "." identifier } ;
call         = identifier "(" [ expression { "," expression } ] ")" ;   (* no space before "(" *)

literal      = string | number | duration | "true" | "false" ;
string       = '"' { character | escape | interpolation } '"' ;         (* on one line *)
plain-string = string without interpolation ;
escape       = "\" ( '"' | "\" | "n" | "t" | "{" | "}" ) ;
interpolation= "{" identifier { "." identifier } "}" ;
number       = digit { digit } [ "." digit { digit } ] ;                (* at most 18 characters, no sign, no exponent *)
integer      = digit { digit } ;
duration     = number ( "ms" | "s" | "m" ) ;
identifier   = ( letter | "_" ) { letter | digit | "_" } ;              (* Unicode letters; not a reserved word *)
word         = identifier ;
trivia       = newline | ";" | comment ;
comment      = "#" { any character except newline } ;

Reserved words: flow version param allow domains limit steps duration timeout space let for in parallel if else collect into as and or not true false.

Notes:

  • When an action declares a parameter labelled as (export … as markdown), as is that parameter and the action's result cannot be named. For every other action as name names the result.
  • A word is read as a label only if the action has that label and a value follows; otherwise it is a value.
  • Statements end at a newline, at ; or before }.

# Types

text, number, bool, url, duration, page, article, report, file, list<T>. There are no user-defined types. Parameters are text, number, bool or url.

Type Fields
page url: url, title: text
article title, text, byline, language: text, url: url, links: list<url>
report title, text: text, citations: list<url>
file name, path: text

Rules:

  • A string literal is a url where a URL is expected; any other text needs url(text).
  • ==/!= compare two values of the same simple type; <, <=, >, >= compare numbers or durations; and/or/not take booleans (and/or short-circuit).
  • Names are assigned once. A name defined in a block is visible until the end of that block. Redefining a visible name is an error.
  • collect value into name appends to a workflow-wide list (list<type of value>); the name can be read anywhere, including before the first collect (it is then empty).
  • Branches of parallel (and iterations of for … parallel) run at the same time on a copy of the values that existed before the block. A branch cannot see a sibling's result. Results named by the branches of a parallel block are visible after the block; collected values are appended in branch order, whatever order they finished in.

# Functions

Pure; none performs I/O; new functions cannot be defined.

count(list|text) → number, empty(list|text) → bool, contains(text, text) | contains(list<T>, T) → bool, first(list<T>) → T (the step fails on an empty list), take(list<T>, number) → list<T>, unique(list<T>) → list<T>, allowed(list<url>) → list<url> (keeps the URLs on the allowed domains), join(list<text>, text) → text, host(url|page) → text, url(text) → url, text(value) → text, lower, upper, trim (text) → text.

# Actions (standard registry)

Action Result Capability Confirmation
open <url> page navigate
close <page> navigate
extract article from <page> article read
extract text from <page> text read
extract links from <page> list<url> read
summarize <article|report|text|list<article>|list<text>> [with citations] [length short|medium|long] report ai
ask <text> about <article|report|text|list<…>> text ai
export <report|article|text> as markdown|text|html|json to downloads|documents write-file
download <url> file download always
save note <text|report|article> [title <text>] write-note
bookmark <url|page> [title <text>] write-bookmark
fill <text selector> on <page> with <text> interact
click <text selector> on <page> interact always
submit <text selector> on <page> submit-form always
notify <text> notify
wait <duration> (≤ 60 s, done by the engine) none

# Safety rules checked before a workflow can run

Rule Diagnostic code
Every loop has a static limit between 1 and 100 unbounded-loop, loop-limit-out-of-range
parallel width between 1 and 8; at most 16 branches unbounded-parallel, parallel-width-out-of-range, too-many-branches
limit steps ≤ 500 (default 50), duration ≤ 3600 s (default 300 s), timeout ≤ 300 s (default 30 s) limit-out-of-range, duplicate-limit
Any network action or URL requires allow domains missing-allow-domains
Domains are registrable names: no scheme, path, wildcard, IP address or bare TLD; at most 50 invalid-domain, too-many-domains
URL literals are http/https, without credentials, with a constant host that is on the list; interpolation only after the host invalid-url, dynamic-host, domain-not-allowed
Names, types, fields, functions, options and arguments resolve undefined-name, duplicate-name, reserved-name, type-mismatch, unknown-member, unknown-function, wrong-argument-count, unknown-action, unexpected-argument, missing-argument, duplicate-argument, invalid-option, no-result
Language version is 1 unsupported-version
Bounded text: ≤ 256 KB, ≤ 2000 statements, blocks ≤ 8 deep, expressions ≤ 32 deep, chains ≤ 32 source-too-large, too-many-statements, nesting-too-deep

Recursion is impossible: a workflow cannot define anything callable and no action runs a workflow. The validator also computes the worst-case number of steps (loop limits multiplied) and warns (step-budget) when it exceeds the step limit.

Every diagnostic has a severity, a code, a message, a source range (UTF-16 offset, 1-based line and column) and a fix hint. At most 200 diagnostics are reported per compilation.

# What is enforced again while running

Static checks cannot see run-time values, so the interpreter repeats them on the actual values:

  1. Capability: an action whose capability is not in the run's grant fails before the host is called.
  2. Domains: every url, every page (its current URL) and every list of them passed to an action must be on the allow-list — including values that came from a page (article.links), from a parameter, from url(text) or from a saved checkpoint. The page returned by open is checked too (redirects). The host receives the policy in FlowActionCall.policy and must apply it to redirects and sub-navigation it performs itself.
  3. Interpolation into a URL percent-encodes the value as one component (only A–Z a–z 0–9 - . _ ~ are kept), so a value cannot add a path segment, a query or a fragment.
  4. Budgets: the step counter (shared by all branches), the run duration and the per-step timeout. Time spent waiting for a user confirmation is not charged to the duration.
  5. Loop limit: a loop takes at most limit items whatever the list holds.
  6. Host answers are checked: declared result type, list length ≤ 2000, text ≤ 4 MiB.
  7. Confirmation: actions marked "always" pause the run (awaitingConfirmation) until the host answers.
  8. Cancellation: cancelling the task that runs the workflow cancels the current steps cooperatively.

# Dry run

FlowRunner.plan(program, parameters:, grant:) returns a FlowPlan: every action in program order with its rendered summary, URLs (resolved from the parameters, or marked unresolved when only known while running), capability, whether it is granted, whether it asks for confirmation, how many times it can repeat, and whether it is conditional or parallel; plus required and missing capabilities, the worst-case numbers of steps and confirmations, the limits, the allowed domains and the list of problems. The planner takes no host: it cannot have side effects.

# Run log and resume

A FlowRunRecord holds the status, one FlowStepRecord per executed action (path, summary, start, end, status, error) and a checkpoint: the index of the next top-level statement and the values that existed there. With a FlowRunStore observer the record is saved in the module's own table (flow_runs) at the start, after every step change, after every top-level statement and at the end.

FlowRunner.resume(record, program:, grant:) continues from the checkpoint if the workflow text is unchanged (SHA-256). Statements before the checkpoint are not executed again. The statement that was interrupted is executed again from its beginning: if it is a loop that had done three of five iterations, those three run again. The step count carries over; the duration limit starts afresh. Pages in the checkpoint keep their handle and URL; the host must treat an unknown handle as stale and reopen the URL (which the engine has re-checked).

# Editor support

Pure functions, usable from any thread:

  • FlowHighlighter.highlight(source) → non-overlapping tokens (UTF-16 ranges) classified as keyword, action, label, function, type, option, string, interpolation, number, comment, punctuation, identifier, invalid.
  • FlowCompletion.complete(source, utf16Offset:) → the range to replace and the items valid there: declarations, statement keywords and actions at the start of a statement; second word of a two-word action; labels not yet used and as; option words; types after param name:; fields after name.; names inside "{…"; and the variables in scope at the cursor (filtered by expected type for action arguments) with the functions.
  • FlowFormatter.format(source:) → canonical layout (4-space indentation, one statement per line, declarations in the order parameters, domains, limits; comments kept) or nil when the text has syntax errors. format(format(x)) == format(x). A comment at the end of a line moves above the next statement.

# Not verified / limits

  • No host exists yet: the interpreter is tested against a scripted in-memory host only. Opening tabs, extraction, AI summaries, file export and downloads have never run for real.
  • The timeout and cancellation are cooperative: a host whose perform ignores task cancellation delays the end of the step until it returns.
  • Domain matching is suffix matching on the host. It does not consult the Public Suffix List: allow domains "co.uk" is accepted and would allow every .co.uk site.
  • Run logs contain the URLs and the values of the workflow (in the local database, like history). Runs started from a private (ghost) context must use a runner without a store; the engine cannot detect that context itself.
  • The formatter drops nothing but layout, with one exception: redundant parentheses.
Files main
Menu

Theme