Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Engine reference — generated from the canonical engineering source. Do not edit this page by hand.

Architecture: See cel-vision.md (docs/cel-vision.md) for the design philosophy, cross-runtime contract, and subsystem relationships. This document is the API reference.

cel.lua — ZERG Standard Library

cel.lua is the unified standard library for the ZERG project. It provides a consistent API surface across both the Luna client (LuaJIT) and the Sol plugin sandbox (luerl), so developers and plugin authors can rely on a single import for JSON, OOP, collections, and utilities.

Import

Luna client (LuaJIT)
local cel = require("core.cel")

Sol plugin sandbox (luerl)
cel is preloaded as a global by sol_sandbox_shared:preload_stdlib/1 — no require needed
local cel = cel

Subsystems

cel.json — JSON Encode/Decode

Dual-backend JSON that automatically selects the best available implementation: Preferred on BOTH runtimes: JSON_luerl (pure Lua, the project’s own vendored lib — per; more robust than dkjson, which has a nil-comparison panic bug on some data shapes) Fallback (LuaJIT): dkjson — used only when vendor.JSON_luerl cannot be required

local obj = cel.json.decode('{"name":"alice","age":30}')
Returns: obj, nil

local str = cel.json.encode({items = {1, 2, 3}})
Returns: '{"items":[1,2,3]}'

Error handling:
local obj, err = cel.json.decode("invalid")
obj = nil, err = "expected..."
APISignatureReturns
cel.json.encode(t)table → string; a string input passes through unchangedJSON string
cel.json.decode(s)string → table(obj, nil) on success, (nil, err) on failure

The 2-value nil, err boundary is normalized inside cel — the underlying backends return three values (obj, nil, err), but the third slot is never echoed. Note: this boundary exists in the Luna build; the trimmed luerl build still returns the raw 3-value shape and additionally exposes cel.json.encode_pretty(t).

cel.class — Object-Oriented Programming

middleclass v4.1.1 — class definition, single inheritance, mixins, metamethods.

local Animal = cel.class("Animal")
function Animal:initialize(name)
    self.name = name
end
function Animal:speak()
    return "I am " .. self.name
end

local Dog = cel.class("Dog", Animal)
function Dog:initialize(name, breed)
    Animal.initialize(self, name)
    self.breed = breed
end

local d = Dog("Rex", "Lab")  -- __call shorthand
assert(d.name == "Rex")
assert(d.class.name == "Dog")
assert(d:speak() == "I am Rex")

Plugin pattern: Sol plugins use a thin module wrapper around a singleton instance, because the plugin manager calls plugin.init(config) (dot-call, no self):

local MyPlugin = cel.class("MyPlugin", cel.ChannelPlugin)
function MyPlugin:initialize(config)
    cel.ChannelPlugin.initialize(self, config)
end
... methods...

local _instance = nil
local plugin = { name = "my_plugin", config_schema = {...} }
function plugin.init(config)
    _instance = MyPlugin(config)
    return true
end
plugin.send_message = function(...)
    return _instance:send_message(_instance, ...)
end
return plugin
APIDescription
cel.class(name)Define a new class
cel.class(name, parent)Define a subclass
ClassName:initialize(...)Constructor
instance.classRuntime type reference
instance.class.nameClass name string

cel.ChannelPlugin — Plugin Base Class

Available in the Sol plugin sandbox build of cel only (server/priv/lua_libs/cel.lua). Provides shared channel plugin functionality:

local TelegramPlugin = cel.class("TelegramPlugin", cel.ChannelPlugin)
function TelegramPlugin:initialize(config)
    cel.ChannelPlugin.initialize(self, config)
    self.parse_mode = config.parse_mode or "MarkdownV2"
end
MethodDescription
:initialize(config)Set up rate limiting, queue, config (rate_limit_ms default 100, max_queue_depth default 100, max_message_len default 4096)
:validate_config(schema)Check required fields; apply optional defaults
:start_backend(channel_id)Create backend state for a channel
:stop_backend(channel_id)Remove backend state
:queue_message(channel_id, msg)Enqueue with depth check (queue full error at cap)
:check_rate_limit(channel_id)Returns true if at least rate_limit_ms has elapsed
:enqueue(channel_id, msg)Alias that forwards to queue_message
:sleep(ms)No-op in the sandbox (async drain model)
:drain_queue(channel_id)Pop queued messages while rate limit allows; calls self:do_send if defined
:truncate(text, max_len)Truncate with "..." suffix (default cap max_message_len)
:format_event(type, data)Override in subclasses (base returns nil)
:shutdownStop all backends

cel.X — Eager Collection Operations (Lume)

One-shot table transforms. Use for small-to-medium data where readability matters.

local names = cel.map(users, function(u) return u.name end)
local active = cel.filter(items, function(i) return i.active end)
local found = cel.find(list, "admin")            -- value equality, not predicate
local has_admin = cel.any(roles, function(r) return r == "admin" end)
APISignatureReturns
cel.map(t, fn)Transform valuesNew table (preserves keys)
cel.filter(t, fn)Keep matching (predicate)New array/dict
cel.each(t, fn)Side-effect iterationnil
cel.reduce(t, fn, init)AccumulateSingle value
cel.any(t, fn)Short-circuit ORboolean
cel.all(t, fn)Short-circuit ANDboolean
cel.find(t, value)Value-equality search (NOT a predicate — the needle is compared with ==)Key/index of the match, or nil
cel.keys(t)Extract keysArray
cel.values(t)Extract valuesArray
cel.clone(t)Shallow copyNew table
cel.extend(a, b)Merge b into aTable a (mutated)
cel.pick(t,...keys)Project only the named keysNew table
cel.split(str, sep)Split stringArray
cel.trim(str)Strip whitespaceString
cel.format(fmt,...)String formattingString
cel.wordwrap(str, limit)Wrap text at widthString
cel.serialize(t)Serialize to stringString
cel.deserialize(s)Parse serializedTable
cel.clamp(x, min, max)Constrain number to rangeNumber
cel.lerp(a, b, t)Linear interpolationNumber
cel.random(a, b)Random number (int or float form)Number
cel.uuidRandom UUIDString

When to use cel.X: One-shot transforms on data that fits in memory. Prefer over raw loops when the predicate is a single expression.

cel.iter — Lazy Iterator Pipelines (Fun)

Composable lazy iterators. Use for large datasets, chains of 3+ transforms, or when you want zero intermediate allocations.

local pipeline = cel.iter.range(1, 1000)
    |> cel.iter.map(function(x) return x * 2 end)
    |> cel.iter.filter(function(x) return x % 3 == 0 end)
    |> cel.iter.take(10)
for _, v in pipeline do
    print(v)  -- 6, 12, 18, ...
end
APIDescription
cel.iter.range(start, stop)Integer iterator
cel.iter.map(fn, iter)Transform elements
cel.iter.filter(fn, iter)Keep matching
cel.iter.reduce(fn, init, iter)Fold to single value
cel.iter.each(fn, iter)Side-effect traversal
cel.iter.take(n, iter)First n elements
cel.iter.drop(n, iter)Skip first n elements
cel.iter.zip(iter1, iter2)Pair elements
cel.iter.chain(iter1, iter2)Concatenate iterators
cel.iter.enumerate(iter)(index, value) pairs
cel.iter.cycle(iter)Infinite repeat
cel.iter.duplicate(val)Infinite constant
cel.iter.wrap(x)Wrap a value/table so it iterates (Fun adapter)
cel.iter.unwrap(x)Inverse of wrap
cel.iter.to_table(iter)Collect to array

When to use cel.iter: Chains of 3+ transforms, large datasets (thousands+), or when you want zero intermediate table allocations. For single transforms, prefer cel.X.

cel.vec — 2D Vector Math

Immutable 2D vector operations (luerl-safe — no __call metamethod). Available for game/AI/physics plugins.

local v = cel.vec.new(3, 4)
assert(cel.vec.mag(v) == 5)
local n = cel.vec.norm(v)
assert(cel.vec.mag(n) == 1)
local sum = cel.vec.add(cel.vec.new(1, 0), cel.vec.new(0, 1))
APIDescription
cel.vec.new(x, y)Create vector (defaults 0, 0)
cel.vec.from_angle(theta)Unit vector from angle (screen-coords: y = −sin θ)
cel.vec.randomRandom unit vector
cel.vec.is(t)True if t is a cel.vec
cel.vec.to_table(v)To {x, y} table
cel.vec.from_table(t)From {x, y} or {[1], [2]} array
cel.vec.clone(v)Copy
cel.vec.mag(v)Magnitude
cel.vec.mag_sq(v)Squared magnitude
cel.vec.set_mag(v, mag)Rescale to length
cel.vec.norm(v)Normalize (zero vector returns a clone)
cel.vec.limit(v, max)Clamp magnitude
cel.vec.add(a, b)Addition
cel.vec.sub(a, b)Subtraction
cel.vec.mul(a, b)Scalar or component multiply
cel.vec.div(v, s)Scalar divide
cel.vec.neg(v)Negate
cel.vec.eq(a, b)Component equality
cel.vec.dot(a, b)Dot product
cel.vec.dist(a, b)Distance
cel.vec.heading(v)Angle of vector (y-flipped to match from_angle)
cel.vec.rotate(v, theta)Rotate by angle

cel.shell_quote — Shell Argument Safety

The ONLY sanctioned way to pass any value into a shell command line. Always wraps in single quotes (even non-strings — input is stringified first), so the result is always exactly one shell token:

local cmd = "grep " .. cel.shell_quote(pattern) .. " " .. cel.shell_quote(path)
cel.shell_quote("it's") → 'it'\''s'

Blocklist sanitizers are forbidden in ZERG (the deprecated blocklist was deleted — ); use cel.shell_quote for every argument, no exceptions.

Validation Helpers

Shape-checkers for values interpolated into command lines. Each returns the input on success or nil on failure (never throws):

APIAccepts
cel.validate_image_name(s)Non-empty [_%w%.%-/:]+ that does not start with - (option-shaped tokens rejected)
cel.validate_path(s)Non-empty /, word, ., -, _ characters only
cel.validate_docker_name(s)Word characters, -, _ only

Secure Temp Files (fd discipline)

mkostemp-based temp file creation with mode 0600 and O_EXCL semantics. Two flavors:

APIContract
cel.secure_tmpfile(prefix?)Creates the file (0600), CLOSES it, returns the path. The reopen-by-name window is documented — keep this for read-only uses only.
cel.secure_tmpfile_fd(prefix?)Keeps the fd open; returns {fd, path} or nil, err. Write content through the fd — a same-dir attacker cannot swap the path pre-rename.
cel.fd_write_all(fd, content)Chunked (64KB) write to the open fd; true or nil, err. Caller owns/closes the fd.
cel.rename_tmpfile_fd(fdp, target)Links the fd’s INODE into place (linkat AT_EMPTY_PATH, with /proc/self/fd verify-then-rename fallback); refuses loudly on attacker unlink/swap. true or nil, err.

Write-then-rename flows MUST use the _fd trio; os.tmpname is banned.

cel.string.hash — FNV-1a Content Hash

cel.string.hash(s) returns an 8-hex-char FNV-1a 32-bit hash (16-bit-limb implementation so partial products stay below 2^53 — ). Used for content-distinct cache keys (e.g. long tool arguments); non-string input is stringified; without the bit library it degrades to the string length.

cel.ansi_sanitize — Escape-Sequence Stripping

cel.ansi_sanitize(s) strips terminal escape sequences and dangerous control bytes from untrusted text before it reaches agent context or terminal rendering:

CSI sequences (SGR color, cursor movement, device queries) OSC sequences (window-title / hyperlink smuggling), BEL- or ST-terminated DCS / SOS / PM / APC string-machine sequences Two-byte ESC sequences (charset designators, ESC 7, ESC =) Bare/trailing ESC, C0 controls (except \t and \n), and DEL Bytes 0x80–0x9F are untouched (UTF-8 continuation bytes — stripping them would corrupt multi-byte characters)

Returns a new string; input is never mutated. Non-string input is stringified.

Utility Functions

APIDescription
cel.deep_copy(t)Recursive table copy (non-table values pass through)
cel.deep_merge(base, overlay)Recursive merge — arrays extend when BOTH sides are arrays, tables recurse, scalars overwrite; returns base (mutated)
cel.is_array(t)True for non-empty contiguous 1..n integer-keyed tables
cel.split_lines(text)Split text by \n; empty string yields {}, no trailing empty line

Decision Guide

Do you need JSON?           → cel.json
Do you need a class?        → cel.class
Do you need a one-shot      → cel.X (eager)
  filter/map/any/find?
Do you need a pipeline      → cel.iter (lazy)
  of 3+ transforms?
Do you need 2D math?        → cel.vec
Do you need deep copy/merge?→ cel.deep_copy / cel.deep_merge
Do you need shell args?     → cel.shell_quote
Do you need temp files?     → cel.secure_tmpfile_fd (+ fd_write_all / rename_tmpfile_fd)
Do you need to render       → cel.ansi_sanitize
  untrusted terminal text?

Runtimes

FeatureLuaJIT (Luna)luerl (Sol sandbox)
cel.jsonJSON_luerl preferred (dkjson fallback); 2-value decode boundaryJSON_luerl; raw 3-value decode; plus encode_pretty
cel.classmiddleclass v4.1.1middleclass v4.1.1
cel.XLume (eager)Lume (eager)
cel.iterFun (lazy)Fun (lazy)
cel.vecFullFull
cel.shell_quote, validators, string.hash, ansi_sanitizeYesNo (trimmed luerl build omits them)
cel.secure_tmpfile / _fd trioYes (FFI)No (no FFI in luerl)
cel.ChannelPluginNoYes (plugins only)

The two builds have intentionally diverged: client/core/cel.lua carries the Luna-only FFI/security utilities; server/priv/lua_libs/cel.lua carries ChannelPlugin + encode_pretty for plugins. Shared subsystems (json, class, Lume/Fun collections, vec) are kept behaviorally identical.

Performance Reference

From benchmarks (100K elements, LuaJIT):

Operationcel.iter (Fun)cel.X (Lume)Raw Lua
map1.8ms22ms6ms
filter2.1ms220ms8ms
reduce1.2ms18ms5ms
take(10)0.01msN/AN/A

Cel.iter is 10-100x faster for large datasets (lazy, no allocation) Cel.X is more readable for small datasets (one-liners) Raw Lua is fine for simple cases where cel adds no clarity

File Locations

Runtimecel.luaDependencies
Luna (LuaJIT)client/core/cel.luaclient/vendor/middleclass.lua, client/vendor/dkjson.lua (fallback), client/vendor/fun_luerl.lua, client/vendor/lume.lua, client/vendor/JSON_luerl.lua
Sol (luerl)server/priv/lua_libs/cel.luaserver/priv/lua_libs/middleclass.lua, server/priv/lua_libs/fun.lua, server/priv/lua_libs/lume.lua, server/priv/lua_libs/JSON_luerl.lua (preloaded by sol_sandbox_shared:preload_stdlib/1)