Programming Neam
📖 17 min read

Appendix A: Built-in Functions Reference #


This appendix provides a complete reference for every built-in function available in the Neam runtime. Functions are organized by category. Each entry includes the function signature, parameter descriptions, return value, and a usage example.

All built-in functions are available in any Neam program without imports. They are implemented natively in the VM and execute without LLM calls.


A.1 Core Functions #

These functions provide fundamental operations: type conversion, output, input, introspection, and JSON handling.

len(value) -> number #

Returns the length of a string, list, or map.

Parameter Type Description
value string, list, or map The value to measure

Returns: Number of characters (string), elements (list), or key-value pairs (map).

neam
{
  let s = "hello";
  let l = [1, 2, 3, 4];
  let m = { "a": 1, "b": 2 };

  emit str(len(s));  // 5
  emit str(len(l));  // 4
  emit str(len(m));  // 2
}

str(value) -> string #

Converts any value to its string representation.

Parameter Type Description
value any The value to convert

Returns: String representation of the value.

neam
{
  emit str(42);          // "42"
  emit str(3.14);        // "3.14"
  emit str(true);        // "true"
  emit str(nil);         // "nil"
  emit str([1, 2, 3]);   // "[1, 2, 3]"
}

print(value) -> nil #

Prints a value to standard output without a newline. Use emit for line-based output.

Parameter Type Description
value any The value to print

Returns: nil

neam
{
  print("Loading");
  print(".");
  print(".");
  print(".");
  emit "";  // newline
  // Output: Loading...
}

typeof(value) -> string #

Returns the type name of a value as a string.

Parameter Type Description
value any The value to inspect

Returns: One of: "number", "string", "bool", "nil", "list", "map", "function", "agent".

neam
{
  emit typeof(42);         // "number"
  emit typeof("hello");    // "string"
  emit typeof(true);       // "bool"
  emit typeof(nil);        // "nil"
  emit typeof([1, 2]);     // "list"
  emit typeof({"a": 1});   // "map"
}

json_parse(text) -> value #

Parses a JSON string into a Neam value (map, list, string, number, bool, or nil).

Parameter Type Description
text string A valid JSON string

Returns: The parsed Neam value. Throws a runtime error if the JSON is invalid.

neam
{
  let data = json_parse("{\"name\": \"Alice\", \"age\": 30}");
  emit data["name"];   // "Alice"
  emit str(data["age"]); // "30"

  let list = json_parse("[1, 2, 3]");
  emit str(len(list)); // "3"
}

json_stringify(value) -> string #

Serializes a Neam value (map, list, string, number, bool, nil) to a JSON string.

Parameter Type Description
value any The value to serialize

Returns: A JSON string. Maps and lists are serialized recursively.

neam
{
  let obj = { "name": "Bob", "scores": [95, 87, 92] };
  let json = json_stringify(obj);
  emit json;
  // {"name":"Bob","scores":[95,87,92]}
}

input(prompt) -> string #

Reads a line of input from the user. Blocks until the user presses Enter.

Parameter Type Description
prompt string The prompt to display

Returns: The user's input as a string (without trailing newline).

neam
{
  let name = input("What is your name? ");
  emit "Hello, " + name + "!";
}

emit(value) -> nil #

Prints a value to standard output followed by a newline. This is Neam's primary output function and is also used as a statement: emit "hello";.

Parameter Type Description
value any The value to output

Returns: nil

neam
{
  emit "Hello, world!";
  emit 42;
  emit [1, 2, 3];
}

A.2 String Functions #

String manipulation functions. All functions return new strings; the original string is never modified.

contains(haystack, needle) -> bool #

Returns true if the string contains the substring.

neam
{
  emit str(contains("Hello, World!", "World"));  // true
  emit str(contains("Hello, World!", "world"));  // false (case-sensitive)
}

starts_with(text, prefix) -> bool #

Returns true if the string starts with the given prefix.

neam
{
  emit str(starts_with("neam-cli", "neam"));  // true
  emit str(starts_with("hello", "world"));     // false
}

ends_with(text, suffix) -> bool #

Returns true if the string ends with the given suffix.

neam
{
  emit str(ends_with("report.pdf", ".pdf"));  // true
  emit str(ends_with("report.pdf", ".txt"));  // false
}

index_of(haystack, needle) -> number #

Returns the zero-based index of the first occurrence of needle in haystack, or -1 if not found.

neam
{
  emit str(index_of("hello world", "world"));  // 6
  emit str(index_of("hello world", "xyz"));    // -1
}

substring(text, start, end) -> string #

Returns the substring from index start (inclusive) to end (exclusive).

neam
{
  emit substring("Hello, World!", 0, 5);   // "Hello"
  emit substring("Hello, World!", 7, 12);  // "World"
}

replace(text, search, replacement) -> string #

Replaces all occurrences of search with replacement.

neam
{
  emit replace("hello world", "world", "Neam");  // "hello Neam"
  emit replace("aaa", "a", "bb");                 // "bbbbbb"
}

split(text, delimiter) -> list #

Splits a string by a delimiter and returns a list of substrings.

neam
{
  let parts = split("apple,banana,cherry", ",");
  emit str(len(parts));  // 3
  emit parts[0];         // "apple"
  emit parts[2];         // "cherry"
}

join(list, separator) -> string #

Joins a list of strings with a separator.

neam
{
  let words = ["Hello", "World"];
  emit join(words, " ");   // "Hello World"
  emit join(words, ", ");  // "Hello, World"
}

trim(text) -> string #

Removes leading and trailing whitespace from a string.

neam
{
  emit trim("  hello  ");  // "hello"
}

str_lower(text) -> string #

Converts a string to lowercase.

neam
{
  emit str_lower("Hello, World!");  // "hello, world!"
}

str_upper(text) -> string #

Converts a string to uppercase.

neam
{
  emit str_upper("Hello, World!");  // "HELLO, WORLD!"
}

str_repeat(text, count) -> string #

Repeats a string the specified number of times.

neam
{
  emit str_repeat("ab", 3);   // "ababab"
  emit str_repeat("-", 20);   // "--------------------"
}

str_pad_left(text, width, pad_char) -> string #

Pads a string on the left to reach the specified width.

neam
{
  emit str_pad_left("42", 5, "0");   // "00042"
  emit str_pad_left("hi", 6, " ");   // "    hi"
}

str_pad_right(text, width, pad_char) -> string #

Pads a string on the right to reach the specified width.

neam
{
  emit str_pad_right("hello", 10, ".");  // "hello....."
}

A.3 List Functions #

Functions for creating, querying, and transforming lists.

list_push(list, value) -> list #

Returns a new list with the value appended to the end.

neam
{
  let items = [1, 2, 3];
  let updated = list_push(items, 4);
  emit str(updated);  // [1, 2, 3, 4]
}

list_pop(list) -> list #

Returns a new list with the last element removed.

neam
{
  let items = [1, 2, 3];
  let shorter = list_pop(items);
  emit str(shorter);  // [1, 2]
}

list_slice(list, start, end) -> list #

Returns a new list containing elements from index start (inclusive) to end (exclusive).

neam
{
  let items = [10, 20, 30, 40, 50];
  emit str(list_slice(items, 1, 4));  // [20, 30, 40]
}

list_contains(list, value) -> bool #

Returns true if the list contains the specified value.

neam
{
  let fruits = ["apple", "banana", "cherry"];
  emit str(list_contains(fruits, "banana"));  // true
  emit str(list_contains(fruits, "grape"));   // false
}

list_index_of(list, value) -> number #

Returns the zero-based index of the first occurrence of value, or -1 if not found.

neam
{
  let items = ["a", "b", "c", "b"];
  emit str(list_index_of(items, "b"));  // 1
  emit str(list_index_of(items, "z"));  // -1
}

list_reverse(list) -> list #

Returns a new list with elements in reverse order.

neam
{
  emit str(list_reverse([1, 2, 3]));  // [3, 2, 1]
}

list_sort(list) -> list #

Returns a new list with elements sorted in ascending order. Works with numbers and strings.

neam
{
  emit str(list_sort([3, 1, 4, 1, 5]));           // [1, 1, 3, 4, 5]
  emit str(list_sort(["cherry", "apple", "banana"])); // ["apple", "banana", "cherry"]
}

list_map(list, func) -> list #

Returns a new list with each element transformed by the given function.

neam
{
  let nums = [1, 2, 3, 4];
  let doubled = list_map(nums, fn(x) { return x * 2; });
  emit str(doubled);  // [2, 4, 6, 8]
}

list_filter(list, func) -> list #

Returns a new list containing only elements for which the function returns true.

neam
{
  let nums = [1, 2, 3, 4, 5, 6];
  let evens = list_filter(nums, fn(x) { return x % 2 == 0; });
  emit str(evens);  // [2, 4, 6]
}

list_reduce(list, initial, func) -> value #

Reduces a list to a single value by applying a function to each element and an accumulator.

neam
{
  let nums = [1, 2, 3, 4, 5];
  let total = list_reduce(nums, 0, fn(acc, x) { return acc + x; });
  emit str(total);  // 15
}

list_flat_map(list, func) -> list #

Maps each element to a list and flattens the result into a single list.

neam
{
  let words = ["hello world", "foo bar"];
  let chars = list_flat_map(words, fn(w) { return split(w, " "); });
  emit str(chars);  // ["hello", "world", "foo", "bar"]
}

list_unique(list) -> list #

Returns a new list with duplicate elements removed. Preserves first occurrence order.

neam
{
  emit str(list_unique([1, 2, 2, 3, 1, 4]));  // [1, 2, 3, 4]
}

list_zip(list_a, list_b) -> list #

Combines two lists into a list of pairs. Stops at the length of the shorter list.

neam
{
  let keys = ["name", "age"];
  let vals = ["Alice", 30];
  let pairs = list_zip(keys, vals);
  emit str(pairs);  // [["name", "Alice"], ["age", 30]]
}

A.4 Map Functions #

Functions for working with maps (key-value dictionaries).

map_keys(m) -> list #

Returns a list of all keys in the map.

neam
{
  let config = { "host": "localhost", "port": 8080, "debug": true };
  emit str(map_keys(config));  // ["host", "port", "debug"]
}

map_values(m) -> list #

Returns a list of all values in the map.

neam
{
  let config = { "host": "localhost", "port": 8080 };
  emit str(map_values(config));  // ["localhost", 8080]
}

map_has(m, key) -> bool #

Returns true if the map contains the specified key.

neam
{
  let user = { "name": "Alice", "role": "admin" };
  emit str(map_has(user, "name"));   // true
  emit str(map_has(user, "email"));  // false
}

map_remove(m, key) -> map #

Returns a new map with the specified key removed.

neam
{
  let data = { "a": 1, "b": 2, "c": 3 };
  let trimmed = map_remove(data, "b");
  emit str(trimmed);  // {"a": 1, "c": 3}
}

map_merge(base, overlay) -> map #

Returns a new map that combines both maps. Keys in the overlay map overwrite keys in the base map.

neam
{
  let defaults = { "timeout": 30, "retries": 3, "debug": false };
  let overrides = { "timeout": 60, "debug": true };
  let config = map_merge(defaults, overrides);
  emit str(config);  // {"timeout": 60, "retries": 3, "debug": true}
}

map_entries(m) -> list #

Returns a list of [key, value] pairs.

neam
{
  let user = { "name": "Alice", "age": 30 };
  let entries = map_entries(user);
  for entry in entries {
    emit entry[0] + " = " + str(entry[1]);
  }
}

A.5 Regex Functions #

Functions for regular expression matching and replacement.

regex_match(pattern, text) -> bool #

Returns true if the text matches the regular expression pattern.

neam
{
  emit str(regex_match("^[a-z]+@[a-z]+\\.[a-z]+$", "user@example.com"));  // true
  emit str(regex_match("^\\d{3}-\\d{4}$", "555-1234"));                   // true
  emit str(regex_match("^\\d+$", "abc"));                                  // false
}

regex_find(pattern, text) -> string #

Returns the first substring matching the pattern, or an empty string if no match.

neam
{
  let email = regex_find("[\\w]+@[\\w]+\\.[\\w]+", "Contact us at info@neam.dev today");
  emit email;  // "info@neam.dev"
}

regex_find_all(pattern, text) -> list #

Returns a list of all substrings matching the pattern.

neam
{
  let numbers = regex_find_all("\\d+", "Order 123 has 4 items at $56 each");
  emit str(numbers);  // ["123", "4", "56"]
}

regex_replace(pattern, text, replacement) -> string #

Replaces all matches of the pattern with the replacement string.

neam
{
  let cleaned = regex_replace("\\s+", "  too   many   spaces  ", " ");
  emit cleaned;  // " too many spaces "

  let redacted = regex_replace("\\d{4}-\\d{4}-\\d{4}-(\\d{4})", "Card: 1234-5678-9012-3456", "****-****-****-$1");
  emit redacted;  // "Card: ****-****-****-3456"
}

A.6 Environment Functions #

Functions for reading environment variables at runtime.

env_get(name) -> string #

Returns the value of an environment variable. Throws a runtime error if the variable is not set.

Parameter Type Description
name string The environment variable name
neam
{
  let api_key = env_get("OPENAI_API_KEY");
  emit "Key loaded: " + substring(api_key, 0, 8) + "...";
}

env_get_or(name, default) -> string #

Returns the value of an environment variable, or the default value if not set.

Parameter Type Description
name string The environment variable name
default string Fallback value if variable is not set
neam
{
  let port = env_get_or("PORT", "8080");
  let debug = env_get_or("DEBUG", "false");
  emit "Starting on port " + port;
}

env_has(name) -> bool #

Returns true if the environment variable is set.

neam
{
  if (env_has("OPENAI_API_KEY")) {
    emit "OpenAI configured.";
  } else {
    emit "Warning: No OpenAI key found.";
  }
}

A.7 Math Functions #

Mathematical operations. All functions operate on numbers and return numbers unless otherwise noted.

math_abs(x) -> number #

Returns the absolute value of x.

neam
{ emit str(math_abs(-42)); }  // 42

math_floor(x) -> number #

Returns the largest integer less than or equal to x.

neam
{ emit str(math_floor(3.7)); }  // 3

math_ceil(x) -> number #

Returns the smallest integer greater than or equal to x.

neam
{ emit str(math_ceil(3.2)); }  // 4

math_round(x) -> number #

Returns x rounded to the nearest integer.

neam
{ emit str(math_round(3.5)); }  // 4

math_min(a, b) -> number #

Returns the smaller of a and b.

neam
{ emit str(math_min(10, 3)); }  // 3

math_max(a, b) -> number #

Returns the larger of a and b.

neam
{ emit str(math_max(10, 3)); }  // 10

math_clamp(x, min, max) -> number #

Clamps x to the range [min, max].

neam
{
  emit str(math_clamp(15, 0, 10));  // 10
  emit str(math_clamp(-5, 0, 10));  // 0
  emit str(math_clamp(5, 0, 10));   // 5
}

math_sqrt(x) -> number #

Returns the square root of x.

neam
{ emit str(math_sqrt(16)); }  // 4

math_pow(base, exponent) -> number #

Returns base raised to the power of exponent.

neam
{ emit str(math_pow(2, 10)); }  // 1024

math_sin(x) -> number #

Returns the sine of x (x in radians).

neam
{ emit str(math_sin(0)); }  // 0

math_cos(x) -> number #

Returns the cosine of x (x in radians).

neam
{ emit str(math_cos(0)); }  // 1

math_tan(x) -> number #

Returns the tangent of x (x in radians).

neam
{ emit str(math_tan(0)); }  // 0

math_asin(x) -> number #

Returns the arcsine of x in radians. Domain: [-1, 1].

neam
{ emit str(math_asin(1)); }  // 1.5708 (pi/2)

math_acos(x) -> number #

Returns the arccosine of x in radians. Domain: [-1, 1].

neam
{ emit str(math_acos(0)); }  // 1.5708 (pi/2)

math_atan(x) -> number #

Returns the arctangent of x in radians.

neam
{ emit str(math_atan(1)); }  // 0.7854 (pi/4)

math_atan2(y, x) -> number #

Returns the angle in radians between the positive x-axis and the point (x, y).

neam
{ emit str(math_atan2(1, 1)); }  // 0.7854 (pi/4)

math_exp(x) -> number #

Returns e raised to the power of x.

neam
{ emit str(math_exp(1)); }  // 2.71828

math_log(x) -> number #

Returns the natural logarithm (base e) of x.

neam
{ emit str(math_log(2.71828)); }  // ~1.0

math_log10(x) -> number #

Returns the base-10 logarithm of x.

neam
{ emit str(math_log10(1000)); }  // 3

math_cbrt(x) -> number #

Returns the cube root of x.

neam
{ emit str(math_cbrt(27)); }  // 3

math_random() -> number #

Returns a random floating-point number in the range [0.0, 1.0).

neam
{
  let r = math_random();
  emit "Random: " + str(r);  // e.g., "Random: 0.472831"
}

math_random_int(min, max) -> number #

Returns a random integer in the range [min, max] (inclusive).

neam
{
  let dice = math_random_int(1, 6);
  emit "Dice roll: " + str(dice);  // e.g., "Dice roll: 4"
}

A.8 Time Functions #

Functions for working with timestamps, durations, and scheduling.

clock() -> number #

Returns the elapsed time in seconds since the VM started. Useful for benchmarking.

neam
{
  let start = clock();
  // ... do work ...
  let elapsed = clock() - start;
  emit "Elapsed: " + str(elapsed) + "s";
}

time_now() -> string #

Returns the current UTC date-time as an ISO 8601 string.

neam
{ emit time_now(); }  // "2026-01-15T14:30:00Z"

time_now_millis() -> number #

Returns the current Unix timestamp in milliseconds.

neam
{ emit str(time_now_millis()); }  // 1768500600000

time_now_micros() -> number #

Returns the current Unix timestamp in microseconds.

neam
{ emit str(time_now_micros()); }  // 1768500600000000

time_sleep(milliseconds) -> nil #

Pauses execution for the specified number of milliseconds.

Parameter Type Description
milliseconds number Duration to sleep in ms
neam
{
  emit "Starting...";
  time_sleep(1000);  // Sleep 1 second
  emit "Done.";
}

time_parse(text, format) -> number #

Parses a date-time string into a Unix timestamp (seconds).

Parameter Type Description
text string The date-time string to parse
format string The format string (e.g., "%Y-%m-%dT%H:%M:%S")
neam
{
  let ts = time_parse("2026-01-15T14:30:00", "%Y-%m-%dT%H:%M:%S");
  emit str(ts);  // Unix timestamp
}

time_format(timestamp, format) -> string #

Formats a Unix timestamp (seconds) into a string.

Parameter Type Description
timestamp number Unix timestamp in seconds
format string The format string
neam
{
  let ts = time_now_millis() / 1000;
  let formatted = time_format(ts, "%Y-%m-%d %H:%M:%S");
  emit formatted;  // "2026-01-15 14:30:00"
}

A.9 File Functions #

Functions for reading and writing files. All paths are relative to the working directory unless an absolute path is provided.

file_read_string(path) -> string #

Reads an entire file as a UTF-8 string.

neam
{
  let content = file_read_string("./data/config.json");
  let config = json_parse(content);
  emit config["version"];
}

file_write_string(path, content) -> nil #

Writes a UTF-8 string to a file. Creates the file if it does not exist; overwrites if it does.

neam
{
  let report = "Pipeline Report\nStatus: OK\n";
  file_write_string("./reports/daily.txt", report);
}

file_read_bytes(path) -> list #

Reads a file as a list of byte values (numbers 0-255).

neam
{
  let bytes = file_read_bytes("./data/image.png");
  emit "File size: " + str(len(bytes)) + " bytes";
}

file_write_bytes(path, bytes) -> nil #

Writes a list of byte values to a file.

neam
{
  let header = [0x89, 0x50, 0x4E, 0x47];  // PNG header
  file_write_bytes("./output/header.bin", header);
}

file_exists(path) -> bool #

Returns true if the file or directory exists.

neam
{
  if (file_exists("./config.json")) {
    emit "Config found.";
  } else {
    emit "Using defaults.";
  }
}

file_remove(path) -> nil #

Deletes a file. Throws if the file does not exist.

neam
{
  if (file_exists("./tmp/cache.dat")) {
    file_remove("./tmp/cache.dat");
  }
}

file_copy(source, destination) -> nil #

Copies a file from source to destination.

neam
{
  file_copy("./config.json", "./config.json.bak");
}

file_rename(old_path, new_path) -> nil #

Renames or moves a file.

neam
{
  file_rename("./output/draft.txt", "./output/final.txt");
}

file_open(path, mode) -> handle #

Opens a file and returns a file handle. Mode: "r" (read), "w" (write), "a" (append).

Parameter Type Description
path string File path
mode string "r", "w", or "a"
neam
{
  let f = file_open("./log.txt", "a");
  // Use with file handle methods (future extension)
}

A.10 HTTP Functions #

Functions for making HTTP requests to external services.

http_get(url) -> string #

Performs an HTTP GET request and returns the response body as a string.

Parameter Type Description
url string The URL to fetch

Returns: Response body as a string. Throws on connection errors or non-2xx status codes.

neam
{
  let response = http_get("https://api.example.com/status");
  let data = json_parse(response);
  emit "Status: " + data["status"];
}

http_request(options) -> string #

Performs a configurable HTTP request with full control over method, headers, and body.

Parameter Type Description
options map Request configuration

Options map fields:

Field Type Required Description
method string yes HTTP method: GET, POST, PUT, DELETE, PATCH
url string yes Request URL
headers map no HTTP headers as key-value pairs
body string no Request body

Returns: Response body as a string.

neam
{
  let response = http_request({
    "method": "POST",
    "url": "https://api.example.com/data",
    "headers": {
      "Content-Type": "application/json",
      "Authorization": "Bearer sk-abc123"
    },
    "body": json_stringify({ "key": "value" })
  });
  emit response;
}

A.11 Crypto Functions #

Cryptographic and encoding functions.

crypto_hash(algorithm, data) -> string #

Computes a cryptographic hash of the data.

Parameter Type Description
algorithm string "sha256", "sha384", "sha512", or "md5"
data string The data to hash

Returns: Hex-encoded hash string.

neam
{
  let hash = crypto_hash("sha256", "hello world");
  emit hash;  // "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
}

crypto_hmac(algorithm, key, data) -> string #

Computes an HMAC (Hash-based Message Authentication Code).

Parameter Type Description
algorithm string "sha256", "sha384", or "sha512"
key string The secret key
data string The data to authenticate

Returns: Hex-encoded HMAC string.

neam
{
  let mac = crypto_hmac("sha256", "secret-key", "message");
  emit mac;
}

crypto_random_bytes(count) -> string #

Generates cryptographically secure random bytes, returned as a hex-encoded string.

Parameter Type Description
count number Number of random bytes to generate
neam
{
  let token = crypto_random_bytes(32);
  emit "Token: " + token;  // 64-character hex string
}

crypto_uuid_v4() -> string #

Generates a random UUID v4.

neam
{
  let id = crypto_uuid_v4();
  emit id;  // "550e8400-e29b-41d4-a716-446655440000"
}

crypto_base64_encode(data) -> string #

Encodes a string to Base64.

neam
{
  let encoded = crypto_base64_encode("Hello, Neam!");
  emit encoded;  // "SGVsbG8sIE5lYW0h"
}

crypto_base64_decode(encoded) -> string #

Decodes a Base64 string.

neam
{
  let decoded = crypto_base64_decode("SGVsbG8sIE5lYW0h");
  emit decoded;  // "Hello, Neam!"
}

crypto_hex_encode(data) -> string #

Encodes a string to hexadecimal.

neam
{
  let hex = crypto_hex_encode("AB");
  emit hex;  // "4142"
}

crypto_hex_decode(hex) -> string #

Decodes a hexadecimal string.

neam
{
  let data = crypto_hex_decode("4142");
  emit data;  // "AB"
}

A.12 Voice Functions #

Functions for speech-to-text, text-to-speech, and real-time voice streaming. Requires a voice pipeline declaration in the program.

voice_transcribe(pipeline, audio_path) -> string #

Transcribes an audio file to text using the pipeline's STT provider.

Parameter Type Description
pipeline string Name of the voice pipeline
audio_path string Path to the audio file (WAV, MP3, M4A)

Returns: Transcribed text.

neam
{
  let text = voice_transcribe("my_pipeline", "/tmp/recording.wav");
  emit "You said: " + text;
}

voice_synthesize(pipeline, text, output_path) -> nil #

Synthesizes text to an audio file using the pipeline's TTS provider.

Parameter Type Description
pipeline string Name of the voice pipeline
text string Text to synthesize
output_path string Path for the output audio file
neam
{
  voice_synthesize("my_pipeline", "Hello!", "/tmp/greeting.mp3");
}

voice_pipeline_run(pipeline, audio_path) -> string #

Runs the complete voice pipeline: STT -> Agent -> TTS. Returns the agent's text response.

Parameter Type Description
pipeline string Name of the voice pipeline
audio_path string Path to the input audio file

Returns: The agent's text response (audio output is saved alongside the input).

neam
{
  let response = voice_pipeline_run("my_pipeline", "/tmp/question.wav");
  emit "Agent said: " + response;
}

realtime_connect(pipeline) -> nil #

Establishes a real-time WebSocket connection for full-duplex voice streaming.

neam
{
  realtime_connect("my_realtime_pipeline");
  emit "Connected to real-time voice.";
}

realtime_send_audio(pipeline, audio_chunk) -> nil #

Sends an audio chunk through the real-time connection.

Parameter Type Description
pipeline string Name of the voice pipeline
audio_chunk string Base64-encoded audio data
neam
{
  realtime_send_audio("my_pipeline", audio_data);
}

realtime_send_text(pipeline, text) -> nil #

Sends a text message through the real-time connection.

neam
{
  realtime_send_text("my_pipeline", "What is the weather today?");
}

A.13 Agent Cognitive Functions #

Functions for interacting with agent cognitive features: reflection, learning, evolution, autonomy, and goal management. These functions operate on agents that have cognitive properties enabled.

agent_status(agent_name) -> map #

Returns the full cognitive status of an agent.

Parameter Type Description
agent_name string The agent's declared name

Returns: A map with keys: reasoning_mode, learning_count, evolution_version, goals, evolved_prompt, budget_calls_used, budget_cost_used, budget_tokens_used.

neam
{
  let s = agent_status("MyAgent");
  emit "Reasoning: " + str(s["reasoning_mode"]);
  emit "Evolution v" + str(s["evolution_version"]);
}

agent_pause(agent_name) -> nil #

Pauses autonomous execution for an agent.

neam
{ agent_pause("Monitor"); }

agent_resume(agent_name) -> nil #

Resumes autonomous execution for a paused agent.

neam
{ agent_resume("Monitor"); }

agent_rate(agent_name, score) -> nil #

Submits an explicit feedback score for the agent's most recent response.

Parameter Type Description
agent_name string The agent's name
score number Feedback score from 0.0 to 1.0
neam
{
  let answer = MyAgent.ask("question");
  agent_rate("MyAgent", 0.9);
}

agent_reflect(agent_name) -> map #

Triggers on-demand reflection and returns dimension scores.

Returns: A map of dimension names to scores, e.g., {"accuracy": 0.85, "relevance": 0.9}.

neam
{
  let scores = agent_reflect("MyAgent");
  emit "Accuracy: " + str(scores["accuracy"]);
}

agent_learning_stats(agent_name) -> map #

Returns learning statistics for an agent.

Returns: A map with keys: total_interactions, avg_reflection_score, reviews_completed.

neam
{
  let stats = agent_learning_stats("MyAgent");
  emit "Interactions: " + str(stats["total_interactions"]);
}

agent_set_goals(agent_name, goals) -> nil #

Updates an agent's goals at runtime.

Parameter Type Description
agent_name string The agent's name
goals list New list of goal strings
neam
{
  agent_set_goals("Monitor", [
    "Check CPU usage",
    "Report anomalies"
  ]);
}

agent_get_goals(agent_name) -> list #

Returns the current goals list for an agent.

neam
{
  let goals = agent_get_goals("Monitor");
  emit str(goals);
}

agent_evolve(agent_name) -> nil #

Triggers a manual prompt evolution cycle, regardless of the review_after threshold.

neam
{ agent_evolve("MyAgent"); }

agent_prompt_history(agent_name) -> list #

Returns a list of all evolved prompt strings. Index 0 is the original prompt.

neam
{
  let history = agent_prompt_history("MyAgent");
  emit "Versions: " + str(len(history));
}

agent_rollback(agent_name, version) -> nil #

Rolls back an agent's prompt to a specific version number.

Parameter Type Description
agent_name string The agent's name
version number The version number to rollback to
neam
{
  agent_rollback("MyAgent", 0);  // Rollback to original prompt
}

A.14 Async Functions #

Functions for working with asynchronous operations and futures.

future_resolve(value) -> future #

Creates an immediately resolved future with the given value.

neam
{
  let f = future_resolve(42);
  let result = await f;
  emit str(result);  // 42
}

future_reject(error) -> future #

Creates an immediately rejected future with the given error message.

neam
{
  let f = future_reject("something went wrong");
  // Awaiting this will throw a runtime error
}

future_all(futures) -> future #

Returns a future that resolves when all input futures resolve. The result is a list of values.

Parameter Type Description
futures list A list of futures
neam
{
  let f1 = async { http_get("https://api.example.com/a") };
  let f2 = async { http_get("https://api.example.com/b") };
  let results = await future_all([f1, f2]);
  emit "Got " + str(len(results)) + " responses";
}

future_race(futures) -> future #

Returns a future that resolves with the value of the first future to complete.

neam
{
  let f1 = async { http_get("https://api-us.example.com/data") };
  let f2 = async { http_get("https://api-eu.example.com/data") };
  let fastest = await future_race([f1, f2]);
  emit "Fastest response: " + fastest;
}

await_all(futures) -> list #

Convenience function: equivalent to await future_all(futures).

neam
{
  let results = await_all([f1, f2, f3]);
  emit "All done: " + str(len(results));
}

A.15 Assert Functions #

Assertion functions for testing. These throw a runtime error with a descriptive message if the assertion fails. Designed for use with neamc test.

assert_eq(actual, expected) -> nil #

Asserts that actual equals expected.

neam
{
  assert_eq(2 + 2, 4);
  assert_eq("hello", "hello");
}

assert_ne(actual, expected) -> nil #

Asserts that actual does not equal expected.

neam
{
  assert_ne(2 + 2, 5);
}

assert_true(value) -> nil #

Asserts that the value is true.

neam
{
  assert_true(10 > 5);
}

assert_false(value) -> nil #

Asserts that the value is false.

neam
{
  assert_false(10 < 5);
}

assert_some(value) -> nil #

Asserts that the value is not nil.

neam
{
  let x = "hello";
  assert_some(x);
}

assert_none(value) -> nil #

Asserts that the value is nil.

neam
{
  let x = nil;
  assert_none(x);
}

assert_ok(result) -> nil #

Asserts that a result value represents success (not an error).

neam
{
  let result = { "ok": true, "value": 42 };
  assert_ok(result);
}

assert_err(result) -> nil #

Asserts that a result value represents an error.

neam
{
  let result = { "ok": false, "error": "not found" };
  assert_err(result);
}

assert_throws(func) -> nil #

Asserts that calling the given function throws a runtime error.

neam
{
  assert_throws(fun() {
    let x = 1 / 0;
  });
}

A.16 Error Functions #

Functions for error handling, context annotation, and controlled failure.

panic(message) -> never #

Immediately terminates execution with an error message. Use for unrecoverable errors.

Parameter Type Description
message string The error message
neam
{
  let config = json_parse(file_read_string("config.json"));
  if (config["version"] != "1.0") {
    panic("Unsupported config version: " + str(config["version"]));
  }
}

context(message) -> nil #

Adds contextual information to the current error context stack. If an error occurs later, the context messages are included in the error trace.

neam
{
  context("Processing order ORD-123");
  context("Step: validation");
  // If an error occurs here, the context is included in the trace
}

with_context(message, func) -> value #

Executes a function within a named context. If the function throws, the context message is included in the error trace.

Parameter Type Description
message string Context description
func function The function to execute

Returns: The function's return value.

neam
{
  let result = with_context("Loading configuration", fun() {
    return json_parse(file_read_string("config.json"));
  });
  emit "Config loaded: " + str(result["version"]);
}

try(func) -> map #

Executes a function and catches any error, returning a result map instead of throwing.

Parameter Type Description
func function The function to execute

Returns: {"ok": true, "value": result} on success, {"ok": false, "error": message} on failure.

neam
{
  let result = try(fun() {
    return json_parse("invalid json{{{");
  });

  if (result["ok"]) {
    emit "Parsed: " + str(result["value"]);
  } else {
    emit "Error: " + result["error"];
  }
}

A.17 NeamClaw Workspace and Memory Functions #

These functions provide workspace file operations, semantic memory search, and session history access for NeamClaw agent types (claw agents and forge agents). Workspace functions operate within the agent's scoped workspace directory. All paths are resolved relative to the workspace root, and path traversal (..) is rejected at runtime.

workspace_read(path) -> string|nil #

Reads the contents of a file from the agent's workspace directory.

Parameter Type Description
path string Relative path within the workspace (e.g., "notes/meeting.txt")

Returns: The file contents as a string, or nil if the file does not exist.

Security: The path is resolved relative to the workspace root. Paths containing .. are rejected with a runtime error.

neam
{
  let notes = workspace_read("MEMORY.md");
  if (notes != nil) {
    emit "Memory contents: " + notes;
  } else {
    emit "No memory file found.";
  }
}

workspace_write(path, content) -> bool #

Writes content to a file in the agent's workspace directory, creating the file and any parent directories if they do not exist. Overwrites the file if it already exists.

Parameter Type Description
path string Relative path within the workspace
content string Content to write

Returns: true on success, false on failure (e.g., disk full, permission denied).

neam
{
  let success = workspace_write("notes/meeting.txt", "Meeting notes here...");
  if (success) {
    emit "Notes saved.";
  }
}

workspace_append(path, content) -> bool #

Appends content to an existing file in the agent's workspace directory, creating the file and any parent directories if they do not exist.

Parameter Type Description
path string Relative path within the workspace
content string Content to append

Returns: true on success, false on failure.

neam
{
  // Append a log entry
  workspace_append("logs/activity.log", "User logged in\n");

  // Build up a memory file over multiple interactions
  workspace_append("MEMORY.md", "- User prefers dark mode\n");
}

memory_search(query, top_k?) -> list #

Performs semantic search across all indexed .md files in the agent's workspace. Uses hybrid scoring: 70% vector similarity plus 30% BM25 keyword matching. Requires semantic memory to be configured on the agent (via the semantic_memory field or impl Searchable).

Parameter Type Description
query string Natural language search query
top_k number (optional) Maximum number of results to return. Default: 5.

Returns: A list of maps, each containing file_path (string), chunk (string), and score (number from 0.0 to 1.0), sorted by descending score.

neam
{
  // Basic search
  let results = memory_search("authentication flow");

  // Search with custom result count
  let results = memory_search("user preferences for UI", 10);

  // Process results
  for (let r in results) {
    emit f"[{r['score']}] {r['file_path']}: {r['chunk']}";
  }
}

session_history(session_key?, limit?) -> list #

Reads the conversation transcript from a session's JSONL storage. Without arguments, reads the current session. Useful for cross-session analysis and audit logging.

Parameter Type Description
session_key string (optional) Session key to read. Default: current session.
limit number (optional) Maximum number of recent turns to return. Default: all turns.

Returns: A list of maps, each containing role (string: "user" or "assistant") and content (string), ordered chronologically.

neam
{
  // Get all history for the current session
  let hist = session_history();

  // Get last 10 turns for a specific user session
  let hist = session_history("user_123", 10);

  // Count user messages
  let user_msgs = list_filter(hist, fun(entry) {
    return entry["role"] == "user";
  });
  emit f"User has sent {len(user_msgs)} messages.";
}

Quick Reference Table #

Category Function Arity Returns
Core len 1 number
Core str 1 string
Core print 1 nil
Core typeof 1 string
Core json_parse 1 value
Core json_stringify 1 string
Core input 1 string
Core emit 1 nil
String contains 2 bool
String starts_with 2 bool
String ends_with 2 bool
String index_of 2 number
String substring 3 string
String replace 3 string
String split 2 list
String join 2 string
String trim 1 string
String str_lower 1 string
String str_upper 1 string
String str_repeat 2 string
String str_pad_left 3 string
String str_pad_right 3 string
List list_push 2 list
List list_pop 1 list
List list_slice 3 list
List list_contains 2 bool
List list_index_of 2 number
List list_reverse 1 list
List list_sort 1 list
List list_map 2 list
List list_filter 2 list
List list_reduce 3 value
List list_flat_map 2 list
List list_unique 1 list
List list_zip 2 list
Map map_keys 1 list
Map map_values 1 list
Map map_has 2 bool
Map map_remove 2 map
Map map_merge 2 map
Map map_entries 1 list
Regex regex_match 2 bool
Regex regex_find 2 string
Regex regex_find_all 2 list
Regex regex_replace 3 string
Env env_get 1 string
Env env_get_or 2 string
Env env_has 1 bool
Math math_abs 1 number
Math math_floor 1 number
Math math_ceil 1 number
Math math_round 1 number
Math math_min 2 number
Math math_max 2 number
Math math_clamp 3 number
Math math_sqrt 1 number
Math math_pow 2 number
Math math_sin 1 number
Math math_cos 1 number
Math math_tan 1 number
Math math_asin 1 number
Math math_acos 1 number
Math math_atan 1 number
Math math_atan2 2 number
Math math_exp 1 number
Math math_log 1 number
Math math_log10 1 number
Math math_cbrt 1 number
Math math_random 0 number
Math math_random_int 2 number
Time clock 0 number
Time time_now 0 string
Time time_now_millis 0 number
Time time_now_micros 0 number
Time time_sleep 1 nil
Time time_parse 2 number
Time time_format 2 string
File file_read_string 1 string
File file_write_string 2 nil
File file_read_bytes 1 list
File file_write_bytes 2 nil
File file_exists 1 bool
File file_remove 1 nil
File file_copy 2 nil
File file_rename 2 nil
File file_open 2 handle
HTTP http_get 1 string
HTTP http_request 1 string
Crypto crypto_hash 2 string
Crypto crypto_hmac 3 string
Crypto crypto_random_bytes 1 string
Crypto crypto_uuid_v4 0 string
Crypto crypto_base64_encode 1 string
Crypto crypto_base64_decode 1 string
Crypto crypto_hex_encode 1 string
Crypto crypto_hex_decode 1 string
Voice voice_transcribe 2 string
Voice voice_synthesize 3 nil
Voice voice_pipeline_run 2 string
Voice realtime_connect 1 nil
Voice realtime_send_audio 2 nil
Voice realtime_send_text 2 nil
Cognitive agent_status 1 map
Cognitive agent_pause 1 nil
Cognitive agent_resume 1 nil
Cognitive agent_rate 2 nil
Cognitive agent_reflect 1 map
Cognitive agent_learning_stats 1 map
Cognitive agent_set_goals 2 nil
Cognitive agent_get_goals 1 list
Cognitive agent_evolve 1 nil
Cognitive agent_prompt_history 1 list
Cognitive agent_rollback 2 nil
Async future_resolve 1 future
Async future_reject 1 future
Async future_all 1 future
Async future_race 1 future
Async await_all 1 list
Assert assert_eq 2 nil
Assert assert_ne 2 nil
Assert assert_true 1 nil
Assert assert_false 1 nil
Assert assert_some 1 nil
Assert assert_none 1 nil
Assert assert_ok 1 nil
Assert assert_err 1 nil
Assert assert_throws 1 nil
Error panic 1 never
Error context 1 nil
Error with_context 2 value
Error try 1 map
Workspace workspace_read 1 string
Workspace workspace_write 2 bool
Workspace workspace_append 2 bool
Memory memory_search 1-2 list
Memory session_history 0-2 list
Start typing to search...