agent-block
Single-purpose agent building block with built-in mesh communication.
What is agent-block?
A headless agent runtime. Each agent runs as a single process, executes its task, then exits. No rich interactive TUI, no sub-agent orchestration — orchestration belongs to the caller (shell, A2A, CI, etc.).
agent-block handles the infrastructure that individual agents shouldn't have to — mesh connectivity (A2A), MCP server management, LLM API access — so that Lua code focuses purely on domain logic.
Think of it like Envoy for agents: the process itself is simple, but the communication layer is fully capable.
Design Decisions
- Single run — One process, one task, one exit. Orchestration belongs to the caller (shell, A2A, CI, etc.), not inside the agent
- Headless — No terminal UI. Agents are composed via A2A/mesh protocols, not interactive prompts
- Runtime owns the protocol — Mesh, MCP, and HTTP are provided by the runtime. Lua code never deals with connection management or wire formats
- Lua for logic, Rust for plumbing — Domain logic in Lua. VM, networking, and protocol handling in Rust
Design documentation lives in the code
Settled design is written into the code's own documentation and nowhere else:
Rust crate and module docs (//!) plus item docs, and the --- module headers of
the embedded Lua libraries. There is no separate design document tree — a document
beside the code drifts and goes unread, a module doc is compiled, linted and read
with the code it describes.
The entry points for the kernel are the module docs of
crates/agent-block-core/src/knl/mod.rs (the kernel's invariants),
crates/agent-block-core/src/bridge/knl.rs (the syscall surface Lua sees) and
crates/agent-block-core/blocks/lib/knl/init.lua (the Lua kernel: session, device,
beat, Outcome, shapes). cargo doc --open renders the Rust side.
Architecture
The repository is a Cargo workspace with 4 crates (strict one-way
dependency bin → core → mcp → types):
| Crate | Role | Deps |
|---|---|---|
agent-block-types |
shared error + obs (sanitize_url 等) |
leaf |
agent-block-mcp |
rmcp wrapper + Lua↔JSON converters | types |
agent-block-core |
host runtime + Lua stdlib bridge + EventBus | mcp, types |
agent-block (bin) |
thin CLI on top of core |
core, mcp |
Downstream Rust applications can depend on agent-block-core (or just
agent-block-types for error/obs) without pulling in clap / the CLI.
┌─────────────────────────────────────────────┐
│ agent-block (binary) │
│ │
│ ┌─────────┐ ┌──────────┐ ┌───────────┐ │
│ │ mlua-isle│ │ mesh-sdk │ │ llm-client│ │
│ │ (Lua VM) │ │ (relay) │ │ (API) │ │
│ └────┬─────┘ └────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ ─────┴─────────────┴──────────────┴─────── │
│ Lua Stdlib Bridge │
│ mesh.send / mesh.on / llm.chat / fs.read │
│ tool.register / tool.call / log.* / env.* │
│ mcp.connect / mcp.call / mcp.list_tools │
└─────────────────────────────────────────────┘
↕ WebSocket ↕ stdio
┌─────────────────┐ ┌──────────────────┐
│ agent-mesh │ │ MCP Servers │
│ relay │ │ (outline-mcp) │
└─────────────────┘ └──────────────────┘
Installation
# From crates.io
# Prebuilt binaries (GitHub Releases, built by cargo-dist for
# linux x86_64 / macOS x86_64 + aarch64 / windows x86_64).
# Handy in CI where a cargo build is too slow:
|
Windows PowerShell: use agent-block-installer.ps1 from the same release.
Per-platform archives (agent-block-<target>.tar.xz / .zip) with sha256
checksums are attached to each release for direct download.
Usage
# Basic
# A registered block, by name (see "Blocks and libraries" below)
# With project context
# With mesh
ANTHROPIC_API_KEY=...
# Pass a prompt and system context from the CLI
CLI flags --prompt and -c / --context inject the _PROMPT and _CONTEXT Lua globals
into the script. Use them with agent.run:
-- my_agent.lua
local agent = require
local result = agent.
print
Both flags also accept environment variables as fallback:
| Flag | Env var |
|---|---|
--prompt |
AGENT_BLOCK_PROMPT |
-c / --context |
AGENT_BLOCK_CONTEXT |
Blocks and libraries
Two directories, two jobs, at two tiers:
<project>/blocks/<name>.lua | <name>/init.lua entry points — run by name
<project>/lib/<name>.lua | <name>/init.lua modules — require("<name>")
~/.agent-block/blocks/… the user's blocks, every project
~/.agent-block/lib/… the user's modules, every project
(`$AGENT_BLOCK_HOME` moves the pair)
A block is a script the host runs for the one value it returns. It is
callable by name — agent-block --block <name> from a shell, run_block over
MCP — and the two surfaces share one registry: <project>/blocks/ then
$AGENT_BLOCK_HOME/blocks/, the project winning a clash. A module is what
a block requires: script_dir → <project>/lib/ → $AGENT_BLOCK_HOME/lib/
→ embedded, first hit wins. Nothing crosses: a file in blocks/ cannot be
required, a file in lib/ is never run by name, so a helper dropped beside a
block does not become a callable block by accident.
The working shape is a script that grows a library:
blocks/summarize.lua write it, run it: agent-block -b summarize
lib/summarize_util.lua pull the reusable part out; require("summarize_util")
~/.agent-block/lib/summarize_util.lua mv it here when a second project wants it
crates/agent-block-core/blocks/lib/… upstream, once it is general (EMBEDDED_LIBS)
The file and its require name never change on the way up; each tier
resolves the same name. --project names the project root only (.env, the
sandbox write root, the kernel database) — it is not a library path.
Serving blocks over MCP
agent-block mcp serves the registered blocks to an MCP client as one
run_block tool. The same scripts the CLI runs become callable from an agent
that speaks MCP, without that agent knowing where they live:
That serves <project>/blocks/ and ~/.agent-block/blocks/; `--block-dir
A block runs against its own model with its own credentials, so its LLM turns never enter the calling agent's context — only its return value does. That is the point of the mode: a caller strong at planning and review hands the loop off and gets one value back.
The contract is one line: a block returns a JSON string.
-- blocks/summarize.lua
-- Summarize the prompt. Returns { ok, text }.
local agent = require
local r = agent.
return std..
The host stringifies whatever the chunk evaluates to, and a Lua table
stringifies to table: 0x… — hence std.json.encode. _PROMPT / _CONTEXT
carry the tool's prompt / context arguments, exactly as the CLI flags do.
| Surface | Meaning |
|---|---|
tool run_block |
run one registered block; block is an enum of the registered names |
resource agent-block://guide |
the authoring contract, in full |
resource agent-block://blocks |
the registry as JSON |
resource agent-block://blocks/<name> |
one block's source |
A block is <name>.lua or <name>/init.lua directly inside a block root;
nothing deeper, and nothing under lib/, is callable. The roots are re-scanned
per request — a new block is callable as soon as the file lands, without
restarting the server. A block's leading -- comment is what the caller reads
as its description, so it is worth writing.
A Lua error comes back as a failed tool call carrying the message. A block that ran and concluded "no" should return normally and say so in its JSON: the two are different events and only the block knows which happened.
Because stdio transport owns stdout, this mode writes its logs to stderr, which
is where MCP clients surface server logs — including the ab.obs lines.
Sandbox mode (Linux)
--sandbox wraps the whole process in an OS-level execution boundary built from
Landlock (filesystem + TCP) and a seccomp filter (io_uring).
It is off by default.
# Confine writes; TCP stays open
# Same, plus extra writable paths and no TCP at all
AGENT_BLOCK_SANDBOX_FS_RW=/opt/cache:/srv/data \
AGENT_BLOCK_SANDBOX_TCP=0 \
| Flag / Env var | Default | Effect |
|---|---|---|
--sandbox / AGENT_BLOCK_SANDBOX |
off | Install the boundary at startup |
AGENT_BLOCK_SANDBOX_FS_RW |
(empty) | :-separated extra writable paths |
AGENT_BLOCK_SANDBOX_TCP |
true |
0 / false / no / off denies TCP bind + connect |
What it enforces:
- Reads and executes are unrestricted. PATH lookups, shared libraries and ordinary tooling keep working — the boundary is about mutation, not secrecy.
- Writes are denied except under the project root (
--project), the agent-block state dir (AGENT_BLOCK_HOME, default$HOME/.agent-block),/tmp,/dev/null,/dev/urandom,/dev/tty, and anything listed inAGENT_BLOCK_SANDBOX_FS_RW. Allowlist entries that do not exist are skipped. - io_uring is denied (
io_uring_setup/_enter/_registerreturnEPERM), since a ring bypasses the syscall-level view a seccomp filter has. - Child processes inherit it. Landlock rulesets and seccomp filters survive
fork/execve, sosh.execpayloads andmcp.connectservers run inside the same boundary with no extra wiring. The Luaos.*/io.*stdlib is left intact and caught at the OS layer instead. - Fail-closed startup. If the sandbox is requested but the kernel enforces
nothing, the process exits with an error instead of running unconfined, and
an unresolvable
--projectpath is a startup error (it is the primary write grant). A partial enforcement of the default rights on older Landlock ABIs logs a warning naming what was dropped and continues — except an explicitly requested TCP denial (AGENT_BLOCK_SANDBOX_TCP=0), which aborts startup on kernels older than 6.7 rather than silently failing open.
Operational notes:
- A build target outside
--projectneeds an explicit grant. The default write allowlist is only the project root,AGENT_BLOCK_HOME,/tmpand/dev/{null,urandom,tty}, so when the directory being worked on is not under--project(e.g. the checkout driving the run differs from the repo being built), add that checkout toAGENT_BLOCK_SANDBOX_FS_RW. - Toolchain cache dirs must be writable too.
~/.cargois not in the default allowlist, so cargo fails creating its registry cache (Permission denied). Either list it inAGENT_BLOCK_SANDBOX_FS_RWor point the cache at an allowed path withCARGO_HOME=/tmp/cargo— the latter works from cold, since TCP stays open and downloads still succeed.
KNOWN LIMITATIONS:
- Linux only. On other platforms
--sandboxis a startup error, never a silent no-op. - UDP and DNS are not restricted. Landlock's network rights cover TCP
bind/connect only, so
AGENT_BLOCK_SANDBOX_TCP=0does not stop UDP traffic (DNS included) or unix-domain sockets. - io_uring cannot be used inside the sandbox, including by dependencies that would otherwise pick it up opportunistically.
- TCP is a single on/off switch — no per-host or per-port granularity. This is an execution boundary, not a policy engine.
- The io_uring deny only exists on x86_64 / aarch64. On other Linux architectures no seccomp filter is compiled and the deny is skipped with a warning; the Landlock filesystem boundary still applies.
MCP Echo Harness
A self-contained reference MCP server for smoke-testing the agent-block MCP client bridge. Exposes tools, resources, prompts, logging, and sampling over stdio or HTTP.
# stdio (default) — connect via mcp.connect("echo", "target/debug/examples/echo_mcp_server", {})
# HTTP on an ephemeral port — prints ECHO_MCP_URL=http://127.0.0.1:<port>/mcp
# Also emit 5 log notifications (1-second intervals) and attempt a sampling round-trip
Verify from Lua (requires the server to be running with --transport http):
local url = os.
mcp.
print -- 2 tools: echo, slow_echo
print -- 2 resources: text://hello, text://note
print -- 1 prompt: greet
-- call slow_echo to exercise progress notifications
mcp.
print
See crates/agent-block/examples/verify_echo_harness.lua for the full verification script.
MCP Resource Subscribe Smoke Server
A standalone binary example for shell-level smoke-testing the Resource Subscribe API
(mcp.subscribe_resource / mcp.on_resource_update). Starts an HTTP MCP server with
resources.subscribe capability enabled and fires at least one notify_resource_updated
event after each subscribe call.
# Ephemeral port — prints SUBSCRIBE_TEST_SERVER_URL=http://127.0.0.1:<port>/mcp
# Fixed port
# Periodic notify every 500 ms (instead of single fire on subscribe)
Shell smoke (requires the server URL printed above):
# Expect: SUBSCRIBE_OK, RESOURCE_UPDATE_EV_OK, UPDATE_HITS=1, FIXTURE_DONE
See docs/runbooks/e2e-mcp-resource-subscribe.md for the full positive/negative verification
procedure (Step 2 = shell positive, Step 3 = negative against a server without subscribe
capability).
Lua API
llm.*
llm.chat(messages, opts)— LLM call (Anthropic Messages API)
tool.*
tool.register(name, schema, handler [, meta])— Register a tool. Optionalmeta = { group = "..." }assigns the tool to a named group for use withagent.run({ tool_groups = {...} }).tool.call(name, input)— Call a registered tooltool.list()— List registered tool namestool.schema()— Anthropic tools-format schema array (includesgroupfield when set)
mcp.*
Support status, capability matrix, and the tool-grouping design rationale
live in docs/architecture/mcp-support.md.
mcp.connect(name, command, args, opts)— Spawn MCP server over stdio + initialize handshake.opts.trace_context(bool, defaultfalse) injects__ab_obsintocall_toolarguments;opts.cwd(string) overrides the subprocess working directory (default: project root). The spawned server is a child process, so — exactly likesh.execchildren — it does not inherit the host's own credential variables (ANTHROPIC_API_KEY,OPENAI_API_KEY,AGENT_BLOCK_MESH_SECRET_KEY). A server that legitimately needs one is handed it explicitly:mcp.connect(name, cmd, args, { env = { ANTHROPIC_API_KEY = "..." } })—opts.envis a string→string table applied after the removal, and is the only way to pass a stripped variable through. Every other variable is still inherited (this is not an allowlist); a non-stringopts.envvalue raises an error rather than being dropped.mcp.connect_http(name, url, opts)— Connect to an MCP server over HTTP transport.opts.transport = "sse" | "http"(default"http"= Streamable HTTP;"sse"= SSE).opts.headerstable is forwarded as request headers.mcp.call(name, tool_name, arguments)— Call an MCP toolmcp.list_tools(name)— List available toolsmcp.list_resources(name)— List resources exposed by the server. Returns{ ok=true, resources=[{uri, name, description, mimeType, ...}] }.mcp.list_resource_templates(name)— List resource URI templates exposed by the server. Returns{ ok=true, resource_templates=[{uriTemplate, name, ...}] }.mcp.read_resource(name, uri)— Read a resource by URI. Returns{ ok=true, contents=[{uri, mimeType, text|blob}] }.mcp.list_prompts(name)— List prompt templates exposed by the server. Returns{ ok=true, prompts=[{name, description, arguments}] }.mcp.get_prompt(name, prompt_name, args)— Retrieve a rendered prompt template. Returns{ ok=true, description, messages=[{role, content}] }.mcp.complete(name, ref, arg_name, arg_value)— Request completion suggestions (MCP Completion typeahead, Phase 3).refis{type="ref/prompt", name=...}or{type="ref/resource", uri=...}. Returns{ ok=true, values=[...], total=number?, has_more=bool? }or{ ok=false, error=str }.mcp.on_progress(name, handler)— Register a per-server progress notification callback.handler(token, progress, total, message)is called for eachnotifications/progressevent from the named server. Handler must be a pure Lua function.mcp.on_log(name, handler)— Register a per-server log notification callback.handler(level, logger, data)is called for eachnotifications/messageevent from the named server. When no handler is registered the notification is forwarded to the Rusttracingtarget"lua"at the corresponding level (debug/info/notice/warning/ error/critical/alert/emergency). Handler must be a pure Lua function.mcp.cancel(name, request_id)— Send anotifications/cancellednotification to the named server for the givenrequest_id. Also fired automatically whenmcp.calltimes out. Explicit use is only needed for manual cancellation flows.mcp.set_sampling_handler(server_name, handler)— Register a per-server Lua function to respond tosampling/createMessagerequests from the MCP server.handler(params)receives theCreateMessageRequesttable and must return a table matchingCreateMessageResult({ model, stop_reason, role, content }). When no handler is registered the server receivesmethod_not_found.mcp.set_elicitation_handler(server_name, fn)— Register a per-server Lua function to respond toelicitation/createrequests originating from the MCP server (server→client, Form variant only).fn(server_name, message, schema_json)must return a table withaction = "accept"|"decline"|"cancel"and (for accept) acontenttable conforming to the schema. Url-variant elicitation requests are always declined without reaching the callback. Handler must be a pure Lua function.mcp.set_roots_handler(server_name, fn)— Register a per-server Lua function to respond toroots/listrequests originating from the MCP server (server→client direction).fn(server_name)must return a Lua array of root tables, each with at least aurifield and an optionalnamefield (e.g.{ { uri="file:///home/user", name="home" } }). When no handler is registered the server receivesmethod_not_found. Handler must be a pure Lua function; C functions and Rust-bound callbacks are not supported.mcp.notify_roots_list_changed(name)— Send anotifications/roots/list_changednotification to the named server (client→server, fire-and-forget). Use this whenever the client's set of filesystem roots changes so the server can re-request the updated list viaroots/list. Failures are logged atwarnlevel and silently discarded.mcp.server_info(name)— Return the server'sInitializeResultas a Lua table. Returns{ ok=true, server_info={serverInfo, capabilities, ...} }on success. Useful for inspecting which MCP capability groups (resources, prompts, tools, etc.) a server declares. Returns{ ok=false, error="..." }if the server is not connected.mcp.ping(name)— Send apingkeepalive request to the named server and measure round-trip latency. Returns{ ok=true, latency_ms=N }on success or{ ok=false, error="..." }on failure (unknown server, timeout, or RPC error).mcp.subscribe_resource(server, uri)— Send aresources/subscribeRPC for the given resource URI. Returns{ ok=true }on success or{ ok=false, error="..." }on failure. Requires the server to declare theresources.subscribecapability.mcp.unsubscribe_resource(server, uri)— Send aresources/unsubscribeRPC to stop receiving change notifications for the given URI. Same return shape assubscribe_resource.mcp.on_resource_update(server, callback)— Register a per-server callback fornotifications/resources/updatedevents.callback(ev)whereev = { type="resource_update", server, uri }. Handler must be a pure Lua function.mcp.on_resources_list_changed(server, callback)— Register a per-server callback fornotifications/resources/list_changedevents.callback(ev)whereev = { type="resources_list_changed", server }.mcp.on_tools_list_changed(server, callback)— Register a per-server callback fornotifications/tools/list_changedevents.callback(ev)whereev = { type="tools_list_changed", server }.mcp.on_prompts_list_changed(server, callback)— Register a per-server callback fornotifications/prompts/list_changedevents.callback(ev)whereev = { type="prompts_list_changed", server }.mcp.disconnect(name)— Disconnect server
mesh.*
mesh.send(agent_id, payload)— Synchronous send (raises Lua error on failure)mesh.request(agent_id, payload)— Request-responsemesh.agent_id()— Own AgentId
std.fs.* (mlua-batteries)
std.fs.read(path),std.fs.write(path, content),std.fs.glob(pattern),std.fs.exists(path)std.fs.walk(dir),std.fs.copy(src, dst),std.fs.mkdir(path),std.fs.remove(path)std.fs.is_file(path),std.fs.is_dir(path),std.fs.read_binary(path),std.fs.write_binary(path, bytes)std.fs.tool_specs(opts)/std.fs.register_tools(opts)— the LLM-facing file tools (agent-block):fs_readandfs_edit(line-addressed, checked against anexpectof the current text) by default; opt in throughopts.allowedtofs_write,fs_rollbackandfs_search_replace, which addresses an edit by a unique verbatim snippet and carries it out asfs_editwith the same checks — the form to offer a model that reconstructsexpectfrom memory instead of copying it
sh.*
sh.exec(cmd, opts)— Execute a shell command.opts.cwd(default: project root),opts.timeout(seconds, default 30). On timeout the child is SIGKILLed, not left running.- Children inherit the environment except the host's own credential variables:
ANTHROPIC_API_KEY,OPENAI_API_KEYandAGENT_BLOCK_MESH_SECRET_KEYare removed from everysh.execchild, so code the agent runs (including code it just wrote) cannot read the keys the host itself uses. - A script that legitimately needs an API key must be given its own — pass it under a different variable name, or through the block conf (
api_key/api_key_env). Customapi_key_envnames are not stripped, and this is not an allowlist: every other variable is still inherited. - The same set is removed from MCP server subprocesses spawned by
mcp.connect; that path takes an explicitopts.envtable for servers that need a key (seemcp.*above).
std.json.* (mlua-batteries)
std.json.encode(value),std.json.decode(str),std.json.encode_pretty(value)
std.env.* (mlua-batteries + agent-block extensions)
std.env.get(key),std.env.set(key, value),std.env.get_or(key, default),std.env.home()std.env.agent_id(),std.env.project_root()— agent-block specific
std.path.* / std.time.* (mlua-batteries)
std.path.join(...),std.path.basename(path),std.path.dirname(path)std.time.now(),std.time.sleep(secs),std.time.measure(fn)
std.kv.* (mlua-batteries, SQLite-backed)
std.kv.get(ns, key)— retrieve a value by namespace + key; returnsnilif absentstd.kv.set(ns, key, value)— store a value (any Lua value, JSON-encoded internally)std.kv.delete(ns, key)— delete a key; returnstrueif it existed,falseotherwisestd.kv.list(ns, prefix?)— list keys in a namespace, optionally filtered by prefixstd.kv.register_tools()— registerkv_get,kv_set,kv_delete,kv_listas LLM-callable tools
Storage: AGENT_BLOCK_HOME/kv.sqlite (override via AGENT_BLOCK_KV_PATH; :memory: supported).
std.sql.* (mlua-batteries, SQLite-backed)
std.sql.execute(sql, params?)— execute a DML statement; returns{ affected = N }std.sql.query(sql, params?)— execute a query; returns an array of row tablesstd.sql.register_tools()— registersql_execute,sql_queryas LLM-callable tools
Storage: AGENT_BLOCK_HOME/sql.sqlite (override via AGENT_BLOCK_SQL_PATH; :memory: supported).
std.ts.* (agent-block, SQLite-backed TSDB)
std.ts.append(series, value, tags?, at?)— append a data point;valueis a Lua number or table (JSON-encoded, losslessly decoded on read);tagsis an optional{key=value}table;atis an optional Unix timestamp in milliseconds (default: now)std.ts.query(series, opts)— range query;optsfields:from,to(integer ms) — time range (default: full range)tags(table) — AND-filter; each key-value pair uses SQLitejson_extractagg(string) —"count"|"sum"|"avg"|"last"(optional)bucket_ms(integer) — bucket width; requiresagg; produces time-bucketed rowslimit,offset(integer) — pagination
std.ts.last(series, tags?)— most-recent data point; same tag AND-filter asquerystd.ts.register_tools()— registerts_append,ts_query,ts_lastas LLM-callable tools
Ordering guarantee: raw-path results (query without agg) are ordered by (ts ASC, rowid ASC);
last and query with agg="last" resolve same-millisecond ties by (ts DESC, rowid DESC) so
the last-appended row always wins. This is a deterministic SQLite rowid tie-breaker — no DDL or
index change is required.
Storage: AGENT_BLOCK_HOME/ts.sqlite (override via AGENT_BLOCK_TS_PATH; :memory: supported).
Embedded blocks: four layers
The crate's blocks/ directory is baked into the binary, so require("agent") works
after cargo install with no path configuration. A filesystem copy of a module in a
lib/ tier normally wins over the embedded one — but the four layers below differ in
whether that is the intended way to change them.
| layer | modules | how to change it |
|---|---|---|
| kernel + declaration | knl, knl_adapter, knl_types, lshape (and lshape.t / .check / .reflect / .luacats) |
Sealed — a filesystem copy fails the run rather than replacing the module. The kernel is one thing across Rust and Lua, held together by declaration tests a Lua-side replacement would pass while meaning something else. Change it upstream. AGENT_BLOCK_UNSEAL=1 downgrades the refusal to a warning, for work on the kernel itself and not for shipping. |
| shell packs | policy, supervisor |
Do not shadow: a pack is a value you hand to knl.device or consult in your own loop, not a registry the host reads. The two are one set — a loop is composed from both — and a model's limits are not a third pack: they go into the seams the kernel already has (fold / filters / cost / tool_policy, the loop's predicates, the supervisor's tree) and into what the Port declares (LLMPort:profile); see the policy module header. For a partial change, delegate through embedded.<name>. |
| consumers | agent |
Copy-on-write is the intended way — drop your own lib/agent/init.lua in the project root (or ~/.agent-block/lib/) and it is the agent your scripts get. For a partial change, delegate through embedded.<name>. |
| utilities | llm_proto (with .openai / .anthropic), mcp_tools, session |
Shadowing works, but knl_adapter requires llm_proto and mcp_tools, so replacing either replaces a sealed module's dependency. Prefer delegation. |
Resolution order, highest priority first: the script's own directory →
project_root/lib/ → $AGENT_BLOCK_HOME/lib/ → embedded. blocks/ directories are
not on it (see Blocks and libraries). The seal is checked once
at start over those filesystem roots, before the script runs; the error names the module
and the file that would have replaced it.
Delegation — a shadowing module reaching the one it replaced:
-- project_root/lib/agent/init.lua
local base = require
local M = setmetatable
return M
embedded.<name> resolves from memory and only from memory: every embedded module is
registered a second time under that prefix, ahead of the filesystem roots, so a
lib/embedded/ directory cannot stand in for it. The alias evaluates the embedded
source under its own name, which means require("agent") (yours) and
require("embedded.agent") (the base) are two tables — exactly the pair the idiom needs.
It exists for sealed modules too: require("embedded.knl") reads the kernel, which is
fine; replacing it is what the seal refuses.
Promotion runs the other way. A module that starts as project_root/lib/<name>/init.lua
moves to ~/.agent-block/lib/ when a second project wants it, and becomes an embedded
lib by a change upstream once it proves general — the same file, moved under
crates/agent-block-core/blocks/ and listed in EMBEDDED_LIBS. Projects still carrying
their own copy keep resolving to it until they delete it.
agent (StdPkg — require("agent"))
Built-in ReAct loop module. Available without any path configuration after cargo install.
local agent = require
local result = agent.
if result.
-- result fields: ok, content, usage{input_tokens,output_tokens,total_tokens}, num_turns, error, messages
Correlation ids
There is no option for them. agent.run reads AGENT_BLOCK_TRACE_ID, AGENT_BLOCK_RUN_ID, AGENT_BLOCK_AGENT_ID and AGENT_BLOCK_AGENT_NAME off the environment and stamps whichever are set onto the run's seed event as meta labels — the same four the HTTP bridge puts on its ab.obs http_request / http_response lines. So the session log is selected by the id the log lines are grepped by:
session:
With AGENT_BLOCK_AGENT_ID unset the obs lines still carry a per-process id the host makes up, and the seed event carries no agent_id; set it and both sides agree.
Provider Switching
By default agent.run uses the Anthropic Messages API. Pass provider = "openai" to route to any OpenAI-compatible endpoint (vLLM, llama.cpp, OpenRouter, RunPod, etc.):
-- Anthropic (default) — requires ANTHROPIC_API_KEY
local result = agent.
-- OpenAI — requires OPENAI_API_KEY (or opts.api_key)
local result = agent.
-- Local vLLM / llama.cpp / RunPod — custom base_url
local result = agent.
Environment variables used per provider:
| provider | default key env | override via |
|---|---|---|
anthropic |
ANTHROPIC_API_KEY |
opts.api_key / opts.api_key_env |
openai |
OPENAI_API_KEY |
opts.api_key / opts.api_key_env |
opts.base_url overrides the endpoint root. Default for openai is https://api.openai.com/v1.
cache_control, context_management, and context_management_config are Anthropic-only: they are operative when provider="anthropic" (or unset) and emit a warn-level log message then are ignored when provider="openai".
Protocol options (llm_proto)
Request building lives in the llm_proto package, reached through the provider Port every block's device carries. The vocabulary is OpenAI's; each adapter renames or drops what its provider does not accept, so the same options work on both paths.
local result = agent.
Notable translations:
| you pass | Anthropic | OpenAI | vLLM / llama.cpp / Ollama |
|---|---|---|---|
tool_choice = "required" |
{type="any"} |
"required" |
as OpenAI (ignored by Ollama) |
parallel_tool_calls = false |
tool_choice.disable_parallel_tool_use |
top-level | top-level |
thinking = { effort = ... } |
{type="adaptive"} + output_config.effort (4.7+) or {type="enabled", budget_tokens} (4.5 and earlier) |
reasoning_effort |
chat_template_kwargs (+ reasoning_effort); Ollama takes reasoning_effort only |
stop |
stop_sequences |
stop |
stop |
max_tokens |
max_tokens |
max_completion_tokens on o-series / gpt-5, else max_tokens |
max_tokens |
Combinations the API would reject are refused locally instead: forced tool use under manual extended thinking, a thinking budget that does not fit in max_tokens, and tools plus reasoning on gpt-5.6+. Values a model cannot accept (temperature on reasoning models, temperature ~= 1 on Claude past Opus 4.6, top_k on api.openai.com) are dropped with a warn rather than sent.
Responses are normalized to one shape regardless of provider: reasoning arrives as a thinking content block whether the server sent reasoning_content, reasoning, Anthropic thinking blocks, or raw <think> tags in the text; usage carries cache_read_input_tokens / cache_creation_input_tokens / thinking_tokens on both paths.
Key behaviours:
- MCP servers listed in
mcp_serversare connected automatically and disconnected on exit (even on error). - Each entry may use the stdio form
{ name, command, args }or the HTTP form{ name, url, transport_opts }. Both forms can coexist in the same list. - Pass
sampling = fninagent.runopts to register a single Lua function as thesampling/createMessagehandler for every connected MCP server (mcp.set_sampling_handleris called per server automatically). - Pass
enable_resources = trueinagent.runopts to automatically register{server}__mcp_list_resourcesand{server}__mcp_read_resourceas LLM-callable tools for each connected server that declares theresourcescapability. Defaultfalse. If a server does not declareresources, the opt-in is silently skipped (logged atinfo). - Pass
enable_prompts = trueinagent.runopts to automatically register{server}__mcp_list_promptsand{server}__mcp_get_promptas LLM-callable tools for each connected server that declares thepromptscapability. Defaultfalse. Capability check and silent skip apply the same way asenable_resources. - Pass
on_progress = fn(ev)inagent.runopts to receive progress notifications from all connected MCP servers. The callback is called with an envelope table{ type="progress", server, token, progress, total, message }. No capability gate — all servers are registered. User callback errors are swallowed and logged atwarn. - Pass
progress_to_log = trueinagent.runopts to bridge progress notifications tolog.infoautomatically. Ignored whenon_progressis also set (callback takes priority). Defaultfalse. - Pass
on_log = fn(ev)inagent.runopts to receive log notifications from servers that declare theloggingcapability. The callback is called with an envelope table{ type="log", server, level, logger, data }. Servers without logging capability are silently skipped (logged atinfo). User callback errors are swallowed and logged atwarn. - Pass
log_to_stderr = trueinagent.runopts to bridge server log notifications tolog.debug|info|warn|errorautomatically. Ignored whenon_logis also set (callback takes priority). Logging capability gate applies the same way ason_log. Defaultfalse. - MCP tool names are namespaced as
server_name__tool_nameto avoid collisions. - MCP tools are automatically assigned to a group for use with
tool_groups. Group resolution follows this priority: (1) the tool's_meta.groupfield (string, non-empty) declared by the server takes precedence — rmcp serialisesTool.metaas_metavia#[serde(rename = "_meta")]; (2) fallback to the server name. Passtool_groups = { "outline" }(for example) toagent.runto include only tools from that MCP server. This aligns with the MCP SEP-986 tool-name prefix grouping guidance and themcp__<server>__*convention used by Claude Code. Tools without an explicit group (e.g. plain registered Lua tools) fall into the"default"group. - Tool dispatch: MCP tools via
mcp.call(), registered Lua tools viatool.call(). - Never throws — all errors returned as
{ ok=false, error="..." }. - Context editing is on by default: once the conversation crosses ~80K input tokens, Anthropic evicts all but the most recent 3 tool-use / tool-result pairs server-side so the loop can keep running. Works on Sonnet 4 / Sonnet 4.5 / Haiku 4.5 / Opus 4 / 4.1 / 4.5. Pass
context_management = falseto disable, orcontext_management_config = { edits = { ... } }to replace the default entirely (the whole table is forwarded asbody.context_management; no partial merge). on_turn(info)is handed exactly four keys —turn_number,content,tool_calls,usage— and returningfalsefrom it stops the run. What the server did with context editing is not among them; the response that carried it is in the session log asllm_response.agentis a consumer block: a locallib/agent/init.luain the project root replaces it, and can delegate to the embedded one throughrequire("embedded.agent"). See Embedded blocks: four layers.- No block emits an LLM dump. Each model call is recorded in the session log (
llm_request/llm_response/llm_call_failed) instead, andAGENT_BLOCK_LLM_DUMPis gone with the layer that read it.
lshape (Vendored package — require("lshape"))
lshape is vendored under blocks/lib/lshape/ so scripts can use schema validation
and LuaCATS generation without external installation.
local lshape = require
local T = lshape.
local User = T.
local ok, why = lshape..
assert
Lua kernel (knl — require("knl"))
knl is the Lua half of a kernel/shell split. Rust owns the session: an
append-only event log, a budget the owner granted it, and a scope it is written
under. Lua owns the beat — one model call plus the tools that call asks for
— and the device it runs against, a frozen bundle of policy (llm, tools,
tool_policy, fold, filters, system, cost). knl.beat(session, device)
takes the two separately because they differ in owner, lifetime and mutability.
There is no run loop: a caller writes the loop, which is why the primitive is
one beat.
local kernel = require
local adapter = require
local device = kernel.
kernel. -- the bracket closes either way
Views come in two tiers. A built-in view is a kernel read reached with
s:view(name, opts?), and there are exactly two fixed reads —
s:events(from) and view("tail", { n }). Everything else is a query
view: a named Lua function running one SELECT through s:query(sql, params?, opts?) over the published event table. knl.views.beats /
tool_pairs / ledger / usage are the four shipped, and a consumer's own
view is a function of the same form — nothing about the four is privileged.
The design is in three module docs: crates/agent-block-core/src/knl/mod.rs
(the kernel's invariants), crates/agent-block-core/src/bridge/knl.rs (the
syscall surface Lua sees) and
crates/agent-block-core/blocks/lib/knl/init.lua (this half: beat, device,
Outcome, shapes, views).
log.*
log.info/warn/error/debug(msg)
Testing
Rust (e2e + integration)
cargo test --workspace
Lua block unit specs (mlua-lspec)
The whole suite runs in one command:
just test-lua # every spec
just test-lua window_spec # one, by filename substring
Two kinds of file are picked up: the fixtures under
crates/agent-block/tests/fixtures/*_test.lua, and each block's own specs under
crates/agent-block-core/blocks/lib/<block>/spec/. Both run with the mlua-lspec
framework (describe / it / expect) and need no API keys and no network.
The embedded blocks expose their pure, I/O-free helpers through a
_test_helpers() accessor so a spec can reach them.
What a spec can reach is what needs no kernel: knl is a syscall bridge the
pure runner does not have, so a loop that opens a session is covered by the
Rust e2e suite in the full host (tests/e2e_knl_beat.rs) and the specs cover
what sits around it. Each spec file's header documents how to run it on its
own.
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.