SPB Git

Repository Public License

FLOW_LANGUAGE.md 14.1 KB 243 lines markdown

1# The Flow language (version 1)23Flow is the declarative workflow language of ORIX Navigator. A workflow is **text** (`Workflow.source`), interpreted4by `FlowEngine` over a fixed set of actions. It is data, not a program: it cannot define functions, cannot load or5download code, has no unbounded loop and no recursion, and every effect goes through the host application after6capability, domain and confirmation checks.78Module: `Packages/NavigatorKit/Sources/FlowEngine`. Extension points and platform rules: [SDK.md](SDK.md).910## Example1112```13# Reads an encyclopedia article and a few of the pages it links to,14# then writes a summary with citations.15flow "Research brief" version 11617param topic: text1819allow domains "wikipedia.org", "arxiv.org"20limit steps 40, duration 300s, timeout 30s2122space "Research" {23    open "https://en.wikipedia.org/wiki/{topic}" as wiki24    extract article from wiki as overview25    collect overview into sources26    # Only links that stay on the allowed domains are followed.27    for link in allowed(overview.links) limit 5 parallel 3 {28        open link as page29        extract article from page as item30        collect item into sources31        close page32    }33    if count(sources) > 0 {34        summarize sources with citations as report35        export report as markdown to downloads36    }37}38```3940Four examples ship in `FlowEngine.examples`; a test validates each of them.4142## Grammar (EBNF)4344```45program      = { trivia } header { trivia | declaration } body { trivia } ;46header       = "flow" plain-string "version" integer ;47declaration  = parameter | domains | limits ;48parameter    = "param" identifier ":" type [ "=" literal ] ;49type         = "text" | "number" | "bool" | "url" ;50domains      = "allow" "domains" plain-string { "," plain-string } ;51limits       = "limit" limit-item { "," limit-item } ;52limit-item   = "steps" integer | "duration" duration | "timeout" duration ;53body         = "space" plain-string block            (* nothing may follow the block *)54             | { statement-line } ;5556block        = "{" { statement-line } "}" ;57statement-line = { trivia } statement { ";" statement } ;58statement    = action | let | for | parallel | if | collect ;5960let          = "let" identifier "=" expression ;61for          = "for" identifier "in" expression "limit" integer [ "parallel" integer ] block ;62parallel     = "parallel" "limit" integer block ;       (* each statement of the block is one branch *)63if           = "if" expression block [ "else" ( if | block ) ] ;   (* "else" may start the next line *)64collect      = "collect" expression "into" identifier ;65action       = action-name [ expression ] { label argument } [ "as" identifier ] ;66action-name  = word | word word ;                        (* names registered in the action registry *)67label        = word ;                                    (* a parameter label of that action *)68argument     = expression | word ;                       (* a bare word for an option parameter *)6970expression   = or ;71or           = and { "or" and } ;72and          = not { "and" not } ;73not          = "not" not | comparison ;74comparison   = primary [ ( "==" | "!=" | "<" | "<=" | ">" | ">=" ) primary ] ;75primary      = ( literal | call | identifier | "(" expression ")" | "[" [ expression { "," expression } ] "]" )76               { "." identifier } ;77call         = identifier "(" [ expression { "," expression } ] ")" ;   (* no space before "(" *)7879literal      = string | number | duration | "true" | "false" ;80string       = '"' { character | escape | interpolation } '"' ;         (* on one line *)81plain-string = string without interpolation ;82escape       = "\" ( '"' | "\" | "n" | "t" | "{" | "}" ) ;83interpolation= "{" identifier { "." identifier } "}" ;84number       = digit { digit } [ "." digit { digit } ] ;                (* at most 18 characters, no sign, no exponent *)85integer      = digit { digit } ;86duration     = number ( "ms" | "s" | "m" ) ;87identifier   = ( letter | "_" ) { letter | digit | "_" } ;              (* Unicode letters; not a reserved word *)88word         = identifier ;89trivia       = newline | ";" | comment ;90comment      = "#" { any character except newline } ;91```9293Reserved words: `flow version param allow domains limit steps duration timeout space let for in parallel if else94collect into as and or not true false`.9596Notes:9798- When an action declares a parameter labelled `as` (`export … as markdown`), `as` is that parameter and the action's99  result cannot be named. For every other action `as name` names the result.100- A word is read as a label only if the action has that label **and** a value follows; otherwise it is a value.101- Statements end at a newline, at `;` or before `}`.102103## Types104105`text`, `number`, `bool`, `url`, `duration`, `page`, `article`, `report`, `file`, `list<T>`. There are no user-defined106types. Parameters are `text`, `number`, `bool` or `url`.107108| Type | Fields |109|---|---|110| `page` | `url: url`, `title: text` |111| `article` | `title`, `text`, `byline`, `language: text`, `url: url`, `links: list<url>` |112| `report` | `title`, `text: text`, `citations: list<url>` |113| `file` | `name`, `path: text` |114115Rules:116117- A **string literal** is a `url` where a URL is expected; any other text needs `url(text)`.118- `==`/`!=` compare two values of the same simple type; `<`, `<=`, `>`, `>=` compare numbers or durations;119  `and`/`or`/`not` take booleans (`and`/`or` short-circuit).120- Names are assigned once. A name defined in a block is visible until the end of that block. Redefining a visible121  name is an error.122- `collect value into name` appends to a workflow-wide list (`list<type of value>`); the name can be read anywhere,123  including before the first `collect` (it is then empty).124- Branches of `parallel` (and iterations of `for … parallel`) run at the same time on a copy of the values that125  existed before the block. A branch cannot see a sibling's result. Results named by the branches of a `parallel`126  block are visible after the block; collected values are appended in branch order, whatever order they finished in.127128## Functions129130Pure; none performs I/O; new functions cannot be defined.131132`count(list|text) → number`, `empty(list|text) → bool`, `contains(text, text) | contains(list<T>, T) → bool`,133`first(list<T>) → T` (the step fails on an empty list), `take(list<T>, number) → list<T>`, `unique(list<T>) → list<T>`,134`allowed(list<url>) → list<url>` (keeps the URLs on the allowed domains), `join(list<text>, text) → text`,135`host(url|page) → text`, `url(text) → url`, `text(value) → text`, `lower`, `upper`, `trim` `(text) → text`.136137## Actions (standard registry)138139| Action | Result | Capability | Confirmation |140|---|---|---|---|141| `open <url>` | `page` | navigate | |142| `close <page>` | | navigate | |143| `extract article from <page>` | `article` | read | |144| `extract text from <page>` | `text` | read | |145| `extract links from <page>` | `list<url>` | read | |146| `summarize <article\|report\|text\|list<article>\|list<text>> [with citations] [length short\|medium\|long]` | `report` | ai | |147| `ask <text> about <article\|report\|text\|list<…>>` | `text` | ai | |148| `export <report\|article\|text> as markdown\|text\|html\|json to downloads\|documents` | | write-file | |149| `download <url>` | `file` | download | always |150| `save note <text\|report\|article> [title <text>]` | | write-note | |151| `bookmark <url\|page> [title <text>]` | | write-bookmark | |152| `fill <text selector> on <page> with <text>` | | interact | |153| `click <text selector> on <page>` | | interact | always |154| `submit <text selector> on <page>` | | submit-form | always |155| `notify <text>` | | notify | |156| `wait <duration>` (≤ 60 s, done by the engine) | | none | |157158## Safety rules checked before a workflow can run159160| Rule | Diagnostic code |161|---|---|162| Every loop has a static `limit` between 1 and 100 | `unbounded-loop`, `loop-limit-out-of-range` |163| `parallel` width between 1 and 8; at most 16 branches | `unbounded-parallel`, `parallel-width-out-of-range`, `too-many-branches` |164| `limit steps` ≤ 500 (default 50), `duration` ≤ 3600 s (default 300 s), `timeout` ≤ 300 s (default 30 s) | `limit-out-of-range`, `duplicate-limit` |165| Any network action or URL requires `allow domains` | `missing-allow-domains` |166| Domains are registrable names: no scheme, path, wildcard, IP address or bare TLD; at most 50 | `invalid-domain`, `too-many-domains` |167| 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` |168| 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` |169| Language version is 1 | `unsupported-version` |170| Bounded text: ≤ 256 KB, ≤ 2000 statements, blocks ≤ 8 deep, expressions ≤ 32 deep, chains ≤ 32 | `source-too-large`, `too-many-statements`, `nesting-too-deep` |171172Recursion is impossible: a workflow cannot define anything callable and no action runs a workflow. The validator173also computes the worst-case number of steps (loop limits multiplied) and warns (`step-budget`) when it exceeds the174step limit.175176Every diagnostic has a severity, a code, a message, a source range (UTF-16 offset, 1-based line and column) and a177fix hint. At most 200 diagnostics are reported per compilation.178179## What is enforced again while running180181Static checks cannot see run-time values, so the interpreter repeats them on the actual values:1821831. **Capability**: an action whose capability is not in the run's grant fails before the host is called.1842. **Domains**: every `url`, every `page` (its current URL) and every list of them passed to an action must be on185   the allow-list — including values that came from a page (`article.links`), from a parameter, from `url(text)` or186   from a saved checkpoint. The page returned by `open` is checked too (redirects). The host receives the policy in187   `FlowActionCall.policy` and must apply it to redirects and sub-navigation it performs itself.1883. **Interpolation into a URL** percent-encodes the value as one component (only `A–Z a–z 0–9 - . _ ~` are kept),189   so a value cannot add a path segment, a query or a fragment.1904. **Budgets**: the step counter (shared by all branches), the run duration and the per-step timeout. Time spent191   waiting for a user confirmation is not charged to the duration.1925. **Loop limit**: a loop takes at most `limit` items whatever the list holds.1936. **Host answers** are checked: declared result type, list length ≤ 2000, text ≤ 4 MiB.1947. **Confirmation**: actions marked "always" pause the run (`awaitingConfirmation`) until the host answers.1958. **Cancellation**: cancelling the task that runs the workflow cancels the current steps cooperatively.196197## Dry run198199`FlowRunner.plan(program, parameters:, grant:)` returns a `FlowPlan`: every action in program order with its200rendered summary, URLs (resolved from the parameters, or marked unresolved when only known while running),201capability, whether it is granted, whether it asks for confirmation, how many times it can repeat, and whether it is202conditional or parallel; plus required and missing capabilities, the worst-case numbers of steps and confirmations,203the limits, the allowed domains and the list of problems. The planner takes no host: it cannot have side effects.204205## Run log and resume206207A `FlowRunRecord` holds the status, one `FlowStepRecord` per executed action (path, summary, start, end, status,208error) and a checkpoint: the index of the next **top-level** statement and the values that existed there. With a209`FlowRunStore` observer the record is saved in the module's own table (`flow_runs`) at the start, after every step210change, after every top-level statement and at the end.211212`FlowRunner.resume(record, program:, grant:)` continues from the checkpoint if the workflow text is unchanged213(SHA-256). Statements before the checkpoint are not executed again. The statement that was interrupted is executed214again from its beginning: if it is a loop that had done three of five iterations, those three run again. The step215count carries over; the duration limit starts afresh. Pages in the checkpoint keep their handle and URL; the host216must treat an unknown handle as stale and reopen the URL (which the engine has re-checked).217218## Editor support219220Pure functions, usable from any thread:221222- `FlowHighlighter.highlight(source)` → non-overlapping tokens (UTF-16 ranges) classified as keyword, action, label,223  function, type, option, string, interpolation, number, comment, punctuation, identifier, invalid.224- `FlowCompletion.complete(source, utf16Offset:)` → the range to replace and the items valid there: declarations,225  statement keywords and actions at the start of a statement; second word of a two-word action; labels not yet used226  and `as`; option words; types after `param name:`; fields after `name.`; names inside `"{…"`; and the variables in227  scope at the cursor (filtered by expected type for action arguments) with the functions.228- `FlowFormatter.format(source:)` → canonical layout (4-space indentation, one statement per line, declarations in229  the order parameters, domains, limits; comments kept) or `nil` when the text has syntax errors.230  `format(format(x)) == format(x)`. A comment at the end of a line moves above the next statement.231232## Not verified / limits233234- No host exists yet: the interpreter is tested against a scripted in-memory host only. Opening tabs, extraction,235  AI summaries, file export and downloads have never run for real.236- The timeout and cancellation are cooperative: a host whose `perform` ignores task cancellation delays the end of237  the step until it returns.238- Domain matching is suffix matching on the host. It does not consult the Public Suffix List: `allow domains239  "co.uk"` is accepted and would allow every `.co.uk` site.240- Run logs contain the URLs and the values of the workflow (in the local database, like history). Runs started241  from a private (ghost) context must use a runner without a store; the engine cannot detect that context itself.242- The formatter drops nothing but layout, with one exception: redundant parentheses.243
Files main
Menu

Theme