lmscript user guide
This guide describes lmscript 0.2.482. For a guided first session see the tutorial.
Overview
lmscript is a dynamically typed scripting language for automation. A script is a .lms text file run by the lmscript command. The language is deliberately small: statements, functions, lists and maps, a large standard library of plain functions, built-in blocks for CSV/JSON/TOML/properties/GraphQL/command data, and direct process execution without a shell.
Two properties shape how you work with it:
- Check before run. Every run first checks the whole script (syntax, undeclared names, wrong argument counts, unknown functions and methods, bad data blocks), including code in branches that will not run. Errors stop the script with exit code 2 before anything happens.
- Dry run on request. --dry-run executes the script in a simulation in which file writes, deletes and program runs are recorded instead of performed, and prints that record as a plan. A normal run does not do this: it checks and then runs once.
Scripts run with your full local permissions. There is no sandbox: run only scripts you trust.
Install
lmscript is in the npm package @lmctl-ai/lmctl, together with lmctl. It needs Node.js 24.15 or later.
npm install -g @lmctl-ai/lmctl
lmscript --version lmscript 0.2.482
Update with the same command; npm view @lmctl-ai/lmctl version shows the latest published version.
For GitHub host installation failures when installing a native host, see Troubleshooting GitHub host installation.
Troubleshooting GitHub host installation
A rate-limit error means the unauthenticated GitHub API allowance of 60 requests per hour per IP is exhausted. The message includes the reset time in local time, minutes remaining, GitHub rate-limit headers and whether a verified cached binary could be used. Set GITHUB_TOKEN to any valid token; no scopes are needed, and gh auth token prints one. Or pin an exact release tag such as github:lmctl-ai/lmmagnum@v0.1.0; a pinned host already in the verified cache needs no release lookup. You can also retry after the displayed reset.
A 403 that is not a rate limit includes GitHub's own message, such as abuse detection or organization access restrictions. A 404 can mean a typo in the public owner or repository, no published release, or a private repository; use GITHUB_TOKEN for private access. A 401 means GITHUB_TOKEN is invalid or expired. Never share the token value.
Download failures identify the asset and URL. Checksum failures show the expected and downloaded SHA-256 values; ask the tool owner to verify the asset and digest, and do not bypass verification. Network errors identify the URL and suggest checking network access, DNS, proxy and firewall. install= downloads a binary directly and does not extract archives. Unsupported platforms need a Linux, macOS or Windows x64 or arm64 host, or a matching release asset from the tool owner.
Concepts
- Script
- A UTF-8 text file, conventionally NAME.lms, run as lmscript NAME.lms [args…]. Top-level statements run in order; functions are hoisted.
- Check
- Static analysis of the whole file and its imports. Diagnostics have the form error:FILE:LINE:COLUMN: message.
- Dry run and plan
- A simulated execution, done only under --dry-run. Effects are recorded as dummy calls with typed placeholder results instead of being performed. The record is the plan.
- Strict access
- Reading a missing map key or list index is an error, not undefined. Use m.has(k), m.get(k, default) or l.get(i, default) when something may be absent.
- Module
- An lmscript file included with import; a file that starts with package NAME; exposes its functions as NAME.fn().
- Data block
- A marker such as _csv_ whose text body follows the statement and ends with end _csv_; the value is parsed data.
Reference
Command line
lmscript [OPTIONS] FILE [ARGS…] lmscript [OPTIONS] - [ARGS…] lmscript [OPTIONS] -e CODE [ARGS…]
Options go before the script; everything after FILE, - (read the script from standard input) or -e CODE is passed to the script in ARGV, including words that look like options.
| Option | Meaning |
|---|---|
| --check | Check only; run nothing. Exit 0 or 2. |
| --lint | Like --check. |
| --check-files | Also verify path literals (i"…", o"…") against the file system, read-only. |
| --dry-run | Check, then run only the simulation and print the plan on stdout; findings go to stderr. |
| --plan-format text|json | Plan format; accepted only together with --dry-run. |
| --dry-loop-limit N | With --dry-run, stop the simulation when a loop has entered its body N times; the plan status is loop-limited and the exit code 0. Without it, dry loops run in full. |
| --trace FILE | Write an execution trace to FILE. |
| --resumepoint PATH | Start a recover block at the named resume point. |
| --pref FILE | Overlay a TOML properties file on PROPS. |
| --base-dir DIR, --source-name LABEL | Import resolution base and the file name used in diagnostics (useful with - and -e). |
| --lmcode-signatures SCHEMA [--without-std] | Print a host schema's canonical signatures, with the standard catalog unless --without-std (see lmcode blocks). |
| --lmcode-schema SCHEMA [--without-std] [--json] | Print a schema summary, or the exact schema as JSON. |
| --saveas FILE | Listed in the usage line of lmscript --help. |
| install github:OWNER/REPO[@TAG] | Attended one-off install of a native host; also npm:@lmctl-ai/TOOL@VERSION|latest. |
| --version, -v | Print the version. |
| --help, --help NAME | List all functions by category and the topics, or explain one function, built-in or topic. |
Exit codes
| Code | Meaning |
|---|---|
| 0 | Success; also a dry run whose plan is complete, needs-real-result or loop-limited, including one that reached exit(N). |
| 1 | Run-time failure: a run-time error, a failed require or assert, recorded error() calls, an unknown option or other usage error, a script file that cannot be read. |
| 2 | Check error (syntax, undeclared name, bad block, removed import); also a dry run that fails before any simulated effect (PLAN failed). |
| N | exit(N) with N from 0 to 255. |
| 130 / 143 | Interrupted by SIGINT / SIGTERM. |
Syntax basics
- Every simple statement ends with ;: assignments, calls, let, return, break, continue, import, package, command statements. Blocks (if, while, for, fn) end with } and take no ;. A stray extra ; is an error.
- Every if/else/while/for body is a { … } block, even for one statement.
- Comments: # …, // … and /* … */.
- Identifiers: ASCII letters, digits and _, case-sensitive. Reserved words include fn function let if else while for return break continue true false null parallel sync import system cmd recover resumepoint.
- Numbers: 42, 1.5, .5; no exponent, hex or _ forms; - is an operator.
Values and types
| Value | Literal | type(x) |
|---|---|---|
| null | null | null |
| boolean | true, false | boolean |
| number (64-bit float) | 3, 2.5 | number |
| string | "a", 'a', f"…", r"…", """…""" | string |
| list | [1, "a", null], tuple (1, 2) | array |
| map | {name: "Ada", "key with space": 1} | object |
| function reference | a function's name, e.g. len | function |
Lists and maps are references: assigning one to another variable does not copy it. No trailing commas in list or map literals. Map keys are identifiers or plain strings; use m["if"] or m[k] for other keys. Keys are returned in JavaScript order: integer-like keys first in numeric order, then the others in insertion order.
False values are null, false, 0 and the empty string; empty lists and maps are true.
Strings
| Form | Behaviour |
|---|---|
| "text", 'text' | Plain string; \n \t \r \\ \" \' escapes. |
| f"Hi {name}" | Formatted: {expr} fields are checked expressions; {{ and }} give literal braces. Lists and maps insert as compact JSON. |
| r"C:\dir" | Raw: backslashes stay as written. |
| rf"…", fr"…" | Raw text with formatted fields. |
| """…""", '''…''' | Multi-line (also with f/r prefixes); no dedent. |
| i"in.txt", o"out.txt", io"f" | Path literals: a path the script reads, writes or both; checked to exist (or be writable) before the first statement runs. |
There are no heredocs. + concatenates (and converts the other operand to text); str(x) converts explicitly. expand(text, vars) fills ${name} placeholders from a map.
Operators
From lowest to highest precedence: assignment =; cond ? a : b; ||; &&; == !=; < <= > >=; + -; * / %; unary ! -; call, index and member access. Equality is strict (0 == false is false); lists and maps compare by identity. && and || return one of their operands (null || "x" is "x"). Division by zero is a run-time error. There is no ++, +=, **, bitwise or in operator.
Control flow
if (n > 10) {
println("big");
} else if (n > 0) {
println("small");
} else {
println("none");
}
while (queue_len > 0) { queue_len = queue_len - 1; }
for (let i = 0; i < 3; i = i + 1) { println(i); }
for (item in ["a", "b"]) { println(item); } # list values
for (key in {x: 1, y: 2}) { println(key); } # map keys
for (ch in "héllo") { println(ch); } # characters
break; and continue; act on the innermost loop. A for (x in …) loop iterates a snapshot of the sequence. Loops stop with an error after 1,000,000 iterations.
Functions and scope
fn area(w, h) {
return w * h;
}
println(area(3, 4));
op = area; # a function reference
println(op(2, 5));
- Functions are declared at top level only, with a fixed number of parameters; there are no anonymous functions or closures. A function without return returns null. Recursion depth is limited to 1000 calls.
- Assignments inside a function create local variables; they never change a global of the same name. Changing the contents of a list or map passed in does affect the caller.
- Blocks are scopes: a name first assigned inside an if or loop body does not exist after it (check error Undeclared variable). Assign it before the block.
- let x = …; declares explicitly (a second let x in the same scope is an error); let (a, b) = list; and [a, b] = list; destructure, filling missing values with null.
Lists, maps and methods
| Type | Methods |
|---|---|
| map | get(key, default), has(key), len(), keys() |
| list | get(index, default), len() |
| string | len() |
Everything else is a plain function: push(list, x), keys(m), contains(list, x), sort(list, "field"), set(m, "a.b", v). Writing a missing key creates it (m.k = v); reading one is an error that names the fix:
map user has no key "email"; test with user.has("email") or read user.get("email", default)
Modules and imports
# lib/textutil.lms
package textutil;
fn shout(s) { return upper(s) + "!"; }
# main.lms
import "lib/textutil.lms";
println(textutil.shout("hi"));
- import "path"; includes another lmscript file (relative to the importing file) or an https:// URL at that point. Each location loads once; import order matters (import a module before using it).
- Without package, the imported functions and variables are used unqualified. With package NAME; at the top, callers write NAME.fn().
- import "native:git"; is removed and is a check error (exit 2); call the tool with system, or use an lmcode host.
- JavaScript and npm packages cannot be imported.
Data blocks
rows = _csv_;
name,score
Ada,95
end _csv_
cfg = _toml_;
[server]
port = ${port}
end _toml_
| Marker | Value |
|---|---|
| _csv_ | List of maps (first line is the header) or, with heading=false, list of lists. Option delimiter=";". Numbers and true/false/null are typed. |
| _json_ | The parsed JSON value (strict JSON). |
| _toml_ | A map (TOML 1.0). |
| _props_ | A flat map of strings (Java properties). |
| _cmd_ | An argument list for system, one command spread over several lines. |
| _graphql_ | A GraphQL document as a string, syntax-checked. |
| Native block | Experimental: a compiled program for a native host (below). |
Rules: the statement ends with ; on the marker line; the body starts on the next line; the block closes with a line that is exactly end _csv_ (matching marker, column 1). Blank lines and lines starting with # are dropped. ${expr} inserts a value safely: it can never add rows, cells or quotes. All blocks are validated by the check, before anything runs.
Running programs
r = system git status --short; # run now, without a shell
if (r.code != 0) { exit(1); }
println(r.stdout);
argv = cmd git log -n ${count}; # build ["git","log","-n","5"]
r = system(argv, 10000); # computed argv, 10 s timeout
- system WORDS; runs a program and returns {stdout, stderr, code, signal, timed_out, duration_ms, pid}. A non-zero exit is data: check r.code.
- Words split on spaces; quotes group words; ${expr} inserts a value as one word, or a list as several words.
- Pipes, redirects, ;, globbing, ~ and $( ) are refused. For shell features run a shell explicitly: system(["bash", "-c", script]), passing data as extra arguments.
- Default timeout 60 s; output is limited to 10 MiB.
Standard library
lmscript help lists every function with its signature; lmscript help NAME explains one. Highlights by category:
| Category | Examples |
|---|---|
| Strings | split join trim upper lower replace replace_all starts_with ends_with contains index_of substring slice pad_start sprintf format words lines regex_test regex_match regex_find_all regex_replace |
| Lists | len push pop first last range sort reverse unique flatten chunk take drop sum avg enumerate concat |
| Maps and data | keys values get set has_key merge pluck filter_by find_by json_parse json_stringify |
| Files | read_file write_file append_file read_lines write_lines read_json write_json read_csv write_csv file_exists list_dir glob mkdir copy_file move_file delete_file path_join basename dirname temp_file |
| System | system env set_env which sleep_ms now date strftime exit require assert error warning |
| Output | println print printf (printf adds no newline) |
| Types | type str is_string is_number is_array is_map is_function is_empty is_blank |
With lmctl installed, the lm_* functions (for example lm_prompt) drive agent teams; see lmscript help lmctl.
Arguments, environment and properties
- ARGV: the list of words after the script name.
- env("NAME", default): an environment variable.
- PROPS.a.b: read-only properties from ~/.lmctl/init.toml (or $LMCTL_HOME/init.toml), overlaid by --pref FILE.
- Directory: the working directory.
Check, dry run and run in detail
A normal run is: check, then one real run. There is no silent dry pass before it: a script that prints, writes a file and then reads a missing map key prints, writes the file and stops at the error with exit code 1. The options --no-preflight, --dryrun-timeout and --module no longer exist; each is rejected as an unknown option with exit code 1.
--dry-run checks the script and then evaluates it with effects off. The first line of the plan gives the status. PLAN complete means the simulation reached the end or an exit(N); the exit code is 0 either way. PLAN needs-real-result means a fatal error came after a simulated effect, so the placeholder results may be the cause; it is reported as a warning and the exit code is 0. PLAN failed means a fatal error came before any simulated effect; the exit code is 2. PLAN loop-limited appears only with --dry-loop-limit N: the simulation stops at the loop and the statements after it are not simulated. There is no time limit and no default loop limit on a dry run. A plan is a prediction, not a proof: data read at run time can differ. --dry-run --plan-format json prints one JSON report on a single line (shown here indented):
lmscript --dry-run --plan-format json pj.lms
{
"version": 1,
"status": "complete",
"entries": [
{
"seq": 1,
"kind": "dummy",
"file": "/home/me/pj.lms",
"line": 1,
"column": 1,
"function": "write_file",
"arguments": [
"a.txt",
"x"
],
"simulated": true
}
],
"stop": null,
"diagnostics": []
}
Other features
- parallel([f(a), g(b)])
- Runs the calls concurrently and returns their results in order.
- recover { resumepoint NAME: … }
- Named entry points; --resumepoint NAME restarts a failed script from there. It saves no state.
- require(value, message)
- Returns value or stops with message (exit 1) when it is null or empty.
lmcode blocks for native hosts
An _lmcode_ block is not lmscript: its body is code in a small, statically typed language that lmscript compiles for a native host. The literal constructs an opaque immutable program and does not execute; only run_lmcode executes it. Hosts include lmhtml (HTML checking) and lmcad (3D shapes and images), built with the LMCode SDK family. The removed forms _dsl_, savedsl and dsl_cli are check errors in current lmscript.
check = _lmcode_ cli="lmhtml" install="github:lmctl-ai/lmhtml@latest";
let pages = html.load_dir("site");
for (i in range(0, pages.len())) {
let page = pages.at(i);
let links = page.links();
for (j in range(0, links.len())) {
let url = links.at(j);
if (!html.link_exists(page, url)) {
report.add("broken-link", page.path(), 0, url + " not found");
}
}
}
report.write_text("broken.txt");
end _lmcode_
r = run_lmcode(check);
require(r.ok, "host failed");
println(r.result);
- The header names the host: cli="lmhtml" finds the program, and the optional install="github:lmctl-ai/lmhtml@latest" (or npm:@lmctl-ai/TOOL@VERSION|latest) binds an installed binary. The header semicolon belongs to the literal, the body follows, and end _lmcode_ at column one closes it.
- lmscript --check links.lms compiles the block against the host schema. Check never starts the host for execution and never downloads.
- lmscript links.lms runs it: run_lmcode starts the host once and returns the whole envelope, {ok, result}. Here it prints null and the host writes broken.txt.
load_schema
load_schema(cli="PROGRAM") discovers the schema once and retains the host; load_schema(schema="FILE") creates a file-only descriptor, which needs an explicit command or builder host to run. The clauses must be literals, and cli and schema are exclusive. Use the descriptor as the block header: p = _lmcode_ s;. Inline cli/schema headers use the same resolver.
run_lmcode
Signature: run_lmcode(program_or_builder: lmcode, options?: map): map. For one program the options are args (a string list) and command (a string or argv list). The default argv is the retained host prefix, --lmcode, a private file, then args. An explicit command template has exactly one $DSLFILE outside argv[0]; there is no shell, glob or environment expansion. The call returns the terminal envelope, including controlled host failures, so test r.ok. Malformed frames or unexpected exits are located runtime errors. Under --dry-run the host is invoked once with dry metadata and its simulated envelope is recorded in PLAN as a dry host run (simulated).
lmcode_build
Signature: lmcode_build(host: lmcode schema | string | string list): lmcode_builder. The host is a host-bound load_schema descriptor or an explicit command prefix. builder.add(program, fragment=["--lmcode", "$DSLFILE"]) appends a program with one argv fragment and returns the builder. The first run seals the builder; the host processes all slots in one process and success is {ok: true, result: [...], parts: N}, even for one slot. The example passes a file-only fragment for the second program because lmhtml takes --lmcode FILE [FILE ...]; it prints 2 and [3,"two"].
s = load_schema(cli="lmhtml");
a = _lmcode_ s;
$return = 1 + 2;
end _lmcode_
b = _lmcode_ s;
$return = "two";
end _lmcode_
builder = lmcode_build(s);
builder.add(a);
builder.add(b, fragment=["$DSLFILE"]);
r = run_lmcode(builder);
require(r.ok, "host failed");
println(r.parts);
println(r.result);
The language inside the block:
- Statements: let x = expr; (type inferred), assignment, if/else, for (i in range(a, b)) (end excluded), for (item in collection), while with break; and continue;, switch on int, string or enum values without fallthrough, and calls. Every statement ends with ; and every body is a block.
- Top-level fn name(param: TYPE) -> TYPE definitions are type-checked and inlined; nested functions and recursion are rejected.
- Types: int, float (literals need a fraction: 1.0), string, bool, and the object types and enums the schema declares. Arithmetic never mixes int and float; float(i) converts. "a" + "b" concatenates strings; str(x) formats a primitive.
- The schema's context objects (for lmhtml: html and report), its functions and the standard catalog are the API. Collections are host objects with len() and at(i).
- ${expr} in the body splices an lmscript value as a typed literal: scalars, lists (qw, qi, qf) and homogeneous maps. Writing it inside a quoted string is a check error.
- Type errors are check errors at the exact position, before anything runs.
- The program value is opaque (type(p) is lmcode); it can be stored and passed to helpers but not serialized.
- Host protocol: hosts provide --lmcode-schema, --lmcode-schema --json, --lmcode-signatures and --lmcode FILE.dslb; run_lmcode drives it for you.
The host contract binds the exact schema bytes used to compile. The accepted schema is version 2 ("dsl.schema": 2) and bytecode version 6 is accepted by matching hosts.
Standard catalog: lmcode_std_v3 (226 signatures)
Besides the host's own types and context objects, every _lmcode_ block can call the standard catalog lmcode_std_v3. The current catalog has 226 canonical signatures (206 before the REST and CLI module was merged in; 72 in std v1). lmscript 0.2.482 adds exactly these 226 signatures when it compiles a block: lmscript --lmcode-signatures SCHEMA lists host plus standard signatures, and --without-std lists only the host's own.
The 20 newest signatures are the former lmcode_std_rest_v1 module: five functions and 15 RestExchange methods, together with 10 standard interfaces.
| Standard function | Signature | Purpose |
|---|---|---|
| rest_config | rest_config(string, string) -> void | Set one REST configuration value by name. |
| rest_route | rest_route(string, string, string) -> void | Register a route; route templates accept {param} and {rest...} as well as :param and :rest... placeholders. |
| rest_serve | rest_serve() -> void | Start serving the registered routes. |
| rest_stop | rest_stop() -> void | Stop serving. |
| rest_cli | rest_cli(StrList) -> string | Stateless CLI mode: dispatches options, commands and REST routes for one argv list without resetting the outer run state. |
| Standard interface | Role |
|---|---|
| RestGet, RestPost, RestPut, RestDelete, RestPatch, RestHead, RestOptions | One interface per HTTP method for REST endpoint handlers. |
| RestHandler | General REST handler interface. |
| CliCommand | A command of the stateless CLI dispatched by rest_cli. |
| CliOption | An option of the stateless CLI dispatched by rest_cli. |
| RestExchange method | Signature |
|---|---|
| method | RestExchange.method() -> string |
| path | RestExchange.path() -> string |
| param | RestExchange.param(string) -> string |
| query | RestExchange.query(string) -> string |
| has_query | RestExchange.has_query(string) -> bool |
| header | RestExchange.header(string) -> string |
| has_header | RestExchange.has_header(string) -> bool |
| body | RestExchange.body() -> string |
| get | RestExchange.get(string) -> string |
| set | RestExchange.set(string, string) -> void |
| increment | RestExchange.increment(string) -> int |
| status | RestExchange.status(int) -> void |
| set_header | RestExchange.set_header(string, string) -> void |
| send | RestExchange.send(string) -> void |
| json | RestExchange.json(string) -> void |
Whether a given host actually serves REST routes depends on that host and on the std release it vendors; check HOST --lmcode-signatures before relying on them.
Native host install cache
A declaration using install with @latest checks for a newer release at most once every six hours per exact install string. The verified binary and the last successful release check are stored in the lmscript tool cache. A fresh check uses the cached binary when GitHub is temporarily unavailable and prints a warning. An exact release tag needs no release lookup after its binary is cached and SHA-256 verified.
Set LMSCRIPT_INSTALL_CACHE_TTL_MS to a non-negative number of milliseconds to change the @latest check interval. Set it to 0 to check on every real run. Leave it unset for the six-hour default. CI jobs with fresh runners should pin an exact release tag so every run uses a deliberate release and does not depend on the mutable latest endpoint.
Tasks
Summarize a CSV file
rows = read_csv(i"sales.csv");
total = 0;
for (r in rows) { total = total + r.amount; }
write_json(o"summary.json", {rows: len(rows), total: total});
Run a tool and fail cleanly
r = system git rev-parse --short HEAD;
if (r.code != 0) {
println(f"git failed: {trim(r.stderr)}");
exit(1);
}
println(f"commit {trim(r.stdout)}");
Preview a destructive script
Run lmscript --dry-run script.lms and read the plan; then run it normally.
Run a one-liner
lmscript -e 'println(len(list_dir(".")));'
Limits
- No sandbox: scripts can read, write and run anything your user can.
- Loops: 1,000,000 iterations; call depth: 1000; program output captured by system: 10 MiB; default system timeout: 60 s.
- No classes, closures, anonymous functions, nested function declarations, ++ or compound assignment.
- Numbers are 64-bit floats (exact integers up to 2^53).
- A dry run has no default loop or time limit (--dry-loop-limit N sets a loop limit); it cannot predict data that only exists at run time.
- LMCode blocks are experimental.
Troubleshooting
- Expected ';' after the assignment; every statement ends with ';'
- Add the ; at the reported position. Blocks (}) take none.
- Undeclared variable 'x'
- The name is first assigned inside a block or misspelled. Assign it before the block.
- map m has no key "k"; …
- Use m.has("k") or m.get("k", default).
- Expected '{' after if (...); braces are required …
- Wrap the body in { }.
- A command with | or > is refused
- system runs no shell. Do the piping in lmscript or call bash -c explicitly.
- path literal i"x" (resolved ./x) does not exist
- The input file is missing relative to the working directory; this check runs before any effect.
- error: Unknown option --no-preflight (or --dryrun-timeout, --module)
- These options were removed. A normal run no longer does a dry pass, so there is nothing to skip or time out; delete the option.
- LMCode error, or the host says LOAD_SCHEMA_MISMATCH
- Recompile against the exact schema the host prints with --schema --json; the bytecode embeds the schema hash.