# 04 · Turn Programs in Lua

> Canonical HTML: https://multiplayer.tech/blackbird/turn-programs/
> Manual Index: https://multiplayer.tech/blackbird/index.md

Every turn in Blackbird is a short Lua 5.5.1 script read fresh into a clean VM at the start of the turn. Edit the file and the next turn runs your version — no rebuild, no restart.

## Run Your Own Turn Loop
```bash
cp "$HOME/.local/lib/blackbird/current/share/blackbird/programs/turn.lua" my-turn.lua
blackbird --workflow my-turn.lua
```
Switch live inside a session with `/workflow FILE` (`/session` shows the active path). Run a one-off Lua expression inside a session with:
```text
/lua print(blackbird.json.encode(blackbird.stats()))
```

## The Default Loop (Abridged `programs/turn.lua`)
```lua
while true do
  local response = blackbird.request()
  local calls = 0
  for _, item in ipairs(response.output) do
    if item.type == "function_call" then
      calls = calls + 1
      local result = blackbird.call(item.name, item.arguments, { call_id = item.call_id })
      blackbird.append({
        { type = "function_call_output", call_id = item.call_id, output = result },
      })
    elseif item.type == "message" then
      blackbird.present(item)
    end
  end
  if blackbird.restarting() or calls == 0 then
    return
  end
end
```

## Host API
- `blackbird.request(opts)` — Call the model using live context (optional per-request overrides).
- `blackbird.call(name, args)` — Invoke any model tool (`read_file`, `write_file`, `edit_file`, `exec`, etc.).
- `blackbird.append(items)` — Append items to conversation context.
- `blackbird.present(item)` / `blackbird.display(text)` / `print` — Emit output.
- `blackbird.stats()` — Return exact context byte sizes.
- `blackbird.blocks()`, `read_block(id)`, `compact(args)`, `pin(ids)` — Inspect and compact context directly from Lua.
- `blackbird.json.encode` / `decode` — JSON encoding/decoding.
- `blackbird.define_tool(def)` — Register a persistent Lua tool (available after clean exit and across reopens).

The model also has a `lua` tool with the same API.

## VM Rules, Hooks & Slash Workflows
- **Libraries:** `base`, `coroutine`, `table`, `string`, `math`, `utf8`; `os` exposes only `time`, `clock`, `difftime`. No `io`, `package`, `debug`, `dofile`, or `loadfile`. Globals reset each turn. Lua is NOT a security sandbox (any script can call `exec`).
- **Five hook events:** turn start, turn end, before tool call, after tool call, context compaction. Hooks can observe, transform context, or refuse a tool call. Configured via `program_config`; inspect with `/hooks`, `/hooks history`, `/hooks enable|disable NAME`, `/hooks explain JSON`.
- **Slash workflows:** Every new session includes `/ultracode TASK`.
