The lua tool
The agent has a single tool, lua, taking one required argument: code (a string of Lua 5.4 source). See functions.md for the canonical host function reference, lua.md for full VM/scheduler details, and agent-loop.md for how tool calls fit into turns.
Tool call contract
- Arguments: JSON object
{"code": "..."}. Invalid JSON, a missing or non-stringcode, or calling any tool name other thanluareturns an error tool result (code = 1) immediately without starting a Lua job or firinglua_start/lua_endhooks. Unknown tool names tell the model to call functions such asreadorshinsidelua. - Compilation and return values: Tuse first tries compiling
return <code>so a lone expression (such asx + 1orread("a.txt")) returns its value automatically; if that does not parse, it compiles<code>as statements. - Output format: Captured
print(...)(tab-separated, newline-terminated) andio.write(...)(concatenated directly) come first, followed by any non-nil return values rendered withinspect(value)(tab-separated, separated from prior printed text by a newline when needed). Top-level returned strings render raw without quotes; tables with a__tostringmetamethod (includingshresults) usetostring; plain tables format with sorted keys, cycle detection (<cycle>), and a depth cap (root depth0; tables nested beyond depth6render as{...}). - Uncapped output: Tuse does not truncate
luacall output,sh().out, or task logs. Keep large outputs concise in your script (for exampleout:sub(1, 2000)orgrepwithlimit). - Exit status: Successful calls finish with
code = 0, errors and timeouts withcode = 1, and cancelled calls withcode = nil.
VM lifetime, timeouts, and scheduling
- Persistent VM: One Lua 5.4 VM runs on a dedicated thread for the lifetime of a session. Globals persist between
luacalls (uselocalfor scratch variables). Errors, timeouts, and cancellations do not destroy the VM or wipe globals. Starting/newor/resumecreates a fresh VM. - 120-second deadline: Each
luatool call has a 120-second wall-clock deadline. Tight CPU loops are interrupted via an instruction hook (every 1,000 instructions) and return[timed out]or[cancelled]. Start long jobs withspawn(fn, name)(background tasks have no deadline). - Cooperative scheduler: Agent tool calls, hooks, custom slash commands,
openhandlers, and background tasks all run as coroutines in the same VM. Waiting calls (sh,sleep,pick,ask,reload,llm) yield so other coroutines continue running;shandsleepalso yield through user-createdcoroutine.resumeandcoroutine.wrap. - Paused deadlines: Interactive UI waits (
pick,ask) andreload()pause the calling coroutine's remaining deadline while waiting and resume the remaining budget afterward.llm()does not pause the deadline. - Non-yieldable boundaries: Inside C callbacks where Lua cannot yield (for example a
string.gsubfunction),shandsleepblock the VM thread until finished (still respecting cancellation and deadlines), whilepick,ask,reload, andllmraiseinteractive wait cannot run here.
Standard library and modules
- Loaded libraries:
string,table,math,utf8,io,os(withos.exit = nil),coroutine,package,load,loadfile,dofile(takes only a file path, no explicit environment argument), andrequire. Thedebuglibrary is not available. Lua patterns are not regular expressions; usegreporshfor regexes. - Added globals:
json.encode(value),json.decode(text)(maps JSONnulltonil), andinspect(value). - Modules:
package.pathandpackage.cpathare cleared.requireresolves"tuse"(a live, read-only agent-scoped proxy reflecting active overrides andfalsedisables),"global", relative paths ("name","a.b","./x","../x"),"~/...", absolute paths, and explicit.luapaths, cached by canonical path in the agent's isolatedpackage.loaded. An initial file or preloadrequirereturns(value, canonical_path_or_preload); subsequent cached calls return only(value). Filesrequired fromlua(code)run in the agent environment (subject to configured overrides and disables). See config.md and lua.md. - Paths passed to file functions may be absolute,
~/..., or relative to the session working directory. - Disabled built-ins: Built-in functions disabled in config (
functions = { name = false }) arenilas globals and onrequire("tuse"), raise"<name> is disabled"through any previously saved alias, and are filtered out of the system prompt, theluatool description, anddocs()output. Private runtime helpers (such as return-value rendering withinspect) remain functional.
File, search, and shell behavior inside lua
Built-in host functions are Lua globals inside lua, not separate API tools. Automatic diff attachment and model image attachment apply only to agent lua tool calls (not hooks, custom commands, open handlers, or background tasks). See functions.md for full signatures and options.
read(path, opts?): Rejects directories; returns[binary file, N bytes]when a NUL byte appears in the first 8,192 bytes; returns raw text by default or paginated numbered lines with{lines = true, offset = 1, limit = 2000}(lines cut at 2,000 chars with… [line cut]). On images (.png,.jpg,.jpeg,.gif,.webp) up tosettings.max_image_bytes, returns[image: <path>, <KB> KB]and attaches the image to the tool result so the model sees it.write(path, content)/append(path, text)/delete(path)/edit(path, old, new, {all = false}):write,append, andeditwrite atomically (temp file in target directory, preserving existing file permissions, flushing to disk, then renaming).writeandappendcreate missing parent folders and reject directories;appenddecodes existing file contents with lossy UTF-8 before appending;deleteremoves a single file (never directories).editrequires UTF-8 text, exact match (unique unlessall = true, listing up to 10 line numbers on ambiguity), and preserves CRLF line endings whenoldcontains no\r.- Diff capture: Each file mutation in an agent
luacall attaches a diff to the tool result (shown in TUI chat and/trace, not returned in the Lua string). Diffs include 2 context lines, up to 5 hunks foredit([N more replacements]), up to 200 lines for whole-file creation/deletion ([N more lines]), and up to 200 removed lines and 200 added lines per changed span forwriteoverwrites andappend([N more changed lines]). Binary deletions record- [binary file, N bytes].
grep(pattern, opts?): Searches files with regular expressions (orliteral = true), respecting.gitignoreand skipping.gitand binary files. Formats matches aspath:line: textand context lines aspath:line- text(--between separated context blocks), clipping lines at 300 characters with…. Default limit is 100 matches.sh(cmd, opts?): Runsbash -c <cmd>with stdin closed, stdout and stderr merged, in its own process group. Timeout clamps to the calling coroutine's remaining deadline; timeout, cancellation, or drop kills the entire process group withSIGKILL. Returns{out, code, ok, timed_out}with:lines()and__tostring. Shell state does not persist between calls.