The KScript language
Introduction
This is the reference for KScript 2 scripts: the core language every script and page has, the packages you import for the rest, and a few tips for scripts that run on every OS. If you’re new to KScript, Getting started is a gentler first read.
Variables and output
$count = 0 // declare
$people = [{ name: 'Joan', age: 82 }]
$count = $count + 1 // change it
$count += 1
$total = $price * $qty
const $limit = 10
$n: int = $args[0] // convert, or stop with a clear error
echo "Hello, {$name}! You have { $count } new { $count == 1 ? 'message' : 'messages' }."
echo "{ $person.name } is { $person.age }"
echo "{ $people }" // a map or list of maps prints as indented JSON
A map, or a list of maps, on its own in echo prints as indented JSON, coloured in a terminal (unless NO_COLOR is set). Inside text it stays on one line. echo(format: json) reformats JSON text, and ->convert(to: json) gives compact JSON.
Variables belong to the block they are declared in. {{ and }} are literal braces.
"Double quotes" interpolate expressions in { } after echo, in assignments, in return values, and in call arguments. In .kscript, KS6019 catches bare references and offers to wrap them in braces. 'Single quotes' keep text exactly as written, so text with nothing to fill in goes in them (KS6020 suggests the change). Quoted text after echo is printed as written too, with its spaces: echo " - { $item }" prints the two spaces. In XML, the text between <echo> and </echo> is trimmed and loses the indentation its lines share, and the values filled into it are left alone, except that an empty value leaves no stray space behind and the text never ends in a line break.
$greeting = "Hello { $name }, you have { $count * 2 } points."
$label = 'Write $name to use a variable.' // kept as written
$boxes = "{ 2 * 3 } boxes, { [1, 2]->count() } lists" // a { } always holds an expression
$route = '/users/{id}' // text with braces of its own goes in single quotes
A { } in double quotes always holds an expression, whatever it opens with: a variable, a command, a type ({ Order->count() }), a number or a bracketed sum. Text with braces of its own, such as a route ('/users/{id}'), a pattern ('\d{3}'), CSS or translation text ('Hello {name}'), goes in single quotes, or doubles them: "/users/{{id}}". The text given to @sql is the one exception: its { } are sent as parameters, never pasted in (see Data).
Expressions
+ - * / % **, == != (loose: '3' == 3), === !== (strict), < <= > >=, and or not, ??, ?., a ? b : c, in, list [1, 2] and map { name: 'Joan' } literals, $p.name, $list[0] (negative indexes count from the end), ranges 0..10 and 0..100 step 5 (end excluded, also with a step such as 0.1) and 1..=10 (end included), match $x { 1 => 'one', _ => 'other' }, ->method(), |> and fn(x) => …. Write and and or to combine conditions. Prefix ! has the same precedence and truthiness as not, so !$ready, ! $ready and not $ready are equivalent. Use it on a field (!$user.active), a whole condition (if !($ready and $open) { … }), or an interpolation ("{ ! null->is_null() }"). The spelling null->!is_null() negates the method result before the next link in the chain. XML has a word for each comparison as well (lt le gt ge eq ne), for use inside quoted attributes, since XML can’t hold a raw < there; the shorthand start tags accept < and > as written. In a .kscript file the words are reported (KS6012) and kscript check --fix writes the symbols.
When comparing a number with a string using <, <=, > or >=, KScript compares numerically if the string can be parsed as a number. If parsing fails, the comparison returns false. Comparisons chain as in maths, which the Maths section shows. Two dates are equal with == only when they are the same moment, seconds included.
Maths
Everyday maths has its own symbol, and each works the same in a script, in a template and in a database query. + adds, - subtracts, * multiplies and / divides, keeping any fraction. ~/ divides into whole numbers, rounding down. % gives the remainder, which keeps the sign of the number on the left, %% wraps round like a clock, and ** raises to a power:
$minutes = 135
$hours = $minutes / 60 // 2.25 because / keeps the fraction
$whole = $minutes ~/ 60 // 2 because 60 fits into 135 twice
$left = $minutes % 60 // 15 because 135 - 2 * 60 leaves 15
$behind = -7 % 3 // -1 because % keeps the sign of -7
$area = 4 ** 2 // 16 because 4 * 4 is 16
$kilobyte = 2 ** 10 // 1024 because ten 2s are multiplied
Operators bind in this order, tightest first, so 2 + 3 * 4 is 14 because * binds before +:
| Level | Operators | Grouping |
|---|---|---|
| 1 | . -> ?. ( ) [ ] |
left to right |
| 2 | ** |
right to left: 2 ** 3 ** 2 is 2 ** 9, 512 |
| 3 | -x +x |
-2 ** 2 is -4 because ** binds first, so write -(2 ** 2) or (-2) ** 2 (KS6023) |
| 4 | * / ~/ % %% |
left to right |
| 5 | + - |
left to right |
| 6 | .. ..= step |
one range per expression |
| 7 | |> |
left to right |
| 8 | < <= > >= in |
a chain in one direction: 0 <= $n < 10 |
| 9 | == != === !== |
one per comparison: join more with and |
| 10 | not, and, or, ??, a ? b : c |
% and %% only differ when a sign is negative. The remainder keeps the sign of the left side, like C# and JavaScript. Mod takes the sign of the right side, so it wraps round: an hour before midnight is 23, not -1. Use %% for clocks, weekdays and positions in a list that wrap at the end:
$hour = 9 - 12 // -3 because 3 hours before 9
$late = $hour % 24 // -3 because % keeps the sign of -3
$clock = $hour %% 24 // 21 because %% wraps back round the clock
$days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
$today = 0 // 'mon' is at 0
$yesterday = $days[($today - 1) %% 7] // 'sun' because -1 wraps round to the last day
$spare = -15m %% 1h // 45m because durations wrap the same way
~/ rounds down, not toward zero, so it pairs with %%: ($a ~/ $b) * $b + $a %% $b is always $a. It works on durations and money too, and gives a plain number:
$balance = -7
$weeks = $balance ~/ 2 // -4 because it rounds down, not toward zero
$rest = $balance %% 2 // 1 because -4 * 2 + 1 is -7
$runtime = 2h10m
$episodes = $runtime ~/ 25m // 5 because five 25m episodes fit into 2h10m
$spare = $runtime %% 25m // 5m because 2h10m - 5 * 25m leaves 5m
// starts a comment, so it can’t be whole-number division. $hours = $minutes // $per_hour leaves $minutes alone, and KS6022 points it out with a fix that writes ~/.
Comparisons that point the same way chain as they do in maths, so a range check reads the way it is said. Each value in the middle is worked out once, and the chain stops at the first comparison that is false:
$score = 42
$passed = 0 <= $score < 100 // true because 42 is from 0 up to (not including) 100
$top = 90 <= $score <= 100 // false because 42 is below 90
$falling = 10 > 7 >= 7 > 1 // true because each step goes down or stays the same
A chain goes one way. 1 < $n > 0 is an error because it says nothing about how 1 and 0 compare, so write 1 < $n and $n > 0. == and != don’t chain either: $a == $b == $c would compare true or false with $c, so write $a == $b and $b == $c. Brackets stop a chain, so (1 < $n) == true compares the result. A chain works in a database query too: Person->where(fn(person) => 18 <= $person.age < 65) asks for age >= 18 AND age < 65. ->between() is gone, and its error names the chain to write instead.
.. makes a range that stops before its end, which suits counting from 0 and positions in a list. ..= takes in the end as well, which suits counting from 1. Hovering either one shows where the range starts and stops:
$positions = 0..3 // [0, 1, 2] because .. stops before 3
$places = 1..=3 // [1, 2, 3] because ..= takes in 3
$quarters = 0..=1 step 0.25 // [0, 0.25, 0.5, 0.75, 1] because a step lands on 1
$odd = 1..=10 step 2 // [1, 3, 5, 7, 9] because no step lands on 10
$monday = '2026-11-30'->to_date()
$week = $monday..=$monday + 6d // seven dates because ..= takes in the Sunday
Like .., a range counts down when its end is below its start, so 3..=1 is [3, 2, 1] and 1..=0 is [1, 0]. To count up to a value that may be 0, as in 1..($count + 1), keep .., which gives no values when $count is 0.
^ isn’t power in KScript (in C# and JavaScript it is a bitwise operator), so 2 ^ 10 is an error whose fix writes 2 ** 10.
Bits are worked on with one method, ->bits(), rather than symbols, because & and | are so easily mistaken for and and or. It takes one step at a time, on whole numbers:
$read = 4
$write = 2
$permissions = 6 // read and write, because 4 + 2 is 6
$can_read = $permissions->bits(and: $read) == $read // true because 6 has the 4 bit
$with_run = $permissions->bits(or: 1) // 7 because or: adds the 1 bit
$toggled = $permissions->bits(xor: $write) // 4 because xor: flips the 2 bit off
$doubled = $permissions->bits(shift: 1) // 12 because each bit moves one place left
$halved = $permissions->bits(shift: -1) // 3 because a negative shift moves right
$flipped = $permissions->bits(invert) // -7 because every bit flips
&, a single |, << and >> between two values are errors that name the ->bits() call to write, and & and | offer a fix that writes and or or, which is usually what was meant.
($hour + 24) % 24 was the old way to wrap a number round. KS6021 suggests $hour %% 24, which also works for numbers below -24.
+=, -=, *=, /=, ~/=, %=, %%=, **= and ??= change a variable in place: $total += 5 is $total = $total + 5. Spaces around an operator are up to you, but a space inside one splits it: 2 * * 10 is an error that names **, and its quick fix removes the space.
The editor lists the variables after an operator and a space, those of the left side’s type first, and hovering an operator shows what it does.
Use expression as Type for a checked conversion, for example $text as int. The target can also be a declared record, enum or refinement type. Checked conversions
Control flow
if $n < 10 {
// …
} elif $n < 100 {
// …
} else {
// …
}
for p in $people {
// …
}
for i at n in 0..10 step 2 {
// …
}
for key, value in $map {
// …
}
while $queue->count() > 0 {
// …
break
// …
continue
// …
}
match $choice {
1 => echo "One"
2, 3 => {
// …
}
_ when $it > 9 => echo "Out of range"
_ => {
// …
}
}
Each arm of a match is pattern => result. The pattern is one value or several (2, 3 =>), or _ for anything, and a when test can follow it (_ when $it > 9 =>). The result is one statement on the same line, or a { } block of them. A match used as a value writes its arms the same way, with a value as each result: $label = match $choice { 1 => 'one', 2, 3 => 'a few', _ => 'many' }. Arms are separated by a new line or a comma, and the first arm that fits is taken. In XML the arms are <case is="2, 3">, <case when="…"> and <default>.
One-line if
When an if does a single thing, write it on one line: the condition, =>, then the statement. It reads like the arms of a match and like fn(name) => ..., and it keeps guard checks and early exits to one line each.
$basket = ['apple', 'plum', 'pear']
$budget = 3
// The guard is one line, so the main path stays at the left edge.
if $basket->is_empty() => exit
// 3 items and a budget of 3: the test is true, so the line prints.
if $basket->count() >= $budget => echo "The basket is full"
for fruit in $basket {
// 'plum' is skipped, because continue moves on to the next fruit.
if $fruit == 'plum' => continue
echo $fruit
}
// apple
// pear
elif and else take the same form, one branch per line:
$temperature = 18
// 18 is not below 5, but it is below 20, so 'Mild' is printed.
if $temperature < 5 => echo 'Cold'
elif $temperature < 20 => echo 'Mild'
else => echo 'Warm'
The statement after => can be anything that fits on a line: a call (if $continue => @method_call()), an assignment (if $count > 2 => $label = 'many'), echo, return, break, continue, throw or exit. It ends where the line ends, so if $ready => echo 1; echo 2 prints 2 either way. For more than one statement, or for a loop, a match or another if, use a { } block. The first => outside brackets ends the condition, so fn(fruit) => ... inside a call and @load() catch => false stay part of it. if $ready => { } is an error: a block follows the condition without an arrow. XML has no one-line form, so kscript convert writes <if> with the statement inside.
In XML, <if>, <elif>, <while> and <match> take their expression straight in the start tag: <if $user.is_logged_in> is short for <if test="$user.is_logged_in">, and <match $choice> for <match value="$choice">. Both forms work in scripts and pages; use the long one when the tag has other attributes. Inside the tag, <, > and quotes need no escaping, so <if $n > 3> and <if $name == "Joan"> work. A > ends the tag unless it has a space on both sides with more of the condition after it, so write $n > 3, not $n>3. kscript convert and the editor’s <if> snippet use the short form.
Shorthand tags make a .ks.xml file KScript markup rather than strict XML: KScript’s own parser, formatter and editor support read it, but generic XML tools such as xmllint will reject it. Stick to test="…" if a file has to stay valid XML.
Early returns instead of else
Inside a function or a loop, end a branch early instead of writing else: return in a function, continue or break in a loop (they act on a loop in the same function, never on the loop that called it). The main path then stays at the left edge and each special case is dealt with first.
fn grade(score: number) {
if $score >= 90 => return 'A'
if $score >= 75 => return 'B'
return 'C'
}
echo "{ @grade(82) }"
kscript check and the editor warn about else and elif with KS6001 there, and at the top of a script when every branch before already ends with return, break, continue, throw or exit. The quick fix removes the else (or turns elif into a separate if) and, when the chain is the last statement of the function or loop, adds the return or continue for you. Pages, <live> blocks and for…else (for an empty list) are not flagged, since there is nothing to return from. KS6001 comes from the default standard, kscript:recommended. To turn it off for a project, set "lint": { "rules": { "KS6001": "off" } } in kscript.json (or in a standard your projects share).
Unused code
kscript check and the editor also point out code that does nothing. In the editor it is drawn faded, with quick fixes to delete it or to rename it with a leading _, which marks it as unused on purpose (_ names are never reported).
| Code | What it flags |
|---|---|
| KS6002 | A function nothing calls. Calls from the other files of the project count: a library function another script imports and calls, a controller a route file names (to="people.show", or <Resource to="people"> for its index, store, show, update and destroy), and middleware named in kscript.json. A function that only calls itself is still unused. |
| KS6003 | A variable, constant or loop variable whose value is never read, including one that is only ever set. A script’s top-level constants are exported like its functions, so they count as used when an importing file uses them. In pages, only a function’s own variables are checked, because a layout or component may read the rest. |
| KS6004 | A function parameter the body never reads. For a lambda, only the parameters after the last one it reads, since the caller decides what it is passed: write fn(_y) => ... to keep the position. |
| KS6005 | An import nothing uses: an as alias, a name in names="...", a whole script, or a package none of whose elements, commands, methods or variables appear. |
| KS6006 | Not unused code, but a style hint: a list of names written as one string in a .kscript file (Middleware(use: "log, cors")). Write it as an array, use: [log, cors]; the quick fix does it for you. XML attributes are text, so use="log, cors" is fine there. |
| KS6008 | Not unused code either: a script in a project that declares a second type, model, enum or error type. Each goes in its own file, named after it, and is imported where it is used; the warning says where to move it (types/order-status.kscript). The type the file is named after stays. Scripts outside a project aren’t checked. |
The project is the folder with the nearest kscript.json and everything under it (hidden folders, bin, obj and node_modules are skipped). A script outside a project is checked against the other files in its own folder. A function that is part of an API used from outside the project can say so with @public in its doc comment:
/// Kept for scripts that still call it.
/// @public
fn titlecase(text: string) => $text->upper()
Like KS6001, these come from the default standard, kscript:recommended, as warnings (kscript:strict makes them errors). A project can change or turn off each one in kscript.json, such as "lint": { "rules": { "KS6004": "off" } }.
Functions
fn greet(who: string, greeting = 'Hello') {
return $greeting + ', ' + $who + '!'
}
fn square(n: number) => $n * $n
echo "{ @greet('World') } { 4 |> @square() }"
@greet('Kyle')
spawn(fn: @background_job)
Functions can be called before they are declared, recurse, and be passed around: @square is the function itself. Lambdas are values too, and declare their parameters the same bare way: $by_age = fn(a, b) => $a.age - $b.age.
A short function reads a field or calls a method on each item. It starts with . or ->, which stands for the item, and works anywhere a function goes:
$urgent = $orders->sort(by: .priority)->filter(.paid)
$by_shop = $orders->group_by(.shop.name)
$lines = $lines->map(->trim()->upper())
.priority is fn(order) => $order.priority, and ->trim() is fn(line) => $line->trim(). A short function is one chain of fields and method calls. For anything more, such as $order.price > 10, write fn(order) => ….
Block functions
When a function needs more than one expression, give it a block instead of =>. The block holds statements, just like the body of fn name() { }, and return gives the function’s result:
$prices = [3, 7, 12]
$with_tax = $prices->map(fn(price) {
$taxed = $price * 1.5 // 4.5 for the first price, because 3 * 1.5 is 4.5
return $taxed->round() // 5, because 4.5 rounds up
})
// $with_tax is [5, 11, 18]: the block ran once for each price
The parameters get their types from the call, as they do in fn(price) => …: $price is a number here because $prices is a list of numbers, so the editor suggests number methods after $price-> and shows with_tax: number[].
A block can decide with if and leave early with return:
$scores = [42, 97, 61, 88]
$passed = $scores->filter(fn(score) {
if $score < 60 {
return false // 42 is dropped here, because it is under 60
}
return $score % 2 == 0 // 97 and 61 are dropped, because they are odd
})
// $passed is [88]
Functions that take two parameters, such as ->reduce(fn(total, item), initial?), take a block in the same way:
$basket = [{ name: 'apple', cost: 2 }, { name: 'melon', cost: 5 }]
$total = $basket->reduce(fn(sum, item) {
return $sum + $item.cost // 2 after the apple, then 7, because the melon adds 5
}, 0)
// $total is 7
A block that ends without return gives null, which suits ->each(), where only what the block does matters. Everywhere else the call uses what the block gives, so a block that is empty or never returns a value is an error, in the editor, in kscript check and when it runs:
$words = ['fig', 'kiwi']
$longest = $words->common(1, by: fn(word) {
})
// Error: This fn block is empty, so it gives null each time it is called, and 'by' uses what it gives.
The block can read and change the variables around it, and the variables it makes stay inside it:
$seen = 0
['x', 'y', 'z']->each(fn(letter) {
$seen = $seen + 1 // the outer $seen goes up, because the block changes the variable around it
$shout = $letter->upper() // $shout exists only inside the block
echo $shout // X, then Y, then Z, because the block runs once per letter
})
// $seen is 3
A block function is a value like any other function, so it can be kept in a variable and called: $greet = fn(name) { … }, then $greet('Ada'). Block functions work in .kscript files. An XML attribute can’t hold statements, so there you write fn(n) => value, or declare a <fn> and pass it as @name. A database query’s condition (->where(fn(u) => $u.age >= 18)) is turned into SQL, so it must stay a single expression.
A parameter declared as any accepts any value. A method call on it uses the value’s actual type. For example, $key->trim() trims a string, raises an error for a number, and calls the type’s own trim() when one exists. Write fn trim_key(key: string) => $key->trim() for a string normalizer. The editor can then infer a string return type.
Named arguments
Any call can name its arguments, in any order: built-in commands, methods, your own fn functions and lambdas.
echo "{ @known_folder(name: 'downloads') }"
echo "{ @greet(greeting: 'Hi', who: 'Kyle') }"
echo "{ @range(1, step: 2, end: 10) }"
echo "{ 'abc'->pad(char: '*', width: 6, start) }"
echo "{ @join_path(base: $folder, ['archive', $name]) }"
Positional arguments fill parameters in order, and each name: value fills the parameter of that name, so you can skip optional ones in between. A positional argument written after named ones fills the first parameter still empty, which is how @join_path(base: $folder, [...]) reads. Naming a parameter that doesn’t exist, or giving one twice, is an error with a “did you mean” hint. The editor completes parameter names after ( or ,.
One of a group
Some parameters are alternatives: a call passes exactly one of them. Join their names with |:
fn file(note_id: int, add|remove: string, notify: bool = true) {
$change = $add != null ? "Added { $add }" : "Removed { $remove }"
$told = $notify ? ', and told its owner' : ''
return "{ $change } on note { $note_id }{ $told }"
}
echo @file(4, add: 'plan.png')
echo @file(4, remove: 'old.png', not notify)
@file(4, add: $a, remove: $b) is an error (“@file() takes add: or remove:, not both”), and so is @file(4) (“needs add: or remove:”). kscript check reports both before the code runs. The members of a group are always named, and the ones a call doesn’t pass are null in the body. Passing null (or false) for one counts as not passing it.
| Written | Means |
|---|---|
add|remove: file |
Exactly one of add and remove, both files. |
at|after?: date |
At most one: the ? after the last name lets a call pass neither. |
text: string | template: Template |
Exactly one, each with its own type. |
(text: string | template: Template)? |
The same in brackets, with ? for at most one. |
A group whose members have different types needs brackets when other parameters sit beside it, so it’s clear where the group ends: fn send(to: email, (text: string | template: Template), at|after?: date). Brackets are allowed around any group. A member can’t have a default of its own.
Built-in commands use groups too. @api() takes one of post:, put:, patch: and delete:, and a job’s ->dispatch() takes delay: or at:, not both. Signature help shows a group as one slot, completion stops offering the other members once one is written, and the editor gives a group’s names one colour.
Flags
A true/false parameter can be written as a bare word: recursive sets it to true and not recursive to false, so calls read like a sentence.
$all = @files($folder, pattern: '*.txt', recursive)
echo "{ $data->convert(to: json, indented) }"
fn save(path: string, overwrite: bool = false) {
// …
}
@save('out.txt', overwrite)
Writing overwrite: true or recursive: false works too, but the editor suggests the flag instead (KS6024), with a fix that rewrites it as overwrite or not recursive.
Argument types
Each argument must be a value its parameter takes. One rule decides this, and the editor, kscript check and the run all apply it, so they report the same mistake in the same words before anything runs:
$rolls = [4, 6, 6, 2]
$rolls->common(1, least) // [2]: least on its own is true
$rolls->common(1, not least) // [6]: not least is false
$rolls->common(1, least: 'yes') // [2]: text that reads as true or false is converted
$rolls->common('1') // [6]: text that reads as a number is converted
$rolls->common(1, least: {})
// Error: The 'least' argument needs true or false, but this is a map. It is a flag: write least on its own for true, or not least for false.
$rolls->common(fn() => 2)
// Error: The 'count' argument needs a number, but this is a function.
$rolls->common(1, by: 3)
// Error: The 'by' argument needs a function, but this is a number.
['fig']->union('fig')
// Error: The 'other' argument needs a list, but 'fig' is text.
| The parameter takes | It also takes | It never takes |
|---|---|---|
text (string) |
a number or true/false, written as text | a list, a map or a function |
a number (number, int, float) |
text that reads as a number, such as '3' |
other text, true/false, a list, a map or a function |
true or false (bool) |
text that reads as true or false, such as 'yes' |
a number, a list, a map or a function |
| a list, a map or a function | anything else |
A { } is always a map, even when it is written over two lines after an argument’s name, so least: { and } on the next line is a map, not a block. The editor offers to replace least: { } with least.
Trailing commas
A comma goes between items. After the last item, a comma is allowed only when the list is written one item per line, so adding an item changes one line. Before the closing bracket on the same line it is an error, in every kind of list:
$label = fn(name,) => $name // Error: Nothing follows this comma.
$sizes = [1, 2,] // Error, and the same for { size: 1, } and ->take(2,)
$sizes = [
1,
2, // fine: the list is written one per line
]
Enums and consts
enum declares a set of named values, and const a value that can’t change.
enum Size { small, medium, large }
const $max_items = 10
fn pack(size: Size, gift: bool = false) => 'Packing ' + $size
echo "{ @pack(.large) } { @pack(size: .small, gift) } { Size.medium }"
A long enum can hold one value per line, with no commas, the way a type holds one field per line. kscript fmt puts an enum that fits in the line width on one line, and a longer one one value per line:
enum Topping {
mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos
}
Where the type is known, write an enum’s value with a leading dot: .large is Size.large, because size is a Size (see A leading dot below). Where nothing says the type, write it in full: Size.medium. A list of an enum takes an array of them: with fn pack_all(sizes: Size[]), write @pack_all([.large, .small]). Built-in commands have word parameters too, and those words are written bare, without the dot: @known_folder(downloads) takes home, desktop, documents, downloads, music, pictures, videos, appdata or temp. Size itself is a map from each name to itself, so 'large' in Size checks a value. Top-level <const> and <enum> declarations are exported to scripts that import the file.
A leading dot: .name
A name that starts with a dot is a member of whatever the place it is written expects. It saves writing the type’s name when the code around it already says it:
enum NoteColor { yellow, pink, blue, red }
type Note {
text: string
color: NoteColor = .yellow
fn label() => .text->upper()
fn urgent() => .color == .red
fn kind(): string => match .color {
.red => 'Urgent'
_ => 'Normal'
}
}
fn paint(color: NoteColor): string => "painted { $color }"
$note = Note(text: 'milk', color: .pink)
echo "{ $note->label() } { $note->kind() } { $note->urgent() } { @paint(color: .blue) }"
$people = [{ name: 'Ann', age: 31 }, { name: 'Bo', age: 25 }]
echo $people->sort(by: .age)->map(.name)
What the dot means is read in this order:
- A typed slot. An argument, a field’s default, a comparison, a match arm, a list item or a typed
fn’s return that takes an enum:.pinkis that enum’s value. A slot that takes a function, as->map(.name)does, reads that field of each item. - The item, inside a
forloop. Infor account in $accounts { ... },.idis$account.idand.name = 'Ann'sets the item’s field. In nested loops the innermost item that has the name wins, so the inner loop’s.labeland the outer loop’s.idcan sit side by side. Awhileloop has no item, so it adds nothing. - The record, inside its own methods. In a
type,model,extendor component method,.textis the record’s own field and.save()calls its own method..count += 1and.color = .redset its fields. - None of these.
$c = .redis an error,.red needs a type here, and the quick fix writes it in full:NoteColor.red.
The slot is tried first. Inside a method, @paint(color: .red) is NoteColor.red even if the record has a field called red. A name the enum doesn’t have is the record’s own, so fn current(): NoteColor => .color returns the record’s color. A name neither has is an error.
A loop’s item comes before the record. In a method that loops over rows that have a title, .title is the row’s, and the record’s own is written $this.title; the checker says so and offers that fix.
type Tag {
label: string
}
type Row {
id: int
name: string
tags: Tag[] = []
}
$rows: Row[] = [Row(id: 1, name: 'Ann', tags: [Tag(label: 'new')])]
for row in $rows {
echo "{ .id } { .name->upper() }"
for tag in .tags {
echo "{ .id } { .label }"
}
}
Typing . where a value goes suggests exactly what fits: the enum’s values in a typed slot, the loop item’s fields (then the outer loops’ and the record’s) inside a loop, or the record’s fields and methods inside a method. Hovering a value shows what it stands for, such as NoteColor.pink.
Typed data
type declares the shape of some data, such as an API response. Data that passes through it is checked and turned into a record: a map that knows its type, so the editor completes its fields and a typo like $repo.stras is caught. Fields can also be email, password, handle, uuid or regex, and types can add rules to other types or join them. See Types and validation.
A type is a block with one field per line, name: type:
type User {
login: string
id: int
}
type Repo {
name: string
stars: int from stargazers_count
owner: User
}
$repo = Repo({ name: 'kscript', stargazers_count: 12, owner: { login: 'kyle', id: 1 } })
echo "{ $repo.name } has { $repo.stars } stars, owned by { $repo.owner.login }"
stars: int from stargazers_count reads the field from a key with another name, and owner: User is another type, so the nested data is checked and turned into a User record too. Repo(data) maps a map, a list of maps or JSON text.
Use $.name to look up a value in the current scope. It resolves the same name as $name, including a function parameter, local variable or component field.
Method signatures
A type may declare a method without writing its body: end the fn line with ; where the => or { } would go. That line is a method signature, and another type that extends this one must implement it. A ? after the method’s name, as in fn details?(): string;, makes the method optional. The editor and these docs show signature lines in italics, so you can tell them from methods with a body at a glance. The checker reports any missing required method or mismatch in its parameter names, parameter types, or return type.
type Summary {
fn label(prefix: string): string;
fn details?(): string;
}
type NoteSummary extends Summary {
title: string
fn label(prefix: string): string => $prefix + .title
}
Field lines
A field line is name[?][: type] [from path] [= default | => value]. Each part is optional except the name. A field with a value and no type may write the value straight after the colon, layout: ```text ... ``` or symbols: { '#': '#' }, and takes its type from the value:
enum Visibility { public, private, internal }
/// A GitHub repository.
type Repo {
name: string
/// How many people starred it.
stars: int from stargazers_count
owner: User
owner_name: string from owner.login
topics: string[] = []
license?: string from license.name
visibility: Visibility
updated: date from updated_at
label => $name + ' (' + $stars + ' stars)'
}
| Part | What it does |
|---|---|
: type |
A built-in (string, int, float, number, bool, date, list, map, fn, any, email, password, handle, uuid, regex), an enum, another type, T[] for a list. Rules can follow in brackets: string(min: 1). Without it the field takes any value. |
? after the name |
The value can be missing or null. This is the one way to mark an optional field, in a type, a model, an error and a job: license?: string, not license: string? (KS6014, with a quick fix). T? is for a type that isn’t a field’s own, such as a parameter that may be null: fn show(repo: Repo?). |
from path |
Where to read the value when it isn’t the field’s name: stargazers_count, owner.login, items[0].name. Nested data comes out flat. Quote a path that has spaces. |
= default |
The value when the data has none. The field is then optional. |
=> value |
Works the field out from the other fields (they are $name, $stars and so on) instead of reading it. |
/// above the line |
Shown on hover and in completion. |
The type itself takes options in brackets: type Repo(extra: error) { … }. extra says what happens to keys the type doesn’t list: drop (the default), keep or error. path: "data/repo.json" takes the fields from a saved sample of the data: objects become nested types, and keys only some list items have become optional. Lines in the block replace the sampled fields they name. Types can refer to each other in any order and to themselves, and top-level types are exported to scripts that import the file. In a project, give each type its own file (types/repo.kscript, types/owner.kscript) and import the ones it uses: import "owner.kscript" at the top of types/repo.kscript (see One type per file).
A small type can also go on one line, with the fields written like fn parameters: type Point(fields: [x: int, y: int]). kscript convert writes it as a block.
In XML, a type is <type name="Repo"> with a <field name="stars" type="int" from="stargazers_count" /> element for each line, or a fields="..." attribute for the one-line form. Switch the examples to XML to see them.
Where data meets a type
$repo = @api($url, as: Repo) // KScript.Net: ->check()->convert(from: json, as: Repo)
$repos = @read_json(./repos.json, as: Repo) // KScript.IO; a list maps item by item
$user = $text->convert(from: json, as: User)
$user = User($data) // a map, a list or JSON text
$repo: Repo = $data // also on const and plain assignment
fn show(repo: Repo, tags: string[]) {
// …
}
as: takes a type: as: Repo, as: int, or as: Repo[] for a list of them, written as a declaration writes it. $repo->type() is 'Repo'. A record still works everywhere a map does, but reading or setting a field the type doesn’t have is an error, and setting a field converts the value to the field’s type.
->type() reports a list’s element type. [1, 2]->type() returns 'number[]', and a list of Repo records returns 'Repo[]'. Mixed lists and untyped empty lists return 'any[]'. Use ->is_a(list) to test whether a value is any kind of list.
When the data doesn’t fit, mapping fails with one Shape error that lists every problem with its JSON path:
The response from https://api.github.com/... doesn't fit Repo (2 problems):
$.stargazers_count: needs an int, but got the string 'lots'.
$.visibility: must be a Visibility (public, private, internal), but got the string 'secret'.
In a catch, $err.problems is a list of { path, field, message } maps. Repo->check($data) returns that list without throwing (empty when the data fits), Repo.fields lists the fields, and Repo->schema() describes the type as JSON Schema.
Types from types
A type can be made from another type, so a parameter or field follows the type it’s about instead of repeating it. When the type changes, everything made from it changes too, and the editor completes, links and checks the names.
| Form | What it is |
|---|---|
Post.fields |
One of Post’s field names, written bare: title. A model’s own fields (id, its keys) and relations count. |
Post.fields(except: [body]) |
Fewer names: except: drops some, only: keeps some, relations: false drops relations and relations: only keeps only them. |
Post.title |
The type of Post’s title field, with its rules. Post.title(max: 80) adds rules on top. |
Order.address.postcode |
A field of a field. Order.lines.item is one item of the list field lines. |
Self.fields, Self.title |
Inside a type or model, the type being declared. |
draft|live |
One of these words, written bare. |
int|uuid |
A value of either type. A word that names a type is the type; quote it to mean the word: card|'email'. |
(draft|live)[] |
Brackets group a union, here to make a list of it. |
type Post {
title: string(min: 3)
body: string
tags: string[]
sorted_by: Self.fields = 'title'
}
fn column(by: Post.fields(except: [tags])) => "sorted by { $by }"
fn retitle(title: Post.title) => "renamed to { $title }"
fn tag(tag: Post.tags.item) => "tagged { $tag }"
fn publish(post: Post, as: draft|live = 'live') => "{ $post.title } is { $as }"
fn find(id: int|uuid) => "found { $id }"
$post = Post({ title: 'Hello', body: '…', tags: [] })
echo "{ @column(by: body) }, { @retitle('Hello again') }, { @tag('news') }"
echo "{ @publish($post, as: draft) }, { @find(42) }, { $post.sorted_by }"
A value that doesn’t fit is reported the way any typed argument is, listing every name it could be:
'titel' isn't one of Post's fields. Use title, body, tags or sorted_by.
'drafty' isn't one of these words. Did you mean draft? Use draft or live.
The 'id' argument of @find() doesn't fit int|uuid: needs int or uuid, but got the string 'nope'.
Built-in options are typed the same way, and hover, signature help and the reference show each one’s type:
- A model’s
hidden:andguarded:takeSelf.fields[], andkey:takesSelf.fields.unique:andindex:take(Self.fields|Self.fields[])[], which is a name or a group of names. - A job’s
unique_by:takesSelf.fields[]. ModelUpdate’sfields:takesmodel.fields[], the fields of the model itsmodel:names.- A migration’s
Index(columns:)takes the fields of its table. - Methods name the receiver’s fields the same way:
$post->is_dirty(title)takesSelf.fields,->pick([title, views])and->omit([body])on a record takeSelf.fields[], and$posts->pluck(title)or->pluck([title, views])on a list of records takesSelf.fields|Self.fields[]. A name the receiver doesn’t have is an error with a suggestion. - Options with a few fixed words are word unions:
Document(template: plain|paper|report|letter|invoice),->sort(by:, order?: asc|desc), andResource(only:), which takes(index|store|show|update|destroy)[]. A word that is also a type’s name is quoted in the type, as inecho’sformat: text|'json'|'markdown', but you still write it bare:format: json.
A model field written status: draft|live is stored as a database enum column.
In a one-of group, a | before the colon separates the names and a | after it is a union: id|slug: int|uuid takes id: or slug:, either an int or a uuid. In a group whose members have different types, a | followed by name: starts the next member: (as: draft|live | template: Template).
Values and methods
Values are strings, numbers, bools, lists, maps, dates, functions and null, plus values packages add (files, HTTP responses). Every value has methods, called with -> and chained:
echo "{ $name->trim()->upper() }"
echo "{ $people->filter(fn(p) => $p.age >= 18)->map(.name)->join(', ') }"
echo "{ $people |> sort(by: .name) |> first() }"
echo "{ @now()->add(days: 7)->format(pattern: 'd MMMM yyyy') }"
Use pluck(key) to read a field from each item in order. Give pluck a list of keys to produce one new map per item. Keys can be bare names, quoted strings or variables.
$people = [{ name: 'Joan', age: 82 }, { name: 'Sam' }]
$names = $people->pluck(name) // ['Joan', 'Sam']
$cards = $people->pluck([name, age]) // [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }]
$labels = $people->pluck(['name']) // [{ name: 'Joan' }, { name: 'Sam' }]
A missing map key gives null. Typed records keep their usual field checks. An empty input list gives [], and pluck([]) gives one empty map per input item. Repeated keys appear once, in the requested order.
On a list, contains(value), index_of(value), remove(value) and count_of(value) compare with ==. For example, [1, '1']->count_of(1) gives 2. unique() uses strict equality (===), so [1, '1']->unique() keeps both items.
is_empty() means zero characters on a string, zero items on a list, or zero keys on a map. If you used $text->is_empty() to accept whitespace-only input, use $text->is_blank() to keep that behavior.
| Text | ->is_empty() |
->is_blank() |
|---|---|---|
'' |
true |
true |
' ' |
false |
true |
'hello' |
false |
false |
A number is always written in plain digits, never with an exponent: echo 10 ** 20 prints 100000000000000000000 and echo 0.1 ** 20 prints 0.00000000000000000001. Whole numbers are exact at any size: 123456789 * 987654321 is 121932631112635269, 2 ** 100 is 1267650600228229401496703205376, and a 20-digit id read from text or JSON keeps every digit. +, -, *, %, **, / (when it divides evenly), ->sum(), ->product(), @gcd, @lcm and @factorial all stay exact; a fraction, @sqrt and the like work in ordinary floating point. A fraction shows 15 significant digits, so 0.1 + 0.2 prints 0.3. A whole number can grow to about 30,000 digits before it stops with a Limit error.
On text, ->count() and positions (in ->slice(), ->index_of() and $text[0]) count most characters as one place and a character such as an emoji as two. No method cuts such a character in half: ->chars(), ->first(), ->last() and ->reverse() work with whole characters as a reader sees them, and ->slice() and ->truncate() move a cut that would fall inside one back to before it.
A plain fact about a value is a field, read with a dot and no brackets, the same way a map’s keys are:
import KScript.IO
$day = '2026-11-19'->to_date()
$file = @file(./notes.txt)
echo "{ $day.year } { $day.weekday } { $file.name } { $file.size }"
So $response.status, $file.size, $url.host and $e.status are fields, and anything that takes arguments or does work is a method: $response->convert(from: json), $file->read_text(), $day->format('yyyy'). A name that answers true or false starts with is_ or has_: $response.is_ok, $ip.is_private, $list->is_empty(), $map->has(key).
A length of time is a duration: a number and a unit with no quotes, such as 500ms, 30s, 10m, 2h, 1d or 1w, joined for more (1h30m). Everything that takes a length of time takes one: wait(500ms), @api($url, options: { timeout: 30s }), $cache->set(key, value, ttl: 10m). A plain number is always seconds.
Years and months are y and mo (m is minutes): 1y, 6mo, 5y10mo. A month or a year has no fixed length, so these move dates by the calendar ($date + 1mo keeps the day of the month where it can) and are refused where a fixed length is needed, such as wait(1mo) or 1mo.hours.
The editor completes the fields and methods for each type and shows what they do. To change a value’s format, such as reading JSON text or writing rows as CSV, use ->convert(): see Converting between formats.
Dates
A date’s calendar facts are fields: .year, .month, .day, .weekday, .quarter, .day_of_year, .week (the ISO week number) and .days_in_month. .is_past, .is_future, .is_today and .is_weekend compare it with now, so they suit templates:
$post = { title: 'Launch', published_at: '2030-01-01 09:00'->to_date() }
echo $post.published_at.is_future ? 'Coming soon' : $post.title
->start_of(unit) and ->end_of(unit) give the first and last moment of the day, week, month, quarter or year a date is in, which is what a report of “this month’s orders” needs. A week starts on the locale’s first day (Monday in en-GB, Sunday in en-US), or the one week_start: names:
$now = '2026-11-19 14:30'->to_date()
$from = $now->start_of(month) // 2026-11-01 00:00
$to = $now->end_of(month) // 2026-11-30 23:59:59
$monday = $now->start_of(week, week_start: monday) // 2026-11-16
Calendar arithmetic counts whole units. $date + 1y6mo moves a date by years and months, and so does ->add(), which takes any mix of years:, months:, weeks: and days: (->subtract() moves it back). A month keeps the day of the month where it can, so 31 January plus a month is the last day of February. For hours and minutes, add or take away a duration:
$due = '2026-11-30'->to_date()->add(months: 1, days: 2) // 2027-01-01
$last_week = @today()->subtract(weeks: 1)
$renewal = '2026-01-31'->to_date() + 1y1mo // 2027-02-28
$meeting = '2026-11-30 09:00'->to_date() + 1h30m // 10:30
A date moves only by a duration. $date + 1 is an error, because a plain number is seconds everywhere else, and so is adding a bool, a list or another date. Write the unit ($date + 3d). The one place a number stands for a date is a Unix timestamp, seconds since 1970, which ->to_date() reads and ->timestamp() gives back:
$created = 1795996800->to_date() // 2026-11-30 00:00 UTC
$seconds = $created->timestamp() // 1795996800
Subtracting one date from another gives the exact time between them as a duration. ->since(other, in: unit) counts whole days, weeks, months or years instead, the way a birthday does. ->is_same(other, unit) asks whether two dates share a day (the default), week, month, quarter or year:
$start = '2026-11-30 09:00'->to_date()
$took = '2026-11-30 10:30'->to_date() - $start // 1h30m
$born = '1990-12-01'->to_date()
$age = '2026-11-19'->to_date()->since($born, in: years) // 35
$same = @today()->is_same(@now(), day) // true
Now comes from the computer’s clock, so in tests @with_clock(date, fn) fixes it for @now(), @today(), the fields above and @format_relative().
Working with text
Text has helpers for the jobs that come up again and again: changing the case of a name, cutting at a separator, tidying spaces, and signing a payload.
echo 'Order Total'->case(snake) // order_total
echo 'order_total'->case(camel) // orderTotal
echo 'order total'->case(pascal) // OrderTotal
echo 'orderTotal'->case(kebab) // order-total
$email = 'joan@example.com'
echo "{ $email->before('@') } at { $email->after('@') }" // joan at example.com
echo 'archive.tar.gz'->after('.', last) // gz
echo ' too many spaces '->squish() // too many spaces
$words = 'Hello, world!'->words() // ['Hello', 'world']
echo '4242424242424242'->mask('*', keep_end: 4)
->before() and ->after() cut at the first separator, or the last with last, and give the whole text back when the separator isn’t there. ->wrap(width: 60) breaks text between words so it fits a width, such as @terminal_width(). ->is_numeric() is true for text such as '42' or '-3.5'.
->contains(), ->starts_with(), ->ends_with(), ->index_of() (the last match with last) and ->replace() match case exactly. Pass ignore_case to match upper and lower case alike:
$query = 'TEA'
echo 'Green tea'->contains($query, ignore_case) // true
To check a webhook, work out the signature with ->hmac(key) (SHA-256 by default, or sha1 or sha512) and compare it with @secure_equals(), which takes the same time however much of the two matches:
$body = '{"id": 1}'
$signature = $body->hmac('whsec_test')
echo @secure_equals($signature, $body->hmac('whsec_test')) // true
->md5(), ->sha1(), ->sha256() and ->sha512() give hashes in hex. @escape_regex(text) escapes what a user typed so a pattern built from it matches only that text.
Lists and maps
Lists compare as sets with ->difference(other), ->intersect(other) and ->union(other). Each keeps the order of the first list, gives every item once and matches items with ==, or by what by: gives for each:
$left = [1, 2, 3, 4]->difference([2, 4]) // [1, 3]
$both = ['tea', 'milk']->union(['milk', 'sugar']) // ['tea', 'milk', 'sugar']
$people = [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]
$kept = $people->intersect([{ id: 2 }], by: fn(p) => $p.id) // [{ id: 2, name: 'Bo' }]
->count_by(fn) counts the items for each key, ->take_while(fn) and ->skip_while(fn) stop at the first item that fails, ->window(size, step?) gives overlapping runs, and ->replace_at(index, item) gives a copy with one item changed:
$counts = ['apple', 'avocado', 'banana']->count_by(fn(fruit) => $fruit->first()) // { a: 2, b: 1 }
$pairs = ['mon', 'tue', 'wed', 'thu']->window(2) // [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']]
$fixed = ['tea', 'tae', 'milk']->replace_at(1, 'juice') // ['tea', 'juice', 'milk']
Most and least common: common
->common(count?, least, by?) counts how often each item occurs and gives the items back in that order, each once. Without least the most common come first; with least the rarest do. count keeps only that many from the front, and without it you get every distinct item. Items that occur equally often stay in the order they first appear in the list, and each item comes back as it is, so numbers stay numbers:
$basket = ['apple', 'pear', 'apple', 'fig', 'fig', 'apple']
// apple occurs 3 times, fig 2 times, pear once.
echo $basket->common() // ['apple', 'fig', 'pear'] because that is most to least
echo $basket->common(1) // ['apple'] because it is the 1st most common
echo $basket->common(2) // ['apple', 'fig'] because those are the top 2
echo $basket->common(1, least) // ['pear'] because it is the 1st least common
echo $basket->common(least) // ['pear', 'fig', 'apple'] because that is least to most
by: decides what counts as the same item. Here 'Tea' and 'tea' count together because both lower to 'tea', and the one that came first is the one you get back:
$drinks = ['Tea', 'milk', 'tea']
echo $drinks->common(1, by: fn(drink) => $drink->lower()) // ['Tea'] because 'Tea' and 'tea' count as one, twice
To multiply the three most common numbers together, take them with ->common(3) and multiply with ->product():
$readings = [12, 7, 12, 9, 7, 12, 3]
$top = $readings->common(3) // [12, 7, 9] because 12 occurs 3 times, 7 twice, then 9 comes before 3
echo $top->product() // 756 because 12 * 7 * 9 is 756
Maps have the same callbacks as lists, given the value and then the key: ->filter(), ->reject(), ->any(), ->all(), ->find() (which gives { key, value }), ->reduce(), ->sort(by:) and ->map(). ->map_keys(fn) renames each key, given the key and then the value:
$stock = { apples: 3, pears: 0, plums: 2 }
$empty = $stock->reject(fn(n) => $n > 0) // { pears: 0 }
$order = $stock->sort(by: fn(n) => $n, order: desc)->keys() // ['apples', 'plums', 'pears']
$renamed = { first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel)) // { firstName: 'Ada' }
Converting between formats: convert
Data moves between formats all the time: an API answers in JSON, a settings file is YAML, a spreadsheet is saved as CSV. Every value has one method for all of it, ->convert(), and it reads like a sentence: convert from this format, to that one.
from: reads text written in a format and gives you the values in it. to: writes a value in a format. Give both to turn one format straight into another.
| Format | from: reads it |
to: writes it |
|---|---|---|
json |
maps, lists, text, numbers | json text |
yaml |
maps, lists, text, numbers | yaml text |
csv |
a list of rows | csv text |
markdown, latex |
a document | with KScript.Document |
html |
from Markdown with KScript.Markdown, from documents with KScript.Document |
Reading text: from
from: takes text, a text block such as a ```yaml or ```csv block, a json or csv value, or an HTTP response (its body):
$order = '{"fruit": "apple", "count": 3}'->convert(from: json)
echo $order.count // 3 because the json text is now a map with a count key
$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml).size // 12 because the yaml is read into a map
CSV has a header line by default, which names each row’s keys. Write not header when every line is data, and each row is then a list of its cells:
$prices = ```csv
fruit,price
apple,3
plum,5
```
echo $prices->convert(from: csv)[0].fruit // 'apple' because the header line names the fruit column
echo $prices->convert(from: csv, not header)[0] // ['fruit', 'price'] because without a header the first line is a row too
Checking it against a type: as
as: checks what was read against a type and turns it into records, so a missing or wrong field is an error on the line that read it, not a surprise later. A list of records is written as a declaration writes it, Fruit[]:
type Fruit {
fruit: string
price: int
}
$prices = ```csv
fruit,price
apple,3
plum,5
```
$fruits = $prices->convert(from: csv, as: Fruit[])
echo $fruits[0].price + 1 // 4 because as: Fruit[] turned the '3' cell into the int 3
Writing a format: to
to: writes any value: maps and lists as JSON or YAML, and a list of rows as CSV. indented spreads JSON over lines, and headers: picks and orders the CSV columns:
$basket = [{ fruit: 'apple', count: 3 }, { fruit: 'plum', count: 5 }]
echo $basket->convert(to: json) // [{"fruit":"apple","count":3},{"fruit":"plum","count":5}] on one line
echo $basket->convert(to: json, indented) // the same json, one key a line, for people to read
echo $basket->convert(to: csv, headers: ['count']) // "count", then "3" and "5" because only the count column is asked for
Both at once
Give from: and to: together to change one format into another without handling the values in between:
$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml, to: json) // {"theme":"dark","size":12} because the yaml is read, then written as json
Shortcuts: from and to
When you only read or only write, ->from(type: json) and ->to(type: csv) say the same thing in fewer words. They take the same options as ->convert():
$order = '{"fruit": "apple"}'->from(type: json)
echo $order.fruit // 'apple' because ->from(type: json) is ->convert(from: json)
echo [{ fruit: 'plum' }]->to(type: json) // [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json)
->convert() is the only way to change a format, so the older one-method-per-format spellings (->json(), ->yaml(), ->csv(), ->markdown(), ->to_json(), ->to_yaml(), ->to_csv(), and a document’s ->html(), ->latex() and ->markdown()) are errors that show the ->convert() to write instead, with a fix in the editor.
Reading structured text
Data often arrives as text: one record per line, groups of lines separated by a blank line, or a picture drawn in characters. These methods turn that text into lists you can work with.
Lines and blocks
->lines() gives one text per line. ->blocks() splits the text at blank lines instead, so each block is a group of lines. A single line break stays inside a block; only an empty line starts a new one:
$pantry = ```text
tea
milk
flour
sugar
eggs
```
$shelves = $pantry->blocks()
// ['tea\nmilk', 'flour\nsugar\neggs'] because the blank line after milk starts a second block
$counts = $shelves->map(.lines()->count())
// [2, 3] because the first block has 2 lines and the second has 3
.lines() in a function’s place is short for fn(block) => $block->lines(): the method is called on each item, as .name reads each item’s field. It works wherever a function goes, such as ->filter(.is_empty()) or ->sort(by: .age).
Splitting a list: split
When you already have a list, ->split(separator) cuts it into lists wherever the separator item appears, and drops the separator. Give a value to match with ==, or a check that is true for the separator:
$lines = ['tea', 'milk', '', 'juice']
echo $lines->split('') // [['tea', 'milk'], ['juice']] because '' is the separator
echo $lines->split(.is_empty()) // [['tea', 'milk'], ['juice']] because the check is true for ''
echo [5, 0, 7, 8, 0]->split(0) // [[5], [7, 8], []] because a separator at the end leaves an empty list after it
->split() on text cuts the text; ->split() on a list cuts the list.
Numbers in text: numbers
->numbers() gives every number written in the text, in order, so you don’t need a pattern for it. A minus counts as a sign when it sits right before a number with nothing joined to its left, as in x=-3; between two numbers, as in 1-3, it is a dash, so you get 1 and 3:
echo 'move 3 boxes from -1 to 12'->numbers() // [3, -1, 12] because -1 has a space before its minus
echo 'pages 4-9'->numbers() // [4, 9] because the minus joins 4 and 9, so it is a dash
echo 'price 2.50, qty 4'->numbers() // [2.5, 4]
Pictures in characters: grid
->grid() turns lines of characters into rows of single characters, so $grid[row][column] is one character. Row 0 is the top line and column 0 the first character:
$garden = ```text
#.#
..#
```
$plot = $garden->grid()
// [['#', '.', '#'], ['.', '.', '#']]
echo $plot[0][1] // '.' because row 0 is '#.#' and column 1 is its second character
echo $plot[1][2] // '#' because row 1 is '..#' and column 2 is its last character
Going through rows and columns: cells
->cells() reads a grid the way you’d read a table. On its own, or with rows, it gives every row; with columns it gives every column, top to bottom. That is how you loop over a grid in either direction:
$garden = ```text
#.#
..#
```
$plot = $garden->grid()
for row in $plot->cells(rows) {
echo $row->join('')
}
// '#.#' then '..#' because each row is one line of the picture
for column in $plot->cells(columns) {
echo $column->join('')
}
// '#.' then '..' then '##' because each column reads one character from every line, top to bottom
echo $plot->cells(columns)->map(fn(column) => $column->count_of('#'))
// [1, 0, 2] because only the last column has a # in both rows
row: picks one row and column: one column, each counted from 0, and -1 is the last. Give both to get the one cell where they meet:
$garden = ```text
#.#
..#
```
$plot = $garden->grid()
echo $plot->cells(row: 0) // ['#', '.', '#'] because row 0 is the top line
echo $plot->cells(column: -1) // ['#', '#'] because -1 is the last column, and both lines end in #
echo $plot->cells(row: 1, column: 0) // '.' because row 1 is '..#' and column 0 is its first character
Lines can be different lengths, as in a ragged map. A column then skips the rows too short to reach it, so nothing is made up to fill the gap:
$steps = ```text
#.#
#
```
echo $steps->grid()->cells(columns)
// [['#', '#'], ['.'], ['#']] because the second line only reaches column 0
->cells() works on any list of lists, not only a grid: [[1, 2], [3, 4]]->cells(columns) is [[1, 3], [2, 4]], which turns rows into columns.
Finding things in a grid: positions_of
->positions_of(item) gives every place an item is in a grid, as points with a .row and a .column, row by row and left to right. Given a function, it gives the places where the function is true for the cell:
$garden = ```text
#.#
..#
```
$trees = $garden->grid()->positions_of('#')
// [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first
echo $trees->contains({ row: 1, column: 2 }) // true because there is a # at row 1, column 2
echo $trees->contains({ row: 1, column: 0 }) // false because row 1 starts with a .
Points work well with ->combinations(2), which gives every pair once with the earlier point first. A function with two parameters gets the pair’s two points one by one. This counts the squares whose four corners are all trees, even with other trees between the corners:
$field = ```text
#.##.
.....
.#...
##.##
```
$trees = $field->grid()->positions_of('#')
echo $trees->combinations(2)->count_of(fn(left, right) {
// only two trees on the same row can be a square's top corners
if $left.row != $right.row {
return false
}
// the gap between them is the square's width, so the bottom corners sit that many rows down
$size = $right.column - $left.column
return $trees->contains({ row: $left.row + $size, column: $left.column })
and $trees->contains({ row: $left.row + $size, column: $right.column })
})
// 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them
Finding shapes: shapes
->shapes() finds shapes in text, a list, a grid or a 3D list: squares, rectangles, lines and circles that are built in, and masks, which are shapes you draw. Text is read as ->grid() reads it, one row a line and one cell a character, so there’s no need to call ->grid() first. A grid’s cells can hold anything, so for the built-in shapes of: says which cells make the shape: a value such as '#', or a regex such as /[#@]/. Each match comes back once, as { kind, points }, and each point is a cell { row, column, value }. Other cells may sit between a shape’s points:
$field = ```text
#.##.
.....
.#...
##.##
```
echo $field->shapes(square, of: '#')->count()
// 1 because the #s at columns 0 and 3 of row 0 have #s 3 rows below both of them
Without rotated, shapes stand level: squares and rectangles have level sides, and lines run across or down. With rotated, they may lean, so a square can be a diamond and a line can run diagonally:
$kite = ```text
..#..
.#.#.
..#..
```
echo $kite->shapes(square, of: '#')->count() // 0 because no four #s make a square with level sides
echo $kite->shapes(square, of: '#', rotated)->count() // 1 because the four #s make a diamond, a square on its corner
Name several shapes to find them all. A match is given once even when it fits more than one: a square is also a rectangle, so it comes back as a square, and .kind says which it is:
$plot = ```text
@@@.
@..@
@@@@
```
echo $plot->shapes(rectangle, of: '@')->count() // 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2
echo $plot->shapes(square, rectangle, of: '@')->map(.kind)
// ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well
echo $plot->shapes(line, of: '@', size: 4)->count() // 1 because only the bottom row has 4 @s in a row
echo $plot->shapes(line, of: '@', size: 3, rotated)->count() // 4 because rotated lets lines run diagonally too
A line needs size:, how many points it has. A circle needs radius:, and distance: says how far is far: straight (as the crow flies, the default), steps (across and down only, which draws a diamond) or moves (diagonals count as one, which draws a square ring):
$pond = ```text
.~.
~.~
.~.
```
echo $pond->shapes(circle, of: '~', radius: 1)->count() // 1 because the four ~s are each 1 away from the middle
echo $pond->shapes(circle, of: '~', radius: 1, distance: moves)->count() // 0 because with moves the corners are 1 away too, and they aren't ~
->shapes() works on a list of points as well, such as ->positions_of() gives or rows read from a csv. Then every point counts, so there’s no of:: $trees->shapes(square, rotated).
Shapes of your own: masks
A mask is a shape you draw. Built-in shapes only know where the points are; a mask says exactly what every cell must hold, gaps included. Declare it as a type that extends Mask, and draw it in its layout: a text block that pictures the shape, one character a cell. Every character matches a cell that holds the same character. The indentation every line shares isn’t part of the picture, so indent it with the code around it.
To find a solid two-by-two block of #s, draw it, and pass the mask to ->shapes() by name:
/// Four #s packed into a square.
type Block extends Mask {
layout: ```text
##
##
```
}
$roof = ```text
###.
###.
...#
```
$blocks = $roof->shapes(Block) // the matches, top left first
echo $blocks->count() // 2 because the block fits at columns 0-1 and again at columns 1-2
echo $blocks->first().kind // 'Block' because a mask's match is named after its type
echo $blocks->first().points->map(.column) // [0, 1, 0, 1] because the first block covers columns 0 and 1 of rows 0 and 1
symbols is only for the characters that mean something other than themselves. It maps a character to what it matches: a value (t: 'taken') matches a cell that holds it, a regex (/[#@]/) a cell whose text fits, a fn(cell) a cell it gives true for, and any a cell that isn’t part of the shape. An any cell can hold anything, can hang over the edge of the input, and is left out of the match’s points. To find four trees at the corners of a three-by-three square, with anything between them:
/// Trees at the four corners of a 3x3 square, anything between.
type Corners extends Mask {
layout: ```text
#.#
...
#.#
```
symbols: { '.': any }
}
$orchard = ```text
#.#.#
.#...
#.#.#
```
echo $orchard->shapes(Corners)->count() // 2 because the corners fit at columns 0-2 and at columns 2-4
echo $orchard->shapes(Corners)->first().points->map(.symbol)
// ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle
symbols earns its place when the cells aren’t single characters. A row of seats is a list of words, and a list of values is one row, so the layout needs a letter for each word:
/// Two free seats side by side, with a taken seat on each side.
type QuietPair extends Mask {
layout: ```text
tfft
```
symbols: { t: 'taken', f: 'free' }
}
$row = ['free', 'taken', 'free', 'free', 'taken', 'taken']
echo $row->shapes(QuietPair)->count() // 1 because only seats 1 to 4 read taken, free, free, taken
->shapes() takes one mask or a list of them, and rotated turns each every way the input allows: back to front along a row, a quarter, a half and three quarters in a grid, and all 24 ways round in 3D. Matches of several masks come back together, each named by its .kind, and masks and built-in shapes can be looked for in one call:
/// Three trees in a V, with anything between them.
type Fork extends Mask {
layout: ```text
t~t
~t~
```
symbols: { t: /[#@]/, '~': any }
}
/// Two trees with a clearing between them.
type Gap extends Mask {
layout: ```text
#.#
```
}
$wood = ```text
#.@
.#.
#.#
```
echo $wood->shapes(Fork)->count() // 1 because the V fits only with its point at the bottom
echo $wood->shapes(Fork, rotated)->count() // 4 because turned a quarter, a half and three quarters, it fits once each way
echo $wood->shapes([Fork, Gap], rotated)->map(.kind)
// ['Fork', 'Fork', 'Fork', 'Fork', 'Gap', 'Gap'] because the bottom row and the left column are each #.#
echo $wood->shapes(Fork)->first().points->map(.symbol)
// ['t', 't', 't'] because ~ is any, so its cells aren't part of the match
A mask’s symbols can be changed where it’s used, as any field can: Fork(symbols: { t: fn(cell) => $cell != '.', '~': any }) is the same V of anything but ..
A blank line in a layout starts the next layer, top layer first, as a blank line does in the text the mask looks through. Every layer has the same number of rows, and each point of a match in 3D has a layer too. A 3D list ($cube[layer][row][column]) is read the same way:
/// A step: one block on the top layer, with two under it on the layer below.
type Step extends Mask {
layout: ```text
#.
##
```
symbols: { '.': any }
}
$tower = ```text
#..
...
##.
.#.
```
echo $tower->shapes(Step)->count() // 1 because the one block on the top layer has a block under it, and another beside that
echo $tower->shapes(Step)->first().points->map(.layer) // [0, 1, 1] because one point is on the top layer and two are on the layer below
A mask with fewer layers or rows than the input slides through all of it: a one-line mask is tried along every row of a grid, and a flat mask in every layer of 3D text or a 3D list. A mask with more is an error that says so, such as “Step has 2 layers, and this is one grid.”
Mask is a type you can write for a parameter or a field. It takes any type that extends Mask, as the type itself (Block) or one made from it (Block(symbols: ...)), and Mask[] takes a list of them:
/// Four #s packed into a square.
type Block extends Mask {
layout: ```text
##
##
```
}
fn count_in(input: string, shape: Mask): int => $input->shapes($shape)->count()
fn count_all(input: string, shapes: Mask[]): int => $input->shapes($shapes)->count()
$roof = ```text
###.
###.
...#
```
echo @count_in($roof, Block) // 2 because Block fits twice in the roof
echo @count_in($roof, Block(symbols: { '#': /[#.]/ })) // 6 because now a . counts as well, so every 2x2 window fits
echo @count_all($roof, [Block, Block(symbols: { '#': '.' })]) // 2 because no 2x2 of the roof is all .s, so only Block's 2 count
A mask holds layout, symbols and its own methods, written with :. The editor and kscript check report a mask written wrong, most with a fix: a missing or empty layout, a layout that is all any, a tab in the picture, layers of different heights, a symbol that is more than one character or is listed twice, null for any, layout = for layout:, and like:, which ->shapes() no longer takes. A symbol the layout doesn’t use is a warning (KS6026), and so is one that maps a character to itself (KS6025), since every character already matches itself:
type Block extends Mask {
layout: ```text
##
```
symbols: { '#': '#' } // the warning: '#' already matches '#'.
}
In the editor, a mask is part of the language. extends ‸ offers Mask, and inside a Mask type, typing layout writes the text block; once it has one, symbols comes written out with a character of the layout and any. Inside symbols: { }, completion offers the layout’s characters not yet listed. Hovering a character of the layout says what it matches and how often the layout uses it, and each character is coloured by what it matches: itself or a value like text, a regex like a regex, a fn like a function, and any dimmed like a comment.
Working through sequences
Multiplying: product
->product(fn?) multiplies the items, as ->sum() adds them. Given a function, it multiplies what the function gives for each item. Whole numbers stay exact at any size:
echo [2, 3, 4]->product() // 24 because 2 * 3 * 4 is 24
$boxes = [{ width: 2, height: 5 }, { width: 3, height: 1 }]
echo $boxes->product(fn(box) => $box.width) // 6 because 2 * 3 is 6
echo [942, 945, 571]->product() // 508298490
Running totals: scan
->scan(fn(total, item), initial?) works like ->reduce() but keeps every total along the way, so you see how the result builds up. Without initial, the first item is the first total:
$spending = [5, 2, 8, 1]
echo $spending->scan(fn(total, amount) => $total + $amount)
// [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1
echo $spending->scan(fn(total, amount) => $total - $amount, 20)
// [15, 13, 5, 4] because the budget starts at 20 and each amount comes off it
Every pick: combinations
->combinations(size) gives every way to pick size items from the list when the order of the picked items doesn’t matter. Each pick keeps the items in list order, and no item is picked twice in the same pick.
Picking 2 from ['tea', 'milk', 'juice'] works like this: start with tea and pair it with each item after it (milk, then juice), then start with milk and pair it with each item after it (juice). juice has nothing after it, so there is nothing more. ['milk', 'tea'] never appears, because it is the same pick as ['tea', 'milk']:
$drinks = ['tea', 'milk', 'juice']
echo $drinks->combinations(2)
// [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2
echo $drinks->combinations(3)
// [['tea', 'milk', 'juice']] because there is only one way to pick all 3
echo $drinks->combinations(1)
// [['tea'], ['milk'], ['juice']]
A common use is checking every pair, for example finding the two prices that add up to a total:
$prices = [15, 40, 25, 60]
$pair = $prices->combinations(2)->find(fn(two) => $two->sum() == 65)
// [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is
A function with one parameter per picked item gets the items one by one, so you can name them instead of reading $two[0] and $two[1]. This works for any size: picks of 3 fill fn(first, second, third). A function with one parameter still gets the whole pick:
$prices = [15, 40, 25, 60]
echo $prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70)
// 3 because 15 + 60, 40 + 60 and 25 + 60 are over 70, and no other pair is
$sides = [3, 4, 5, 9]
echo $sides->combinations(3)->count_of(fn(shortest, middle, longest) => $shortest ** 2 + $middle ** 2 == $longest ** 2)
// 1 because only 3, 4 and 5 make a right-angled triangle: 9 + 16 is 25
echo $sides->combinations(3)->map(fn(three) => $three->sum())
// [12, 16, 17, 18] because a function with one parameter gets each pick as a list
Because the picked items fill the parameters, such a function doesn’t get the index as well: with pairs, fn(first, second) is the pair’s two items.
Every order: permutations
->permutations(size?) gives every ordering, where the order does matter, so ['tea', 'milk'] and ['milk', 'tea'] are both there. Without size each ordering uses every item:
echo ['tea', 'milk', 'juice']->permutations()
// 6 orderings: [['tea', 'milk', 'juice'], ['tea', 'juice', 'milk'], ['milk', 'tea', 'juice'], ...]
// because there are 3 choices for first, 2 for second and 1 for third, and 3 * 2 * 1 is 6
echo ['tea', 'milk', 'juice']->permutations(2)->count()
// 6 because 3 choices for first and 2 for second
Combinations and permutations grow fast (10 items have 3,628,800 orderings), so past a million lists they stop with a Limit error rather than run out of memory.
Turning round: rotate
->rotate(by) moves every item by places towards the start, and the ones that fall off the front go on the end. A negative by turns the other way:
$week = ['mon', 'tue', 'wed', 'thu']
echo $week->rotate(1) // ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end
echo $week->rotate(-1) // ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front
Adding methods to a type: extend
extend adds your own methods to a type, built-in or your own. Inside, each fn is a method, and $this is the value it is called on:
extend date {
/// The date as text for an API: 2026-11-21.
fn api_date() => $this->format('yyyy-MM-dd')
fn is_payday() => $this.day == 25
}
extend list {
fn second() => $this[1]
}
extend string {
fn slug() => $this->lower()->trim()->replace(' ', '-')
}
echo "{ '2026-11-25'->to_date()->api_date() } { '2026-11-25'->to_date()->is_payday() }"
echo "{ ['a', 'b', 'c']->second() } { 'Hello World'->slug() } { 'Hello World' |> slug() }"
You can extend string, number (or int and float), bool, list, map, fn, date, email, password, handle, uuid and regex, a package’s values such as file or response, and your own types, whose methods see $this (a record) and its fields as $this.name. Methods take parameters, defaults and named arguments like any fn.
A method can’t take the name of one the type already has, so a typo or a clash never changes what a built-in method does. To replace one on purpose, write override:
extend date {
override fn to_string() => $this->format('d MMMM yyyy')
}
In XML, extend is <extend type="date"> holding <fn> elements, and override fn is <fn override="true">.
Where extensions apply. A file’s own extend blocks apply in that file and in every file that imports it. In a project (a folder with kscript.json), every file in the extensions/ folder applies to every script, test and page in the project, with no import needed. Split them up however you like, one file per type for example:
extensions/
date.kscript extend date { … }
list.kscript extend list { … }
text/
slug.kscript extend string { … }
kscript make extension date --methods api_date,is_payday writes extensions/date.kscript to start from. To keep them elsewhere, list folders or globs in kscript.json, which replaces the default folder: "extensions": ["extensions", "shared/**/*.kscript"]. Two extension files adding the same method to the same type is an error that names both. A script’s own extend (or an import’s) wins over the project’s.
The editor completes and checks extension methods only where they apply: in a file that neither declares, imports nor (through the project) gets ->api_date() on dates, @today()->api_date() is still an unknown method. Hover shows the method’s /// docs and which file adds it, and go to definition opens that file.
Errors
Use guard condition else { ... } to continue only when a precondition holds. The failure block must leave the current flow with return, throw, break, continue, or exit.
fn save_age(age: int, enabled: bool) {
guard $enabled else {
return 'Skipped'
}
throw if $age < 0 {
type: 'Validation'
message: "Age cannot be negative: { $age }"
}
return 'Saved'
}
echo @save_age(-1, true) catch => $err.message
A postfix catch preserves the value on its left when evaluation succeeds. When it throws, KScript binds the error to $err and evaluates the fallback. Use catch Validation => $err.message to recover from one error type, or catch Validation as problem => $problem.message to name the binding. A null fallback propagates the original error.
In @a() + @b() catch => 0, the handler covers both calls and the addition. In @a() + (@b() catch => 0), it covers only @b().
Use throw if to raise an error only when a condition holds. Inside its block, write one field per line. KScript evaluates the condition once. It evaluates the fields only when the condition is true, so a successful reply can omit e entirely.
fn result(reply: map) {
throw if $reply->has('e') {
type: 'Network'
message: "Host refused: {$reply.e.message}"
code: $reply.e.code
}
return $reply.r
}
try {
echo @result({ r: 'ready' })
} catch Network as err {
echo "Request failed ({$err['code']}): {$err.message}"
}
try {
$data = @read_json($path)
} catch FileNotFound {
echo "No file at {$path}, using defaults."
} catch err {
echo "Failed: {$err.message} (line {$err.line})"
} finally {
echo "done"
}
throw Validation "Age must be positive, got {$age}"
catch takes the error types it handles, joined by |, and as names the error: catch FileNotFound | Permission as e. A catch with only a lower-case name (catch err) handles every error. when adds a test: catch Network as e when $e.status == 503. Catches are tried in order and the first that fits runs. Error type names start with a capital letter, which is how catch tells them from the variable’s name.
Unknown elements, attributes and syntax errors are reported before a script starts, so a typo near the end doesn’t leave a job half done.
An error nothing catches is printed as a KScript error, with where it happened and its type, and the script exits with code 3:
ERROR app.kscript:2:11: Name: Unknown command @nope().
kscript shows every failure this way, in scripts, kscript serve error pages and all the other commands, never as a .NET exception. A failure that comes from the computer rather than the script gets the error type that fits (FileNotFound, Access, IO, Network and so on), and one kscript didn’t expect is an Internal error, which is a bug worth reporting. To see the .NET exception and stack trace behind an error, run with --stack-trace (before the script’s path: kscript --stack-trace app.kscript) or set KSCRIPT_STACK_TRACE=1, which also works for kscript serve and compiled programs.
Handlers on functions and types
Attach a catch to a function or method to handle errors for every caller. Attach it to a type to share a handler across its methods.
The nearest matching handler runs first. Return a non-null value to recover. Values such as false, 0, and '' all work. A bare throw, a null return, or reaching the end of the handler passes the original error to the next enclosing handler.
type Directory {
fallback: string
fn lookup(key: string) {
if !$key->is_blank() => return $key
if !$this.fallback->is_blank() => return $this.fallback
throw Validation "A key is required"
}
} catch Validation as err {
return $err.message
}
$directory = Directory(fallback: 'guest')
echo $directory->lookup('owner') // owner
echo $directory->lookup('') // guest
$empty = Directory(fallback: '')
echo $empty->lookup('') // A key is required
Inside a handler, throw if condition rethrows the current error when the condition holds. Add a payload block to raise a new error. A handler that only logs the error lets it propagate. The runnable catch tests show a method handler passing an error to its type’s handler and a caller catching an error after it was logged.
Use /// @throws Network to document an error that can reach the caller. Hover and signature help show known errors. At the top level of a script, kscript check and the editor warn when a known error can escape (KS5016).
For a single call, recover the result inline with catch.
echo @testing(1, 2) catch Error => $err.message
fn testing(arg1: number, arg2: number) {
throw Error(message: "{ $arg1 } and { $arg2 }")
}
Throw with a value and a cause
Use throw Error(message: ..., value: ..., cause: ...) to raise a generic error with extra data. The name before the parentheses sets the error type. Use Error for a generic error, a built-in type such as Validation, or a type you declare yourself. The named arguments become fields. message: sets the explanation and cause: holds the earlier error when you wrap one.
$age = -1
try {
try {
throw Validation "Age must be positive, got {$age}"
} catch Validation as original {
throw Error(
message: 'Could not save profile',
value: $age,
cause: $original
)
}
} catch Error as err {
echo "{ $err.type }: { $err.message }"
echo "Rejected value: { $err['value'] }"
echo "Caused by: { $err.cause.message }"
}
Error: Could not save profile
Rejected value: -1
Caused by: Age must be positive, got -1
Omit cause: when raising the first error. Use bracket lookup, such as $err['value'], for fields added directly to a built-in error. For fields callers should be able to discover and type-check, declare an error type and catch that type. Its declared fields can be read with dot syntax, such as $err.value.
If you already have a map with type, message, and other fields, throw the map directly with throw $payload. Passing the map as the first argument to Error($payload) converts it to message text. The error constructor offers named arguments in editor completion.
In XML, the same throw is <throw value="Error(message: 'Could not save profile', value: $age, cause: $original)" />. The outer XML value attribute holds the entire error expression. The inner value: argument is the extra field on that error. For a type and message alone, <throw type="Validation" message="Invalid age" /> corresponds to throw Validation "Invalid age".
Trying again
Some failures go away on their own: a busy database, a network blip, an API that is rate limiting you. @retry(times, work) calls work, and calls it again each time it throws, up to times calls in all. It returns what work returns, or throws the last error. work is given the attempt, 1 for the first:
fn fetch_rates(attempt: int) {
if $attempt < 3 => throw Timeout "The rates service is busy"
return { eur: 0.86 }
}
$rates = @retry(3, @fetch_rates, backoff: 100ms)
echo $rates.eur
backoff waits between calls. when is given the error and says whether to try again, so a mistake that will never succeed fails at once: @retry(5, @charge, when: fn(err) => $err.type == 'Timeout').
Error types
Declare your own error types with error. Fields work as in a type, the message can use them, and extends says what kind of error it is:
/// No person has that id.
error PersonNotFound(message: "No person with id {$id}") extends NotFound {
id: int
}
error OutOfStock(status: 409, message: "{$item} is out of stock") {
item: string
left: int = 0
}
fn find_person(id: int) {
throw PersonNotFound(id: $id)
}
try {
@find_person(42)
} catch NotFound as e {
echo "{ $e.message } ({ $e.type }, status { $e.status })"
}
- Throwing.
throw PersonNotFound(id: 42)makes the error and throws it. Its arguments are its fields, by name, plusmessage:(instead of the type’s message) andcause:(the error that led to this one). A field without a default must be given, and the editor flags missing and unknown fields.throw Validation "Too short"still works for a type with no fields, andthrow Validation(field: 'name', message: 'Too short')adds fields to a built-in one. - Catching.
catch NotFoundcatchesPersonNotFoundtoo, because it extendsNotFound. In the catch,$e.idreads a field, and the editor completes the fields of the types the catch names. Every error hastype,message,line,column,file,statusandcause.$e->is(NotFound)checks the type in code, and$e->chain()lists it:['PersonNotFound', 'NotFound', 'Error']. - Rethrowing and wrapping. A bare
throwinside a catch rethrows the error it is handling, unchanged.throw $edoes the same with a saved error. To add context, wrap it:throw ConfigBroken(path: $path, cause: $e), then$err.cause.messagereads the original. - Making one without throwing.
OutOfStock(item: 'tea')gives the error as a value, to return or throw later. - Status.
statusis the HTTP status a KScript.Http route answers with when nothing catches the error. A type inherits it, and its fields and message, from the type it extends. - Exports. Top-level error types are exported, like functions and types, so
import "errors/payment-failed.kscript"brings them in.kscript make error PaymentFailed --status 402 --extends Validation --fields "order: int"writes one toerrors/.
The built-in error types, which KScript itself raises, form a tree that catch follows:
| Type | Extends | Raised for |
|---|---|---|
Error |
Every error. catch Error catches everything. |
|
Syntax, Name, Null, Argument, Value, Const, Math |
Error |
Mistakes in a script: bad syntax, an unknown name, null where a value is needed, wrong arguments, a bad value, changing a const, dividing by zero. Index extends Value, for a position outside a list. |
Type |
Error |
A value of the wrong type. Shape extends it, for data that doesn’t fit a type ($e.problems lists each problem). |
Format |
Error |
Text in the wrong format. Json and Yaml extend it. |
IO |
Error |
Files. FileNotFound, Permission and Access extend it. |
Network |
Error |
Requests. Timeout extends it, and $e.status is the response’s status. |
Import, Config, Input, Limit, Context, Platform, Cancelled, Retired, Http, AI, UI, Reference, Assertion, Internal |
Error |
Imports, settings, input, limits such as recursion, the wrong place, the OS, a stopped script, retired features, KScript.Http apps, language models, desktop windows, a document’s references, failed test checks, a fault in KScript itself. |
Validation (422), BadRequest (400), Unauthorized (401), Forbidden (403), NotFound (404), Conflict (409), TooManyRequests (429) |
Error |
For your own code to throw or extend. The number is the HTTP status. |
Query, Connection (503) |
Error |
KScript.Data: a query the database refused, a database that can’t be opened. Migration: a migration that can’t be read or run, or a kscript db command that can’t go ahead. ModelNotFound extends NotFound; UniqueViolation and ForeignKeyViolation extend Conflict; MultipleRecordsFound (from ->sole()) extends Query. |
JobFailed |
Error |
KScript.Queue: a job that used up its tries. JobTimeout extends Timeout. |
No type’s name ends in Error: they are all errors. (QueryError and ConnectionError are now Query and Connection, and catch QueryError says so.)
A name in catch or throw that is neither declared nor built in still works (as a kind of Error), but the editor warns about it (KS5011), since it is usually a typo.
Settings: $config
$config holds the app’s own settings, such as its name, its database and its cache. Every script, page, route and test can read it without an import. The settings live in one place: the config section of kscript.json.
{
"name": "shop",
"config": {
"app": { "name": "Shop" },
"database": { "connections": { "main": { "url": "sqlite:data/shop.sqlite" } } },
"features": ["search", "cart"]
}
}
echo $config.app.name
$timeout = $config->get('http.timeout', 30) // a path, and a default when it isn't set
if $config->has('features') => echo "{ $config.features->join(', ') }"
$key = $config->require('api.key') // stops with a clear message when it's missing
A setting that isn’t there is null, so $config.port ?? 8080 works. Names don’t depend on case, so $config.app.name and $config.APP.NAME are the same setting. In the editor, hovering over $config.app.name shows its type, and Go to Definition opens the key in the file that supplies it, inside interpolated strings too.
Packages read their own parts of $config: KScript.Data reads database, KScript.Cache reads cache, KScript.Mail reads mail, $log reads logging, translations read i18n, and money arithmetic reads money.exchange_rates (see Money).
Environments. The same app often needs other settings in another place: an in-memory database for tests, or a real server in production. Put those in kscript.<env>.json beside kscript.json. Its config section is laid over the one in kscript.json, and maps merge field by field, so it only needs the settings that change:
// kscript.test.json
{
"config": {
"database": { "connections": { "main": { "url": "sqlite::memory:" } } }
}
}
Choose the environment with kscript --env staging script.kscript or KSCRIPT_ENV=staging. kscript test uses test.env from kscript.json (see Testing). $config->environment() gives the environment, or null when none is chosen. An environment’s file holds only a config section: everything else belongs in kscript.json.
Settings that need code: config.kscript. JSON can’t read an environment variable or work something out. For those settings, add config.kscript beside kscript.json (config.ks.xml in an XML project). It defines configure(environment), which gets the environment (or development when none is chosen) and returns a map. That map is laid over the JSON settings, so it only needs the settings that need code:
// config.kscript
fn configure(environment: string) {
$url = @env('DATABASE_URL', default: '')
return {
database: { connections: { main: $url->is_blank() ? {} : { url: $url } } }
http: { timeout: $environment == 'production' ? 8s : 30s }
}
}
The values keep their KScript types, so 8s stays a duration. The script can use @env(), $env, imported files and packages such as KScript.IO, and paths in it start from its own folder. It runs once, the first time a script reads $config, and it can’t read $config itself. kscript make config base writes a starting config.kscript, and kscript make config staging writes kscript.staging.json.
The layers, later ones winning: the config section of kscript.json, then kscript.<env>.json, then config.kscript. A script outside a project reads config.kscript from its own folder.
.env files keep secrets out of the project’s files. .env (and .env.<env> for an environment) beside kscript.json holds NAME=value lines, with # comments, export in front if you like, 'single quotes' taken as written, and "double quotes" that allow \n and can span lines. ${NAME} and ${NAME:-default} use another variable. The values are read with @env('NAME'), usually in config.kscript, and they also become environment variables unless one is already set, so KScript.AI finds ANTHROPIC_API_KEY in .env. Keep .env files out of git.
The person’s own settings. A desktop app can let the person change a setting without touching the project: with "app": { "user_config": true } in kscript.json, config.json in the app’s config folder is laid over everything else (see App folders).
config reads settings again with other options, or reads another set of settings into a variable. Without into, it changes $config:
config(env: 'production')
config(files: ['themes/dark.json'], into: theme) // a separate set of settings in $theme
config(files: ['settings.json', 'secrets.kscript?', '.env?'], prefix: 'SHOP_', defaults: { server: { port: 8080 } }, require: ['database.host'])
files lists other files to read instead of the project’s: JSON files of settings, config scripts and .env files, in order, each followed by its version for the environment (settings.staging.json). A name without an extension means its .json file, and a name ending in ? may be missing. With prefix, environment variables override the files and __ nests: SHOP_DATABASE__HOST=db.internal sets database.host, and values such as true, false and 8080 become booleans and numbers. root is the folder the files are in, defaults fills in settings no file sets, require lists settings that must be set, and user: true also reads the person’s own settings.
$config->sources() lists the files that were read, $config->all() gives every setting as a map, and $config->reload() reads them again. @parse_env(text) parses .env text, and KScript.IO adds @read_env(path).
kscript serve never serves kscript.json, kscript.<env>.json, scripts, .env files, or config.* JSON files. Pages read the project’s settings and can use @env() for values in its .env files, but they leave the process environment alone.
Logging: $log
Every script has a logger. Entries at info and above go to the terminal (stderr) until you set up somewhere else for them:
log "Import started"
log(level: warn, category: 'payments', fields: { order: $order.id }) "Card declined for {$customer.name}"
$log->info('Saved', { id: $id, size: $bytes })
$db = $log->named('db')->with({ host: $config.database.host })
$db->debug('Connected') // category db, with a host field
if $log->is_enabled(debug) => $log->debug($everything->convert(to: json))
try {
@read_json(./missing.json)
} catch err {
$log->error('Could not read the file', $err) // error, error_type and error_line fields
}
Levels are trace, debug, info, warn, error and fatal. Providers decide where entries go, and are usually set in config:
// kscript.json
{
"config": {
"logging": {
"level": "info", // the lowest level written (default info)
"levels": { "db": "debug" }, // per category; db also covers db.queries
"providers": [
{ "type": "console", "level": "warn" }, // stderr, coloured at a terminal; stream: stdout, format: json, time: HH:mm:ss.fff
{ "type": "file", "path": "logs/app.log", "format": "json" }, // text, or json lines; roll: daily writes app-2026-11-20.log
{ "fn": "notify", "level": "error" } // a fn in the script, called with each entry
]
}
}
}
log_provider(…) adds one from a script, with the same options (replace removes the ones already set up, including the default console one). A memory provider keeps entries for $log->entries(), which is handy in tests. Entries that a provider holds back, such as an http batch, are sent when the script ends or on $log->flush(). A provider that fails is reported once on stderr, and the others carry on.
Packages add provider types with p.LogProvider("type", description, create), and programs that run KScript can add their own with host.Logs.AddProvider(provider, level), where a provider implements ILogProvider.
Translations: @t()
Put translations in a locales folder next to the script (or in the site folder): locales/en.json, locales/fr.yaml, or a folder per locale such as locales/de/shop.json, whose keys start with shop..
# locales/fr.yaml
hello: Bonjour, {name} !
cart:
items:
"=0": Votre panier est vide
one: "{count} article"
other: "{count} articles"
locale(set: 'fr')
echo "{ @t('hello', { name: $user.name }) }" // Bonjour, Ann !
echo "{ @t('cart.items', { count: $cart->count() }) }" // 3 articles
echo "{ @format_currency($total, 'EUR') } { @format_date(@today(), 'long') }" // 9,50 € 20 novembre 2026
- Plurals. With a
count,@t()pickszero,one,two,few,manyorotherby the language’s own rules. These are the CLDR rules for English, French, Portuguese, Russian, Ukrainian, Polish, Czech, Arabic, Hebrew, Irish, Welsh, Japanese, Chinese, Korean and more. An exact form such as=0wins. - Fallbacks. A missing translation is looked for in
fr-CA, thenfr, then the default locale (enunless set). If it isn’t anywhere, you get the key itself, and a warning is logged once under thei18ncategory. - The locale comes from
locale(set: fr), fromlocale(from: …)(the best available match for a list or an Accept-Language header), from$config.i18n.locale, fromKSCRIPT_LOCALE, or from the computer’s language.@locale()gives it, and@locales()lists the locales there are files for. - Pages pick it in this order: a path prefix (
/fr/aboutservesabout.htmlin French when there are French translations),?lang=fr, alangcookie, and then the browser’s Accept-Language.@locale_path($request.path, 'de')gives the link to the same page in German. The default locale has no prefix. - Formatting. These follow the locale, or one you pass as the last argument:
@format_number(1234.5)gives 1,234.5 or 1 234,5;@format_percent(0.25);@format_currency(9.5, 'GBP');@format_date(date, 'short' | 'medium' | 'long' | 'full' | 'time' | 'datetime' | 'd MMMM yyyy');@format_relative(date, from?)gives 3 hours ago, in 2 days or just now, measured from now unlessfrom:is given;@format_duration(1h30m)gives 1 hour 30 minutes;@format_list(['tea', 'coffee', 'milk'])gives tea, coffee and milk, or tea, coffee or milk withstyle: 'or';@format_ordinal(23)gives 23rd, and 23e in French;@format_bytes($file.size)gives 1.4 MB, or 1.3 MiB withbinary: true.
- Settings:
i18n: { folder: lang, default: en-GB, locale: fr }in config, ortranslations(folder: lang, default: en-GB).@has_t(key)checks whether a key has a translation, and@plural(count)gives the plural category.
The words for relative times, lengths of time, lists and ordinals are built in for English, French, German, Spanish, Italian, Portuguese and Dutch. For another language, or to change them, add these keys to its translation file: time.second up to time.year with plural forms and {count}, time.ago and time.in with {time}, time.now, list.and, list.or, and ordinal with {count}:
# locales/pl.yaml
time:
hour: { one: "{count} godzina", few: "{count} godziny", many: "{count} godzin" }
ago: "{time} temu"
Packages
KScript.Core (everything above) is always there. Everything else comes from a package, imported at the top of the script, so a script only loads what it uses: a terminal script never loads the web server.
import KScript.Terminal
import KScript.Math as math // commands stay under the prefix: @math.sqrt(2)
import "lib/strings.kscript" as str // another script's top-level functions and constants
import slugify from "lib/strings.kscript"
// …
Only .kscript and .ks.xml files can be imported. A function the script declares itself wins over an imported one of the same name, and an imported const stays a constant.
| Package | What it adds |
|---|---|
KScript.Terminal |
input(into, type, default, secret) (type can be email, handle, uuid or password), picker (a file or folder path), menu(options, multiple), progress(into, total) with ->advance(), confirm, pause, clear, @color(text, color: 'green'), @bold, @dim, @underline, @terminal_width(), @is_terminal() (no when output is piped), echo(format: markdown), and the kscript command line’s own look: info, success, warn, alert(type: error), heading, detail(name), bullets(items), task(name) { }, table(rows, columns, header, align) (see Terminal output) |
KScript.Math |
@sqrt @round(x, digits: 2) @clamp(x, min: 0, max: 10) @logarithm @sin @cos @atan2 @hypot @gcd @factorial @random(low: 1, high: 6) @random_bytes(16, format: hex) @pick @shuffle @sum @average @median @stdev @variance @mode @percentile(values, 95), $pi $e |
KScript.IO |
@read_text @read_lines @read_json @write_text @append_text @write_json @files(folder, pattern: '*.txt', recursive) @folders @file(path) @exists @join_path(base: $dir, ['a', 'b.txt']) @known_folder(downloads), @move(from, to) @copy(from, to) @delete(path) @create_folder(path). File values have the fields .name .extension .mime .size .modified… and the methods ->read_text() ->read_bytes() ->read_json(as:) ->sha256() ->write_text(text) ->copy_to(path) ->move_to(path) ->delete(). |
KScript.Net |
Sends HTTP requests with @api(url, options: { method, headers, body, timeout }), or the shorthands post:, put:, patch:, delete:, bearer:, timeout:, retries:, as:, encoding: (json, form or multipart) and query:. The response has .status, .is_ok, .text, ->convert(from: json) and ->check(). Also provides @download(url, to) and @query_string. A path such as '/api/notes' asks the project’s own routes. See Calling your own API. |
KScript.Markdown |
@markdown(text) and @read_markdown(path) (html, title, meta from front matter), ->convert(from: markdown, to: html) |
KScript.Web |
Renders pages with layouts, components and live blocks for kscript serve. Pages have KScript.IO, KScript.Markdown and KScript.Web without importing them. |
KScript.AI |
@llm(prompt, system, schema, tools, model, max_tokens), llm(into, system, schema, tools, model, max_tokens), @chat(system) with ->ask() .history ->reset(), and @fake_llm(replies) for tests. Claude, with the key from ANTHROPIC_API_KEY (see Language models). |
KScript.Style |
Stylesheets written in KScript (.ks.css, .ks.scss, .ks.sass); @up, @down, @between, @rem, @fluid, @adjust_lightness, @lighten, @darken, @mix, @alpha, @contrast_color, @css_var, @css_vars; @stylesheet(path, vars) (see Stylesheets). |
KScript.Http |
Routes, controllers and middleware for kscript serve: a Routes { } file holds Get Post Put Patch Delete Any Route Resource Group Middleware. Controllers use @view, @response, @redirect, @abort and @route. See Routes, controllers and middleware. |
KScript.Storage |
The app’s own folders, in the right place on each platform: @storage(config) (also data, cache, state, logs) with ->read ->read_json ->write ->write_json ->read_bytes ->write_bytes ->file ->move ->copy ->append ->list ->delete ->folder ->path_of, plus @app_name() and @app_folders(). See App folders. |
KScript.Cache |
$cache (in memory) and @cache(file) with ->get ->set ->remember(key, fn, ttl: 10m) ->has ->remove ->increment ->ttl ->keys ->clear. See Caching. |
KScript.Data |
Stores records with model, queries them with a query builder, and manages schema changes with Migration and kscript db migrate. See Databases. |
KScript.Queue |
Declares background work with job, queues it with ->dispatch() and runs it with kscript worker. Its Schedule runs tasks at set times. See Queues and jobs and Scheduling tasks. |
KScript.Mail |
Sends email with @send_mail(to:, subject:, html:|text:|view:) over SMTP, to the log or to a fake, now or with queue from kscript worker. @fake_mail() keeps it for tests. See Mail. |
KScript.Auth |
Sign-in for kscript serve apps: @register, @attempt, @login, @logout, @user(), @is_signed_in(), $session (->get ->set ->flash …), @users(), @csrf_field(), @reset_token, @reset_password, @api_token, and the auth and guest middleware. See Sign-in. |
KScript.Document |
Document(template: paper, to: "paper.pdf") { } with Section, Paragraph, List, Table, Figure, Math, Bibliography and more; Letter and Invoice; ->save ->pages ->words ->markdown ->latex ->html. See Documents. |
KScript.UI |
Desktop windows: a Window { } block opens one. Column Row Grid Text Button TextBox CheckBox Select Slider Box Spacer Timer, @close_window(). See Desktop apps. |
KScript.Test |
test, describe, before_each, after_each, expect, expect_error, capture, @assert, @fail, @run_script, @check_script. Test files import it on their own (see Testing scripts). |
Using something from a package that isn’t imported stops with input is part of KScript.Terminal. Add import KScript.Terminal at the top of the script., and the editor offers to add the import. A package is named only in an import: a statement is never written with the KScript. prefix (input, not KScript.input), and nothing is imported silently, job and dispatch included (import KScript.Queue). A project can import packages for every script in kscript.json (below).
Cryptographically secure random bytes
@random_bytes(count, format: hex) reads entropy from the operating system. Give it a whole byte count from 1 to 65536. Lowercase hex uses two characters per byte. The base64url format uses URL-safe characters and omits padding. Both formats are independent of @random_seed().
import KScript.Math
$key = @random_bytes(16) // 32 hex characters
$url_token = @random_bytes(16, format: base64url) // 22 characters
Names of statements and arguments
Statements and their arguments follow one set of rules in every package, and kscript check and the test suite hold the built-in ones to them:
| Rule | Examples |
|---|---|
A statement that does something, or declares something, is a lower snake_case word. |
input, table, before_each, expect_error, log_provider |
Statements that describe a window, route table or document in KScript.UI, KScript.Http and KScript.Document use PascalCase. In KScript.Data, Migration and its schema steps also use PascalCase. |
Button, Routes, Get, Section, Migration, CreateTable |
Arguments are snake_case. No name has a hyphen. |
max_tokens, must_exist, on_click, new_page |
into: is the variable that receives a result. |
input(into: name), llm(into: reply), capture(into: out) |
to: is where something goes: a file, a URL, a controller. It never names a variable. |
Get(path: /, to: @home), Post(path: /notes, to: @notes.add) |
path: is the file a statement reads or acts on. |
import(path: "lib.kscript"), <include path="_nav.html">, <layout path="_layout.html"> |
at is a position, as in for item at i in $list. |
menu(into: choice, at: i) |
A function is named as @name, as it is in an expression. |
spawn(fn: @job), llm(tools: [@order_status]), Get(to: @people.show) |
Three kinds of name are not functions and stay bare: a controller (Resource(to: people) is the name a script is imported as), the names in a middleware list ([log, throttle:30, my_check], where built-ins, groups and functions share one list), and a variable or type being declared. In XML the same arguments are attributes with the same names, and a function is written without the @ (<spawn fn="job" />); kscript convert adds and removes it.
In a page, on-click and the other handlers sit on HTML tags (<button on-click="$count += 1">), so they keep HTML’s hyphen. On KScript’s own elements, such as Button, the argument is on_click.
A name from before these rules is an error that says the new one ('to' is now into.), and kscript check --fix renames it. Letting a statement be assigned ($name = input "Name? ") is not part of the language yet.
Terminal output
KScript.Terminal prints the same way the kscript commands do, so a script’s output looks like the rest of the tool. Colours are only used at a terminal: piped output, files and tests get the same text without them, and NO_COLOR, FORCE_COLOR, --ansi and --no-ansi work as they do for kscript itself.
import KScript.Terminal
$people = [{ name: 'Joan', age: 82 }, { name: 'Sam', age: 9 }]
heading "Report"
detail(name: 'People') "{ $people->count() }"
task(name: 'Adding up') {
$total = 1 + 2
}
table(rows: $people)
info "Wrote [report.txt]."
alert(type: error) "The file [data.csv] is empty."
Report
People .................................................... 2
Adding up .......................................... 2ms DONE
┌──────┬─────┐
│ name │ age │
├──────┼─────┤
│ Joan │ 82 │
│ Sam │ 9 │
└──────┴─────┘
INFO Wrote [report.txt].
ERROR The file [data.csv] is empty.
[bracketed] parts of a label are shown in bold. alert(type: error) writes to stderr. Numbers in a table line up on the right; align: ['left', 'right'] sets each column.
Work done in steps gets a progress bar. progress(into: bar, total: n) shows it with its text as the label, and $bar->advance() moves it on one step (or ->advance(5) for five). At a terminal it is redrawn in place; piped output and tests get one line, like a task’s, when it reaches the total:
import KScript.Terminal
$files = ['a.csv', 'b.csv', 'c.csv']
progress(into: bar, total: $files->count()) "Importing"
for _file in $files {
$bar->advance()
}
menu(multiple: true) lets the answer pick several choices, such as 1, 3, and stores a list of them in the menu’s order (and at: a list of their positions).
Language models: KScript.AI
KScript.AI lets a script ask Claude. The API key comes from the ANTHROPIC_API_KEY environment variable (or a token in ANTHROPIC_AUTH_TOKEN, or the profile ant auth login saved, when the ant command is installed), never from the script. ANTHROPIC_BASE_URL sends requests to another host, such as a proxy. Scripts use claude-opus-5-5 unless they ask for another model, or KSCRIPT_AI_MODEL names one.
import KScript.AI
// One question, one answer.
echo "{ @llm('Write a haiku about XML.') }"
// A prompt written as a template, with a system prompt.
$customer = { name: 'Ann' }
$message = 'My order is late arrived.'
llm(into: reply, system: 'You answer customer emails politely and briefly.') "{$customer.name} wrote: {$message}"
// Structured output: the answer is a map with these fields.
$report = 'The login page spins forever on Safari.'
llm(into: ticket, schema: { category: 'bug|feature|question', urgency: 'int 1-5', summary: 'one line' }) "Triage this report: {$report}"
echo "{$ticket.category} ({$ticket.urgency}): {$ticket.summary}"
// Tools: the model may call your fn functions, and sees what they return.
/// The shipping status of an order.
fn order_status(id: int) => $id == 42 ? 'shipped' : 'unknown'
llm(into: answer, tools: [@order_status]) "Where is order 42?"
// A conversation that remembers what was said.
$chat = @chat('You are a patient maths tutor.')
echo "{ $chat->ask('What is a prime number?') }"
echo "{ $chat->ask('Is 91 one?') }"
llmand@llm(prompt, ...)ask the same question with the same options:system,schema,tools(a list such as[@order_status]),modelandmax_tokens(16,000 by default). The one difference is where the prompt comes from and where the answer goes: thellmstatement takes the prompt as its text and stores the answer into:, and@llm()takes the prompt as a value and returns the answer, so it fits inside an expression.@llm()takes its options by name:@llm($prompt, system: 'Be brief.', max_tokens: 500).- Schemas: each field is required.
'string','number','int','bool'and'date'name a type,'int 1-5'gives a range,'a|b|c'lists the choices, a map is a nested object,['string']is a list, and any other text describes a string field. - Tools are
fnfunctions. Theirparams(with types such asid: int) anddescriptiontell the model how to call them. If a tool fails, the model is told the error and can carry on. - Tests use
@fake_llm(replies)instead of Claude: see Faking a language model. - Errors have the type
AI, so atrywithcatch ecan check$e.typeand handle a missing key, a refusal, or an answer cut off bymax_tokens. When Claude’s safety checks decline a request, the API first retries it on a fallback model.
Writing portable scripts
- Build paths with
@join_path(base: $dir, ['reports', 'file.txt'])(KScript.IO) rather than hard-coding\or/. - Find the user’s folders with
@known_folder(downloads)(KScript.IO):home,desktop,documents,downloads,music,pictures,videos,appdataortemp. It follows each system’s own settings, such as Windows’ Downloads location and Linux’suser-dirs.dirs. $os.nameiswindows,linuxormacos, and$os.home,$os.tempand$os.separatorare there too;$env.HOMEreads an environment variable.- Numbers are always parsed and printed with
.as the decimal separator, whatever the machine’s language.