Language specification
The complete reference for the language and the modules built into the binary, in one page. The topic pages under Language and Standard library cover the same ground a subject at a time, with more examples.
Overview
A small language for work that is not: failures are values you catch, mistakes fail at the line that made them or before the program starts, input has ceilings, and it all ships as one binary. Model calls are part of the language too - ai is a keyword, with typed output and contracts, not a library to wire up.
Philosophy: "Code that reads like intent, runs like intent."
Design Principles
- 1. Intent-Readable Syntax - Code reads like intent, not implementation
- 2. Predictable Failure - a failure is a catchable value with a stable
kind; a mistake fails where it was made - 3. Immutable by Default - a binding cannot be reassigned unless it is declared
mut; that includes a barex = v - 4. Pipeline-First - Data flows through pipelines naturally
- 5. Structured Data Native - JSON and structured values are first-class citizens
- 6. Runnable Offline - without an API key,
airuns in mock mode; programs never need network to develop
Statements and Newlines
A newline ends a statement. So does ;, which exists for short bodies (for i in 0..3 { a(i); b(i) }). ; is accepted exactly where a newline would end a statement: at top level and inside { ... } blocks (function, loop, branch and match-arm bodies). A trailing ; (before }, at end of line or end of file) and an empty statement (;;) are accepted and mean nothing. Anywhere a newline would not end a statement - inside (...), [...], a map literal, or where a value is expected (x = ;) - ; is a parse error. return; and break; carry no value. ecko fmt rewrites ;-separated statements onto separate lines, so ecko fmt --check reports a file that uses ; as unformatted. An expression continues across a newline only when:
- the line ends with a binary operator (
x = 1 +⏎2), or - the next line starts with
|>(pipeline continuation) or.(chaining), or - you are inside parentheses
(...)or brackets[...], where newlines are insignificant.result = data |> filter(pred) |> map(transform) xs = [ 1, 2, ]
Comments & Documentation
# begins a comment and runs to end of line. There is no block comment.
## is a documentation comment, read by ecko doc. Doubling the marker rather than adding a second comment syntax keeps one rule: everything from a # is a comment; a doubled one is also documentation. A third # is content, so ### heading keeps its shape.
## Fetch a user by id.
##
## Returns null when no such user exists.
##
## example:
## user = fetch(42)
export fn fetch(id) = db.get(id) # an ordinary comment, ignored by ecko doc
A ## block documents the declaration on the line below it. A blank line detaches it; an unattached block at the top of a file documents the module. An ordinary # line inside the block does not break the run, so implementation notes can sit between the docs and the code.
example: on its own line, followed by indented lines, becomes a fenced code block in the generated markdown - it reads as prose in the source and as a runnable snippet in the output.
ecko doc <file|dir> [-o <dir>] writes one markdown file per source file (to stdout without -o, mirroring the source layout with it), skipping vendor/. Exported declarations are always listed, documented or not, so gaps in the public surface are visible; undocumented private helpers are omitted.
Documenting a file follows its export ... from "./other" statements into the files that hold the declarations, with the same selectivity an importer gets: export * takes the module's whole exported surface, export { a } takes a and leaves its siblings private, and an as alias is documented under the new name. This is what a multi-file package's entrypoint means by its public surface - without it, a package that curates its API in main.ecko and keeps the implementation in siblings documents as a title and nothing else.
Variables & Mutability
name = "Ecko" # bare assignment: defines an immutable binding
# name = "Echo" # error: 'name' is immutable
mut count = 0 # explicitly mutable
count = count + 1 # OK
let ratio = 3.14 # immutable - the same as a bare assignment
let PI = 3.14159 # immutable (`let` is already a constant)
# ratio = 1.0 # error: cannot reassign immutable variable
Every binding is immutable unless it is declared mut. A bare x = v that introduces a name declares it exactly like let. Parameters, loop variables, catch variables and pattern bindings are immutable too; mut n = n at the top of a body gives a copy you can change. Reassigning an immutable binding is an error at the reassignment (a catchable {kind: "bug"} at run time), and ecko check refuses it before the program starts (immutable-reassign, an error). Redeclaring with let or mut still shadows. A function may write a top-level binding only when that binding is mut, and a closure may write a captured binding only when it is mut. Top-level code runs in order, so in a block at the top level (a loop body, an if), assigning a name whose top-level declaration comes further down declares a local of that block: the global does not exist yet. _ is the discard and can be assigned any number of times. ecko fix --migrate --only=mut adds mut at the declaration of every binding a program reassigns.
const is a deprecated alias for let - the two are identical (both immutable). ecko check warns (deprecated-syntax) on const, and both ecko fmt and ecko fix --migrate rewrite it to let; a future major removes the keyword (see Migrating off deprecated syntax).
Assignment works through fields and indexes (the root binding must be mutable):
mut user = { name: "Alice", tags: ["a"] }
user.name = "Bob"
user.tags[0] = "admin"
Compound assignment (+= and friends)
mut total = 0
for n in [3, 4, 5] {
total += n # total = total + n
}
mut stats = { hits: 0, tags: [1] }
stats.hits += 1
stats.tags[0] *= 10
x op= e means exactly x = x op e, for op one of + - * / // %, and follows every rule the long form does: the target must be mut (or a path whose root is), += on a string needs a string on the right, and an undefined target is an undefined-variable error - a compound assignment updates a binding and never creates one. It is a statement, not an expression, so print(x += 1) is a parse error.
The long form evaluates the target twice, so a target whose object or index could have a side effect is refused at parse time rather than run that way: xs[next()] += 1 is an error that says to bind the index first (i = next() then xs[i] += 1). A target made of names, literals, fields and indexes of those is accepted. ecko fmt keeps whichever form you wrote.
Destructuring bindings
Bind or reassign several names from a list at once, the same flat, strict form as for-loop destructuring: two or more parenthesized names, and the value must be a list of exactly that length.
let (a, b) = [1, 2] # two new immutable bindings: a = 1, b = 2
mut (x, y) = [10, 20] # ...mutable ones
(x, y) = [y, x] # bare form reassigns existing mut vars - a swap
let (user, host) = split("ada@example.com", "@") # reads well with functions that return a list
let (a, b) = [1, 2, 3] # error: destructuring expected 2 elements, got 3
let/mut introduce new bindings; the bare (a, b) = ... form reassigns existing ones (each name follows the usual rules - an immutable target is an error). Names only, no nesting; use _ to discard a position. A single name in parentheses is just a grouped expression, so (a) = 1 is an ordinary assignment.
Numbers
Ecko has three numeric types:
int- a 64-bit signed integer. Arithmetic is checked: an overflow is a runtime error, never a silent wraparound.float- a 64-bit IEEE-754 binary float, for scientific/approximate work. Literals take an optional exponent:1e3,1.5e3,2.5e-9,6.022e23,1E5. An exponent always yields afloat, so1e3is1000.0and not the integer1000. At least one digit must follow thee(and its optional sign), which is what keepseusable as an ordinary name -2 * eis arithmetic, not a malformed literal.ecko fmtreprints a literal that was written with an exponent exactly as written, the way it reprints strings: expanding6.022e23to twenty-four digits would be the same value and a worse line.decimal- an exact base-10 number (~28 significant digits), for money and any value where0.1 + 0.2must equal exactly0.3. A decimal never rounds its own input: amliteral, adecimal("...")string or ajson.decode(..., decimal: true)number with more digits than fit is refused (a parse error, or a catchableparseerror at run time), not read as a nearby value. Zeros at the end of the fraction are dropped when they would not fit.
Division: / divides, // floors
/ always divides. Two ints give a float - 7 / 2 is 3.5, 6 / 3 is 2.0 - so a mean or a percentile cannot quietly lose its fraction. A float on either side gives a float, and a decimal stays a decimal.
// is floor division: the quotient rounded toward negative infinity. Two ints give an int (7 // 2 is 3, -7 // 2 is -4), a float on either side gives a float with no fraction (7.5 // 2 is 3.0), and a decimal gives a whole decimal (decimal(10) // 4 is 2). Floor rather than truncation keeps a == (a // b) * b + r with r taking the sign of b, as in Python. Dividing by zero is an error for both, and so is // overflowing (the one case is the smallest int by -1).
% is the remainder of that floor division, so its sign is the divisor's: -7 % 2 is 1 and 7 % -2 is -1, and a == (a // b) * b + a % b holds for every int, float and decimal. Clock and calendar arithmetic can use % on a value that may be negative - a time before 1970, a negative offset - without a correction. % accepts a float with an int, as every other arithmetic operator does; decimal with float is an error for all three.
/ on two ints used to truncate (7 / 2 was 3), and % took the sign of the dividend (-7 % 2 was -1). Code that meant a whole number now writes //; % only differs from before when an operand is negative. A / left over where a whole number was meant does not always fail: a whole Float that only feeds more arithmetic gives the right answer, slowly, off the Int fast paths. ecko check warns (exact-division) where a % == 0 guard proves the division exact.
Decimals (money-safe)
NaN does not equal itself. math.sqrt(-1.0) == math.sqrt(-1.0) is false, and so is x == x when x is NaN - the IEEE-754 rule, and the same answer every other language gives. It follows everywhere equality is asked, so contains(xs, nan) is false even when xs holds that very value. Ask with math.isnan(x), which is what it is for.
Binary floats cannot represent most decimal fractions exactly, so they are the wrong tool for money. Write a decimal with a trailing m, or build one with the decimal(...) constructor:
price = 19.99m # a decimal literal
qty = 3
subtotal = price * qty # 59.97 (exact)
tax_rate = decimal("0.0825") # from a string - no float ever involved
tax = subtotal * tax_rate # 4.947525
total = subtotal + tax # 64.917525
print(0.1m + 0.2m) # 0.3 (exact)
print(0.1 + 0.2) # 0.30000000000000004 (float)
Rules, chosen so money behaves predictably:
decimalmixes withint(which is exact) and the result isdecimal:19.99m * 3is59.97.5m == 5istrue.- Float equality is exact (IEEE
==;0.1 + 0.2 == 0.3isfalse). Useapprox(a, b)for tolerance comparison (default epsilon1e-9, override with a third argument:approx(a, b, 0.01)). decimalmixing withfloatis a hard error - a binary float must never silently contaminate an exact value. Convert explicitly if you really mean to.decimal(x)converts anintor a numericstring.decimal(aFloat)is rejected: a float has already lost precision, so pass a string (decimal("0.1")) to state the exact value you want.+,-,*preserve scale, so cents are never dropped:19.99m + 0.01mis20.00./and%return the exact quotient in normalized form:decimal(10) / 4is2.5;//floors it:decimal(10) // 4is2.- Overflow and divide-by-zero are runtime errors, like
int. int,round,floorandceilaccept a decimal and return anInt, exactly - the decimal carries its own integer part, so nothing routes through a float.inttruncates toward zero androundtakes halves away from zero (not the half-to-even a statistics library would use, because money does not work that way).float(aDecimal)stays rejected, for the same reasondecimal(aFloat)is.round(x, places, mode?)rounds toplaces(an Int from 0 to 28) and keeps the type: a decimal comes back a decimal at exactly that scale (round(12.3m, 2)is12.30m), a float a float, an Int unchanged.modeis"half_up"(the default: halves away from zero),"half_even","half_down","up"(away from zero),"down"(toward zero),"ceiling"or"floor"; an unknown mode or out-of-rangeplacesis an error.- JSON has no exact-decimal type, so
json_encodeemits a decimal as a plain number in its exact text, scale included (12.50mis12.50). Decoding gives a float by default;json.decode(text, decimal: true)(andjson.read) reads every non-integer number as an exact decimal from its source text, and a number with more than 28 significant digits is then aparseerror rather than a rounded value.
Functions & Lambdas
fn add(a, b) = a + b # expression body
fn greet(name) = "Hello, {name}!" # string interpolation
fn factorial(n) {
if n <= 1 { 1 } else { n * factorial(n - 1) }
}
double = fn(x) x * 2 # lambda (canonical)
double2 = |x| x * 2 # deprecated pipe form (warns; `ecko fmt` rewrites it)
fetch = async fn(url) http.get(url) # async lambda
The fn(params) body form is canonical - it says plainly that this is a function. The |params| body pipe form still parses but is deprecated: ecko check warns (deprecated-syntax), and both ecko fmt and ecko fix --migrate rewrite it to fn(...). A future major version removes it (see Migrating off deprecated syntax). (This is the anonymous form; a named function is fn name(params) = body.) A fn(x) { ... } body is a block, except when the brace opens a map literal - fn(c) { value: c } returns a map, because no statement can begin with name :. The explicit fn(x) ({ ... }) still works and is never ambiguous.
Functions are closures over their defining scope - they observe later updates and can mutate outer mut variables:
fn make_counter() {
mut n = 0
fn() {
n = n + 1
n
}
}
Named functions may also be declared inside another function. Plain, async, and contracted nested functions all capture the same lexical scope; that scope remains alive when a nested function is returned from its defining call.
return exits the enclosing function immediately.
fn bindings are immutable, like let: bare reassignment (f = ...) is an error. Redeclaring with an explicit let f = ... remains legal. Builtin names are also immutable, but assignment shadows them with a new immutable binding in the current scope (so sum = 0 is fine anywhere and never touches the builtin; mut sum = 0 if you mean to change it). A name bound by import follows the same rule: assignment shadows it in the current scope and never replaces the module, so json = "text" inside a function is a local of that function, in the entry file and in an imported module alike, and json.encode still works everywhere else. ecko check warns on it (shadows-import), since it is almost never meant.
Parameters: defaults and named arguments
fn box(w, h, fill = "-") = fill * (w * h)
box(2, 3) # positional
box(2, h: 3) # named; defaults fill the rest
box(2, 3, fill: "#") # mix - positional first, then named
Named arguments bind by parameter name after positional binding. Passing a parameter more than once (whether positionally and by name or by repeating a name), or naming a parameter that doesn't exist, is an error. Positional arguments may not follow named ones. Parameter binding metadata scales with the declaration; functions are not limited to 64 parameters.
Typed parameters
fn fee(amount: Decimal, rate: Decimal = 0.03m) = amount * rate
fn count_tags(id: Int, tags: List<String> = []) = len(tags)
area = fn(w: Float, h: Float) w * h
A parameter may declare a type with name: Type, before any default. The annotation is optional - an unannotated parameter accepts anything, as before - and uses the same rules as a struct field: Int widens to Float and to Decimal, Float never narrows to Int, Decimal refuses a Float, T? also takes null, List<T> and Map<K, V> check every element, a record type compares by name, a variant satisfies its sum type, and json, Any or _ take anything. Any other name is a record or sum type and takes only a value of that type: fn h(x: Tier) refuses 5, "vip" and null (write Tier? to allow null), and so does a name nothing declares. The capitalised kind names Bytes, List, Map, Null and Function written bare take a value of that kind, unless a type of the same name is declared.
It is checked twice, by the same matcher, and never only by one. When the function is entered, after defaults are filled in, every typed parameter is checked and a mismatch throws parameter \x\ of \f\ expects Int, got string (kind: "bug"), located at the annotation with the caller on the call stack. A default that does not fit its own annotation fails the same way. Before the program runs, ecko check refuses a literal argument that cannot match (param-type-mismatch, an error), positional or named, and a literal default that cannot match its annotation. A value only known at run time - a decoded payload, a map lookup, an ai result - is left to the entry check. Lambdas, async and contracted functions take annotations the same way.
T? is a value of type T, or null. It is the annotation for anything that may be absent, and it works wherever a type does - a parameter, a return type, a record field, inside a generic (List<Int?>), in ai[Int?]:
fn port(p: Int? = null) = p ?? 8080
fn find(m, k) -> String? = get(m, k)
type Contact { name: String, email: String? = null }
null is the only absence the language and the standard library use. Some/None are ordinary variants for your own modelling and are not T?: a function declared -> Int? that returns Some(1) fails its return check. The bare annotation Option names that predefined union: Some(1), None and None() all satisfy a parameter typed Option, and Ok(1) does not. Option<T> is the deprecated spelling of T? - it still means "T or null", so it does not take the None variant, ecko check warns (deprecated-syntax), and ecko fmt and ecko fix --migrate rewrite it.
An @tool function's annotations are its schema: a typed parameter is advertised to the model with the type's JSON Schema (limit: Int is {"type": "integer"}) instead of string, and offline it is passed the mock value for its type rather than the prompt.
Return types
fn total(xs) -> Int = sum(xs)
fn lookup(m, k) -> String? = get(m, k)
print([total([1, 2]), lookup({ a: "x" }, "b")])
A function may declare what it returns with -> Type after its parameters. The annotation is optional and uses the same rules as a typed parameter (above). It is checked on every value the function returns - the value the body ends with and each return - on both engines, and a mismatch throws f is declared to return Int, but returned string (kind: "bug"), located at the returning expression. A function that ends without a value returns null, which only T? (or json/Any/_) accepts. The check runs before any @ensures, so a postcondition always sees a value of the declared type. async and contracted functions are checked the same way; for an async fn the check is on the value the task produces, so await raises it. Lambdas cannot declare a return type.
ecko check refuses a literal return that cannot fit (return-type-mismatch, an error): the body's final value, through if/match/try branches, and every return <literal>, but not one inside a nested function, whose returns are its own. Anything else is left to the check at return.
Arity is checked at the call site. Calling with more arguments than parameters, or fewer than the required (non-default) parameters, raises 'f' expects N argument(s), got M (a N..M range when defaults widen it). A named-argument call that skips a required parameter raises 'f' is missing required argument 'x'. Passing null explicitly satisfies arity and does not trigger a default.
The same holds for native functions, both the globals and the std.* modules: an extra argument raises f takes at most N arguments, got M. A native with optional trailing arguments accepts them up to its own documented maximum (str.trim(s, chars?), sql.query(db, sql, params?)), and a variadic one (fs.join, fmt.format, bg.spawn) takes any number. Native arity is checked after the capability gate, so a call the caller has no capability for is refused on that ground first.
A native's options are named arguments, and only named arguments. proc.run(cmd, args, timeout_ms: 5000), http.get(url, headers: h, timeout: 2000), log.to_file(path, level: "warn"). Each such native declares its options and their types, and three mistakes that used to pass silently are errors: a positional options map (proc.run(cmd, args, { timeout_ms: 5000 }) names the named spelling), an option the native does not have (timout_ms, with did-you-mean), and a value of the wrong type (timeout_ms: 1.5). null means the option was not given. An optional positional before the options may be left out: proc.run("ls", timeout_ms: 5000). ecko check refuses the first two before the program runs (positional-options, unknown-named-argument). A map that is data rather than options stays positional: http.response's headers, a log.info call's fields, a sql block's parameters.
Contracts
@requires(x > 0)
@ensures(result > x)
fn increment(x) = x + 1
@requires runs before the body (parameters in scope); @ensures runs after (parameters and result in scope). A false condition raises an error of kind bug, raised at the call site. Its message names the condition and the values it read: precondition failed: x > 0 (x = -3) or postcondition failed: result > x (result = 1, x = 4). The caught error also carries contract ("requires" or "ensures"), condition (the condition as ecko fmt prints it) and values (a map from each name the condition reads to its value; functions are left out). In a message each value is shown as print shows it, cut at 80 characters; a secret is redacted there but stays a secret in values. A string contract that fails reads precondition failed: "<text>" and carries no values. An error raised while evaluating the condition itself keeps the @requires error: / @ensures error: prefix.
@requires conditions run in the order written, after the arguments are bound and any parameter types checked. @ensures conditions run on every way out of the body, an early return included, after the declared return type is checked. They see the parameters, result and the function's top-level bindings, but not a binding made inside a block the return is in: @ensures reads the function's own scope. Inside @ensures, result always names the returned value, even when the body has a local of that name. It is a copy: a condition may assign it (result = 5, result[0] = 99) without changing what the function returns.
A function whose contracts are all boolean expressions compiles to the bytecode VM with its checks in its own code, so a passing check costs about as much as the condition itself. It is never inlined into its callers. A function with a string contract, an @ensures on a typed ai body (the retry case), @tool, or async runs on the AST evaluator; so does one whose condition contains a return, break or continue of its own. Both engines report the same failures.
String contracts (@ensures("result is a valid email")) are verified by the LLM. Be clear-eyed about what that means:
- A boolean contract is a deterministic guarantee. A string contract is a probabilistic judgment - useful for properties you cannot express as code, but not proof. Prefer boolean contracts wherever the property is expressible.
- In mock mode (no API key) string contracts pass - they cannot catch anything offline - but not silently: a run ends with one note on stderr naming each string contract that went unchecked, and
ecko testadds a summary line counting them. Boolean contracts work identically on- and offline. - Every
@ensuresretry of anai-bodied function is a paid API call. Retries are bounded per call byECKO_AI_MAX_RETRIES(default 3), and the two retry layers compound: a typedaibody inside a failing contract can retry coercion (up to 1+3 calls) on each of up to 1+3 contract attempts - worst case 16 calls for one invocation. String contracts add one verification call per attempt, and those verification calls are themselves traced and budget-counted.ECKO_AI_MAX_CALLSis the hard stop - set it in production so a failing contract on a hot path fails fast instead of spending. - Privacy: a string contract sends the checked value (
@ensures) or the relevant parameter bindings (@requires) to your provider so the model can judge them. Don't put secrets, credentials, or PII behind a string contract - use a boolean contract (evaluated locally, nothing leaves the process) for anything sensitive.
Control Flow
status = if age >= 18 { "adult" } else { "minor" }
unless ready { wait() } # negated if: runs the body when `ready` is falsy
for i in 0..10 { print(i) } # ranges: 0..10 exclusive, 0..=10 inclusive
# lazy and unbounded - iterating never allocates
while condition { do_work() }
value = loop { # loop yields its break value
n = n + 1
if n * n > 50 { break n * n }
}
for x in items {
if skip(x) { continue }
if done(x) { break }
}
for (k, v) in config { print(k) } # destructure map [key, value] pairs
for (i, x) in enumerate(xs) { print(x) } # index + value
break/continue work in for, while, and loop; using them outside a loop is an error. for/while evaluate to null.
For-loop destructuring: two or more parenthesized names bind each item's elements directly - for (k, v) in map (map iteration yields [key, value] pairs in sorted key order), for (i, x) in enumerate(xs), or any list of lists (for (a, b, c) in triples). The binding is strict: every item must be a list with exactly that many elements, else the loop errors - silent partial binding would guess. Use _ for positions you don't need: for (_, v) in map.
Each iteration binds the loop variable afresh. A closure created in the body captures that iteration's binding, not one shared across the loop:
mut fs = []
for i in [1, 2, 3] {
fs = push(fs, fn() i * 10)
}
print(map(fs, fn(g) g())) # [10, 20, 30]
Through 0.59 the variable was one binding for the whole loop, so this printed [30, 30, 30]. Only the loop variable is per-iteration: a mut declared outside the loop is still one variable, and every closure sees its latest value. Both engines agree, and a loop whose body creates no closure costs nothing extra.
Conditions
if, unless and while take any value as a condition. false, null, 0, 0.0, 0m, "", b"", [], {} and an empty range (3..3) count as false; every other value counts as true, NaN included. and, or and not read their operands the same way, and always return a Bool.
That rule is short, but if count { ... } still hides a decision: it skips the body when the count is zero, and nothing on the line says whether zero was meant to. ecko check warns (non-bool-condition) when a condition is evidently an Int, Float, Decimal, String, List or Map - a literal, a builtin whose result kind never varies (len, split, upper, ...), arithmetic on two of one kind (n + 1 when n is an Int; mixed kinds and / say nothing), or a binding initialised with one - and names the comparison to write instead (count != 0, name != "", len(xs) > 0). A mut binding counts when its first value and every assignment to it anywhere in the program have the same evident kind, so mut count = 0 updated only by count += 1 is an Int for good. A value whose kind is not known (a parameter, a get, a user function's result, a mut assigned one) is never warned about.
A condition cannot be an assignment. if x = 2 { ... } is a parse error that names ==, the comparison it almost always meant.
unless cond { ... } is if with the condition negated - the body runs when cond is falsy. It is an expression like if (it yields the taken branch's value, or null when nothing runs) and takes an optional else; it reads best as an early-return guard: unless valid(x) { return err }.
Pattern Matching
match value {
0 => "zero"
-1 => "negative one"
n when n > 0 => "positive" # guards are evaluated with bindings in scope
_ => "negative"
}
match user {
{ role: "admin" } => "Admin access"
{ role: "user", active: true } => "Active user"
_ => "Unknown"
}
match response {
Ok(data) => process(data) # call-style variant patterns
Err(error) => handle(error)
}
Pattern bindings are scoped to the arm - they do not leak into or clobber the surrounding scope. Result (Ok/Err) and Option (Some/None) are built in.
A match over a declared type that leaves a variant without an arm, and has no _ or binding arm, is refused before the program runs (non-exhaustive-match, an error since 0.63); a guarded arm does not count as covering its variant. At run time, a value no arm accepts - one the check could not see, such as a string or a type from another module - raises Non-exhaustive match: no pattern matched <value> (the value shortened to 60 characters). When the match is written inside a catch (e) block, the message ends (while handling: <e's message>), so the error being dispatched on is not lost. This is lexical, like e itself: a function called from the catch block does not see it. User type variants match positionally by field order:
type Shape = Circle { r: Int } | Square { side: Int }
match shape {
Circle(r) => 3.14 * r * r
Square(side) => side * side
}
A variant declared with no fields is a value, not a constructor. There is only ever one Red, so the name binds to the variant itself:
type Colour = Red | Green | Blue
c = Red
c == Red # true
match c { Red => "stop", Green => "go", Blue => "cold" }
contains([Red, Green], Red) # true
Red() returns the same value, so the constructor form remains valid. A variant that declares fields is still a constructor and must be called: Circle(3).
A fieldless variant prints as its bare name, everywhere a value becomes text: print(Red), string(Red), "{c}", and inside a list or map ([Red, Green]). A variant with fields prints its fields: Circle{r: 3}.
A record is written once. A type with a single variant named after it is a record, and the brace follows the type's name directly:
type User { name: String, age: Int = 0 } # the same as type User = User { ... }
u = User("Ada")
match u { User(name, _) => name }
ecko fmt prints a single self-named variant with fields in this form. Every other declaration - several variants, or one whose name differs from the type's - keeps type T = Variant { ... }.
A type from another module may be qualified, on both sides. The brace form builds one and matches one:
import "./shapes.ecko"
c = shapes.Circle { r: 2 } # or shapes.Circle(2)
match c {
shapes.Circle { r } => r * r
shapes.Square { s } => s * s
}
The qualifier says where the type was declared, not what it is called. The value carries the bare name either way, so shapes.Circle { r } and Circle { r } match the same values and the two spellings are interchangeable - adding or removing a qualifier never changes which arm runs. ecko fmt prints back whichever you wrote.
A qualified name in a pattern has to be a constructor: shapes.Circle alone is refused rather than read as a binding, since Circle on its own would match everything and silently swallow the other arms.
Positional patterns work across modules too. shapes.Circle(r) binds by the field order shapes.ecko declared, which an import carries with the module, through export * from and export { Circle } from re-exports as well. A bare Circle(r) finds the order the same way when the file declares no Circle of its own and exactly one import exports one; when two imports export a Circle with different fields it is refused, with the qualified spelling as the fix. A positional pattern on a variant whose fields nothing visible declares - a type a module builds but does not export - is an error naming both fixes: export the type, or match it by field name with the brace form, which needs no field order. Until 0.59.2 a qualified positional pattern never matched and the match fell through to its other arms.
Error Handling
try {
risky()
} catch (error) {
print("Error: {error}")
} finally {
cleanup() # always runs
}
try/catch catches runtime errors only; return/break/continue unwind through it.
finally runs on every exit: success, an error, or an early return/break/continue. It is cleanup, not a handler. With a catch, the catch decides the outcome. With no catch, an error from the try body is rethrown, value and kind unchanged, after the finally runs. On success the try's value is the result, and the finally's value is discarded. An error thrown by the finally itself replaces the one in flight. ecko check counts the kinds a try … finally body can throw as escaping it. A bare try { … }, with neither clause, is the ignore-the-error shorthand: it is try { … } catch { null }, so any error in the body, a bug included, makes the try evaluate to null, and ecko check counts every kind as handled. Through 0.68.0, a try … finally with no catch behaved like that bare form: the error was swallowed and the try returned null.
One error dialect
Ecko has exactly one story per failure class - you can always predict what an API does:
- 1. Absence returns
null- only from the lookups documented as nullable (get(xs, i),get(m, k),os.env(...)). Everything else is strict:xs[9]andm.missingare errors at the site of the mistake. - 2. Operational failures throw
{ kind, message, ... }maps. Anything that fails because of the world - malformed data, missing files, network trouble, closed channels, exhausted budgets - throws a map with a stablekind, the human-readablemessage, and context fields. Dispatch withmatch get(e, "kind")(below);getis total, so the same match also handles a string you threw yourself (kindisnull). - 3. Programmer mistakes throw
{ kind: "bug", message }. Wrong argument types, arity errors, out-of-bounds indexing, a missing field, undefined names. You fix these rather than dispatch on them, so they share one kind, but every runtime errorcatch (e)receives is a map with akindand amessage, soe.messageis always readable.bugis ambient, likelimit:ecko checknever asks for an arm for it.ecko checkcatches most before the program starts. A value thrown witherror(v)is caught exactly as thrown. - 4.
Ok/ErrandSome/Noneare ordinary data types for your own match-based modeling. They are not the error channel; nothing in the stdlib returns them.
The stdlib's kinds: parse (json/csv/toml/yaml/regex on malformed input, with format and path where relevant), fs (file IO, with path), net (HTTP/socket/websocket failures, with url/host where known), sql (database errors; the official postgresql-client and mysql-client packages raise it too, adding driver and the server's SQLSTATE as code), closed (send on a closed channel), budget (ECKO_AI_MAX_CALLS exhausted, with calls/max/scope), capability (package code denied a gated operation, with capability and package fields, plus path when a path-scoped grant refused a specific path), and cancelled (task cancellation). Also ai, timeout (with ms from with_timeout, func from py()), io (stream reads and writes), limit (a configured ceiling), proc, os, archive, signal, watch and assert.
The whole set is ERROR_KINDS in the evaluator, and it is checked from both ends: a release fails if a kind is thrown that pubdocs/language/error-handling.md does not list, or listed and never thrown, and ecko check warns on a match arm naming a kind that does not exist, and on one naming a kind its try cannot throw. Before those existed the taxonomy lived only in prose and drifted both ways - eight kinds were being thrown that no page mentioned.
try {
resp = http.get(url)
data = json.decode(resp.body)
} catch (e) {
match get(e, "kind") {
"parse" => print("bad {e.format} payload: {e.message}")
"net" => print("offline: {e.message}")
_ => error(e) # a panic or unknown kind: re-throw
}
}
Checked error kinds
ecko check (and the LSP) works out which kinds a try body can throw and compares them with the catch's kind arms. Kinds stay strings; nothing changes at run time.
The set for a body is the union of:
- the kinds each standard-library function it calls declares (
json.decodethrowsparse;json.readthrowsfsandparse;sql.querythrowssql;sendthrowsclosed;int("x")throwsparse). A function that fails only on a programmer mistake declares none; - the sets of the program's own functions it calls, followed through the whole call graph, recursion included, and through imported files and packages (
ecko check <file>only, since it needs the file's location); - every literal
error({ kind: "not_found", .. })- this is how a program's own kinds take part with no declaration; - minus whatever an inner
trycatches and does not re-throw. A re-throw is followed:_ => error(e)passes on the kinds the other arms did not take.
Two findings, both warnings that never block a run:
unhandled-error-kind: the body can throw a kind with no arm, and there is no_(or binding) arm. Anchored at thematch, naming where the kind comes from: "json.decodeon line 4 can throw 'parse', which this catch does not handle".unreachable-error-kind: an arm names a kind nothing in the body throws, so it never runs. A near miss gets a suggestion, from the kinds the body does throw first.
What stays silent, by design:
- Unknown bodies. A call through a variable or parameter, a callback to a higher-order builtin (
map,filter,reduce,pmap,sort_by,retry,sql.transaction, ...),await,py(),ai ... using, or anerror(v)whose kind is not a literal makes the set unknown, and nothing is reported. - Ambient kinds.
limit,budgetandcancelledcan come from almost any call, andcapabilityonly from package code under a missing grant, so none of them is ever required and an arm for one is never unreachable.timeoutis not ambient: only a function that declares it can throw it. - Iterating a possible stream. A
forover anything but a literal, a range or a builtin's result may be walking a stream, which raises whatever its source does, so no arm is called unreachable there. Missing arms are still reported. - A
catchwithout a kindmatchhandles everything and is left alone, as is a kindmatchnested under anifinside thecatch.
Errors are first-class values. error(v) throws any value; catch (e) binds it. The idiom for structured errors is a { kind, message } map, so a handler can branch on the kind and re-throw the rest:
fn find_user(id) {
if id == 0 { error({ kind: "not_found", message: "no user 0" }) }
id
}
try {
find_user(0)
} catch (e) {
match get(e, "kind") {
"not_found" => default_user()
_ => error(e) # re-throw; the payload is preserved
}
}
A plain error("boom") is caught as the string "boom". An uncaught error prints error: <message> (a map's message field, if present), the source line that raised it with a caret under --> file:line:col, and the call stack, outermost call first, one name at file:line:col per frame with that line's source. The location is where the error was raised even when that is inside an imported module, a callback run by a built-in such as map or pmap, or an async fn task that was awaited; the stack then runs from the program through the callback, the task (its frame is the await) or the import (a <module file> frame). A call is located at its callee: the name in f(x) and x |> f(y), the . of obj.f(x) - never the (. A failure of the call itself (the wrong number of arguments, an unknown named argument, a parameter's or the return value's declared type, @requires, @ensures) is raised at the call, from the caller, so the stack does not list the function that was rejected. A frame is named after the function, whatever variable held it (b = boom; b() is a boom frame). The VM and the AST evaluator follow these rules identically, so an error's text does not change when a function gains a contract or becomes async. An embedder's one-line form is Runtime error: <message> (line L, col C), with in <file> inside the parentheses when the location is in an imported module. A lambda's frame, and its name in an arity error, is the name it was bound to (check = fn(x) ... is check), or <lambda at line N> for one passed straight to a call.
error needs its argument. error() is an arity mistake and is refused the way abs() and len() are - rule 3 above - rather than throwing something empty. Throwing null on purpose is still available as error(null); the two are different, and conflating them meant a typo produced an error with nothing in it.
The payload survives whatever it is thrown through. A throw from inside a callback passed to a higher-order builtin - map, filter, pmap, reduce, sort_by - reaches the enclosing catch as the same value, including across the worker threads pmap runs its callback on:
try { map(ids, fn(id) find_user(id)) } catch (e) {
get(e, "kind") # "not_found" - not the flattened message
}
For your own recoverable failures, throw a { kind, message } map (rule 2 above) so callers dispatch on your kinds exactly like the stdlib's.
Secrets
db_pass = secret(os.env("DB_PASS"))
print(db_pass) # [secret]
print("pw: {db_pass}") # pw: [secret]
db = mysql.connect({ host: "db", port: 3306, user: "app", password: reveal(db_pass), database: "shop" })
secret(v) wraps a credential; the wrapper renders as [secret] through every stringifying sink - print, interpolation, std.log, ECKO_AI_TRACE, error messages, templates, and JSON encoding - so a wrapped value cannot leak into a log line. reveal(s) returns the inner value and is the only way out: grep reveal audits every exposure point. is_secret(v) tests for the wrapper.
Rules: "x" + s is a type error (use reveal); secrets compare equal only to other secrets with equal contents (s == "raw" is always false); error(secret(x)) renders redacted while catch still binds the wrapped value. Redaction is a leak guard for honest code paths, not encryption - the value lives in memory and reveal is unrestricted.
The OS keychain (std.keychain)
import std.keychain
keychain.set("acme-api", "default", token) # store; a string or a secret
key = keychain.get("acme-api", "default") # -> a secret, or null if absent
keychain.delete("acme-api", "default") # -> true if there was one
std.keychain reads and writes the operating system's credential store: the login Keychain on macOS, Credential Manager on Windows, and the Secret Service (GNOME Keyring or KWallet) on Linux. A credential is named by two non-empty strings, the service (your program, or the API the credential is for) and the account (a user name, or something like "default"). Values are text. get returns the value wrapped as a secret, so it reads as [secret] until reveal takes it out, and null when there is no such entry; set replaces any value already there; delete returns true if it removed an entry and false if there was none.
When the store cannot be reached or refuses, the call throws { kind: "os" }. The common case is a Linux server: it has no desktop session, so no Secret Service, and the message says to keep the secret in the environment there. A stored value that is not UTF-8 text is os too. A value never appears in an error message. The functions need the keychain capability - their own, not env: granting a package the environment is common, while the keychain holds credentials other programs stored, and a write there outlives the program.
Strings: Triple-Quoted Literals
"""...""" strings are multi-line and dedented:
text = """
Line one
indented relative line
Line two
"""
# => "Line one\n indented relative line\nLine two"
- A newline immediately after the opening
"""is dropped. - Text on the same line as the opening
"""keeps its leading whitespace:""" two"""is" two". It still counts toward the common indentation below. - A whitespace-only last line (the closing quotes' indentation) is dropped.
- The common indentation of the remaining non-blank lines is stripped; relative indentation is preserved.
{expr}interpolation and the usual escapes work; single"quotes need no escaping.
The escapes, in any string that is not raw: \n, \t, \r, \\, \", \', \0, \{/\} for a literal brace, and \u{HEX} - one Unicode scalar value by its code point, 1 to 6 hex digits ("caf\u{e9}" is café). A \u{...} that is not a character (past 10FFFF, a surrogate, empty) is a lex error. Any other backslash is kept as written. \u{...} used to be no escape at all: "\u{1}" was the three characters \u1.
An interpolation hole holds exactly one expression; "{a b}" is a parse error rather than the value of a. A hole holding only a number ("{3}", "^[A-Z]{3}$") is refused by ecko check (literal-interpolation, an error), because the result - 3, ^[A-Z]3$ - is never what was written; use a raw string or \{. Interpolation errors give the line and column of the hole's {.
A string is a string whatever it contains. "{x}" renders x the way string(x) would and yields text, exactly as "a{x}" does - the amount of literal text beside the hole makes no difference to the type.
An interpolation hole may contain string literals of its own: the lexer only opens a hole on a { that actually balances, and then reads the hole's own quotes and braces as part of it. So "val {get(m, "k")} end" and "a {"}"} b" both work. A { with no matching } is an error (Unclosed interpolation brace in string, at the {), and so is a balanced {...} that is not valid Ecko - write \{ for a literal brace, or use a raw string, which is why CSS wants one.
A { that starts its string and is followed at once by the closing quote, "{", is a literal brace, whatever comes later on the line. So "{", "}" is two strings and "{" + x + "}" is a concatenation. (Read the other way, the { balanced against the } of a later string and the code between became the text of a hole: one string, silently.) A literal hole followed by more text, "{"}"} b", and a hole after other text, "a{"x"}", are holes as before.
Raw strings
r"..." and r"""...""" disable interpolation and escape processing - for CSS, JSON, regexes, and anything else full of braces:
css = r"body { margin: 0 }" # braces are literal
block = r"""
.row { display: flex }
"""
# raw + dedent
For JSON, use the triple form. A single r"..." ends at the first quote, and JSON is full of them, so it can only hold the braces. r"""...""" holds both:
r"""{"jsonrpc": "2.0", "method": "tools/list"}"""
+ joins a string only to a string
"a" + "b" is "ab". A string beside anything else is an error, in either order:
"count: " + 5 # error: Can't add string and int
5 + " items" # error: Can't add int and string
"count: {n}" # interpolation formats any value
"count: " + string(5) # or convert explicitly
+ used to format the other side into the string, so "5" + 1 gave "51" where a program that received a number as text meant 6 - a quiet wrong answer. The conversion is now written where it happens. string + secret and string + bytes were already errors with their own messages. ecko fix --migrate --only=strplus wraps the non-string side in string(...) wherever the other side is visibly a string.
Bytes & Bitwise Operators
bytes is the home for binary data - what a UTF-8-validated string cannot hold. The text/bytes boundary is always explicit: encoding is total, decoding can fail and fails loudly instead of corrupting data with replacement characters.
The b"..." literal
ASCII plus escapes; \xNN for arbitrary bytes; \n \t \r \\ \" \0 as usual. No {expr} interpolation (bytes are bytes, not text). Non-ASCII characters and unknown escapes are lex errors.
magic = b"\x89PNG\r\n\x1a\n" # 8 bytes
empty = b"" # falsy, like "" and []
print/str.from render bytes canonically: \n \t \r \" \\ short forms, other printable ASCII verbatim, everything else \xNN lowercase (NUL is \x00, never \0, so a following digit can't blur into the escape).
Core operations
| Operation | Result |
|---|---|
len(b) | byte count |
b[i] | Int 0-255 (strict, negative-from-end) |
b[i..j] | bytes (clamped like other slices) |
b1 + b2 | concatenation (both sides must be bytes) |
for x in b | iterates Ints |
==, < | bytewise equality / lexicographic order |
contains(b, sub), index_of(b, sub) | binary-safe search |
b"\x01" in match | literal pattern |
bytes + string is a type error - decode with string(b) or encode with bytes(s) to pick a side explicitly (same stance as secrets).
Conversions: the explicit text <-> bytes boundary
bytes(s) # string -> bytes: UTF-8 encode (total)
bytes([137, 80, 78]) # list of Ints 0..=255 -> bytes (else error)
string(b) # bytes -> string: ERROR on invalid UTF-8
str.from_utf8(b) # same strict decode, as a module fn (catchable)
str.from_utf8_lossy(b) # explicit, opt-in replacement-char decode
list(b) # bytes -> list of Ints
JSON has no byte type: json_encode emits bytes as a base64 string (and json.decode leaves it a string - decode back explicitly). ai[bytes] typed output advertises a base64 string schema and decodes it; mock mode returns a deterministic blob through the same coercion path.
Bitwise operators (word operators)
| belongs to lambdas and pipelines, so bitwise ops are words, like and/or/not:
a band b a bor b a bxor b a shl 3 a shr 2 bnot a
- Int: two's-complement on 64 bits. Shifts error when the amount is outside
0..64(no silent wrap);shris arithmetic (sign-extending). - bytes:
band/bor/bxorare element-wise and require equal lengths;bnotcomplements each byte. Shifts don't apply to bytes. - Mixed
int/bytesoperands are a type error.
Precedence sits between comparison and range - looser than arithmetic (a + b shl 2 means (a + b) shl 2), with band tighter than bxor tighter than bor, mirroring Python's relative order. ecko fmt always prints clarifying parentheses when bitwise mixes with arithmetic:
|> < or < and < comparisons < bor < bxor < band < shl/shr < .. < + - < * / % < unary
key = b"\x5a\x5a\x5a\x5a"
masked = message bxor key # XOR mask...
original = masked bxor key # ...and back
Templates
template defines a function whose body is a template string - the home for prompts (and any generated text):
template summarize(text, tone = "neutral") = """
You are an editor. Summarize the following in a {tone} tone.
<input>
{text}
</input>
"""
result = ai summarize(article, tone: "formal")
Template bodies support control flow:
template report(title, items) = """
== {title} ==
{for item in items}
- {item.name}: {item.count}
{end}
{if items == []}
(nothing to report)
{end}
"""
{expr}interpolates;{for x in expr}...{end}repeats;{if cond}...{else}...{end}branches.- A directive alone on its line vanishes from the output (its indentation and newline are removed); inline directives affect only their own text.
{input expr}renders the value wrapped in<input>delimiters with any embedded</input>/<input>sequences neutralized - the injection-safe way to put untrusted data into anaiprompt.- The
{input …}and{for …}directives are template-body only. Writing them in a plain interpolated string is a parse error pointing you at templates. (A bare{input}is still an ordinary variable, and{if …}in a plain string is a genuine if-expression - only the directive forms are rejected.) - Templates are ordinary functions: first-class values, callable anywhere a string is expected, and the natural way to build reusable
aiprompts. - Use
\{for a literal{.
Prompt safety: @untrusted
@untrusted marks attacker-controlled data - an HTTP body, a file, a tool result. The static analyzer (ecko check) then warns (untrusted-in-prompt) when a marked value is rendered into an ai prompt through a plain {expr} hole instead of the injection-safe {input …} guard. It is analysis-only (no runtime effect) and never blocks a run.
The safe, checked pattern is a template whose parameter is marked @untrusted and rendered with {input}:
template reply(@untrusted note) = "Answer using: {input note}" # ok template reply(@untrusted note) = "Answer using: {note}" # warning: use {input note}
{input …} (a template-body directive) wraps the value in <input> delimiters so the model treats it as data, not instructions. Build prompts as templates like this and pass untrusted values through them.
@untrusted also works on a let binding or an ordinary function parameter; taint propagates through derived lets. A marked value warns wherever it reaches an ai prompt, as a conservative audit:
@untrusted let body = http.get(url).body ai "summary: {body}" # warning (a plain ai string cannot use {input})
Taint tracking is intraprocedural in v1: it does not follow a value across a function or template call, so mark the parameter at each boundary you want checked. A value marked at a call site still warns at the ai sink, because the callee is not inspected - the checked, warning-free path is to mark the template parameter and use {input} there.
Strings (std.str)
A handful of the most common string operations are global builtins (upper, lower, trim, split, join, replace, contains, starts_with, ends_with, chars, lines, reverse, index_of, len). std.str is the complete toolkit - import it when you need the fuller set. Every operation is character-indexed, so it is correct for multi-byte UTF-8.
import std.str
str.title("the quick fox") # "The Quick Fox"
str.pad_start("7", 4, "0") # "0007"
str.substring("hello world", -5) # "world" (negative counts from end)
str.replace_first("a-b-c", "-", "/") # "a/b-c" (vs replace, which is all)
str.count("banana", "na") # 2
str.from(1 + 2) + " apples" # "3 apples"
str.diff("a\nb", "a\nB") # [" a", "- b", "+ B"]
Full surface:
- Case:
upper,lower,capitalize(first letter up, rest down),title(each word),swapcase(flip every cased char), andeq_ignore_case(a, b)- case-insensitive equality (compares Unicode lowercased forms; full case folding like Germanß->ssis not performed). - Trim:
trim(s, chars?),trim_start(s, chars?),trim_end(s, chars?)- with nochars, strips whitespace; withchars, strips any character in that set (trim("xxhixx", "x")->"hi"- a set of code points, not a substring).trim_prefix(s, p)/trim_suffix(s, sfx)strip a fixed affix once. - Pad:
pad_start(s, width, fill?)/pad_end(...)-filldefaults to a space and, if multi-character, cycles then truncates to the gap;center(s, width, fill?)pads both sides (an odd leftover goes right);zfill(s, width)zero-pads after any leading sign (zfill("-5", 4)->"-005"- the one casepad_start(s, w, "0")gets wrong). - Extract:
substring(s, start, end?)andchar_at(s, i)- both accept negative indices (counting from the end);substringclamps,char_aterrors out of range. - Code points:
ord(c)-> the Unicode scalar value of the first character (ord("A")-> 65,ord("🦀")-> 129408);chr(n)-> the character for a code point. Scalar values, not bytes, so the pair round-trips for any character.ord("")errors;chrerrors on a negative value, on anything above U+10FFFF, and on the surrogate range. - Search:
contains,starts_with,ends_with,index_of/last_index_of(char offset, or-1),count(s, sub)(non-overlapping). - Replace:
replace(s, from, to)(all) andreplace_first(...). - Split/join:
split(s, sep, limit?)-limitcaps the number of splits (split("a,b,c", ",", 1)->["a", "b,c"]; absent or negative = unlimited);rsplit(s, sep, limit?)counts the limit from the right (rsplit("a,b,c", ",", 1)->["a,b", "c"]), parts always in order;partition(s, sep)/rpartition(s, sep)split once around the first/last separator into a guaranteed 3-list[head, sep, tail]- with no match,partitionkeeps the string in the head,rpartitionin the tail - solet (h, sep, t) = str.partition(line, "=")always destructures;split_whitespace,lines,join(list, sep),chars,reverse. - Test: character-class predicates - true iff the string is non-empty and every char is in the class.
is_digit(Unicode numeric),is_alpha(alphabetic),is_alnum,is_space(whitespace),is_ascii;is_upper/is_lowerneed at least one cased char and no cased char of the opposite case ("A1!"is upper,"123"is neither). The empty string isfalsefor every predicate - one uniform rule (Python's"".isascii()diverges; Ecko doesn't). For "empty or whitespace" checks usestr.is_blank. - Diff:
diff(old, new, context: n?)compares two texts line by line and returns the result as a list of strings, each marked" "(in both),"- "(only inold) or"+ "(only innew); equal inputs give[].oldandneware each a string, split on every\n(so a trailing newline is a last, empty line, and shows when only one side has it), or a list of strings taken as the lines. The diff is Myers', the onegit diffuses: as few lines marked as possible. Withcontext:, onlynunchanged lines are kept around each change, and each hunk starts with a unified-diff header,"@@ -4,3 +4,3 @@"(start line and line count on each side, the count left out when it is 1), sojoin(str.diff(a, b, context: 3), "\n")reads like a patch. The two sides may hold 40,000 lines together; past that it throws{ kind: "limit" }, because the time a diff takes grows with the square of the lines when the two have little in common. - Unicode:
normalize(s, form)puts text into one of the four forms of UAX #15 -"NFC","NFD","NFKC","NFKD", matched case-insensitively. Unicode lets one visible character be spelled more than one way ("é" is U+00E9, or "e" followed by the combining acute U+0301): the two render identically, compare unequal, and have differentlen. Which spelling arrives is not the program's choice - macOS filenames are decomposed, most of the web is composed - so normalize before comparing, keying a map, or hashing.NFC/NFDare canonical and round-trip;NFKC/NFKDalso fold presentation differences (the "fi" ligature becomes"fi", "②" becomes"2") and are lossy on purpose - for matching, not for storage. ASCII is unchanged by all four.category(ch)takes exactly one character and returns its general-category abbreviation ("Lu","Ll","Nd","Mn","Zs"), which pairs withNFDto fold accents without a table: decompose, drop every character whose category is"Mn", rejoin. - Info:
len,is_empty,is_blank(empty or all whitespace),repeat(s, n). - Convert:
from(x)turns any value into a string.
Note: the module binds
str, deliberately notstring. A module named after thestring()converter would shadow it for the whole scope, which is what this module used to do. Both work in the same file now:string(x)andstr.from(x)are the same conversion.
AI/LLM Primitives
answer = ai "What is the capital of France?"
count = ai[Int] "How many words: {text}" # typed structured output
best = ai[Sentiment] "classify this review" votes 5 # majority vote of 5 samples
# (Sentiment: a type you declare)
items = ai[json<List<Int>>] "List three primes"
result = data # pipelines feed the value
|> ai "Extract all dates" # in as prompt input
|> ai "Format as ISO 8601"
story = ai "Write a short story" -> stream # runs in the background
for chunk in story { print_no_newline(chunk) } # consume incrementally...
print(story) # ...or block for the whole
The clauses after the prompt go in one order: votes N, on <image>, using [tools], with <session>, via m, -> stream (via is also accepted after -> stream; fmt prints it last). A clause out of that order is a parse error naming the order, or, when the pairing itself is not allowed, the "can't be combined" error for that pairing.
Provider configuration (never code):
ECKO_AI_API_KEY- API key (no flag: a key on the command line is in shell history andps)ECKO_AI_PROVIDER-openai(default) /openrouter/ollama(--provider)ECKO_AI_MODEL- model override (--model)ECKO_AI_BASE_URL- endpoint override; https, or http to loopback only (the API key travels on it), unlessECKO_NET_ALLOW_HTTP=1ECKO_LIMIT_PARALLEL- concurrency cap for pmap and tool rounds (default: all cores)ECKO_AI_MAX_RETRIES- retries for typed/contractaicalls (default 3)ECKO_AI_MAX_CALLS- hard budget onaicalls (0/unset = unlimited). A script counts its whole run. Insidehttp.serveeach request counts on its own, including work it hands topmap, tasks and tool rounds, and each message anon_wshandler receives throughws.recvstarts a fresh count, so a long-running server never runs out. The error'sscopefield is"process","request"or"message"ECKO_AI_OLLAMA_FORMAT-0stops sending a typed call's JSON Schema to Ollama asformat, where Ollama enforces it on the model's output (untyped calls,ai[Json]and tool rounds never send it). Default: sent.ECKO_AI_MOCK-1forces mock mode whatever the environment or a call'svianames.ecko testsets it.ECKO_AI_CACHE- directory for the content-addressed prompt cache (--cacheuses.ecko-cache/). Identical calls (same provider + model + prompt, schema included) replay the cached response through the normal coercion path: no API call, no budget consumption, traced ascached: true. Content-addressing means entries never go stale by key - delete the directory to reset. Mock mode bypasses the cache.ECKO_AI_TRACE-1/stderrtraces everyaicall to stderr; a file path appends one JSON object per call (JSONL). Also:ecko --trace. The trace records each prompt and response verbatim: an unrevealedsecretrenders redacted as everywhere else, but areveal()ed value interpolated into a prompt lands in the trace file - treat trace output like any log.
Without a key, ai runs in mock mode and programs stay fully runnable offline: untyped calls echo [AI Mock] <prompt>; typed calls return deterministic, schema-valid values - ai[Int] → 42, ai[Bool] → true, enum types → their first variant, struct types → variants with a schema-valid mock value per declared field type, json<List<T>> → a one-element list. Typed pipelines, matches, and contracts are therefore testable without an API key. llm.is_mock() (import std.llm) reports which mode is in effect, for code - a tool, most often - that should skip a side effect offline.
A provider call that fails raises { kind: "ai", message }, whichever form made it: a plain or typed call, voting, a session turn, a tool loop, or a stream. A failed -> stream raises from for chunk in s, from the std.io read verbs and from resolving it (string(s)) - after any chunks that did arrive - rather than ending as though the model had said nothing.
A field may declare a default, which fills it when either construction form leaves it out:
type User { name: String, age: Int = 0 }
User("Sean") # age is 0
User { name: "Sean" } # age is 0
User("Ada", 36) # an explicit value still wins
Three rules:
- Defaulted fields come last. Otherwise
User("Sean")is ambiguous the moment a default sits between two required fields - the second argument could be filling the default or the field after it. Refused at the declaration, naming both fields, rather than at every construction site. - The default is evaluated at construction, not at declaration, so two instances never share one.
n: Int = next_id()callsnext_idonce per value built. - It is evaluated in the scope the type was declared in, which holds functions and builtins but not local variables.
age: Int = abs(-1)andn: Int = seven()work; a default naming aletormutbinding fails with an undefined-variable error when a value is constructed.
A field with no default is still required: omitting it leaves the field unset and fails its declared type, exactly as before.
Every type an ai[T] names must exist: a primitive (Int, Float, Decimal, String, Bool, bytes, json, Any) or a type the program has declared by the time the call runs. An unknown name is an error (kind: "bug", with the name in type) - ai[Sentimnet] used to come back null. No AI-specific types are built in: the demo Sentiment, Classification and Entity types were removed in 0.62, and naming one says which declaration to add.
A record type's declared field types are real to ai[T], not just its field names: type User { name: String, age: Int } sends age to the provider as a number in the JSON schema rather than a string, and mock mode matches it field for field - Int gives an integer, Float a number, Bool a boolean, String the usual [AI Mock] <field> string. A field typed List<T> or Map<K, V> recurses the same way, element by element, and so does a field whose type is itself a record. A field typed T? recurses the same way: the schema sends {"anyOf": [<schema for T>, {"type": "null"}]}, and mock mode produces a schema-valid T value rather than null (the present case is more useful to exercise offline than the absent one, and both satisfy the schema) - type U { age: Int? } mocks age as an integer, not a string. A field typed Result<T, E> does not: it still falls back to the same permissive schema used for json, in both the schema and mock paths, because Result is an Ok/Err ADT rather than a single value shape and is far less common as a field type, so adding that case is left for a later change.
This is also about what ai[T] coerces back, not only what it sends and mocks: a live provider's response is mapped into a record's fields through the same coercion a bare ai[Int] gets, so a provider that returns "34" for an age: Int field - despite the schema already saying integer - still lands 34. A field that cannot be coerced becomes Null first, and if the field's own declared type does not accept Null (an untyped field and T? are the two that do), that now becomes a retry reason naming the field, threaded back to the model the same way an @ensures failure is - up to ECKO_AI_MAX_RETRIES (default 3) further attempts. If every attempt still leaves the field uncoercible, the call returns anyway with that field null, rather than throwing - the same best-effort outcome a bare ai[Int] gets once its own retries run out. Mock mode never reaches any of this: the mock generator already produces the right native JSON type before this mapping runs, and coercing an already-correctly-typed value against its own type is a no-op.
Plain construction goes further than ai[T]: it does not retry, it rejects. User("Sean", "not-a-number") throws before the struct is ever built, and so does every other constructor path - the positional call, the brace form (User { name: "Sean", age: "not-a-number" }), a positional call inside a bridged closure (map(xs, fn(s) User(s, 0))), and the brace form on the AST tier, which is what an async fn or a fn with a string contract constructs on. Both engines agree on this; it is one check, called from both. The message names the field, the owning type, the expectation and what arrived:
field `age` of `User` expects Int, got string
Int is written the way the type appears in source; string is what type_of reports on the value that arrived - deliberately the same word, so the error and an investigation of it agree. The asymmetries worth knowing by heart: a Float field accepts an Int (widening is lossless, the same reason 1 + 2.0 is a float), but an Int field rejects a Float (narrowing loses data). A Decimal field is the same in the first direction and stricter in the second - it accepts an Int, which widens exactly as it does in decimal arithmetic, and rejects a Float, because admitting binary floating point into a field declared Decimal would defeat the reason the type exists. Result<T, E> fields are still unmatched here too, consistent with the schema gap above - whatever value is given passes. A field that is missing outright is checked the same way: User("Sean") against the two-field User above throws, naming age, rather than silently building age: null - unless the field's own declared type already accepts null (no annotation, or T?), in which case a missing field still defaults to null as before.
ecko check reports a mismatch statically wherever the offending value is a literal, in either construction form, before the program runs; a value only known at run time - json.decode output, a map lookup, an ai response - falls to the constructor's own runtime check as the backstop.
Assignment is checked too, by the same matcher. set_in_path is the one function both engines share for writing into a field, so a single check covers construction and assignment alike. Given the User above, mut u = User("Sean", 34); u.age = "not-a-number" now throws before the assignment takes effect, with the identical message:
field `age` of `User` expects Int, got string
A nested path is checked at the field it actually writes, not at the root. Given type Server { port: Int } and type Config { server: Server }, c.server.port = "nope" throws:
field `port` of `Server` expects Int, got string
The inner write checks port against Server's own declaration; the rebuilt Server is then checked, in turn, against Config's declaration of server - cheap, since that check only compares a struct by name. A variant satisfies the sum type it belongs to: with type Tier = Basic | Vip, a field declared Tier accepts Vip, Basic and any variant built by a constructor, a brace literal or ai[Tier], and refuses a variant of another type or any value that is not a variant (5, "vip", null). Every struct value records the type it is a variant of for this. json, _ and Any accept every value. The same asymmetry as construction holds: a Float field accepts an Int, an Int field rejects a Float. Result<T, E> fields still accept anything, consistent with construction.
A plain map has no declared field types and stays permissive: m.a = "anything" on mut m = { a: 1 } still works. That is the boundary that stops enforcement from reaching past records.
Index assignment is checked against the element type. r.xs[0] = "x" on a List<Int> field throws the same field 'xs' of 'R' expects List<Int>, got list as assigning a whole wrong list would. The field was valid before the write, so checking the one new element against Int is enough - O(1), not a re-validation of the list. The same holds for a key written into a Map<K, V> field. A path that reaches deeper than one element (r.xs[0].name = v) is checked against the whole field after the write, on a copy of that field, so a rejected write changes nothing.
The cost is the same shape as construction's: 500,000 assignments measured 127ms before this check and 141ms after, interleaved - about 11 percent, or 30 nanoseconds per write, the same construction pays.
map(list, fn(x) ai x) and pmap(list, f) execute on a bounded parallel worker pool: ECKO_LIMIT_PARALLEL workers, the core count by default. pmap(list, f, limit: n) runs n workers for that call instead (1 to 1024, anything else an error), which is what work that waits on the network wants: its right concurrency does not depend on the machine's cores.
ai[T] "prompt" votes n runs n independent samples (1-25) and returns the majority-coerced value - a quality dial for noisy classifications. Votes bypass the cache (identical cached responses would defeat voting) but count against ECKO_AI_MAX_CALLS. Cannot combine with -> stream.
Worst-case call arithmetic. The dials multiply: a typed call that fails coercion retries (up to ECKO_AI_MAX_RETRIES, default 3), each voting sample runs its own retry loop, and each tool round is a provider call (up to ECKO_AI_MAX_TOOL_ROUNDS, default 8). So ai[T] "..." votes 5 can spend up to 5 × 4 = 20 provider calls before returning. ECKO_AI_MAX_CALLS is the hard stop across all of it - every vote, retry, and tool round counts (mock calls too, so budgets are testable offline; cache replays don't).
Vision (image input)
ai "..." on <image> attaches image input to a vision model. The image is a std.image handle (or a list of them), so a resize/crop pipeline flows straight into the call:
import std.image
img = image.load("chart.png")
ai "what does this chart show?" on img # a vision call
ai[Kind] "classify this image" on img # typed vision output
ai "spot the differences" on [before, after] # multiple images
Live, the image serializes into the provider's message content (OpenAI image_url data-URLs; Ollama base64 image arrays), so the same code runs on either. In mock mode a vision call echoes the prompt plus each image's real dimensions - ai "describe" on img → [AI Mock] describe [image 4x2] - staying deterministic and offline; typed vision calls return their schema-valid mock as usual. on composes with [T]; combining it with using (tools), with (session), voting, or -> stream is a follow-up and is currently a clear parse error.
A vision call is an ordinary ai call that happens to carry images, and runs through the same machinery: ECKO_AI_MAX_CALLS counts it, a typed call whose answer fails coercion is retried with the failure fed back (images and all), the response is cached, and it emits a trace record carrying the provider's token counts. The cache keys on the image content as well as the prompt, so the same question about a different picture is a different call.
Tool calling
Functions annotated with @tool("description") can be offered to an ai call via a using [...] clause. The runtime drives the tool-call loop - the model requests a tool, the runtime invokes the Ecko function, feeds the result back, and repeats until a final answer, which is still coerced to ai[T] and checked by any @ensures contract.
@tool("look up the current weather for a city")
fn weather(city) = http.get("https://api.example/w?q={city}").body
@tool("search internal docs")
fn docs(query) = search_index(query) # your own retrieval
answer = ai[Report] "Compare weather in Cairo and Oslo" using [weather, docs]
using takes a list of function names, resolved in the lexical scope of the ai expression; local tools may capture their defining scope and shadow tools with the same name in an outer scope. Each function must carry a @tool description (used as the tool's schema description). A parameter's type annotation becomes its schema (limit: Int is advertised as an integer); an unannotated parameter is advertised as a string.
A computed tool set. When the list is not written out as bare identifiers, the expression is evaluated instead, and each element may be a tool spec map:
answer = ai "what changed?" using mcp.as_tools(session)
# each element of the evaluated list:
{ name: "search", description: "Search the docs", params: ["query", "path"], call: fn(query, path) ... }
name, description and call are required; params defaults to [], since a zero-argument tool is ordinary. call receives one positional value per entry in params, in order - not one map of arguments - so it declares as many parameters as params names. This is what lets a tool discovered at runtime
- from an MCP server, a plugin registry, a config file - be offered to a model at all: a value created while the program runs cannot carry a parse-time
@toolannotation, and has no identifier to be named after.
The two forms mix in one list. A bare identifier keeps taking its name from the source, which is what @tool functions rely on. Cannot combine with voting or -> stream. Offline (mock mode) the loop is deterministic: it invokes every tool named in the prompt and feeds the prompt as each argument a model would have to supply - a parameter with a default keeps it - so a tool is called with the same arity offline as live. That is enough to test the wiring without a provider. An untyped call then returns the last tool's result; a typed ai[T] call returns the same mock value for T that it would without tools. A tool that fails throws its error (catchable, kind preserved): live mode feeds error strings back to the model because the model can recover, but in mock the developer is the recovery mechanism, so failures surface. With a configured provider the model performs real tool selection over the wire.
An untyped call returns the last invoked tool's result, live and offline alike. Live used to return the model's prose instead, so the same source handed back a map offline and a string online - code reading a field off it passed its offline test and failed against a provider. When no tool runs at all, both fall back to the model's answer. To get the model's own answer with tools available, type the call: ai[T] "..." using [...] coerces the final answer to T on both paths.
With a live provider, the tools a model requests in one round run concurrently (at most ECKO_LIMIT_PARALLEL at once, default: all cores), and each is bounded by a per-round timeout (ECKO_AI_TOOL_TIMEOUT_MS, default 30000; 0 = unlimited). A tool that errors, times out, or names nothing known yields an error string fed back to the model, so a single slow or failing tool never stalls the loop. The whole loop is capped at ECKO_AI_MAX_TOOL_ROUNDS rounds (default 8). Concurrent tools follow Ecko's usual share-nothing model - coordinate through cell if they must share state.
The arguments a model supplies are checked against the schema the tool advertised, and bound to the function by name. A name the tool does not declare comes back to the model as an error rather than being dropped; a parameter the model left out takes the function's declared default, and one that is genuinely required is an arity error the model can act on. Only parameters without a default are advertised as required.
Each tool result is capped at ECKO_AI_TOOL_MAX_RESULT bytes (default 32768; 0 disables) and marked where it was cut. A result is not returned once - it stays in the message list for every remaining round - so one oversized answer would otherwise be paid for again on each request.
See examples/apps/agent.ecko for a full orchestration script combining RAG, @tool functions, typed ai, contracts, session, retry, and an HTTP handler.
Conversations (session)
A session() holds conversation history so multi-turn ai calls remember prior turns:
chat = session()
ai "My name is Ada." with chat
who = ai "What is my name?" with chat # the call sees the earlier turn
cell_get(chat) # the transcript: [{ role, content }, ...]
with s sends the session's prior turns as a native role-separated message array (not a flattened transcript) and records the new prompt and reply back into s. A session is a cell of { role, content } messages - read it with cell_get. Conversational turns bypass the prompt cache. Cannot combine with using, voting, or -> stream.
Choosing the model per call (via)
judge = model("openrouter", "anthropic/claude-sonnet-5")
local = model("ollama", "llama3.2", base_url: "http://gpu-box:11434")
verdict = ai[Verdict] "Judge this argument: {text}" via judge
draft = ai "Summarise the notes" using [read_notes] via local
story = ai "Write a scene" -> stream via judge
quick = ai "One-word answer: {q}" via "gpt-4o-mini" # a model on the configured provider
via m gives one call its own provider and model, so a program can put different questions to different models. It composes with every other clause (on, using, with, voting, -> stream), and ecko fmt prints it last. m is either a model(provider, name) value - provider is openai, openrouter or ollama, with optional base_url:, key: and reasoning: - or a string, which names a model on the configured provider. reasoning: is how hard a reasoning model thinks - none, minimal, low, medium, high, xhigh or max - sent as OpenRouter's reasoning.effort, OpenAI's reasoning_effort, or Ollama's think (off for none, else on); ECKO_AI_REASONING sets it for calls that do not. It is part of the cache key.
An AI request fails when nothing arrives for ECKO_AI_READ_TIMEOUT_MS (default 120000) - a limit on silence, not on the whole request, so a long reply that keeps streaming is never cut off. The error names the cause.
Settings a via leaves out come from the environment only when it names the environment's own provider. Switching provider takes that provider's defaults instead, and its key from key:, else OPENROUTER_API_KEY or OPENAI_API_KEY - never from ECKO_AI_API_KEY, which belongs to the environment's provider. So an OpenAI key is never sent to OpenRouter because a call said via OpenRouter; a call with no key for its provider runs in mock mode like any other.
The choice belongs to that one call. An ai inside a tool it runs uses its own via or the environment, a stream keeps the model it started with, and the cache and trace record the provider and model actually used. model() returns a plain map with the key held as a secret, so printing it never shows the key.
Token budgeting (tokens, cost)
n = tokens("some prompt text") # Int - GPT-4 (cl100k) tokenizer
usd = cost(n, 500, 0.15, 0.6) # Float - USD at the prices you pass
if tokens(prompt) < 100000 { ai prompt } # a budget guard before spending
tokens counts with the cl100k_base tokenizer (exact for OpenAI, close enough elsewhere for budgeting). cost(in_tokens, out_tokens, in_per_1m, out_per_1m) is the arithmetic over prices you supply, in USD per million tokens. Until 0.59 it also took a model name and priced it from a built-in table; vendors reprice, so the table went stale, and cost(model, in, out) now fails with the explicit form in its message. --trace and ecko profile report tokens, with no estimated dollar figure.
Retrying (retry)
reply = retry(3, fn() ai "flaky prompt") # up to 3 attempts, exponential backoff
retry(n, f) calls the zero-arg function f, re-running on error up to n attempts total with exponential backoff (base ECKO_RETRY_BASE_MS, default 50ms, doubling). Returns the first success, or propagates the final error once the attempts are spent. Works with any failing operation, not just ai.
Tracing
Every ai call - including streamed, piped, and parallel-mapped calls - emits a trace record when tracing is enabled: sequential call id, source line/col, provider, model, mock flag, prompt (with a stable content hash), response, wall-clock latency, retry count, token usage (when the provider reports it), and the failure reason if the call errored. Mock-mode calls are traced too, so CI runs are observable. Tracing never alters program behavior; sink errors are swallowed.
Structured Data
mut config = { server: { host: "localhost", port: 8080 }, features: ["auth", "cache"] }
print(config.server.port) # 8080
print(config.features[0]) # "auth"
config.server.port = 9090 # path assignment (root must be mutable)
Maps print and JSON-encode with sorted keys, so output is deterministic.
Keys may be written bare or quoted. A bare key must be an identifier (or a keyword - x.type is fine); a quoted key can be anything, which is what makes HTTP headers and hyphenated JSON shapes expressible inline:
http.response(303, "", { location: "/", "set-cookie": "a=b; HttpOnly" })
The two forms name the same key - { a: 1 } and { "a": 1 } are one map. A quoted key is taken verbatim: {expr} does not interpolate in key position, since a map literal's shape is fixed at parse time. ecko fmt canonicalises to the bare form wherever the key is a plain identifier.
Access is strict. xs[i] out of bounds raises index 9 is out of bounds (len 3) (negative indices count from the end and must also land in range); m.key / m["key"] on a missing key raises map has no key 'key'; a missing struct field raises struct has no field 'f'. The nullable lookup is get(collection, key), which returns null on a miss - reach for it when absence is expected. match patterns test rather than access, so a non-matching pattern is never an error.
Slicing. Strings, lists, and bytes slice with range syntax - by character for strings, so multi-byte UTF-8 is handled correctly:
s = "hello"
s[1..3] # "el" exclusive end
s[0..=2] # "hel" inclusive end (like ..= ranges)
s[..3] # "hel" open start
s[2..] # "llo" open end
s[-3..] # "llo" negative indices count from the end
s[1..-1] # "ell"
xs = [1, 2, 3, 4]
xs[1..3] # [2, 3] same rules for lists (and bytes)
Ranges are lazy and unbounded. a..b builds no list, so for i in 0..30000000 costs the same memory as any other loop, and the range-aware builtins (sum, count, len, first, min, max) stream one without materializing it. Turning a range into a real list is what allocates, so that is what is capped at 10,000,000 elements: list(0..30000000) raises and names the alternative, and so does any builtin that needs the list (chunk, join, sort, ...). Comparing ranges is lazy too - (0..20000000) == (0..20000000) answers without building either side. A range within the cap prints exactly like its list; one past it can never be that list, so it prints as its literal, 0..30000000.
Unlike single-index access, slices are total: out-of-range bounds clamp (s[2..99] is "llo", s[7..9] is "") and a reversed range is empty - slicing takes what's there, it never errors. ..= requires an end index (s[0..=] is a parse error; use s[0..] for an open end).
An index or slice bound is any expression, every operator included: xs[n shr 7], xs[i band 1], flags[a == b] and xs[get(m, "i") ?? 0] need no parentheses. A bound ends at the slice's own ../..= or at ], so xs[n shr 1..n] slices from n shr 1 to n; a range written inside a call or block in the brackets is still a range (xs[pick(0..2)]). Before 0.82 the bound stopped at the operators looser than +, so these needed parentheses, and ecko fmt removed them.
Membership: in
2 in [1, 2, 3] # true - an equal element
"ell" in "hello" # true - a substring (bytes in bytes too)
"port" in { port: 80 } # true - a key
3 in 0..5 # true - an Int within the range
not (9 in [1, 2]) # true - `not 9 in xs` means this too
item in coll answers exactly what contains(coll, item) answers - note the operand order is reversed - and an unsupported pair (1 in 5) throws a catchable error rather than returning false. It binds like a comparison: looser than arithmetic and ranges, tighter than and/or, so n + 1 in xs and ok is ((n + 1) in xs) and ok. ecko fmt writes not (x in xs) with the parentheses, as it does for every comparison under not. The in of for x in xs is unaffected.
Defaults for absent values (??) and merge
settings = { level: "debug" }
level = get(settings, "level") ?? "info" # "debug"
port = get(settings, "port") ?? 8080 # 8080
zero = get({ n: 0 }, "n") ?? 5 # 0 - only null is replaced
merged = merge({ a: 1, b: 2 }, { b: 3 }) # { a: 1, b: 3 }
a ?? b is a unless a is null, in which case it is b. Only null is replaced - 0, false and "" are values - which is what separates it from or, a boolean operator. b is evaluated only when needed. ?? binds tighter than comparison and looser than arithmetic, so get(m, "n") ?? 0 > 5 compares the defaulted value and x ?? 1 + 2 defaults to 3; it groups to the right, so a ?? b ?? c takes the first non-null.
merge(a, b) returns a new map with b's entries laid over a's: the right side wins a shared key, neither input changes, and nested maps are replaced rather than merged. a + b on two maps is an error that names merge, since which side should win is a choice + should not make silently.
type_name(x) gives the declared name of a record or variant ("User", "Circle"), where type_of gives the kind ("struct"); for any other value the two agree.
Modules
import std.io # binds `io`
import std.json # binds `json` (json.encode / json.decode)
import std.http # binds `http` (client + server)
import std.llm # binds `llm` (llm.chat)
import std.time # binds `time` (clock, format, parse, monotonic)
import std.re # binds `re` (regex)
import std.os # binds `os` (env, exec, args)
import std.fs # binds `fs` (filesystem)
import std.archive # binds `archive` (zip and tar)
import std.proc # binds `proc` (child processes)
import std.signal # binds `signal` (OS signal handlers)
import std.watch # binds `watch` (filesystem events)
import std.sql # binds `sql` (embedded SQLite)
import std.web # binds `web` (router over http.serve)
import std.random # binds `random` (seedable RNG)
import std.hash # binds `hash` (sha256, hmac)
import std.encoding # binds `encoding` (base64 / hex / url)
import std.fmt # binds `fmt` (format, fixed, inspect)
import std.log # binds `log` (leveled logging)
import std.config # binds `config` (layered config.load: defaults / file / env)
import std.csv # binds `csv` (parse / stringify / read / write / each)
import std.toml # binds `toml` (parse / stringify / read / write)
import std.yaml # binds `yaml` (parse / stringify / read / write)
import "./utils" # user module, binds `utils` by file stem
utils.helper(42)
Aliasing. Choose the local binding name with as, so a module never has to collide with your own definitions:
import std.time as t # binds `t` instead of `time`
import "./helpers.ecko" as h # binds `h` instead of `helpers`
fn time() = t.now() # your own `time` is free; the module is `t`
t.now()
import <path> as <name> cannot be combined with a { … } selection (that form has its own per-name as).
Selecting names. import <module> { a, b as c } binds the chosen names directly (optionally renamed) instead of the whole module - for std, file, and package modules alike:
import std.math { sqrt, pi as PI } # bind sqrt and PI directly
import "./util" { double, greet } # from a file module
import mypackage { helper } # from a vendored package
Selecting a name the module does not export is an error.
Modules run in their own scope on top of the builtins and are private by default: a top-level definition is visible to importers only if it carries the export modifier. Circular imports are detected and reported.
export fn helper(x) = x * 2 # public
export type Color = Red | Green # public (with its variants)
export MAX = 100 # public binding
fn internal() = helper(1) # private to this file
Re-export another module's surface without binding it locally - a barrel entrypoint composes its sibling files this way:
export * from "./responses.ecko" # re-export the whole surface
export { validate } from "./forms.ecko" # re-export selected names
export { render as html } from "./views.ecko" # re-export with a rename
export import "./util.ecko" # bind `util` locally AND re-export it
A re-exported name that collides with another re-export or a local export is a hard error. A definition may share a builtin's name (e.g. a package's get); reach the shadowed builtin as core.get.
Packages
A bare import name (not std.*, not a "./path") resolves to a vendored package. name is a local alias the importer's ecko.json maps to a package's source path in its dependencies; the package is vendored under ./vendor/<host/owner/repo>/:
# ecko.json: "dependencies": { "greet": "github.com/ecko-lang/greet@v1.0.0" }
import greet # → ./vendor/github.com/ecko-lang/greet/
greet.greeting("Ada")
The importer's ecko.json is found by walking up from the importing file to the nearest ancestor holding one, and vendor/ is read from that same directory. So every file in a project can use the aliases the project declares, not only the ones sitting beside the manifest. The nearest manifest wins: a nested project with its own ecko.json is its own root and does not inherit an outer project's dependencies.
A package is a directory with an ecko.json manifest declaring its canonical module path (e.g. github.com/ecko-lang/greet), plus version, entrypoint, and optional capabilities/dependencies. A vendored package's module must match the path it was fetched from (a mismatch is a hard error), entrypoints must be relative paths inside the package, and - when the project has an ecko.sum - its file tree is verified against that pin on load. Each package resolves its own bare imports against its own vendor/, so dependency namespaces don't collide. See package commands for the full ecko get workflow.
Package commands: ecko get <host/owner/repo>[@version] discovers a package's versions from its git tags over plain HTTPS (no git binary needed), downloads the selected version (@0.38.0 and @v0.38.0 both find a tag spelled either way, the exact spelling first), vendors it at vendor/<host/owner/repo>/, and pins a content hash of its file tree in ecko.lock (a direct archive URL or local path also works, as an escape hatch). The dependencies key it writes - the name import binds - is the last path segment with - mapped to _, so mysql-client is imported as mysql_client; --as <alias> chooses it explicitly, and a name that cannot be an identifier at all (a leading digit, a keyword) is refused rather than written. ecko install rebuilds vendor/ from the lockfile (re-verifying each hash, and refusing when there is no ecko.sum to check against unless --allow-unverified is given; a vendored tree that fails its pin is an error and is left in place, and --repair replaces it with a re-fetched, verified copy); ecko remove <name> drops a package, and is an error when <name> is not a dependency in ecko.json; ecko pack [-o <file>] builds a deterministic, self-contained distributable zip, and refuses a directory with no ecko.json. A fetch the forge answers with 401, 403 or 404 is reported as "not found, or private". vendor/ + ecko.lock are committed, so clones run offline.
Capabilities are enforced. A package's code may perform a gated operation only if the grant its importer wrote covers it; your own top-level code is ungated and keeps full authority. The seven names are net, fs:read, fs:write, env, exec, device and keychain. A package's own capabilities field is advisory (it documents what the package asks for); what is enforced is the grant list on the importer's dependency entry:
{
"dependencies": {
"logger": { "path": "github.com/acme/logger", "version": "v1.2.0",
"grant": ["fs:write:./logs"] }
}
}
fs:read, fs:write and device may carry a path scope - everything after the second colon - confining them to one subtree or one port (device:/dev/ttyUSB0). fs:write on its own still means anywhere. The other four names take no scope, and net:example.com is an error rather than a grant that quietly does nothing.
device is separate from the fs pair even though a serial port is a file on Unix, for two reasons. Granting a package fs:write is common and reasonable, and it must not quietly also mean "may drive any attached hardware". And a Windows port is COM3, which is not a path and could never be scoped under an fs name. No standard-library module needs it since std.serial was removed in 0.61; a grant naming it is still accepted.
env grants reading the environment and setting your own variables, not choosing what exec runs. os.set_env refuses PATH, PATHEXT and the LD_* / DYLD_* loader hooks from a package that does not also hold exec, since those decide which binary a bare command name resolves to. Any ECKO_* name is refused to a package outright, whatever the grant: those reconfigure the interpreter, and ECKO_AI_BASE_URL would redirect every model call and its credential. Root code is unaffected in both cases.
- A relative scope resolves against the directory holding the
ecko.jsonthat wrote it, sofs:write:./logsmeans the same thing wherever the program is launched from. - Requested paths are made absolute and symlink-resolved before the check, so neither
../nor a symlink inside an allowed directory escapes the scope. A glob is checked against its literal prefix:fs.glob("/etc/**/*.conf")needs read on/etc. - Scopes are compared by path component, so a grant on
/datadoes not cover/data-backup. - A grant is clamped to what the granter holds, so a package that itself has dependencies writes the plain
"grant": ["fs:read"]and passes on whatever the root program allowed. Authority only ever narrows going down the tree; granting a subtree or a name you do not hold is a hard error at import.
The set follows the call, not the thread. A package function re-enters its own set wherever it is called from, and a worker thread started on a package's behalf, by pmap, bg.spawn, an async fn call or a live ai tool round, begins in the context of the code that started it. So a bare native handed across that boundary, pmap(cmds, proc.run) say, is denied exactly as a direct call would be. A root callback handed into a package runs with root authority: that is explicit capability passing, and it is the one way a package gets to do something it was not granted.
A denial raises { kind: "capability", capability, package }, plus path when a scope refused a specific path. See capabilities.
ecko build <file> [-o <app>] compiles a program to a single self-contained executable - a copy of the interpreter with the program (the whole project + vendor/ when an ecko.json is present; otherwise the entry file plus every file it reaches through relative imports, export * from re-exports included) appended, so the output runs on its own with nothing else installed. Run it directly (./app); any arguments become the program's os.args(), and CLI subcommands are disabled inside it. This is packaging, not compilation: startup and speed are unchanged, py() still needs a host Python, and the binary only runs on the platform it was built on (cross-compilation is separate). Without an ecko.json, a relative import that does not resolve stops the build with an error naming the file and the import; a file imported by a computed path at run time is not in the bundle, and the run-time error says so and points at ecko init. Files other than code go in when the manifest lists them: "embed": [patterns] (fs.glob syntax, relative to the project root, no .. or absolute path; a pattern matching no file, dotfiles aside, fails ecko build and ecko pack, which carry the same files; symlinks are followed, and an executable an earlier build made is never matched). In the built program the std functions that read a file by path - std.fs's reads, fs.open in read mode, web.static, csv.read/csv.each, image.load, archive.zip_list/tar_list/*_extract
- serve a listed file from the binary when the path, relative or absolute under the working directory, names it, and never consult the disk for it; every other path reads the disk.
fs.list_dir,fs.walkandfs.globmerge the embedded entries with the disk's. Writing to an embedded file (write,append,openin"w"/"a"/"x",remove,rename,copyonto,chmod,chown,set_modified,symlink,create_new; alsojson.write,csv.write,image.save,archive.*_createand*_extractonto one, and alog.to_file/log.configurefile sink) raises kindfs:'<path>' is embedded in this build and read-only.fs.modifiedof an embedded file is the binary's own modification time. Not covered:sql.open,http.serve's certificate and key files, archive creation's input files, and a package's own files (ecko getwarns when a package declaresembed). Full walkthrough: package concepts and package commands.
A module's members are reachable by module.name and by module["name"] - the same lookup, and an absent name is an error either way. The index form is what reaches a member whose name is decided at runtime, which matters for modules whose surface comes from data, like std.defaults.
Streams
A stream is a value you read from or write to a piece at a time. A file opened with fs.open, a socket from net.connect, a child's pipe from proc.stdout, an HTTP body fetched with stream: true, standard input, and the result of ai "..." -> stream are all the same type, and one set of verbs in std.io works on all of them:
import std.fs
import std.io
s = fs.open("data.bin") # a stream; type_of(s) == "stream"
piece = io.read(s, 4096) # at most 4096 bytes from one read -> bytes; null at the end
text = io.read_text(s, 4096) # the same, decoded; never splits a character
line = io.read_line(s) # one line, terminator stripped; null at the end
head = io.read_exact(s, 8) # exactly 8 bytes, or an error
frame = io.read_until(s, "\n") # through the delimiter, delimiter included
io.write(s, "text") # a string writes its UTF-8; bytes write exactly
io.timeout(s, 5000) # milliseconds per read or write; 0 or null clears
at = io.tell(s) # byte offset of the next byte the program reads (file streams)
io.seek(s, at) # move there, dropping anything read ahead (file streams)
part = io.limit(s, 4096) # the next 4096 bytes of s as a stream, then the end
io.close(s) # idempotent; a dropped stream closes too
for line in io.lines(s) { ... } # a line stream: strings, terminators gone
for piece in s { ... } # the stream's own unit: bytes, or text chunks
- A read that reaches the end with nothing pending returns
null, and never errors for it. An empty line is""; the end of the stream isnull. A read that reaches the end mid-answer is the other case, and it raises:read_exactshort of its count,read_untilwith bytes read and no delimiter, andread_textorread_lineon a character the stream cut in half.read_exactandread_untilput back what they consumed, so a retry sees it; a truncated character is not recoverable and the read says so. - Each piece is bounded, the whole is not.
io.readandio.read_textwithout a count return one chunk (64 KiB). A count overECKO_LIMIT_ALLOCis refused, and so is aread_untilor a line whose delimiter never arrives within it; the tail stays readable withio.read. That is the whole memory contract: a stream lets a program handle something larger than memory without ever holding more than a piece of it. io.read(s, n)is one read, and can be short. It returns at mostnbytes and may return fewer before the end, on any stream: a file read takes at most 1 MiB at a time, and a socket or pipe returns what has arrived.io.read_exactis the verb for a count that matters.io.limit(s, n)is a stream over the nextnbytes ofs, ending there or whensdoes.sis left exactlynbytes further on (fewer at its end), so consecutive limits cut a file into parts, and a limit is a request body, ahash.sha256input, or anything else that takes a stream. Over a file it knows its length, so an upload sendscontent-length. Closing it does not closes.nmust be a non-negative Int; it is not an allocation, soECKO_LIMIT_ALLOCdoes not cap it. A line stream is refused.- A stream has a unit. Sockets, files, pipes and HTTP bodies are bytes;
ai -> streamandio.linesare text.forbinds the unit; the byte verbs work on any bytes stream and on anaistream (its bytes are the UTF-8 of its text), and refuse a line stream, which has already had its terminators removed. io.lines(s)derives a line stream, andio.lines()with no argument reads standard input. It is theforform ofio.read_line.- Timeouts are errors, not
null. A socket starts with the deadlineECKO_NET_TIMEOUT_MSgives it (default 30000); a pipe and an HTTP body start with none;io.timeout(s, ms)sets one and returns the stream. A read that waits past it raises an error of kind"io", so a loop that reads untilnullcannot mistake a slow peer for the end. The deadline bounds each read the stream makes rather than the verb that called it, so aread_lineagainst a peer that keeps sending finishes the line. A file and the console accept a deadline and never enforce one: a file read does not wait, and standard input is not wired to a clock, soio.timeout(io.stdin(), 300)is accepted and has no effect. - Closing is not optional but it is forgiving.
io.closeflushes and releases; calling it twice is fine, and a stream that goes out of scope is closed by the runtime. A derived stream is the exception in one direction:io.close(io.lines(s))closesstoo, because that is an instruction, while letting a line stream go out of scope leavessopen, because that is only scope ending. So reading the headers withio.linesand then the body withio.readworks on the same stream. What closing means depends on the source: on a child's stdin it sends end of input, on a socket it shuts the connection, on an output pipe it releases nothing, becauseproc.waitstill collects what the stream did not consume. Closing a console stream cannot be undone: there is one per process, soio.close(io.stdin())costs the program standard input for the rest of its life, and closing a line stream derived from one does the same.printkeeps working, because the descriptor is untouched. - An
ai -> streamused as a value still resolves to its text. That is the one stream that has a value other than itself; every other stream prints as<stream>and must be read. - Errors carry
kind: "io", with the verb and the stream's source in the message (io.read_exact: stream ended after 3 of 8 bytes). The verbs themselves need no capability: holding the stream is the grant, and the constructor is what was gated (fs.openonfs:readorfs:write,net.connectonnet,proc.stdoutonexec).
The constructors, and what each one reads or writes:
| constructor | unit | read | write | needs |
|---|---|---|---|---|
fs.open(path, mode?) | bytes | "r" (default) | "w" truncates, "a" appends | fs:read or fs:write |
net.connect(host, port), net.connect_tls(host, port, opts?) | bytes | yes | yes | net |
proc.stdout(h), proc.stderr(h) | bytes | yes | no | exec |
proc.stdin(h) | bytes | no | yes | exec |
http.get(url, stream: true).body | bytes | yes | no | net |
io.stdin(), io.lines() | bytes, lines | yes | no | none |
io.stdout(), io.stderr() | bytes | no | yes | none |
ai "..." -> stream | text | yes | no | net |
hash.sha256(fs.open(path)) digests a stream a chunk at a time; see std.hash.
Standard input and output (std.io)
std.io is the console and the stream verbs in one module: the same io.read_line reads standard input, a file, a socket and a child's stdout.
io.print(value) behaves exactly like the global print. It exists for the case where a module of your own shadows print, or where an explicit io. prefix reads better.
io.read_line() and io.read_all() read standard input, which is what makes an Ecko program usable as a pipeline stage:
import std.io
io.print("hello") # same as print("hello")
line = io.read_line() # the next line, without its terminator
text = io.read_all() # everything, as one string
for line in io.lines() { # the same loop, without the null check
print(line)
}
End of input is null, not "". An empty line is a real line and reads as "", so a loop terminates on the null:
loop {
line = io.read_line()
if is_null(line) { break }
print(line)
}
cat data.txt | ecko filter.ecko
A trailing \r is stripped along with the \n, so a CRLF file compares equal to what you expect. A final line with no terminator is still returned.
io.lines() is that loop as a stream, and io.lines(s) does the same for any stream. io.stdin(), io.stdout() and io.stderr() hand the console over as streams, for code that takes a stream and should not have to care that this one is the console. io.stdin() returns the same stream every call and shares its buffer with io.read_line, so mixing the two loses nothing.
Reading standard input needs no capability. A pipeline stage is handed its input by the parent exactly the way it is handed its arguments, which is why os.args() is ungated too - there is no authority here to withhold. The stream verbs are ungated for the same reason: the constructor is what was gated, and holding the stream is the grant. Reading a file is std.fs and does need fs:read.
The rest of the module is the stream verb set - io.read, io.read_text, io.read_exact, io.read_until, io.write, io.timeout, io.close - described under Streams. Files are std.fs; formatting is std.fmt; leveled output is std.log; raw keypresses for a TUI are std.term, whose raw-mode reads take from the same descriptor as io.read_line, so a program should drive standard input through one of them or the other, not both.
Time (std.time)
Timestamps are unix milliseconds (Int). now/now_iso are calendar (UTC) time; monotonic is a steady clock for measuring durations, also in milliseconds, and monotonic_ns reads the same clock in nanoseconds for anything shorter. (Before 0.58 monotonic returned Float seconds.)
import std.time
time.now() # 1751725402931 (unix millis)
time.now_iso() # "2026-07-05T14:03:22.931Z"
time.format(0, "%Y-%m-%d") # "1970-01-01" (strftime, UTC)
time.format_local(time.now(), "%H:%M") # the machine's own time zone
time.parse("2026-07-05T12:00:00Z") # 1783252800000 (RFC 3339)
time.parse_format("2024-01-15 13:30", "%Y-%m-%d %H:%M") # 1705325400000 (UTC)
time.monotonic() # Int milliseconds since first call
time.monotonic_ns() # Int nanoseconds on the same clock
parse_format is the inverse of format: it reads a date with a strftime pattern as UTC millis, falling back to midnight UTC when the pattern has no time and to the top of the hour when it has an hour but no minute (%H alone). A pattern with %z or %:z applies the offset it reads, written +HHMM, +HH:MM or Z: time.parse_format("2026-01-01 17:00 +0200", "%Y-%m-%d %H:%M %z") is 15:00Z. Text that does not match the pattern throws parse; a pattern with an unknown specifier (%Q, a trailing %) is the program's mistake and throws bug, as it does in format. format_local is format in the machine's time zone (TZ where set), for timestamps a person reads, such as a log file named for when a run started.
Calendar work is not here, by design. Pulling a year, month or weekday out of a timestamp, adding months, asking whether a year is a leap year - all of it is arithmetic over the millis above, needing nothing from the OS. That puts it in a package rather than a native module, and the datetime package has it: components, year/month/day/hour/minute/second, weekday_name, from_components, add_months, is_leap, days_in_month. What stays here is the part that does need the OS: reading the clock, formatting and parsing.
Config (std.config)
Layered configuration in one call. config.load(spec, file?) resolves each key with the precedence env > config file > default and returns a validated map.
import std.config
cfg = config.load({
port: { default: 8080, env: "PORT" }, # env PORT overrides, coerced to Int
host: { default: "localhost", env: "HOST" },
key: { env: "API_KEY", required: true, secret: true },
}, "app.toml") # optional middle layer
cfg.port # 3000 if PORT=3000, else app.toml's port, else 8080
cfg.key # [secret] (wrapped; reveal() to use it)
Each key's descriptor is { default?, env?, required?, secret? }. Env values (always strings) are coerced to match the type of default - an Int default parses the env value as an integer, a Bool default reads true/1/yes/on. A required key with no value from any layer raises an error; secret: true wraps the value so it renders [secret], and keeps it out of the coercion error too - a secret that fails its type is reported by key name alone (config: API_KEY is not an integer), while an ordinary key still shows the offending value so a typo stays findable. The optional config file is parsed by extension (.toml / .yaml / .json) and supplies the layer between defaults and env.
Project defaults (std.defaults)
The ecko.json sitting next to the file being run is loaded automatically, before the program starts. No call, no import step - the values are simply there.
{
"app": "billing",
"version": "1.0",
"api_url": "https://api.example.com",
"environment": { "ECKO_AI_PROVIDER": "ollama" }
}
import std.defaults
defaults.app # "billing"
defaults.version # "1.0"
defaults[name] # same lookup, for a key decided at runtime
Two things happen. The optional environment object is applied to the process environment, and every other top-level key becomes a member of std.defaults, keeping its JSON type (string, number, bool, list, map).
Every key must be a valid identifier - letters, digits and underscores, not starting with a digit. JSON would happily hold "api-url" or "two words", but neither can be read back (defaults.api-url is a subtraction), so the file is refused when it loads rather than supplying values nothing can name. The same rule covers environment, where a name a shell cannot export is no use either. Keywords are fine (defaults.type parses).
environment values must be a string, number or boolean - there is no sensible environment-variable spelling for an object or a list, so those are an error rather than a silent JSON encoding.
The shell wins over environment (since 0.58): an entry is applied only to a variable that is not already set, the same env-over-file precedence as std.config. An ECKO_* value from the block is validated like one from the shell - an invalid one stops the run naming ecko.json. A setting that changes where data goes or what is trusted - ECKO_AI_BASE_URL, ECKO_AI_API_KEY, ECKO_AI_TRACE, ECKO_AI_CACHE, ECKO_PKG_TOKEN, ECKO_PKG_TOKEN_HOSTS, ECKO_PKG_GIT_BASE, ECKO_NET_ALLOW_HTTP, ECKO_TEMPLATES_REPO, ECKO_PY_ENV - may not be set from the block at all; the run stops and says to set it in the shell. Because it is applied before evaluation, it also configures Ecko itself - ECKO_AI_PROVIDER, ECKO_LIMIT_DEPTH and the rest of the env settings all take effect.
This is the same file as the package manifest. A manifest is just a defaults file with no environment block, so defaults.version and defaults.entrypoint read back from it. The two readers are independent: the manifest reader stays strict about the fields a package needs, while this one accepts any JSON object, so a project that only wants defaults never has to satisfy the manifest schema.
Being project configuration rather than a secret store, std.defaults is ungated - it holds what the author committed. Secrets belong in the environment, which stays behind the env capability.
ecko check cannot know what a given ecko.json holds, so members of std.defaults are never reported as unknown.
Regex (std.re)
Pattern-first; patterns are always written as raw strings (r"\d+"). In a plain string {2} is an interpolation hole, so re.test("a{2}", "aa") silently tests a2 and returns false. ecko check flags this (regex-interpolation). A pattern is compiled on first use and cached by its text (bounded: 512 patterns, each at most 4 KiB), so a pattern in a loop compiles once.
import std.re
re.test(r"^\d+$", "123") # true (matches anywhere, returns Bool)
re.find(r"\d+", "a1b") # "1" (or null)
re.find_all(r"\w+", "a b c") # ["a", "b", "c"]
re.captures(r"(\w+)@(\w+)", "b@c") # ["b@c", "b", "c"] (group 0 = whole match)
re.captures_all(r"(\w)(\d)", "a1 b2") # [["a1","a","1"], ["b2","b","2"]] (per match)
re.replace(r"\s+", "a b", "_") # "a_b" (replaces all)
re.replace_first("a", "banana", "X") # "bXnana" (first occurrence only)
re.split(r",\s*", "a, b, c") # ["a", "b", "c"]
OS & Filesystem (std.os, std.fs)
os.args() is the program's own argument list - ecko tool.ecko a b gives ["a", "b"] (empty in the REPL). os.script() is the running file's path, or null when there isn't one.
os.mem() is this process's resident set size in bytes, read from the OS on each call (/proc/self/statm on Linux, task_info on macOS, the working set on Windows). It is the memory held now, not the peak. It returns null where the platform gives no answer and never raises. The value differs on every run, so it belongs in logs and limits, not in output a test compares.
import std.os
os.env("PORT") # String, or null if unset
os.env_or("PORT", "8080")
os.set_env("K", "v")
os.unset_env("K") # the inverse; absent already is fine
os.args() # [String]
os.exec("git", ["status"]) # { code, stdout, stderr }
os.cwd() # current working directory (String)
os.platform() # "linux" | "macos" | "windows" | ...
os.family() # "unix" | "windows" (what to branch on)
os.arch() # "x86_64" | "aarch64" | ...
os.pid() # this process's id (Int)
os.cpu_count() # usable parallelism (Int), read once per process
os.hostname() # the machine name (String)
os.mem() # resident memory in bytes (Int), or null
os.exit(1)
import std.fs
fs.exists(p) / fs.is_dir(p) / fs.is_file(p) # Bool; all three follow a symlink
fs.exists(p, follow: false) # the link itself (lstat): a dangling link is there
fs.list_dir(".") # [String] (entry names; always openable again, see below)
fs.walk(dir) # [{path, is_dir, kind, size, mtime}], recursive, sorted, links not followed
fs.walk(dir, on_error: fn(e) ...) # an unreadable directory goes to the fn; the walk carries on
fs.match(path, pattern) # glob-match one path; arguments swapped is an error
fs.mkdir("out/logs") # recursive
fs.read(p) / fs.write(p, text) / fs.remove(p) # remove is recursive for dirs
fs.read_bytes(p) / fs.write(p, b"...") # binary: read/write exact bytes
fs.open(p) / fs.open(p, "w") / fs.open(p, "a") # a stream: read/write in pieces
fs.open(p, "x") # a new file; kind "fs" if anything is at p
fs.create_new(p, data) # true if this call created p, false if taken (O_EXCL)
fs.size(p) # bytes, by stat - never reads the file
fs.modified(p) # unix millis, same clock as time.now()
fs.is_symlink(p) # lstat: is_file/is_dir follow the link
fs.canonical(p) # realpath: absolute, links resolved
fs.symlink(target, link) # create one
fs.readlink(p) # the link's literal target (may dangle); kind "fs"
fs.owner(p) / fs.owner(p, follow: false) # { uid, gid }; unix only, kind "fs" elsewhere
fs.chown(p, uid, gid) / fs.chown(p, uid, gid, follow: false) # set the owner (lchown with follow: false)
fs.set_modified(p, ms) # set the mtime, unix millis; needs fs:write
fs.mode(p) # permission bits, as "755"
fs.chmod(p, "755") # set them - what makes a file runnable
fs.append(p, text) # append (creates the file if absent)
fs.copy(src, dst) / fs.rename(src, dst) # move/copy a file; kind "fs", with path and to
fs.join("a", "b", "c.txt") # "a/b/c.txt"
fs.basename("a/b/c.txt") # "c.txt"
fs.dirname("a/b/c.txt") # "a/b"
fs.extension("a/b/c.txt") # "txt" ("" if none) - pure string ops
fs.open(path, mode?) returns a stream rather than a value: "r" (the default) reads, "w" truncates or creates, "a" appends. It is what to reach for when a file is larger than the memory you want to spend on it. A mode is a string, not a number. fs.chmod(p, "755"), and fs.mode returns the same spelling so the two round-trip. Ecko has no octal literal, so the readable form is not available as a number - and the number someone would reach for is a trap: 755 in decimal is 0o1363, which is setuid and rwx for nobody. A numeric mode is refused, with the fix in the message. Unix only; on Windows an executable is decided by its extension, so there is nothing to set and the call says so. chmod needs fs:write (it is what makes a file executable); mode needs fs:read.
fs.walk(dir) returns every entry below dir, sorted, as {path, is_dir, kind, size, mtime}, all taken from one lstat: kind is "file", "dir", "symlink" or "other" (FIFO, socket, device); is_dir is true only for a real directory; size is the byte length for a file or link and 0 otherwise; mtime is unix millis, the unit fs.modified uses (null where the platform has none). Symlinks are never followed, so a link to a directory is a "symlink" entry and is not descended into. A directory that cannot be listed - the root or any below it - throws kind: "fs" with path, rather than being skipped. With on_error: fn(e), that map goes to the function instead, the directory's contents are left out, and the walk carries on; what the function throws is thrown from the walk. fs.glob still follows links and skips what it cannot read.
File names are bytes on Unix, not always UTF-8. A name that is valid UTF-8 is returned as is. For any other, fs.list_dir and fs.walk spell each invalid byte as one private-use character U+F780..U+F7FF (U+F700 plus the byte), and every fs function turns those characters back into the bytes before it touches the disk, so a listed or walked name can always be opened again. A valid name that itself contains a character in that range is escaped the same way, so it round-trips too. A string a program writes by hand containing one of those 128 characters is read as the bytes they stand for. On Windows names stay lossy.
fs.match(path, pattern) tests one path against a glob (*, ?, [...]). It is pure and needs no capability. The path comes first: if only the first argument has wildcards, the call is almost certainly swapped and throws instead of answering false.
fs.readlink(p) returns a link's literal target, whether or not it exists (fs.canonical resolves the chain and needs the end to be there). It needs fs:read. fs.set_modified(p, ms) sets the modification time to ms unix milliseconds, the inverse of fs.modified, and needs fs:write. Both throw kind: "fs" with path on failure.
fs.read and fs.read_bytes refuse a file over ECKO_LIMIT_ALLOC (default 256 MiB) and the error names fs.open as the way through. Every module that loads a whole file to parse it - csv.read, json.read, config.load, the ecko.json loader - shares that reader and that ceiling, and refuses with kind: "limit" (fields limit, env, path). csv.each reads a CSV file or stream one row at a time instead, in constant memory; a row with the wrong number of fields or bytes that are not UTF-8 becomes { kind: "parse", format: "csv", line, raw, message }, handed to on_error or, without one, thrown at that row. A path needs fs:read for it; a stream does not. "r" needs fs:read and the other two fs:write, checked against the same path scopes as the rest of the module.
os.set_env mutates process-global state. Setting it from concurrent code (pmap, http.serve workers) races with every other thread reading the environment - set it once during startup, before any concurrency, or not at all. os.exec shells out; treat its command and arguments as trusted.
Images (std.image)
import std.image for decoding, resizing, cropping, and encoding PNG/JPEG, and for image input to a vision model (ai "..." on img). An image is a value - a map { format, width, height, bytes }, where bytes is the image encoded as format ("png" or "jpeg"). Encoding returns bytes, so it pairs with the bytes type and std.encoding for a base64 round trip.
import std.image
pic = image.decode(png_bytes) # bytes -> image (PNG or JPEG)
img = image.load("photo.png") # read + decode a file (needs fs:read)
image.width(img) / image.height(img) # Int - also img.width / img.height
image.dimensions(img) # [width, height]
thumb = image.resize(img, 128, 128) # exact new size -> a NEW image
region = image.crop(img, x, y, w, h) # sub-region -> a NEW image
bytes = image.encode(img, "png") # image -> bytes ("png" | "jpeg")
image.save(img, "out.png") # encode (format from extension) + write (fs:write)
ai "describe this" on thumb # a vision call; a list of images works too
- Transforms return a new image; the source is unchanged.
decodeandloadkeep the bytes they were given; a transform stores its result as PNG, which is lossless, soresizethencropon a JPEG loses nothing between steps andencode(img, "jpeg")converts once.encodein the image's own format returns its bytes unchanged. - Being a value, an image is released when nothing refers to it, crosses a channel or a task like any other value, and cannot be reached by guessing. Until 0.59 it was an integer handle into a process-wide registry that only
image.freeemptied;image.freewas removed in 0.61, andai ... ongiven an Int says to pass the image itself. - Decoding refuses an image whose pixels need more than
ECKO_LIMIT_ALLOC, since a small file can claim a huge canvas, andresizerefuses an output that large - both are errors, not an attempted allocation. load/saveare the only filesystem-touching functions and are capability-gated (fs:read/fs:write); decode/encode/resize/crop are pure.
Compression (std.zlib)
import std.zlib for gzip and raw-deflate compression. Compression is bytes -> bytes (a string compresses its UTF-8 bytes); decompression always returns bytes - decode with string() when you know it's text. Pairs with std.http content-encoding.
import std.zlib
zlib.gzip(data) # bytes | string -> gzip bytes (optional level 0-9)
zlib.gunzip(bytes) # gzip bytes -> the original bytes
zlib.deflate(data) # bytes | string -> raw-deflate bytes (optional level)
zlib.inflate(bytes) # raw-deflate bytes -> the original bytes
- All four are pure (no capability), and the compressors take an optional second argument, a level
0-9(0= store,9= best; default6). - Decompressing a stream of the wrong format errors - gzip and raw deflate are distinct (a gzip stream carries a header;
deflateproduces none). - zstd is not included (it is a separate native library with real binary-size cost); gzip/deflate cover the common web and archive cases.
HTTP
import std.http provides a full client and a server.
import std.http
# Client - all verbs, named-argument options
resp = http.get("https://api.example.com/items", headers: { authorization: "Bearer t" })
made = http.post(url, json: { name: "x" }, timeout: 30000) # milliseconds
print(resp.status) # 200
print(resp.body) # response text
print(resp.headers["content-type"])
meta = http.head(url) # status and headers only; body and body_bytes are empty
http.put(url, body: fs.read_bytes("photo.jpg")) # a bytes body is sent exactly
http.put(url, body: fs.open("backup.tar")) # a stream body is sent as it is read
# Stream the response body instead of buffering it into a string.
live = http.get(url, stream: true)
for piece in live.body { process(piece) } # live.body is a stream of bytes
# Server - the handler receives a request map and returns a response
http.serve(8080, fn(req) {
match [req.method, req.path] {
["GET", "/"] => http.html(render_page())
["POST", "/classify"] => http.json({
sentiment: ai[Sentiment] "Classify: {req.body}"
})
_ => http.not_found()
}
})
- Client verbs:
get,post,put,patch,deleteandhead. - Client options:
headers:(map; a List value sends one header line per element),json:(any value, setscontent-type: application/json),body:(a string is sent as its UTF-8 text,bytesexactly as they are, a byte stream as it is read -fs.open(path)uploads a file without loading it, withcontent-lengthset from the file's size; a stream of unknown length is sent chunked, and a line stream fromio.linesis refused),timeout:(milliseconds, a positive Int, default 60000 - it was seconds before 0.58; a Float, zero, negative or non-number value is refused),stream:(bool). Responses are{ status, headers, body, body_bytes }with lowercase header keys -bodyis the (lossy) text view,body_bytesthe exact payload (downloads, images). A buffered body overECKO_LIMIT_ALLOCis refused with an error namingstream: true, rather than read into memory the program does not have. A response header value is decoded as UTF-8, or as Latin-1 when it is not valid UTF-8 (RFC 9110 obs-text); it is never replaced by"". The client keeps one connection pool per process (pertimeout:andstream:setting), so sequential calls to a host reuse a connection. - With
stream: truethe response is{ status, headers, body }, andbodyis a stream of bytes with nobody_bytesbeside it: the connection is read as the program reads the stream, so the bound is a piece rather than the payload.for piece in resp.bodyyields bytes;io.read_textandio.linesdecode.timeout:becomes the connect deadline plus a per-read deadline that resets on each frame the server sends, andio.timeout(resp.body, ms)sets an independent reader-side one. - Server options, by name:
host:,cert:/key:(TLS),origins:,on_ws:/on_upgrade:,compress:(a Bool, defaulttrue; see Response compression below), and the server's limits -workers:,max_body:,max_conns:,max_streams:,max_ws_conns:,read_timeout_ms:,request_timeout_ms:,drain_ms:. Each limit is also anECKO_HTTP_*setting, which overrides the option when it is set, so an operator can change a deployed server without editing it. A limit must be at least 1 and a timeout 0 or more (0 is off); anything else is refused whenservestarts. - At
max_connsopen connections, a new client makes the server close the connection that has been idle longest (no request in flight, response fully written, idle for at least 1 s); that client reconnects for its next request. The new client is dropped before anything is read only when no connection qualifies. A connection with a request in flight, a streaming response, or one that connected less than a second ago is never closed this way. A request already sent on a closing connection is still answered; a connection that has never completed a request and stays idle (half-sent headers included) is dropped 250 ms later; one that has served a response gets 5 s to finish writing it, and is dropped after that if no request is in flight; and at most a sixteenth ofmax_conns(at least 16) such closes are pending at a time, which bounds how far pastmax_connsmaking room can take the server. - An accept that fails because a client left (aborted, reset, refused) is skipped. Any other accept failure - the process or system out of file descriptors, buffers or memory - never ends the server. It first closes up to 64 of the connections idle longest, as above (the next batch once that one has gone, or after 1 s), and tries again a moment later; when none qualifies it waits 5 ms, doubling to at most 1 s, before the next accept. It logs
ecko http: accept failed: <error>; <what it did>(with a hint to raiseulimit -nfor EMFILE) at most once every 10 s, andecko http: accepting connections againwhen an accept next succeeds after a logged failure. - The handler's request map:
{ method, path, params, headers, body, body_bytes, json, form, files }-paramsis the parsed query string,jsonis the decoded body (ornull),bodyis lossy UTF-8 text andbody_bytesthe raw bytes.formholds url-encoded or multipart text fields;filesholds multipart uploads as{ name, filename, content_type, data }withdataas bytes. Both are empty (never absent) for other content types. - Response helpers:
http.html(s),http.json(v),http.text(s),http.not_found(),http.response(status, body, headers?)- headers are positional orheaders: {...}by name. A List header value sends one header line per element, which is how a response sets several cookies:{ "set-cookie": ["a=1", "b=2"] }is twoSet-Cookielines, and[]sends none. A header name or value holding a control character (CR or LF above all) refuses the whole response: the client gets a 500 and the server log names the header, so a value built from request data cannot split the response or add a header of its own. The same holds for a streaming response's headers. A bare string return becomes a 200 text response. A bytes body (fromhttp.responseor returned bare) is sent raw - serve files and images directly (bare bytes default toapplication/octet-stream). - Streaming responses: return
{ status, headers, stream: ch }wherechis achannel(). The handler returns immediately; each value the channel yields is written as a body chunk (bytes raw, else text) until the channel isclosed, which ends the body. Feed it from anasync fn(see Async tasks). This is the substrate for Server-Sent Events - setcontent-type: text/event-streamand send"data: ...\n\n"frames. A streamed response is drained on a thread of its own, not on the handler pool, so open streams do not reduce handler concurrency. They have their own bound instead (ECKO_HTTP_MAX_STREAMS, default 1024); past it a streaming response is refused with 503 rather than sent as an empty body. A client that disconnects ends its drain within about 10ms, without waiting for the program to produce another chunk. - Handlers run on a bounded pool (
ECKO_HTTP_WORKERS, default 8), which caps how many handler invocations run at once. The cap is the knob that matters for throughput: handlers that compute are fastest at the default, since extra workers only contend for cores, while handlers that wait on a database, a service oraiare limited to roughlyworkers / handler time- 8 workers and a 5ms handler is 1,600 req/s on any machine, and raising the pool lifts it proportionally. Each request is isolated: a handler error becomes a 500, a panicking handler becomes a 500 (the worker survives), and - ifECKO_HTTP_REQUEST_TIMEOUT_MSis set - the client is answered 503 when a handler runs past it, whatever the handler is doing. A computing handler is cancelled at its next step, and so is one insleepor waiting on a channel or a task; one waiting in a syscall (a socket, a lock, anaicall) cannot see the cancel until its wait ends, so the server stops waiting for it and answers on time, and that handler's worker thread is freed when its wait returns. - A 5xx body sent to the client is always the generic
Internal Server Error- internal text (paths, limits, messages) must not leak over the wire. The reason is written to the server's stderr instead, so a 500 stays diagnosable for whoever runs the process: the message, itskindwhen it has one, thefile:line:colthat raised it, and the call stack. - Port 0 asks the OS for any free port.
http.port()returns what it chose (ornullwhen no server is running), and the startup banner names the bound port rather than the 0 that was requested. Readable from a handler or from a task spawned beforeserveblocks. - Graceful shutdown:
http.serveblocks until shutdown. SIGTERM (what a container orchestrator sends before a deploy), Ctrl-C (SIGINT) andhttp.stop()from a handler all drain: the server stops accepting, lets every in-flight request finish, closes idle keep-alive connections, and returns, so the program exits 0. The drain is bounded byECKO_HTTP_DRAIN_MS(default 25000, inside the 30 s an orchestrator allows before SIGKILL); a request still running past it is cut off rather than holding the deploy. A second SIGTERM or Ctrl-C forces the exit (143 or 130). - HTTPS/TLS: pass
cert:andkey:(PEM file paths) to serve over TLS -http.serve(8443, handler, cert: "cert.pem", key: "key.pem"). Both are required together; without them the server is plain HTTP. A TLS listener also advertises HTTP/2 over ALPN, falling back to HTTP/1.1 for clients that cannot speak it. - WebSockets: pass
on_ws: fn(c) { ... }to accept upgrade connections (see WebSockets below). - HTML escaping (XSS): neither
{expr}string interpolation norhttp.htmlescapes anything - they emit values verbatim. When you build HTML from untrusted input (request params, form fields, LLM output), pass it throughescape_html(s)first, e.g.http.html("<p>{escape_html(name)}</p>"). Interpolating raw user data into a page is an XSS hole. - Slow clients: a connection that dribbles its request headers is dropped at
ECKO_HTTP_READ_TIMEOUT_MS(default 30000). This is separate fromECKO_HTTP_REQUEST_TIMEOUT_MS, which bounds handler run time once a request has fully arrived. - Response compression: buffered responses over 1 KiB are compressed when the client sends
Accept-Encoding: gzipordeflate, gzip preferred, and the response gainsContent-EncodingandVary: Accept-Encoding. Already compressed content types (image/*,video/*,audio/*, zip) are skipped, as is anything for which a handler set its ownContent-Encoding. Streaming responses are never compressed, because buffering them to compress would defeat the point.compress: falseonhttp.serve, orECKO_HTTP_COMPRESS=0(which overrides the option), turns it off for the whole server, for when the CPU is worth more than the bytes - a server on the same host as its database, or one behind a proxy that compresses. - Protocol support: HTTP/1.0 and 1.1 with correct keep-alive in both directions, chunked request and response bodies,
100-continue, trailers and request pipelining. HTTP/2 is negotiated over TLS via ALPN. On plain TCP a client that opens with the HTTP/2 preface (h2c with prior knowledge, ascurl --http2-prior-knowledgedoes) is answered in HTTP/2; theUpgrade: h2chandshake from HTTP/1.1 is not offered.
Archives (std.archive)
zip and tar containers. Reading an archive or its inputs needs fs:read; writing one or extracting it needs fs:write.
import std.archive
archive.zip_create("out.zip", ["src/", "README.md"])
archive.zip_extract("out.zip", "dest/")
archive.zip_list("out.zip") # [{ name, size, dir }]
archive.tar_create("out.tar.gz", ["src/"]) # gzip follows the filename
archive.tar_extract("out.tar.gz", "dest/")
archive.tar_list("out.tar.gz")
- Entry names are relative, rooted at the input's last component:
zip_create(out, ["/srv/app/src"])producessrc/..., the same aszip_create(out, ["src/"]). An absolute name in an archive is one that extraction would refuse, so writing one would make the archive unextractable by the tool that wrote it. - Extraction refuses entries that leave the destination.
..components, absolute paths and drive prefixes are rejected rather than sanitised - quietly rewriting a hostile path still extracts an archive that lied about where its contents would go. Non-file entries in a tar (symlinks, hard links) are skipped, because a link is a path something else follows later. - Extraction is capped at
ECKO_LIMIT_UNPACKED(default 1 GiB) on the running total, since the cheap expansion attack is a million small files rather than one big one. .tar.gzand.tgzcompress automatically; passgzip: trueto force it under another name, orgzip: falseto suppress it.- Archives are deterministic: entries are sorted, so the same tree produces the same archive rather than depending on directory iteration order.
zip_createandtar_createreturn the number of files written;_extractreturns the number extracted.
Child processes (std.proc)
Run a program, with a deadline that reaps everything it started. Needs exec - spawning a program and signalling its process group is process control, the same authority os.exec and os.exit need.
import std.proc
import std.io
r = proc.run("ffmpeg", ["-i", "in.mp4", "out.mp4"], timeout_ms: 5000)
r.code r.stdout r.stderr r.timed_out
p = proc.spawn("server", [])
proc.pid(p)
proc.wait(p, 5000) # waits; at the deadline it kills and reaps (timed_out: true)
proc.wait(p) # a poll: result map, or null if still running
proc.kill(p) # SIGTERM to the group; "kill" for SIGKILL. Only signals:
proc.wait(p, 5000) # ...the handle stays valid until wait collects the exit
io.write(proc.stdin(p), "request\n") # the pipes are streams; std.io drives them
io.read_line(proc.stdout(p)) # one line of its stdout, or null at the end
io.timeout(proc.stdout(p), 5000) # a deadline if you want one: it errors
io.close(proc.stdin(p)) # let a child that reads to EOF finish
spawnopens stdin;rundoes not.runwaits for the child to exit, and a child reading a pipe nobody writes to would block forever, so there it stays closed and reads see EOF at once.spawnis for a child you drive: write a request, read the answer, repeat. That is the shape a language server or an MCP server over stdio takes.- The pipes are streams, so the verbs are the ones that read a file or a socket.
proc.stdout(h),proc.stderr(h)andproc.stdin(h)return the same stream on every call, so a line buffered by one read is still there for the next. All three needexec, like the rest of the module. - A read returns
nullonly at the end of the output. A pipe starts with no deadline;io.timeoutsets one, and a read that passes it raises an error, so a loop reading untilnullcannot mistake a slow child for a finished one. The terminator is stripped,\rincluded, and a final line with no newline is still returned. - Closing stdin is not
kill. A child reading until end of input never finishes while the pipe is open.io.close(proc.stdin(h))says "that is all" and lets it exit on its own terms. - The whole tree is reaped, not just the child.
os.exechas no deadline, and killing a process kills only that process - so a timeout aroundsh -c "ffmpeg ..."kills the shell and leaves ffmpeg running. A child started here gets its own process group and the deadline signals the group. - A deadline sends
SIGTERM, thenSIGKILLafter a short grace, because a process ignoring TERM is exactly the case a timeout exists for.timed_outistrueon the result rather than an error, so a caller can still read whatever output arrived first. proc.waitwithout a deadline (or with0) is a poll:nullmeans still running, and the process is left alone. With one, it waits and reaps on expiry.- stdout and stderr are drained continuously, not read after waiting - a child that fills the 64 KiB pipe buffer blocks on write, so reading late would hang instead of timing out. The stream reads from that buffer, and the buffer is unbounded: a child that prints faster than the program reads grows memory, exactly as
proc.run's capture does.proc.waitreturns whatever the streams did not consume, so every byte is delivered once, to whichever side asked first. - The tree is reached on Windows too, but only forcefully. Windows has no process groups in this sense and no signals, so there the group signal becomes
taskkill /PID <pid> /T /F, and/Twalks the child tree the waykillpgdoes. The signal name is validated on every platform, so a typo is refused everywhere, but the distinction betweentermandkillcannot be honoured on Windows: both terminate.
OS signals (std.signal)
Catch SIGTERM and SIGINT so a process can finish what it started instead of dying wherever it happened to be. Installing a handler needs exec: a signal disposition is process-global, so a package that can install one can swallow the operator's Ctrl-C or stop an orchestrator's SIGTERM from ever being seen. That is process control, the same authority os.exit needs.
import std.signal
s = signal.on() # the default set: ["term", "int"]
hup = signal.on(["term", "hup"]) # or name them
name = signal.next(s, 5000) # "term", or null once the deadline passes
signal.close(s)
- Names are lowercase and without the
SIGprefix -signal.names()returns what this platform can deliver. On Unix:int,term,hup,quit,usr1,usr2.SIGKILLis absent because nothing can catch it, and offering it would be a lie. - Windows has no POSIX signals. The console control handler provides Ctrl-C, which is what
intmeans there; the rest are refused by name rather than accepted and never fired. signal.nexttakes a deadline rather than blocking forever, so a drain loop can check between units of work.0polls and returns immediately, and a timeout isnullrather than an error - the check is an ordinaryif.- Handlers compose. Several subscriptions to the same signal all fire, and
std.http's graceful shutdown subscribes through the same registry rather than installing its own. A disposition is process-global, so without one owner whichever installed last would silently win. signal.closestops delivery to that subscription but leaves the process handler installed - removing it would restore the default disposition, so a later Ctrl-C would kill the process outright rather than reaching another live subscriber.signal.raise(name)sends a signal to this process, which is how to exercise a handler without a second terminal and akill.
Filesystem events (std.watch)
inotify on Linux, FSEvents on macOS, ReadDirectoryChangesW on Windows - one surface over all three. Watching needs fs:read: seeing what appears in a directory is reading it.
import std.watch
w = watch.open("./inbox") # non-recursive by default
tree = watch.open("./inbox", recursive: true)
e = watch.next(w, 5000) # { kind, path }, or null once the deadline passes
watch.close(w)
kindis one of"create","modify"or"remove"-watch.kinds()returns the list. Platform-specific access events are dropped, since they fire on plain reads and would drown the signal.w.eventsis a real channel, so a watch composes withrecv, a spawned task, or an SSE response instead of needing its own loop shape.watch.nexttakes a deadline rather than blocking forever: a watch on a quiet directory must not be able to hang the program with no way out.0polls and returns immediately.watch.closestops the OS watch and closes the channel, so a reader parked onrecvsees the end. Closing twice is harmless - afinallyblock will do it.- Events are queued without bound, because blocking the OS notifier thread would drop events for every other watch in the process.
Web router (std.web)
import std.web adds a tiny router over http.serve - path matching with :params, no framework.
import std.http
import std.web
app = web.router([
web.get("/health", fn(req) http.text("ok")),
web.get("/users/:id", fn(req) http.json({ id: req.params["id"] })),
web.post("/users", fn(req) create(req.json)),
])
http.serve(8080, app) # dispatch by method + path; :params merged into req.params
Route constructors: web.get / web.post / web.put / web.delete / web.patch / web.head. web.router returns a handler for http.serve; an unmatched request gets a 404.
A web.get route also answers HEAD. RFC 9110 defines HEAD as GET without the response body, and it is what uptime monitors, health checks, load balancers and curl -I send first - a router that matched the method exactly would 404 them, so a healthy server would report itself down. The GET handler runs and the body is dropped as the response is written, leaving the status and headers (including content-length, the length GET would have sent) intact. Register web.head only when HEAD needs its own handler; an explicit HEAD route takes precedence over the fallback. web.static serves HEAD on the same terms.
- Static files:
web.static(prefix, dir)is a route that serves files underdirfor GET paths starting withprefix, with a content type guessed from the extension. Path traversal (.., symlink escape) is rejected as a 404, as is a missing file. Since 0.59 it takesfs:readondir, checked when the route is built: a package granted onlynetcannot serve a directory. - Middleware:
web.router(routes, [middleware])takes an optional list offn(req, next)functions, run outermost first. Each callsnext(req)to invoke the rest of the chain, or returns its own response to short-circuit (auth gates, CORS, logging, rate limits) - and can post-process the downstream response before returning it.app = web.router( [ web.get("/api/me", fn(req) http.json({ id: 1 })), web.static("/assets", "./public"), ], [ fn(req, next) { # a bearer-token gate if get(req.headers, "authorization") == null { http.response(401, "unauthorized") } else { next(req) } }, ], )
WebSockets (std.ws)
import std.ws for a WebSocket client (ws:// and wss://):
import std.ws
c = ws.connect("wss://echo.example.com") # returns a connection handle
ws.send(c, "hello") # send a text message
msg = ws.recv(c) # block for the next message; null on close
ws.close(c)
ws.recvblocks until a text or binary message arrives, returning it as a string (control frames are handled internally); it returnsnullonce the peer closes.- A connection is an opaque handle. Sending and receiving on the same connection are serialized, so a blocking
recvon one holds only that connection; run arecvloop on its own task if you also need tosend.
Server-side: pass on_upgrade: to http.serve to vet an upgrade before the handshake - it receives the same request map as a handler and returns null to accept or a response to refuse with, so an unwanted socket is answered with a 403 or a 404 rather than accepted and closed. A refused upgrade costs no connection slot. Pass on_ws: to accept incoming WebSocket upgrades. Each connection runs its handler on its own thread, on its own copy of the variables the handler captures (see Shared State; a cell is how connections share), and c is a handle usable with the same ws.send / ws.recv / ws.close:
http.serve(8080, fn(req) http.text("http"), on_ws: fn(c) {
for msg in [1, 2, 3] { # (illustrative) echo a few messages
ws.send(c, "you said: {ws.recv(c)}")
}
}) # the connection closes when on_ws returns
Without on_ws, an upgrade request is refused with 501. An on_ws that throws closes the connection, and the reason goes to the server's stderr as ecko ws: handler failed: <error>, the way a failed HTTP handler's does.
ws.request(c) is what the client asked for - the same map a handler receives, so one piece of code can read either:
http.serve(8080, fn(req) http.text("http"), on_ws: fn(c) {
r = ws.request(c)
if not starts_with(r.path, "/rooms/") {
ws.close(c) # nothing to talk about
} else if not session_ok(r.headers.cookie) {
ws.close(c) # not who they say they are
} else {
join_room(r.path, c)
}
})
method, path, params and headers, carrying whatever the browser sent including its cookies. A client connection answers null: it was not upgraded from anything, so there is no request to give.
It is a verb rather than a second parameter to on_ws because arity is enforced at the call site: on_ws(c, req) would stop every existing handler with an arity error before the program started.
What it cannot do is refuse before the handshake. The 101 has already gone out by the time on_ws runs, so an unwanted socket is accepted and then closed rather than answered with a 403. For a browser that is the ordinary idiom; it is still a difference worth knowing, and on_upgrade: (above) is the place to refuse first.
An upgrade carrying an Origin that does not match the request's Host is refused with 403. Upgrades are answered before the router runs, so no middleware sees them - without this check nothing could refuse one, and any page could open the socket from a victim's browser with the victim's cookies attached. Clients that send no Origin at all (everything that is not a browser) are unaffected. Pass origins: ["https://app.example"] to allow named cross-origin callers, or origins: ["*"] to accept any - the explicit opt-out for a public socket.
Networking (std.net)
import std.net for DNS and raw TCP, below the HTTP/WebSocket layer:
import std.io
import std.net
net.lookup("example.com") # [String] of resolved IP addresses
plain = net.connect("127.0.0.1", 6379) # plain TCP -> a stream
s = net.connect_tls("db.example.com", 5432) # TLS from the first byte
c = net.starttls(plain, verify: false) # upgrade a live plaintext socket
io.write(c, "PING\r\n") # a string writes its UTF-8 bytes...
io.write(c, b"\x00\x2a") # ...bytes write exactly
data = io.read(c, 1024) # read up to N bytes -> bytes; null on close
text = io.read_text(c, 1024) # the text form: strict UTF-8, errors if not
head = io.read_exact(c, 5) # read EXACTLY 5 bytes -> bytes (length-prefixed)
crlf = io.read_until(c, b"\r\n") # read through a delimiter -> bytes (line protocols)
io.close(c)
l = net.listen(0) # accept side: 0 asks the OS for a port
net.port(l) # which port it got
conn = net.accept(l, 5000) # a stream, or null if nothing arrived in 5s
net.stop(l) # idempotent
- A connection is a stream, so the verbs are
std.io's - the same ones that read a file or a child's pipe. It is behind its own lock, so a blocking read holds that connection and nothing else. That lock covers both directions: a read that is waiting blocks a write on the same socket, so one connection is a request-and-response conversation, not a full-duplex one. A protocol that needs to send while a read is parked wants a second connection, orstd.ws. - TLS:
net.connect_tls(host, port, verify:)handshakes up front;net.starttls(conn, verify:)upgrades a live plaintext socket in place and returns the same stream (the STARTTLS shape - PostgresSSLRequest, SMTPSTARTTLS). Certificates are verified against the OS trust store by default, and against the host name the caller connected with rather than the address it resolved to;verify: falseaccepts any cert (self-signed / dev only). Everything after is transparent: theioverbs behave identically on plain and TLS connections. An upgrade is refused while plaintext the program read ahead is still buffered, because those bytes arrived before the handshake and cannot belong to it. - Errors: a failure while connecting - a name that does not resolve, a refused or unreachable address, a connect timeout, a failed TLS handshake - throws
{ kind: "net", host }, fromnet.lookup,net.connect,net.connect_tlsandnet.starttlsalike. Once the stream is open, a read or write failure (a reset, a deadline passing) isio, as for any stream. - Deadlines: a socket starts with a read and write deadline (
ECKO_NET_TIMEOUT_MS, default 30000), so a peer that accepts and then sends nothing surfaces an error instead of blocking forever.0disables it, for a socket that legitimately waits on server push, andio.timeout(c, ms)changes it for one socket. io.readdoes a single read of up to N bytes -> bytes (nullon close).io.read_textdecodes as UTF-8, erroring on invalid data (never lossy).- Framing for wire protocols:
io.read_exact(c, n)reads exactlynbytes (errors on early close - never a short read, and what it did read stays readable), andio.read_until(c, delim)reads up to and including a delimiter without consuming past it (line protocols like Redis RESP). These, plus TLS, are the plumbing that lets DB clients be written in pure Ecko. - Server sockets:
net.listen(port, host?)returns a listener handle - not a stream, because reading it yields connections rather than bytes - bound to0.0.0.0unless a host is given.net.accept(l, timeout_ms?)answers a connection stream, ornullwhen nothing arrived in time, the wayproc.waitdoes for a handle; without a deadline it waits.net.port(l)reports the bound port, which is how a listener on port0finds out what the OS chose.net.stop(l)closes it and is idempotent. An accepted connection is a plain stream:net.starttlsrefuses it, because TLS on the accepting side presents a certificate wherestarttlsverifies one. - Removed in 0.23:
net.send,net.recv,net.recv_text,net.recv_exact,net.recv_untilandnet.close. Theioverbs above replace them one for one, andecko checknames the replacement for each.
UDP datagrams
import std.net
sock = net.udp_bind("0.0.0.0", 0) # a socket handle; 0 asks the OS for a port
net.port(sock) # which port it got
net.send_to(sock, "127.0.0.1", 9000, "ping") # bytes or a string -> Int written
msg = net.recv_from(sock) # ONE datagram: { data, host, port }
net.timeout(sock, 2000) # read+write deadline in ms; 0 disables
net.broadcast(sock, true) # SO_BROADCAST
net.udp_close(sock) # idempotent
- A UDP socket is not a stream. This is the load-bearing decision. The
PullSourcecontract promises byte-stream semantics, where joining two consecutive chunks is always correct:io.read_exact,io.read_untilandio.linesall rely on it. Datagrams have message boundaries that must never be joined, so a UDP socket that was a stream would letio.read_exact(s, 10)splice two unrelated packets into one value with nothing able to detect it. Keeping it out of the stream model makes that unreachable rather than discouraged. The cost is that UDP does not reuse thestd.ioverb set, and that cost is the right one: one stream value behaving two ways is a worse promise than two honest value kinds. - A deadline is an error, not
null.nullmeans end of stream and nothing else, and a datagram socket has no end, so there is no meaning to give it.recv_frompast its deadline raisessocket: timed out. New sockets inheritECKO_NET_TIMEOUT_MS(default 30000), the same variable TCP reads, so one setting governs both;net.timeout(sock, ms)overrides it. recv_fromreturns the sender, which is why it is a map rather than a read verb: a connectionless reply has no other way to learn where to go.datais bytes,hosta string,portan Int.- The receive buffer is a fixed 65536 bytes. The maximum UDP payload is 65507, so a datagram cannot be truncated by construction and
ECKO_LIMIT_ALLOCnever enters into it. net.porttakes either kind. Listener handles and UDP sockets draw ids from one counter, so a handle is valid in at most one registry.- Multicast is out, broadcast is in. Joining a group needs interface selection and IPv6 scope ids, a real surface with no current demand;
SO_BROADCASTis one setsockopt and ordinary LAN discovery needs it. udp_close, notclose.net.closeis a name 0.23 removed, andecko checkstill answers it with "useio.close(c)". A native by that name would shadow that hint and answer old TCP code with a datagram type error.
DNS (std.dns)
import std.dns for hostname resolution and typed record lookups. It sits above getaddrinfo (net.lookup), which can only answer address queries - MX/TXT/CNAME need a real resolver:
import std.dns
dns.resolve("example.com") # [String] of IPs (A + AAAA)
dns.reverse("8.8.8.8") # String - the primary PTR hostname
dns.lookup("example.com", "A") # [String] - likewise AAAA / TXT / CNAME
dns.lookup("example.com", "MX") # [{priority: Int, host: String}]
- Results are deterministic: addresses sort numerically (IPv4 before IPv6), strings sort lexically, MX sorts by priority then host - stable output even where live DNS rotates record order.
- Offline tier: names under the reserved
.testTLD (RFC 6761) andlocalhost- plus the loopback, TEST-NET-1 (192.0.2.0/24), and documentation-prefix (2001:db8::/32) addresses they map to - are answered from a built-in fixed hosts table, no network touched:dns.resolve("ecko.test")→[192.0.2.10, 2001:db8::10],dns.lookup("ecko.test", "MX"),dns.reverse("192.0.2.10")→"ecko.test". Examples and tests are reproducible byte-for-byte. - Everything else queries the system resolver (
/etc/resolv.confon Unix). - Resolution failures throw the
neterror kind with ahostfield. An unsupported record type (anything outside A/AAAA/CNAME/MX/TXT) or a non-string argument is a plain error.
SQL (std.sql)
import std.sql provides embedded SQLite - bundled into the binary, nothing to install. Parameters bind with ? placeholders.
import std.sql
db = sql.open("app.db") # or ":memory:"
sql.exec(db, "create table notes(id integer primary key, body text)")
sql.exec(db, "insert into notes(body) values (?)", ["hello"]) # -> rows affected
rows = sql.query(db, "select * from notes where id > ?", [0]) # [ {id, body}, ... ]
one = sql.query_one(db, "select count(*) as n from notes") # first row, or null
sql.close(db)
query returns rows as maps keyed by column name; SQLite types map to Int / Float / String / Null, and BLOB columns map to bytes (binary, exact - decode with string() when a column holds UTF-8 text). Binding a bytes parameter stores it as a BLOB. Connections are opaque integer handles.
Transactions. sql.transaction(db, fn(tx) ...) runs the function inside a transaction, committing on success and rolling back if it raises (the error re-raises, so a partial write never persists); the closure's value is returned. tx is the same handle - run your sql.exec/sql.query calls on it. The manual primitives sql.begin(db) / sql.commit(db) / sql.rollback(db) are also available. SQLite has no nested BEGIN, so don't start a transaction inside another on the same connection - one on the same thread is refused at once.
Contention waits. sql.open(path, busy_timeout_ms:) sets how long the connection waits for another connection's lock before failing with { kind: "sql", message: "... database is locked" }; the default is ECKO_SQL_BUSY_TIMEOUT_MS, else 5000, and 0 means do not wait. sql.transaction begins with BEGIN IMMEDIATE, taking the write lock up front, so a read-then-write transaction is never refused mid-way by another writer (sql.begin stays a deferred BEGIN). On a handle shared between threads, a second thread's sql.transaction waits for the first, bounded by the same timeout, and so does any other statement from that thread (sql.exec, sql.query, sql.query_one, sql.begin/commit/rollback): it runs after the transaction ends, never inside it, and a wait past the timeout fails with { kind: "sql" }. Transactions from one process on any connections to the same file queue in arrival order before taking SQLite's lock (SQLite's own busy handler is not fair, and starved a waiter under sustained contention); a second transaction from the same thread on another connection to that file is refused at once.
sql.transaction(db, fn(tx) {
sql.exec(tx, "insert into accounts(id, cents) values (?, ?)", [1, 100])
sql.exec(tx, "update accounts set cents = cents - 100 where id = ?", [2])
}) # both writes commit together, or neither does
sql { ... } query blocks
A sql { ... } block writes SQL as raw text. Every {expr} hole compiles to a bind parameter (a ? placeholder), never a string splice - so a value can't break out of its slot. This is injection safety by construction, and it rhymes with secret and the template-input guard.
name = "Ada"
q = sql { SELECT id FROM users WHERE name = {name} }
# q is just a map you can inspect:
# { query: "SELECT id FROM users WHERE name = ?", params: ["Ada"] }
sql.query(db, sql { SELECT * FROM users WHERE id = {uid} }) # -> rows
sql.exec(db, sql { INSERT INTO users(name) VALUES ({name}) }) # -> rows affected
The block evaluates to a { query, params } map (holes bind left to right, the query text trimmed), which sql.query / sql.exec accept alongside the plain (db, string, [params]) form - always with an explicit db handle, never an ambient connection. The official postgresql-client (from 0.38) and mysql-client (from 0.39) packages take a block in their query too; Postgres numbers its ? placeholders as $1..$N. sql followed by { always opens a block; sql.query and the rest are ordinary field access. fmt round-trips the SQL text verbatim.
Embeddings
embed turns text into a vector; cosine compares two vectors. Offline these use deterministic mock vectors (so similarity search and clustering work in CI); with a provider configured, real embeddings are used.
v = embed("some text") # [Float]
vs = embed_all(["a", "b", "c"]) # [[Float]]
cosine(v, v) # 1.0 - a vector is identical to itself
Low-level LLM access (std.llm)
import std.llm is the provider layer with the language machinery taken off. llm.chat sends one prompt and returns the reply as a string - no typed coercion, no contracts, no retry loop, no tool calls. Reach for it when you want the provider and nothing else; reach for ai the rest of the time.
import std.llm
llm.chat({ user: "Say hello" })
llm.chat({ system: "Answer in one word.", user: "Capital of France?" })
llm.chat({ user: "Summarize this", model: "gpt-4o-mini" }) # per-call override
llm.is_mock() # true when `ai` is answering offline
user is the only required field, and a call without it is an error. system sets the system prompt and model overrides the configured model for that call only - it is passed through rather than written to the environment, so concurrent workers under pmap cannot clobber each other's choice.
With no provider configured it returns a deterministic mock string rather than failing, on the same principle as ai: the program still runs offline. A failing call raises a catchable error.
The trade-off is explicit. ai gives typed output, @requires/@ensures contracts, majority voting, tools, sessions, streaming, caching and the retry loop. llm.chat gives you a string.
Terminal (std.term)
What touches the terminal itself: whether stdout is one, its size, whether colour should be written, and keyboard input. Styling - colours, attributes, rgb, style, link, cursor and clear sequences, strip, width - is string building and lives in the tui package; it was in std.term until 0.61.
import std.term
term.is_tty() # is stdout a terminal?
term.color_enabled() # should escape codes be written?
term.size() # { rows, cols } (80x24 fallback off a terminal)
color_enabled()follows the conventions in order:CLICOLOR_FORCEset forces colour on,NO_COLORset forces it off, and otherwise colour is on exactly when stdout is a terminal. Anything that styles its own output asks this first, so the same program is colourful interactively and clean in a pipe.size()returns the real size when interactive and a stable 80x24 otherwise, so piped runs stay deterministic.
Keyboard input
The input side for fully interactive TUIs (menus, editors, games). Unix-only for now (termios); the functions error on other platforms.
import std.term
term.raw_mode(true) # no line buffering, no echo
key = term.read_key() # blocks: "a", "enter", "up", "ctrl-c", ...
next = term.read_key(timeout: 50) # null once 50ms pass with no key
if term.poll() { ... } # is input waiting? (never blocks)
term.raw_mode(false) # restore - also auto-restored at exit
raw_mode(on)switches the terminal's line discipline off/on (per-keypress input, no echo;ctrl-cbecomes a readable key). The original settings are restored byraw_mode(false)and automatically at process exit, even after an error. Off a TTY (piped stdin) it is a no-op returningfalse, so the same program stays testable.read_key()reads one keypress and returns a friendly name: printable characters as themselves (full UTF-8), andenter,tab,esc,backspace,up/down/left/right,home/end,insert/delete,pageup/pagedown,f1-f12,ctrl-a..ctrl-z,shift-tab, plusctrl-/alt-/shift-prefixes for modified arrows and nav keys. Returnsnullat end of input, so aloopthat breaks onnullends cleanly;read_key(timeout: ms)also returnsnullwhen the deadline passes with no key.poll()reports whether a read would find input, without blocking - the building block for game/render loops.
read_key works on any stdin (pipe or TTY), which is how it stays testable offline; raw_mode(true) is only needed for live per-keypress input. See demos/keys.ecko for an interactive arrow-key menu (read demos/README.md for why it lives outside examples/).
Randomness, hashing & encoding
import std.uuid
uuid.v4() # "e3b0c442-..." random; uuid.v7() time-ordered
import std.random
random.seed(42) # reproducible sequence (process-wide RNG)
random.int(1, 6) / random.float() / random.choice(xs) / random.shuffle(xs)
random.bytes(32) # CSPRNG: n random bytes from OS entropy
random.token() # 32-byte token, url-safe base64 (or token(n))
import std.hash
hash.sha256("abc") # hex digest; input is a string, bytes or a stream
hash.sha256(stream) # read a chunk at a time, never held whole
hash.hmac_sha256(key, message) # key a string or bytes; message also a stream
hash.sha256_bytes(data) # raw 32-byte digest as bytes
hash.hmac_sha256_bytes(key, msg)
hash.sha512(data) / hash.sha512_bytes(data) # SHA-512, 64-byte digest
hash.sha3_256(data) / hash.sha3_256_bytes(data) # SHA3-256, 32-byte digest
hash.blake2b(data) / hash.blake2b_bytes(data) # BLAKE2b-512, 64-byte digest
hash.sha1(data) / hash.sha1_bytes(data) # SHA-1: legacy protocols only, not new hashing
hash.md5(data) / hash.md5_bytes(data) # MD5: checksums and protocols only, not security
h = hash.hasher("sha256") # "sha256" | "sha512" | "sha3_256" | "sha1" | "md5": a value
h = hash.update(h, data) # -> a new hasher; data is bytes, a string or a stream
hash.finish(h) / hash.finish_bytes(h) # hex / raw digest; the same as the one-shot form
hash.key() # 32 random bytes (OS entropy) for encrypt/decrypt
hash.encrypt(key, data, aad: ctx) # -> sealed bytes; data is bytes or a string
hash.decrypt(key, sealed, aad: ctx) # -> bytes; throws kind "crypto" on any mismatch
hash.password("pw") # Argon2id PHC string (random salt per call)
hash.bcrypt("pw", cost: 10) # bcrypt "$2b$" string; cost 4-31; at most 72 bytes
hash.verify("pw", stored) # Argon2id or bcrypt; constant-time -> Bool (false on a bad hash)
hash.constant_eq(a, b) # compare a MAC or token without an early exit
k = hash.keypair("ed25519") # {private: secret PEM, public: PEM}; "p256" / "p384"
hash.sign(k.private, msg) # -> signature bytes; the key picks the algorithm
hash.sign(rsa_pem, msg, alg: "PS256") # RS256/384/512, PS256/384/512, ES256/384, EdDSA
hash.signed(k.public, msg, sig) # -> Bool; the key is PEM, DER bytes or a JWK map
hash.signed(jwk, msg, sig, der: true) # der: ECDSA in ASN.1 DER, not r || s
import std.encoding
encoding.base64_encode(data) # data: bytes, or a string's UTF-8 bytes
encoding.base64_decode(s) # -> bytes (binary survives the round trip)
encoding.base64_decode_text(s) # -> string; errors on invalid UTF-8
encoding.hex_encode(data) / encoding.hex_decode(s) # same shape
encoding.hex_decode_text(s)
encoding.url_encode(s) / encoding.url_decode(s) # text-only
Every digest (hash.sha256, sha512, sha3_256, blake2b, sha1, md5), its _bytes form and the message of hash.hmac_sha256 also take a stream. It is read a chunk at a time to the end and consumed by the call, the digest is the same as hashing the same content as a string, and the memory bound is a chunk - so hash.sha256(fs.open(path)) digests a file larger than memory, and there is no hash.file because that is already the spelling. A line stream from io.lines is refused: its terminators are gone, so the digest would be of something that was never the input.
Decoders return bytes - decoding produces binary data, and the old lossy-string behavior silently corrupted it. The *_decode_text forms are the explicit "this is text" variants (identical on valid UTF-8, loud error otherwise). ecko fix --migrate --only=bytes <paths> rewrites text-assuming callers mechanically (*_decode -> *_decode_text).
random.seed(n) seeds a process-wide RNG - concurrent workers share it, so seed once at startup if you need reproducibility. random.bytes(n) and random.token(n) are the crypto-safe pair: they draw from OS entropy, not the seedable RNG, so session tokens, CSRF tokens, and API keys stay unpredictable even after random.seed. random.token returns url-safe base64 (no padding), ready for cookies and URLs. hash.password / hash.verify are the password pair - Argon2id with a per-call random salt, storing a self-describing PHC string; verify is constant-time and returns false (never errors) on a malformed stored hash, so a login path can't be crashed by bad data. hash.bcrypt(password, cost: 10) is for apps whose stored hashes are bcrypt: it returns a 60-character $2b$ string with a random salt, cost: is an Int from 4 to 31 (10 when absent), and a password over 72 bytes raises an argument error, because bcrypt reads only the first 72 and cutting the rest off would let passwords sharing them match. hash.verify recognises bcrypt hashes ($2a$, $2b$, $2x$, $2y$) by their prefix and checks them with the cost they carry; a candidate over 72 bytes is false.
hash.md5 takes the same inputs as hash.sha256 (a string, bytes or a stream) and returns lowercase hex; hash.md5_bytes returns the raw 16-byte digest, which is what S3's Content-MD5 header wants, base64-encoded: encoding.base64_encode(hash.md5_bytes(fs.open(path))). MD5 is broken for collision resistance - use it for checksums and protocols that name it, never to authenticate or sign anything.
hash.sha512, hash.sha3_256 and hash.blake2b (BLAKE2b with its full 512-bit output) exist for interop with formats and protocols that name them; for a new integrity check sha256 is enough. hash.hasher takes every digest except blake2b, whose implementation does not expose its state, and a hasher is that state - hash.blake2b(stream) still hashes a large file a chunk at a time.
Authenticated encryption. hash.encrypt(key, data, aad: ...) seals data (bytes, or a string as its UTF-8) with ChaCha20-Poly1305 (RFC 8439) and returns bytes laid out as
version (1 byte, 0x01) || nonce (12) || ciphertext || tag (16)
The nonce is drawn from OS entropy on every call, so encrypting the same data twice gives different output; the caller never handles one. Version 0x01 means exactly this cipher, so a future format is a new version byte; after it the bytes are the standard RFC 8439 nonce || ciphertext || tag. hash.key() returns a fresh 32-byte key. key must be exactly 32 bytes of bytes (never a string - derive one from a passphrase elsewhere); any other length or type is an ordinary argument error. aad: is optional associated data (bytes or a string): it is authenticated but not stored, so decrypt must be given the same value. hash.decrypt(key, sealed, aad: ...) returns the plaintext as bytes and throws { kind: "crypto" } when the key is wrong, the aad: differs, the data was altered by even one bit, or the sealed bytes are truncated or carry an unknown version; the message does not say which. Streams are refused for data - a sealed value is one message with one tag, so the whole message is held in memory (under ECKO_LIMIT_ALLOC). Random 96-bit nonces are safe up to about 2^32 messages per key; rotate keys past that.
hash.constant_eq(a, b) compares two strings or byte values without stopping at the first difference. Use it for anything secret you check for equality - a MAC, a CSRF token, a session id, an API key. == returns as soon as it finds a differing byte, so how long it takes reveals how much of a guess was right, and an attacker who can time the answer recovers the value a byte at a time.
It takes bytes or a string, and a string compares as its UTF-8, so a hex digest and its _bytes form both work. Values of different lengths are false rather than an error: length is not hidden, only content. Every value this is for is fixed-length, so the length carries nothing an attacker does not already know.
This is native rather than written in Ecko for the same reason hash.password is: a loop in the language allocates, bounds-checks and can be descheduled between iterations, so it cannot promise anything about timing.
Signatures. hash.sign(private_key, message, alg: ..., der: ...) returns a signature as bytes, and hash.signed(public_key, message, signature, alg: ..., der: ...) returns whether it verifies. The algorithms take their JWS names: EdDSA (Ed25519), ES256 and ES384 (ECDSA on P-256 and P-384, with SHA-256 and SHA-384), RS256, RS384 and RS512 (RSA PKCS#1 v1.5), and PS256, PS384 and PS512 (RSA-PSS, salt the length of the digest). When alg: is absent the key decides: Ed25519 signs EdDSA, a P-256 key ES256, a P-384 key ES384, and an RSA key RS256. An alg: the key cannot do - ES256 with an RSA key - is an argument error, not a false. HS256 and the other HMACs are refused with a pointer to hash.hmac_sha256: keeping HMAC out of these functions means an RSA public key can never be used as an HMAC secret, the "algorithm confusion" attack on JWT verifiers.
An ECDSA signature is r || s by default, fixed-width, which is what JWS and WebAuthn use; der: true reads and writes the ASN.1 DER form that OpenSSL and X.509 use instead. der: with any other algorithm is an argument error. Ed25519 signatures are deterministic, so signing the same message with the same key always gives the same bytes; ECDSA and PSS signatures differ on every call and all verify.
A private key is PEM text (PKCS#8 PRIVATE KEY, or PKCS#1 RSA PRIVATE KEY), DER bytes of PKCS#8, or a secret holding either. A public key is PEM text (PUBLIC KEY, or PKCS#1 RSA PUBLIC KEY), DER bytes, a JWK map ({kty: "RSA", n, e}, {kty: "EC", crv: "P-256", x, y} or {kty: "OKP", crv: "Ed25519", x}), or the 32 raw bytes of an Ed25519 key. A JWK's own alg, when it has one, is used when alg: is absent, so a key from a JWKS document verifies with what it says it is for. A key that cannot be read throws { kind: "parse" }, with the openssl command that converts it when the format is a known one this does not take (a SEC1 EC PRIVATE KEY, an encrypted key, a certificate). RSA keys under 2048 bits or over 8192 are refused the same way. hash.signed throws only for its key: a signature that does not verify, including one of the wrong length or shape, is false. hash.sign throws { kind: "crypto" } if signing fails after the key was read.
hash.keypair(algorithm) makes a new key pair from OS entropy, for "ed25519", "p256" or "p384", as {private, public}: the private key is PEM text wrapped as a secret, and the public key plain PEM. It does not make RSA keys; the error says how to make one with openssl. The message for every signature function is bytes or a string (its UTF-8), held whole: a stream is refused, as for hash.encrypt.
Math (std.math)
import std.math for constants and the float-domain functions. The Int-aware basics (abs, floor, ceil, round, min, max) stay global. min and max take a list or range (max(xs)) or two or more values (max(a, b)).
import std.math
math.pi / math.e / math.tau / math.inf / math.nan # constants
math.sin(x) / cos(x) / tan(x) / asin(x) / acos(x) / atan(x) / atan2(y, x)
math.exp(x) / ln(x) / log2(x) / log10(x) / log(x, base)
math.sqrt(x) / cbrt(x) / pow(x, y) / hypot(x, y)
math.sign(x) # -1 / 0 / 1 (Int)
math.clamp(x, lo, hi) # x confined to [lo, hi]
math.factorial(n) # Int, checked overflow (21! overflows i64)
Every function coerces Int or Float input to Float and returns Float, except sign and factorial, which return Int.
Formatting, logging & CSV
import std.fmt
fmt.format(r"{} of {}", 3, 10) # "3 of 10" - raw string so {} isn't interpolated
fmt.fixed(3.14159, 2) # "3.14" - fixed decimals, halves away from zero
fmt.fixed(decimal("0.07"), 2) # "0.07" - a Decimal is rounded in decimal, never
# through float
fmt.inspect([1, { a: 1 }]) # "list[2] [int 1, map{1} {a: int 1}]" - typed,
# keys sorted, a secret shown as [secret]; a
# value too deep for the native stack is a
# catchable `bug` error
# Removed in 0.61 (they duplicated std.str): fmt.pad_left / pad_right /
# repeat / truncate -> str.pad_start / str.pad_end / str.repeat / s[..n].
import std.log # leveled logging with pluggable sinks
log.info("started", { port: 8080 })
log.warn(...) / log.error(...) / log.debug(...)
# Sinks: the default is one stderr/text sink filtered by ECKO_LOG. Add or
# replace them; each sink has its own level, text-or-JSON format, and rotation.
log.to_file("app.log", level: "warn", json: true, max_bytes: 1000000, keep: 5)
log.to_stderr(json: true)
log.to_stderr(location: true) # each line ends at=app.ecko:12:5 - the call site
log.configure({ sinks: [{ target: "stderr", level: "info" },
{ target: "file", path: "app.log", json: true }] })
log.reset() # back to the single default stderr sink
import std.csv
csv.parse(text) / csv.stringify(rows) # rows are maps keyed by column
csv.read(path) / csv.write(path, rows)
csv.each(path, fn(row) load(row)) # one row at a time -> { rows, errors }
csv.each(stream, fn(row) load(row), on_error: fn(bad) keep(bad))
import std.json
json.encode(v) / json.decode(s) # value <-> JSON string
json.decode(s, decimal: true) # non-integers as exact decimals
json.read(path) / json.write(path, v) # JSON file I/O (read takes the option too)
fmt.format uses {} placeholders in a raw string (a normal string would trigger Ecko's own {expr} interpolation). log defaults to one stderr sink filtered by ECKO_LOG (debug < info < warn < error, default info); fields print in sorted order. to_file / to_stderr / configure add or replace sinks, each with its own level, json (text [LEVEL] msg k=v vs one JSON object per line), and size-based rotation (max_bytes + keep, rolling app.log -> app.log.1 ...). location: true makes a sink name each line's call site as file:line:col, the way an error names a location: at=app.ecko:12:5 at the end of a text line, an "at" field after "msg" in JSON. The file is the imported module for a call inside one, else the program being run (just line:col when there is no file, as for an embedded string); a field the caller named at is kept and the location is not added. Every engine records the call site before each native call, so the location is the call that logged, through an alias (note = log.info) or a contracted function alike. There is no automatic timestamp, so output stays deterministic; add time.now() as a field when you want one. log.reset() restores the default. csv.stringify sorts columns, since Ecko maps are unordered.
Config formats (std.toml, std.yaml)
import std.toml
cfg = toml.parse("[server]\nport = 8080") # nested tables -> nested maps
toml.stringify(value) / toml.read(path) / toml.write(path, value)
import std.yaml
yaml.parse(text) / yaml.stringify(value) / yaml.read(path) / yaml.write(path, value)
Both have the same shape: parse/stringify for strings, read/write for files. Values map to Ecko's usual types (maps, lists, strings, ints, floats, bools), so they interconvert with JSON. Output keys are sorted (deterministic). toml.stringify requires a map at the root - TOML has no top-level array or scalar. Both stringifys (and so both writes) refuse a value nested more than 1000 containers deep with a limit error carrying limit: 1000, because their serializers recurse per level. json.encode has no such bound: it is exact at any depth.
Shared State (cell)
Ecko's parallel calls (pmap callbacks, http.serve handlers, on_ws connections) each observe a snapshot of captured variables, taken from the state before the map or the server started - mutating an ordinary outer mut from a parallel closure changes only that call's copy. The caller never sees the write, and no call sees another call's, so a call's result does not depend on scheduling. (Each worker thread keeps one copy and resets its mut bindings and captured locals before every call, so the snapshot costs one write per mutable slot, not a copy of the program. An on_ws connection gets its copy when it opens and keeps it until it closes, so its writes last across its own messages and reach no other connection.) A function a parallel call creates and returns keeps that call's copy as its globals: calling it later, from anywhere, reads and writes the copy and never the caller's variables of the same name. When workers genuinely need to share mutable state (a request counter, an accumulator), use a cell: explicit, thread-safe, and the one place locking is intentional.
hits = cell(0) # thread-safe mutable box
http.serve(8080, fn(req) {
n = cell_update(hits, fn(v) v + 1) # atomic read-modify-write
http.text("request #{n}")
})
cell(initial)- create a cell.cell_get(c)- read the current value (a copy).cell_set(c, v)- replace the value.cell_update(c, fn)- runfn(current)under the cell's lock and store the result atomically; returns the new value. Use this (notcell_set(c, cell_get(c) + 1)) for counters - the latter races.- Binding a cell to another name shares it (unlike a list, which copies); that's the point.
- Caveat: don't touch the same cell inside its own
cell_updatefunction - the lock is not reentrant and would deadlock.
Async tasks (async / await)
Calling an async function spawns its body as a concurrent task and returns a task handle immediately; await blocks until the task finishes and yields its result. Many tasks run at once, so this is how you overlap I/O-bound work (LLM calls, HTTP, SQL):
async fn summarize(doc) {
ai "Summarize in one line: {doc}"
}
# All three summaries are in flight at once...
tasks = map(docs, fn(d) summarize(d)) # each call spawns a task
summaries = map(tasks, fn(t) await t) # ...then join them
Anonymous async functions use async fn(args) body; async |args| body is the deprecated spelling (ecko check warns; ecko fmt canonicalises it to the fn(...) form). Their task, capture, cancellation, and error semantics are identical to named async fn. map(items, async fn(item) ...) therefore returns a list of tasks. Higher-order builtins that require each callback result immediately (predicates, key functions, folds, retries, and cell_update) reject async callbacks; map to tasks and await them explicitly instead.
- Spawn on call, join on
await.awaiton a non-task value returns it unchanged (soawait 7 == 7). - Errors propagate at
await. An error thrown inside a task - including a structurederror({ kind, message })- surfaces (intact) where it is awaited, sotry { await t } catch (e) { ... }works. - Same share-nothing model as
pmap. Each call snapshots ordinary arguments and captured variables before its task starts. Mutating a capturedmutchanges only that task's copy; usecellwhen tasks must share updates. Each task runs on its own thread. - Bounded execution. At most
ECKO_LIMIT_TASKStasks run at once (default 256); the rest queue. A task parked onawaitfrees its slot (and reclaims one on resume), so nested awaits never deadlock the pool. cancel(task)requests cancellation. It is cooperative: the task unwinds at its next loop or call checkpoint, and runtime-managed waits (await, channel receive/select/iteration, and stream waits) are interrupted promptly. A task blocked in an external syscall (a slow HTTP read) still stops only once that call returns. Cancelling a parent parked onawaitpropagates cancellation to the awaited child. Awaiting a cancelled task raises{ kind: "cancelled" }.
Channels
For coordination beyond fork-join, tasks pass values through a channel:
jobs = channel()
async fn produce() {
for n in [1, 2, 3] { send(jobs, n) }
close(jobs) # signals "no more values"
}
produce()
for job in jobs { handle(job) } # drains until the channel is closed
channel()- a new unbounded, multi-producer/multi-consumer channel.channel(n)- the bounded form (n >= 1): the buffer holds at mostnvalues, andsendblocks while it is full - real backpressure for producer/consumer pipelines instead of an unbounded queue. The blocked send is cancellation-aware and wakes as receivers drain (or errors if the channel closes).send(ch, v)- enqueuev(never blocks on an unbounded channel); errors on a closed channel.recv(ch)- dequeue the next value, blocking until one is available; returnsnullonce the channel is closed and drained.try_recv(ch)- the non-blocking receive: the next value, ornullimmediately (whether the channel is merely empty or closed and drained - the same null convention asrecv). Poll-friendly: do other work between attempts instead of parking.close(ch)- mark the channel done; wakes blocked receivers and senders.select([ch1, ch2, ...])- fan-in: blocks until one of the channels has a value and returns it (the earlier channel in the list wins when several are ready), ornullonce every channel is closed and drained. Only the winning channel is consumed. Tag values beforesendif you need to know which channel a result came from.for v in ch { ... }- the idiomatic consumer: drains the channel, ending when it is closed (a value ofnullsent as data is still yielded, unlike therecvsentinel).
Streaming (-> stream)
ai "..." -> stream runs in the background and returns a stream you can consume two ways:
s = ai "write a poem" -> stream
for chunk in s {
print_no_newline(chunk) # incrementally, chunk by chunk
}
full = string(s) # or block for the whole result
Iterating drains text chunks; using the stream as a value blocks for the final (typed-coerced) result. Offline the chunks are the mock text split into pieces; with a live provider, untyped streams deliver the model's tokens as they arrive - real server-sent events, across OpenAI, OpenRouter, and Ollama. A typed stream (ai[T] ... -> stream) instead resolves through the normal coercion-and-retry path and chunks the completed result, since it needs the whole response to validate the schema.
That stream is the same type as every other one (see Streams): the std.io verbs read it, and its bytes are the UTF-8 of its text. It is the only stream with a value other than itself - using it as a value blocks for the final result, where any other stream has to be read.
A streamed call is a provider call and accounts for itself like one. It counts against ECKO_AI_MAX_CALLS, and it reports the token counts the provider returned, so ECKO_AI_TRACE records its usage and cost the way it does for any other call.
It retries a transient failure - a timeout, a 429, a 5xx - only while nothing has reached the caller yet. Once a chunk has been handed out it cannot be taken back, so replaying the call would deliver that chunk twice and the assembled text would be wrong with nothing downstream able to tell. A stream that fails part-way through therefore raises, rather than starting over.
Background tasks (std.bg)
import std.bg adds fire-and-forget background work with lifecycle management, built on the same task machinery as async fn (a returned task is the same Task value that await accepts).
import std.bg
t = bg.spawn(fn() expensive()) # start work in the background
bg.status(t) # "running" | "completed" | "failed"
bg.result(t) # block for the value (raises if it failed)
bg.cancel(t) # cooperative cancellation
bg.spawn(add, [2, 3]) # optional second arg: a list of call args
bg.after(1000, fn() cleanup()) # run once after a delay (ms)
bg.every(1000, fn() heartbeat()) # run on an interval until cancelled
bg.join_all([a, b, c]) # block for all, returns a list of values
- Tasks are bounded by the same
ECKO_LIMIT_TASKSrunning-slot semaphore asasynctasks, and a panicking task surfaces as a failed result rather than leaking its slot. after/everysleep cancellably:bg.cancelwakes them promptly.everystops on cancel (resultnull) or if an iteration errors (that error).bg.resultandbg.join_allre-raise a failed task's error value whole, kind and fields included, asawaitdoes;join_allraises the first failure in list order.
Testing (std.test + ecko test)
A test file is a plain script; cases run as they are defined, print a result line each, and keep going after failures:
import std.test
test.case("slugify lowercases", fn() {
test.eq(slugify("Hello World"), "hello-world") # eq(actual, expected)
test.ok(contains("ecko", "ck"), "substring") # truthiness + label
})
test.case("bad input errors", fn() {
test.err(fn() parse_config(""), "empty") # must error, msg contains
})
test.case(name, fn)(aliastest.group) runsfnnow, printsok <name>orFAIL <name> - <why>, and records the outcome. A failing assert unwinds only its own case; later cases still run. A body that runs cases of its own is a group: its cases are what is counted, and its line after them isok <name>, orFAIL <name> - N of M cases failedwhen any failed. It counts once itself only for an error raised in its body outside every case (FAIL <name> - <why>), or atest.skipthere.- Asserts:
eq(actual, expected, label?)(language equality, so1 == 1.0),ok(cond, label?),err(fn, phrase?),fail(msg). They throw{ kind: "assert", ... }errors - the standard error dialect. Failure messages quote strings (expected "a b", got "a b", newlines as\n).eq's error also carriesexpectedandactual, anddiff(a list of lines prefixed" ","- "expected,"+ "actual, fromstr.diff) when both values are lists, or both are strings and one has a newline. No diff paststr.diff's ceiling of 40,000 lines, both sides together; past 40 diff lines the rest is counted in a final... N more lines. - Failure report: under a case's
FAILline the runner printsat <file>:<line>(the innermost call site in the test file; none when nothing in the stack is in it, and none for a group'sN of M cases failedline), then the diff lines, each indented six spaces, then the case's captured output:output:and one| <line>per line, ending| ... N more bytespast 64 KiB. Underecko test(not a direct run) eachtest.casebody's stdout is captured per thread (print,print_no_newline,io.print,io.stdout()), so spawned tasks andpmapworkers print as they run; a case inside a case keeps its own; a passing or skipped case's output is dropped.ecko test --no-captureturns capture off. ecko test --filter TEXT(or--filter=TEXT) runs only thetest.cases whose name, or the name of an enclosingtest.group, contains TEXT (plain substring, case-sensitive). A non-matching case is not called, printed or counted; group bodies always run, and a group with no matching case prints no line. A file with no matching case prints nothing unless it fails outside every case. A run that matches no case printsno test case matches 'TEXT'on stderr and exits 1. An empty TEXT exits 2.test.skip(reason)ends the current case as skipped: it printsSKIP <name> - <reason>and is counted apart, not as a pass or a failure. It throws{ kind: "skip", message: reason }to unwind the case. A case that catches it and then finishes cleanly is still a skip; one that catches it and then fails is a failure. The reason must be a non-empty string, and calling it outside atest.case/test.groupbody is an error.ecko test [paths...]discovers anything undertests/and any*_test.ecko, both recursively (or runs the given files/dirs, a directory argument likewise recursively), skippingvendor/,target/,node_modules/and dot-directories. It prints per-case lines and aN file(s), M case(s): P passed, F failedsummary (with, S skippedwhen any case was skipped), and exits non-zero on any failure - a skip is not one. CI needs nothing else.- Mock mode is forced: the runner strips the API keys, the provider and the base URL, so
aicalls are deterministic, offline, and free - AI pipelines are unit-testable by construction. Each file runs in its own process (soos.pid()differs per file and module-level state, or a port a fake server bound, never reaches another file).--jobs N(-j N) runs up to N files at once, with each file's output buffered and printed in file order; the default is 1. Running a test file directly (ecko tests/x_test.ecko) also exits non-zero when cases failed.
Built-in Functions
- Collections:
len,push,pop,get,set,keys,values,range,filter,map,pmap,reduce,sort,sort_by,sort_with,reverse,first,last,take,drop,slice,unique,flatten,zip,enumerate,any,all,contains,sum,min,max,insert,remove,index_of,empty_map,group_by,frequencies,chunk,window,partition,find,count,merge sort/sort_byrequire the elements (or keys) to be mutually comparable and raise an error otherwise - mixed types ([1, "a"]), unorderable values (maps), or NaN - so the result is always deterministic.sort_with(list, fn(a, b) -> Int)sorts by a comparator returning a negative number, zero, or a positive one. Use it when the order cannot be expressed as a key - a comparison whose result depends on the operands' types, for instance. Stable, likesort_by. Only the sign is read, and a Float result is compared as a Float, sofn(a, b) a - bsorts Floats; a comparator that returns NaN is an error.setreplaces,insertsplices.set(list, i, v)returns the list with positionireplaced, and refuses an index past the end;insertputs a new element between two others and grows the list. On a map both set the key. Reaching forinsertwhen you meantsetgrows the collection silently, so the names are worth keeping straight.drop(list, n)is the complement oftake:take(n) + drop(n)rebuilds the input.slice(list, start, end)is the half-open range, with out-of-range bounds clamped rather than raised.- Strings:
split,join,trim,upper,lower,replace,escape_html,starts_with,ends_with,lines,chars(all UTF-8/char-correct) - Math:
abs,round,floor,ceil,pow,sqrt - Types:
int,float,string,bool,type_of,type_name,is_null,is_map,is_list,is_string,is_number,has(map, key) - JSON:
json_encode,json_decode - Embeddings:
embed(text),embed_all(texts),cosine(a, b)- text → vector and vector similarity (offline: deterministic mock vectors) - IDs:
import std.uuid;uuid.v4()(random) /uuid.v7()(time-ordered) - AI budgeting & sessions:
tokens(text),cost(in, out, in_per_1m, out_per_1m),retry(n, f),session(),model(provider, name)- see AI/LLM Primitives above - I/O:
print,print_no_newline,read_file,write_file.printtakes any number of arguments and writes them joined by one space, then a newline (print("total:", n)); with none it writes an empty line.print_no_newlinejoins the same way and writes no newline. - Errors:
error(msg),assert(cond, msg?).assertreturnsnullwhencondis truthy and otherwise raises kindassert. Called by its own name in a program or module that binds the nameassertnowhere (no parameter, local,fn, assignment,match/for/catchbinding, type variant or import of that name), a failure names the condition and the values it read, on both engines:assertion failed: x == 3 (x = 2). The error also carriescondition(the condition asecko fmtprints it) andvalues(a map from each name the condition reads to its value; a name that is not bound, or holds a function, is left out; each value in the message is cut at 80 characters and a secret shows as[secret]). Withmsg, the message ismsgand the fields are the same. On this pathmsgis evaluated only when the assertion fails, so amsgwith side effects does not run when it passes. Called any other way (a = assert; a(false), or anywhere in a program that binds the name) it is the plain builtin: both arguments are evaluated first, and a failure isassertion failed, ormsg, with no extra fields. - Shared state:
cell,cell_get,cell_set,cell_update(thread-safe) - Async:
await(join a task),cancel(cooperatively stop one);channel,send,recv,close(cross-task channels) - see Async tasks - FFI:
py("module.func", args...)- calls Python through a persistent worker process (state such as imports and seeds persists across calls; Python exceptions surface as catchable errors;printoutput goes to stderr). Calls are serialized through the single worker - parallelpy()calls queue (a worker pool is a future extension). The function name is evaluated by Python; treat it as trusted code and never build it from AI output. The worker does not inherit your environment. It receives only what Python needs to run -PATH,HOME, the locale andPYTHON*variables - so a snippet cannot readECKO_AI_API_KEYor any other credential the parent holds.ECKO_PY_ENV=NAME,OTHERforwards named variables on purpose. A call that does not answer withinECKO_PY_TIMEOUT_MS(default 30000) raises kindtimeoutand the worker is restarted, so one wedged call costs its own result rather than every laterpy()in the process. An argument nested more than 1000 levels deep is refused before the call with kindlimit(Python's decoder refuses that depth too). - Timing:
sleep(ms)- blocks the current task formsmilliseconds, a non-negative Int. Before 0.58 it took seconds; a Float is refused with the millisecond spelling (sleep(0.5)says to writesleep(500)), so old code fails loudly rather than waiting a thousandth as long. Cancellation (acancel(t)on its task, or an expiredwith_timeout) ends the sleep early. - Deadlines:
with_timeout(ms, f)- callsf()and returns its result, or throws{ kind: "timeout", message, ms }iffis still running aftermsmilliseconds (a non-negative Int; otherwise kindbug). Cooperative, on the task-cancellation machinery: the deadline is checked at every loop and call checkpoint, and every runtime-managed wait (sleep,recv,sendon a full channel,select,await, stream reads) ends promptly. A native call blocked outside the runtime (a socket read, a database query) completes first, then the timeout is raised;fnever keeps running after it. An error thrown byfpasses through unchanged. Deadlines nest, and an enclosing cancellation (a taskcancel, an outerwith_timeout, an HTTP request timeout) still arrives as a cancellation rather than atimeout.
Empty lists and absent values
Behavior on an empty list or a missing element follows one rule per kind of operation:
- Retrieval returns
nullwhen the element is absent.first([]),last([]),find([], p)andget(collection, missingKey)all yieldnull- the same "there is nothing here" answer an optional lookup gives. - Indexing is not retrieval, and is strict.
[][0]andxs[9]raiseindex 9 is out of bounds (len 3);m["nope"]raisesmap has no key 'nope'. Indexing asserts the element is there;getis the form that tolerates its absence. See Access is strict under Structured Data. - Reductions that need at least one element raise an error on empty.
min([])andmax([])error, because the minimum or maximum of nothing is undefined (andnullwould be indistinguishable frommin([null])). - Operations with an identity value return it and never error.
sum([])is0,filter/map/unique/sort/take/flatten([])are[],frequencies([])is{}, andindex_of([], x)is-1(its not-found sentinel).
Semantics Notes
- Integers are
i64with checked arithmetic - overflow is a runtime error, never a crash.1 == 1.0is true (numeric cross-type equality). - Strings are UTF-8;
len, indexing, and slicing count characters. and/orshort-circuit and return booleans.- Ranges behave exactly like the list of ints they span (capped at 10M elements), but are held lazily on both engines.
min/max/first/lastanswer from the bounds without touching the elements;takereads only the prefix it returns;sum/count/map/filter/reduce/forstream them. A range that is only iterated never allocates its elements. The laziness is unobservable - a range compares, prints, indexes, and destructures as its list, and any operation needing random access materializes it first. - Calling an
async fnspawns a concurrent task and returns immediately;awaitjoins it (see Async tasks).pmapand-> streamremain for data-parallel maps and background AI calls. - Parse errors report
lineandcolumn. - Field access after
.accepts keyword names (x.type,req.match,obj.for) - handy for JSON/API shapes whose keys collide with keywords. - Keyword names also work as map-literal keys and struct-pattern keys:
{ from: "a", type: "b" }constructs whatm.fromreads, andmatch m { { from: f, type: t } => ... }destructures it. In a pattern a keyword key needs the explicitkey: nameform (shorthand{ from }would bind a name nothing could reference).
Resource limits
Adversarial or buggy input is meant to degrade to a catchable error, not a process crash or an unbounded hang - hard budgets, no surprises. The limits below are how.
The runtime's own code is held to the same rule by a count: docs/reference/panic-surface.txt records every unwrap, expect, panic!, unreachable!, unchecked index or string slice, integer division or remainder, and narrowing cast in the shipped binary that is not annotated with the reason it cannot fire, and CI fails if it rises. Since 0.73.0 every one of those counts is zero, and a program's bytecode is checked before it runs, so the VM's own reads do not depend on the compiler having been right. What the count does not measure is the remaining gap, in three classes:
- Faults reported as a bug in Ecko. A Rust
assert!that fires, or a panic inside a dependency, stops the program with exit 70 and the message that it is a fault in Ecko. Insidehttp.serveit is a 500 for that request, and the worker keeps serving. - Aborts with no report. The allocator's own failure (a request the limits below do not bound) ends the process on a signal; nothing can catch it, and it never reaches the exit-70 report. A native stack overflow would too, so every thread that runs Ecko code knows where its stack ends, and the places the runtime recurses natively (a callback, an AST-tier call,
fmt.inspect) refuse with a catchable error before reaching it - see Recursion depth below. What remains is native recursion that check does not cover. - Arithmetic inside the runtime. Release builds do not check Rust integer overflow, so a wrap in the implementation's own arithmetic is a wrong value, not a stop. This is not Ecko's
Int: overflow in a program's arithmetic is always an error at the line (see Numbers).
Until those are closed too, Ecko is not described as crash-free.
Every limit below is an ECKO_* environment setting, and every setting follows three rules (all of them read through one table, so none can differ): an invalid value - ECKO_LIMIT_DEPTH=lots - stops ecko before the program starts, exit 2, naming the variable; a safety ceiling may not be 0, since off would mean unbounded, while a timeout's 0 turns it off; and a name that is no longer read - the pre-0.58 spellings such as ECKO_MAX_DEPTH, dropped in 0.61 - prints which setting replaced it if it is still set. The full list is pubdocs/config/environment.md.
- Expression/block nesting is capped (
ECKO_LIMIT_PARSE_DEPTH, default 128): deeply nested input is a parse error rather than a parser stack overflow. The cap is on the tree's height, so chains count too: every operator ina + b + c, every stage inx |> f |> g, every call inm.a().b()and every arm of anelse ifchain nests one level. - Recursion depth is capped (
ECKO_LIMIT_DEPTH, default 2000): infinite or runaway recursion raises a catchablerecursion limit exceedederror instead of hanging or overflowing. Execution runs on a large-stack thread so the cap has real headroom; raiseECKO_LIMIT_DEPTHfor genuinely deep recursion. There is no tail-call optimization - this is deliberate: a bounded call stack is what makes runaway recursion a catchable error (not a silent hang) and keeps call stacks intact for error traces. So recursion is for depth that fits the cap; for deep iteration reach for a loop (for/while/loop) orreduce, which run in constant stack. The cap counts calls within one run of the VM, except a call to a small function that calls no other function, which the compiler may copy into its caller: that call is not a frame, so at the cap one more such call still runs. It cannot recurse, so a runaway recursion stops at the same call. Recursion through a callback - a function that passes itself tomap,filter,sort_byand so on - starts a fresh run per level, and a call to a function the AST tier runs (async,@tool, a string contract, or an@ensureson a typedaibody; a function whose contracts are all boolean is not one) recurses on the native stack, so both are bounded by that stack instead: near its end (16 MiB short of the 256 MiB every Ecko thread gets) the next level raises the same catchablerecursion limit exceedederror, kindbug, saying the native stack is nearly full. That is about 14,000 levels throughmapin a release build. RaisingECKO_LIMIT_DEPTHdoes not move it. (Through 0.73 this overflowed the stack and aborted the process.) - Data nesting is not capped, and does not need to be.
ECKO_LIMIT_PARSE_DEPTHbounds nesting in source; a value built at run time (x = [x]in a loop) may nest as deep as memory allows. Rendering (print, interpolation,string()) and comparison (==) walk it with an explicit stack rather than by recursing, so neither has a depth limit and neither elides anything. They recursed once, and printing a 150,000-deep list died with a stack overflow - which is not a catchable error but a process abort. Releasing a value is bounded the same way: lists, maps, structs, cells, secrets and closures free their contents with an explicit queue once nesting passes a fixed depth, so a chain tens of millions of levels deep is freed without growing the stack. (It used to abort at about 8,000,000 levels of lists.) A chain that runs through tasks, channels, or functions the AST tier runs still releases a level at a time. - Loop steps are optionally capped (
ECKO_LIMIT_STEPS, default unlimited): set it to bound runaway loops when running untrusted code. - Values built from a count are capped (
ECKO_LIMIT_ALLOC, default 256 MiB): a string from*,repeator the pad family, bytes fromrandom.bytesorio.read_exact. A count past the cap raises an error naming it; without the cap a count the allocator cannot satisfy is an abort, not an error. The same cap bounds one piece read from a stream: aread_untilor a line whose delimiter never arrives stops there with the tail still readable, andfs.readon a whole file and a buffered HTTP body are refused with an error naming the streaming form. Turning a range into a list is capped separately at 10,000,000 elements (see Ranges), and decompression (zlib.gunzip,zlib.inflate,std.archive) stops atECKO_LIMIT_UNPACKED(default 1 GiB). - AI/concurrency budgets (
ECKO_AI_MAX_CALLS,ECKO_LIMIT_TASKS,ECKO_LIMIT_PARALLEL, tool/HTTP timeouts) cap the outward-facing surface. - Web server: request bodies are size-capped (
ECKO_HTTP_MAX_BODY, default 10 MiB); a response header with a CR, LF or other control character is refused as a logged 500 (no response splitting); 5xx bodies are generic (internal errors are logged, not sent to the client);http.serve(port, handler, host: "127.0.0.1")binds locally (default is all interfaces, printed at startup); WebSocket upgrades are capped (ECKO_HTTP_MAX_WS_CONNS). py()is a trusted-code escape hatch, capability-gated behindexec: the function name must be a dotted identifier path (no eval), and arguments pass as JSON values, never as code. Note that granting a packageexecimplies network reach - a spawned process orpy()call can open sockets - soexecwithoutnetis not a network sandbox; grant it only to packages you'd trust with both.
Running a program (ecko, ecko -e, ecko -)
ecko file.ecko [args...] (or ecko run file.ecko) runs a file; ecko -e '<code>' [args...] runs the code given on the command line, and ecko - [args...] reads the program from stdin. All three apply the ecko.json beside the program (the working directory's, for -e and -), run the pre-run check and refuse to start on an error-level finding, and exit 1 on an uncaught error. Everything after the file, the code or - is the program's argv (os.args()). Diagnostics name inline code -e and stdin <stdin>; imports resolve from the working directory.
Static analysis (ecko check)
Deterministic, offline checks over the parsed program (also pushed as LSP diagnostics). ecko check and ecko fmt take files or directories; a directory means every .ecko file under it, skipping vendor/, target/, node_modules/ and dot-directories. ecko fmt --stdin formats a buffer from stdin to stdout, for editors. A file that does not parse is reported with every syntax error in it, in source order, up to 25: the parser records a failing statement, skips to where the next can begin (the first newline after the failure with every bracket opened since the statement began closed again, and followed by a line no deeper than the statement's own column), and keeps going, at the top level and inside each block. The first error is always the one a run or ecko fmt stops at. A statement that fails on the line straight after another failed one in the same block is not reported, since a lost bracket or comma breaks the lines after it too; a blank line, or a statement that parses through to its end, ends the run. A ), ], else, catch or finally that starts a line left of its block's statements ends the block, as the } it lost would have. The same list backs the LSP's diagnostics and the rendering when a file is run. The analyses below need a program that parses. Two severities:
- Errors - definite will-crash bugs: undefined names (with did-you-mean, transposition-aware), arity mismatches on known functions (builtins included, too few as well as too many, each builtin's minimum and maximum read from its registration; a piped value counts as the first argument), an inline
fn(...)passed to a function that calls it with a fixed number of values it cannot take (map,reduce,sort_with,retry,sql.transaction,csv.eachand the like), a field read off an immutable binding holding a known struct that the struct does not have, a member astdmodule does not export (checked whether or not the file's location is known, so it gates a run too), named arguments a function does not declare (unknown-named-argument, with did-you-mean against the declared parameters - the runtime refuses the call, so the program cannot run; for astdnative, an option it does not declare), an options map passed positionally to a native that takes its options by name (positional-options), a literal argument or default that cannot satisfy a typed parameter (param-type-mismatch) or a literal return that cannot satisfy a declared return type (return-type-mismatch), amatchover a declared type that misses a variant and has no_(non-exhaustive-match, since 0.63 - before that a warning, so the gap surfaced only when the missing variant arrived at run time), top-level use-before-definition (straight-line code reading a binding its own program has not created yet), and reassigning - or writing through a path of - a binding that was not declaredmut(immutable-reassign, with a fix that adds themut), and a probable misspelling that declared a new name instead of reassigning (likely-typo): inside a block, a bare assignment that introduces a name never read afterwards, when amutbinding in scope is one slip away from it -totl = total + nin a loop leavestotalunchanged and the program prints a wrong answer. A name that is read, starts with_, or is near nomutis an ordinary local. A literal that is certainly not a function, passed where a callback builtin needs one (callback-type-mismatch), is an error.ecko checkand the pre-run gate also analyze every local.eckofile the entry imports (vendored code excepted), reporting each finding under its own path. Running a file checks these first:ecko app.eckorefuses to start a program that cannot work, before its first side effect. - Manifest errors (
ecko check <file>): theecko.jsongoverning the checked files is validated too - an unknown capability (including one in a dependency'sgrant), an invalidmodulepath, aneckoversion that is not a version, a missing or escapingentrypoint, a dependency key that is not a legal identifier and so can never be imported, and a dependency value that does not resolve topath@version. The manifest is found by walking up from the file, the same wayimportfinds it, so checkingapp/main.eckovalidates the project root's manifest. Only when the file is acting as a manifest.ecko.jsoncarries two jobs - the package manifest, and the project defaults whose every other top-level key becomes astd.defaultsmember - and a defaults-only file has noentrypointand is perfectly valid. A file declaring none ofmodule,entrypoint,dependencies,capabilitiesorexportsis left alone. - Cross-file errors (
ecko check <file>, which knows the file's path): imports that don't resolve (unresolved-import- a missing"./module", an unvendored package, or an unknownstd.*), calls to a member the imported module doesn't export (unknown-member, with did-you-mean - or, for a std member a release removed, the replacement to use), and arity mismatches on functions from an imported user module. These need the file location, so they surface throughecko check, not the file-local pre-run gate. Too many arguments to astd.*native (math.gcd(12, 18, "x")) is anarity-mismatchtoo, counted exactly as the run time counts it, optional trailing arguments included; that one needs no file location, so it also stops a run before the first line. - Warnings - hygiene, shown by
ecko checkand the LSP but never blocking a run: scope-aware unused variables/parameters/functions/imports (_-prefixed names are exempt; a file of pure definitions is treated as an importable module and its top-level surface is not flagged), a local shadowing a builtin the file actually calls, writes that reach a top-level binding from inside a function, unreachable code, unwrapped credentials -os.env("STRIPE_KEY")-shaped reads must flow throughsecret(...), except where the read is only tested for presence (!= null,== "",is_null(...)), which never touches the value - andregex-interpolation: astd.repattern written as a plain string, where{2}is an interpolation hole rather than a quantifier, so the engine receives a pattern nobody wrote. Only an integer hole is flagged, since"^{prefix}"is a legitimate dynamic pattern and a rule that fired on it would be turned off.exact-division: a/inside the branch ana % b == 0guard selects (or theelseofa % b != 0), dividing the sameaby the sameb- a plain name, and a name or non-zero integer literal - with neither rebound in between. The guard proves the quotient whole, so/changes only its type, to a Float, and//keeps the Int; outside such a guard a/may be meant to give a fraction and is not judged. Lambdas and nestedfns in the branch are not entered, since they may run after the names have moved.float-bound: a/as a range bound (a..b), a slice bound, or a count passed torange,take,droporslice- directly or under further arithmetic (n / 2 + 1), but not inside a call (round(n / 2))./never returns an Int, so the line fails whenever it runs. An index is not checked, since a map takes a Float key, and a call is skipped when the file binds the builtin's name itself. (0.58 and 0.59.0 also warnedunit-changedat every call to an API whose unit moved from seconds to milliseconds; 0.59.1 retired it.ecko fix --migrate --only=msstill converts code written for seconds.)non-bool-condition: anif,unlessorwhilecondition that is evidently not a Bool - see Conditions.deprecated-moduleanddeprecated-member(0.59): an import of, or a call to, a std module or member on its way out, naming the replacement - the package and itsecko getline, or the function that now does the job. One table holds them, so the warning and the eventual removal error say the same thing. - Error-kind warnings - for a
trywhosecatch (e)dispatches withmatch get(e, "kind")ormatch e.kind, the analyzer infers which kinds thetrybody can throw (see Checked error kinds) and reportsunhandled-error-kindfor a kind the body can throw that has no arm and no_arm, andunreachable-error-kindfor an arm naming a kind nothing in the body throws - which also catches a misspelt kind, with a did-you-mean.unknown-error-kindstill fires on its own for a near miss of a standard-library kind, and an arm it reported is not reported twice.
Exit codes
ecko check exits 1 on errors, 0 on warnings. Warnings are still printed, and a run that ends with warnings says so, so a green exit beside printed output does not read as a missed finding.
ecko check src/*.ecko # errors fail; warnings inform
ecko check --strict src/*.ecko # any finding fails
Warnings do not gate because some can be deliberate, and there is no suppression mechanism, so treating one as fatal turns a judgment call into a build failure. Use --strict in a project that controls its own source and wants a clean board; leave it off where a warning is a considered choice.
shadows-builtin used to be the standing example: a cache exporting get/set or a heap exporting push tripped it, and four shipped packages became unreleasable on an analyzer change alone. It no longer fires there. An exported function taking a builtin's name is a module's public API declaring itself, not a name taken by accident, so the rule exempts it and fires only on a private shadow - the case it was written for. Of the 40 official packages, only heap trips it, for a private merge helper that really does shadow the builtin.
The native compiler report (--native)
ecko check --native also prints, for each function of each file it checks, whether the native compiler (ECKO_JIT_ENABLE=1) covers it and, if it does, which of its locals have a known type, which ones its loops compute with without one, and which kinds of op in it run on the bytecode VM instead, each with the line of its first use:
src/job.ecko: native compiler
<main>: compiled; on the VM: DefFn (line 3), Call (line 23)
spin: compiled; typed: total (Int), i (Int); untyped: n (line 5)
fib: compiled (calls itself)
rate: compiled (called from compiled code)
pick: compiled (called by value from compiled code)
helper: not compiled (has a default parameter)
label: not compiled (runs BuildString on the VM (line 30))
The compiler is opt-in: ECKO_JIT_ENABLE=1.
A function compiles when it contains a loop. A function without one compiles when it is a direct-call target that compiled code reaches: one with no defaulted parameter and no try (type annotations on its parameters and result are checked in machine code), and whose own code hands no op to the VM on the way through (a contract's failure path excepted; a call by name to a global, or a call through a value, counts as such an op even when it turns out to call a native), called with one argument per parameter from a compiled function, itself included. The report gives the reason for such a function: calls itself when its own code calls it directly, otherwise called from compiled code. A call through a global, a value or a parameter looks at what it calls each time it runs, as the VM does: it runs a native in place, enters a compiled function of the same program in machine code, and leaves anything else to the VM. A function or lambda that would qualify, captures no variables, and that such a call can find also compiles: one bound to a global that some call names (mut pick = fn(x) ... and pick(i)), or, when the program calls through a local or parameter anywhere, a lambda that is not stored in a global. The report gives it called by value from compiled code when nothing calls it directly, and the VM still runs its bytecode when it calls it itself. A function stored under another name, or in a list or a map, and called from there is not compiled for that call.
Every other function without a loop runs on the VM, called the ordinary way, and the report says why, naming the first of these that holds: has a default parameter, has a try, captures variables (a lambda a call through a value could otherwise enter), calls through a value (line N), runs <Op> on the VM (line N) (the first op its code hands to the VM on every call), or not called from compiled code (it qualifies, but only the VM calls it, or compiled code reaches it only under a second name or out of a list or map). A small function that the VM copies into its callers before anything compiles is also not called from compiled code: no call to it is left, and its body runs as part of each caller. The top level of a file without a loop is not compiled (no loop at the top level). A direct call stays in machine code; when the callee needs the VM partway (an error, a yielded op, the depth limit), the calls in progress become ordinary VM frames, so error call stacks and try are unchanged. A loop that would hand an op to the VM on every pass runs wholly on the VM unless it has at least 16 ops of machine code of its own, and the report then lists all its ops; a try in a loop body is such an op. A contract's CheckFail, run only once a call has failed, is never listed. typed lists the locals the compiler knows hold an Int (or a Float) wherever its loops reach them, which it keeps in machine registers without checking them; untyped lists, with a line, each local a loop does arithmetic or a comparison on without knowing its type, which is checked every time. A type comes from a literal start value (mut i = 0), from arithmetic on typed values, and from a parameter annotation (n: Int; Float parameters also accept an Int, so they do not count). A call to a function, or any other op the VM runs, forgets every type in the function at that point, so a loop that calls something in its body lists its counters as untyped. In a compiled function, an op the compiler has no machine code for is run by the VM and the function carries on as machine code after it. Which functions compile and which ops run on the VM is decided by the source alone, so the report holds for every run of the program. A function called from only one place may not appear: small functions are copied into their callers first. The flag changes only the output; the exit status is the ordinary check's.
Project scaffolding (ecko scaffold)
ecko scaffold <template> <path> writes a small, running program of a known shape, then prints the one command that starts it. Nothing in the language requires it: a .ecko file on its own is still a complete program.
ecko scaffold cli my-tool # a project from the `cli` template
ecko scaffold # list the templates (same as --list)
ecko scaffold --update # refetch the templates
| Flag | Effect |
|---|---|
--list | Print the templates and exit. A bare ecko scaffold does the same. |
--update | Refetch the templates and replace the cache, then scaffold if a template and path are given. |
--name <n> | Use n as the project name instead of the destination's. |
--force | Overwrite files that are already there. |
--ref <ref> | Take the templates from a branch or tag other than main. |
Templates are not built into the binary. They live in a separate public repo (ecko-lang/templates by default), described by a templates.json index, and the first ecko scaffold on a machine fetches and caches them. Every run after that is offline. This is the only command in the toolchain that needs the network to get started, and the trade is that templates can be fixed and added without an ecko release.
ECKO_TEMPLATES_REPO selects the source: an owner/repo, an archive URL, or a local directory, which is read straight through with no network and no cache. ECKO_TEMPLATES_DIR moves the cache, which otherwise sits under the platform cache directory.
Each template declares the oldest ecko it works on. A binary older than that refuses to scaffold it, naming both versions, and --list marks it rather than hiding it.
The project name comes from the last component of the destination path (or the current directory's name for .), reduced to [a-z][a-z0-9_-]*. It is substituted into the manifest and the README, and into the generated test's filename. It is never substituted into .ecko source, because { opens a string interpolation there and a substituted template would stop being a valid program.
Scaffolding refuses rather than overwrites. Every destination is computed and checked before anything is written, so a collision names the offending files and leaves the tree untouched; --force overwrites.
Profiling (ecko profile)
ecko profile <file> [args...] runs a program and reports, per function, how many times it was called and how long it took. Everything after the file is the program's, as with ecko run.
ecko profile app.ecko
ecko profile app.ecko --reset # --reset goes to the program
function calls self ms total ms
--------------------------------------------
normalise 60000 21.02 21.02
parse_row 20000 15.88 36.90
41.10 ms total, 4.20 ms outside any function
self is the time inside the function with its callees taken out, and the report is sorted by it; total is the function and everything it called. A small self beside a large total is a wrapper, and the time is further down. A recursive function's total counts each outermost call once, so no row is longer than the run. A function is listed under its own name whatever variable called it, and a lambda under the name it was bound to, or as <lambda at line N>.
The report goes to stderr, so the program's stdout is byte-identical to an unprofiled run and still pipes. The program's exit code is its own: one that fails still reports its numbers on the way out. A run that made ai calls gets a line for them, with the token count when the provider reported it (no estimated dollar figure since 0.59).
Counting is instrumented rather than sampled, so call counts are exact and a run gives the same ones every time. The cost is a clock read entering and leaving each function, which an ordinary run does not pay. Two things it does not break out: time in a builtin is charged to the function that called it, and code outside any function is the summary line's second figure rather than a row.
Migrating off deprecated syntax
Removed std modules and members (0.61)
Deprecated in 0.59 and removed in 0.61. Importing a removed module, or using a removed member, is an error - from ecko check before the program runs, and at run time where the check cannot see the call - that names the replacement:
| removed | use instead |
|---|---|
std.humanize | the humanize package, same functions: ecko get github.com/ecko-lang/humanize |
std.cli | the cli package (1.0), same parse and help: ecko get github.com/ecko-lang/cli |
std.debug | type_of(v), time.monotonic(), fmt.inspect(v) |
std.db, std.rag | the embed, cosine and ai builtins they were written over |
std.serial | nothing in the standard library |
std.term styling (44 functions) | the tui package's functions of the same names |
fmt.pad_left, pad_right, repeat, truncate | str.pad_start, str.pad_end, str.repeat, a slice s[..n] |
image.free | nothing - an image is a value; delete the call |
The setting names that changed in 0.58 (ECKO_API_KEY, ECKO_TRACE, ECKO_MAX_*, ...) were read under the old name through 0.60 and are not read in 0.61; one that is still set prints which name replaced it.
Deprecated syntax
Syntax that has been superseded goes through deprecate -> migrate -> remove. Nothing breaks under you at a minor version: the old form keeps parsing and running, ecko check warns (deprecated-syntax) with the replacement, and two commands rewrite it for you.
ecko fix --migrate --list # what can be migrated, and what runs by default
ecko fix --migrate --check src/ # report, write nothing (exit 2 if any file needs it)
ecko fix --migrate src/ # rewrite in place
ecko fix --migrate --only=const src/ # just one
ecko fmt canonicalises the same forms as part of formatting. Use it if the project is already formatted; use ecko fix --migrate if it is not, because it touches only the deprecated constructs and leaves the rest of the file alone - the difference between a reviewable diff and a whole-file reflow.
Currently migrated: const -> let, |params| body -> fn(params) body, Option<T> -> T?, and the bare vote count ai[T] 5 "..." -> ai[T] "..." votes 5.
One-time codemods are opt-in. --only=exports, --only=bytes and --only=strplus (wraps the non-string side of a + whose other side is visibly a string in string(...), for the release where + stopped converting to string), --only=mut (adds mut where a program reassigns a binding, for the release where a bare x = v became immutable) and --only=ms (seconds to milliseconds for sleep, time.monotonic, debug.elapsed, humanize.duration and http timeout:, for 0.58) belong to specific past breaking releases and are not in the default set. A deprecation rewrite is a canonicalisation, so canonical source is a fixed point and repeated runs are safe. A codemod is a reinterpretation: it cannot tell already-migrated code from code that never needed it, so running it twice changes the meaning of correct code.
Removal. Each deprecated form is accepted until the next major version. After that, the old form is a parse error naming its replacement and the migrator. A test fails the build if Ecko reaches that major with the old forms still accepted, so the removal cannot be forgotten.