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 form | Meaning |
|---|---|
| --check | Static check only, including compiling _lmcode_ blocks; never starts a host. |
| --dry-run | Checks, then evaluates with effects off and prints PLAN; a reached run_lmcode starts the host once with dry metadata. |
| --lint | Stops after checking, like --check. |
| --trace FILE | Writes an execution trace to FILE. |
| --dry-loop-limit N | Loop iteration limit for the dry run. |
| --plan-format text|json | Plan format for --dry-run. |
| --resumepoint PATH | Start at a named resume point of a recover block. |
| --pref FILE | Properties file. |
| --check-files | Also verify path literals against the file system. |
| --base-dir dir | Base directory for relative paths. |
| --source-name label | Source label used in diagnostics. |
| --saveas FILE | Download 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|latest | Explicit 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 --version | Print the version. |
Exit codes
| Exit code | Meaning |
|---|---|
| 0 | Success. |
| 1 | Ordinary runtime failure, for example a failed require or a failed fetch of a remote script. |
| 2 | Static 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)
| Signature | Description |
|---|---|
| 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)
| Signature | Description |
|---|---|
| format_file_blocks(files: array): string | Inverse 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): map | key: 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]): array | Sorted 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): array | POSIX 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)
| Signature | Description |
|---|---|
| sql_exec(path: string, sql: string, [params: array|map]): map | Runs 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]): array | Runs 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)
| Signature | Description |
|---|---|
| abs_path(filePath: string): string | Resolves a path to an absolute path |
| append_file(path: string, content: any): boolean | Appends string content to file |
| basename(filePath: string, [ext: string]): string | Returns the last path segment, optionally stripping a trailing extension |
| copy_file(src: string, dest: string): boolean | Copies a file to a new path |
| csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array | Parses 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 = ","]): string | Serializes records or rows to CSV text |
| dirname(filePath: string): string | Returns the directory portion of a path |
| file_exists(path: string): boolean | Checks if file exists |
| glob(pattern: string): array | Finds files matching a glob pattern and returns an array of matching paths |
| list_dir(path: string): array | Lists filenames in a directory |
| lmcode_build(host: lmcode schema | string | string list): lmcode_builder | Creates an opaque run-local lmcode builder |
| mkdir(dirPath: string, [recursive: boolean = true]): boolean | Creates a directory (recursive by default) |
| move_file(src: string, dest: string): boolean | Moves/renames a file |
| path_join(...parts: string): string | Joins path segments using the OS-native separator |
| read(path: string): string | Reads entire file as UTF-8 string |
| read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array | Reads 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): string | Reads entire file as UTF-8 string |
| read_json(path: string): any | Reads file and parses JSON content |
| read_lines(path: string): array | Reads file as an array of string lines |
| rmdir(dirPath: string, [recursive: boolean = false]): boolean | Removes a directory; pass true for recursive removal of a non-empty directory |
| run_lmcode(program_or_builder: lmcode, options?: map): map | Executes an opaque lmcode program or sealed builder; dry calls require dry-marked preview envelopes and record simulated PLAN data |
| temp_file(): string | Creates an empty temporary file and returns its absolute path; caller deletes it |
| write(path: string, content: any): boolean | Writes string content to file |
| write_csv(path: string, data: array, [delimiter: string = ","]): boolean | Writes array of objects or rows to CSV file |
| write_file(path: string, content: any): boolean | Writes string content to file |
| write_file_exclusive(path: string, content: any): boolean | Creates a new file; refuses to overwrite an existing path |
| write_json(path: string, data: any, [indent: number = 2]): boolean | Serializes data and writes formatted JSON to file |
| write_lines(path: string, lines: array): boolean | Writes an array of lines to a file with trailing newline |
JSON & Data (core)
| Signature | Description |
|---|---|
| filter_by(arr: array, key: string, value: any): array | Filters array of objects where item[key] == value |
| find_by(arr: array, key: string, value: any): any | Finds first object in array where item[key] == value |
| json_parse(str: string): any | Parse JSON text. |
| json_parse_safe(str: string, [fallback: any = null]): any | Parse with fence/preamble recovery; fallback if invalid. |
| json_stringify(val: any, [indent: number = 0]): string | Serializes value into JSON string |
| json_validate(val: any, schema: map): map | Validate value against JSON-Schema subset (type, properties, required, enum, items, minimum/maximum, minLength/maxLength, additionalProperties:false). Returns {ok, errors}. |
| pluck(arr: array, key: string): array | Extracts 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)
| Signature | Description |
|---|---|
| avg(arr: array): number | Calculates average of array |
| chunk(arr: array, size: number): array | Partition into lists; size<=0 gives []. |
| compact(arr: array): array | Remove null elements only; retain false/0/empty text. |
| concat(first: array, ...more: array): array | Concatenates arrays |
| drop(arr: array, n: number): array | Return suffix; negative start clamps to 0. |
| enumerate(arr: array): array | Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29). |
| first(arr: array): any | Returns first element |
| flatten(arr: array): array | Flattens array one level |
| insert(arr: array, index: number, item: any): array | Inserts item at index and returns the same array |
| last(arr: array): any | Returns last element |
| len(item: any): number | Returns length of string, array, or object |
| pop(arr: array): any | Pops item from end of array |
| push(arr: array, ...items: any): array | Pushes item(s) to end of array and returns the same array |
| range(start: number, [end: number], [step: number = 1]): array | Generates an array of numbers |
| remove_at(arr: array, index: number): any | Removes element at index |
| reverse(arr: array): array | Returns reversed array |
| shift(arr: array): any | Removes and returns first element |
| sort(arr: array, [key: string]): array | Sorts array numerically, alphabetically, or by object key |
| sum(arr: array): number | Calculates sum of array |
| take(arr: array, n: number): array | Return prefix; negative n gives []. |
| unique(arr: array): array | Removes duplicate elements |
| unshift(arr: array, ...items: any): array | Adds item(s) to front of array and returns the same array |
| zip(arr1: array, arr2: array): array | Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...]. |
Maps & Key-Value (core)
| Signature | Description |
|---|---|
| clone(val: any): any | Deep clones an object or array |
| delete_key(obj: object, key: string): object | Deletes key from object |
| entries(obj: object): array | Returns array of [key, value] pairs |
| from_entries(pairs: array): object | Creates map from [key, value] pairs |
| get(obj: any, path: string|array, [defaultVal: any]): any | Safely extracts nested property by path (e.g. 'user.address.city') |
| getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean | Reads 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 = []]): array | Reads 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]): number | Reads a numeric field from a map/request form; fallback (default 0) when missing or null |
| getstr(obj: any, path: string|array, [fallback: string = ""]): string | Reads 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): boolean | Checks if object has key |
| items(obj: object): array | Returns array of [key, value] pairs (alias for entries) |
| keys(obj: object): array | Returns array of object keys |
| merge(a: object, b: object): object | Shallow merges two objects |
| set(obj: object, path: string|array, value: any): object | Sets nested property by path |
| values(obj: object): array | Returns array of object values |
Math (core)
| Signature | Description |
|---|---|
| abs(n: number): number | Absolute value |
| ceil(n: number): number | Ceil value |
| clamp(val: number, low: number, high: number): number | Restricts a numeric value to lie within [low, high] bounds. |
| floor(n: number): number | Floor value |
| max(...nums: number|array): number | Maximum value |
| min(...nums: number|array): number | Minimum value |
| num(val: any): number | Converts value to number |
| pow(base: number, exp: number): number | Power calculation |
| random(): number | Random float between 0 and 1 |
| round(n: number): number | Round value |
| sqrt(n: number): number | Square root |
Math & Utilities (core)
| Signature | Description |
|---|---|
| sha256(text: string): string | Returns lowercase SHA-256 of UTF-8 text; strings only |
Properties (core)
| Signature | Description |
|---|---|
| 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)
| Signature | Description |
|---|---|
| char_at(s: string, index: number): string | UTF-16 code unit text; out of range gives empty string. |
| char_code(s: string, [index: number = 0]): number | UTF-16 code unit number; out of range gives NaN. |
| contains(haystack: string|array, needle: any): boolean | Checks if string or array contains item |
| count_matches(s: string, sub: string): number | Count non-overlapping substrings; empty needle gives 0. |
| ends_with(s: string, suffix: string): boolean | Checks if string ends with suffix |
| endswith(s: string, suffix: string): boolean | Checks 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): string | Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution |
| from_char_code(...codes: number): string | Returns string from character codes |
| includes(haystack: string|array, needle: any): boolean | Checks if string or array contains item |
| index_of(haystack: string|array, needle: any, [fromIndex: number]): number | Finds substring or strictly equal array element index; -1 if absent |
| is_alnum(s: string): boolean | Nonempty ASCII letters/digits. |
| is_alpha(s: string): boolean | Nonempty ASCII alphabetic text. |
| is_blank(s: any): boolean | Returns true if string is null, empty, or whitespace only. |
| is_digit(s: string): boolean | Nonempty ASCII digit text. |
| is_empty(val: any): boolean | Literal 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]): string | Join list values; default separator is comma-space; non-list becomes String(value). |
| last_index_of(haystack: string|array, needle: any): number | Finds last substring or strictly equal array element index; -1 if absent |
| last_line_as_status(s: string): string|null | Returns 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): array | Splits string into array of lines |
| lower(s: string): string | Converts string to lowercase |
| lstrip(s: string): string | Trims leading whitespace (alias for trim_start) |
| pad_end(s: string, targetLength: number, [padChar: string = " "]): string | Right-pads string |
| pad_start(s: string, targetLength: number, [padChar: string = " "]): string | Left-pads string |
| pos([s: string|number|null], [offset: number|null]): number | Reads 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|null | Returns first matched substring or null; g retains first-match shape, y is rejected |
| regex_find_all(s: string, pattern: string, [flags: string]): array | Returns capture arrays with Unicode-aware zero-width progress; y is rejected |
| regex_find_pos(s: string, pattern: string, [flags: string]): string|null | Matches 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|null | Returns first full match and captures; g retains first-match shape, y is rejected |
| regex_match_pos(s: string, pattern: string, [flags: string]): array|null | Matches 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]): array | Returns flat array of matched substrings with Unicode-aware zero-width progress; y is rejected |
| regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string | Replaces matches using JavaScript regex replacement semantics |
| regex_test(s: string, pattern: string, [flags: string]): boolean | Tests a JavaScript regular expression against text |
| regex_test_pos(s: string, pattern: string, [flags: string]): boolean | Tests 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): string | Repeats string count times |
| replace(s: string, search: string, replacement: string): string | Replaces first occurrence |
| replace_all(s: string, search: string, replacement: string): string | Replaces all occurrences |
| reverse_str(s: string): string | Reverse UTF-16 code units (not code points). |
| rstrip(s: string): string | Trims trailing whitespace (alias for trim_end) |
| set_pos(s_or_offset: string|number|null, [offset: number|null]): number | Sets or resets the stateful regex match offset and returns the new offset |
| slice(target: string|array, start: number, [end: number]): string|array | Slices string or array |
| split(s: string, delimiter: string): array | Splits string by required delimiter; use explicit empty delimiter for characters |
| split_regex(s: string, pattern: string, [flags: string]): array | Splits text at regular expression matches |
| sprintf(template: string, ...args: any): string | Formats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax |
| starts_with(s: string, prefix: string): boolean | Checks if string starts with prefix |
| startswith(s: string, prefix: string): boolean | Checks if string starts with prefix (alias for starts_with) |
| strip(s: string): string | Trims whitespace from both ends (alias for trim) |
| substr(s: string, start: number, [length: number]): string | Returns substring by end-relative start and optional length |
| substring(s: string, start: number, [end: number]): string | Returns substring between indices |
| title_case(s: string): string | Uppercase ASCII word-initial characters; does not lowercase the tail. |
| to_lower(s: string): string | Converts string to lowercase |
| to_upper(s: string): string | Converts string to uppercase |
| trim(s: string): string | Trims whitespace from both ends |
| trim_end(s: string): string | Trims trailing whitespace |
| trim_start(s: string): string | Trims leading whitespace |
| upper(s: string): string | Converts string to uppercase |
| upper_first(s: string): string | Uppercase first UTF-16 code unit; retain tail. |
| words(s: string): array | Splits string into words |
System & Process (core)
| Signature | Description |
|---|---|
| args_parse(argv, flags, [usage]) | Parses declared long options without effects; returns values, args, provided, help and help_requested |
| assert(condition: any, [message: string]): boolean | Throws 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): any | Returns the first non-null/non-undefined argument, else null |
| date([epochMs: number]): string | Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp |
| env(name: string, [fallback: any = null]): any | Reads 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]): never | Terminates script execution with an optional exit code (default: 0) |
| getenv(name: string, [fallback: any = null]): any | Reads 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): any | Eager JS-truthiness choice; use ?: for lazy selection. |
| if_null(val: any, fallback: any): any | Returns fallback if value is null/undefined, else value |
| is_array(val: any): boolean | Checks if value is an array |
| is_function(val: any): boolean | Checks if value is a first-class function reference |
| is_map(val: any): boolean | Checks if value is a map/object |
| is_number(val: any): boolean | typeof number predicate; includes NaN/Infinity. |
| is_string(val: any): boolean | Checks if value is a string |
| now(): number | Returns 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]): map | Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms) |
| require(value: any, message: string): any | Requires a present value; injected diagnostic/captured error and exit 1 on missing |
| set_env(name: string, value: any): boolean | Sets 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): void | Sleeps for the specified milliseconds |
| str(val: any): string | Converts lists and maps to compact JSON; scalars to normal text |
| strftime(epochMs: number, fmt: string): string | Formats local time: epoch milliseconds first, format string second |
| system(argv: array, [timeoutMs: number = 0 | options: map]): SystemResult | Executes 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(): number | Returns current Unix epoch in whole seconds |
| type(val: any): string | Returns runtime type of value |
| warning(message: any): string | Adds a located non-failure warning |
| which(name: string): string|null | Finds the first executable path without spawning |
Templates (core)
| Signature | Description |
|---|---|
| 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)
| Signature | Description |
|---|---|
| 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)
| Signature | Description |
|---|---|
| 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(): list | Returns 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)
| Signature | Description |
|---|---|
| run_script(...) | Run child in-process with inherited binding, properties and cancellation. |
lmctl Automation (lmctl)
| Signature | Description |
|---|---|
| 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)
| Signature | Description |
|---|---|
| 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 attribute | Meaning |
|---|---|
| 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. |
| Function | Returns | Description | Example |
|---|---|---|---|
| run_lmcode(program_or_builder: lmcode, options?: map): map | map | Runs 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_builder | lmcode_builder | Creates 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
| Item | Meaning |
|---|---|
| options.args | String list appended to the host argv; copied, literal data, no shell, glob or environment expansion. |
| options.command | String or argv list, single program only: a complete command template with exactly one $DSLFILE outside argv[0]. |
| default argv | The 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 failure | Returned as data with ok false (optional validated part for builders); malformed frames, unexpected exits or mismatched envelopes are located runtime errors. |
| --check | Never starts hosts. |
| --dry-run | Starts 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)
| Function | Returns |
|---|---|
| json_parse(string) | Json |
| template_render(string, Json) | string |
Functions: file (5)
| Function | Returns |
|---|---|
| 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)
| Function | Returns |
|---|---|
| float_list() | FloatList |
| float_map() | FloatMap |
| float_pq() | FloatPQ |
| float_queue() | FloatQueue |
| float_stack() | FloatStack |
Functions: int (5)
| Function | Returns |
|---|---|
| int_list() | IntList |
| int_map() | IntMap |
| int_pq() | IntPQ |
| int_queue() | IntQueue |
| int_stack() | IntStack |
Functions: lmcode (24)
| Function | Returns |
|---|---|
| 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)
| Function | Returns |
|---|---|
| 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)
| Function | Returns |
|---|---|
| rest_cli(StrList) | string |
| rest_config(string, string) | void |
| rest_route(string, string, string) | void |
| rest_serve() | void |
| rest_stop() | void |
Functions: str (26)
| Function | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| FloatPQ.clear() | FloatPQ |
| FloatPQ.empty() | bool |
| FloatPQ.len() | int |
| FloatPQ.peek() | float |
| FloatPQ.pop() | float |
| FloatPQ.push(float, float) | FloatPQ |
Methods: FloatQueue (7)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| IntPQ.clear() | IntPQ |
| IntPQ.empty() | bool |
| IntPQ.len() | int |
| IntPQ.peek() | int |
| IntPQ.pop() | int |
| IntPQ.push(int, float) | IntPQ |
Methods: IntQueue (7)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| StrPQ.clear() | StrPQ |
| StrPQ.empty() | bool |
| StrPQ.len() | int |
| StrPQ.peek() | string |
| StrPQ.pop() | string |
| StrPQ.push(string, float) | StrPQ |
Methods: StrQueue (7)
| Method | Returns |
|---|---|
| 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)
| Method | Returns |
|---|---|
| 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.
| Interface | Signature |
|---|---|
| RestGet | fn(exchange: RestExchange) -> void |
| RestPost | fn(exchange: RestExchange) -> void |
| RestPut | fn(exchange: RestExchange) -> void |
| RestDelete | fn(exchange: RestExchange) -> void |
| RestPatch | fn(exchange: RestExchange) -> void |
| RestHead | fn(exchange: RestExchange) -> void |
| RestOptions | fn(exchange: RestExchange) -> void |
| RestHandler | fn(exchange: RestExchange) -> void |
| CliCommand | fn(exchange: RestExchange) -> void |
| CliOption | fn(exchange: RestExchange) -> void |
REST functions
| Function | Returns |
|---|---|
| rest_config(string, string) | void |
| rest_route(string, string, string) | void |
| rest_serve() | void |
| rest_stop() | void |
| rest_cli(StrList) | string |