LMScript Standard Library Reference
Filter selected built-in functions in the outer LMScript runtime below. Looking for the 206-signature
lmcode_std_v3 catalog available inside _lmcode_ blocks? See the
LMCode Standard Catalog.
1. Console, Paths & File System
| Signature | Description |
|---|---|
print(...args: any): string | Prints formatted values to output log |
println(...args: any): string | Prints line to output log |
warning(message: any): string | Adds a located non-failure warning |
read_file(path: string): string | Reads entire file as UTF-8 string |
write_file(path: string, content: any): boolean | Writes string content to file |
append_file(path: string, content: any): boolean | Appends string content to file |
read_lines(path: string): array | Reads file as an array of string lines |
file_exists(path: string): boolean | Checks if file exists |
mkdir(dirPath: string, [recursive: boolean = true]): boolean | Creates a directory (recursive by default) |
delete_file(path) | Deletes file if it exists |
rmdir(dirPath: string, [recursive: boolean = false]): boolean | Removes a directory; pass true for recursive removal of a non-empty directory |
copy_file(src: string, dest: string): boolean | Copies a file to a new path |
move_file(src: string, dest: string): boolean | Moves/renames a file |
list_dir(path: string): array | Lists filenames in a directory |
glob(pattern: string): array | Finds files matching a glob pattern and returns an array of matching paths |
basename(filePath: string, [ext: string]): string | Returns the last path segment, optionally stripping a trailing extension |
dirname(filePath: string): string | Returns the directory portion of a path |
path_join(...parts: string): string | Joins path segments using the OS-native separator |
abs_path(filePath: string): string | Resolves a path to an absolute path |
temp_file(): string | Creates an empty temporary file and returns its absolute path; caller deletes it |
2. Strings, Regular Expressions & Bidirectional Templates
| Signature | Description |
|---|---|
len(item: any): number | Returns length of string, array, or object |
upper(s: string): string | Converts string to uppercase |
lower(s: string): string | Converts string to lowercase |
trim(s: string): string | Trims whitespace from both ends |
trim_start(s: string): string | Trims leading whitespace |
trim_end(s: string): string | Trims trailing whitespace |
split(s: string, delimiter: string): array | Splits string by required delimiter; use explicit empty delimiter for characters |
join(arr: array, [separator: string]): string | Join list values; default separator is comma-space; non-list becomes String(value). |
replace(s: string, search: string, replacement: string): string | Replaces first occurrence |
replace_all(s: string, search: string, replacement: string): string | Replaces all occurrences |
starts_with(s: string, prefix: string): boolean | Checks if string starts with prefix |
ends_with(s: string, suffix: string): boolean | Checks if string ends with suffix |
contains(haystack: string|array, needle: any): boolean | Checks if string or array contains item |
substr(s: string, start: number, [length: number]): string | Returns substring by end-relative start and optional length |
slice(target: string|array, start: number, [end: number]): string|array | Slices string or array |
regex_test(s: string, pattern: string, [flags: string]): boolean | Tests a JavaScript regular expression against text |
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_matches(s: string, pattern: string, [flags: string]): array | Returns flat array of matched substrings with Unicode-aware zero-width progress; y is rejected |
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_find_all(s: string, pattern: string, [flags: string]): array | Returns capture arrays with Unicode-aware zero-width progress; y is rejected |
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) |
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 |
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 |
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 |
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 |
regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string | Replaces matches using JavaScript regex replacement semantics |
split_regex(s: string, pattern: string, [flags: string]): array | Splits text at regular expression matches |
expand(text, [vars]) | Expand simple references from explicit vars, PROPS paths and invocation ARGV; inserted text is opaque |
template_extract_text(template, text) | Exact whole-string extraction with simple ${name} holes, anchored suffix and earliest separators; returns {matched,value,candidate,error}. |
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. |
Regex offsets count UTF-16 code units. Equal string values share a cursor within a run; parallel tasks are isolated. As in Perl, an empty stateful match consumes no character and leaves the cursor at the match offset, and a second empty match at that same offset is refused so repeated matching terminates: anchored matching returns null/false, while a g search resumes one code unit (one code point with u/v) further on. Assigning pos(s, offset) lifts the refusal. A Unicode match never starts before the cursor; reset an offset inside a surrogate pair to a code point boundary.
3. Lists, Maps & Data Formats (JSON, CSV, TOML, Props)
| Signature | Description |
|---|---|
push(arr: array, ...items: any): array | Pushes item(s) to end of array and returns the same array |
pop(arr: array): any | Pops item from end of array |
shift(arr: array): any | Removes and returns first element |
slice(target: string|array, start: number, [end: number]): string|array | Slices string or array |
sort(arr: array, [key: string]): array | Sorts array numerically, alphabetically, or by object key |
reverse(arr: array): array | Returns reversed array |
map() | Creates a new empty map/hash |
keys(obj: object): array | Returns array of object keys |
values(obj: object): array | Returns array of object values |
entries(obj: object): array | Returns array of [key, value] pairs |
has_key(obj: object, key: string): boolean | Checks if object has key |
delete_key(obj: object, key: string): object | Deletes key from object |
merge(a: object, b: object): object | Shallow merges two objects |
json_parse(str: string): any | Parse JSON text. |
json_stringify(val: any, [indent: number = 0]): string | Serializes value into JSON string |
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 |
4. SQLite, HTTP Client & XML/HTML Trees
| 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. |
http_get(url: string): string | Downloads UTF-8 text from a public HTTP(S) URL |
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_attr(node, name, fallback=null) | Look up an unqualified or {URI}local attribute, with optional fallback. |
xml_text(node) | Concatenate descendant XML text in document order, excluding comments. |
load_schema(cli="host") or load_schema(schema="file.json") loads an immutable schema descriptor for an _lmcode_ header. Run builders with run_lmcode(builder).
5. LMCode Bridge & Bytecode Functions
| Signature | Description |
|---|---|
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 |
lmcode_build(host: lmcode schema | string | string list): lmcode_builder | Creates an opaque run-local lmcode builder |
6. Unified AI Agents (agent_*), Direct LLM (llm_*) & Tools
| Signature | Description |
|---|---|
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_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_turn(handle, 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_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_info(handle) | 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_close(handle, status = "done") | Closes an open agent and releases its lease; idempotent. Scope exit, recorded errors, exit and signals also close it. |
llm_prompt(model: string, prompt: string, [options: map]): map | 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_models(provider: string, [options: map]): map | 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. |
tool_specs([options: map]): list | Returns OpenAI-compatible JSON Schema tool specifications for tools enabled by the given options. |
tool_call(name: string, args: map, [options: map]): map | 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: string): map | Extracts a tool call request from model output text. Returns {ok: bool, name: string|null, args: map|null, error: string|null}. |
7. Math, Time, Crypto & OS Environment
| Signature | Description |
|---|---|
abs(n: number): number | Absolute value |
min(...nums: number|array): number | Minimum value |
max(...nums: number|array): number | Maximum value |
floor(n: number): number | Floor value |
ceil(n: number): number | Ceil value |
round(n: number): number | Round value |
sqrt(n: number): number | Square root |
pow(base: number, exp: number): number | Power calculation |
str(val: any): string | Converts lists and maps to compact JSON; scalars to normal text |
sha256(text: string): string | Returns lowercase SHA-256 of UTF-8 text; strings only |
now(): number | Returns current epoch in ms |
sleep_ms(ms: number): void | Sleeps for the specified milliseconds |
strftime(epochMs: number, fmt: string): string | Formats local time: epoch milliseconds first, format string second |
env(name: string, [fallback: any = null]): any | Reads an environment variable, or a fallback if unset |
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 |
error(value: any, ...args: any): string | Formats and logs an error to stderr and records it for the execution error summary |
assert(condition: any, [message: string]): boolean | Throws error if condition is falsy |
exit([code: number = 0]): never | Terminates script execution with an optional exit code (default: 0) |