lmscript reference

Generated from lmscript 0.2.482: the built-in functions come from lmscript --help, the standard lmcode signatures from lmscript --lmcode-signatures, and the interfaces from the lmcode_std_v3 schema. See the user guide for the language and the skill for a compact summary.

Command line

lmscript [--check|--dry-run|--lint] [--trace FILE] [--dry-loop-limit N] [--plan-format text|json] [--resumepoint PATH] [--pref FILE] [--check-files] [--base-dir dir] [--source-name label] [--saveas FILE] <file>|http(s)://.../x.lms|-| -e <code> [args...]
lmscript install github:OWNER/REPO[@TAG] | npm:@lmctl-ai/TOOL@VERSION|latest
lmscript --lmcode-signatures SCHEMA [--without-std]
lmscript --lmcode-schema SCHEMA [--without-std] [--json]
Flag or formMeaning
--checkStatic check only, including compiling _lmcode_ blocks; never starts a host.
--dry-runChecks, then evaluates with effects off and prints PLAN; a reached run_lmcode starts the host once with dry metadata.
--lintStops after checking, like --check.
--trace FILEWrites an execution trace to FILE.
--dry-loop-limit NLoop iteration limit for the dry run.
--plan-format text|jsonPlan format for --dry-run.
--resumepoint PATHStart at a named resume point of a recover block.
--pref FILEProperties file.
--check-filesAlso verify path literals against the file system.
--base-dir dirBase directory for relative paths.
--source-name labelSource label used in diagnostics.
--saveas FILEDownload a remote .lms URL to FILE instead of running it; refused with exit 2 beside --check, --lint, --check-files or --dry-run.
<file> | http(s)://.../x.lms | - | -e <code> [args...]Script source: file, URL of an .lms file, standard input or inline code; the words after it are script arguments.
lmscript install github:OWNER/REPO[@TAG] | npm:@lmctl-ai/TOOL@VERSION|latestExplicit install of a native lmcode host from a GitHub release or a pinned npm package.
lmscript --lmcode-signatures SCHEMA [--without-std]Print the canonical signatures of a host schema, with or without the standard catalog.
lmscript --lmcode-schema SCHEMA [--without-std] [--json]Print a schema summary, or the normalized schema as JSON.
lmscript --help [NAME]List all functions and topics, or explain one function, built-in or topic.
lmscript --versionPrint the version.

Exit codes

Exit codeMeaning
0Success.
1Ordinary runtime failure, for example a failed require or a failed fetch of a remote script.
2Static check failure or refused flag combination; nothing ran.

Built-in functions

255 functions in 20 categories, as listed by lmscript 0.2.482. The description column is filled where the standard library reference documents the function.

Agents (agent)

SignatureDescription
agent_close(agent, [status])Closes an open agent and releases its lease; idempotent. Scope exit, recorded errors, exit and signals also close it.
agent_compact(agent, [options])Compacts an embedded conversation to its budget now (or to target_tokens), dropping the oldest exchanges and recording a compaction marker; a CLI tool manages its own context and answers status unsupported.
agent_history(agent, [options])The transcript of an open agent: the provider session reader (the lmctl tail path) for CLI tools, the native store for embedded models. Roles: user, assistant, system, tool_use, tool_result, thinking; kind compaction_summary marks a compaction marker.
agent_info(agent)State of an open agent without side effects: kind, provider, model, session_id, cwd, label, turns, pending_tools, context (managed_by host|provider, input_tokens_last, budget, compacted, estimated, compactions) and the accounting totals of its turns in this run.
agent_models(provider, [options])Model ids for one provider: the embedded provider's /models endpoint, or the known model list of a CLI tool (codex, agy, claude, kimi). Other CLI tools give ok:false with error.code unsupported.
agent_open(spec, [options])Opens a conversation with a CLI coding tool or an embedded model without a teamfile. spec: provider (required), model, kind, cwd, session_id (resume), label; embedded only: system, tools ("none" | "script" | {script:[declarations]} | {root, write, web, shell}), context {max_input_tokens, reserve_output_tokens, strategy: truncate_oldest|summarize|fail}, persist: full|none; CLI only: effort, permission: yolo|plan. A key the kind cannot honour is an author error. Returns an opaque resource handle owned by its first receiving binding, or null after writing the admission failure (busy, not found, provider down) to stderr. Dry run returns null without any effect.
agent_prompt(spec, prompt, [options])One shot: agent_open, one agent_turn, agent_close. The result carries session_id so the conversation can be resumed later with agent_open({... session_id}) or another agent_prompt. Admission failures come back as status busy or error rather than null.
agent_providers([options])The one catalog of agent providers: CLI coding tools (kind cli) and in-process embedded models (kind embedded) side by side, with transport, default model and capabilities. key_set (embedded) and binary_found (cli) are probed lazily in a real run and are null in dry run or with probe: false.
agent_tool_result(agent, results, [options])Answers a tool_request turn (tools_mode script): results is a list of {id, ok, data | error} covering exactly the pending calls; the same turn and the same turn_id finish. A wrong or missing id is error/invalid_argument and sends nothing.
agent_turn(agent, prompt, [options])Sends one user turn on an open agent and waits for the reply. The host owns the conversation: a CLI tool keeps its native session, an embedded model keeps the message list, runs granted tools and compacts the context to its budget. Exactly one accounting row (the turn_id) is written with the four token buckets and the saved price; usage and cost come back in the result. World failures are data (status != "ok"); a closed handle is error/invalid_argument.
agent_usage([options])Read-only accounting of agent turns from the same turn_usage view lmctl usage reads: this run by default (scope run), or every direct turn (scope all) narrowed by session_id, provider or since. A turn with unknown usage makes the affected total null and counts in unknown_turns.

Agent Files (core)

SignatureDescription
format_file_blocks(files: array): stringInverse of parse_file_blocks (round-trips content ending in a newline); fence-wrapped content gets a longer outer fence.
kv_from_last_paragraph(text: string): mapkey: value lines of the last paragraph; last key wins, non-pairs ignored, missing keys absent. Up to 3 trailing paragraphs without pairs are skipped as chatter; a file-block marker stops the scan.
parse_file_blocks(text: string): array=== FILE: rel/path === to === END === blocks as [{path, content}]; prose and marker-line whitespace ignored; one wrapping fence stripped; content ends in a newline; a block without END (truncated, or interrupted by the next FILE marker) is dropped. See help agent-files.
read_tree(dir: string, [options: map]): arraySorted text files relative to dir; skips symlinks, binary/non-UTF-8, files over an explicitly supplied maxBytes and .git, node_modules, dist, build, target, .mp, __pycache__, *.lock, package-lock.json. Options ignore/include/maxBytes; missing dir gives [].
split_command(text: string): arrayPOSIX quoting into argv for system(); unquoted | & ; < > ( ) $, $/ in double quotes, word-start #, newline or NAME=value prefix are errors (shell:false). Globs and ~ stay literal.
write_files(dir, files)Writes under dir (created) via temp + rename, keeping a replaced file mode. Rejects empty/absolute/backslash/.. paths, any .git segment, symlink targets and paths through a symlink leaving dir. Language dry run: skipped with {}, without classifying paths or creating files.

Database (core)

SignatureDescription
sql_exec(path: string, sql: string, [params: array|map]): mapRuns ONE write statement against a local SQLite file (created if missing; refuses the lmctl state database) and returns {changes, last_insert_rowid}. Literal SQL, bound parameters.
sql_read(path: string, sql: string, [params: array|map]): arrayRuns ONE SELECT against a SQLite file opened read-only and returns the rows as a list of maps. The SQL must be a string literal; values are bound parameters (list for ?, map for :name), never text.

File I/O (core)

SignatureDescription
abs_path(filePath: string): stringResolves a path to an absolute path
append_file(path: string, content: any): booleanAppends string content to file
basename(filePath: string, [ext: string]): stringReturns the last path segment, optionally stripping a trailing extension
copy_file(src: string, dest: string): booleanCopies a file to a new path
csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): arrayParses inline CSV text into records or rows. Typed cells: a trimmed -?digits or -?digits.digits cell becomes a number (007 becomes 7), true/false/null in any case become those values; other cells stay text; a missing trailing column is null.
csv_stringify(data: array, [delimiter: string = ","]): stringSerializes records or rows to CSV text
dirname(filePath: string): stringReturns the directory portion of a path
file_exists(path: string): booleanChecks if file exists
glob(pattern: string): arrayFinds files matching a glob pattern and returns an array of matching paths
list_dir(path: string): arrayLists filenames in a directory
lmcode_build(host: lmcode schema | string | string list): lmcode_builderCreates an opaque run-local lmcode builder
mkdir(dirPath: string, [recursive: boolean = true]): booleanCreates a directory (recursive by default)
move_file(src: string, dest: string): booleanMoves/renames a file
path_join(...parts: string): stringJoins path segments using the OS-native separator
read(path: string): stringReads entire file as UTF-8 string
read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): arrayReads CSV file and parses into array of objects or rows. Typed cells: a trimmed -?digits or -?digits.digits cell becomes a number (007 becomes 7), true/false/null in any case become those values; other cells stay text; a missing trailing column is null.
read_file(path: string): stringReads entire file as UTF-8 string
read_json(path: string): anyReads file and parses JSON content
read_lines(path: string): arrayReads file as an array of string lines
rmdir(dirPath: string, [recursive: boolean = false]): booleanRemoves a directory; pass true for recursive removal of a non-empty directory
run_lmcode(program_or_builder: lmcode, options?: map): mapExecutes an opaque lmcode program or sealed builder; dry calls require dry-marked preview envelopes and record simulated PLAN data
temp_file(): stringCreates an empty temporary file and returns its absolute path; caller deletes it
write(path: string, content: any): booleanWrites string content to file
write_csv(path: string, data: array, [delimiter: string = ","]): booleanWrites array of objects or rows to CSV file
write_file(path: string, content: any): booleanWrites string content to file
write_file_exclusive(path: string, content: any): booleanCreates a new file; refuses to overwrite an existing path
write_json(path: string, data: any, [indent: number = 2]): booleanSerializes data and writes formatted JSON to file
write_lines(path: string, lines: array): booleanWrites an array of lines to a file with trailing newline

JSON & Data (core)

SignatureDescription
filter_by(arr: array, key: string, value: any): arrayFilters array of objects where item[key] == value
find_by(arr: array, key: string, value: any): anyFinds first object in array where item[key] == value
json_parse(str: string): anyParse JSON text.
json_parse_safe(str: string, [fallback: any = null]): anyParse with fence/preamble recovery; fallback if invalid.
json_stringify(val: any, [indent: number = 0]): stringSerializes value into JSON string
json_validate(val: any, schema: map): mapValidate value against JSON-Schema subset (type, properties, required, enum, items, minimum/maximum, minLength/maxLength, additionalProperties:false). Returns {ok, errors}.
pluck(arr: array, key: string): arrayExtracts key from array of objects
xml_attr(node, name, fallback=null)Look up an unqualified or {URI}local attribute, with optional fallback.
xml_children(node)Return a native XML element's ordered child array; operate on Data.value() copies.
xml_select(tree, selector)Select native XML nodes by *, local tag, .class or #id; returns references inside the supplied copy.
xml_text(node)Concatenate descendant XML text in document order, excluding comments.

Language Constructs (core)

Signature
break
continue
fn name(arg1, arg2) { ... }
for (x in expr) { ... }; for (init; condition; update) { ... }
if (condition) { ... } else { ... }
import "path"
parallel([ call1(), call2() ])
parallel_map(items, fn[, limit])
return expr
sync expr
while (condition) { ... }

Lists & Arrays (core)

SignatureDescription
avg(arr: array): numberCalculates average of array
chunk(arr: array, size: number): arrayPartition into lists; size<=0 gives [].
compact(arr: array): arrayRemove null elements only; retain false/0/empty text.
concat(first: array, ...more: array): arrayConcatenates arrays
drop(arr: array, n: number): arrayReturn suffix; negative start clamps to 0.
enumerate(arr: array): arrayReturns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).
first(arr: array): anyReturns first element
flatten(arr: array): arrayFlattens array one level
insert(arr: array, index: number, item: any): arrayInserts item at index and returns the same array
last(arr: array): anyReturns last element
len(item: any): numberReturns length of string, array, or object
pop(arr: array): anyPops item from end of array
push(arr: array, ...items: any): arrayPushes item(s) to end of array and returns the same array
range(start: number, [end: number], [step: number = 1]): arrayGenerates an array of numbers
remove_at(arr: array, index: number): anyRemoves element at index
reverse(arr: array): arrayReturns reversed array
shift(arr: array): anyRemoves and returns first element
sort(arr: array, [key: string]): arraySorts array numerically, alphabetically, or by object key
sum(arr: array): numberCalculates sum of array
take(arr: array, n: number): arrayReturn prefix; negative n gives [].
unique(arr: array): arrayRemoves duplicate elements
unshift(arr: array, ...items: any): arrayAdds item(s) to front of array and returns the same array
zip(arr1: array, arr2: array): arrayCombines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].

Maps & Key-Value (core)

SignatureDescription
clone(val: any): anyDeep clones an object or array
delete_key(obj: object, key: string): objectDeletes key from object
entries(obj: object): arrayReturns array of [key, value] pairs
from_entries(pairs: array): objectCreates map from [key, value] pairs
get(obj: any, path: string|array, [defaultVal: any]): anySafely extracts nested property by path (e.g. 'user.address.city')
getbool(obj: any, path: string|array, [fallback: boolean = false]): booleanReads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null
getlist(obj: any, path: string|array, [fallback: array = []]): arrayReads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array
getnum(obj: any, path: string|array, [fallback: number = 0]): numberReads a numeric field from a map/request form; fallback (default 0) when missing or null
getstr(obj: any, path: string|array, [fallback: string = ""]): stringReads a string field from a map/request form; fallback (default "") when missing or null (never the string "null"). A distinguishable non-"" fallback (e.g. "?") tells "missing" apart from a real empty string.
has_key(obj: object, key: string): booleanChecks if object has key
items(obj: object): arrayReturns array of [key, value] pairs (alias for entries)
keys(obj: object): arrayReturns array of object keys
merge(a: object, b: object): objectShallow merges two objects
set(obj: object, path: string|array, value: any): objectSets nested property by path
values(obj: object): arrayReturns array of object values

Math (core)

SignatureDescription
abs(n: number): numberAbsolute value
ceil(n: number): numberCeil value
clamp(val: number, low: number, high: number): numberRestricts a numeric value to lie within [low, high] bounds.
floor(n: number): numberFloor value
max(...nums: number|array): numberMaximum value
min(...nums: number|array): numberMinimum value
num(val: any): numberConverts value to number
pow(base: number, exp: number): numberPower calculation
random(): numberRandom float between 0 and 1
round(n: number): numberRound value
sqrt(n: number): numberSquare root

Math & Utilities (core)

SignatureDescription
sha256(text: string): stringReturns lowercase SHA-256 of UTF-8 text; strings only

Properties (core)

SignatureDescription
get_properties([prefix])Read or overlay hierarchical run-local properties; no persistence
get_property(key, [default])Read or overlay hierarchical run-local properties; no persistence
has_property(key)Read or overlay hierarchical run-local properties; no persistence
set_property(key, value)Read or overlay hierarchical run-local properties; no persistence

Strings (core)

SignatureDescription
char_at(s: string, index: number): stringUTF-16 code unit text; out of range gives empty string.
char_code(s: string, [index: number = 0]): numberUTF-16 code unit number; out of range gives NaN.
contains(haystack: string|array, needle: any): booleanChecks if string or array contains item
count_matches(s: string, sub: string): numberCount non-overlapping substrings; empty needle gives 0.
ends_with(s: string, suffix: string): booleanChecks if string ends with suffix
endswith(s: string, suffix: string): booleanChecks if string ends with suffix (alias for ends_with)
expand(text, [vars])Expand simple references from explicit vars, PROPS paths and invocation ARGV; inserted text is opaque
format(template: string, ...args: any): stringFormats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution
from_char_code(...codes: number): stringReturns string from character codes
includes(haystack: string|array, needle: any): booleanChecks if string or array contains item
index_of(haystack: string|array, needle: any, [fromIndex: number]): numberFinds substring or strictly equal array element index; -1 if absent
is_alnum(s: string): booleanNonempty ASCII letters/digits.
is_alpha(s: string): booleanNonempty ASCII alphabetic text.
is_blank(s: any): booleanReturns true if string is null, empty, or whitespace only.
is_digit(s: string): booleanNonempty ASCII digit text.
is_empty(val: any): booleanLiteral emptiness: null, empty string, empty array or empty map; whitespace-only strings are not empty. Use is_blank for whitespace.
join(arr: array, [separator: string]): stringJoin list values; default separator is comma-space; non-list becomes String(value).
last_index_of(haystack: string|array, needle: any): numberFinds last substring or strictly equal array element index; -1 if absent
last_line_as_status(s: string): string|nullReturns the state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER) from the last 3 non-blank lines of a string, or null if absent or conflicting
lines(s: string): arraySplits string into array of lines
lower(s: string): stringConverts string to lowercase
lstrip(s: string): stringTrims leading whitespace (alias for trim_start)
pad_end(s: string, targetLength: number, [padChar: string = " "]): stringRight-pads string
pad_start(s: string, targetLength: number, [padChar: string = " "]): stringLeft-pads string
pos([s: string|number|null], [offset: number|null]): numberReads or sets the Perl-like stateful regex match offset (0-based UTF-16 units, isolated per run and parallel task)
regex_find(s: string, pattern: string, [flags: string]): string|nullReturns first matched substring or null; g retains first-match shape, y is rejected
regex_find_all(s: string, pattern: string, [flags: string]): arrayReturns capture arrays with Unicode-aware zero-width progress; y is rejected
regex_find_pos(s: string, pattern: string, [flags: string]): string|nullMatches substring at pos(s) (sticky by default, or from pos(s) with g), advancing pos(s) after non-empty matches and leaving pos(s) unchanged on failure. An empty match consumes no input and leaves pos(s) at the match offset and a second empty match at that offset is refused (null/false; g resumes one unit or u/v code point later); Unicode matches never rewind the cursor
regex_match(s: string, pattern: string, [flags: string]): array|nullReturns first full match and captures; g retains first-match shape, y is rejected
regex_match_pos(s: string, pattern: string, [flags: string]): array|nullMatches at pos(s) (sticky by default, or from pos(s) with g), advancing pos(s) after non-empty matches and leaving pos(s) unchanged on failure. An empty match consumes no input and leaves pos(s) at the match offset and a second empty match at that offset is refused (null/false; g resumes one unit or u/v code point later); Unicode matches never rewind the cursor
regex_matches(s: string, pattern: string, [flags: string]): arrayReturns flat array of matched substrings with Unicode-aware zero-width progress; y is rejected
regex_replace(s: string, pattern: string, replacement: string, [flags: string]): stringReplaces matches using JavaScript regex replacement semantics
regex_test(s: string, pattern: string, [flags: string]): booleanTests a JavaScript regular expression against text
regex_test_pos(s: string, pattern: string, [flags: string]): booleanTests pattern at pos(s) (sticky by default, or from pos(s) with g), advancing pos(s) after non-empty matches and leaving pos(s) unchanged on failure. An empty match consumes no input and leaves pos(s) at the match offset and a second empty match at that offset is refused (null/false; g resumes one unit or u/v code point later); Unicode matches never rewind the cursor
repeat(s: string, count: number): stringRepeats string count times
replace(s: string, search: string, replacement: string): stringReplaces first occurrence
replace_all(s: string, search: string, replacement: string): stringReplaces all occurrences
reverse_str(s: string): stringReverse UTF-16 code units (not code points).
rstrip(s: string): stringTrims trailing whitespace (alias for trim_end)
set_pos(s_or_offset: string|number|null, [offset: number|null]): numberSets or resets the stateful regex match offset and returns the new offset
slice(target: string|array, start: number, [end: number]): string|arraySlices string or array
split(s: string, delimiter: string): arraySplits string by required delimiter; use explicit empty delimiter for characters
split_regex(s: string, pattern: string, [flags: string]): arraySplits text at regular expression matches
sprintf(template: string, ...args: any): stringFormats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax
starts_with(s: string, prefix: string): booleanChecks if string starts with prefix
startswith(s: string, prefix: string): booleanChecks if string starts with prefix (alias for starts_with)
strip(s: string): stringTrims whitespace from both ends (alias for trim)
substr(s: string, start: number, [length: number]): stringReturns substring by end-relative start and optional length
substring(s: string, start: number, [end: number]): stringReturns substring between indices
title_case(s: string): stringUppercase ASCII word-initial characters; does not lowercase the tail.
to_lower(s: string): stringConverts string to lowercase
to_upper(s: string): stringConverts string to uppercase
trim(s: string): stringTrims whitespace from both ends
trim_end(s: string): stringTrims trailing whitespace
trim_start(s: string): stringTrims leading whitespace
upper(s: string): stringConverts string to uppercase
upper_first(s: string): stringUppercase first UTF-16 code unit; retain tail.
words(s: string): arraySplits string into words

System & Process (core)

SignatureDescription
args_parse(argv, flags, [usage])Parses declared long options without effects; returns values, args, provided, help and help_requested
assert(condition: any, [message: string]): booleanThrows error if condition is falsy
cmd_render(argv, [dialect])Renders argv as posix, windows or powershell text; execution never uses rendered text
coalesce(...values: any): anyReturns the first non-null/non-undefined argument, else null
date([epochMs: number]): stringReturns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp
env(name: string, [fallback: any = null]): anyReads an environment variable, or a fallback if unset
error(value, ...values)Formats and logs an error to stderr and records it for the execution error summary
exit([code: number = 0]): neverTerminates script execution with an optional exit code (default: 0)
getenv(name: string, [fallback: any = null]): anyReads an environment variable, or a fallback if unset (alias for env)
http_get(url)Downloads UTF-8 text from a public HTTP(S) URL
if_else(cond: any, thenVal: any, elseVal: any): anyEager JS-truthiness choice; use ?: for lazy selection.
if_null(val: any, fallback: any): anyReturns fallback if value is null/undefined, else value
is_array(val: any): booleanChecks if value is an array
is_function(val: any): booleanChecks if value is a first-class function reference
is_map(val: any): booleanChecks if value is a map/object
is_number(val: any): booleantypeof number predicate; includes NaN/Infinity.
is_string(val: any): booleanChecks if value is a string
now(): numberReturns current epoch in ms
print(...values)Prints formatted values to output log
printf(format, ...values)Formats %s, %d, %f and %% with the sprintf rules and writes exactly that text to stdout (no newline added)
println(...values)Prints line to output log
prompt_human_config([config: map|string], [dir: string]): mapConfigures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms)
require(value: any, message: string): anyRequires a present value; injected diagnostic/captured error and exit 1 on missing
set_env(name: string, value: any): booleanSets an environment variable for this run (isolated per parallel/parallel_map task): env()/getenv() and later system() calls, command literals, which(), run_script children and lm_* provider calls see it; null unsets the name, including an inherited value
sleep_ms(ms: number): voidSleeps for the specified milliseconds
str(val: any): stringConverts lists and maps to compact JSON; scalars to normal text
strftime(epochMs: number, fmt: string): stringFormats local time: epoch milliseconds first, format string second
system(argv: array, [timeoutMs: number = 0 | options: map]): SystemResultExecutes argv directly with shell:false and optional timeoutMs (default 0, no deadline) or options {cwd, timeoutMs, stdin}, returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}
timestamp(): numberReturns current Unix epoch in whole seconds
type(val: any): stringReturns runtime type of value
warning(message: any): stringAdds a located non-failure warning
which(name: string): string|nullFinds the first executable path without spawning

Templates (core)

SignatureDescription
template_extract(pattern, data)Pure tree projection over parsed JSON-like values; returns {matched,value,candidate,error}; no-match is data, not an exception.
template_extract_first(patterns, data)Validate a nonempty candidate list and return the first matching projection as {matched,value,candidate,error}; failure records stay ordered.
template_extract_text(template, text)Exact whole-string extraction with simple ${name} holes, anchored suffix and earliest separators; returns {matched,value,candidate,error}.

Uncategorized (core)

SignatureDescription
array(...args)Creates a new list/array
clear(arg1)Clears array or map
delete_file(arg1)Deletes file if it exists
hash()Creates a new empty map/hash
list(...args)Creates a new list/array
map()Creates a new empty map/hash
remove_file(arg1)Deletes file if it exists
size(arg1)Returns number of elements in array, string, or map

LLM (llm)

SignatureDescription
llm_models(provider, options)Fetches the list of model IDs available for a provider (ollama-cloud, openrouter, deepseek, zai-coding-plan, anthropic) and returns a normalized response map with sorted model IDs. Returns {ok, provider, models:[string ids sorted], count, error:null|{code,message,http_status}, dry_run, latency_ms}. World failures return ok:false with error:{code, message, http_status}. Scripts must inspect r.ok.
llm_prompt(model, prompt, options)Sends a single prompt to a provider model (ollama-cloud, openrouter, deepseek, zai-coding-plan, anthropic) and returns a normalized response map. Returns {ok, text, provider, model, response_model, finish_reason, usage:{input_tokens, output_tokens, total_tokens}, latency_ms, id, error, dry_run, attempts}. World failures return ok:false with error:{code, message, http_status}. Scripts must inspect r.ok.
llm_providers(): listReturns the list of registered LLM providers and their metadata. Returns list of {id, label, key_env, key_set: boolean|null, default_model, models: boolean, reasoning_min_tokens: number|null, max_output_tokens: number|null}. Pure catalog query; dry run returns key_set:null without reading env.

Storage (lmbee)

Signature
lmbee_job_claim(options)
lmbee_job_read(options)
lmbee_job_write(options)

Host Functions (lmctl)

SignatureDescription
run_script(...)Run child in-process with inherited binding, properties and cancellation.

lmctl Automation (lmctl)

SignatureDescription
lm_batch_close(handle, status = "done", error = null)Closes an active teamfile batch resource; scope exit, script error, exit, and signals also close it. Tracked-invocation and bundle cleanup run on close.
lm_batch_open(teamfile, alias, batchfile, options = {})Opens the only returned production resource: an async-only opaque read-only id handle. The first receiving lexical binding owns it until scope exit; aliases borrow, and returning/storing/coercing the handle is refused at runtime. Teamfile batches keep existing admission. A provider session without a teamfile is opened with agent_open (or agent_prompt for one turn), not here. Dry-run skips resource operations with typed dummies (factories return null), without provider or lease activity.
lm_batch_turn(batch, prompt, [index], [total])Runs one prompt of a teamfile batch; index and total are required. Dependent conversational turns on a provider session go through agent_turn.
lm_classify_failure(text, [options])Classifies a recorded provider failure text with the same classifier lm_prompt uses for live turns, so a script reading stored errors (for example tracked_invocation.error) never carries its own regex table. Pure: no database, provider or file access. Text no rule recognises is unknown, never the nearest class.
lm_error(value, ...args)Writes error messages to standard error prefixed with 'error: '.
lm_exit(code = 0)Immediately terminates script execution with the specified integer exit code (0-255).
lm_lint(teamfile)Validates a teamfile over the exact same internal path lmctl lint takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI's own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.
lm_log(value, ...values)Writes formatted log messages to standard error with trailing newline.
lm_member(teamfile, alias)Resolves a specific member in a team configuration file.
lm_members(teamfile)Resolves all team members declared in a team configuration file.
lm_prompt(teamfile, alias, prompt, [options])Sends a direct one-shot prompt to a team member and returns an ordinary result map. The host owns its pending per-turn lease and critical release; no returned resource or script closer.
lm_ratelimit_readings([options])Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.
lm_read_paragraphs(batchfile)Reads a prompt file and splits it into blank-line-separated paragraphs.
lm_read_prompts(batchfile, [single])Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.
lm_running([options])Returns active tracked-invocation snapshot. Options: since (e.g. "1h", "2d") and reconcile (boolean, default false). reconcile:true may mutate tracked invocations by reconciling verified dead holders; the default is read-only. Dispatch and branch on status busy, never gate on this.
lm_seed(teamfile, [options])Seeds a real teamfile over the exact same internal path lmctl seed takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. lmctl seed itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.
lm_session_delete(member, [options])Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.
lm_session_get(target)Reads native session messages. Returns messages in chronological order (tool_use and tool_result entries carry tool_name and tool_call_id when the provider records them), or not_found if the session does not exist.
lm_session_list([options])Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.
lm_terminal(teamfile, alias)Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. The host attempts checked lock/invocation release on completion, failure, cancellation or signal and reports unresolved failures, including a busy database; the returned outcome is an ordinary map. Refuses non-interactive mode.
prompt_human([question|session])Reads an operator answer or hands off a session. Accepts one optional question/session value; non-interactive mode refuses the operation. A handoff reservation is host-owned and released on EOF, provider failure, cancellation, context finalization or signal; the returned outcome is an ordinary map. Core prompt options apply only without this binding.

Tools (tools)

SignatureDescription
tool_call(name, args, [options])Executes a single tool call with workspace containment and error-as-data return. Returns {ok, tool, data, error, text, dry_run}. World failures return ok:false with error:{code, message}. text is compact JSON for the model.
tool_parse(text)Extracts a tool call request from model output text. Returns {ok: bool, name: string|null, args: map|null, error: string|null}.
tool_specs([options])Returns OpenAI-compatible JSON Schema tool specifications for tools enabled by the given options.

lmcode blocks and execution

An _lmcode_ block constructs an opaque immutable program of type lmcode; it does not execute. The block ends with end _lmcode_ and runs only through an explicit run_lmcode call.

Header attributeMeaning
schema=Path of the host schema JSON file that the body is type-checked against; a schema handle from load_schema can be used in its place.
cli=Command that runs the host; binds the executable used by run_lmcode. A file-only schema requires an explicit command or a builder host.
install=Where to fetch the native host: github:OWNER/REPO@TAG or npm:@lmctl-ai/TOOL@EXACT_VERSION|latest. Check and dry run never download.
with=[...]Optional list of Data toLmcode fragments prepended to the body; may appear in either order with schema and cli.
FunctionReturnsDescriptionExample
run_lmcode(program_or_builder: lmcode, options?: map): mapmapRuns one opaque lmcode program or one sealed builder in a single host process. Single results are {ok,result}; builder results are {ok,result:[...],parts}. Args are copied; command is single-program only. Returns validated success/failure envelopes. Check never executes; dry invokes the host once with dry metadata and records its simulated envelope in PLAN.r = run_lmcode(program); require(r.ok, "host failed");
lmcode_build(host: lmcode schema | string | string list): lmcode_builderlmcode_builderCreates a run-local one-process builder for lmcode programs. host is a host-bound load_schema descriptor or an explicit command prefix string/list; add programs with one $DSLFILE fragment each, then pass the builder to run_lmcode.builder = lmcode_build(schema); builder.add(program); result = run_lmcode(builder);

run_lmcode options and result frame

ItemMeaning
options.argsString list appended to the host argv; copied, literal data, no shell, glob or environment expansion.
options.commandString or argv list, single program only: a complete command template with exactly one $DSLFILE outside argv[0].
default argvThe retained host prefix, --lmcode, a private file, then args.
builder.add(program, fragment=["--lmcode", "$DSLFILE"])Appends a program plus one argv fragment containing exactly one $DSLFILE and returns the same builder; the first run seals the builder.
single program result{ok:true, result:PAYLOAD}
builder result{ok:true, result:[...], parts:N}, even for a one-slot builder; each result is checked against the schema contract of its slot.
controlled failureReturned as data with ok false (optional validated part for builders); malformed frames, unexpected exits or mismatched envelopes are located runtime errors.
--checkNever starts hosts.
--dry-runStarts the host once with dry:true metadata and records its simulated envelope in PLAN as lmcode-host-dry.

Standard lmcode signatures (lmcode_std_v3)

226 signatures that every lmcode host ships: 88 functions and 138 methods. Generated with lmscript --lmcode-signatures SCHEMA minus the --without-std output.

Functions: core (2)

FunctionReturns
json_parse(string)Json
template_render(string, Json)string

Functions: file (5)

FunctionReturns
file_append(string, string)void
file_exists(string)bool
file_lines(string)StrList
file_read(string)string
file_write(string, string)void

Functions: float (5)

FunctionReturns
float_list()FloatList
float_map()FloatMap
float_pq()FloatPQ
float_queue()FloatQueue
float_stack()FloatStack

Functions: int (5)

FunctionReturns
int_list()IntList
int_map()IntMap
int_pq()IntPQ
int_queue()IntQueue
int_stack()IntStack

Functions: lmcode (24)

FunctionReturns
lmcode_return_null()void
lmcode_return_put(string, FloatList)void
lmcode_return_put(string, FloatMap)void
lmcode_return_put(string, IntList)void
lmcode_return_put(string, IntMap)void
lmcode_return_put(string, Json)void
lmcode_return_put(string, StrList)void
lmcode_return_put(string, StrMap)void
lmcode_return_put(string, bool)void
lmcode_return_put(string, float)void
lmcode_return_put(string, int)void
lmcode_return_put(string, string)void
lmcode_return_put_null(string)void
lmcode_return_set(FloatList)void
lmcode_return_set(FloatMap)void
lmcode_return_set(IntList)void
lmcode_return_set(IntMap)void
lmcode_return_set(Json)void
lmcode_return_set(StrList)void
lmcode_return_set(StrMap)void
lmcode_return_set(bool)void
lmcode_return_set(float)void
lmcode_return_set(int)void
lmcode_return_set(string)void

Functions: math (16)

FunctionReturns
math_abs(float)float
math_abs(int)int
math_ceil(float)float
math_ceil(int)int
math_floor(float)float
math_floor(int)int
math_max(float, float)float
math_max(int, int)int
math_min(float, float)float
math_min(int, int)int
math_pow(float, float)float
math_pow(int, int)int
math_round(float)float
math_round(int)int
math_sqrt(float)float
math_sqrt(int)int

Functions: rest (5)

FunctionReturns
rest_cli(StrList)string
rest_config(string, string)void
rest_route(string, string, string)void
rest_serve()void
rest_stop()void

Functions: str (26)

FunctionReturns
str_base64_decode(string)string
str_base64_encode(string)string
str_contains(string, string)bool
str_ends_with(string, string)bool
str_find(string, string)int
str_hex_decode(string)string
str_hex_encode(string)string
str_is_float(string)bool
str_is_int(string)bool
str_len(string)int
str_list()StrList
str_lower(string)string
str_map()StrMap
str_match(string, string)bool
str_pq()StrPQ
str_queue()StrQueue
str_repeat(string, int)string
str_replace(string, string, string)string
str_split(string, string)StrList
str_stack()StrStack
str_starts_with(string, string)bool
str_substr(string, int, int)string
str_to_float(string)float
str_to_int(string)int
str_trim(string)string
str_upper(string)string

Methods: FloatList (7)

MethodReturns
FloatList.add(float)FloatList
FloatList.at(int)float
FloatList.clear()FloatList
FloatList.contains(float)bool
FloatList.index_of(float)int
FloatList.len()int
FloatList.set(int, float)FloatList

Methods: FloatMap (10)

MethodReturns
FloatMap.clear()FloatMap
FloatMap.get(string)float
FloatMap.get_or(string, float)float
FloatMap.has(string)bool
FloatMap.key_at(int)string
FloatMap.keys()StrList
FloatMap.len()int
FloatMap.remove(string)bool
FloatMap.set(string, float)FloatMap
FloatMap.values()FloatList

Methods: FloatPQ (6)

MethodReturns
FloatPQ.clear()FloatPQ
FloatPQ.empty()bool
FloatPQ.len()int
FloatPQ.peek()float
FloatPQ.pop()float
FloatPQ.push(float, float)FloatPQ

Methods: FloatQueue (7)

MethodReturns
FloatQueue.at(int)float
FloatQueue.clear()FloatQueue
FloatQueue.empty()bool
FloatQueue.len()int
FloatQueue.peek()float
FloatQueue.pop()float
FloatQueue.push(float)FloatQueue

Methods: FloatStack (7)

MethodReturns
FloatStack.at(int)float
FloatStack.clear()FloatStack
FloatStack.empty()bool
FloatStack.len()int
FloatStack.peek()float
FloatStack.pop()float
FloatStack.push(float)FloatStack

Methods: IntList (7)

MethodReturns
IntList.add(int)IntList
IntList.at(int)int
IntList.clear()IntList
IntList.contains(int)bool
IntList.index_of(int)int
IntList.len()int
IntList.set(int, int)IntList

Methods: IntMap (10)

MethodReturns
IntMap.clear()IntMap
IntMap.get(string)int
IntMap.get_or(string, int)int
IntMap.has(string)bool
IntMap.key_at(int)string
IntMap.keys()StrList
IntMap.len()int
IntMap.remove(string)bool
IntMap.set(string, int)IntMap
IntMap.values()IntList

Methods: IntPQ (6)

MethodReturns
IntPQ.clear()IntPQ
IntPQ.empty()bool
IntPQ.len()int
IntPQ.peek()int
IntPQ.pop()int
IntPQ.push(int, float)IntPQ

Methods: IntQueue (7)

MethodReturns
IntQueue.at(int)int
IntQueue.clear()IntQueue
IntQueue.empty()bool
IntQueue.len()int
IntQueue.peek()int
IntQueue.pop()int
IntQueue.push(int)IntQueue

Methods: IntStack (7)

MethodReturns
IntStack.at(int)int
IntStack.clear()IntStack
IntStack.empty()bool
IntStack.len()int
IntStack.peek()int
IntStack.pop()int
IntStack.push(int)IntStack

Methods: Json (11)

MethodReturns
Json.as_bool()bool
Json.as_float()float
Json.as_int()int
Json.as_string()string
Json.at(int)Json
Json.get(string)Json
Json.has(string)bool
Json.keys()StrList
Json.kind()string
Json.len()int
Json.to_json()string

Methods: RestExchange (15)

MethodReturns
RestExchange.body()string
RestExchange.get(string)string
RestExchange.has_header(string)bool
RestExchange.has_query(string)bool
RestExchange.header(string)string
RestExchange.increment(string)int
RestExchange.json(string)void
RestExchange.method()string
RestExchange.param(string)string
RestExchange.path()string
RestExchange.query(string)string
RestExchange.send(string)void
RestExchange.set(string, string)void
RestExchange.set_header(string, string)void
RestExchange.status(int)void

Methods: StrList (8)

MethodReturns
StrList.add(string)StrList
StrList.at(int)string
StrList.clear()StrList
StrList.contains(string)bool
StrList.index_of(string)int
StrList.join(string)string
StrList.len()int
StrList.set(int, string)StrList

Methods: StrMap (10)

MethodReturns
StrMap.clear()StrMap
StrMap.get(string)string
StrMap.get_or(string, string)string
StrMap.has(string)bool
StrMap.key_at(int)string
StrMap.keys()StrList
StrMap.len()int
StrMap.remove(string)bool
StrMap.set(string, string)StrMap
StrMap.values()StrList

Methods: StrPQ (6)

MethodReturns
StrPQ.clear()StrPQ
StrPQ.empty()bool
StrPQ.len()int
StrPQ.peek()string
StrPQ.pop()string
StrPQ.push(string, float)StrPQ

Methods: StrQueue (7)

MethodReturns
StrQueue.at(int)string
StrQueue.clear()StrQueue
StrQueue.empty()bool
StrQueue.len()int
StrQueue.peek()string
StrQueue.pop()string
StrQueue.push(string)StrQueue

Methods: StrStack (7)

MethodReturns
StrStack.at(int)string
StrStack.clear()StrStack
StrStack.empty()bool
StrStack.len()int
StrStack.peek()string
StrStack.pop()string
StrStack.push(string)StrStack

REST and CLI interfaces

A top-level fn in an lmcode body with a directly preceding @NAME annotation must carry implements NAME after its return type and match the interface signature exactly; the host calls it as an entry.

InterfaceSignature
RestGetfn(exchange: RestExchange) -> void
RestPostfn(exchange: RestExchange) -> void
RestPutfn(exchange: RestExchange) -> void
RestDeletefn(exchange: RestExchange) -> void
RestPatchfn(exchange: RestExchange) -> void
RestHeadfn(exchange: RestExchange) -> void
RestOptionsfn(exchange: RestExchange) -> void
RestHandlerfn(exchange: RestExchange) -> void
CliCommandfn(exchange: RestExchange) -> void
CliOptionfn(exchange: RestExchange) -> void

REST functions

FunctionReturns
rest_config(string, string)void
rest_route(string, string, string)void
rest_serve()void
rest_stop()void
rest_cli(StrList)string