LM lmscript.io Stdlib
Built-In Standard Library

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.

All functions shown

1. Console, Paths & File System

SignatureDescription
print(...args: any): stringPrints formatted values to output log
println(...args: any): stringPrints line to output log
warning(message: any): stringAdds a located non-failure warning
read_file(path: string): stringReads entire file as UTF-8 string
write_file(path: string, content: any): booleanWrites string content to file
append_file(path: string, content: any): booleanAppends string content to file
read_lines(path: string): arrayReads file as an array of string lines
file_exists(path: string): booleanChecks if file exists
mkdir(dirPath: string, [recursive: boolean = true]): booleanCreates a directory (recursive by default)
delete_file(path)Deletes file if it exists
rmdir(dirPath: string, [recursive: boolean = false]): booleanRemoves a directory; pass true for recursive removal of a non-empty directory
copy_file(src: string, dest: string): booleanCopies a file to a new path
move_file(src: string, dest: string): booleanMoves/renames a file
list_dir(path: string): arrayLists filenames in a directory
glob(pattern: string): arrayFinds files matching a glob pattern and returns an array of matching paths
basename(filePath: string, [ext: string]): stringReturns the last path segment, optionally stripping a trailing extension
dirname(filePath: string): stringReturns the directory portion of a path
path_join(...parts: string): stringJoins path segments using the OS-native separator
abs_path(filePath: string): stringResolves a path to an absolute path
temp_file(): stringCreates an empty temporary file and returns its absolute path; caller deletes it

2. Strings, Regular Expressions & Bidirectional Templates

SignatureDescription
len(item: any): numberReturns length of string, array, or object
upper(s: string): stringConverts string to uppercase
lower(s: string): stringConverts string to lowercase
trim(s: string): stringTrims whitespace from both ends
trim_start(s: string): stringTrims leading whitespace
trim_end(s: string): stringTrims trailing whitespace
split(s: string, delimiter: string): arraySplits string by required delimiter; use explicit empty delimiter for characters
join(arr: array, [separator: string]): stringJoin list values; default separator is comma-space; non-list becomes String(value).
replace(s: string, search: string, replacement: string): stringReplaces first occurrence
replace_all(s: string, search: string, replacement: string): stringReplaces all occurrences
starts_with(s: string, prefix: string): booleanChecks if string starts with prefix
ends_with(s: string, suffix: string): booleanChecks if string ends with suffix
contains(haystack: string|array, needle: any): booleanChecks if string or array contains item
substr(s: string, start: number, [length: number]): stringReturns substring by end-relative start and optional length
slice(target: string|array, start: number, [end: number]): string|arraySlices string or array
regex_test(s: string, pattern: string, [flags: string]): booleanTests a JavaScript regular expression against text
regex_find(s: string, pattern: string, [flags: string]): string|nullReturns first matched substring or null; g retains first-match shape, y is rejected
regex_matches(s: string, pattern: string, [flags: string]): arrayReturns flat array of matched substrings with Unicode-aware zero-width progress; y is rejected
regex_match(s: string, pattern: string, [flags: string]): array|nullReturns first full match and captures; 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
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)
set_pos(s_or_offset: string|number|null, [offset: number|null]): numberSets or resets the stateful regex match offset and returns the new offset
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
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
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
regex_replace(s: string, pattern: string, replacement: string, [flags: string]): stringReplaces matches using JavaScript regex replacement semantics
split_regex(s: string, pattern: string, [flags: string]): arraySplits 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)

SignatureDescription
push(arr: array, ...items: any): arrayPushes item(s) to end of array and returns the same array
pop(arr: array): anyPops item from end of array
shift(arr: array): anyRemoves and returns first element
slice(target: string|array, start: number, [end: number]): string|arraySlices string or array
sort(arr: array, [key: string]): arraySorts array numerically, alphabetically, or by object key
reverse(arr: array): arrayReturns reversed array
map()Creates a new empty map/hash
keys(obj: object): arrayReturns array of object keys
values(obj: object): arrayReturns array of object values
entries(obj: object): arrayReturns array of [key, value] pairs
has_key(obj: object, key: string): booleanChecks if object has key
delete_key(obj: object, key: string): objectDeletes key from object
merge(a: object, b: object): objectShallow merges two objects
json_parse(str: string): anyParse JSON text.
json_stringify(val: any, [indent: number = 0]): stringSerializes value into JSON string
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

4. SQLite, HTTP Client & XML/HTML Trees

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.
http_get(url: string): stringDownloads 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

SignatureDescription
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
lmcode_build(host: lmcode schema | string | string list): lmcode_builderCreates an opaque run-local lmcode builder

6. Unified AI Agents (agent_*), Direct LLM (llm_*) & Tools

SignatureDescription
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]): mapSends 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]): mapFetches 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]): listReturns OpenAI-compatible JSON Schema tool specifications for tools enabled by the given options.
tool_call(name: string, args: map, [options: map]): mapExecutes 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): mapExtracts 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

SignatureDescription
abs(n: number): numberAbsolute value
min(...nums: number|array): numberMinimum value
max(...nums: number|array): numberMaximum value
floor(n: number): numberFloor value
ceil(n: number): numberCeil value
round(n: number): numberRound value
sqrt(n: number): numberSquare root
pow(base: number, exp: number): numberPower calculation
str(val: any): stringConverts lists and maps to compact JSON; scalars to normal text
sha256(text: string): stringReturns lowercase SHA-256 of UTF-8 text; strings only
now(): numberReturns current epoch in ms
sleep_ms(ms: number): voidSleeps for the specified milliseconds
strftime(epochMs: number, fmt: string): stringFormats local time: epoch milliseconds first, format string second
env(name: string, [fallback: any = null]): anyReads an environment variable, or a fallback if unset
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
error(value: any, ...args: any): stringFormats and logs an error to stderr and records it for the execution error summary
assert(condition: any, [message: string]): booleanThrows error if condition is falsy
exit([code: number = 0]): neverTerminates script execution with an optional exit code (default: 0)