if runs a block when a condition holds. match picks the first matching arm, as a statement or as a value. try captures recoverable expression failures as data. for and loop handle iteration. while provides bounded pipeline loops. bail stops the script.
If
if runs statements when a condition is true. It is a statement: it does things, and it has no value of its own. To choose a value, use match or the ternary @c ? a : b.
Block form, with optional else if and else:
const @score = 72
if @score >= 90 [
show "Excellent"
] else if @score >= 70 [
show "Good"
] else [
show "Keep going"
]
The first true condition runs its block and the rest are skipped. A block can hold any statements, including let for names that live only inside it:
const @user = { name: "Ada", admin: true }
if @user.admin [
let @greeting = `Welcome back, ${@user.name}`
show @greeting
show "You have admin access."
]
Inline form, for a single effect:
const @verbose = true
if @verbose => show "verbose mode is on"
The inline form takes one effect after =>: show, log, output, run, bail, and so on. To call a function there, write run @f(), or show @f() to print its result. It has no else. Use the block form when you need more than one statement or a fallback.
Filtering a for loop. An if written straight after a for source is a filter. The loop body runs only for items that pass:
const @nums = [1, 5, 8, 2]
>> Collect the matching items
const @big = for @n in @nums if @n > 3 => @n
show @big
>> Run a block for the matching items
for @n in @nums if @n > 3 [
show `big: ${@n}`
]
The collecting form takes a value after =>. The statement form takes a block. See For with Inline Filter.
=> inside an if block. An if block is transparent to =>: a => inside it acts on whatever encloses the if. In an exe body it returns from the function:
exe @validate(input) = [
if !@input [
=> { error: "missing" }
]
=> { ok: @input }
]
show @validate("")
show @validate("data")
In a for body it gives the value for that item, and the loop carries on with the next one (see For Block Form). At the top level of a script it ends the script (see Script Return).
Assignments inside if. A block can only assign to a let declared in that same block. To pick a value based on a condition, compute it with match or a ternary instead of assigning in branches:
const @count = 3
const @label = @count == 1 ? "item" : "items"
show `${@count} ${@label}`
Conditions can use comparison and logical operators; see Conditions and Operators.
match
match checks a list of arms in order and runs the first one whose condition is true. Each arm is condition => action. * is the default arm: it matches when nothing above it did.
const @score = 85
const @hasBonus = true
match [
@score > 90 => show "Excellent!"
@hasBonus => show "Bonus earned!"
* => show "No matches" >> runs only if nothing matched
]
Only the first matching arm runs. Use separate if statements when you want several actions to run.
Put each arm on its own line, or separate arms with ;:
const @ready = false
match [ @ready => show "go"; * => show "wait" ]
A match can also compare one value against patterns: match @status [ "active" => …; * => … ]. See Match on a Subject.
Two positions. Where you write a match decides what its arms hold:
- As a statement (on its own line, like above), each arm runs an effect or a block:
show,log,output,run,bail, and so on. To call a function in an arm, writerun @f(), orshow @f()to print its result. - As a value (
const @x = match [ … ],=> match [ … ],exe @f() = match [ … ]), each arm gives a value, and thematchevaluates to the value of the arm that matched. See Value-Returning Match.
show match … is not a value position. Assign the match to a const first and show that, or put show inside the arms.
For a single condition with one effect, the inline if is shorter: if @ready => show "go". See If.
Match on a Subject
match has two forms: with a subject (match @value [ patterns ]) and without one (match [ conditions ]).
With a subject, each arm is a pattern that the subject is compared against:
const @status = "active"
match @status [
"active" => show "Running"
"pending" => show "Waiting"
* => show "Unknown"
]
The subject must be an @ reference, such as @status or @user.role. A field such as @s.length works as a subject, but a call, a method call or a parenthesised expression does not. To match on one of those, use the subject-less form and write the comparison in each condition: match [ @s.trim() == "" => … ].
Patterns a subject arm can use:
| Pattern | Matches when the subject |
|---|---|
"active", 42, @other |
equals the value |
> 5, <= @limit, != "done" |
passes the comparison |
"pending" || "queued" |
matches either one |
> 0 && < 10 |
matches both |
/^v\d+/ |
matches the regular expression |
~= "a@b.com" |
tolerantly equals the value (see Conditions and Operators) |
* |
anything (the default arm) |
const @n = 7
match @n [
> 10 => show "large"
> 5 && <= 10 => show "medium"
* => show "small"
]
const @tag = "pending"
match @tag [
"pending" || "queued" => show "Waiting"
* => show "Other"
]
const @version = "v12"
match @version [
/^v\d+$/ => show "a version tag"
* => show "not a version"
]
An array pattern is compared as a whole array (["a", "b"] matches only an equal array). To match any of several values, join them with ||.
Without a subject, each arm is a full condition:
const @score = 85
match [
@score > 90 => show "A"
@score > 80 => show "B"
* => show "F"
]
In both forms, arms are checked in order and the first match wins.
One condition, one effect: use the inline if:
const @cond = true
if @cond => show "Match"
Value-Returning Match
A match in value position evaluates to the value of the arm that matched. Value positions are the right side of const/let, the value after =>, and an exe body.
exe @classify(score) = match [
@score >= 90 => "A"
@score >= 80 => "B"
* => "F"
]
const @grade = @classify(85)
show @grade
Here each arm holds a value: a literal, a reference, a template, an object, or an expression. When no arm matches and there is no * arm, the result is null.
const @size = 7
const @label = match @size [
> 10 => "large"
> 5 => "medium"
* => "small"
]
show @label
An arm whose value is an array needs parentheses, because a bare [ after => opens a block (see Match Blocks):
const @kind = "pair"
const @parts = match @kind [
"pair" => (["left", "right"])
* => ([])
]
show @parts
Returning a match from an exe block. Put the match after =>:
exe @describe(n) = [
let @doubled = @n * 2
=> match [
@doubled > 10 => `big: ${@doubled}`
* => `small: ${@doubled}`
]
]
show @describe(8)
Early return with if. Inside an exe block, => in an if block returns from the function, because if blocks pass => through to the enclosing body:
exe @check(x) = [
if !@x [
=> "missing"
]
=> "ok"
]
show @check("")
if itself never produces a value. For a two-way choice in one expression, the ternary works too: const @msg = @ok ? "yes" : "no".
Picking from your own values: match choice. When a model or other outside input decides which arm runs, the result carries that input's labels, so a policy that refuses untrusted data at a destructive operation refuses the result too. Marking the match with choice says the arms are a menu: when the arm that matched yields a literal you wrote (a string with no interpolation, a number, a boolean or null) and the deciding value was .untrusted or .influenced, the result also gets .chosen.
import { @noUntrustedDestructive } from "@mlld/policy"
policy @rules = union(@noUntrustedDestructive)
exe .fs:w @deleteDir(dir) = `deleted ${@dir}`
const .untrusted @pick = "cleanup"
const @dir = match choice @pick [
"cleanup" => "/tmp/cache"
"archive" => "/tmp/old"
* => null
]
const @done = @deleteDir(@dir)
show @dir.mx.labels
@noUntrustedDestructive refuses .untrusted data at a destructive operation unless it is .chosen, so this call runs; the same program with a plain match is refused. The rules around .chosen:
- A
match choiceneeds a*arm, so an answer that is not on the menu has somewhere to go, and it must be used as a value; either mistake is refused when the file loads. .chosenbelongs to the exact value picked. A template, a.join, or any other value built from it does not carry it, so rebuilding a string out of picked pieces is refused again.- An arm that yields a variable, a call, an object, an array or an interpolated string mints nothing, and a match decided only by trusted values mints nothing.
- The result keeps every other label its deciding values carried,
.secretincluded, and.chosenis no exception to any other rule. - No program, policy or guard can add
.chosen; onlymatch choicemints it. It is not proof, so it does not satisfy a fact requirement or a grant.
To let a model route but never authorize, import the opt-in @noVibeAuthority fragment from @mlld/policy. Under it a .chosen value may not reach a .risk:destructive or .risk:exfil operation, and a destructive operation reached by an untrusted branch decision (.pc:untrusted) is refused. @standard and @strict do not include it.
See labels-trust for the fragment and labels-facts for proof.
Asking a person: match ask. .chosen is not proof: it says only that a value is one you wrote. To have a person pick from your menu, with proof of the answer and, when the host names them, of who chose, write match ask "question" [ … ] instead; an agent can also have a question shown, through @mlld/ask. See match-ask.
Asking a Person
match ask puts a question to the person running the program and returns what they picked. The arms are a menu you write: each starts with the label the person sees, and its value is what the match returns when they pick it. Only the picked arm runs.
const @target = match ask "Deploy the release where?" [
"Staging" => "staging-eu-1"
"Production" => "prod-us-1"
]
show `Deploying to ${@target}`
The question goes to whoever is hosting the run (see "Who answers" below). With nobody to answer, the ask refuses with no host is answering questions; a question nobody answers in time refuses with nobody answered the question in time.
A * arm, last, lets the person type their own answer instead of picking. Inside it, @mx.answer.text holds their words:
const @region = match ask "Which region?" [
"Europe" => "eu-west-1"
"United States" => "us-east-1"
* => `custom: ${@mx.answer.text}`
]
show @region
What the pick carries. A pick from your own menu carries proof of the answer: @target.mx.answer names the option picked, the question, the menu (developer), the source it came through (terminal, sdk or live) and, when the host says who answered, the principal and login. That proof is bound to the exact value picked, so a value built from it (a template, a field) does not carry it. Typed words are the person's own words and carry no proof. An answer through MCP carries none either, so it has no .mx.answer: an MCP client does not say who answered.
How this differs from match choice. match choice (see match-value-returning) marks a model's or other outside input's pick from your menu with .chosen, which is not proof: it only says the value is one you wrote. A person's pick from a match ask menu is proof. When a host the config trusts to record approvals (self_attestation: { host: { claims: ["intent", "approval", "principal"] } }) names who answered, or the pick was typed at mlld run's own prompt and the config opts the terminal in, the pick also counts as known user intent, the stamp a host approval gives, and a grant made from it is authorized by the roles the config maps that person to (see security-policies and policy-authorizations).
Letting an agent write the menu
match ask @question from @options shows a menu an agent wrote. It returns the option's text, labelled .influenced, and the pick is never authority: it proves only that the person chose that option. A menu can be your arms or an agent's options, not both.
const @options = ["rebase", "merge"]
const @pick = match ask "How should the branch land?" from @options
show @pick
Letting an agent ask
An agent can have a question put to the person without the answer passing through the model. Hand it the ask tool from @mlld/ask:
import { @ask } from @mlld/ask
tools @workerTools = {
ask_user: { mlld: @ask }
}
>> Stands in for an llm exe that runs a model with the tool list it is given.
llm @worker(prompt, config) = run cmd { echo "planned" }
const @result = @worker("Plan the release; ask the user which region if unsure", { tools: @workerTools })
for @a in @result.mx.answers [
show `${@a.mx.answer.question}: ${@a} (chosen by ${@a.mx.answer.principal})`
]
The model sees a tool ask_user that takes a question and a list of at least two options. mlld shows the question through the host, marked as written by the agent, and the model gets back one of three results:
asked: the person picked an option. The pick goes onto the LLM call's returned value, in the list.mx.answers, in the order answered; the model never sees it.not answered: nobody answered in time, no host is answering questions, or the answer named no option. Nothing is added to.mx.answers.- an error saying what is wrong with the input (fewer than two options, a repeated option, a non-string), before anything is asked.
Each answer is the option's text, labelled .influenced, with .mx.answer as above. Like any agent's menu, it never authorizes. A script that wants an answer for itself uses match ask, and calling @ask outside an LLM call is refused.
.mx.answers belongs to the value the LLM call returned. An exe that wraps the call and returns something built from it, such as @result.text, does not carry it. The answers are also recorded on the run's tape, so an agent you hand a tool that reads that tape can read them there.
What an agent wrote is shown as the agent's
A question can mix your words with an agent's: a template that interpolates a model's draft, or an agent's whole menu. Every piece of the question and every option whose value is .influenced or .untrusted is shown to the person marked as written by the agent, so an agent cannot dress up its own words as yours to steer the answer. mlld run's prompt shows such a piece as [written by an agent: …]; a host gets an agentWritten flag on each piece and option and must mark them the same way.
Who answers
mlld runat a terminal. When stdin and stderr are both a terminal,mlld runasks the person there itself: the question goes to stderr with the options numbered, and the person types a number (or their own words, where a*arm allows it). It waits up to 5 minutes and shows the time left. Anything typed before the question appeared is thrown away. A guard's or a policy rule'sask(seesecurity-guards-basics) comes the same way, as Approve (1) or Deny (2). With stdin from a pipe or a file there is nobody to ask, so every ask refuses as it would with no host.mlld testnever prompts. A terminal shows who is there, not who they are: any program with a shell can start a pseudo-terminal and type into it, so an agent harness that runsmlld runthat way answers its own questions, Approve included. Withlabeling.answers.anonymouslistingterminal, its picks also count as known user intent, so opt the terminal in only where nothing but a person runsmlld runon one. The config's policy may list it, and so may the project's own policy, declared over an object the script writes out in full:const @answers = { labeling: { answers: { anonymous: ["terminal"] } } }thenpolicy @answers_policy = union(@answers)(seesecurity-policies).- A program that embeds mlld. Over
mlld serve live --stdioand the language SDKs, a request started with host asks gets each question as aguard_askevent and answers it with the option's id (seeconfig-live-stdioandsdk-language-sdks). Starting the request with host asks is what lets the host answer a guard's or policy'saskas it happens: its Approve allows the operation with noself_attestationrow. A request started without host asks has nobody to answer, and the ask refuses. What the host's answers count for once they are read back from a tape is set by the config'shostrow instead (see "Resuming a run"). - An MCP client. When a module is served with
mlld mcpand the client advertisedelicitation, a question raised by a tool call is sent to the client as anelicitation/createrequest. Declining or cancelling refuses.mlld mcpkeeps no tape, so these answers are not recorded. Whatever answers the client is the person: a client that is itself an agent, or that answers elicitations automatically, approves its own guard and policy asks, since an Approve needs no proof. Serve a module to an elicitation-capable client only when a person answers its elicitations.
Who answered
Only the host writes who answered, as a principal: a provider-namespaced account id such as gh:12345678, with an optional login for display. A script cannot set it, and mlld looks nothing up: it trusts the host that wrote it, and only when the project config trusts that host's writes. Hosts should send the account's stable numeric id, not its login, because a login can be renamed and then claimed by someone else. No signed-in person means no principal.
A principal grants nothing by itself. The project's config maps principals to roles (labeling.principals, see security-policies), and a role applies to that person's answer only: to a grant made from their pick, never to the run or to an agent's tool calls. An answer typed at mlld run's prompt names nobody, so it never carries a role; the config or the project's own policy can still let it count as proof (labeling.answers.anonymous).
Switching on an exception
A .priv.sss policy may write exceptions a person can switch on for a while (see policy-label-flow, "Exceptions a person switches on"). When a call is about to be refused and such an exception would let it through, mlld asks the person through the host, as a guard_ask event with source: "activation" and an activation field naming the exception, its rule, the operations it allows, its limits and the roles that may switch it on. The menu is the developer's: option 1 switches it on, option 2 keeps the restriction. Only a host answers it: a terminal answer names nobody and an MCP elicitation reply says nothing about who answered, so neither can switch an exception on. It counts only when the host's answer names a principal that labeling.principals maps to one of the exception's roles, and the config's host row grants principal and activate.
Resuming a run
Each answer is recorded on the run's tape, and a resumed run is served the recorded answer instead of asking again (see checkpoint-resume). The served value comes back marked as read from a tape. Its proof comes back only when the tape's seal verifies against the project's signers, and then only under the config in force now: a principal maps through today's labeling.principals, not the one the run started with, and a pick or a security ask's answer the host recorded counts only while the host row still grants approval. A security ask's recorded answer that does not count is asked again. So two gates apply to a security ask: live, the request's host-ask opt-in; on resume, a verified seal and the host row's approval. A statement restored from a snapshot gets no proof back at all. As with every recorded approval, whoever can roll the tape files back can have an earlier answer served again.
Match Blocks
An arm can run a block, [ … ], instead of a single action.
In a value match, the block ends with => and a value. That value becomes the value of the match:
exe @transform(text) = `processed(${@text})`
const @data = "raw"
const @needsProcessing = true
const @result = match [
@needsProcessing => [
show "Processing..."
let @processed = @transform(@data)
=> @processed
]
* => @data
]
show @result
In a statement match, a block arm is just a group of statements:
const @count = 12
match [
@count > 10 => [
show "Too many items"
show `Count: ${@count}`
]
* => show "OK"
]
A statement arm block is transparent to =>, like an if block. Inside an exe body, a => in such a block returns from the exe:
exe @guard(x) = [
match [
!@x => [
log "empty input"
=> "missing"
]
* => log "input present"
]
=> "ok"
]
show @guard("")
show @guard("value")
Conditions are checked in order and only the first matching arm runs.
Because [ after => always opens a block, an array value must be wrapped in parentheses: @cond => ([@a, @b]).
Local Variables
let @name = value declares a name that lives only inside the block it is written in. Blocks are the bodies of exe, if, match, for, loop, try/catch and box. At the top level of a script, use const instead.
Shared names at the top of a match. A match body can open with let lines before the first arm. Every arm can read them:
const @mode = "active"
match @mode [
let @prefix = "Status:"
"active" => show `${@prefix} Active`
"pending" => show `${@prefix} Pending`
* => show `${@prefix} Unknown`
]
Changing a let. A let can be reassigned with =, or extended with +=. Both are bare statements:
exe @collect() = [
let @items = []
@items += "a"
@items += "b"
=> @items
]
show @collect()
+= works with arrays (adds another array's items, or a single value), strings (appends), and objects (merges).
Object merge is shallow and the right-hand side wins: a colliding key's value is replaced whole, not merged.
exe @merge() = [
let @obj = { "a": 1, "nested": { "x": 1, "y": 2 } }
@obj += { "b": 3, "nested": { "x": 99 } }
=> @obj
]
show @merge()
The colliding nested key is replaced by the right-hand side, so its y is lost.
Only the same block. = and += can only change a let declared earlier in the same block. A nested block (an if, a for body, a match arm) cannot change a let from outside it, and nothing can change a const. To build a value up across a loop or a branch, return it from the loop or the match instead:
exe @evens(nums) = [
let @picked = for @n in @nums if @n % 2 == 0 => @n
=> @picked
]
show @evens([1, 2, 3, 4])
exe @sizeLabel(n) = [
let @label = match [
@n > 100 => "large"
* => "small"
]
=> `size: ${@label}`
]
show @sizeLabel(5)
No reusing visible names. A let or const may not reuse a name that is already visible from an enclosing scope: a top-level const, an import, a parameter, or an outer block's let. mlld reports an error and asks you to pick a new name. Parameters, loop variables and @input are the exception: they may reuse any name.
Conditions
Conditions and Operators
Conditions in if, match and for … if are ordinary expressions. Any value can be a condition: see Truthiness Rules for what counts as false.
Operators:
- Comparison:
<,>,<=,>=,==,!=,~=,!~= - Logical:
&&,||,! - Arithmetic:
+,-,*,/,% - Labels:
@x is .secret,@x is not .untrusted(see the security docs on labels) - Parentheses:
(@a || @b) && @c
const @role = "mod"
const @active = true
const @verified = true
const @banned = false
match [
@role == "admin" || @role == "mod" => show "Privileged"
@active && @verified => show "Active user"
!@banned => show "Allowed"
* => show "Blocked"
]
Tolerant comparison (~=):
Use ~= when the left side is produced by an LLM or otherwise has an unstable format. Strict == stays available; ~= tolerates common differences in representation:
- String and single-element array:
"alice@example.com" ~= ["alice@example.com"] - Arrays in any order:
["b", "a"] ~= ["a", "b"] - Subset matching for arrays:
["alice@example.com"] ~= ["alice@example.com", "bob@example.com"] - Null and empty are equal when the expected side is empty:
"null" ~= [] - Numeric strings:
"11" ~= 11 - A regular expression on the right:
"alice@example.com" ~= /@example\.com$/
!~= is the negation.
const @recipients = ["bob@example.com", "alice@example.com"]
const @sender = "carol@example.com"
const @cc = []
match [
@recipients ~= ["alice@example.com", "bob@example.com"] => show "Authorized recipients"
* => show "Blocked"
]
if @sender ~= /@example\.com$/ => show "Known sender domain"
if @cc !~= [] => show "Unexpected CC"
Arithmetic
Arithmetic operators work anywhere an expression is allowed: const and let values, conditions, and => values:
const @total = 2 + 3 * 4 >> 14: multiplication binds tighter than addition
const @half = 9 / 2 >> 4.5
const @rest = 10 % 3 >> 1
show `${@total} ${@half} ${@rest}`
Multiplication, division, and remainder bind tighter than addition and subtraction. Use parentheses to change the order.
Operands are turned into numbers before the operation (see Truthiness Rules for the table). Two cases are worth knowing: booleans become 1/0, and a numeric string is parsed:
const @flag = true + false >> 1
const @sum = "11" + 1 >> 12
show `${@flag} ${@sum}`
A non-numeric string or an array gives NaN rather than joining text: + is always arithmetic. Build strings with backtick templates instead.
Truthy tally
Each comparison is a boolean and booleans become 1/0, so you can add several checks into one count. This is the usual way to ask "how many of these passed?":
const @role = "user"
const @age = 30
const @email = "sam@example.com"
const @c1 = @role == "admin"
const @c2 = @age > 18
const @c3 = @email ~= /@example\.com$/
const @score = @c1 + @c2 + @c3
match [
@score == 3 => show "all three checks passed"
@score >= 1 => show "some checks passed"
* => show "none passed"
]
for
Arrow form:
const @items = ["a", "b"]
for @item in @items => show `Processing ${@item}`
for @n in [1,2,3] => log @n
The arrow form runs one action per item. For several statements per item, use a block: see For Block Form. To collect a result for each item, assign the loop: see For Collection Form.
For Collection Form
Collection form (returns results):
const @doubled = for @x in [1,2,3] => @x * 2 >> [2, 4, 6]
const @users = [{ name: "Ada" }, { name: "Lin" }]
const @names = for @user in @users => @user.name >> ["Ada", "Lin"]
Collecting into an object (a map / lookup table):
When the body yields a single-entry object with a computed key ({ [@expr]: ... }), the entries merge into one object instead of an array — like a dict comprehension where the returned shape decides:
const @scores = {"alice": 1, "bob": 2}
const @doubled = for @name, @score in @scores => { [@name]: @score }
>> { "alice": 1, "bob": 2 } (one object, not [ {alice:1}, {bob:2} ])
const @people = [{ id: "x", name: "Xavier" }, { id: "y", name: "Yvonne" }]
const @byId = for @p in @people => { [@p.id]: @p.name }
show `${@byId.x}` >> Xavier
Only a computed key opts into the map. A static literal key (=> { count: @n }) collects into an array. Duplicate keys are an error — de-duplicate the source or compute distinct keys. Each field keeps its own labels and taint through the merge (a value labeled .secret stays .secret on its field of the map).
For Block Form
Block form:
exe @transform(x) = `<${@x}>`
exe @validate(x) = @x.trim()
const @items = [" a ", " b "]
for @item in @items [
let @processed = @transform(@item)
show `Done: ${@processed}`
]
>> Collection with block
const @results = for @item in @items [
let @step1 = @validate(@item)
let @step2 = @transform(@step1)
=> @step2
]
show @results
What => does in a for body. In a for body, => gives the value for the current item and moves on to the next item. It does not return from an enclosing exe. An if block inside the body passes => through, so an early => in an if picks that item's value:
const @labels = for @n in [1, 5, 9] [
if @n > 4 [
=> `big ${@n}`
]
=> `small ${@n}`
]
show @labels
mlld validate points out a => inside an if inside a for body, since it is easy to read as an early return from the function.
To leave an item out, use skip; to stop the loop, use done:
const @firstEvens = for @n in [2, 4, 5, 6] [
if @n % 2 != 0 [ done ]
=> @n * 10
]
show @firstEvens
done ends the loop and keeps the values collected so far. See Skip Keyword for skip.
A collecting block can run show, log, output and append for each item, so a long fan-out reports progress and writes per-item files as it goes. This works in for parallel(N) too. Without =>, the item is the value of the last statement: the shown value for show, and an empty string for log, output and append.
exe @review(item) = `Review of ${@item}`
const @items = ["alpha", "beta"]
const @reports = for parallel(4) @item in @items [
show `Reviewing ${@item}`
let @report = @review(@item)
output @report to `reports/${@item}/review.md`
=> @report
]
Variables in the body. A let in the body is fresh for each item. The body cannot change a let or const from outside the loop; to build something up across items, collect it with => as above. See Local Variables.
For with Inline Filter
An if written straight after the for source filters the items. Only items that pass run the body.
Collecting form: the value after => is kept for each passing item:
const @items = ["a", null, "b"]
const @valid = for @x in @items if @x != null => @x
const @users = [{ name: "Ada", role: "admin" }, { name: "Lin", role: "dev" }]
const @admins = for @u in @users if @u.role == "admin" => @u.name
show @valid
show @admins
Statement form: the filter takes a block, which runs for each passing item:
const @scores = [40, 85, 92]
for @s in @scores if @s >= 80 [
show `pass: ${@s}`
]
After => the filter takes a value, not an effect. To run show or another effect for each passing item, use the block form.
For filtering with more than one condition, or with a different value per case, use a match with skip: see Skip Keyword.
Skip Keyword
Skip keyword (drop items from results):
const @items = [{ id: 1, valid: true }, { id: 2, valid: false }]
const @filtered = for @x in @items => match [
@x.valid => @x.id
* => skip >> omit this item from results
]
show @filtered
The same as an inline filter, but it allows a different value per case:
exe @transformA(item) = `A:${@item.name}`
exe @transformB(item) = `B:${@item.name}`
const @data = [{ type: "a", name: "x" }, { type: "b", name: "y" }, { type: "c", name: "z" }]
const @processed = for @item in @data => match [
@item.type == "a" => @transformA(@item)
@item.type == "b" => @transformB(@item)
* => skip >> unknown types dropped
]
show @processed
skip also works as a statement in a block body: if !@item.ok [ skip ].
Object Iteration
Object iteration:
const @cfg = {"host": "localhost", "port": 3000}
for @k, @v in @cfg => show `${@k}: ${@v}`
>> Output: host: localhost, port: 3000
Value-only form:
for @v in @cfg => show `${@v.mx.key}: ${@v}`
When you bind only the value, the key is available at @v.mx.key and @v_key. The key/value form does not bind @v_key.
Nested For Loops
Nested for:
for @x in ["A","B"] => for @y in [1,2] => show `${@x}-${@y}`
>> Output: A-1, A-2, B-1, B-2
Batch Pipelines
Batch pipelines (process collected results):
A trailing => | @stage runs a pipeline stage over the whole collected array. The stage is any exe that takes the array. The @mlld/array module has common ones (import { @sum, @sortBy, @unique, @groupBy } from @mlld/array), .reduce(…) folds a list in mlld itself (see builtins-methods), and you can define your own:
exe @sum(arr) = js { return arr.reduce((a, b) => a + b, 0) }
exe @sortBy(arr, key) = js { return [...arr].sort((a, b) => a[key] - b[key]) }
exe @process(item) = js { return { ...item, done: true } }
const @total = for @n in [1, 2, 3, 4] => @n => | @sum
show @total >> 10
const @items = [{ name: "b", priority: 2 }, { name: "a", priority: 1 }]
const @sorted = for @item in @items => @process(@item) => | @sortBy("priority")
show @sorted >> a first, then b
A stage name that is not a defined function is an error: the loop does not run.
Parallel For
Run iterations concurrently with for parallel.
exe @process(x) = `processed ${@x}`
exe @runTask(task) = `ran ${@task.id}`
const @items = ["a", "b", "c"]
const @tasks = [{ id: 1 }, { id: 2 }, { id: 3 }]
>> Default concurrency (MLLD_PARALLEL_LIMIT, default 4)
for parallel @x in @items => show @x
>> Custom concurrency cap
const @ran = for parallel(3) @task in @tasks => @runTask(@task)
>> With pacing (delay between starts)
const @paced = for parallel(2, 1s) @x in @items => @process(@x)
>> Variable cap and pacing
const @cap = 2
const @pace = "1s"
const @capped = for parallel(@cap, @pace) @x in @items => @process(@x)
show @capped
Parallel blocks:
exe @runTask(task) = `ran ${@task.id}`
const @tasks = [{ id: 1 }, { id: 2 }, { id: 3 }]
for parallel(3) @task in @tasks [
let @result = @runTask(@task)
show `Done: ${@task.id}`
]
Error handling:
- Errors accumulate in
@mx.errors - Failed iterations add error markers to results
- A branch cannot change anything outside it (declare with
letinside the body, and collect results with=>) - Writes to a record slot of a
stateare held per branch and applied once after the whole loop, in input order (see State in Parallel Branches)
exe @run(t) = js { if (t === "bad") throw new Error("failed: " + t); return "ok " + t }
exe @repair(results, errors) = `${@errors.length} task(s) failed`
exe @process(tasks) = [
let @results = for parallel @t in @tasks => @run(@t)
=> match [
@mx.errors.length == 0 => @results
* => @repair(@results, @mx.errors)
]
]
show @process(["a", "b"]) >> ["ok a", "ok b"]
show @process(["a", "bad", "c"]) >> 1 task(s) failed
Fail-fast canary
for parallel runs the first iteration to completion before fanning out the rest. If that canary fails, the loop aborts before the remaining branches start. This adds one fixed wave: parallel(N) over N items runs in two waves (~2x a single item) and is fully sequential at N=2.
Opt out to start all branches at once, trading fail-fast for full-width throughput:
mlld run script --no-parallel-canary
MLLD_PARALLEL_CANARY=0 mlld run script >> also: false, off, no
{ "parallel": { "canary": false } }
Resolution precedence: --no-parallel-canary flag > MLLD_PARALLEL_CANARY env > mlld-config.json > default true. With the canary disabled, an if filter still applies per iteration and iteration errors collect in @mx.errors instead of aborting.
State in Parallel Branches
A write to a record slot (@book.upsert("contact", …)) inside a parallel branch is checked when the branch makes it, then held. While the loop runs, every branch reads the slot as it was before the loop, so a branch does not see its own held writes or a sibling's. After all branches finish, mlld applies the held writes in input order, including writes a branch made before it failed. Reads after the loop see them all.
Writes to an ordinary slot (@s.append("notes", …), @s.increment("count")) are not held: they apply at once, and a sibling branch running at the same time may or may not see them. To collect values from branches in a fixed order, return them with => instead.
For Loop Context
Loop context via @mx.for:
const @items = [10, 20, 30]
for @n in @items => show `Index: ${@mx.for.index}, Value: ${@n}`
>> Output:
>> Index: 0, Value: 10
>> Index: 1, Value: 20
>> Index: 2, Value: 30
Available @mx.for fields:
@mx.for.index- Current 0-based iteration index@mx.for.total- Total number of items in collection@mx.for.key- Key for objects, stringified index for arrays@mx.for.parallel- Boolean indicating parallel execution
Array binding metadata @item.mx.index:
const @items = [10, 20, 30]
for @item in @items => show `Item ${@item.mx.index}: ${@item}`
>> Output:
>> Item 0: 10
>> Item 1: 20
>> Item 2: 30
For arrays, the loop-bound variable exposes @item.mx.index with the zero-based array position. This works in expressions, if filters, templates, directive bodies, and nested loops.
Object iteration:
const @cfg = {"host": "localhost", "port": 3000}
for @v in @cfg => show `Key: ${@v.mx.key}, Value: ${@v}`
>> Output:
>> Key: host, Value: localhost
>> Key: port, Value: 3000
Object iteration binds @v.mx.key but does not set @v.mx.index.
In parallel loops:
const @tasks = ["a", "b", "c"]
for parallel(2) @item in @tasks => show `Slot ${@mx.for.index}, item ${@item.mx.index}: ${@item}`
@mx.for.parallel returns true in parallel loops, false in sequential loops.
Each branch of a parallel loop sees its own @mx.for.index, so @mx.for.index and @item.mx.index agree in both sequential and parallel loops. Parallel iterations still complete out of order, so show output arrives in completion order rather than source order; the collection form (const @results = for parallel ...) returns results in source order.
Loop Blocks
Block-based iteration with explicit done and continue.
const @result = loop(10) [
let @count = (@input ?? 0) + 1
if @count >= 3 => done @count
continue @count
]
Control keywords:
done @value- Exit loop and return valuedone- Exit loop and return nullcontinue @value- Next iteration with new@inputcontinue- Next iteration with unchanged@input
A loop body ends each pass with done or continue; if neither runs, the next pass starts with @input unchanged, until the loop reaches its cap and returns null. => is not allowed in a loop body; done @value is how a loop produces its value.
done exits the loop, not the entire script. Execution continues with the next statement after the loop. To capture the exit value and act on it conditionally:
const @result = loop(10) [
let @count = (@input ?? 0) + 1
if @count >= 3 => done @count
continue @count
]
if @result => show `Loop returned: ${@result}`
To halt execution entirely, use bail:
loop(10) [
if @mx.loop.iteration > 5 => bail "Too many iterations"
continue
]
@input starts as null and updates only via continue @value.
Loop context (@mx.loop):
iteration- Current iteration (1-based)limit- Configured cap or null for endlessactive- true when inside loop
Until clause:
loop until @input >= 3 [
let @next = (@input ?? 0) + 1
show `${@next}`
continue @next
]
With pacing:
loop(endless, 10ms) until @input >= 3 [
let @next = (@input ?? 0) + 1
show "poll"
continue @next
]
Bail Directive
Terminates the entire script immediately with exit code 1. Works from any context including nested blocks and imported modules.
>> Explicit message
bail "config file missing"
>> With variable interpolation
const @missing = "database"
bail `Missing: ${@missing}`
>> Bare bail (uses default message)
bail
Exit from nested contexts:
>> From if blocks
if @checkFailed [
bail "validation failed"
]
>> From match arms
match [
!@ready => bail "not ready"
* => run @process()
]
>> From for loops
for @item in @items [
if !@item.valid [
bail `Invalid item: ${@item.id}`
]
]
Terminates imported modules:
When an imported module calls bail, the entire script terminates, not just the module:
>> module.mld
const @data = "ok"
if !@configured [
bail "module not configured"
]
export { @data }
>> main.mld
import { @data } from "./module.mld" >> terminates here
show @data >> never reached
Exit behavior:
- The run stops immediately with exit code 1.
- The resolved bail message goes to stderr (prefixed
mlld:); whatever
the document had already emitted stays on stdout. - The message is never catchable: a
tryaround a bail does not catch it, and
a hook body re-raises it rather than swallowing it. - Default message: "Script terminated by bail directive."
- Message accepts strings, variables, and expressions. Nullish values and
blank strings fall back to the default;0andfalseare used verbatim.
Three things you cannot guess:
- In a parallel
for, a bail poisons the cursor: no NEW iteration starts
after the bail, every already-started iteration runs to completion, and the
first bail is the error the loop raises. A bail in the canary (first)
iteration aborts before the pool starts at all. - Under
--no-stream, output emitted before the bail is discarded — an
aborted run produces no document. Under the default streaming mode you see
the partial document on stdout before the process exits 1. - One exception: inside an exe served as an MCP tool (
mlld serve/mcp),
a bail fails that tool call and the server keeps serving — a single tool
call cannot take down a server other clients are using.
While Loops
Bounded iteration with while.
exe @countdown(n) = match [
@n <= 0 => done "finished"
* => continue (@n - 1)
]
const @result = 5 | while(10) @countdown
Control keywords:
done @value- Terminate, return valuedone- Terminate, return current statecontinue @value- Next iteration with new statecontinue- Next iteration with current state
While context (@mx.while):
iteration- Current iteration (1-based)limit- Configured capactive- true when inside while
Accumulator pattern — build a collection over iterations:
exe @fetchNext(cursor) = js {
const n = cursor ?? 0;
if (n >= 2) return null;
return { value: "d" + n, cursor: n + 1 };
}
exe @collect(state) = [
let @items = @state.items
let @next = @fetchNext(@state.cursor)
if !@next [
done @items
]
continue { items: @items.concat([@next.value]), cursor: @next.cursor }
]
const @all = { items: [], cursor: null } | while(50) @collect
show @all >> ["d0", "d1"]
With pacing:
exe @processor(n) = match [
@n >= 3 => done @n
* => continue (@n + 1)
]
const @result = 0 | while(100, 1s) @processor >> 1s between iterations
show @result >> 3
Foreach
foreach is not part of mlld. To apply a function to every item of an array, use a for expression: bind a loop variable and call the function on it.
const @names = ["alice", "bob", "charlie"]
exe @greet(name) = `Hi ${@name}!`
const @greetings = for @name in @names => @greet(@name)
show @greetings >> ["Hi alice!", "Hi bob!", "Hi charlie!"]
See for for the full collection-expression reference, and Batch Pipelines for running a stage over the collected results.
exe
Recursive Functions
A function may call itself, directly or through other functions. There is nothing to declare: every exe may recurse, and a depth limit stops a runaway.
exe @lte1(n) = js { return n <= 1 }
exe @dec(n) = js { return n - 1 }
exe @mul(a, b) = js { return a * b }
exe @fact(n) = [
if @lte1(@n) [ => 1 ]
let @prev = @dec(@n)
let @rest = @fact(@prev)
=> @mul(@n, @rest)
]
show @fact(5) >> 120
Two functions that call each other work the same way.
Depth limit
Default maximum depth: 64. Override with the MLLD_RECURSION_DEPTH environment variable:
MLLD_RECURSION_DEPTH=128 mlld run myscript
When the limit is exceeded:
'@fact' exceeded maximum recursion depth (64). Add a base case or
increase the limit with MLLD_RECURSION_DEPTH.
The limit counts each function separately, so several functions calling each other can nest deeper than it. If a recursion runs out of stack before any function reaches the limit, it stops with a similar error:
'@fact' exceeded the interpreter's stack: recursion went too deep. Add a
base case or lower the limit with MLLD_RECURSION_DEPTH.
Works inside for and for parallel
Each iteration runs independently — concurrent branches track their own depth:
const @inputs = [1, 2, 3, 4, 5]
const @results = for parallel(3) @n in @inputs => @fact(@n)
show @results >> [1, 2, 6, 24, 120]
Combining with llm
llm @plan(task) = [
if @task.depth >= @maxDepth [ => @withKind(@task, "atomic") ]
let @kind = @classify(@task)
if @kind == "atomic" [ => @withKind(@task, "atomic") ]
let @children = @decompose(@task)
let @planned = for parallel(5) @child in @children => @plan(@child)
=> @withChildren(@task, @planned)
]
mlld records every model call a run makes, including those inside recursive calls, so a resumed run reuses the answers it already has instead of asking the model again. See Checkpoint & Resume.
Try Expression
try evaluates one expression and returns a result object instead of aborting on recoverable failures.
exe @parseAddress(text) = js {
const [street, city] = text.split(",").map(s => s.trim());
if (!city) throw new Error("expected 'street, city'");
return { street, city };
}
const @rawAddress = "12 Main St"
const @result = try @parseAddress(@rawAddress)
match [
@result.ok => show `address: ${@result.value.city}`
* => show `invalid address: ${@result.error.message}`
]
>> invalid address: expected 'street, city'
Successful expressions return:
{ ok: true, value: <normal result>, error: null }
Catchable failures return:
{ ok: false, value: null, error: { class: "...", message: "...", ... } }
Use try where a failed parse, cast, code block, or helper executable is an expected branch:
exe @loadConfig(path) = [
let @parsed = try <@path>|@parse
=> match [
@parsed.ok => @parsed.value
* => { mode: "default" }
]
]
A shell command that exits non-zero is a failure inside try. Outside try, run keeps the command's output as its value and the script continues; inside it, ok is false and error.message names the exit code:
const @r = try run cmd { false }
show @r.ok >> false
show @r.error.message >> Command execution failed (exit 1): false
This covers a run written in the try itself, in its operand or its block. A run inside an exe that the try calls behaves as it does anywhere else, so a helper that reads a failing command's output keeps working.
A policy or guard denial is caught too. The refused call does not run, and error carries the denial's code and reason:
policy @guardrails = {
.secret { deny: [.risk:exfil] }
.risk:exfil { includes: [.net:w] }
}
const .secret @apiKey = "sk-123"
exe .net:w @post(body) = `posted: ${@body}`
const @sent = try @post(@apiKey)
show @sent.ok >> false
show @sent.error.code >> POLICY_LABEL_FLOW_DENIED
Some failures are not caught and still stop the run: capability denials (for example a command the policy's capabilities forbid), bail, and cancellation. A value-returning match with a denied => arm is the other way to handle a denial as an expected branch; see security-denied-handlers.
Imported MCP tool failures are recoverable when the tool throws a JSON-RPC error
or protocol isError result. Wrap each call with try, then branch on ok to
collect successes and failures:
const @attempt = try @mcp.some_tool(@args)
match [
@attempt.ok => show `tool result: ${@attempt.value}`
* => show `tool failed: ${@attempt.error.message}`
]
A caught MCP error has the fields class and message. If a tool
returns an error-shaped value instead of throwing, try reports ok: true; use
the @mlld/mcp helpers for that returned-shape case.
Catch Form
try [ ... ] catch @err [ ... ] catches the same recoverable failures and evaluates the catch block in a child scope with @err bound to the error snapshot.
exe @parseAddress(text) = js {
const [street, city] = text.split(",").map(s => s.trim());
if (!city) throw new Error("expected 'street, city'");
return { street, city };
}
const @message = try [
=> @parseAddress("12 Main St")
] catch @err [
=> `invalid: ${@err.message}`
]
show @message >> invalid: expected 'street, city'
The catch parameter must be written as an @ variable. It is scoped to the catch block.