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:

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.

OptionMeaning
--checkCheck only; run nothing. Exit 0 or 2.
--lintLike --check.
--check-filesAlso verify path literals (i"…", o"…") against the file system, read-only.
--dry-runCheck, then run only the simulation and print the plan on stdout; findings go to stderr.
--plan-format text|jsonPlan format; accepted only together with --dry-run.
--dry-loop-limit NWith --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 FILEWrite an execution trace to FILE.
--resumepoint PATHStart a recover block at the named resume point.
--pref FILEOverlay a TOML properties file on PROPS.
--base-dir DIR, --source-name LABELImport 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 FILEListed 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, -vPrint the version.
--help, --help NAMEList all functions by category and the topics, or explain one function, built-in or topic.

Exit codes

CodeMeaning
0Success; also a dry run whose plan is complete, needs-real-result or loop-limited, including one that reached exit(N).
1Run-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.
2Check error (syntax, undeclared name, bad block, removed import); also a dry run that fails before any simulated effect (PLAN failed).
Nexit(N) with N from 0 to 255.
130 / 143Interrupted by SIGINT / SIGTERM.

Syntax basics

Values and types

ValueLiteraltype(x)
nullnullnull
booleantrue, falseboolean
number (64-bit float)3, 2.5number
string"a", 'a', f"…", r"…", """…"""string
list[1, "a", null], tuple (1, 2)array
map{name: "Ada", "key with space": 1}object
function referencea function's name, e.g. lenfunction

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

FormBehaviour
"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));

Lists, maps and methods

TypeMethods
mapget(key, default), has(key), len(), keys()
listget(index, default), len()
stringlen()

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"));

Data blocks

rows = _csv_;
name,score
Ada,95
end _csv_

cfg = _toml_;
[server]
port = ${port}
end _toml_
MarkerValue
_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 blockExperimental: 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

Standard library

lmscript help lists every function with its signature; lmscript help NAME explains one. Highlights by category:

CategoryExamples
Stringssplit 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
Listslen push pop first last range sort reverse unique flatten chunk take drop sum avg enumerate concat
Maps and datakeys values get set has_key merge pluck filter_by find_by json_parse json_stringify
Filesread_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
Systemsystem env set_env which sleep_ms now date strftime exit require assert error warning
Outputprintln print printf (printf adds no newline)
Typestype 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

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);
  1. 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.
  2. lmscript --check links.lms compiles the block against the host schema. Check never starts the host for execution and never downloads.
  3. 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:

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 functionSignaturePurpose
rest_configrest_config(string, string) -> voidSet one REST configuration value by name.
rest_routerest_route(string, string, string) -> voidRegister a route; route templates accept {param} and {rest...} as well as :param and :rest... placeholders.
rest_serverest_serve() -> voidStart serving the registered routes.
rest_stoprest_stop() -> voidStop serving.
rest_clirest_cli(StrList) -> stringStateless CLI mode: dispatches options, commands and REST routes for one argv list without resetting the outer run state.
Standard interfaceRole
RestGet, RestPost, RestPut, RestDelete, RestPatch, RestHead, RestOptionsOne interface per HTTP method for REST endpoint handlers.
RestHandlerGeneral REST handler interface.
CliCommandA command of the stateless CLI dispatched by rest_cli.
CliOptionAn option of the stateless CLI dispatched by rest_cli.
RestExchange methodSignature
methodRestExchange.method() -> string
pathRestExchange.path() -> string
paramRestExchange.param(string) -> string
queryRestExchange.query(string) -> string
has_queryRestExchange.has_query(string) -> bool
headerRestExchange.header(string) -> string
has_headerRestExchange.has_header(string) -> bool
bodyRestExchange.body() -> string
getRestExchange.get(string) -> string
setRestExchange.set(string, string) -> void
incrementRestExchange.increment(string) -> int
statusRestExchange.status(int) -> void
set_headerRestExchange.set_header(string, string) -> void
sendRestExchange.send(string) -> void
jsonRestExchange.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

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.