# What this is

Nursultan scripts are plain Kotlin files with a `.kts` extension that the client compiles while the game is running. Save the file and the script reloads — no restart needed.

One file is one script. Here is a whole working one:

```kotlin
name("Hello")
description("My first script")

chat.print("hi")

on<ClientTickEvent> {
    // runs every game tick while the script is on
}
```

## What you can build

* **Your own module** — settings, a bind, a switch in the Scripts tab. See [How a script works](https://docs.nursultan.fun/scripting/start/lifecycle) and [Kinds of settings](https://docs.nursultan.fun/scripting/settings/types).
* **Reactions to the game** — ticks, damage, attacks, input, packets, entities spawning and so on. See [Events](https://docs.nursultan.fun/scripting/events).
* **Reading the world** — player, blocks, entities, inventory, server and so on. See [Game data](https://docs.nursultan.fun/scripting/game) and [Vectors, boxes, angles](https://docs.nursultan.fun/scripting/game/math).
* **Actions** — attack, place, break, turn your head, swap slots, send packets and so on. See [Actions](https://docs.nursultan.fun/scripting/actions) and [Keys and binds](https://docs.nursultan.fun/scripting/actions/keys).
* **Your own graphics** — HUD, boxes and lines in the world, custom shaders and so on. See [Interface](https://docs.nursultan.fun/scripting/ui).
* **Your own commands** — with Tab completion, just like the client's own and so on. See [Your own commands](https://docs.nursultan.fun/scripting/extras/commands).

## Where scripts live

`%APPDATA%\Nursultan\scripts`

That folder holds **only** finished `.kts` files — see [The project in your IDE](https://docs.nursultan.fun/scripting/start/ide).

Everything a script reads — fonts, images, data — goes one folder down, into `scripts\assets`. See [The assets folder](https://docs.nursultan.fun/scripting/extras/assets).

The file name is the script id: `auto-jump.kts` shows up in the menu as `auto-jump` until you give it a `name(...)`.

## The Scripts tab

Everything is managed from the **Scripts** tab in the client menu.

* While compiling, the script's card is inactive. An error turns it red and shows the message.
* Every script gets one card: the **switch** turns it on and off, **the dots or right click** opens settings, **the keyboard icon or middle click** sets a bind.
* State survives restarts: on/off, bind and settings all come back.

---

# Getting started

Where to begin: your first file, setting up the IDE, and how a script works.

---

# Your first script

The file name without `.kts` is the script id; everything at the top level runs once when the file loads, and `on<...>` handlers run only while the script is switched on.

```kotlin
name("Auto jump")
key(Key.G)
val delay by slider("Delay", 5, 1, 20)
var ticks = 0
onEnable { ticks = 0 }
on<ClientTickEvent> {
    if (++ticks < delay) return@on
    ticks = 0
    whenInGame { control.jump() }
}
```

## The smallest file

| Fact | Detail |
|---|---|
| file | any `.kts` in the scripts folder, `*.gradle.kts` is ignored |
| script id | file name without `.kts`, key for configs and presets |
| empty file | compiles, appears in the Scripts tab, does nothing |
| menu label | `name(...)` when set, otherwise the script id |
| saving the file | recompiles it, restores the bind and the on/off state |

## Settings and a bind

| What | Documented on |
|---|---|
| `checkBox`, `slider`, `input`, `selectable`, `combo`, `colorPicker`, `hotkey`, `button` | [Kinds of settings](https://docs.nursultan.fun/scripting/settings/types) |
| `name`, `description`, `key`, `bind`, `onEnable`, `onDisable` | [How a script works](https://docs.nursultan.fun/scripting/start/lifecycle) |
| `on<E> { }`, `ignoreCancelled`, `unsubscribe()` | [Subscribing](https://docs.nursultan.fun/scripting/events/basics) |

## Reading a setting

| Declaration | Type | Description |
|---|---|---|
| `val delay by slider("Delay", 5f, 1f, 20f)` | `Float` | delegate, reads the live value on every access |
| `val delay = slider("Delay", 5f, 1f, 20f)` | `Slider` | the setting object: `value()`, `onChange`, `visibleWhen` |

`var x by ...` writes as well: assigning to the property calls the setting's setter. The delegate type of every setting kind is on [Kinds of settings](https://docs.nursultan.fun/scripting/settings/types).

## Where errors go

| Destination | What lands there |
|---|---|
| script console | compile errors, handler throws as `failed - <file>.kts:<line>: <message>`, `log.info/warn/error` |
| chat | only what the script prints itself through `chat.print` |
| client log | every console line, mirrored into the Minecraft log file |

Repeated throws are throttled to one report per 3000 ms per script, and 5 throws in a row switch the script off — [Sandbox and limits](https://docs.nursultan.fun/scripting/extras/limits). Console and chat output are on [Messages](https://docs.nursultan.fun/scripting/ui/messages).

---

# The project in your IDE

The script development folder from the site (`nursultan-scripts-v10.zip`) unpacks into `nursultan-scripts/`, a ready IntelliJ IDEA project: the API jars, the build files and an example script. Inside the client's scripts folder the client refreshes `.sdk/` and both build files on every launch.

## What to download

| Path | What it is |
|---|---|
| `example.kts` | example script; every `.kts` in the folder root is one script |
| `assets/` | fonts, images and data the scripts read — see [the assets folder](https://docs.nursultan.fun/scripting/extras/assets) |
| `.sdk/nursultan-script-api-v<N>.jar` | the API and the `.kts` script definition; `<N>` is the client's script API version, currently 10 |
| `.sdk/nursultan-script-packets-<mcVersion>.jar` | Minecraft packet classes, needed only by scripts that read or send packets; the suffix is the client's Minecraft version |
| `build.gradle.kts`, `settings.gradle.kts` | wire the `.sdk` jars and Kotlin scripting in |
| `README.md` | the same steps, offline |

`.sdk/` is generated: the client overwrites its jars and deletes every `nursultan-script-*.jar` left from another version. Files are rewritten only when their bytes changed, so an unchanged SDK causes no Gradle re-sync.

## Open it in IntelliJ IDEA

1. `File → Open`, pick the folder, "Open as Project", trust the project.
2. Gradle syncs once and pulls the Kotlin plugin, `kotlin-scripting-jvm` and `kotlin-scripting-common` from Maven Central.
3. The project sets `jvmToolchain(21)`, so Gradle needs a JDK 21.

## The script definition

**Settings → Languages & Frameworks → Kotlin → Kotlin Scripting** → *Custom Definitions* → **Search Definitions** → **Nursultan Script** (`.kts`) appears in the list → keep it enabled and **above** *Default Kotlin Script* → **Apply**.

IntelliJ does not discover custom script definitions on its own: until this is applied every `.kts` is red. Resolution is computed per file, so open a script after applying.

## Moving it into the game

1. Copy the `.kts` into `%APPDATA%\Nursultan\scripts`; the file name without `.kts` is the script id.
2. Copy the fonts, images and data it reads into `%APPDATA%\Nursultan\scripts\assets`, keeping the subfolders used in the project.
3. Switch the script on in the Scripts tab.

`.sdk/` and the build files stay behind — the client does not read them. Saving an already loaded file recompiles and reloads the script in the running game.

## Developing in the game folder

`%APPDATA%\Nursultan\scripts` counts as the project when it contains `build.gradle.kts` or a `.sdk/` folder; put the whole development folder there and open that path in IDEA. On every launch the client then rebuilds the `.sdk` jars out of itself and rewrites `build.gradle.kts` and `settings.gradle.kts`, so the SDK never lags behind the client. With neither `build.gradle.kts` nor `.sdk/` present the client leaves the folder alone.

---

# How a script works

A loaded script is not a running script: the top level of the file runs at load, handlers and commands run only while the script is switched on. Everything the API offers hangs off the implicit receiver of the file, so every member on this page is callable unqualified.

```kotlin
name("Auto jump")
description("Jumps for you")
key(Key.G)

onEnable { chat.print("$id on") }
onDisable { chat.print("$id off") }
onUnload { storage.save() }

whenInGame { enabled = true }
```

## Loaded and switched on

| Method | Type | Description |
|---|---|---|
| `id` | `String` | script id = `.kts` file name without the extension |
| `enabled` | `Boolean` | on/off state, read and write; the write marshals to the client thread |
| `toggle()` | `Unit` | flips `enabled` |
| `onEnable(action)` | `Unit` | enable callback, several allowed, throws are logged |
| `onDisable(action)` | `Unit` | disable callback, several allowed, throws are logged |
| `onUnload(action)` | `Unit` | runs once on unload or reload (throws `ScriptStateException` when already unloaded) |
| `whenInGame(body)` | `Unit` | runs `body` only when player and world exist |

The top level runs once, at load. While the script is off its handlers, commands, hotkeys and scheduled tasks are unsubscribed; switching it back on re-arms them without re-running the file.

### Script

| Method | Type | Description |
|---|---|---|
| `Script.setEnabled(value)` | `void` | Java form of writing `enabled`, marshals to the client thread |
| `Script.defaultKey(key)` | `Script` | Java form of `key(key)`, returns the script |
| `Script.events()` | `Events` | the event registry behind `on<E> { }` — [Subscribing](https://docs.nursultan.fun/scripting/events/basics) |
| `Script.client()` | `Client` | the `client` root, table below |
| `Script.game()` | `Game` | the `game` root, table below |

`Script` is the Java object every member above forwards to; `id()`, `name()`, `description()`, `enabled()`, `toggle()`, `bind()`, `onEnable()`, `onDisable()` and `onUnload()` carry the names already on this page.
`Script` extends `SettingHost`, so every setting factory on [Kinds of settings](https://docs.nursultan.fun/scripting/settings/types) is a member of it too.

## Name, description, bind

| Method | Type | Description |
|---|---|---|
| `name(value)` | `Unit` | menu display name, trimmed (throws `ScriptException` when blank or over 32 chars) |
| `description(value)` | `Unit` | menu description, null becomes `""` |
| `key(key)` | `Unit` | default toggle key, written only while the bind is still empty |
| `bind` | `Bind` | the script's own toggle keybind — [Keys and binds](https://docs.nursultan.fun/scripting/actions/keys) |

## What you can reach

| Method | Type | Description |
|---|---|---|
| `client` | `Client` | client-side services, table below |
| `game` | `Game` | the running game session, table below |
| `user` | `User` | Nursultan account of the local user — [Your account](https://docs.nursultan.fun/scripting/extras/user) (API 2) |
| `chat` | `Chat` | chat printing and sending — [Messages](https://docs.nursultan.fun/scripting/ui/messages) |
| `text` | `Texts` | text component factory — [Styled text](https://docs.nursultan.fun/scripting/ui/text) |
| `log` | `Logger` | script console logger — [Messages](https://docs.nursultan.fun/scripting/ui/messages) |
| `storage` | `Config` | the script's default config — [Saving data](https://docs.nursultan.fun/scripting/settings/storage) |
| `configs` | `Configs` | this script's named configs — [Saving data](https://docs.nursultan.fun/scripting/settings/storage) |
| `assets` | `Assets` | read access to `scripts/assets` — [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) (API 2) |
| `sound` | `Sound` | plays `.wav` and `.ogg` from `scripts/assets` — [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) (API 9) |
| `clipboard` | `Clipboard` | system clipboard — [Messages](https://docs.nursultan.fun/scripting/ui/messages) (API 2) |
| `filters` | `EntityFilters` | prebuilt entity predicates — [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `keys` | `Keys` | keyboard and mouse state — [Keys and binds](https://docs.nursultan.fun/scripting/actions/keys) |
| `party` | `Party` | party info and the script message bus — [Party messages](https://docs.nursultan.fun/scripting/extras/party) (API 4) |
| `player` | `SelfPlayer` | the local player — [Your player](https://docs.nursultan.fun/scripting/game/player) |
| `world` | `World` | the loaded world — [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `inventory` | `Inventory` | the player inventory — [Inventory and items](https://docs.nursultan.fun/scripting/game/inventory) |
| `container` | `Container` | the open screen handler — [Containers](https://docs.nursultan.fun/scripting/game/containers) |
| `recipes` | `Recipes` | the recipe book — [Containers](https://docs.nursultan.fun/scripting/game/containers) (API 2) |
| `inGame` | `Boolean` | true when both player and world exist |
| `interaction` | `Interaction` | attack, use, break — [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `raycast` | `Raycast` | block and entity rays — [Rays and the crosshair](https://docs.nursultan.fun/scripting/game/raycast) |
| `control` | `Control` | movement flags and jump — [Movement](https://docs.nursultan.fun/scripting/actions/control) |
| `gameSettings` | `GameSettings` | Minecraft options — [Movement](https://docs.nursultan.fun/scripting/actions/control#game-settings) (API 2) |
| `slots` | `Slots` | hotbar slot selection — [Slots and armor](https://docs.nursultan.fun/scripting/actions/slots) |
| `armor` | `Armor` | worn armor comparison — [Slots and armor](https://docs.nursultan.fun/scripting/actions/slots) |
| `combat` | `Combat` | attack point and target marking — [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `rotations` | `Rotations` | server-side yaw/pitch spoofing — [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `prediction` | `Prediction` | movement and projectile prediction — [Prediction](https://docs.nursultan.fun/scripting/actions/prediction) |
| `gpu` | `Gpu` | mesh and pipeline registry — [Your own geometry](https://docs.nursultan.fun/scripting/ui/gpu) (API 2) |
| `theme` | `Theme` | client menu and HUD colours and scales — [2D render](https://docs.nursultan.fun/scripting/ui/render-2d#client-theme) (API 8) |
| `language` | `String` | client interface language, `en` or `ru` (API 8) |

`player`, `world`, `inventory`, `container`, `recipes`, `interaction`, `raycast` and `control` throw `ScriptStateException` outside a world; `inGame` is the guard.
Every root throws `ScriptStateException` after the script has been unloaded.

## The client object

| Method | Type | Description |
|---|---|---|
| `client.user()` | `User` | Nursultan account of the local user (API 2) |
| `client.chat()` | `Chat` | chat printing and sending, tagged with the script id |
| `client.text()` | `Texts` | text component factory |
| `client.log()` | `Logger` | script console logger, still usable after unload |
| `client.notifications()` | `Notifications` | client notification stack — [Messages](https://docs.nursultan.fun/scripting/ui/messages) |
| `client.tasks()` | `Tasks` | tick scheduler owned by this script — [Timers and tasks](https://docs.nursultan.fun/scripting/extras/tasks) |
| `client.storage()` | `Config` | the script's default config, file name `storage` |
| `client.configs()` | `Configs` | named per-script config store |
| `client.assets()` | `Assets` | read-only file access under `scripts/assets` (API 2) |
| `client.sound()` | `Sound` | plays `.wav` and `.ogg` from `scripts/assets` — [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) (API 9) |
| `client.clipboard()` | `Clipboard` | system clipboard read and write (API 2) |
| `client.commands()` | `Commands` | `.`-prefixed command registration — [Your own commands](https://docs.nursultan.fun/scripting/extras/commands) |
| `client.modules()` | `Modules` | client module registry — [Client modules](https://docs.nursultan.fun/scripting/extras/modules) |
| `client.waypoints()` | `Waypoints` | client waypoint manager — [Waypoints](https://docs.nursultan.fun/scripting/extras/waypoints) |
| `client.party()` | `Party` | party info and the script message bus — [Party messages](https://docs.nursultan.fun/scripting/extras/party) (API 4) |
| `client.rotations()` | `Rotations` | spoofed server rotation handler |
| `client.combat()` | `Combat` | attack point, target marking |
| `client.slots()` | `Slots` | hotbar and held-slot control |
| `client.armor()` | `Armor` | worn armor accessor |
| `client.prediction()` | `Prediction` | movement and projectile prediction |
| `client.timer()` | `Timer` | a new independent stopwatch on every call — [Timers and tasks](https://docs.nursultan.fun/scripting/extras/tasks) |
| `client.filters()` | `EntityFilters` | entity predicate factory, still usable after unload |
| `client.keys()` | `Keys` | keyboard, mouse and cursor state |
| `client.fonts()` | `Fonts` | per-session font registry — [2D render](https://docs.nursultan.fun/scripting/ui/render-2d) |
| `client.shaders()` | `Shaders` | per-script shader registry — [Shaders](https://docs.nursultan.fun/scripting/ui/shaders) |
| `client.gpu()` | `Gpu` | per-script GPU buffer and pipeline registry (API 2) |
| `client.textures()` | `Textures` | per-script texture registry — [2D render](https://docs.nursultan.fun/scripting/ui/render-2d) |
| `client.theme()` | `Theme` | client menu and HUD colours and scales — [2D render](https://docs.nursultan.fun/scripting/ui/render-2d#client-theme) (API 8) |
| `client.language()` | `String` | client interface language, `en` or `ru` (API 8) |

`client.fps()`, `tick()`, `millis()`, `nanos()`, `tickDelta()` and `onClientThread()` are documented on [Timers and tasks](https://docs.nursultan.fun/scripting/extras/tasks).

## The game object

| Method | Type | Description |
|---|---|---|
| `game.inGame()` | `boolean` | true when both player and world exist |
| `game.connected()` | `boolean` | true while a play network handler exists |
| `game.player()` | `SelfPlayer` | the local player — [Your player](https://docs.nursultan.fun/scripting/game/player) |
| `game.world()` | `World` | the client world — [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `game.inventory()` | `Inventory` | the player inventory — [Inventory and items](https://docs.nursultan.fun/scripting/game/inventory) |
| `game.control()` | `Control` | movement-state control — [Movement](https://docs.nursultan.fun/scripting/actions/control) |
| `game.interaction()` | `Interaction` | attack, use, break — [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `game.raycast()` | `Raycast` | block and entity ray casting — [Rays and the crosshair](https://docs.nursultan.fun/scripting/game/raycast) |
| `game.server()` | `Server` | current server info — [Server, scoreboard, tab list](https://docs.nursultan.fun/scripting/game/server) (throws `ScriptStateException` when not connected) |
| `game.packets()` | `Packets` | outgoing packet sender, never throws — [Packets](https://docs.nursultan.fun/scripting/actions/packets) |
| `game.screenOpen()` | `boolean` | true when any screen is open |
| `game.screenKind()` | `ScreenKind` | kind of the open screen, `NONE` when there is none |
| `game.screen()` | `Screen?` | snapshot of the open screen, null when none — [Server, scoreboard, tab list](https://docs.nursultan.fun/scripting/game/server) |
| `game.container()` | `Container` | the open screen handler — [Containers](https://docs.nursultan.fun/scripting/game/containers) |
| `game.recipes()` | `Recipes` | the recipe book — [Containers](https://docs.nursultan.fun/scripting/game/containers) (API 2) |
| `game.settings()` | `GameSettings` | game options, never throws — [Movement](https://docs.nursultan.fun/scripting/actions/control#game-settings) (API 2) |
| `game.translate(key, arguments)` | `String` | translated Minecraft text, `""` for a blank key |
| `game.hasTranslation(key)` | `boolean` | true when the key exists in the loaded language |
| `game.language()` | `String` | language code, e.g. `en_us` |
| `game.item(itemId)` | `Item` | new stack of size 1, namespace defaults to `minecraft:` (throws `ScriptException` when the id is unparseable) |
| `game.closeScreen()` | `void` | closes the open screen on the client thread |
| `game.disconnect()` | `void` | leaves the server on the client thread |

`player()`, `world()`, `inventory()`, `control()`, `interaction()`, `raycast()`, `container()` and `recipes()` throw `ScriptStateException` outside a world.

## Version requirement

| Method | Type | Description |
|---|---|---|
| `requireApi(minimum)` | `Unit` | refuses the load on an older client (throws `ScriptApiException` when `ApiVersion.CURRENT` < `minimum`) |

This client provides API version 10 — see [API versions](https://docs.nursultan.fun/scripting/extras/api-versions).

---

# Settings

Checkboxes, sliders, dropdowns, and saving your own data.

---

# Kinds of settings

Every setting is created at the script's top level and shows up under its card in the Scripts tab in creation order. The `by` delegate reads and writes the live value.

```kotlin
val enabled by checkBox("Enabled", true)
val delay by slider("Delay", 200f, 0f, 1000f, 50f).postfix(Postfixes.MS)
val mode by selectable("Mode", "Fast", "Smooth", selected = "Fast")
val color by colorPicker("Colour", 0xFF5AC8FFL)

on<ClientTickEvent> {
    if (enabled && mode == "Fast") chat.print("$delay ms, $color")
}
```

## Creating one

| Method | Type | Description |
|---|---|---|
| `checkBox(name, value)` | `CheckBox` | boolean setting, `value` defaults to `false` |
| `checkBox(parent, name, value)` | `CheckBox` | nested under `parent` (throws ScriptException when the parent is not this script's checkbox) |
| `slider(name, value, min, max, step)` | `Slider` | float slider, `step` defaults to `1f` (throws ScriptException when min >= max, step <= 0 or value outside min..max) |
| `slider(parent, name, value, min, max, step)` | `Slider` | nested float slider, same validation |
| `slider(name, value: Int, min: Int, max: Int, step: Int)` | `Slider` | int convenience form, stored as float |
| `slider(parent, name, value: Int, min: Int, max: Int, step: Int)` | `Slider` | nested int convenience form |
| `rangeSlider(name, from, to, min, max, step)` | `RangeSlider` | two-handle slider (throws ScriptException when from..to does not fit min..max) |
| `rangeSlider(parent, name, from, to, min, max, step)` | `RangeSlider` | nested two-handle slider, same validation |
| `input(name, value, placeholder)` | `Input` | text field; `placeholder` is literal text shown while empty (API 2) |
| `input(parent, name, value, placeholder)` | `Input` | nested text field (API 2) |
| `selectable(name, vararg entries: Entry)` | `Selectable` | one-of-N from `entry()` objects, first auto-selected when none is |
| `selectable(parent, name, vararg entries: Entry)` | `Selectable` | nested one-of-N from entries |
| `selectable(name, vararg options: String, selected)` | `Selectable` | one-of-N from strings, `selected` defaults to the first option |
| `selectable(parent, name, vararg options: String, selected)` | `Selectable` | nested one-of-N from strings |
| `combo(name, vararg entries: Entry)` | `Combo` | any-of-N from `entry()` objects |
| `combo(parent, name, vararg entries: Entry)` | `Combo` | nested any-of-N from entries |
| `combo(name, vararg options: String, selected)` | `Combo` | any-of-N from strings, `selected` defaults to empty |
| `combo(parent, name, vararg options: String, selected)` | `Combo` | nested any-of-N from strings |
| `colorPicker(name, argb: Int)` | `ColorPicker` | ARGB colour, `0xAARRGGBB` |
| `colorPicker(name, argb: Long)` | `ColorPicker` | same, `Long` narrowed so a `0xFFRRGGBB` literal compiles |
| `colorPicker(parent, name, argb: Int)` | `ColorPicker` | nested ARGB colour |
| `colorPicker(parent, name, argb: Long)` | `ColorPicker` | nested, `Long` narrowed to int |
| `hotkey(name, key, action)` | `Hotkey` | key setting; `action` runs on press while the script is on |
| `hotkey(parent, name, key, action)` | `Hotkey` | nested key setting |
| `button(name, action)` | `Button` | menu button; throws inside `action` are logged, not propagated |
| `button(parent, name, action)` | `Button` | nested menu button |
| `entry(name, selected, body)` | `Entry` | one option for a `selectable` or `combo`, see [Entries](https://docs.nursultan.fun/scripting/settings/entries) |

Two settings with the same name under the same parent throw `IllegalArgumentException`; every creator throws `ScriptStateException` once the script is unloaded.
`hotkey` takes a `Key` from [Keys and binds](https://docs.nursultan.fun/scripting/actions/keys).

### SettingHost

| Method | Type | Description |
|---|---|---|
| `settings()` | `List<Setting>` | every setting the script created, creation order, immutable |

`SettingHost` is the interface the creators above are declared on; nested settings are in the list too.

## The `by` delegate

| Method | Type | Description |
|---|---|---|
| `val x by checkBox(...)` | `Boolean` | reads `value()` |
| `var x by checkBox(...)` | `Boolean` | writes `value(v)` |
| `val x by slider(...)` | `Float` | reads `value()` |
| `var x by slider(...)` | `Float` | writes `value(v)`, clamped to min..max |
| `val x by rangeSlider(...)` | `ClosedFloatingPointRange<Float>` | reads `from()..to()` |
| `var x by rangeSlider(...)` | `ClosedFloatingPointRange<Float>` | writes both ends, each clamped to min..max |
| `val x by input(...)` | `String` | reads `value()` |
| `var x by input(...)` | `String` | writes `value(v)`, null becomes `""` |
| `val x by colorPicker(...)` | `Int` | reads the ARGB int, `0xAARRGGBB` |
| `var x by colorPicker(...)` | `Int` | writes the ARGB int |
| `val x by selectable(...)` | `String` | reads the selected entry's `name()` |
| `var x by selectable(...)` | `String` | selects by name or id (throws ScriptException when unknown) |
| `val x by combo(...)` | `List<String>` | reads the selected entry names, declaration order |
| `var x by combo(...)` | `List<String>` | selects exactly those names (throws ScriptException when unknown) |
| `val x by hotkey(...)` | `Key` | reads the bound key |
| `var x by hotkey(...)` | `Key` | rebinds the key |

`Button` holds no value and has no delegate.

## Common to every setting

| Method | Type | Description |
|---|---|---|
| `setting.name()` | `String` | display name |
| `setting.id()` | `String` | lookup id; the value given to `id(...)`, else the display name |
| `setting.id(stableId)` | `Setting` | sets the lookup id (script settings only) (throws ScriptException when null or blank) |
| `setting.visible()` | `boolean` | last computed visibility flag |
| `setting.visibleWhen(condition)` | `Setting` | installs a `BooleanSupplier` visibility predicate (script settings only) |

`visible()` is recomputed on every value change and every menu draw, so `visibleWhen` runs at draw rate.
On a built-in module setting `name()` returns the locale key after `.setting.`, `id()` the full locale key, and every write is marshalled onto the client thread.

## Checkbox

| Method | Type | Description |
|---|---|---|
| `checkBox.value()` | `boolean` | current checked state |
| `checkBox.value(v)` | `CheckBox` | writes the state, fires listeners |
| `checkBox.toggle()` | `CheckBox` | writes the inverted state |
| `checkBox.onChange(listener)` | `CheckBox` | `Consumer<Boolean>` fired on every write (script settings only) |
| `checkBox.id(stableId)` | `CheckBox` | covariant `Setting.id` |
| `checkBox.visibleWhen(condition)` | `CheckBox` | covariant `Setting.visibleWhen` |

`CheckBox` is the only setting usable as the `parent` of a nested setting.

## Sliders

| Method | Type | Description |
|---|---|---|
| `slider.value()` | `float` | current value, within min..max |
| `slider.intValue()` | `int` | current value rounded with `Math.round` |
| `slider.value(v)` | `Slider` | writes the value clamped to min..max, no step snapping |
| `slider.min()` | `float` | lower bound given at creation |
| `slider.max()` | `float` | upper bound given at creation |
| `slider.step()` | `float` | UI drag increment given at creation |
| `slider.postfix(unit)` | `Slider` | unit drawn after the number, null clears it (script settings only) |
| `slider.onChange(listener)` | `Slider` | `Consumer<Float>` fired on every write (script settings only) |
| `slider.id(stableId)` | `Slider` | covariant `Setting.id` |
| `slider.visibleWhen(condition)` | `Slider` | covariant `Setting.visibleWhen` |
| `rangeSlider.from()` | `float` | lower end of the selected range |
| `rangeSlider.to()` | `float` | upper end of the selected range |
| `rangeSlider.value(from, to)` | `RangeSlider` | writes both ends clamped to min..max (throws IllegalArgumentException when from > to) |
| `rangeSlider.min()` | `float` | lower bound given at creation |
| `rangeSlider.max()` | `float` | upper bound given at creation |
| `rangeSlider.step()` | `float` | UI drag increment given at creation |
| `rangeSlider.postfix(unit)` | `RangeSlider` | unit drawn after the numbers, null clears it (script settings only) |
| `rangeSlider.onChange(listener)` | `RangeSlider` | `BiConsumer<Float, Float>` receiving from and to (script settings only) |
| `rangeSlider.id(stableId)` | `RangeSlider` | covariant `Setting.id` |
| `rangeSlider.visibleWhen(condition)` | `RangeSlider` | covariant `Setting.visibleWhen` |

`step()` only drives dragging in the menu; `value(...)` is never snapped to it.

## Text and colour

| Method | Type | Description |
|---|---|---|
| `input.value()` | `String` | current text; a script input accepts any text, newlines included |
| `input.value(v)` | `Input` | writes the text, null becomes `""` |
| `input.onChange(listener)` | `Input` | `Consumer<String>` fired on every write (script settings only) |
| `input.id(stableId)` | `Input` | covariant `Setting.id` |
| `input.visibleWhen(condition)` | `Input` | covariant `Setting.visibleWhen` |
| `colorPicker.value()` | `int` | colour packed as `0xAARRGGBB` |
| `colorPicker.value(argb)` | `ColorPicker` | writes the colour, no range checks |
| `colorPicker.onChange(listener)` | `ColorPicker` | `Consumer<Integer>` fired on every write (script settings only) |
| `colorPicker.id(stableId)` | `ColorPicker` | covariant `Setting.id` |
| `colorPicker.visibleWhen(condition)` | `ColorPicker` | covariant `Setting.visibleWhen` |

On a built-in module input, text the client rejects reverts to the client default.
`Colors.rgb`, `Colors.rgba` and the rest of the ARGB packing helpers are on [2D render](https://docs.nursultan.fun/scripting/ui/render-2d).

## Choices

| Method | Type | Description |
|---|---|---|
| `selectable.value()` | `Entry` | currently selected entry |
| `selectable.select(entry)` | `Selectable` | selects it, deselects the rest (throws ScriptException when the entry is not this setting's) |
| `selectable.select(reference)` | `Selectable` | resolves the reference then selects (throws ScriptException when unknown) |
| `selectable.selected(entry)` | `boolean` | whether that entry is the selected one; false for foreign objects |
| `selectable.selected(reference)` | `boolean` | same by reference (throws ScriptException when unknown) |
| `selectable.entry(reference)` | `Entry` | resolves by full id, name or last id segment (throws ScriptException when unknown) |
| `selectable.entries()` | `List<Entry>` | all options, declaration order, immutable copy |
| `selectable.options()` | `List<String>` | entry display names, declaration order |
| `selectable.onChange(listener)` | `Selectable` | `Consumer<Entry>` receiving the new entry (script settings only) |
| `selectable.id(stableId)` | `Selectable` | covariant `Setting.id` |
| `selectable.visibleWhen(condition)` | `Selectable` | covariant `Setting.visibleWhen` |
| `combo.value()` | `List<Entry>` | selected entries, declaration order, immutable copy |
| `combo.value(selected)` | `Combo` | selects exactly these, deselects the rest; null clears everything |
| `combo.has(entry)` | `boolean` | whether that entry is selected; false for foreign objects |
| `combo.has(reference)` | `boolean` | same by reference (throws ScriptException when unknown) |
| `combo.set(entry, selected)` | `Combo` | selects or deselects one entry (throws ScriptException when the entry is not this setting's) |
| `combo.set(reference, selected)` | `Combo` | resolves the reference then sets (throws ScriptException when unknown) |
| `combo.entry(reference)` | `Entry` | resolves by full id, name or last id segment (throws ScriptException when unknown) |
| `combo.entries()` | `List<Entry>` | all options, declaration order, immutable copy |
| `combo.options()` | `List<String>` | entry display names, declaration order |
| `combo.onChange(listener)` | `Combo` | `Consumer<List<Entry>>` receiving the selected list (script settings only) |
| `combo.id(stableId)` | `Combo` | covariant `Setting.id` |
| `combo.visibleWhen(condition)` | `Combo` | covariant `Setting.visibleWhen` |

Reference lookup ignores case, dots, dashes, underscores and whitespace.
`Entry` itself is documented on [Entries with their own logic](https://docs.nursultan.fun/scripting/settings/entries).

## Hotkey and button

| Method | Type | Description |
|---|---|---|
| `hotkey.key()` | `Key` | bound key, `Key.UNKNOWN` when unbound or unmapped |
| `hotkey.key(k)` | `Hotkey` | rebinds the key, modifiers unchanged; null becomes `UNKNOWN` |
| `hotkey.mods()` | `int` | GLFW modifier bitmask held with the key, 0 when none |
| `hotkey.bound()` | `boolean` | whether the key is not `UNKNOWN` |
| `hotkey.id(stableId)` | `Hotkey` | covariant `Setting.id` |
| `hotkey.visibleWhen(condition)` | `Hotkey` | covariant `Setting.visibleWhen` |
| `button.id(stableId)` | `Button` | covariant `Setting.id` |
| `button.visibleWhen(condition)` | `Button` | covariant `Setting.visibleWhen` |

`Button` carries no value: no `value()`, no `onChange`, no delegate — only the action given at creation.

## Units

| Constant | Description |
|---|---|
| `Postfixes.PERCENT` | drawn as `%` |
| `Postfixes.DEGREES` | drawn as `°` |
| `Postfixes.SECONDS` | drawn as `s` |
| `Postfixes.TICKS` | drawn as `t` |
| `Postfixes.BLOCKS` | drawn as `b` |
| `Postfixes.MS` | drawn as `ms` |
| `Postfixes.MULTIPLIER` | drawn as `x` |
| `Postfixes.HEALTH` | drawn as `hp` |

Only `Slider` and `RangeSlider` take a postfix; without one the number is drawn bare.

---

# Entries with their own logic

An `entry(name) { }` is one option of a `selectable` or a `combo` that carries its own callbacks and event handlers. They run only while that option is selected and the script is switched on.

```kotlin
val fast = entry("Fast", true) {
    onSelect { chat.print("fast mode") }
    on<ClientTickEvent> { control.jump() }
}
val smooth = entry("Smooth")

val mode = selectable("Mode", fast, smooth)
```

## Strings or entries

| Method | Type | Description |
|---|---|---|
| `selectable("Mode", "A", "B")` | `Selectable` | options as plain strings, entries built for you |
| `selectable("Mode", entry("A") { }, entry("B") { })` | `Selectable` | options as entry objects carrying their own logic |
| `entry(name, selected, body)` | `Entry` | creates one option, `selected` starts it picked (throws ScriptException when name is blank) |

`combo` takes the same two forms. A `selectable` with nothing marked selects its first option; a `combo` may start with none.
Every `selectable` and `combo` overload is listed on [Kinds of settings](https://docs.nursultan.fun/scripting/settings/types).

## Inside the block

| Method | Type | Description |
|---|---|---|
| `name` | `String` | display name passed to `entry()` |
| `selected` | `Boolean` | whether this option is selected right now |
| `on<E>(ignoreCancelled) { }` | `Subscription` | subscribes; the handler runs only while this option is selected |
| `on(type, ignoreCancelled) { }` | `Subscription` | same, event class given explicitly |
| `on<E>(priority, ignoreCancelled) { }` | `Subscription` | (deprecated, drop the argument) |
| `on(type, priority, ignoreCancelled) { }` | `Subscription` | (deprecated, drop the argument) |
| `onSelect { }` | `Unit` | runs when this option becomes selected |
| `onDeselect { }` | `Unit` | runs when this option stops being selected |

The subscription is registered once at load and stays registered across selection changes; deselecting filters the handler at dispatch, it does not unsubscribe.
`ignoreCancelled`, cancelling and unsubscribing behave exactly as on [Subscribing](https://docs.nursultan.fun/scripting/events/basics).

## The entry object

| Method | Type | Description |
|---|---|---|
| `name()` | `String` | display name; built-in entries drop the leading `entry.` |
| `id()` | `String` | locale key `entry.<scriptId>.<name>`, lowercased, spaces as dashes |
| `selected()` | `boolean` | whether this option is currently selected |
| `onSelect(action)` | `Entry` | adds an action run when selection flips to true |
| `onDeselect(action)` | `Entry` | adds an action run when selection flips to false |
| `on(type, handler)` | `Subscription` | subscribes with `EventOptions.DEFAULT` |
| `on(type, options, handler)` | `Subscription` | subscribes; runs only while selected and the script is on |

`onSelect`/`onDeselect` fire only once the entry belongs to a `selectable` or `combo`, and only on an actual change — the state at creation is never reported.
Reading and switching the selection (`value()`, `select()`, `has()`, `entry(reference)`) is on [Kinds of settings](https://docs.nursultan.fun/scripting/settings/types).

## Built-in module entries

`onSelect(...)`, `onDeselect(...)` and `on(...)` throw `ScriptException` on an entry that belongs to a built-in client module.
`name()`, `id()` and `selected()` work on it, and it is switched through its own `Selectable`/`Combo` — see [client modules](https://docs.nursultan.fun/scripting/extras/modules).

---

# Saving data

`storage` is the script's default config; `config("name")` opens another one. Every value is a string, and the file lives at `%APPDATA%/Nursultan/configs/<uid>/scripts/<scriptId>/<name>.dat`.

```kotlin
var runs = 0

onEnable {
    runs = storage.getInt("runs", 0) + 1
}

onDisable {
    storage.put("runs", runs)
    storage.save()
}
```

## Opening one

| Method | Type | Description |
|---|---|---|
| `config(name)` | `Config` | opens this script's named config, cached per name |
| `configs.open(name)` | `Config` | same as `config(name)` |
| `configs.names()` | `List<String>` | this script's config files on disk, alphabetical |
| `configs.exists(name)` | `boolean` | config file exists on disk |
| `configs.delete(name)` | `void` | deletes the file and empties the open instance |

A name is trimmed, lowercased and must match `^[a-z0-9][a-z0-9_-]{0,31}$`, otherwise `ScriptException`.
`storage` is the config named `storage`.

## Reading

| Method | Type | Description |
|---|---|---|
| `storage.name()` | `String` | the config's lowercased name |
| `storage.has(key)` | `boolean` | key present in memory |
| `storage.get(key, fallback)` | `String` | stored value, fallback when absent |
| `storage.getInt(key, fallback)` | `int` | parsed as int, fallback when absent or unparsable |
| `storage.getLong(key, fallback)` | `long` | parsed as long, fallback when absent or unparsable |
| `storage.getDouble(key, fallback)` | `double` | parsed as double, fallback when absent or unparsable |
| `storage.getBoolean(key, fallback)` | `boolean` | true only for `true` ignoring case, fallback when absent |
| `storage.getList(key)` | `List<String>` | stored list, empty when absent (API 2) |
| `storage.getList(key, fallback)` | `List<String>` | stored list, copy of fallback when absent (API 2) |
| `storage.getIntList(key)` | `List<Integer>` | list parsed as ints, unparsable entries dropped (API 2) |
| `storage.getDoubleList(key)` | `List<Double>` | list parsed as doubles, unparsable entries dropped (API 2) |

A blank key throws `ScriptException` on every method that takes one.
A value written with `put` reads back through `getList` as a single-element list.

## Writing

| Method | Type | Description |
|---|---|---|
| `storage.put(key, value: String)` | `void` | stores the string (throws over 65536 chars) |
| `storage.put(key, value: Int)` | `void` | stores the decimal text |
| `storage.put(key, value: Long)` | `void` | stores the decimal text |
| `storage.put(key, value: Double)` | `void` | stores the decimal text |
| `storage.put(key, value: Boolean)` | `void` | stores `true` or `false` |
| `storage.putList(key, values)` | `void` | stores a `List<String>` (API 2) |
| `storage.putIntList(key, values)` | `void` | stores a `List<Integer>` as text (API 2) |
| `storage.putDoubleList(key, values)` | `void` | stores a `List<Double>` as text (API 2) |
| `storage.remove(key)` | `void` | drops the key |
| `storage.clear()` | `void` | drops every key in memory |

A config holds 4096 keys; adding one more throws `ScriptException`.
`put` throws `NullPointerException` on a null value, the list writers throw `ScriptException` on a null element.

## The file

| Method | Type | Description |
|---|---|---|
| `storage.keys()` | `Set<String>` | immutable copy of the current key set |
| `storage.dirty()` | `boolean` | values differ from the last save or load |
| `storage.save()` | `void` | writes the file and clears `dirty()` |
| `storage.load()` | `void` | re-reads the file, dropping unsaved changes |
| `storage.delete()` | `void` | deletes the file and empties the values in memory |

Every open config with `dirty()` is saved when the script is unloaded or reloaded.
The file is Zstd-compressed obfuscated MessagePack; io failures are logged, never thrown.

---

# Events

How to subscribe to what happens in the game, and which events exist.

---

# Subscribing

`on<E> { }` registers a handler that lives as long as the script is switched on. Every script handler runs at one fixed priority: after the client's `BEFORE_ALL` and `BEFORE` modules, before its `NOW` ones.

```kotlin
on<ClientTickEvent> { }

on<UseItemEvent> { e ->
    if (inventory.held().isA("ender_pearl")) {
        e.cancel()
    }
}

val sub = on<AttackEvent>(ignoreCancelled = true) { e -> chat.print(e.target().name()) }
sub.unsubscribe()
```

## Registering a handler

| Method | Type | Description |
|---|---|---|
| `on<E>(ignoreCancelled) { }` | `Subscription` | subscribes by reified event type, `ignoreCancelled` defaults to false (throws `ScriptException` when `E` is not a supported event) |
| `on(type, ignoreCancelled) { }` | `Subscription` | subscribes by event class (throws `ScriptException` when the class is not a supported event) |
| `on<E>(priority, ignoreCancelled) { }` | `Subscription` | (deprecated, drop the argument) |
| `on(type, priority, ignoreCancelled) { }` | `Subscription` | (deprecated, drop the argument) |

`ignoreCancelled = true` skips the handler when the event is already cancelled.

### Events

| Method | Type | Description |
|---|---|---|
| `Events.on(type, handler)` | `Subscription` | subscribes with `EventOptions.DEFAULT` |
| `Events.on(type, options, handler)` | `Subscription` | subscribes with options; null options fall back to `DEFAULT` |
| `Events.supportedEvents()` | `List<String>` | simple names of every supported event, sorted |

`Events` is the interface the `on(...)` overloads above delegate to. A handler registered while the script is off is activated when it is switched on.

## Cancelling

| Method | Type | Description |
|---|---|---|
| `Cancellable.cancel()` | `void` | marks this dispatch cancelled |
| `Cancellable.cancelled()` | `boolean` | true after `cancel()` on this dispatch |
| `CancellableEvent.cancel()` | `void` | sets the flag, never resets it |
| `CancellableEvent.cancelled()` | `boolean` | flag value, false at dispatch start |

`CancellableEvent` is the base class of every cancellable event; the flag is cleared before every dispatch, so cancellation never leaks into the next one.
Which events are cancellable, and what cancelling each one skips: [Event list](https://docs.nursultan.fun/scripting/events/reference).

## Options

| Method | Type | Description |
|---|---|---|
| `EventOptions(ignoreCancelled)` | `EventOptions` | builds options with `Priority.NORMAL` (API 2) |
| `EventOptions(priority, ignoreCancelled)` | `EventOptions` | canonical constructor (throws `NullPointerException` when priority is null) |
| `EventOptions.DEFAULT` | `EventOptions` | `Priority.NORMAL`, `ignoreCancelled = false` |
| `EventOptions.priority()` | `Priority` | (deprecated) (no effect: the value is never read) |
| `EventOptions.ignoreCancelled()` | `boolean` | true skips the handler on an already-cancelled event |
| `EventOptions.ignoreCancelled(value)` | `EventOptions` | copy with the flag replaced |
| `EventOptions.priority(priority)` | `EventOptions` | copy of `DEFAULT` carrying that priority (deprecated) (no effect: the value is never read) |

The `on(...)` overloads build `EventOptions(ignoreCancelled)` themselves; explicit options only reach `Events.on(type, options, handler)`.

## Priority does nothing

Every script handler is registered at one fixed slot, `EventPriority.SCRIPT` — after the client's `BEFORE_ALL` and `BEFORE` modules, before its `NOW`, `AFTER` and `AFTER_ALL` ones; among scripts the order is registration order.
The enum is `@NoEffect` since API 2.

| Constant | Description |
|---|---|
| `FIRST` | (no effect on dispatch order) |
| `EARLY` | (no effect on dispatch order) |
| `NORMAL` | default in `EventOptions` (no effect on dispatch order) |
| `LATE` | (no effect on dispatch order) |
| `LAST` | (no effect on dispatch order) |

The members that still take or return a `Priority` — the two deprecated `on(priority, ...)` overloads and `EventOptions.priority(...)` — compile and discard the value.

## Unsubscribing

| Method | Type | Description |
|---|---|---|
| `Subscription.unsubscribe()` | `void` | removes the handler; idempotent |
| `Subscription.active()` | `boolean` | true while subscribed and the script is loaded |
| `Subscription.close()` | `void` | calls `unsubscribe()`; `Subscription` is `AutoCloseable` |

Switching the script off unsubscribes every handler; switching it on registers them again.

## Threads and budget

Every event fires on the Minecraft client thread except `PacketReceiveEvent` (netty IO thread) and `PacketSendEvent` (the thread that sends the packet) — see [Packets](https://docs.nursultan.fun/scripting/actions/packets).
One handler invocation has 250 ms; overrunning it switches the script off, and so do 5 consecutive throws — [Sandbox and limits](https://docs.nursultan.fun/scripting/extras/limits#budgets).
`Render2DEvent`, `Render3DEvent`, `PacketReceiveEvent` and `PacketSendEvent` ignore `EventOptions` entirely — both `priority` and `ignoreCancelled`.

---

# Event list

51 events, grouped by area. Every one fires on the Minecraft client thread except `PacketReceiveEvent` and `PacketSendEvent`. An event with no member table carries no payload. Subscribing, cancelling and options are on [Subscribing](https://docs.nursultan.fun/scripting/events/basics).

```kotlin
on<BlockHitEvent> {
    // the top face of a block is never hit
    if (it.side() == Side.UP) it.cancel()
}
```

## Ticks

| Event | Cancellable | Fires when |
|---|---|---|
| `ClientTickEvent` | no | once per client tick, also with no world loaded |
| `PrePlayerTickEvent` | no | once per client tick, before the local player ticks |
| `PlayerTickEvent` | no | mid local-player tick, at the cooldown update |
| `PostPlayerTickEvent` | no | after the local-player tick finished |
| `TimerEvent` | no | once per render tick, before the tick duration is used |

### TimerEvent

| Method | Type | Description |
|---|---|---|
| `timer()` | `float` | client tick-rate multiplier, 1.0 = normal speed |
| `timer(value)` | `void` | overrides it; tick duration is divided by it, not clamped |

Reset to 1.0 before every dispatch, so it does not persist between frames; `0` divides by zero.

## Movement

| Event | Cancellable | Fires when |
|---|---|---|
| `MoveInputEvent` | yes (never read) | each tick, after the movement keys were sampled |
| `MoveEvent` | yes | before a client entity applies its movement vector |
| `MovePacketEvent` | yes | once per tick, before the position and rotation packets go out |
| `MoveRelativeEvent` | no | after movement input was turned into velocity |
| `TravelEvent` | yes | before the local player's vanilla physics step |
| `JumpEvent` | no | the local player jumps |
| `SlowdownEvent` | no | the game reads the item-use movement multiplier |
| `FireworkEntitySpeedEvent` | no | a rocket boosts a gliding entity, once per tick per rocket (API 2) |
| `BlockPushEvent` | yes | the local player is about to be pushed out of a block |
| `EntityPushEvent` | yes | the local player pushes or is pushed by an entity |
| `WebCollisionEvent` | yes | the local player collides with a cobweb |

### MoveInputEvent

| Method | Type | Description |
|---|---|---|
| `forward()` | `boolean` | forward key held |
| `forward(value)` | `void` | overrides the forward flag; the game re-reads it |
| `backward()` | `boolean` | backward key held |
| `backward(value)` | `void` | overrides the backward flag; the game re-reads it |
| `left()` | `boolean` | strafe-left key held |
| `left(value)` | `void` | overrides the left flag; the game re-reads it |
| `right()` | `boolean` | strafe-right key held |
| `right(value)` | `void` | overrides the right flag; the game re-reads it |
| `jump()` | `boolean` | jump key held |
| `jump(value)` | `void` | overrides the jump flag; the game re-reads it |
| `sneak()` | `boolean` | sneak key held |
| `sneak(value)` | `void` | overrides the sneak flag; the game re-reads it |
| `sprint()` | `boolean` | sprint key held |
| `sprint(value)` | `void` | overrides the sprint flag; also drives the sprint key state |
| `moving()` | `boolean` | true when forward, backward, left or right is set |
| `toInput()` | [`MoveInput`](https://docs.nursultan.fun/scripting/actions/prediction) | immutable snapshot of the seven flags |

The game rebuilds the tick's player input from all seven flags. Cancelling does not stop vanilla input — the mixin never reads the flag.

### MoveEvent

| Method | Type | Description |
|---|---|---|
| `movement()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math) | movement delta in blocks for this move call |
| `movement(value)` | `void` | replaces the whole vector; the game re-reads it |
| `x()` | `double` | movement X in blocks |
| `y()` | `double` | movement Y in blocks |
| `z()` | `double` | movement Z in blocks |
| `set(x, y, z)` | `void` | replaces the vector component-wise; the game re-reads it |

Cancelling skips the whole move call: no displacement and no collision handling.

### MovePacketEvent

| Method | Type | Description |
|---|---|---|
| `x()` | `double` | outgoing packet X in world blocks |
| `x(value)` | `void` | overrides outgoing X; the sent packet re-reads it |
| `y()` | `double` | outgoing packet Y in world blocks, feet position |
| `y(value)` | `void` | overrides outgoing Y; the sent packet re-reads it |
| `z()` | `double` | outgoing packet Z in world blocks |
| `z(value)` | `void` | overrides outgoing Z; the sent packet re-reads it |
| `yaw()` | `float` | outgoing packet yaw in degrees, unclamped |
| `yaw(value)` | `void` | overrides outgoing yaw; the sent packet re-reads it |
| `pitch()` | `float` | outgoing packet pitch in degrees, unclamped |
| `pitch(value)` | `void` | overrides outgoing pitch; the sent packet re-reads it |
| `onGround()` | `boolean` | outgoing on-ground flag |
| `onGround(value)` | `void` | overrides the flag; the sent packet re-reads it |
| `sprinting()` | `boolean` | sprint state used by the sprint packet |
| `sprinting(value)` | `void` | overrides it; the sprint packet re-reads it |

Cancelling sends no position, rotation or sprint packet that tick.

### MoveRelativeEvent

| Method | Type | Description |
|---|---|---|
| `speed()` | `float` | movement speed factor applied to the input |
| `input()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math) | raw input: x sideways, y upward, z forward, each about -1..1 |

Read-only: nothing written to this event is copied back.

### SlowdownEvent

| Method | Type | Description |
|---|---|---|
| `multiplier()` | `float` | item-use movement multiplier, 1.0 = no slowdown |
| `multiplier(value)` | `void` | overrides it; returned in place of the vanilla value, not clamped |

### FireworkEntitySpeedEvent

| Method | Type | Description |
|---|---|---|
| `speed()` | `double` | elytra boost factor, vanilla value 1.5 |
| `speed(value)` | `void` | overrides the boost for this tick; the game re-reads it |
| `firework()` | [`Entity`](https://docs.nursultan.fun/scripting/game/entities) | the firework rocket entity |
| `shooter()` | [`LivingEntity?`](https://docs.nursultan.fun/scripting/game/entities) | gliding entity being boosted, null when the rocket has none |

Fires for every rocket in the world, not only your own.

### WebCollisionEvent

| Method | Type | Description |
|---|---|---|
| `x()` | `int` | cobweb block X |
| `y()` | `int` | cobweb block Y |
| `z()` | `int` | cobweb block Z |
| `position()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math) | block position as a vector, a copy |

Cancelling skips the cobweb slowdown.

## Combat

| Event | Cancellable | Fires when |
|---|---|---|
| `AttackEvent` | yes | before the client attacks an entity |
| `AttackedEvent` | no | after an attack went through |
| `TargetUpdateEvent` | no | the client's combat target changed or timed out |

### AttackEvent

| Method | Type | Description |
|---|---|---|
| `target()` | [`Entity`](https://docs.nursultan.fun/scripting/game/entities) | entity about to be attacked |

Cancelling aborts the attack entirely — no swing, no packet, and the attack cooldown is not reset.

### AttackedEvent

| Method | Type | Description |
|---|---|---|
| `target()` | [`Entity`](https://docs.nursultan.fun/scripting/game/entities) | entity that was just attacked |

### TargetUpdateEvent

| Method | Type | Description |
|---|---|---|
| `previous()` | [`Entity?`](https://docs.nursultan.fun/scripting/game/entities) | target before the change, null when there was none |
| `target()` | [`Entity?`](https://docs.nursultan.fun/scripting/game/entities) | new target, null when it was lost or timed out |
| `lost()` | `boolean` | true when `target()` is null |

Published by the client's target tracker: with no combat module running and no `combat.markTarget(...)` call it never fires.

## Blocks

| Event | Cancellable | Fires when |
|---|---|---|
| `BlockBreakingEvent` | yes | every frame the client processes the breaking input |
| `BlockHitEvent` | yes | the client starts or continues hitting a block |
| `BlockPlacedEvent` | no | a block is placed in the client world, by any placer |

### BlockBreakingEvent

| Method | Type | Description |
|---|---|---|
| `breaking()` | `boolean` | true while the attack key is held down |

Cancelling skips the whole breaking step for that frame, including the abort bookkeeping.

### BlockHitEvent

| Method | Type | Description |
|---|---|---|
| `x()` | `int` | block X in world block coordinates |
| `y()` | `int` | block Y in world block coordinates |
| `z()` | `int` | block Z in world block coordinates |
| `side()` | [`Side`](https://docs.nursultan.fun/scripting/game/raycast) | struck face |
| `position()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math) | block position as a vector, a copy |

Fires twice per break flow — at the first hit and at each progress update; cancelling makes both return false, so no hit packet and no progress.

### BlockPlacedEvent

| Method | Type | Description |
|---|---|---|
| `block()` | [`Block`](https://docs.nursultan.fun/scripting/game/world) | placed block snapshot |
| `id()` | `String` | block registry id |
| `x()` | `int` | block X in world block coordinates |
| `y()` | `int` | block Y in world block coordinates |
| `z()` | `int` | block Z in world block coordinates |
| `position()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math) | block position as a vector |

## Inventory

| Event | Cancellable | Fires when |
|---|---|---|
| `SlotClickEvent` | yes | a slot in a container screen was clicked |
| `RightClickEvent` | yes | the client runs its right-click step for a hand |
| `UseItemEvent` | yes | the client is about to send an item-use interaction |
| `StopUsingItemEvent` | yes | the client is about to stop using the held item |
| `FinishUsingItemEvent` | no | an item finished being used, food eaten, potion drunk |

### SlotClickEvent

| Method | Type | Description |
|---|---|---|
| `syncId()` | `int` | screen handler sync id of the open container |
| `slotId()` | `int` | slot index in the screen handler, -999 outside the window |
| `button()` | `int` | mouse button, 0 left and 1 right, or the target hotbar index for SWAP |
| `action()` | [`SlotAction`](https://docs.nursultan.fun/scripting/game/containers) | click action type, null maps to PICKUP |
| `item()` | [`Item`](https://docs.nursultan.fun/scripting/game/inventory) | stack in the clicked slot |

Cancelling drops the click: nothing is processed and no click packet is sent.

### RightClickEvent

| Method | Type | Description |
|---|---|---|
| `hand()` | [`Hand`](https://docs.nursultan.fun/scripting/game/inventory) | hand being used, null maps to MAIN_HAND |

Cancelling skips the whole use step — block and entity interaction included.

### UseItemEvent

| Method | Type | Description |
|---|---|---|
| `hand()` | [`Hand`](https://docs.nursultan.fun/scripting/game/inventory) | hand performing the interaction, null maps to MAIN_HAND |

Cancelling makes the interaction pass, so no item-use packet is sent.

### FinishUsingItemEvent

| Method | Type | Description |
|---|---|---|
| `item()` | [`Item`](https://docs.nursultan.fun/scripting/game/inventory) | stack whose use just completed |

## Input

| Event | Cancellable | Fires when |
|---|---|---|
| `KeyEvent` | yes | a key or mouse button goes down, up or repeats |
| `CharEvent` | yes | a character is typed into the window |
| `MouseScrollEvent` | yes | the mouse wheel scrolls |
| `LookInputEvent` | yes | an entity's look direction changes from cursor movement |

### KeyEvent

| Method | Type | Description |
|---|---|---|
| `key()` | [`Key`](https://docs.nursultan.fun/scripting/actions/keys) | pressed key or mouse button, `Key.UNKNOWN` when unmapped |
| `mods()` | `int` | GLFW modifier bitmask, 0 for synthetic events |
| `action()` | [`KeyAction`](https://docs.nursultan.fun/scripting/actions/keys) | PRESS, RELEASE or REPEAT |
| `mouse()` | `boolean` | true for mouse buttons |
| `pressed()` | `boolean` | true when the action is PRESS |
| `released()` | `boolean` | true when the action is RELEASE |
| `matches(other)` | `boolean` | true when the key constant is the same |

Cancelling keeps the key out of MC keybinds and screens.

### CharEvent

| Method | Type | Description |
|---|---|---|
| `codePoint()` | `int` | Unicode code point of the typed character |
| `character()` | `String` | the code point as a string, 1 or 2 chars |
| `mods()` | `int` | GLFW modifier bitmask active while typing |

### MouseScrollEvent

| Method | Type | Description |
|---|---|---|
| `vertical()` | `double` | vertical wheel delta, positive is up |
| `horizontal()` | `double` | horizontal wheel delta, 0 without a tilt wheel |

### LookInputEvent

| Method | Type | Description |
|---|---|---|
| `deltaX()` | `double` | horizontal cursor delta, multiplied by 0.15 to get yaw degrees |
| `deltaX(value)` | `void` | overrides the horizontal delta; the game re-reads it |
| `deltaY()` | `double` | vertical cursor delta, multiplied by 0.15 to get pitch degrees |
| `deltaY(value)` | `void` | overrides the vertical delta; the game re-reads it |

Fires for any entity, not only the local player; cancelling leaves yaw and pitch untouched.

## World and entities

| Event | Cancellable | Fires when |
|---|---|---|
| `EntitySpawnEvent` | no | an entity was added to the client world |
| `EntityRemoveEvent` | no | an entity is removed from the client world |
| `EffectEvent` | no | a status effect on the local player is added, refreshed or removed |
| `PotionImpactEvent` | no | a thrown potion collided, once per potion entity |
| `PlaySoundEvent` | yes | a positional world sound is about to be built |
| `WorldLoadEvent` | no | the client joins a world, respawns or changes dimension |

### EntitySpawnEvent

| Method | Type | Description |
|---|---|---|
| `entity()` | [`Entity`](https://docs.nursultan.fun/scripting/game/entities) | entity just added to the world |

### EntityRemoveEvent

| Method | Type | Description |
|---|---|---|
| `entity()` | [`Entity`](https://docs.nursultan.fun/scripting/game/entities) | entity being removed from the world |

Covers despawn, death removal and chunk unload alike; the reason is not exposed.

### EffectEvent

| Method | Type | Description |
|---|---|---|
| `effect()` | [`Effect?`](https://docs.nursultan.fun/scripting/game/entities) | effect snapshot, null only for `PLAYER_INIT` |
| `action()` | `EffectEvent.Action` | which map operation triggered the event |
| `added()` | `boolean` | true when the action is `ADD` |
| `removed()` | `boolean` | true when the action is `REMOVE` |

### EffectEvent.Action

| Constant | Description |
|---|---|
| `ADD` | effect newly inserted into the player's effect map |
| `UPDATE` | effect key already present, instance replaced |
| `REMOVE` | effect removed from the map |
| `PLAYER_INIT` | the local player's effect map was created, `effect()` is null |

### PotionImpactEvent

| Method | Type | Description |
|---|---|---|
| `potion()` | [`Entity`](https://docs.nursultan.fun/scripting/game/entities) | the potion projectile entity |
| `hitEntity()` | [`Entity?`](https://docs.nursultan.fun/scripting/game/entities) | entity that was hit, null for block and miss hits |
| `position()` | [`Vec?`](https://docs.nursultan.fun/scripting/game/math) | impact position in world blocks, null without a hit result |

### PlaySoundEvent

| Method | Type | Description |
|---|---|---|
| `id()` | `String` | sound registry id, empty when unresolvable |
| `category()` | `String` | lowercased sound category, empty when absent |
| `volume()` | `float` | sound volume, 1.0 = normal |
| `volume(value)` | `void` | overrides volume; the sound instance re-reads it |
| `pitch()` | `float` | pitch multiplier, vanilla range 0.5..2.0 |
| `pitch(value)` | `void` | overrides pitch; the sound instance re-reads it |
| `x()` | `double` | sound source X in world blocks |
| `x(value)` | `void` | overrides source X; the sound instance re-reads it |
| `y()` | `double` | sound source Y in world blocks |
| `y(value)` | `void` | overrides source Y; the sound instance re-reads it |
| `z()` | `double` | sound source Z in world blocks |
| `z(value)` | `void` | overrides source Z; the sound instance re-reads it |
| `position()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math) | current x, y and z as a copy |
| `position(value)` | `void` | sets x, y and z from the vector |

`id()` and `category()` are read-only. Only sounds routed through the positional world-sound path fire this event; cancelling means the sound is not played.

## Packets

| Event | Cancellable | Fires when |
|---|---|---|
| `PacketReceiveEvent` | yes | a clientbound packet was decoded, before the game handles it |
| `PacketSendEvent` | yes | a serverbound packet is about to leave the client |

### PacketReceiveEvent

| Method | Type | Description |
|---|---|---|
| `packet()` | [`S2CPacket`](https://docs.nursultan.fun/scripting/actions/packets) | decoded clientbound packet |

Runs on the netty IO thread; inside a bundle each sub-packet fires separately and cancelling removes it from the bundle.

### PacketSendEvent

| Method | Type | Description |
|---|---|---|
| `packet()` | [`C2SPacket`](https://docs.nursultan.fun/scripting/actions/packets) | decoded serverbound packet |

Runs on the calling thread. For both events only packets the client can decode reach a handler, and `EventOptions` is ignored.

## Rendering

| Event | Cancellable | Fires when |
|---|---|---|
| `Render2DEvent` | no | every frame, in the script 2D pass after the HUD |
| `Render3DEvent` | no | every frame, during the world render |
| `CameraEvent` | yes | every frame, after the camera position was computed |
| `PerspectiveEvent` | no | the point of view changed to a different value (API 2) |
| `RenderCrosshairEvent` | yes | the vanilla crosshair is about to be drawn (API 2) |
| `RenderItemEvent` | yes | before the first-person swing transform is applied |
| `BlockOutlineEvent` | yes | before the targeted block outline is drawn |
| `SwingSpeedEvent` | no | the game asks how long a hand swing lasts |

### Render2DEvent

| Method | Type | Description |
|---|---|---|
| `render()` | [`Render`](https://docs.nursultan.fun/scripting/ui/render-2d) | the shared 2D drawing surface |
| `tickDelta()` | `float` | partial tick progress, 0..1 |
| `width()` | `float` | framebuffer width in physical pixels, not GUI-scaled |
| `height()` | `float` | framebuffer height in physical pixels, not GUI-scaled |

### Render3DEvent

| Method | Type | Description |
|---|---|---|
| `render()` | [`Render3D`](https://docs.nursultan.fun/scripting/ui/render-3d) | the shared world-space drawing surface |
| `tickDelta()` | `float` | partial tick progress, 0..1 |
| `camera()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math) | camera world position in blocks, the origin world draws use |
| `viewMatrix()` | `float[]` | 16 floats, column-major, cloned per call (API 2) |
| `projectionMatrix()` | `float[]` | 16 floats, column-major, cloned per call (API 2) |

Both render events ignore `EventOptions` and are skipped when nothing is subscribed; `Render3DEvent` also needs a loaded world.

### CameraEvent

| Method | Type | Description |
|---|---|---|
| `yaw()` | `float` | camera yaw in degrees, interpolated by tick delta |
| `yaw(value)` | `void` | overrides camera yaw; applied to the camera |
| `pitch()` | `float` | camera pitch in degrees, interpolated by tick delta |
| `pitch(value)` | `void` | overrides camera pitch; applied to the camera |
| `x()` | `double` | camera X in world coordinates, interpolated |
| `x(value)` | `void` | overrides camera X; applied to the camera |
| `y()` | `double` | camera Y in world coordinates, eye offset included |
| `y(value)` | `void` | overrides camera Y; applied to the camera |
| `z()` | `double` | camera Z in world coordinates, interpolated |
| `z(value)` | `void` | overrides camera Z; applied to the camera |
| `position()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math) | current x, y and z as a copy |
| `position(value)` | `void` | sets x, y and z from the vector |

Cancelling skips the rest of the camera update — third-person distance and clipping — but the values set here are still applied.

### PerspectiveEvent

| Method | Type | Description |
|---|---|---|
| `previous()` | [`Perspective`](https://docs.nursultan.fun/scripting/actions/control#game-settings) | perspective before the change, never null |
| `current()` | [`Perspective`](https://docs.nursultan.fun/scripting/actions/control#game-settings) | perspective after the change, never null |

Setting the same perspective again fires nothing.

### RenderItemEvent

| Method | Type | Description |
|---|---|---|
| `arm()` | [`Arm`](https://docs.nursultan.fun/scripting/game/inventory) | arm being rendered, LEFT or RIGHT |
| `swingProgress()` | `float` | swing animation progress, 0..1 |
| `translate(x, y, z)` | `void` | offsets the held-item matrix, item-space units (API 3) |
| `rotate(degrees, axisX, axisY, axisZ)` | `void` | rotates it about the axis, degrees (API 3) (no effect: axis length squared under 1e-6) |
| `rotateX(degrees)` | `void` | rotates it about `(1, 0, 0)`, degrees (API 3) |
| `rotateY(degrees)` | `void` | rotates it about `(0, 1, 0)`, degrees (API 3) |
| `rotateZ(degrees)` | `void` | rotates it about `(0, 0, 1)`, degrees (API 3) |
| `scale(x, y, z)` | `void` | scales it per axis (API 3) |

Cancelling leaves the matrix at the hand origin, so the swing transform is skipped for that hand.
The ops write into the live hand matrix and compose in call order, before the vanilla swing transform.

### Matrix

| Method | Type | Description |
|---|---|---|
| `translate(x, y, z)` | `void` | offsets the matrix, item-space units (API 3) |
| `rotate(degrees, axisX, axisY, axisZ)` | `void` | rotates it about the axis, degrees (API 3) (no effect: axis length squared under 1e-6) |
| `scale(x, y, z)` | `void` | scales it per axis (API 3) |

`RenderItemEvent.Matrix` is the adapter the event forwards to; `rotateX`, `rotateY` and `rotateZ` exist only on the event.

### BlockOutlineEvent

| Method | Type | Description |
|---|---|---|
| `x()` | `int` | outlined block X in world block coordinates |
| `y()` | `int` | outlined block Y in world block coordinates |
| `z()` | `int` | outlined block Z in world block coordinates |
| `box()` | [`Box`](https://docs.nursultan.fun/scripting/game/math) | outline shape offset to absolute world coordinates |

Fires only while an outline with a non-empty shape exists, and before both render events of the same frame.

### SwingSpeedEvent

| Method | Type | Description |
|---|---|---|
| `durationTicks()` | `int` | hand-swing animation length in ticks, vanilla base 6 |
| `durationTicks(value)` | `void` | overrides the duration; returned to the game, not clamped |

Local player only; swing progress divides by this value.

## Modules

| Event | Cancellable | Fires when |
|---|---|---|
| `ModuleToggleEvent` | no | a client module or a script toggled, after the state changed |

### ModuleToggleEvent

| Method | Type | Description |
|---|---|---|
| `name()` | `String` | module registry name, or the script toggle name |
| `enabled()` | `boolean` | state after the toggle |
| `fromScript()` | `boolean` | true when the toggled unit is a script |

## Everything else

| Event | Cancellable | Fires when |
|---|---|---|
| `ServerConnectEvent` | no | the client starts connecting to a multiplayer server |
| `ScreenCloseEvent` | no | any vanilla screen is closing |
| `FramebufferResizeEvent` | no | the game window resolution changed |

### ServerConnectEvent

| Method | Type | Description |
|---|---|---|
| `host()` | `String` | server hostname, empty when the address is null |
| `port()` | `int` | server port, 0 when the address is null |
| `address()` | `String` | host and port joined by a colon |

Fires before the socket is opened, so earlier than `WorldLoadEvent`.

### FramebufferResizeEvent

| Method | Type | Description |
|---|---|---|
| `width()` | `int` | framebuffer width in pixels, not GUI-scaled |
| `height()` | `int` | framebuffer height in pixels, not GUI-scaled |

---

# Game data

What you can read: the player, the world, entities, the inventory, the server — and the vectors, boxes and angles everything is measured in.

---

# Your player

`player` is `game.player()` — a live view of the local player, re-read on every call; every member throws `ScriptStateException` when there is no player. It is a `PlayerEntity`, so it carries everything an entity has: the tables below are the whole surface of `player`, inherited members included, and [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) documents those same members for any entity.

```kotlin
on<ClientTickEvent> {
    whenInGame {
        val eyes = player.eyePosition()
        val charge = player.attackCooldown()
        chat.print("hp ${player.health()} eyeY ${eyes.y()} charge $charge")
    }
}
```

## Position and movement

| Method | Type | Description |
|---|---|---|
| `player.position()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math#vec) | current feet position in world blocks |
| `player.x()` | `double` | current world X in blocks |
| `player.y()` | `double` | current world Y in blocks |
| `player.z()` | `double` | current world Z in blocks |
| `player.previousPosition()` | `Vec` | position at the previous tick |
| `player.renderPosition()` | `Vec` | tick-interpolated position used for drawing |
| `player.eyePosition()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math#vec) | eye position in world coordinates |
| `player.box()` | [`Box`](https://docs.nursultan.fun/scripting/game/math#box) | bounding box in world coordinates |
| `player.width()` | `float` | hitbox width in blocks |
| `player.height()` | `float` | hitbox height in blocks |
| `player.rotation()` | [`Rotation`](https://docs.nursultan.fun/scripting/game/math#rotation) | yaw and pitch in degrees |
| `player.yaw()` | `float` | yaw in degrees |
| `player.pitch()` | `float` | pitch in degrees, -90..90 |
| `player.bodyYaw()` | `float` | body yaw in degrees |
| `player.headYaw()` | `float` | head yaw in degrees |
| `player.velocity()` | `Vec` | velocity in blocks per tick |
| `player.velocity(value)` | `void` | overwrites it; gravity and input still apply on the next tick (API 5) (throws `ScriptException` when `value` is null) |
| `player.movementSpeed()` | `float` | movement-speed attribute in blocks per tick |
| `player.distanceTo(other)` | `double` | distance between positions in blocks (throws `ScriptStateException` when `other` is not a world entity) |
| `player.distanceTo(point)` | `double` | distance from the position to a point in blocks |
| `player.fallDistanceBlocks()` | `double` | accumulated fall distance in blocks |

## State

| Method | Type | Description |
|---|---|---|
| `player.onGround()` | `boolean` | standing on ground |
| `player.sneaking()` | `boolean` | sneak flag |
| `player.sprinting()` | `boolean` | sprint flag |
| `player.serverSprinting()` | `boolean` | sprint state the server was last told (API 5) |
| `player.wasSprinting()` | `boolean` | older name for `serverSprinting()`, same value |
| `player.hasMovementInput()` | `boolean` | movement keys produce input this tick |
| `player.swimming()` | `boolean` | swimming flag |
| `player.crawling()` | `boolean` | crawling in a 1-block gap |
| `player.sleeping()` | `boolean` | entity is sleeping |
| `player.climbing()` | `boolean` | standing on a climbable block |
| `player.gliding()` | `boolean` | elytra gliding |
| `player.riding()` | `boolean` | has a vehicle |
| `player.flying()` | `boolean` | creative flight is active |
| `player.creative()` | `boolean` | creative abilities are set |
| `player.usingRiptide()` | `boolean` | in a riptide spin attack |
| `player.inWater()` | `boolean` | touching water |
| `player.inLava()` | `boolean` | standing in lava |
| `player.wet()` | `boolean` | touching water or standing in rain |
| `player.submerged()` | `boolean` | eyes are under water |
| `player.onFire()` | `boolean` | entity is burning |
| `player.fireImmune()` | `boolean` | entity type is immune to fire |
| `player.frozen()` | `boolean` | powder-snow freeze is fully applied |
| `player.frozenTicks()` | `int` | powder-snow freeze progress in ticks |
| `player.alive()` | `boolean` | alive and not removed from the world |
| `player.pose()` | [`Pose`](https://docs.nursultan.fun/scripting/game/entities#poses) | current entity pose |
| `player.airTicks()` | `int` | remaining air in ticks |
| `player.maxAirTicks()` | `int` | maximum air in ticks |
| `player.baby()` | `boolean` | entity is a baby |
| `player.scale()` | `float` | scale multiplier, 1.0 by default |
| `player.silent()` | `boolean` | silent flag |
| `player.noGravity()` | `boolean` | no-gravity flag |
| `player.age()` | `int` | ticks the entity has existed on the client |
| `player.glowing()` | `boolean` | glowing flag |
| `player.invisible()` | `boolean` | vanilla invisibility flag |
| `player.invisible(value)` | `void` | sets it client-side; server metadata overwrites it |
| `player.hidden()` | `boolean` | client render-suppression flag; false for untracked entities |
| `player.hidden(value)` | `void` | sets the flag; no-op for untracked entities |
| `player.vehicle()` | [`Entity?`](https://docs.nursultan.fun/scripting/game/entities) | entity being ridden, null when on foot |
| `player.passengers()` | [`List<Entity>`](https://docs.nursultan.fun/scripting/game/entities) | entities riding this one, empty when none |

`invisible(true)` hides the model and not the nametag.
`hidden(true)` outlives the script being switched off — [`world.unhideEntities()`](https://docs.nursultan.fun/scripting/game/world) clears it.

## Health and effects

| Method | Type | Description |
|---|---|---|
| `player.health()` | `float` | current health in half-hearts |
| `player.maxHealth()` | `float` | maximum health in half-hearts |
| `player.absorption()` | `float` | absorption (yellow) hearts |
| `player.armorPoints()` | `int` | armor points, 0..20 |
| `player.bypassedHealth()` | `float` | scoreboard health while BypassHealth is on, else `health()` |
| `player.dead()` | `boolean` | health is at or below zero |
| `player.deathTicks()` | `int` | ticks since death, 0 while alive |
| `player.hurtTicks()` | `int` | remaining hurt-animation ticks |
| `player.hasEffect(effectId)` | `boolean` | an effect with that exact namespaced id is active |
| `player.effects()` | [`List<Effect>`](https://docs.nursultan.fun/scripting/game/entities#effects) | snapshots of every active status effect |
| `player.effect(effectId)` | [`Effect?`](https://docs.nursultan.fun/scripting/game/entities#effects) | one active effect by exact namespaced id, null when absent |
| `player.attributes()` | [`Map<String, Attribute>`](https://docs.nursultan.fun/scripting/game/entities#attributes) | unmodifiable map of every attribute present, keyed by namespaced id |
| `player.attribute(attributeId)` | [`Attribute?`](https://docs.nursultan.fun/scripting/game/entities#attributes) | one attribute, `minecraft:` added when unqualified; null when absent |

`bypassedHealth()` equals `health()` in singleplayer and whenever the BypassHealth module is off.
Effect ids are compared exactly: `hasEffect("minecraft:speed")` matches, `hasEffect("speed")` does not.

## Hunger

| Method | Type | Description |
|---|---|---|
| `player.food()` | `int` | food level, 0..20 |
| `player.saturation()` | `float` | saturation level, 0..food |
| `player.hunger()` | `Hunger` | shared live hunger view (API 2) |

### The Hunger view

| Method | Type | Description |
|---|---|---|
| `hunger.food()` | `int` | food level, 0..20 |
| `hunger.maxFood()` | `int` | constant 20 |
| `hunger.saturation()` | `float` | saturation level, 0..food |
| `hunger.full()` | `boolean` | food level is at maximum |
| `hunger.canSprint()` | `boolean` | food level allows sprinting, above 6 |

Every `Hunger` member is API 2.
Exhaustion and the healing/starving tick counter are server-side, stay at zero on the client, and are not exposed.

## Experience

| Method | Type | Description |
|---|---|---|
| `player.xpLevel()` | `int` | experience level |
| `player.xpProgress()` | `float` | progress to the next level, 0..1 |

## Identity

| Method | Type | Description |
|---|---|---|
| `player.name()` | `String` | plain text of the entity name |
| `player.uuid()` | `String` | entity uuid in string form |
| `player.id()` | `int` | client network entity id |
| `player.typeId()` | `String` | namespaced entity-type id, e.g. `minecraft:player` |
| `player.displayName()` | [`Text`](https://docs.nursultan.fun/scripting/ui/text) | styled name, carries team colour and custom name |
| `player.hasCustomName()` | `boolean` | entity carries a custom name |
| `player.customName()` | `String?` | plain custom name, null when there is none |
| `player.team()` | `String?` | scoreboard team name, null when in no team |
| `player.teamColor()` | `int` | opaque ARGB team colour, -1 without team or colour |
| `player.isFriend()` | `boolean` | name is in the client friend list |
| `player.isParty()` | `boolean` | name is a party member |
| `player.isAlly()` | `boolean` | friend, party or NoFriendDamage teammate; always false while NoFriendDamage is off |
| `player.isBot()` | `boolean` | client bot heuristics; false for self and on FT servers |
| `player.pingMs()` | `int` | own player-list latency in milliseconds, 0 without an entry |
| `player.gameMode()` | [`GameMode`](https://docs.nursultan.fun/scripting/game/entities#players) | current game mode, from the interaction manager |
| `player.skinTexture()` | [`Texture?`](https://docs.nursultan.fun/scripting/ui/render-2d) | body skin texture; null for non-client players and while StreamerMode hides skins |
| `player.isLiving()` | `boolean` | wrapped entity is a living entity |
| `player.isPlayer()` | `boolean` | wrapped entity is a player |
| `player.isSelf()` | `boolean` | wrapped entity is the local player |
| `player.asLiving()` | [`LivingEntity?`](https://docs.nursultan.fun/scripting/game/entities#living-entities) | same entity as `LivingEntity`, null otherwise |
| `player.asPlayer()` | [`PlayerEntity?`](https://docs.nursultan.fun/scripting/game/entities#players) | same entity as `PlayerEntity`, null otherwise |
| `player.asTextDisplay()` | [`TextDisplay?`](https://docs.nursultan.fun/scripting/game/entities#text-displays) | same entity as `TextDisplay`, null otherwise |

## Equipment and item use

| Method | Type | Description |
|---|---|---|
| `player.mainHandItem()` | [`Item`](https://docs.nursultan.fun/scripting/game/inventory) | main-hand stack, empty item when nothing is held |
| `player.offHandItem()` | `Item` | off-hand stack, empty item when nothing is held |
| `player.armorItem(slot)` | `Item` | stack in that [`ArmorSlot`](https://docs.nursultan.fun/scripting/game/inventory), empty item when none |
| `player.armorItems()` | `List<Item>` | non-empty humanoid armor stacks only |
| `player.isNaked()` | `boolean` | no armor in any of the four humanoid slots |
| `player.activeItem()` | `Item?` | stack being used, null when none |
| `player.usingItem()` | `boolean` | currently using an item |
| `player.usingHand()` | [`Hand`](https://docs.nursultan.fun/scripting/game/inventory#hands) | active hand, `MAIN_HAND` unless the off hand is active |
| `player.blocking()` | `boolean` | blocking with a shield |
| `player.itemUseTicks()` | `int` | ticks the current item has been used for |
| `player.itemUseTicksLeft()` | `int` | ticks left before the use completes |
| `player.swinging()` | `boolean` | hand-swing animation is running (API 2) |
| `player.swingTicks()` | `int` | current hand-swing animation tick (API 2) |

## Reach and attack cooldown

| Method | Type | Description |
|---|---|---|
| `player.entityReachBlocks()` | `double` | entity interaction range in blocks |
| `player.blockReachBlocks()` | `double` | block interaction range in blocks |
| `player.attackCooldown()` | `float` | attack charge at the tick boundary, 0..1 |
| `player.attackCooldown(tickDelta)` | `float` | attack charge interpolated by `tickDelta`, 0..1 (API 2) |
| `player.cooldownPeriod()` | `float` | full cooldown length in ticks for the held item (API 2) |
| `player.ticksSinceLastAttack()` | `int` | ticks since the last attack (API 2) |
| `player.belowMinimumAttackCharge()` | `boolean` | main-hand charge below the vanilla minimum, at `tickDelta` 0 |

## Actions

| Method | Type | Description |
|---|---|---|
| `player.respawn()` | `void` | sends a respawn request, queued onto the client thread |

---

# World and blocks

`world` is `game.world()`. Every call throws `ScriptStateException` when there is no world loaded; a block read is a snapshot taken at call time.

```kotlin
on<ClientTickEvent> {
    whenInGame {
        val under = world.block(player.x().toInt(), player.y().toInt() - 1, player.z().toInt())
        val fluid = under.fluid()
        val nearby = world.entitiesNear(player.position(), 8.0, filters.attackable())
        chat.print("${under.id()} ${fluid?.id() ?: "dry"} ${nearby.size}")
    }
}
```

## The world itself

| Method | Type | Description |
|---|---|---|
| `world.dimension()` | `String` | dimension registry key, e.g. `minecraft:overworld` |
| `world.timeTicks()` | `long` | total world age in ticks |
| `world.dayTimeTicks()` | `long` | time of day in ticks, cycle length 24000 |
| `world.raining()` | `boolean` | rain active in this world |
| `world.thundering()` | `boolean` | thunderstorm active in this world |
| `world.rainGradient()` | `float` | rain strength 0..1 |
| `world.thunderGradient()` | `float` | thunder strength 0..1 |
| `world.biome(position)` | `String?` | biome registry id at the floored position |
| `world.respawnAnchorWorks(x, y, z)` | `boolean` | a respawn anchor sets spawn here instead of exploding (API 6) |
| `world.topY(x, z)` | `int` | y above the highest non-air block, bottom y when unloaded |

## Reading a block

| Method | Type | Description |
|---|---|---|
| `world.block(x, y, z)` | `Block` | block state snapshot, `void_air` outside world limits |
| `world.block(position)` | `Block` | same, `Vec` coordinates floored |
| `world.blockPending(x, y, z)` | `boolean` | the block there is your own prediction the server has not acknowledged yet (API 7) |
| `block.id()` | `String` | block registry id, e.g. `minecraft:stone` |
| `block.name()` | `String` | localized block name |
| `block.x()` | `int` | block x coordinate |
| `block.y()` | `int` | block y coordinate |
| `block.z()` | `int` | block z coordinate |
| `block.position()` | `Vec` | block corner coordinates |
| `block.box()` | `Box` | the 1×1×1 cube at this position, not the block shape |

`Vec` and `Box` are documented on [Vectors, boxes, angles](https://docs.nursultan.fun/scripting/game/math).

## Block state

| Method | Type | Description |
|---|---|---|
| `block.air()` | `boolean` | state is air |
| `block.solid()` | `boolean` | state is solid |
| `block.liquid()` | `boolean` | state is a liquid block |
| `block.opaque()` | `boolean` | state is opaque |
| `block.blocksMovement()` | `boolean` | state blocks movement |
| `block.replaceable()` | `boolean` | a placed block can replace this state |
| `block.fullCube()` | `boolean` | state is a full cube at this position |
| `block.hasCollision()` | `boolean` | collision shape at this position is non-empty |
| `block.collisionBoxes()` | `List<Box>` | collision shape parts in world coordinates, empty when none (API 3) |
| `block.outlineBoxes()` | `List<Box>` | outline shape parts in world coordinates, empty when none (API 3) |
| `block.luminance()` | `int` | emitted light 0..15 |
| `block.opacity()` | `int` | light attenuation 0..15 |
| `block.hardness()` | `float` | breaking hardness at this position, -1 for unbreakable |
| `block.blastResistance()` | `float` | explosion resistance |
| `block.slipperiness()` | `float` | friction factor, 0.6 default, 0.98 for ice |
| `block.velocityMultiplier()` | `float` | horizontal movement multiplier |
| `block.jumpVelocityMultiplier()` | `float` | jump velocity multiplier |
| `block.emitsRedstone()` | `boolean` | state emits redstone power |
| `block.toolRequired()` | `boolean` | correct tool required for drops |
| `block.burnable()` | `boolean` | state is burnable |
| `block.randomTicks()` | `boolean` | state receives random ticks |
| `block.pistonBehavior()` | `String` | lowercase: normal, destroy, block, ignore, push_only |
| `block.mapColor()` | `int` | map colour as ARGB, alpha forced to 0xFF |

## Properties and tags

| Method | Type | Description |
|---|---|---|
| `block.properties()` | `Map<String, String>` | every state property as name -> value, unmodifiable, insertion-ordered |
| `block.property(name)` | `String?` | one property value by case-insensitive name |
| `block.tags()` | `List<String>` | block tag ids |
| `block.hasTag(tagId)` | `boolean` | block is in that tag, leading `#` and namespace optional (throws `ScriptException` when tagId is blank or unparsable) |

## Block entities

| Method | Type | Description |
|---|---|---|
| `block.hasBlockEntity()` | `boolean` | state declares a block entity |
| `block.blockEntity()` | `BlockEntity?` | block entity at this position (main thread only) |
| `world.blockEntitiesIn(box)` | `List<BlockEntity>` | block entities whose block centre is inside the box, immutable list (main thread only) (throws `ScriptException` when the box spans more than 32×32 chunks) |
| `blockEntity.type()` | `String` | block entity type registry id, e.g. `minecraft:vault` |
| `blockEntity.x()` | `int` | block x coordinate |
| `blockEntity.y()` | `int` | block y coordinate |
| `blockEntity.z()` | `int` | block z coordinate |
| `blockEntity.position()` | `Vec` | block coordinates |
| `blockEntity.displayItem()` | `Item?` | vault display item or brushable block item, null otherwise |
| `blockEntity.nbt()` | `String` | client-side nbt as a string, empty without a world |

A block entity carries only what the server already sent: a vault's display item is there, a closed chest's contents are not.
`displayItem()` returns an ordinary [item](https://docs.nursultan.fun/scripting/game/inventory).

## Fluids

| Method | Type | Description |
|---|---|---|
| `block.fluid()` | `Fluid?` | fluid state at this position, waterlogging included, null when dry |
| `fluid.id()` | `String` | fluid registry id, e.g. `minecraft:water` |
| `fluid.level()` | `int` | fluid level 1..8, 8 for a source block |
| `fluid.still()` | `boolean` | source block rather than flowing |
| `fluid.height()` | `float` | rendered fluid height 0..1 |

## Light

| Method | Type | Description |
|---|---|---|
| `world.lightLevel(x, y, z)` | `int` | rendered light level 0..15, ambient darkness applied |
| `world.blockLight(x, y, z)` | `int` | block-source light 0..15 |
| `world.skyLight(x, y, z)` | `int` | sky-source light 0..15, no time-of-day adjustment |

## Entities in the world

| Method | Type | Description |
|---|---|---|
| `world.entityCount()` | `int` | number of loaded entities |
| `world.entities()` | `List<Entity>` | every loaded entity, own player included, fresh mutable list |
| `world.entities(filter)` | `List<Entity>` | loaded entities passing the filter, null filter keeps all |
| `world.entitiesIn(box)` | `List<Entity>` | entities whose hitbox intersects the box |
| `world.entitiesIn(box, filter)` | `List<Entity>` | same, filtered, null filter keeps all |
| `world.entitiesNear(origin, radiusBlocks, filter)` | `List<Entity>` | entities within a spherical radius in blocks (throws `ScriptException` when radiusBlocks <= 0) |
| `world.players()` | `List<PlayerEntity>` | loaded players, immutable list |
| `world.players(filter)` | `List<PlayerEntity>` | loaded players passing the filter, immutable list |
| `world.entityByName(name)` | `Entity?` | first entity whose display name matches, case-insensitive |
| `world.entityById(entityId)` | `Entity?` | entity with that network id |
| `world.entityByUuid(uuid)` | `Entity?` | linear scan for that uuid (throws `ScriptException` when the string is not a uuid) |
| `world.nearestEntity(origin, radiusBlocks, filter)` | `Entity?` | closest matching entity within the radius (throws `ScriptException` when radiusBlocks <= 0) |

Entity members and the ready-made filters are on [Entities and filters](https://docs.nursultan.fun/scripting/game/entities).

## Collisions

| Method | Type | Description |
|---|---|---|
| `world.collisionsIn(box)` | `List<Box>` | boxes of hard-colliding entities in the box, block collisions excluded |
| `world.blockCollisionsIn(box)` | `List<Box>` | block collision shape parts intersecting the box, entities excluded (API 3) |
| `world.isFree(box)` | `boolean` | no colliding entity intersects the box, block collisions not checked |
| `world.canPlace(itemId, x, y, z)` | `boolean` | cell replaceable and no entity in the way, support not checked (API 6) (throws `ScriptException` when the item is not a block) |
| `world.isBlockSpaceFree(box)` | `boolean` | no block collision intersects the box, entities not checked (API 3) |

A partial block reports one box per shape part: a fence gives the post and every connected arm, a slab one half-height box.
These are the same shapes `raycast.blocks(...)` clips against; `block.box()` stays the plain 1×1×1 cube.

## Removing and hiding

| Method | Type | Description |
|---|---|---|
| `world.removeEntity(entity)` | `boolean` | client-side removal by wrapper, false when null (main thread only) |
| `world.removeEntity(entityId)` | `boolean` | client-side removal by network id, false for own player (main thread only) |
| `world.unhideEntities()` | `void` | clears the [hidden](https://docs.nursultan.fun/scripting/game/entities#hiding-one) flag on every loaded entity |
| `world.hideEntity(entity)` | `void` | stops drawing the entity: model, armour, nametag, shadow, glow (API 10) (main thread only) (throws `ScriptStateException` when `entity` is not a world entity) |
| `world.showEntity(entity)` | `void` | undoes this script's own `hideEntity` (API 10) (main thread only) (throws `ScriptStateException` when `entity` is not a world entity) |
| `world.entityHidden(entity)` | `boolean` | this script is hiding the entity with `hideEntity` (API 10) (main thread only) (throws `ScriptStateException` when `entity` is not a world entity) |

Removal is local: the server keeps the entity and resends it on a chunk reload, and each removal fires `EntityRemoveEvent`.
`hideEntity` belongs to the script that called it: switching the script off or unloading it shows the entity again, `unhideEntities()` does not touch it, an entity two scripts hide stays hidden until both show it, and one that unloads and comes back is visible again.

## Entity models

| Method | Type | Description |
|---|---|---|
| `world.captureModel(entity)` | `EntityModel?` | model pose drawn this frame, null for non-living entities (API 10) (main thread only) (throws `ScriptStateException` when `entity` is not a world entity) |
| `model.entity()` | `Entity` | entity the model was captured from (API 10) |
| `model.cuboids()` | `List<ModelCuboid>` | every visible cuboid of the model, immutable list (API 10) |
| `cuboid.part()` | `String` | model part path, e.g. `head` or `right_arm/right_sleeve`, empty for the root (API 10) |
| `cuboid.index()` | `int` | cuboid index inside its part, from 0 (API 10) |
| `cuboid.corners()` | `List<Vec>` | 8 corners in world blocks, 0..3 one face, 4..7 the opposite one (API 10) |
| `cuboid.center()` | `Vec` | cuboid centre in world blocks (API 10) |

The pose is the one Minecraft draws this frame, animation, sneaking, sleeping and baby models included; armour, held items, capes and other layers are not in it.
Corners `i` and `i + 4` share an edge, and `0-1-2-3` and `4-5-6-7` each run around one face; a hidden entity can still be captured.

## Sounds and particles

| Method | Type | Description |
|---|---|---|
| `world.spawnParticle(particleId, position, velocity)` | `void` | client-only particle, null velocity means zero (throws `ScriptException` on an unknown particle) |
| `world.playSound(soundId, position, volume, pitch)` | `void` | client-only sound at a position, category PLAYERS (throws `ScriptException` on an unknown sound) |
| `world.playSound(soundId, volume, pitch)` | `void` | client-only sound at the listener, category PLAYERS (throws `ScriptException` on an unknown sound) |

---

# Entities and filters

Every entity you get from [the world](https://docs.nursultan.fun/scripting/game/world), a [ray](https://docs.nursultan.fun/scripting/game/raycast) or an event is a live wrapper: each getter reads the wrapped Minecraft entity at call time, and it keeps reading it after the entity leaves the world, so `alive()` is what tells you it is gone. `LivingEntity`, `PlayerEntity`, `TextDisplay` and `ItemEntity` add members on top of `Entity`; the local player is a [`SelfPlayer`](https://docs.nursultan.fun/scripting/game/player).

```kotlin
on<ClientTickEvent> {
    val nearby = filters.player().and(filters.attackable())
    val target = world.nearestEntity(player.position(), 6.0, nearby)?.asLiving() ?: return@on

    chat.print("${target.name()} ${target.health()} / ${target.maxHealth()}")
    chat.print("box height ${target.box().sizeY()}")
}
```

## Identity

| Method | Type | Description |
|---|---|---|
| `entity.id()` | `int` | client network entity id |
| `entity.uuid()` | `String` | entity uuid in string form |
| `entity.name()` | `String` | plain text of the entity name |
| `entity.typeId()` | `String` | namespaced entity-type id, e.g. `minecraft:zombie` |
| `entity.displayName()` | [`Text`](https://docs.nursultan.fun/scripting/ui/text) | styled name, carries team colour and custom name |
| `entity.hasCustomName()` | `boolean` | entity carries a custom name |
| `entity.customName()` | `String?` | plain custom name, null when there is none |
| `entity.isLiving()` | `boolean` | wrapped entity is a living entity |
| `entity.isPlayer()` | `boolean` | wrapped entity is a player |
| `entity.isSelf()` | `boolean` | wrapped entity is the local player |
| `entity.isItem()` | `boolean` | wrapped entity is a dropped item stack (API 4) |
| `entity.asLiving()` | `LivingEntity?` | same entity as `LivingEntity`, null otherwise |
| `entity.asPlayer()` | `PlayerEntity?` | same entity as `PlayerEntity`, null otherwise |
| `entity.asTextDisplay()` | `TextDisplay?` | same entity as `TextDisplay`, null otherwise |
| `entity.asItemEntity()` | `ItemEntity?` | same entity as `ItemEntity`, null otherwise (API 4) |

## Position and size

| Method | Type | Description |
|---|---|---|
| `entity.position()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math#vec) | current feet position in world blocks |
| `entity.x()` | `double` | current world X in blocks |
| `entity.y()` | `double` | current world Y in blocks |
| `entity.z()` | `double` | current world Z in blocks |
| `entity.previousPosition()` | `Vec` | position at the previous tick |
| `entity.serverPosition()` | `Vec` | position the server last sent, `position()` for entities that never lerp (API 6) |
| `entity.interpolating()` | `boolean` | the client is still lerping towards `serverPosition()` (API 6) |
| `entity.renderPosition()` | `Vec` | tick-interpolated position used for drawing |
| `entity.box()` | [`Box`](https://docs.nursultan.fun/scripting/game/math#box) | bounding box in world coordinates |
| `entity.width()` | `float` | hitbox width in blocks |
| `entity.height()` | `float` | hitbox height in blocks |
| `entity.rotation()` | [`Rotation`](https://docs.nursultan.fun/scripting/game/math#rotation) | yaw and pitch in degrees |
| `entity.yaw()` | `float` | yaw in degrees |
| `entity.yaw(value)` | `void` | sets yaw client-side (API 7) |
| `entity.pitch()` | `float` | pitch in degrees, -90..90 |
| `entity.pitch(value)` | `void` | sets pitch client-side (API 7) |
| `entity.velocity()` | `Vec` | velocity in blocks per tick |
| `entity.velocity(value)` | `void` | sets velocity client-side; a server update overwrites it (API 7) |
| `entity.distanceTo(other)` | `double` | distance between positions in blocks (throws `ScriptStateException` when `other` is not a world entity) |
| `entity.distanceTo(point)` | `double` | distance from the position to a point in blocks |

## State

| Method | Type | Description |
|---|---|---|
| `entity.onGround()` | `boolean` | standing on ground |
| `entity.sneaking()` | `boolean` | sneak flag |
| `entity.sprinting()` | `boolean` | sprint flag |
| `entity.swimming()` | `boolean` | swimming flag |
| `entity.crawling()` | `boolean` | crawling in a 1-block gap |
| `entity.wet()` | `boolean` | touching water or standing in rain |
| `entity.submerged()` | `boolean` | eyes are under water |
| `entity.inWater()` | `boolean` | touching water |
| `entity.inLava()` | `boolean` | standing in lava |
| `entity.onFire()` | `boolean` | entity is burning |
| `entity.fireImmune()` | `boolean` | entity type is immune to fire |
| `entity.frozen()` | `boolean` | powder-snow freeze is fully applied |
| `entity.frozenTicks()` | `int` | powder-snow freeze progress in ticks |
| `entity.glowing()` | `boolean` | glowing flag |
| `entity.invisible()` | `boolean` | vanilla invisibility flag |
| `entity.invisible(value)` | `void` | sets it client-side; server metadata overwrites it |
| `entity.alive()` | `boolean` | alive and not removed from the world |
| `entity.pose()` | `Pose` | current entity pose |
| `entity.airTicks()` | `int` | remaining air in ticks |
| `entity.maxAirTicks()` | `int` | maximum air in ticks |
| `entity.fallDistanceBlocks()` | `double` | accumulated fall distance in blocks |
| `entity.fallDistanceBlocks(value)` | `void` | sets the accumulated fall distance in blocks (API 7) |
| `entity.silent()` | `boolean` | silent flag |
| `entity.noGravity()` | `boolean` | no-gravity flag |
| `entity.noClip()` | `boolean` | entity moves through blocks (API 7) |
| `entity.noClip(value)` | `void` | sets the no-clip flag client-side (API 7) |
| `entity.age()` | `int` | ticks the entity has existed on the client |

`invisible(true)` hides the model and not the nametag, and display entities ignore the flag entirely.

## Teams and relations

| Method | Type | Description |
|---|---|---|
| `entity.team()` | `String?` | scoreboard team name, null when in no team |
| `entity.teamColor()` | `int` | opaque ARGB team colour, -1 without team or colour |
| `entity.isFriend()` | `boolean` | name is in the client friend list |
| `entity.isParty()` | `boolean` | name is a party member |
| `entity.isAlly()` | `boolean` | friend, party or NoFriendDamage teammate; always false while NoFriendDamage is off |
| `entity.isBot()` | `boolean` | client bot heuristics; false for self and on FT servers |

## Riding

| Method | Type | Description |
|---|---|---|
| `entity.vehicle()` | `Entity?` | entity being ridden, null when on foot |
| `entity.passengers()` | `List<Entity>` | entities riding this one, empty when none |

## Hiding one

| Method | Type | Description |
|---|---|---|
| `entity.hidden()` | `boolean` | client render-suppression flag; false for untracked entities |
| `entity.hidden(value)` | `void` | sets the flag; no-op for untracked entities |

Hiding drops the nametag of any entity and a text display in full; the entity keeps ticking and stays readable.
The flag outlives the script being switched off — [`world.unhideEntities()`](https://docs.nursultan.fun/scripting/game/world) clears every one of them.

## Living entities

| Method | Type | Description |
|---|---|---|
| `living.health()` | `float` | current health in half-hearts |
| `living.maxHealth()` | `float` | maximum health in half-hearts |
| `living.absorption()` | `float` | absorption (yellow) hearts |
| `living.armorPoints()` | `int` | armor points, 0..20 |
| `living.bypassedHealth()` | `float` | scoreboard health while BypassHealth is on, else `health()` |
| `living.dead()` | `boolean` | health is at or below zero |
| `living.deathTicks()` | `int` | ticks since death, 0 while alive |
| `living.hurtTicks()` | `int` | remaining hurt-animation ticks |
| `living.bodyYaw()` | `float` | body yaw in degrees |
| `living.headYaw()` | `float` | head yaw in degrees |
| `living.blocking()` | `boolean` | blocking with a shield |
| `living.usingItem()` | `boolean` | currently using an item |
| `living.activeItem()` | `Item?` | stack being used, null when none |
| `living.itemUseTicks()` | `int` | ticks the current item has been used for |
| `living.itemUseTicksLeft()` | `int` | ticks left before the use completes |
| `living.swinging()` | `boolean` | hand-swing animation is running (API 2) |
| `living.swingTicks()` | `int` | current hand-swing animation tick (API 2) |
| `living.baby()` | `boolean` | entity is a baby |
| `living.scale()` | `float` | scale multiplier, 1.0 by default |
| `living.climbing()` | `boolean` | on a climbable block |
| `living.gliding()` | `boolean` | elytra-gliding |
| `living.sleeping()` | `boolean` | entity is sleeping |
| `living.usingRiptide()` | `boolean` | in a riptide spin attack |
| `living.movementSpeed()` | `float` | movement-speed attribute in blocks per tick |
| `living.isNaked()` | `boolean` | no armor in any of the four humanoid slots |

`bypassedHealth()` equals `health()` in singleplayer and whenever the BypassHealth module is off.

## Equipment

| Method | Type | Description |
|---|---|---|
| `living.mainHandItem()` | [`Item`](https://docs.nursultan.fun/scripting/game/inventory) | main-hand stack, empty item when nothing is held |
| `living.offHandItem()` | `Item` | off-hand stack, empty item when nothing is held |
| `living.armorItem(slot)` | `Item` | stack in that [`ArmorSlot`](https://docs.nursultan.fun/scripting/game/inventory), empty item when none |
| `living.armorItems()` | `List<Item>` | non-empty humanoid armor stacks only |

## Effects

| Method | Type | Description |
|---|---|---|
| `living.hasEffect(effectId)` | `boolean` | an effect with that exact namespaced id is active |
| `living.effects()` | `List<Effect>` | snapshots of every active status effect |
| `living.effect(effectId)` | `Effect?` | one active effect by exact namespaced id, null when absent |
| `living.visibleEffects()` | `List<String>` | effect ids read off the potion particles, no amplifier or duration (API 3) |

Effect ids are compared exactly: `hasEffect("minecraft:speed")` matches, `hasEffect("speed")` does not.

### Effect

| Method | Type | Description |
|---|---|---|
| `effect.id()` | `String` | namespaced effect id, e.g. `minecraft:speed` |
| `effect.name()` | `String` | client-localized effect name |
| `effect.amplifier()` | `int` | amplifier, 0 = level I |
| `effect.durationTicks()` | `int` | remaining duration in ticks |
| `effect.ambient()` | `boolean` | effect came from a beacon or conduit |
| `effect.infinite()` | `boolean` | effect has infinite duration |
| `effect.beneficial()` | `boolean` | effect type is classed as beneficial |

## Attributes

| Method | Type | Description |
|---|---|---|
| `living.attributes()` | `Map<String, Attribute>` | unmodifiable map of every attribute present, keyed by namespaced id |
| `living.attribute(attributeId)` | `Attribute?` | one attribute, `minecraft:` added when unqualified; null when absent |

`attributes()` walks the whole attribute registry on each call.

### Attribute

| Method | Type | Description |
|---|---|---|
| `attribute.id()` | `String` | namespaced attribute id, e.g. `minecraft:movement_speed` |
| `attribute.base()` | `double` | value before modifiers |
| `attribute.value()` | `double` | value after every modifier |

## Players

| Method | Type | Description |
|---|---|---|
| `player.pingMs()` | `int` | player-list latency in milliseconds, 0 without an entry |
| `player.gameMode()` | `GameMode` | player-list game mode, `SURVIVAL` without an entry |
| `player.skinTexture()` | [`Texture?`](https://docs.nursultan.fun/scripting/ui/render-2d) | body skin texture; null for non-client players and while StreamerMode hides skins |

### GameMode

| Constant | Description |
|---|---|
| `SURVIVAL` | survival mode; also the fallback when the mode is unknown |
| `CREATIVE` | creative mode |
| `ADVENTURE` | adventure mode |
| `SPECTATOR` | spectator mode |

## Text displays

| Method | Type | Description |
|---|---|---|
| `display.text()` | `String` | plain text of the display |
| `display.styledText()` | `Text` | styled text of the display |

A text display has no custom name: `hasCustomName()` is false and `customName()` is null on it.

### ItemEntity

| Method | Type | Description |
|---|---|---|
| `itemEntity.stack()` | [`Item`](https://docs.nursultan.fun/scripting/game/inventory) | the stack lying on the ground, wrapped on each call (API 4) |

Reached with `entity.asItemEntity()`; every `Entity` member works on it too.

## Poses

| Constant | Description |
|---|---|
| `STANDING` | default upright pose |
| `GLIDING` | elytra flight |
| `SLEEPING` | lying in a bed |
| `SWIMMING` | swimming or crawling posture |
| `SPIN_ATTACK` | trident riptide spin |
| `CROUCHING` | sneaking |
| `LONG_JUMPING` | goat long jump |
| `DYING` | death animation |
| `CROAKING` | frog croak |
| `USING_TONGUE` | frog tongue |
| `SITTING` | sitting, camel and the like |
| `ROARING` | warden roar |
| `SNIFFING` | warden or sniffer sniff |
| `EMERGING` | warden emerging |
| `DIGGING` | warden digging |
| `SLIDING` | breeze slide |
| `SHOOTING` | breeze shooting |
| `INHALING` | breeze inhaling |

## Filters

| Method | Type | Description |
|---|---|---|
| `filters.alive()` | `Predicate<Entity>` | entity is alive |
| `filters.self()` | `Predicate<Entity>` | entity is the local player |
| `filters.player()` | `Predicate<Entity>` | entity type is `minecraft:player` |
| `filters.mob()` | `Predicate<Entity>` | entity is a mob |
| `filters.monster()` | `Predicate<Entity>` | entity is hostile |
| `filters.animal()` | `Predicate<Entity>` | mob that is not hostile |
| `filters.villager()` | `Predicate<Entity>` | entity type is `minecraft:villager` |
| `filters.item()` | `Predicate<Entity>` | entity type is `minecraft:item` |
| `filters.friend()` | `Predicate<Entity>` | entity is flagged as a friend |
| `filters.party()` | `Predicate<Entity>` | entity is flagged as a party member |
| `filters.ally()` | `Predicate<Entity>` | friend, party or NoFriendDamage teammate; always false while NoFriendDamage is off |
| `filters.bot()` | `Predicate<Entity>` | entity is flagged as a bot |
| `filters.attackable()` | `Predicate<Entity>` | alive, not the local player and not an ally |

Every filter returns false for an entity object the script did not get from the world.

---

# Inventory and items

`inventory` is `game.inventory()` — the 36 main slots plus the four armor slots and the off-hand. Reads are free; every mutation is queued onto the client's move queue and needs the client thread.

```kotlin
on<PrePlayerTickEvent> {
    val slot = inventory.find("golden_apple")
    if (!slot.found() || inventory.busy()) return@on
    val stack = inventory.item(slot)
    chat.print("${stack.count()} x ${stack.name()}")
    inventory.shiftClick(slot)
}
```

## Addressing a slot

| Method | Type | Description |
|---|---|---|
| `Slot.hotbar(index)` | `Slot` | hotbar slot by index (throws ScriptException outside 0..8) |
| `Slot.inventory(index)` | `Slot` | main-inventory slot, below 9 yields kind HOTBAR (throws ScriptException outside 0..35) |
| `Slot.armor(slot)` | `Slot` | armor slot from an `ArmorSlot` (throws ScriptException on null) |
| `Slot.offhand()` | `Slot` | the off-hand slot |
| `Slot.NONE` | `Slot` | not-found constant, kind NONE and index -1 |
| `Slot.HOTBAR_SIZE` | `int` | constant 9 |
| `Slot.MAIN_SIZE` | `int` | constant 36 |
| `slot.kind()` | `Slot.Kind` | which part of the inventory the slot addresses |
| `slot.index()` | `int` | index inside the kind, -1 for NONE, ArmorSlot ordinal for ARMOR |
| `slot.found()` | `boolean` | kind is not NONE |
| `slot.inHotbar()` | `boolean` | kind is HOTBAR |
| `slot.isArmor()` | `boolean` | kind is ARMOR |
| `slot.isOffhand()` | `boolean` | kind is OFFHAND |
| `slot.hotbarIndex()` | `int` | hotbar index 0..8, -1 when not a hotbar slot |
| `slot.armorSlot()` | `ArmorSlot?` | the armor slot, null when kind is not ARMOR |
| `slot.toString()` | `String` | `none`, `hotbar N`, `inventory N`, `armor HELMET` or `offhand` |

### Slot.Kind

| Constant | Description |
|---|---|
| `NONE` | not found or absent slot |
| `HOTBAR` | hotbar, index 0..8 |
| `INVENTORY` | main inventory, index 9..35 |
| `ARMOR` | armor slot, index is the `ArmorSlot` ordinal |
| `OFFHAND` | off-hand slot, index 0 |

### ArmorSlot

| Constant | Description |
|---|---|
| `HELMET` | head slot, ordinal 0 |
| `CHESTPLATE` | chest slot, ordinal 1 |
| `LEGGINGS` | legs slot, ordinal 2 |
| `BOOTS` | feet slot, ordinal 3 |

## Reading

| Method | Type | Description |
|---|---|---|
| `inventory.held()` | `Item` | main-hand stack, empty item when nothing held |
| `inventory.offhand()` | `Item` | off-hand stack |
| `inventory.item(slot)` | `Item` | stack in that slot (throws ScriptStateException on a not-found slot) |
| `inventory.armor(slot)` | `Item` | equipped stack in that armor slot (throws ScriptException on null) |
| `inventory.items()` | `List<Item>` | immutable list of the 36 main stacks in index order |
| `inventory.selected()` | `Slot` | currently selected hotbar slot |
| `inventory.count(itemId)` | `int` | total count of that item across the 36 main slots |
| `inventory.full()` | `boolean` | no empty stack among the 36 main slots |
| `inventory.empty()` | `boolean` | all 36 main slots are empty |
| `inventory.wearing(itemId)` | `boolean` | that item is equipped in one of the four armor slots |

Item ids default to the `minecraft:` namespace, so `"mace"` and `"minecraft:mace"` are the same id.
No read returns null: an absent stack comes back as an item whose `empty()` is true.

## Searching

| Method | Type | Description |
|---|---|---|
| `inventory.find(itemId)` | `Slot` | first main-inventory slot holding that item, `Slot.NONE` when absent |
| `inventory.find(filter)` | `Slot` | first main-inventory slot passing the filter (throws ScriptException on a null filter) |
| `inventory.findByTag(tagId)` | `Slot` | first main-inventory slot in that item tag, leading `#` stripped |
| `inventory.findInHotbar(itemId)` | `Slot` | first hotbar slot 0..8 holding that item |
| `inventory.findInHotbar(filter)` | `Slot` | first hotbar slot 0..8 passing the filter |
| `inventory.findUsable(filter)` | `Slot` | first matching slot that is non-empty and not on cooldown |
| `inventory.findAll(filter)` | `List<Slot>` | every matching main-inventory slot in index order |

## Moving things

| Method | Type | Description |
|---|---|---|
| `inventory.click(slot, rightButton)` | `void` | queues a PICKUP click, button 1 when rightButton (main thread only) |
| `inventory.shiftClick(slot)` | `void` | queues a QUICK_MOVE click (main thread only) |
| `inventory.swap(slot, hotbarSlot)` | `void` | queues a SWAP into that hotbar slot (main thread only) (throws ScriptException when hotbarSlot is not a hotbar slot) |
| `inventory.drop(slot, wholeStack)` | `void` | queues a THROW, button 1 for the whole stack (main thread only) |
| `inventory.dropHeld(wholeStack)` | `void` | drops the selected hotbar stack directly (main thread only) |
| `inventory.batch(actions)` | `void` | enqueues the collected actions as one move sequence (main thread only) |
| `inventory.busy()` | `boolean` | the client inventory-move queue is non-empty |

### Inventory.Batch

| Method | Type | Description |
|---|---|---|
| `batch.click(slot, rightButton)` | `Batch` | appends a PICKUP click |
| `batch.shiftClick(slot)` | `Batch` | appends a QUICK_MOVE click |
| `batch.swap(slot, hotbarSlot)` | `Batch` | appends a SWAP (throws ScriptException when hotbarSlot is not a hotbar slot) |
| `batch.drop(slot, wholeStack)` | `Batch` | appends a THROW, button 1 for the whole stack |
| `batch.delay(ticks)` | `Batch` | appends a pause in game ticks (throws ScriptException when ticks is 0 or less) |
| `batch.onFinish(action)` | `Batch` | runs the action when the queue closes (API 2) (throws ScriptException when action is null) |

Every mutation needs an open screen handler, and with a non-player screen open the `ARMOR` and `OFFHAND` slots throw `ScriptStateException`; a batch does not block, its queue drains over the following ticks, and one with no click or delay is dropped together with its `onFinish`.
Slots of an open chest or server menu are addressed by [Containers](https://docs.nursultan.fun/scripting/game/containers); switching the held hotbar slot is [Slots and armor](https://docs.nursultan.fun/scripting/actions/slots).

## The stack

| Method | Type | Description |
|---|---|---|
| `item.empty()` | `boolean` | the stack is empty |
| `item.id()` | `String` | namespaced item id, `minecraft:air` for an empty stack |
| `item.name()` | `String` | plain display name |
| `item.count()` | `int` | stack size |
| `item.maxCount()` | `int` | maximum stack size |
| `item.damage()` | `int` | current damage value |
| `item.maxDamage()` | `int` | maximum durability, 0 when not damageable |
| `item.damageable()` | `boolean` | stack can take durability damage |
| `item.stackable()` | `boolean` | stack can hold more than one item |
| `item.unbreakable()` | `boolean` | has the UNBREAKABLE component |
| `item.enchanted()` | `boolean` | has at least one enchantment |
| `item.rarity()` | `Rarity` | vanilla stack rarity |
| `item.isA(itemId)` | `boolean` | id matches, false for an empty stack |
| `item.hasTag(tagId)` | `boolean` | item is in that tag, leading `#` stripped |

## What it can do

| Method | Type | Description |
|---|---|---|
| `item.placeable()` | `boolean` | BlockItem whose default state has a collision shape |
| `item.buildable()` | `boolean` | BlockItem: full cube, no block entity, default friction/multipliers, not falling or magma (API 2) |
| `item.food()` | `boolean` | has the FOOD component |
| `item.nutrition()` | `int` | food nutrition points, 0 when not food |
| `item.saturation()` | `float` | food saturation value, 0 when not food |
| `item.useAction()` | `String` | lowercase use action: `none`, `eat`, `bow`, `block` |
| `item.disablesBlocking()` | `boolean` | WEAPON component disables shield blocking |
| `item.enchantments()` | `Map<String, Integer>` | namespaced enchantment id to level, insertion-ordered |
| `item.enchantmentLevel(id)` | `int` | level for that id, 0 when absent, `minecraft:` added when unqualified (throws `ScriptException` when the id is blank) |
| `item.attributeModifiers()` | `List<AttributeModifier>` | ATTRIBUTE_MODIFIERS entries, empty when absent |
| `item.containerItems()` | `List<Item>` | CONTAINER contents, else BUNDLE_CONTENTS, else empty |

### AttributeModifier

| Method | Type | Description |
|---|---|---|
| `modifier.attribute()` | `String` | namespaced attribute id the modifier applies to |
| `modifier.id()` | `String` | modifier identifier |
| `modifier.value()` | `double` | modifier amount |
| `modifier.operation()` | `String` | `add_value`, `add_multiplied_base` or `add_multiplied_total` |
| `modifier.slot()` | `String` | equipment-slot group: `any`, `mainhand`, `head` |

## Cooldowns

| Method | Type | Description |
|---|---|---|
| `item.onCooldown()` | `boolean` | this stack's cooldown group is cooling down, false out of world |
| `item.cooldownProgress()` | `float` | remaining cooldown fraction at tickDelta 0, counts down 1..0 (API 2) |
| `item.cooldownProgress(tickDelta)` | `float` | the same fraction interpolated by tickDelta, 1..0 (API 2) |
| `item.setCooldown(ticks)` | `void` | client-side cooldown of that many ticks, 0 or less removes it (API 2) (main thread only) (throws ScriptStateException when out of world) |
| `item.removeCooldown()` | `void` | clears this group's client-side cooldown (API 2) (main thread only) (throws ScriptStateException when out of world) |

A cooldown belongs to the item's cooldown group, not to the stack, so every stack of that item reports the same value.
`setCooldown` and `removeCooldown` write only the client's copy; the server keeps its own, and the next cooldown packet for that group overwrites yours.

## Names, lore, components

| Method | Type | Description |
|---|---|---|
| `item.displayName()` | `Text` | styled display name |
| `item.customName()` | `String?` | plain CUSTOM_NAME text, null when absent |
| `item.lore()` | `List<Text>` | styled LORE lines, empty when absent |
| `item.tooltip(advanced)` | `List<Text>` | vanilla tooltip lines, F3+H version when advanced is true |
| `item.tags()` | `List<String>` | namespaced item tag ids on this item |
| `item.hasComponent(id)` | `boolean` | data component present, false for an unknown id |
| `item.component(id)` | `String?` | `toString()` of the component value, null when absent |
| `item.nbt()` | `String` | CUSTOM_DATA compound as text, empty string when absent |
| `item.customData(key)` | `String?` | string value of that key in CUSTOM_DATA, null when missing |

`Text` values are [styled text](https://docs.nursultan.fun/scripting/ui/text).

## Rarity

| Constant | Description |
|---|---|
| `COMMON` | white name |
| `UNCOMMON` | yellow name |
| `RARE` | aqua name |
| `EPIC` | light purple name |

## Hands

### Hand

| Constant | Description |
|---|---|
| `MAIN_HAND` | main hand |
| `OFF_HAND` | off hand |

### Arm

| Constant | Description |
|---|---|
| `LEFT` | left arm |
| `RIGHT` | right arm |

`Arm` is `nursultan.item.Arm`, the main-arm side reported by `RenderItemEvent.arm()` and the client-settings packets.

---

# Containers

`container` is `game.container()` — the open screen handler as one flat slot list. Indices `0..storage()-1` are the container's own slots, then 27 inventory slots, then the 9 hotbar slots; every member throws `ScriptStateException` when there is no world or no screen handler.

```kotlin
on<ClientTickEvent> {
    if (!container.open() || container.busy()) return@on
    val slot = container.find("minecraft:diamond", 0, container.storage())
    if (!slot.found()) return@on
    container.batch {
        it.shiftClick(slot)      // one step per tick
        it.delay(2)
    }
}
```

## Slot numbering

| Method | Type | Description |
|---|---|---|
| `container.syncId()` | `int` | sync id of the open screen handler |
| `container.size()` | `int` | total slot count of the open handler |
| `container.storage()` | `int` | `size() - 36`, floored at 0 — the container's own slots |
| `container.open()` | `boolean` | true when the sync id is non-zero, i.e. not the plain player inventory |
| `container.playerSlot(slot)` | `Slot` | handler index as an inventory slot; `Slot.NONE` outside the player section |

`playerSlot` maps the first 27 slots of the player section to `Slot.inventory(9..35)` and the last 9 to `Slot.hotbar(0..8)`.

### ContainerSlot

| Method | Type | Description |
|---|---|---|
| `ContainerSlot.NONE` | `ContainerSlot` | constant with index -1, meaning not found |
| `ContainerSlot.of(index)` | `ContainerSlot` | wraps a raw handler index (throws `ScriptException` when index < 0) |
| `slot.index()` | `int` | raw handler slot index, -1 for `NONE` |
| `slot.found()` | `boolean` | index is 0 or more |
| `slot.equals(other)` | `boolean` | true when the other `ContainerSlot` has the same index |
| `slot.hashCode()` | `int` | the index itself |
| `slot.toString()` | `String` | `none` or `container <index>` |

`Slot` and `Item` are documented on [Inventory and items](https://docs.nursultan.fun/scripting/game/inventory).

## Reading

| Method | Type | Description |
|---|---|---|
| `container.item(slot)` | `Item` | stack at that `ContainerSlot`; empty item for null or out of range |
| `container.item(index)` | `Item` | stack at that raw index; empty item when out of range |
| `container.items()` | `List<Item>` | every slot in handler order |
| `container.find(itemId)` | `ContainerSlot` | first slot holding that item id; `NONE` when absent |
| `container.find(itemId, from, to)` | `ContainerSlot` | same, restricted to an index range |
| `container.find(filter)` | `ContainerSlot` | first slot passing the filter; `NONE` for a null filter |
| `container.find(from, to, filter)` | `ContainerSlot` | first passing slot inside the range |
| `container.findAfter(from, filter)` | `ContainerSlot` | first passing slot from that index to the end |
| `container.findAll(filter)` | `List<ContainerSlot>` | every passing slot; empty for a null filter |
| `container.count(itemId)` | `int` | summed stack counts of that item over the handler |
| `container.count(itemId, from, to)` | `int` | same, over an index range |
| `container.empty()` | `ContainerSlot` | first empty slot, or `NONE` |
| `container.empty(from, to)` | `ContainerSlot` | first empty slot inside a range |

Index ranges are half-open and clamped to `0..size()`.
Item ids default to the `minecraft:` namespace; a blank id throws `ScriptException`.

## Clicking

| Method | Type | Description |
|---|---|---|
| `container.click(slot)` | `void` | left click, button 0, `PICKUP` (main thread only) (throws `ScriptException` when the slot is `NONE` or beyond the handler) |
| `container.click(slot, button)` | `void` | click with an explicit mouse button, `PICKUP` (main thread only) |
| `container.click(slot, button, action)` | `void` | click with an explicit slot action (main thread only) |
| `container.shiftClick(slot)` | `void` | click with button 0 and `QUICK_MOVE` (main thread only) |
| `container.clickButton(button)` | `void` | screen-handler button: stonecutter, loom, villager trade (main thread only) |
| `container.busy()` | `boolean` | true while the client's inventory move queue still has actions |

`busy()` also covers the client's own inventory moves, not only a script's.

### SlotAction

| Constant | Description |
|---|---|
| `PICKUP` | normal left/right click; also the fallback when the action is null |
| `QUICK_MOVE` | shift-click move |
| `SWAP` | hotbar swap, button is the hotbar index 0..8 |
| `CLONE` | middle-click clone (throws `ScriptException` outside creative) |
| `THROW` | drop; button 1 drops the whole stack, 0 drops one item |
| `QUICK_CRAFT` | drag-craft / drag-distribute |
| `PICKUP_ALL` | double-click collect-all |

## Sequences

| Method | Type | Description |
|---|---|---|
| `container.batch(actions)` | `void` | queues the steps onto the inventory move queue, drained over following ticks (main thread only) (throws `ScriptException` when actions is null) |

### Container.Batch

| Method | Type | Description |
|---|---|---|
| `it.click(slot)` | `Batch` | queues button 0 / `PICKUP` |
| `it.click(slot, button)` | `Batch` | queues a click with that mouse button / `PICKUP` |
| `it.click(slot, button, action)` | `Batch` | queues a click with an explicit slot action |
| `it.shiftClick(slot)` | `Batch` | queues button 0 / `QUICK_MOVE` |
| `it.swap(slot, hotbarIndex)` | `Batch` | queues `SWAP` onto a hotbar slot (throws `ScriptException` when hotbarIndex is outside 0..8) |
| `it.drop(slot, wholeStack)` | `Batch` | queues `THROW`; button 1 for the whole stack, 0 for one item |
| `it.delay(ticks)` | `Batch` | queues a wait in game ticks (throws `ScriptException` when ticks <= 0) |
| `it.onFinish(action)` | `Batch` | runs on the queue's close hook; the vanilla processor runs it immediately (API 2) (throws `ScriptException` when action is null) |

A batch that queued no click or delay is discarded, and its `onFinish` callbacks never run.

## Recipes

| Method | Type | Description |
|---|---|---|
| `recipes.all()` | `List<RecipeEntry>` | every recipe-book entry in book order (API 2) (main thread only) |
| `recipes.find(resultItemId)` | `List<RecipeEntry>` | entries whose result is that item id (API 2) (main thread only) |
| `recipes.craft(recipeId)` | `void` | clicks the recipe in the open crafting screen, craftAll false (API 2) (main thread only) |
| `recipes.craft(recipeId, craftAll)` | `void` | server fills the open crafting grid; craftAll makes a full stack (API 2) (main thread only) |

## A recipe entry

| Method | Type | Description |
|---|---|---|
| `entry.id()` | `int` | network recipe id, valid only for the current connection (API 2) |
| `entry.resultId()` | `String` | registry id of the displayed result item (API 2) |
| `entry.resultCount()` | `int` | stack size of the displayed result (API 2) |
| `entry.category()` | `String` | recipe-book category registry id; `""` when unknown (API 2) |
| `entry.craftable()` | `boolean` | the inventory currently holds the ingredients (API 2) |
| `entry.kind()` | `RecipeKind` | which display shape `ingredients()` follows (API 2) |
| `entry.width()` | `int` | grid width; 0 for non-`SHAPED` kinds (API 2) |
| `entry.height()` | `int` | grid height; 0 for non-`SHAPED` kinds (API 2) |
| `entry.station()` | `String` | registry id of the crafting station item; `""` when none was sent (API 2) |
| `entry.ingredients()` | `List<List<Item>>` | per slot, the accepted items; empty inner list for an empty cell (API 2) |

### RecipeKind

| Constant | Description |
|---|---|
| `SHAPED` | crafting grid row by row, `width() * height()` cells, empty ones included (API 2) |
| `SHAPELESS` | unordered crafting ingredients, width and height 0 (API 2) |
| `FURNACE` | one ingredient slot, the smelting input (API 2) |
| `STONECUTTER` | one ingredient slot, the cutting input (API 2) |
| `SMITHING` | three ingredient slots: template, base, addition (API 2) |
| `OTHER` | unrecognised display; `ingredients()` is empty (API 2) |

---

# Rays and the crosshair

`raycast` is `game.raycast()`. Every method needs the client thread, a player and a world; distances are in blocks measured from the ray origin.

```kotlin
on<ClientTickEvent> {
    val hit = raycast.crosshair(4.5)
    when {
        hit.isBlock() -> chat.print("block " + (hit as Hit.OnBlock).side())
        hit.isEntity() -> chat.print("entity " + (hit as Hit.OnEntity).entity().name())
        hit.isMiss() -> chat.print("miss")
    }
}
```

## Casting

| Method | Type | Description |
|---|---|---|
| `raycast.crosshair(maxDistanceBlocks)` | `Hit` | crosshair ray including blocks and every hittable entity (throws `ScriptException` when `maxDistanceBlocks <= 0`) |
| `raycast.crosshair(maxDistanceBlocks, includeBlocks, entityFilter)` | `Hit` | same with a block toggle and an entity filter; null filter keeps all (throws `ScriptException` when `maxDistanceBlocks <= 0`) |
| `raycast.entityAtCrosshair(maxDistanceBlocks)` | `Entity?` | entity under the crosshair, blocks occlude |
| `raycast.entityAtCrosshair(maxDistanceBlocks, filter)` | `Entity?` | same with an entity filter |
| `raycast.from(rotation, maxDistanceBlocks, includeBlocks, entityFilter)` | `Hit` | same ray from the eyes along an arbitrary rotation (throws `ScriptException` when `rotation` is null or `maxDistanceBlocks <= 0`) |
| `raycast.blocks(from, to, shape, fluids)` | `Hit` | block-only ray between two points; null shape is `COLLIDER`, null fluids `NONE` |
| `raycast.canSee(from, to)` | `boolean` | true when no `COLLIDER` block interrupts the segment, fluids ignored |
| `raycast.hitOn(entity, from, to)` | `Vec?` | impact point on the hitbox expanded by its targeting margin, `from` when the segment starts inside |

Spectators and entities that cannot be hit are never returned, filter or not.
Off the client thread every method throws [`ScriptThreadException`](https://docs.nursultan.fun/scripting/extras/limits#exceptions); with no player or world, `ScriptStateException`. `Vec` and `Rotation` are on [Vectors, boxes, angles](https://docs.nursultan.fun/scripting/game/math).

## The hit

### Hit

| Method | Type | Description |
|---|---|---|
| `hit.position()` | `Vec` | impact point in world coordinates |
| `hit.distance()` | `double` | blocks from the ray origin to `position()` |
| `hit.isBlock()` | `boolean` | result is `Hit.OnBlock` |
| `hit.isEntity()` | `boolean` | result is `Hit.OnEntity` |
| `hit.isMiss()` | `boolean` | result is `Hit.None` |

On a `blocks(...)` miss `position()` is `to`; when a crosshair trace returns nothing it is the ray origin and `distance()` is 0.

### Hit.OnBlock, Hit.OnEntity

| Method | Type | Description |
|---|---|---|
| `Hit.OnBlock.blockX()` | `int` | x coordinate of the hit block |
| `Hit.OnBlock.blockY()` | `int` | y coordinate of the hit block |
| `Hit.OnBlock.blockZ()` | `int` | z coordinate of the hit block |
| `Hit.OnBlock.side()` | `Side` | face of the block that was hit |
| `Hit.OnEntity.entity()` | `Entity` | the entity the ray hit |

`Hit` is sealed over `OnBlock`, `OnEntity` and `None`; `Hit.None` adds no members of its own.

## Which shape

### RaycastShape

| Constant | Description |
|---|---|
| `COLLIDER` | collision shape |
| `OUTLINE` | outline shape, the one used for highlighting |
| `VISUAL` | visual shape |

### FluidHandling

| Constant | Description |
|---|---|
| `NONE` | fluids never stop the ray |
| `SOURCE_ONLY` | only source fluid blocks stop the ray |
| `ANY` | any fluid, flowing included, stops the ray |

## Sides

### Side

| Constant | Description |
|---|---|
| `DOWN` | -Y face |
| `UP` | +Y face |
| `NORTH` | -Z face |
| `SOUTH` | +Z face |
| `WEST` | -X face |
| `EAST` | +X face |

### Side methods

| Method | Type | Description |
|---|---|---|
| `side.opposite()` | `Side` | face on the other end of the same axis |

`Side` is the same value [`interaction.useBlock` / `placeBlock` / `startBreaking`](https://docs.nursultan.fun/scripting/actions/interaction) take.

---

# Vectors, boxes, angles

`Vec`, `Box` and `Rotation` are immutable value types used everywhere in the API: positions and velocities in blocks, bounding boxes in world coordinates, yaw and pitch in degrees. They are records — every operation returns a new instance, and `equals`/`hashCode` compare components.

```kotlin
on<ClientTickEvent> {
    val eyes = player.eyePosition()
    val ahead = player.rotation().direction().multiply(3.0)   // 3 blocks forward
    val area = Box.around(eyes, 0.5).offset(ahead)
    chat.print("in front: " + world.entitiesIn(area).size)
}
```

## Vec

| Method | Type | Description |
|---|---|---|
| `Vec(x, y, z)` | `Vec` | canonical constructor, components in blocks, no normalization |
| `Vec.of(x, y, z)` | `Vec` | static factory, identical to the constructor |
| `Vec.ZERO` | `Vec` | constant (0, 0, 0) |
| `x()` | `double` | x component in blocks |
| `y()` | `double` | y component in blocks |
| `z()` | `double` | z component in blocks |
| `add(other)` | `Vec` | component-wise sum |
| `add(x, y, z)` | `Vec` | component-wise sum with literals |
| `subtract(other)` | `Vec` | component-wise difference |
| `multiply(factor)` | `Vec` | uniform scale |
| `normalize()` | `Vec` | unit vector, `ZERO` when the length is 0 |
| `dot(other)` | `double` | dot product |
| `length()` | `double` | euclidean length in blocks |
| `squaredLength()` | `double` | squared length, no sqrt |
| `distanceTo(other)` | `double` | euclidean distance in blocks |
| `squaredDistanceTo(other)` | `double` | squared distance, no sqrt |

Positions, eye points and velocities come back as `Vec` — see [Your player](https://docs.nursultan.fun/scripting/game/player) and [Entities and filters](https://docs.nursultan.fun/scripting/game/entities).

## Box

| Method | Type | Description |
|---|---|---|
| `Box(minX, minY, minZ, maxX, maxY, maxZ)` | `Box` | canonical constructor, swaps components so min ≤ max per axis |
| `Box.around(center, radiusBlocks)` | `Box` | cube of half-extent radiusBlocks around a point |
| `minX()` | `double` | lower x bound |
| `minY()` | `double` | lower y bound |
| `minZ()` | `double` | lower z bound |
| `maxX()` | `double` | upper x bound |
| `maxY()` | `double` | upper y bound |
| `maxZ()` | `double` | upper z bound |
| `center()` | `Vec` | midpoint of the box |
| `sizeX()` | `double` | extent along x in blocks |
| `sizeY()` | `double` | extent along y in blocks |
| `sizeZ()` | `double` | extent along z in blocks |
| `offset(offset)` | `Box` | translated copy |
| `offset(x, y, z)` | `Box` | translated copy with literals |
| `expand(blocks)` | `Box` | grown by blocks on all six faces |
| `expand(x, y, z)` | `Box` | grown per axis, on both faces |
| `contract(blocks)` | `Box` | shrunk by blocks on all six faces |
| `contains(point)` | `boolean` | point inside, bounds inclusive |
| `intersects(other)` | `boolean` | volumes overlap, touching faces excluded |
| `raycast(from, to)` | `Vec?` | entry point on the segment, null on a miss, `from` when it starts inside |

`entity.box()` and `block.box()` return one; `world.entitiesIn`, `collisionsIn` and `isFree` take one — see [World and blocks](https://docs.nursultan.fun/scripting/game/world).

## Rotation

| Method | Type | Description |
|---|---|---|
| `Rotation(yawDegrees, pitchDegrees)` | `Rotation` | canonical constructor, clamps pitch to -90..90 degrees |
| `Rotation.of(yawDegrees, pitchDegrees)` | `Rotation` | static factory, identical to the constructor |
| `yawDegrees()` | `float` | yaw in degrees, not wrapped |
| `pitchDegrees()` | `float` | pitch in degrees, -90..90 |
| `yawDeltaTo(other)` | `float` | shortest signed yaw difference, -180..180 degrees |
| `pitchDeltaTo(other)` | `float` | signed pitch difference in degrees |
| `angleTo(other)` | `float` | hypotenuse of the yaw and pitch deltas, in degrees |
| `direction()` | `Vec` | unit look vector for this rotation |

Reading, building and applying rotations is on [Rotations](https://docs.nursultan.fun/scripting/actions/rotations); `raycast.from(rotation, ...)` is on [Rays and the crosshair](https://docs.nursultan.fun/scripting/game/raycast).

---

# Server, scoreboard, tab list

`game.server()` describes the connection you are on and exposes the scoreboard, the tab list and the boss bars. It throws `ScriptStateException` when the client is not connected.

```kotlin
on<ClientTickEvent> {
    val board = game.server().scoreboard()
    if (!board.visible()) return@on
    log.info(board.title())
    board.lines().forEach { log.info(it) }

    val me = game.server().tabList().players().firstOrNull { it.uuid() == player.uuid() }
    log.info("ping ${me?.pingMs() ?: -1} ms")
}
```

## The connection

| Method | Type | Description |
|---|---|---|
| `server.name()` | `String` | server-list entry name, `"singleplayer"` without an entry |
| `server.address()` | `String` | server-list address `host:port`, `"singleplayer"` without an entry |
| `server.type()` | `ServerType` | kind of connection, MULTIPLAYER when unknown |
| `server.protocolVersion()` | `int` | protocol version from the server-list entry, 0 without one |
| `server.pingMs()` | `int` | your own tab-list latency in ms, 0 when unavailable |
| `server.tps()` | `float` | measured server tick rate, rounded to 0.1, 20.0 out of world |
| `server.scoreboard()` | `Scoreboard` | the client scoreboard view |
| `server.tabList()` | `TabList` | the player list view |
| `server.bossBars()` | `List<BossBar>` | boss bars on the HUD, empty without an in-game HUD |

### ServerType

| Constant | Description |
|---|---|
| `SINGLEPLAYER` | integrated server, no server-list entry |
| `LAN` | LAN-discovered server |
| `REALM` | Minecraft Realm |
| `MULTIPLAYER` | any other remote server, also the unknown fallback |

## The sidebar

| Method | Type | Description |
|---|---|---|
| `scoreboard.visible()` | `boolean` | true when a sidebar objective is resolved |
| `scoreboard.title()` | `String` | plain text of the sidebar title, `""` when none |
| `scoreboard.lines()` | `List<String>` | plain text of non-hidden sidebar entries, scoreboard order |
| `scoreboard.contains(vararg needles)` | `boolean` | case-insensitive substring over the title only, never the lines |

The sidebar objective is the team-colour slot matching your own team colour, falling back to the plain `sidebar` slot.

## Objectives and scores

| Method | Type | Description |
|---|---|---|
| `scoreboard.objectives()` | `List<Objective>` | every objective known to the client, empty out of world |
| `scoreboard.objective(name)` | `Objective?` | objective by internal name, null when absent |
| `scoreboard.display(slot)` | `Objective?` | objective in a display slot: `list`, `sidebar`, `below_name`, `sidebar.team.red` |
| `scoreboard.holders()` | `List<String>` | every known score-holder name, empty out of world |

### Objective

| Method | Type | Description |
|---|---|---|
| `objective.name()` | `String` | internal objective name |
| `objective.displayName()` | `Text` | styled display name |
| `objective.criterion()` | `String` | criterion name, e.g. `dummy`, `health`, `playerKillCount` |
| `objective.renderType()` | `String` | `integer` or `hearts` |
| `objective.slots()` | `List<String>` | display slots this objective occupies, empty out of world |
| `objective.score(holder)` | `int` | that holder's score, 0 when there is no entry |
| `objective.entries()` | `List<ScoreEntry>` | every score entry of this objective |

### ScoreEntry

| Method | Type | Description |
|---|---|---|
| `entry.owner()` | `String` | score-holder name |
| `entry.value()` | `int` | the numeric score |
| `entry.hidden()` | `boolean` | true when the server marked the entry as not displayed |
| `entry.name()` | `Text` | styled name as drawn on the sidebar |
| `entry.formattedValue()` | `Text` | styled score value in the entry's own number format |

`Text` is documented on [Styled text](https://docs.nursultan.fun/scripting/ui/text).

## Teams

| Method | Type | Description |
|---|---|---|
| `scoreboard.teams()` | `List<Team>` | every team, empty out of world |
| `scoreboard.team(name)` | `Team?` | team by internal name, null when absent |
| `scoreboard.teamOf(holder)` | `Team?` | team that score-holder name belongs to |

### Team

| Method | Type | Description |
|---|---|---|
| `team.name()` | `String` | internal team name |
| `team.displayName()` | `Text` | styled team display name |
| `team.prefix()` | `Text` | styled prefix prepended to member names |
| `team.suffix()` | `Text` | styled suffix appended to member names |
| `team.color()` | `String` | formatting colour name, e.g. `red`, `aqua` |
| `team.colorRgb()` | `int` | ARGB with 0xFF alpha, -1 when the colour has no RGB |
| `team.members()` | `List<String>` | member score-holder names, immutable copy |
| `team.friendlyFire()` | `boolean` | vanilla friendly-fire flag |
| `team.showFriendlyInvisibles()` | `boolean` | vanilla see-friendly-invisibles flag |
| `team.nametagVisibility()` | `String` | `always`, `never`, `hide_for_other_teams`, `hide_for_own_team` |
| `team.deathMessageVisibility()` | `String` | same four values, applied to death messages |
| `team.collisionRule()` | `String` | `always`, `never`, `push_other_teams`, `push_own_team` |
| `team.decorate(value)` | `Text` | prefix + value + suffix with team formatting, null value is `""` |
| `team.contains(holder)` | `boolean` | membership test, false for null |

The scoreboard is read-only; nothing written into these objects reaches the server.

## Boss bars

| Method | Type | Description |
|---|---|---|
| `bar.uuid()` | `String` | boss bar UUID string |
| `bar.name()` | `Text` | styled boss bar title |
| `bar.percent()` | `float` | fill fraction, 0..1 |
| `bar.color()` | `String` | `pink`, `blue`, `red`, `green`, `yellow`, `purple`, `white` |
| `bar.style()` | `String` | `progress`, `notched_6`, `notched_10`, `notched_12`, `notched_20` |

## The tab list

| Method | Type | Description |
|---|---|---|
| `tab.header()` | `String` | plain text of the tab header, `""` when absent |
| `tab.footer()` | `String` | plain text of the tab footer, `""` when absent |
| `tab.headerContains(vararg needles)` | `boolean` | case-insensitive substring over the trimmed header |
| `tab.footerContains(vararg needles)` | `boolean` | the same test against the footer |
| `tab.players()` | `List<TabEntry>` | whole roster in vanilla tab order, empty when not connected |

### TabEntry

| Method | Type | Description |
|---|---|---|
| `row.name()` | `String` | profile name |
| `row.uuid()` | `String` | profile UUID string |
| `row.displayName()` | `String` | plain text of the tab name, falls back to `name()` |
| `row.pingMs()` | `int` | latency of that entry in milliseconds |
| `row.pingMs(value)` | `void` | client-side latency write, the next server update overwrites it (API 2) |
| `row.gameMode()` | `GameMode` | SURVIVAL, CREATIVE, ADVENTURE, SPECTATOR; SURVIVAL when unset |
| `row.listed()` | `boolean` | true when the entry is one the tab draws |
| `row.skinTexture()` | `Texture?` | skin body texture, null without skins or in StreamerMode |
| `row.player()` | `PlayerEntity?` | loaded entity with that UUID, null when out of world or not loaded |

A row is a profile entry, not an entity: the roster holds every player the server sent, loaded or not.
`Texture` is documented on [2D render](https://docs.nursultan.fun/scripting/ui/render-2d), `PlayerEntity` and `GameMode` on [Entities and filters](https://docs.nursultan.fun/scripting/game/entities).

## Screens

| Method | Type | Description |
|---|---|---|
| `screen.kind()` | `ScreenKind` | classification of the open screen |
| `screen.title()` | `Text` | styled screen title |
| `screen.handled()` | `boolean` | true when the screen has a screen handler |
| `screen.syncId()` | `int` | screen handler sync id, 0 when not handled |
| `screen.size()` | `int` | screen handler slot count, 0 when not handled |

### ScreenKind

| Constant | Description |
|---|---|
| `NONE` | no screen open |
| `INVENTORY` | vanilla survival inventory screen |
| `CREATIVE` | creative inventory screen |
| `CONTAINER` | any other handled screen: chest, villager, shop menu |
| `CHAT` | the chat input screen |
| `OTHER` | any other screen: menus, options |

`game.screen()` returns null when nothing is open; `game.screenOpen()`, `game.screenKind()` and `game.closeScreen()` are on [How a script works](https://docs.nursultan.fun/scripting/start/lifecycle). The closing of a screen fires `ScreenCloseEvent`.

## Translations

`game.translate(key, args)`, `game.hasTranslation(key)` and `game.language()` are on [How a script works](https://docs.nursultan.fun/scripting/start/lifecycle).

---

# Actions

What you can do: hit, place, turn your head, move, read the keyboard, send packets.

---

# Interaction

`interaction` is `game.interaction()` — attacking, using, swinging and breaking; every call except `breakingBlock()` runs on the client thread only. `combat` is `client.combat()` and supplies the aim point on a target's hitbox.

```kotlin
on<ClientTickEvent> {
    val target = raycast.entityAtCrosshair(player.entityReachBlocks()) ?: return@on
    if (player.attackCooldown() < 1f) return@on
    val point = combat.attackPoint(target, AttackPoint.MULTI_POINT, 3.0, false)
    rotations.apply(rotations.lookAt(point))
    interaction.attack(target)
}
```

## Attacking

| Method | Type | Description |
|---|---|---|
| `interaction.attack(target)` | `void` | attacks the entity and swings the main hand (main thread only) (throws `ScriptStateException` when the target is not alive) |
| `interaction.attackCrosshair()` | `void` | vanilla attack on whatever the crosshair hits (main thread only) |
| `interaction.swing(hand)` | `void` | plays the swing animation and sends the swing packet (main thread only) |

`Hand` constants are on [Inventory and items](https://docs.nursultan.fun/scripting/game/inventory#hands).

## Where to hit

| Method | Type | Description |
|---|---|---|
| `combat.attackPoint(target)` | [`Vec`](https://docs.nursultan.fun/scripting/game/math#vec) | `NEAREST` point, max distance = entity reach, through walls |
| `combat.attackPoint(target, mode, maxDistanceBlocks, throughWalls)` | [`Vec`](https://docs.nursultan.fun/scripting/game/math#vec) | aim point on the hitbox; distance and walls read only by `MULTI_POINT` and `TRIANGLE` (throws `ScriptException` when `maxDistanceBlocks` is 0 or less) |
| `combat.markTarget(target, timeoutTicks)` | `void` | marks the client's TargetESP target for that many ticks (main thread only) (throws `ScriptException` when `timeoutTicks` is 0 or less) |
| `combat.target()` | [`Entity`](https://docs.nursultan.fun/scripting/game/entities)`?` | current TargetESP target, null when there is none |

A null `mode` is treated as `NEAREST`; both `attackPoint` overloads throw `ScriptStateException` when the entity has left the world.
`markTarget` throws `ScriptStateException` when the target is not a living entity.

### AttackPoint

| Constant | Description |
|---|---|
| `CENTER` | geometric centre of the bounding box |
| `NEAREST` | closest surface point to the eyes, hitbox shrunk by 0.01 blocks |
| `MULTI_POINT` | best of an 11×11 grid over the visible faces, each candidate ray-checked |
| `TRIANGLE` | one point per visible face, ranked by reach then mouse delta |

## Explosion damage

| Method | Type | Description |
|---|---|---|
| `combat.explosionExposure(target, source)` | `float` | share of the hitbox 0..1 that blocks do not shield (API 3) (main thread only) |
| `combat.explosionExposure(target, source, cover)` | `float` | same, counting boxes that are not in the world yet (API 6) (main thread only) |
| `combat.explosionDamage(target, source, power)` | `float` | damage before armor and effects, 0 outside the radius (API 3) (main thread only) (throws `ScriptException` when `power` is 0 or less) |
| `combat.explosionDamage(target, source, power, cover)` | `float` | same, counting boxes that are not in the world yet (API 6) (main thread only) (throws `ScriptException` when `power` is 0 or less) |
| `combat.explosionDamageTaken(target, source, power)` | `float` | the same after armor, resistance and protection (API 3) (main thread only) (throws `ScriptException` when `power` is 0 or less) |
| `combat.damageAfterArmor(target, damage)` | `float` | damage left after armor points and toughness, weapon armor piercing ignored (API 3) |

## Using an item

| Method | Type | Description |
|---|---|---|
| `interaction.useItem(hand)` | `void` | starts using the item in that hand (main thread only) |
| `interaction.useCrosshair()` | `void` | vanilla use on whatever the crosshair hits (main thread only) |
| `interaction.stopUsingItem()` | `void` | releases the use: fires the bow, throws the trident (main thread only) |
| `interaction.swapHands()` | `void` | sends the offhand swap packet (main thread only) (throws `ScriptStateException` when not connected) |

The game calls `stopUsingItem` itself on the next tick while the use key is not physically held, so a use started from a script ends immediately unless `StopUsingItemEvent` is cancelled.

## Blocks

| Method | Type | Description |
|---|---|---|
| `interaction.useBlock(x, y, z, side, hand)` | `void` | interacts with the centre of that block face (main thread only) |
| `interaction.placeBlock(x, y, z, side, hand)` | `void` | identical to `useBlock`, delegates to it (main thread only) |
| `interaction.useBlock(x, y, z, side, hand, hit)` | `void` | interacts at `hit` in world coordinates, null means the face centre (API 6) (main thread only) |
| `interaction.placeBlock(x, y, z, side, hand, hit)` | `void` | the same with a hit point, delegates to `useBlock` (API 6) (main thread only) |
| `interaction.startBreaking(x, y, z, side)` | `void` | begins breaking that block (main thread only) |
| `interaction.continueBreaking(x, y, z, side)` | `boolean` | advances breaking, true when the block broke (main thread only) |
| `interaction.pendingAck()` | `boolean` | your block use, item use or block break awaits the server's acknowledgement (API 7) (main thread only) |
| `interaction.stopBreaking()` | `void` | cancels the current breaking progress (main thread only) |
| `interaction.breakingBlock()` | `boolean` | true while a block is being broken, false when out of world |

`Side` constants and `opposite()` are on [Rays and the crosshair](https://docs.nursultan.fun/scripting/game/raycast#sides).

---

# Rotations

`rotations` is `client.rotations()`. An applied rotation is written verbatim into the next movement packet, so the server sees it; the client no longer snaps it to the mouse grid for you, and `rotations.quantized(rotation)` is what gives you the angle that will actually be sent.

```kotlin
on<PrePlayerTickEvent> {
    val target = combat.target() ?: return@on
    val aim = rotations.quantized(rotations.lookAt(target))
    rotations.apply(aim, RotationOptions.DEFAULT.priority(RotationPriority.NOW))
}
```

## Reading angles

| Method | Type | Description |
|---|---|---|
| `rotations.player()` | `Rotation` | player yaw/pitch in degrees, spoof included |
| `rotations.camera()` | `Rotation` | angle the rotation handler holds, equals `player()` while idle |
| `rotations.lastSent()` | `Rotation` | yaw/pitch carried by the last movement packet |
| `rotations.angleTo(point)` | `float` | degrees 0..180 from the current look vector to a `Vec` |

Every method throws `ScriptStateException` with no player or world.

## Building one

| Method | Type | Description |
|---|---|---|
| `rotations.lookAt(point)` | `Rotation` | yaw/pitch from the eye position toward a `Vec` |
| `rotations.lookAt(entity)` | `Rotation` | yaw/pitch toward that entity's `NEAREST` attack point |
| `rotations.quantized(rotation)` | `Rotation` | copy snapped to the mouse-sensitivity grid (API 6) |

`quantized` moves both yaw and pitch onto the mouse step, unwraps the yaw into the player's frame and clamps the pitch to -90..90 degrees.
Raycasting the quantised value checks the exact angle you are about to apply.

`Rotation` itself is on [Vectors, boxes, angles](https://docs.nursultan.fun/scripting/game/math#rotation); the attack points are on [Interaction](https://docs.nursultan.fun/scripting/actions/interaction#where-to-hit).

## Applying it

| Method | Type | Description |
|---|---|---|
| `rotations.apply(rotation)` | `void` | queues it with `RotationOptions.DEFAULT` (main thread only) |
| `rotations.apply(rotation, options)` | `void` | queues it, null options mean `DEFAULT` (main thread only) |
| `rotations.locked()` | `boolean` | the handler is locked this tick, `apply` without `lock` does nothing (API 6) |

Applied at the next pre-player-tick exactly as given, or inside the call with `lock`; one call covers one tick.
Does nothing while the handler is locked, except that a `lock` rotation replaces an earlier `lock` one; throws `ScriptStateException` with no player or world.

## Options

| Method | Type | Description |
|---|---|---|
| `RotationOptions.DEFAULT` | `RotationOptions` | static field `(NORMAL, false, BackRotations.SNAP)` |
| `options.priority()` | `RotationPriority` | ordering slot inside the tick's rotation queue |
| `options.priority(value)` | `RotationOptions` | copy with a new priority |
| `options.strongCorrection()` | `boolean` | true skips the WASD remap, movement follows the spoofed yaw |
| `options.strongCorrection(value)` | `RotationOptions` | copy with a new value |
| `options.backRotation()` | `BackRotation` | shape of the return to the camera |
| `options.backRotation(value)` | `RotationOptions` | copy with a new value |
| `options.lock()` | `boolean` | true applies it at once and locks the handler, the attack aura skips that tick (API 7) |
| `options.lock(value)` | `RotationOptions` | copy with a new value (API 7) |
| `options.smoothBackRotation()` | `boolean` | stored flag (deprecated, use `backRotation`) |
| `options.smoothBackRotation(value)` | `RotationOptions` | copy with a new value, true turns a `SNAP` return into `HUMANIZED` (deprecated, use `backRotation`) |
| `options.clientSide()` | `boolean` | stored flag (deprecated) (no effect: the rotation always reaches the server) |
| `options.clientSide(value)` | `RotationOptions` | copy with a new value (deprecated) (no effect: the rotation always reaches the server) |
| `options.normalizeMouseMovement()` | `boolean` | stored flag (deprecated, use `rotations.quantized`) (no effect: the value is never read) |
| `options.normalizeMouseMovement(value)` | `RotationOptions` | copy with a new value (deprecated, use `rotations.quantized`) (no effect: the value is never read) |
| `RotationOptions(priority, clientSide, strongCorrection, smoothBackRotation, normalizeMouseMovement, backRotation, lock)` | `RotationOptions` | canonical constructor (API 7) (throws `NullPointerException` when `priority` or `backRotation` is null) |
| `RotationOptions(priority, clientSide, strongCorrection, smoothBackRotation, normalizeMouseMovement, backRotation)` | `RotationOptions` | the same with `lock` false (throws `NullPointerException` when `priority` or `backRotation` is null) |
| `RotationOptions(priority, strongCorrection, backRotation)` | `RotationOptions` | constructor without the deprecated flags (API 6) |

The record is immutable: every setter returns a copy and `DEFAULT` never changes.
The deprecated members are indexed under [Things that no longer do anything](https://docs.nursultan.fun/scripting/extras/api-versions#things-that-no-longer-do-anything).

## Order inside a tick

### RotationPriority

| Constant | Description |
|---|---|
| `NOW` | weight 200, applied last, overwrites lower priorities |
| `NORMAL` | weight 0, the value in `DEFAULT` |
| `LATER` | weight -200, applied first |

Rotations queued in one tick are applied `LATER` → `NORMAL` → `NOW`, so the highest priority is written last.

## Returning the head

| Method | Type | Description |
|---|---|---|
| `BackRotations.SNAP` | `BackRotation` | 1 tick, returns the head at once, the value in `DEFAULT` (API 6) |
| `BackRotations.INSTANT` | `BackRotation` | 2 ticks, half the delta then the rest (API 6) |
| `BackRotations.HUMANIZED` | `BackRotation` | 20 ticks of recorded human deltas (API 6) |
| `BackRotation.FAST` | `BackRotation` | the return `BackRotations.SNAP` gives (deprecated, use `BackRotations.SNAP`) |
| `BackRotation.SMOOTH` | `BackRotation` | the return `BackRotations.HUMANIZED` gives (deprecated, use `BackRotations.HUMANIZED`) |

Once nothing applies a rotation any more, the handler walks the spoofed head back to the camera with the `BackRotation` of the last applied options.

### Writing your own

| Method | Type | Description |
|---|---|---|
| `BackRotation.step(from, to, tick)` | `Rotation?` | angle for this tick, null when the return is finished (API 6) |
| `BackRotation.maxTicks()` | `int` | ticks the return may take, 20 by default (API 6) |
| `backRotation(maxTicks) { from, to, tick -> }` | `BackRotation` | DSL form of the interface, `maxTicks` defaults to 20 (API 6) |

`from` is where the spoofed head points, `to` is where the real camera points, `tick` counts from 0.
Your steps are applied verbatim, so quantise them yourself; the handler ends the return once `maxTicks` is reached.

---

# Slots and armor

`slots` is `client.slots()` and `armor` is `client.armor()`. `select` returns a handle that remembers the slot selected before it; `armor` compares a candidate piece against what is worn. `Slot` and `ArmorSlot` themselves are documented on [Inventory and items](https://docs.nursultan.fun/scripting/game/inventory).

```kotlin
on<ClientTickEvent> {
    slots.using(Slot.hotbar(2)) {
        interaction.useItem(Hand.MAIN_HAND)
    }

    val best = armor.bestSlotFor(ArmorSlot.HELMET)
    if (best.found()) inventory.shiftClick(best)
}
```

## Selecting a slot

| Method | Type | Description |
|---|---|---|
| `slots.select(hotbarSlot)` | `HeldSlot` | selects the hotbar slot, syncs it, returns a restore handle (main thread only) (throws `ScriptException` when the slot is not a hotbar slot) |
| `slots.selectSilently(hotbarSlot)` | `void` | selects and syncs the slot, records nothing to restore (main thread only) (throws `ScriptException` when the slot is not a hotbar slot) |
| `slots.sync()` | `void` | resends the currently selected hotbar slot to the server (main thread only) |
| `slots.hold(hotbarSlot)` | `HeldSlot` | reuses the live handle when that slot is already selected, selects it otherwise (API 6) (main thread only) (throws `ScriptException` when the slot is not a hotbar slot) |
| `slots.selected()` | `Slot` | hotbar slot selected right now (API 6) (main thread only) |
| `slots.using(slot) { }` | `T` | selects, runs the block, calls `restoreWhenSafe()` in a `finally` (main thread only) |

All of them throw `ScriptStateException` when there is no world and after the script is unloaded. Every live handle of a script is restored silently when the script unloads.
A deferred restore happens on a tick of the client's own, so a handle is not proof of what the hand holds: `hold` and `holding()` compare against the slot that is really selected.

## The handle

| Method | Type | Description |
|---|---|---|
| `originalSlot()` | `int` | hotbar index 0..8 selected when `select` ran |
| `slot()` | `int` | hotbar index 0..8 this handle selected |
| `holding()` | `boolean` | that slot is still the selected one and the handle is not spent (API 6) |
| `restore()` | `void` | switches back now and syncs it |
| `restoreWhenSafe()` | `void` | switches back on a later tick with no attack |
| `keep()` | `void` | drops the pending restore, the slot stays selected |
| `close()` | `void` | same as `restoreWhenSafe()` |

`restore`, `restoreWhenSafe`, `keep` and `close` are mutually exclusive: the first call takes effect and the rest are no-ops. They switch to the client's global last-selected slot, which a manual hotbar change overwrites, so it is not guaranteed to equal `originalSlot()`.

## Armor

| Method | Type | Description |
|---|---|---|
| `armor.bestSlotFor(slot)` | `Slot` | best main-inventory slot 0..35 for that armor slot, `Slot.NONE` when nothing beats the worn piece |
| `armor.isBetterThanEquipped(slot, candidate)` | `boolean` | true when the **equipped** piece wins or ties (`>=`) — inverted relative to the name (throws `ScriptException` when the item is not from the inventory) |

`bestSlotFor` ranks by protection (armor + toughness + protection enchants), then remaining durability, then attribute modifier, then Unbreaking level. Both methods throw `NullPointerException` outside a world and have no thread guard.

---

# Movement

`control` is `game.control()` — three direct writes onto the local player. `gameSettings` is `game.settings()` and reads or writes a slice of the vanilla options.

```kotlin
on<ClientTickEvent> {
    control.sprinting(true)
}

on<MoveInputEvent> {
    it.forward(true)   // hold forward for this tick
    it.jump(false)
}
```

## Direct commands

| Method | Type | Description |
|---|---|---|
| `control.sprinting(value)` | `void` | sets the local player's sprint flag (main thread only) |
| `control.sneaking(value)` | `void` | sets the local player's sneak flag (main thread only) |
| `control.jump()` | `void` | jumps, no-op while not on the ground (main thread only) |

Every method throws [`ScriptThreadException`](https://docs.nursultan.fun/scripting/extras/limits#exceptions) off the client thread and `ScriptStateException` with no world loaded.

## Rewriting input

The tick's seven raw movement flags are [`MoveInputEvent`](https://docs.nursultan.fun/scripting/events/reference#moveinputevent); the game rebuilds the player's input from them after the handler returns. The frame's mouse deltas are [`LookInputEvent`](https://docs.nursultan.fun/scripting/events/reference#lookinputevent).

What is physically held right now, independent of the tick's input, is [Keys and binds](https://docs.nursultan.fun/scripting/actions/keys); aiming the head at a point is [Rotations](https://docs.nursultan.fun/scripting/actions/rotations).

## Game settings

| Method | Type | Description |
|---|---|---|
| `gameSettings.perspective()` | `Perspective` | the player's chosen point of view, `FIRST_PERSON` when options are unavailable (API 2) |
| `gameSettings.perspective(value)` | `void` | sets the point of view, null is a no-op (API 2) (main thread only) |
| `gameSettings.scaleFactor()` | `double` | window GUI scale factor, e.g. 1.0 / 2.0 / 3.0 (API 2) |
| `gameSettings.mouseSensitivity()` | `double` | sensitivity option 0..1, 0.5 when options are unavailable (API 2) |
| `gameSettings.mouseSensitivity(value)` | `void` | sets sensitivity, clamped to 0..1 (API 2) (main thread only) |

Neither setting is restored when the script switches off; `scaleFactor()` is the number [2D render](https://docs.nursultan.fun/scripting/ui/render-2d) pixels are divided by to get vanilla interface coordinates.
`PerspectiveEvent` fires on every point-of-view change, whoever caused it — [Event list](https://docs.nursultan.fun/scripting/events/reference#perspectiveevent).

### Perspective

| Method | Type | Description |
|---|---|---|
| `perspective.firstPerson()` | `boolean` | true only for `FIRST_PERSON` (API 2) |
| `perspective.thirdPerson()` | `boolean` | negation of `firstPerson()` (API 2) |
| `perspective.frontView()` | `boolean` | true only for `THIRD_PERSON_FRONT` (API 2) |

### Perspective constants

| Constant | Description |
|---|---|
| `FIRST_PERSON` | camera in the player's head |
| `THIRD_PERSON_BACK` | camera behind the player |
| `THIRD_PERSON_FRONT` | camera in front of the player, facing it |

## Slowdown

The movement multiplier the game applies while an item is in use is [`SlowdownEvent`](https://docs.nursultan.fun/scripting/events/reference#slowdownevent); the value written back replaces the vanilla one and is not clamped.

---

# Keys and binds

`keys` is `client.keys()` and answers what is physically held right now; `bind` is the script's own toggle keybind, and `Key` is the enum both of them speak.

```kotlin
onEnable { bind.set(Key.G, KeyMods.SHIFT, BindType.TOGGLE) }

on<ClientTickEvent> {
    if (keys.inputBlocked()) return@on          // the player is typing
    if (keys.isDown(Key.LEFT_SHIFT)) {
        chat.print(bind.displayName())
    }
}
```

## Reading the keyboard

| Method | Type | Description |
|---|---|---|
| `keys.isDown(key)` | `boolean` | true while that key or mouse button is held; false for `UNKNOWN` |
| `keys.mouseDown(button)` | `boolean` | true while that GLFW mouse button is held; false outside 0..7 |
| `keys.mouseX()` | `float` | cursor x in framebuffer pixels |
| `keys.mouseY()` | `float` | cursor y in framebuffer pixels |
| `keys.cursorLocked()` | `boolean` | true while the cursor is grabbed for camera look |
| `keys.lockCursor()` | `void` | grabs the cursor, queued onto the client thread |
| `keys.unlockCursor()` | `void` | releases the cursor, queued onto the client thread |
| `keys.inputBlocked()` | `boolean` | true while chat, a sign editor, the client menu or a text field takes typing |

`isDown` polls the OS directly: it stays true while a screen is open, and it never consults the client's bind system.
`mouseX()` and `mouseY()` are in the same framebuffer pixels [2D render](https://docs.nursultan.fun/scripting/ui/render-2d) draws in.

## The bind

### Bind

| Method | Type | Description |
|---|---|---|
| `bind.key()` | `Key` | bound key, `Key.UNKNOWN` when unbound |
| `bind.mods()` | `int` | required modifier bitmask, 0 when none |
| `bind.type()` | `BindType` | `HOLD` or `TOGGLE` |
| `bind.bound()` | `boolean` | a key other than `UNKNOWN` is set |
| `bind.visible()` | `boolean` | the bind is listed in the client's bind UI |
| `bind.active()` | `boolean` | HOLD: key held now; TOGGLE: the bound action reports itself on |
| `bind.displayName()` | `String` | label like `Ctrl+Shift+G`; just the key label when mods are 0 |
| `bind.set(key, type)` | `Bind` | rebinds with no modifiers, same as `set(key, 0, type)` |
| `bind.set(key, mods, type)` | `Bind` | rebinds key, mods and type, keeping visibility; applied on the client thread |
| `bind.clear()` | `Bind` | rebinds to `Key.UNKNOWN` with no mods, keeping the type |

### BindType

| Constant | Description |
|---|---|
| `TOGGLE` | press flips the bound state on and off |
| `HOLD` | state is on only while the key is held |

Writes are queued onto the client thread, so `key()` can still report the old value on the next line; a held `HOLD` bind is force-released first, and any type that is not `HOLD` becomes `TOGGLE`.
`bind` itself and the top-level `key(...)` are on [How a script works](https://docs.nursultan.fun/scripting/start/lifecycle); a client module's bind is `module.bind()` on [Client modules](https://docs.nursultan.fun/scripting/extras/modules).

## Modifiers

### KeyMods

| Method | Type | Description |
|---|---|---|
| `KeyMods.NONE` | `int` | 0, no modifiers |
| `KeyMods.SHIFT` | `int` | 1, GLFW shift bit |
| `KeyMods.CONTROL` | `int` | 2, GLFW control bit |
| `KeyMods.ALT` | `int` | 4, GLFW alt bit |
| `KeyMods.SUPER` | `int` | 8, GLFW super/windows bit |
| `KeyMods.has(mods, mod)` | `boolean` | true when any bit of `mod` is set in `mods` |
| `KeyMods.of(shift, control, alt)` | `int` | mask from three flags, never sets `SUPER` |

Binds keep only `SHIFT`, `CONTROL` and `ALT`, so `SUPER` never appears in `bind.mods()`.
A modifier key bound on its own has its own bit stripped from the mask.

## Key actions

### KeyAction

| Constant | Description |
|---|---|
| `PRESS` | key went down |
| `RELEASE` | key came up |
| `REPEAT` | OS auto-repeat while the key is held |

`KeyEvent.action()` carries it, and `pressed()` / `released()` compare against `PRESS` and `RELEASE`, so a `REPEAT` is neither — see [Event list](https://docs.nursultan.fun/scripting/events/reference).

## Every key

| Method | Type | Description |
|---|---|---|
| `key.displayName()` | `String` | short UI label, e.g. `Ctrl`, `Num 5`, `M1` |
| `key.isUnknown()` | `boolean` | true only for `UNKNOWN` |
| `key.isMouse()` | `boolean` | true for the `MOUSE_*` constants |
| `Key.byName(name)` | `Key` | enum name, then display name, both case-insensitive; `UNKNOWN` on no match |
| `key.toString()` | `String` | returns `displayName()`, not the enum name |

### Key

129 constants, in declaration order:

| Constant | Description |
|---|---|
| `UNKNOWN` | unbound, label `None` |
| `MOUSE_1` … `MOUSE_8` | mouse buttons, labels `M1` … `M8` |
| `SPACE` | spacebar, label `Space` |
| `APOSTROPHE`, `COMMA`, `MINUS`, `PERIOD`, `SLASH`, `SEMICOLON`, `EQUAL` | punctuation, labels `'` `,` `-` `.` `/` `;` `=` |
| `DIGIT_0` … `DIGIT_9` | number row, labels `0` … `9` |
| `A` … `Z` | letter keys, labels `A` … `Z` |
| `LEFT_BRACKET`, `BACKSLASH`, `RIGHT_BRACKET`, `GRAVE_ACCENT` | labels `[` `\` `]` `` ` `` |
| `WORLD_1`, `WORLD_2` | non-US extra keys, labels `World 1`, `World 2` |
| `ESCAPE`, `ENTER`, `TAB`, `BACKSPACE` | labels `Esc`, `Enter`, `Tab`, `Backspace` |
| `INSERT`, `DELETE` | labels `Ins`, `Del` |
| `RIGHT`, `LEFT`, `DOWN`, `UP` | arrow keys, labels `Right`, `Left`, `Down`, `Up` |
| `PAGE_UP`, `PAGE_DOWN`, `HOME`, `END` | labels `PgUp`, `PgDn`, `Home`, `End` |
| `CAPS_LOCK`, `SCROLL_LOCK`, `NUM_LOCK` | lock keys, labels `Caps`, `Scroll`, `Num` |
| `PRINT_SCREEN`, `PAUSE` | labels `Print`, `Pause` |
| `F1` … `F25` | function keys, labels `F1` … `F25` |
| `KP_0` … `KP_9` | numpad digits, labels `Num 0` … `Num 9` |
| `KP_DECIMAL`, `KP_DIVIDE`, `KP_MULTIPLY`, `KP_SUBTRACT`, `KP_ADD`, `KP_ENTER`, `KP_EQUAL` | numpad keys, labels `Num .` `Num /` `Num *` `Num -` `Num +` `Num Enter` `Num =` |
| `LEFT_SHIFT`, `LEFT_CONTROL`, `LEFT_ALT`, `LEFT_SUPER` | left modifiers, labels `Shift`, `Ctrl`, `Alt`, `Win` |
| `RIGHT_SHIFT`, `RIGHT_CONTROL`, `RIGHT_ALT`, `RIGHT_SUPER` | right modifiers, labels `RShift`, `RCtrl`, `RAlt`, `RWin` |
| `MENU` | context-menu key, label `Menu` |

`Key` is also the value type of the `hotkey` setting on [Kinds of settings](https://docs.nursultan.fun/scripting/settings/types), and of `KeyEvent.key()`.

---

# Packets

A packet event hands you one Minecraft protocol packet decoded into a Java record. Packet events fire on the network thread, not the client thread, and the record is a flat snapshot: only what its accessors expose survived the decode.

```kotlin
on<PacketReceiveEvent> { e ->
    val packet = e.packet()
    if (packet !is S2CGameMessagePacket || packet.overlay()) return@on
    if (!packet.content().contains("duel")) return@on

    onClientThread { chat.sendToServer("/next") }
}
```

## Two threads

| Method | Type | Description |
|---|---|---|
| `onClientThread(action)` | `Unit` | queues the action on the client thread, skipped when the script is off by then — [Timers and tasks](https://docs.nursultan.fun/scripting/extras/tasks#getting-onto-the-client-thread) |
| `client.onClientThread()` | `boolean` | true when the caller already runs on the client thread — [Timers and tasks](https://docs.nursultan.fun/scripting/extras/tasks#getting-onto-the-client-thread) |

Reading the record's accessors off the client thread is safe.
`interaction`, `raycast`, `rotations.apply`, inventory and container writes, `world.blockEntitiesIn` and `world.removeEntity` throw [`ScriptThreadException`](https://docs.nursultan.fun/scripting/extras/limits#exceptions) off it; `packets.send` returns `false`.

## Receiving

| Method | Type | Description |
|---|---|---|
| `PacketReceiveEvent.packet()` | `S2CPacket` | decoded clientbound packet, never null in a handler — [Event list](https://docs.nursultan.fun/scripting/events/reference) |
| `PacketSendEvent.packet()` | `C2SPacket` | decoded serverbound packet, never null in a handler — [Event list](https://docs.nursultan.fun/scripting/events/reference) |

Only packets the client has a decoder for reach a handler; anything else fires nothing, and a decode failure is logged once per packet class.
Inside a bundle each sub-packet fires separately.

### Packet, S2CPacket, C2SPacket

| Method | Type | Description |
|---|---|---|
| `Packet` | `interface` | root marker of every packet record, declares no members |
| `S2CPacket` | `interface` | server-to-client marker, extends `Packet` |
| `C2SPacket` | `interface` | client-to-server marker, extends `Packet`; the type `send` takes |

`nursultan.packet.*`, `nursultan.packet.c2s.*` and `nursultan.packet.s2c.*` are default imports, so record and enum names need no `import` line.

## Cancelling

| Method | Type | Description |
|---|---|---|
| `PacketReceiveEvent.cancel()` | `void` | Minecraft never handles that packet |
| `PacketSendEvent.cancel()` | `void` | the packet never leaves the client |

Cancelling a received sub-packet inside a bundle removes it from the bundle.
Both events ignore `EventOptions` — `priority` and `ignoreCancelled` alike.

## Sending

| Method | Type | Description |
|---|---|---|
| `packets.send(packet)` | `boolean` | sends the record as a vanilla packet; false off the client thread, without a player or network handler, on a null or observe-only record, or when a field could not be converted (main thread only) |
| `packets.sendSequenced(packet)` | `boolean` | sends through the interaction manager, which fills in the server sequence number; same false conditions plus a missing world or interaction manager (main thread only) |

`packets` is `game.packets()`; a refused send warns once per packet class in the script console. `send` reuses the record's own `sequence` field, `sendSequenced` replaces it.
A packet sent from a script goes out through the same connection call, so it fires `PacketSendEvent` again.

## Fidelity

| Minecraft type | In the record | Note |
|---|---|---|
| `ItemStack` | `String` + `int` | registry id and count; enchantments, components and NBT are gone |
| `Text` | `String` | plain text from `getString()`, no colours, styles or click events |
| `Identifier` | `String` | `namespace:path` |
| `UUID` | `String` | `toString()` |
| `NbtCompound` | `String` | SNBT text, `""` when the packet carried none |
| enum constant | script enum | matched by constant name — [Packet enums](https://docs.nursultan.fun/scripting/actions/packets/enums) |

A vanilla constant with no script twin decodes to `null` and logs one warning; a script constant with no vanilla twin makes the whole send fail.
Full items, components and signatures are reachable only through the world and [Inventory and items](https://docs.nursultan.fun/scripting/game/inventory), never off a packet.

## The reference

| Page | Contents |
|---|---|
| [Packets you can send](https://docs.nursultan.fun/scripting/actions/packets/c2s) | 65 client-to-server records; 51 sendable, 14 observe-only |
| [Entity packets](https://docs.nursultan.fun/scripting/actions/packets/s2c-entities) | spawning, movement, rotation, velocity, damage, effects, equipment, attributes, tracked data |
| [World packets](https://docs.nursultan.fun/scripting/actions/packets/s2c-world) | blocks, chunks, light, world border, time, weather, sounds, particles, explosions |
| [Screen and chat packets](https://docs.nursultan.fun/scripting/actions/packets/s2c-screens) | screen handlers, inventories, trades, recipe book, chat, titles, tab list, scoreboard |
| [Packet enums](https://docs.nursultan.fun/scripting/actions/packets/enums) | 34 enums, 180 constants used as record field types |

Packet records mirror the Minecraft protocol of the client they ship with (1.21.11) — the only part of the API tied to the game version; a Minecraft update can rename or reshape a record.
The client rewrites `.sdk/` on every launch, so the packets jar follows the client you develop against.

---

# Packets you can send

65 client-to-server records; each is a Java record you build with its canonical constructor and hand to `packets.send` or `packets.sendSequenced` — see [Packets](https://docs.nursultan.fun/scripting/actions/packets#sending). 14 of them are observe-only: `send` returns `false` and warns once in the script console. A send also fails on a null field, an enum constant with no vanilla twin, an entity outside the loaded world or a slot out of range; the enum types are listed in [Packet enums](https://docs.nursultan.fun/scripting/actions/packets/enums).

```kotlin
name("Instant respawn")
key(Key.R)

onEnable {
    // the death screen's Respawn button, as a packet
    packets.send(C2SClientStatusPacket(ClientStatus.PERFORM_RESPAWN))
}
```

## C2SAcknowledgeChunksPacket

Chunk-batch rate the client asks for after finishing a batch.

| Component | Type | Description |
|---|---|---|
| `desiredChunksPerTick()` | `float` | requested chunks delivered per tick |

## C2SAcknowledgeReconfigurationPacket

Acknowledges the server's switch to the configuration phase; no components.

## C2SAdvancementTabPacket

Advancement screen tab opened or closed. Observe-only.

| Component | Type | Description |
|---|---|---|
| `action()` | `AdvancementTabAction` | tab opened or screen closed |
| `tabToOpen()` | `String?` | namespaced advancement tab id, null when closing |

## C2SBoatPaddleStatePacket

Paddle animation state while riding a boat.

| Component | Type | Description |
|---|---|---|
| `leftPaddling()` | `boolean` | left paddle turning |
| `rightPaddling()` | `boolean` | right paddle turning |

## C2SBookUpdatePacket

Writable-book edit or signing. Observe-only.

| Component | Type | Description |
|---|---|---|
| `slot()` | `int` | hotbar slot holding the book |
| `pages()` | `List<String>` | page texts in order |
| `title()` | `String?` | title given at signing, null while unsigned |

## C2SBundleItemSelectedPacket

Selects the active item inside a bundle.

| Component | Type | Description |
|---|---|---|
| `slotId()` | `int` | screen-handler slot holding the bundle |
| `selectedItemIndex()` | `int` | index inside the bundle contents |

## C2SButtonClickPacket

Button pressed inside a screen handler: enchanting table, trade, loom, stonecutter.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | screen handler sync id |
| `buttonId()` | `int` | button index, meaning depends on the handler |

## C2SChangeGameModePacket

Client asks to change its own game mode.

| Component | Type | Description |
|---|---|---|
| `mode()` | `GameMode` | requested game mode; send fails when unmapped |

## C2SChatCommandSignedPacket

Signed command execution. Observe-only; signatures and acknowledgments are not exposed.

| Component | Type | Description |
|---|---|---|
| `command()` | `String` | command text without the leading slash |
| `timestamp()` | `long` | signing time, epoch milliseconds |
| `salt()` | `long` | signing salt |

## C2SChatMessagePacket

Plain chat message from the player. Observe-only; signature data is not exposed.

| Component | Type | Description |
|---|---|---|
| `chatMessage()` | `String` | raw message text |
| `timestamp()` | `long` | signing time, epoch milliseconds |
| `salt()` | `long` | signing salt |

## C2SClickSlotPacket

Inventory slot click. Observe-only; the changed-stack map and the cursor stack are not exposed.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | screen handler sync id |
| `revision()` | `int` | handler revision the click was made against |
| `slot()` | `short` | clicked slot index, -999 outside the window |
| `button()` | `byte` | mouse button or hotbar index, meaning depends on actionType |
| `actionType()` | `SlotActionType` | click semantics |

## C2SClientCommandPacket

Player state command: leave bed, sprint, horse jump, ride inventory, elytra.

| Component | Type | Description |
|---|---|---|
| `mode()` | `ClientCommand` | requested state change; send fails without a player or when unmapped |

## C2SClientOptionsPacket

Full client settings block, sent on join and on every option change.

| Component | Type | Description |
|---|---|---|
| `language()` | `String` | locale code, e.g. `en_us` |
| `viewDistance()` | `int` | render distance in chunks |
| `chatVisibility()` | `ChatVisibility` | chat display preference; send fails when unmapped |
| `chatColorsEnabled()` | `boolean` | colored chat allowed |
| `playerModelParts()` | `int` | skin layer bitmask: cape, jacket, sleeves, pants, hat |
| `mainArm()` | `Arm` | main hand side; send fails when unmapped |
| `filtersText()` | `boolean` | profanity filtering enabled |
| `allowsServerListing()` | `boolean` | may appear in server listings |
| `particleStatus()` | `ParticlesMode` | particle quality; send fails when unmapped |

## C2SClientStatusPacket

Respawn request or statistics request.

| Component | Type | Description |
|---|---|---|
| `mode()` | `ClientStatus` | respawn or request stats; send fails when unmapped |

## C2SClientTickEndPacket

Marks the end of a client tick; no components.

## C2SCloseHandledScreenPacket

Client closed a screen handler.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | sync id of the closed handler |

## C2SCommandExecutionPacket

Unsigned command execution.

| Component | Type | Description |
|---|---|---|
| `command()` | `String` | command text without the leading slash |

## C2SCommonPongPacket

Reply to `S2CCommonPingPacket`.

| Component | Type | Description |
|---|---|---|
| `parameter()` | `int` | value echoed back from the ping |

## C2SCookieResponsePacket

Cookie value returned to the server. Observe-only; the payload bytes are not exposed.

| Component | Type | Description |
|---|---|---|
| `key()` | `String` | namespaced cookie id |

## C2SCraftRequestPacket

Recipe-book craft request.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | crafting screen handler sync id |
| `recipeId()` | `int` | network recipe index |
| `craftAll()` | `boolean` | craft a full stack instead of one |

## C2SCreativeInventoryActionPacket

Creative-mode slot set. Observe-only; item components and NBT are not exposed.

| Component | Type | Description |
|---|---|---|
| `slot()` | `int` | screen-handler slot index |
| `item()` | `String` | namespaced item id of the placed stack |
| `count()` | `int` | stack size |

## C2SCustomClickActionPacket

Custom click action from a server dialog. Observe-only; the payload NBT is not exposed.

| Component | Type | Description |
|---|---|---|
| `id()` | `String` | namespaced action id |

## C2SCustomPayloadPacket

Plugin-channel message. Observe-only; the payload bytes are not exposed.

| Component | Type | Description |
|---|---|---|
| `channel()` | `String` | namespaced channel id |

## C2SDebugSubscriptionRequestPacket

Debug-sample subscription request. Observe-only; no components.

## C2SHandSwingPacket

Arm swing animation.

| Component | Type | Description |
|---|---|---|
| `offhand()` | `boolean` | true swings the off hand, false the main hand |

## C2SJigsawGeneratingPacket

Generate pressed on a jigsaw block.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | jigsaw block x |
| `y()` | `int` | jigsaw block y |
| `z()` | `int` | jigsaw block z |
| `maxDepth()` | `int` | generation depth in levels |
| `keepJigsaws()` | `boolean` | leave jigsaw blocks in the result |

## C2SKeepAlivePacket

Keep-alive reply.

| Component | Type | Description |
|---|---|---|
| `id()` | `long` | id copied from the server keep-alive |

## C2SMessageAcknowledgmentPacket

Acknowledges received chat messages.

| Component | Type | Description |
|---|---|---|
| `offset()` | `int` | number of newly acknowledged messages |

## C2SMoveFullPacket

Movement packet carrying position and rotation.

| Component | Type | Description |
|---|---|---|
| `x()` | `double` | absolute x in blocks |
| `y()` | `double` | absolute y in blocks, feet level |
| `z()` | `double` | absolute z in blocks |
| `yaw()` | `float` | yaw in degrees |
| `pitch()` | `float` | pitch in degrees, -90..90 |
| `onGround()` | `boolean` | standing on ground flag |
| `horizontalCollision()` | `boolean` | collided horizontally this tick |

## C2SMoveLookPacket

Movement packet carrying rotation only.

| Component | Type | Description |
|---|---|---|
| `yaw()` | `float` | yaw in degrees |
| `pitch()` | `float` | pitch in degrees, -90..90 |
| `onGround()` | `boolean` | standing on ground flag |
| `horizontalCollision()` | `boolean` | collided horizontally this tick |

## C2SMoveOnGroundPacket

Movement packet carrying flags only, sent on an idle tick.

| Component | Type | Description |
|---|---|---|
| `onGround()` | `boolean` | standing on ground flag |
| `horizontalCollision()` | `boolean` | collided horizontally this tick |

## C2SMovePositionPacket

Movement packet carrying position only.

| Component | Type | Description |
|---|---|---|
| `x()` | `double` | absolute x in blocks |
| `y()` | `double` | absolute y in blocks, feet level |
| `z()` | `double` | absolute z in blocks |
| `onGround()` | `boolean` | standing on ground flag |
| `horizontalCollision()` | `boolean` | collided horizontally this tick |

## C2SPickItemFromBlockPacket

Middle-click pick block.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | target block x |
| `y()` | `int` | target block y |
| `z()` | `int` | target block z |
| `includeData()` | `boolean` | copy block-entity data into the picked stack |

## C2SPickItemFromEntityPacket

Middle-click pick entity.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | target entity network id |
| `includeData()` | `boolean` | copy entity data into the picked stack |

## C2SPlayerActionPacket

Block-break stage, item drop, hand swap or use-release.

| Component | Type | Description |
|---|---|---|
| `action()` | `PlayerAction` | which action; send fails when unmapped |
| `x()` | `int` | target block x |
| `y()` | `int` | target block y |
| `z()` | `int` | target block z |
| `side()` | `Side` | clicked block face; send fails when unmapped |
| `sequence()` | `int` | interaction sequence; used as-is by `send`, replaced by `sendSequenced` |

## C2SPlayerInputPacket

Raw movement key state, one flag per input.

| Component | Type | Description |
|---|---|---|
| `forward()` | `boolean` | forward key held |
| `backward()` | `boolean` | backward key held |
| `left()` | `boolean` | strafe-left key held |
| `right()` | `boolean` | strafe-right key held |
| `jump()` | `boolean` | jump key held |
| `sneak()` | `boolean` | sneak key held |
| `sprint()` | `boolean` | sprint key held |

## C2SPlayerInteractBlockPacket

Right-click on a block.

| Component | Type | Description |
|---|---|---|
| `offhand()` | `boolean` | true uses the off hand |
| `x()` | `int` | clicked block x |
| `y()` | `int` | clicked block y |
| `z()` | `int` | clicked block z |
| `side()` | `Side` | clicked face; send fails when unmapped |
| `hitX()` | `double` | absolute world x of the hit point |
| `hitY()` | `double` | absolute world y of the hit point |
| `hitZ()` | `double` | absolute world z of the hit point |
| `insideBlock()` | `boolean` | ray started inside the block shape |
| `sequence()` | `int` | interaction sequence; used as-is by `send`, replaced by `sendSequenced` |

## C2SPlayerInteractEntityPacket

Attack, interact or interact-at against an entity.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | target entity network id; send fails when it is not in the loaded world |
| `sneaking()` | `boolean` | player was sneaking |
| `type()` | `InteractType` | ATTACK, INTERACT or INTERACT_AT; send fails when null |
| `hand()` | `Hand?` | used hand, always null for ATTACK; send fails when null otherwise |
| `hitX()` | `Double?` | hit x relative to the entity, INTERACT_AT only |
| `hitY()` | `Double?` | hit y relative to the entity, INTERACT_AT only |
| `hitZ()` | `Double?` | hit z relative to the entity, INTERACT_AT only |

## C2SPlayerInteractItemPacket

Right-click with the held item, not aimed at a block.

| Component | Type | Description |
|---|---|---|
| `offhand()` | `boolean` | true uses the off hand |
| `sequence()` | `int` | interaction sequence; used as-is by `send`, replaced by `sendSequenced` |
| `yaw()` | `float` | yaw in degrees at use time |
| `pitch()` | `float` | pitch in degrees at use time |

## C2SPlayerLoadedPacket

Client finished loading into the world; no components.

## C2SPlayerSessionPacket

Chat session and public-key announcement. Observe-only; no components.

## C2SQueryBlockNbtPacket

Operator block-NBT query, answered by `S2CNbtQueryResponsePacket`.

| Component | Type | Description |
|---|---|---|
| `transactionId()` | `int` | id matched by the response |
| `x()` | `int` | queried block x |
| `y()` | `int` | queried block y |
| `z()` | `int` | queried block z |

## C2SQueryEntityNbtPacket

Operator entity-NBT query, answered by `S2CNbtQueryResponsePacket`.

| Component | Type | Description |
|---|---|---|
| `transactionId()` | `int` | id matched by the response |
| `entityId()` | `int` | queried entity network id |

## C2SRecipeBookDataPacket

Recipe clicked in the recipe book.

| Component | Type | Description |
|---|---|---|
| `recipeId()` | `int` | network recipe index |

## C2SRecipeCategoryOptionsPacket

Per-category recipe-book UI state.

| Component | Type | Description |
|---|---|---|
| `category()` | `RecipeBookCategory` | recipe book tab; send fails when unmapped |
| `guiOpen()` | `boolean` | category panel expanded |
| `filteringCraftable()` | `boolean` | show craftable only |

## C2SRenameItemPacket

Anvil rename field text.

| Component | Type | Description |
|---|---|---|
| `name()` | `String` | new item name |

## C2SRequestCommandCompletionsPacket

Tab-completion request, answered by `S2CCommandSuggestionsPacket`.

| Component | Type | Description |
|---|---|---|
| `completionId()` | `int` | id matched by the response |
| `partialCommand()` | `String` | text typed so far, including the leading slash |

## C2SResourcePackStatusPacket

Resource-pack download and apply status. Observe-only.

| Component | Type | Description |
|---|---|---|
| `id()` | `String` | resource pack uuid string |
| `status()` | `ResourcePackStatus` | accepted, declined, loaded or failed |

## C2SSelectMerchantTradePacket

Villager trade selection.

| Component | Type | Description |
|---|---|---|
| `tradeId()` | `int` | index into the offer list |

## C2SSelectSlotPacket

Hotbar slot selection.

| Component | Type | Description |
|---|---|---|
| `slot()` | `int` | hotbar index 0..8; send fails outside that range |

## C2SSetTestBlockPacket

Test block configuration write.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | test block x |
| `y()` | `int` | test block y |
| `z()` | `int` | test block z |
| `mode()` | `TestBlockMode` | test block mode; send fails when unmapped |
| `message()` | `String` | message field text |

## C2SSlotChangedStatePacket

Crafter slot enabled or disabled.

| Component | Type | Description |
|---|---|---|
| `slotId()` | `int` | crafter slot index |
| `screenHandlerId()` | `int` | screen handler sync id |
| `newState()` | `boolean` | true enables the slot |

## C2SSpectatorTeleportPacket

Spectator teleport to a player by uuid.

| Component | Type | Description |
|---|---|---|
| `uuid()` | `String` | target player uuid string; send fails when null or unparseable |

## C2STeleportConfirmPacket

Confirms a teleport id from `S2CPlayerPositionLookPacket`.

| Component | Type | Description |
|---|---|---|
| `teleportId()` | `int` | id copied from the server teleport |

## C2STestInstanceBlockActionPacket

Button pressed on a test instance block. Observe-only.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | test instance block x |
| `y()` | `int` | test instance block y |
| `z()` | `int` | test instance block z |
| `action()` | `TestInstanceBlockAction` | which button was pressed |

## C2SUpdateBeaconPacket

Beacon effect selection.

| Component | Type | Description |
|---|---|---|
| `primary()` | `String?` | namespaced status effect id, null or blank means none |
| `secondary()` | `String?` | namespaced status effect id, null or blank means none |

An unknown or unparseable id is sent as "none" instead of failing the send.

## C2SUpdateCommandBlockMinecartPacket

Command-block minecart edit.

| Component | Type | Description |
|---|---|---|
| `command()` | `String` | command text |
| `trackOutput()` | `boolean` | store the last output |
| `entityId()` | `int` | minecart entity network id |

## C2SUpdateCommandBlockPacket

Command block edit.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | command block x |
| `y()` | `int` | command block y |
| `z()` | `int` | command block z |
| `command()` | `String` | command text |
| `type()` | `CommandBlockType` | impulse, chain or repeat; send fails when unmapped |
| `trackOutput()` | `boolean` | store the last output |
| `conditional()` | `boolean` | conditional mode |
| `alwaysActive()` | `boolean` | always active instead of needing redstone |

## C2SUpdateDifficultyLockPacket

Difficulty lock toggle; single-player or LAN host only.

| Component | Type | Description |
|---|---|---|
| `difficultyLocked()` | `boolean` | lock the world difficulty |

## C2SUpdateDifficultyPacket

Difficulty change; single-player or LAN host only.

| Component | Type | Description |
|---|---|---|
| `difficulty()` | `Difficulty` | requested difficulty; send fails when unmapped |

## C2SUpdateJigsawPacket

Jigsaw block edit. Observe-only.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | jigsaw block x |
| `y()` | `int` | jigsaw block y |
| `z()` | `int` | jigsaw block z |
| `name()` | `String` | namespaced jigsaw name |
| `target()` | `String` | namespaced target jigsaw name |
| `pool()` | `String` | namespaced template pool id |
| `finalState()` | `String` | block state string placed after generation |
| `jointType()` | `JigsawJoint` | rollable or aligned joint |
| `selectionPriority()` | `int` | selection order weight |
| `placementPriority()` | `int` | placement order weight |

## C2SUpdatePlayerAbilitiesPacket

Flight toggle.

| Component | Type | Description |
|---|---|---|
| `flying()` | `boolean` | player is flying |

`send` builds a fresh abilities object with only `flying` set; the other ability flags are not carried.

## C2SUpdateSignPacket

Sign text write.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | sign block x |
| `y()` | `int` | sign block y |
| `z()` | `int` | sign block z |
| `front()` | `boolean` | true edits the front face, false the back |
| `line1()` | `String` | first text line |
| `line2()` | `String` | second text line |
| `line3()` | `String` | third text line |
| `line4()` | `String` | fourth text line |

## C2SUpdateStructureBlockPacket

Structure block edit.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | structure block x |
| `y()` | `int` | structure block y |
| `z()` | `int` | structure block z |
| `action()` | `StructureBlockAction` | update, save, load or detect; send fails when unmapped |
| `mode()` | `StructureBlockMode` | save, load, corner or data; send fails when unmapped |
| `templateName()` | `String` | structure name field |
| `offsetX()` | `int` | relative offset x in blocks |
| `offsetY()` | `int` | relative offset y in blocks |
| `offsetZ()` | `int` | relative offset z in blocks |
| `sizeX()` | `int` | structure size x in blocks |
| `sizeY()` | `int` | structure size y in blocks |
| `sizeZ()` | `int` | structure size z in blocks |
| `mirror()` | `BlockMirror` | mirror setting; send fails when unmapped |
| `rotation()` | `BlockRotation` | rotation setting; send fails when unmapped |
| `metadata()` | `String` | data-mode metadata string |
| `ignoreEntities()` | `boolean` | exclude entities from save and load |
| `strict()` | `boolean` | strict placement mode |
| `showAir()` | `boolean` | render invisible blocks |
| `showBoundingBox()` | `boolean` | render the bounding box |
| `integrity()` | `float` | load integrity, 0..1 |
| `seed()` | `long` | integrity randomization seed |

## C2SVehicleMovePacket

Position and rotation of the vehicle the player drives.

| Component | Type | Description |
|---|---|---|
| `x()` | `double` | absolute vehicle x in blocks |
| `y()` | `double` | absolute vehicle y in blocks |
| `z()` | `double` | absolute vehicle z in blocks |
| `yaw()` | `float` | vehicle yaw in degrees |
| `pitch()` | `float` | vehicle pitch in degrees |
| `onGround()` | `boolean` | vehicle standing on ground flag |

---

# Entity packets

Server-to-client records about entities and the local player: spawning, movement, rotation, velocity, damage, effects, equipment, attributes and tracked data. Positions are world blocks, velocities blocks per tick, rotations degrees and durations ticks; threading, cancelling and what the decode drops are on [Packets](https://docs.nursultan.fun/scripting/actions/packets).

```kotlin
on<PacketReceiveEvent> { e ->
    val packet = e.packet()
    if (packet !is S2CEntityVelocityPacket) return@on
    if (packet.entityId() != player.id()) return@on

    log.info("knockback ${packet.velX()} ${packet.velZ()}")
}
```

## S2CDamageTiltPacket

Hurt-direction camera tilt.

| Component | Type | Description |
|---|---|---|
| `id()` | `int` | damaged entity network id |
| `yaw()` | `float` | direction the damage came from, degrees |

## S2CDeathMessagePacket

Death screen message.

| Component | Type | Description |
|---|---|---|
| `playerId()` | `int` | dead player entity network id |
| `message()` | `String` | plain-text death message |

## S2CEndCombatPacket

Combat tracker leaves combat. No components.

## S2CEnterCombatPacket

Combat tracker enters combat. No components.

## S2CEntitiesDestroyPacket

Entities removed from the client world.

| Component | Type | Description |
|---|---|---|
| `entityIds()` | `List<Integer>` | network ids of the removed entities |

## S2CEntityAnimationPacket

Entity animation trigger.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | animating entity network id |
| `animationId()` | `int` | 0 swing main hand, 2 wake up, 3 swing off hand, 4 crit, 5 enchanted hit |

## S2CEntityAttachPacket

Leash attached or detached.

| Component | Type | Description |
|---|---|---|
| `attachedEntityId()` | `int` | leashed entity network id |
| `holdingEntityId()` | `int` | holder entity network id, -1 detaches |

## S2CEntityAttributesPacket

Attribute base values and modifiers for one entity.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | entity network id |
| `attributes()` | `List<Attribute>` | attribute entries |

### S2CEntityAttributesPacket.Attribute

| Component | Type | Description |
|---|---|---|
| `attribute()` | `String` | attribute id with namespace, e.g. `minecraft:movement_speed` |
| `base()` | `double` | base value before modifiers |
| `modifiers()` | `List<Modifier>` | modifiers applied to this attribute |

### S2CEntityAttributesPacket.Modifier

| Component | Type | Description |
|---|---|---|
| `id()` | `String` | modifier id with namespace |
| `value()` | `double` | modifier amount |
| `operation()` | `String` | lowercased vanilla operation, e.g. `add_value`, `add_multiplied_base` |

## S2CEntityDamagePacket

Damage taken by an entity. The damage type and the amount are not exposed.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | damaged entity network id |
| `sourceCauseId()` | `int` | attacker entity network id, 0 when none |
| `sourceDirectId()` | `int` | direct source network id, projectile included, 0 when none |
| `sourceX()` | `Double?` | damage source world x, null for most sources |
| `sourceY()` | `Double?` | damage source world y, null for most sources |
| `sourceZ()` | `Double?` | damage source world z, null for most sources |

## S2CEntityEquipmentUpdatePacket

Equipment slot contents for one entity.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | entity network id |
| `equipment()` | `List<Equipment>` | changed equipment slots |

### S2CEntityEquipmentUpdatePacket.Equipment

| Component | Type | Description |
|---|---|---|
| `slot()` | `String` | vanilla slot name: `mainhand`, `offhand`, `head`, `chest`, `legs`, `feet`, `body`, `saddle` |
| `item()` | `String` | item id with namespace, `minecraft:air` when empty |
| `count()` | `int` | stack size |

## S2CEntityMoveRelativePacket

Relative entity move without rotation.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | entity network id |
| `deltaX()` | `short` | x delta in 1/4096 block units |
| `deltaY()` | `short` | y delta in 1/4096 block units |
| `deltaZ()` | `short` | z delta in 1/4096 block units |
| `onGround()` | `boolean` | entity on ground flag |

## S2CEntityPassengersSetPacket

Passenger list of a vehicle entity.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | vehicle entity network id |
| `passengerIds()` | `List<Integer>` | passenger network ids, empty dismounts everyone |

## S2CEntityPositionPacket

Absolute entity teleport with velocity and rotation.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | entity network id |
| `x()` | `double` | x in blocks |
| `y()` | `double` | y in blocks |
| `z()` | `double` | z in blocks |
| `velX()` | `double` | x velocity in blocks per tick |
| `velY()` | `double` | y velocity in blocks per tick |
| `velZ()` | `double` | z velocity in blocks per tick |
| `yaw()` | `float` | yaw in degrees |
| `pitch()` | `float` | pitch in degrees |
| `relatives()` | `List<PositionFlag>` | fields that are deltas on the current values — [Packet enums](https://docs.nursultan.fun/scripting/actions/packets/enums) |
| `onGround()` | `boolean` | entity on ground flag |

## S2CEntityPositionSyncPacket

Periodic absolute position resync for one entity.

| Component | Type | Description |
|---|---|---|
| `id()` | `int` | entity network id |
| `x()` | `double` | x in blocks |
| `y()` | `double` | y in blocks |
| `z()` | `double` | z in blocks |
| `velX()` | `double` | x velocity in blocks per tick |
| `velY()` | `double` | y velocity in blocks per tick |
| `velZ()` | `double` | z velocity in blocks per tick |
| `yaw()` | `float` | yaw in degrees |
| `pitch()` | `float` | pitch in degrees |
| `onGround()` | `boolean` | entity on ground flag |

## S2CEntityRotateAndMoveRelativePacket

Relative entity move plus rotation.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | entity network id |
| `deltaX()` | `short` | x delta in 1/4096 block units |
| `deltaY()` | `short` | y delta in 1/4096 block units |
| `deltaZ()` | `short` | z delta in 1/4096 block units |
| `yaw()` | `float` | yaw in degrees, quantised to 360/256 steps on the wire |
| `pitch()` | `float` | pitch in degrees, quantised to 360/256 steps on the wire |
| `onGround()` | `boolean` | entity on ground flag |

## S2CEntityRotatePacket

Entity rotation only. The entity id is not exposed.

| Component | Type | Description |
|---|---|---|
| `yaw()` | `float` | yaw in degrees, quantised to 360/256 steps on the wire |
| `pitch()` | `float` | pitch in degrees, quantised to 360/256 steps on the wire |
| `onGround()` | `boolean` | entity on ground flag |

## S2CEntitySetHeadYawPacket

Entity head yaw. The entity id is not exposed.

| Component | Type | Description |
|---|---|---|
| `headYaw()` | `float` | head yaw in degrees, quantised to 360/256 steps on the wire |

## S2CEntitySpawnPacket

Entity added to the client world.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | entity network id |
| `uuid()` | `String` | entity uuid string |
| `entityType()` | `String` | entity type id with namespace |
| `x()` | `double` | spawn x in blocks |
| `y()` | `double` | spawn y in blocks |
| `z()` | `double` | spawn z in blocks |
| `velX()` | `double` | x velocity in blocks per tick |
| `velY()` | `double` | y velocity in blocks per tick |
| `velZ()` | `double` | z velocity in blocks per tick |
| `pitch()` | `float` | pitch in degrees |
| `yaw()` | `float` | yaw in degrees |
| `headYaw()` | `float` | head yaw in degrees |
| `entityData()` | `int` | type-specific spawn data: owner id, block state id, orientation |

## S2CEntityStatusEffectPacket

Status effect applied to or refreshed on an entity.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | affected entity network id |
| `effect()` | `String` | effect id with namespace |
| `amplifier()` | `int` | 0-based level, 0 is level I |
| `duration()` | `int` | remaining duration in ticks, -1 is infinite |
| `ambient()` | `boolean` | comes from a beacon or conduit |
| `showParticles()` | `boolean` | effect particles render |
| `showIcon()` | `boolean` | HUD icon shows |
| `keepFading()` | `boolean` | blend animation keeps running |

## S2CEntityStatusPacket

Entity event code: crit particles, death, taming, totem pop. The entity id is not exposed.

| Component | Type | Description |
|---|---|---|
| `status()` | `byte` | vanilla entity status code |

## S2CEntityTrackerUpdatePacket

Tracked data update for one entity.

| Component | Type | Description |
|---|---|---|
| `id()` | `int` | entity network id |
| `values()` | `List<TrackedValue>` | changed entries, empty when the packet carries none |

### S2CEntityTrackerUpdatePacket.TrackedValue

| Component | Type | Description |
|---|---|---|
| `id()` | `int` | data tracker entry index |
| `value()` | `String` | `String.valueOf` of the raw object, format follows its type |

## S2CEntityValueDebugPacket

Debug entity-value push. The value payload is not exposed.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | entity network id |

## S2CEntityVelocityPacket

Entity velocity set: knockback, explosion, fluid push.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | entity network id |
| `velX()` | `double` | x velocity in blocks per tick |
| `velY()` | `double` | y velocity in blocks per tick |
| `velZ()` | `double` | z velocity in blocks per tick |

## S2CExperienceBarUpdatePacket

Experience bar, level and total points.

| Component | Type | Description |
|---|---|---|
| `barProgress()` | `float` | bar fill, 0..1 |
| `experienceLevel()` | `int` | current level |
| `experience()` | `int` | total experience points |

## S2CHealthUpdatePacket

Local player health, food and saturation.

| Component | Type | Description |
|---|---|---|
| `health()` | `float` | health points, 20 is full for an unmodified player |
| `food()` | `int` | food level, 0..20 |
| `saturation()` | `float` | saturation, 0..20 |

## S2CItemPickupAnimationPacket

Item flying towards the entity that collected it.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | picked-up item entity network id |
| `collectorEntityId()` | `int` | collecting entity network id |
| `stackAmount()` | `int` | number of items collected |

## S2CLookAtPacket

Server forces the player to face a target. The target itself is not exposed.

| Component | Type | Description |
|---|---|---|
| `selfAnchor()` | `EntityAnchor?` | FEET or EYES anchor on the player, null when unmapped — [Packet enums](https://docs.nursultan.fun/scripting/actions/packets/enums) |

## S2CMoveMinecartAlongTrackPacket

Minecart rail movement. The step list is not exposed.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | minecart entity network id |

## S2CPlayerAbilitiesPacket

Local player ability flags and speeds.

| Component | Type | Description |
|---|---|---|
| `invulnerable()` | `boolean` | damage immunity |
| `flying()` | `boolean` | currently flying |
| `allowFlying()` | `boolean` | flight permitted |
| `creativeMode()` | `boolean` | creative instant break |
| `flySpeed()` | `float` | flight speed factor, vanilla default 0.05 |
| `walkSpeed()` | `float` | walk speed factor, vanilla default 0.1 |

## S2CPlayerActionResponsePacket

Acknowledges a sequenced interaction so the client drops its prediction.

| Component | Type | Description |
|---|---|---|
| `sequence()` | `int` | acknowledged interaction sequence number |

## S2CPlayerPositionLookPacket

Server teleport of the local player, answered with `C2STeleportConfirmPacket`.

| Component | Type | Description |
|---|---|---|
| `teleportId()` | `int` | id to echo back in the confirm packet |
| `x()` | `double` | target x in blocks |
| `y()` | `double` | target y in blocks, feet level |
| `z()` | `double` | target z in blocks |
| `yaw()` | `float` | target yaw in degrees |
| `pitch()` | `float` | target pitch in degrees |

The relative-flag set is not exposed, so any of the six values may be a delta on the current one.

## S2CPlayerRespawnPacket

Local player respawn or dimension change.

| Component | Type | Description |
|---|---|---|
| `dimension()` | `String` | dimension id with namespace |
| `seed()` | `long` | hashed world seed for biome-dependent client effects |
| `gameMode()` | `GameMode?` | new game mode, null when unmapped — [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `lastGameMode()` | `GameMode?` | previous game mode, null when unmapped |
| `isDebug()` | `boolean` | debug world type |
| `isFlat()` | `boolean` | superflat world type |
| `portalCooldown()` | `int` | remaining portal cooldown in ticks |
| `seaLevel()` | `int` | dimension sea level in blocks |
| `flag()` | `byte` | bit 1 keeps attributes, bit 2 keeps tracked data |

## S2CPlayerRotationPacket

Server sets the local player rotation.

| Component | Type | Description |
|---|---|---|
| `yaw()` | `float` | yaw in degrees |
| `relativeYaw()` | `boolean` | yaw is a delta on the current yaw |
| `pitch()` | `float` | pitch in degrees |
| `relativePitch()` | `boolean` | pitch is a delta on the current pitch |

## S2CPlayerSpawnPositionPacket

World spawn or respawn anchor point.

| Component | Type | Description |
|---|---|---|
| `dimension()` | `String` | dimension id with namespace |
| `x()` | `int` | spawn block x |
| `y()` | `int` | spawn block y |
| `z()` | `int` | spawn block z |
| `yaw()` | `float` | spawn yaw in degrees |
| `pitch()` | `float` | spawn pitch in degrees |

## S2CProjectilePowerPacket

Acceleration power of a fireball-type projectile.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | projectile entity network id |
| `accelerationPower()` | `double` | acceleration factor applied per tick |

## S2CRemoveEntityStatusEffectPacket

Status effect cleared from an entity. Which effect is not exposed.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | affected entity network id |

## S2CSetCameraEntityPacket

Render camera switched to another entity.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | entity network id to view from |

## S2CVehicleMovePacket

Server moves the vehicle the player rides. The entity id is not exposed.

| Component | Type | Description |
|---|---|---|
| `x()` | `double` | vehicle x in blocks |
| `y()` | `double` | vehicle y in blocks |
| `z()` | `double` | vehicle z in blocks |
| `yaw()` | `float` | vehicle yaw in degrees |
| `pitch()` | `float` | vehicle pitch in degrees |

---

# World packets

Server-to-client records about blocks, chunks, light, the world border, time, weather, sounds, particles and explosions. Every one arrives through `PacketReceiveEvent.packet()`; positions are in blocks, chunk coordinates are blocks/16, rotations are degrees and ticks run 20 per second — threads, cancelling and what a decode drops are on [Packets](https://docs.nursultan.fun/scripting/actions/packets).

```kotlin
on<PacketReceiveEvent> { e ->
    val packet = e.packet()
    if (packet !is S2CBlockUpdatePacket) return@on

    // a block somewhere turned into air
    if (packet.block() == "minecraft:air") log("${packet.x()} ${packet.y()} ${packet.z()}")
}
```

## S2CBlockBreakingProgressPacket

Break-progress overlay for a block another entity is mining.

| Component | Type | Description |
|---|---|---|
| `entityId()` | `int` | network id of the mining entity |
| `x()` | `int` | block x |
| `y()` | `int` | block y |
| `z()` | `int` | block z |
| `progress()` | `int` | break stage 0..9, anything outside clears the overlay |

## S2CBlockEntityUpdatePacket

Block entity data for one position.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | block x |
| `y()` | `int` | block y |
| `z()` | `int` | block z |
| `type()` | `String` | namespaced block entity type id |
| `nbt()` | `String` | SNBT payload, `""` when the packet carried none |

## S2CBlockEventPacket

Block action — note block ping, chest lid, piston push, bell ring.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | block x |
| `y()` | `int` | block y |
| `z()` | `int` | block z |
| `type()` | `int` | block-specific action id |
| `data()` | `int` | block-specific action parameter |
| `block()` | `String` | namespaced id of the block acted on |

## S2CBlockUpdatePacket

Single block change; only the block id survives, not the state properties.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | block x |
| `y()` | `int` | block y |
| `z()` | `int` | block z |
| `block()` | `String` | namespaced id of the new block |

## S2CBlockValueDebugPacket

Debug block-value push; the value payload is not exposed.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | block x |
| `y()` | `int` | block y |
| `z()` | `int` | block z |

## S2CChunkBiomeDataPacket

Biome-only chunk resend; no components.

## S2CChunkDataPacket

Full chunk send; sections, block entities, heightmaps and light are not exposed.

| Component | Type | Description |
|---|---|---|
| `chunkX()` | `int` | chunk x, blocks/16 |
| `chunkZ()` | `int` | chunk z, blocks/16 |

## S2CChunkDeltaUpdatePacket

Several block changes inside one 16x16x16 chunk section.

| Component | Type | Description |
|---|---|---|
| `blocks()` | `List<BlockChange>` | changed blocks, positions already absolute |

### S2CChunkDeltaUpdatePacket.BlockChange

One block change inside a chunk-delta update.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | absolute block x |
| `y()` | `int` | absolute block y |
| `z()` | `int` | absolute block z |
| `block()` | `String` | namespaced id of the new block |
| `air()` | `boolean` | the new state is air |

## S2CChunkLoadDistancePacket

Server-side view distance change.

| Component | Type | Description |
|---|---|---|
| `distance()` | `int` | view distance in chunks |

## S2CChunkRenderDistanceCenterPacket

New center chunk for chunk loading.

| Component | Type | Description |
|---|---|---|
| `chunkX()` | `int` | center chunk x |
| `chunkZ()` | `int` | center chunk z |

## S2CChunkSentPacket

End of a chunk batch; answered with `C2SAcknowledgeChunksPacket`.

| Component | Type | Description |
|---|---|---|
| `batchSize()` | `int` | number of chunks in the finished batch |

## S2CChunkValueDebugPacket

Debug chunk-value push; the value payload is not exposed.

| Component | Type | Description |
|---|---|---|
| `chunkX()` | `int` | chunk x |
| `chunkZ()` | `int` | chunk z |

## S2CDifficultyPacket

World difficulty sync.

| Component | Type | Description |
|---|---|---|
| `difficulty()` | `Difficulty?` | current difficulty, null when the constant is unmapped |
| `difficultyLocked()` | `boolean` | difficulty is locked |

## S2CExplosionPacket

Explosion effect; particle type, sound and the destroyed-block list are not exposed.

| Component | Type | Description |
|---|---|---|
| `x()` | `double` | explosion center x in blocks |
| `y()` | `double` | explosion center y in blocks |
| `z()` | `double` | explosion center z in blocks |
| `radius()` | `float` | explosion radius in blocks |
| `blockCount()` | `int` | number of blocks destroyed |
| `knockbackX()` | `double` | player knockback x in blocks/tick, 0 when absent |
| `knockbackY()` | `double` | player knockback y in blocks/tick, 0 when absent |
| `knockbackZ()` | `double` | player knockback z in blocks/tick, 0 when absent |

## S2CGameJoinPacket

Initial join info for the play phase.

| Component | Type | Description |
|---|---|---|
| `playerEntityId()` | `int` | the local player's entity network id |
| `hardcore()` | `boolean` | hardcore world |
| `dimensionIds()` | `List<String>` | namespaced ids of every dimension on the server |
| `maxPlayers()` | `int` | advertised player slot count |
| `viewDistance()` | `int` | server view distance in chunks |
| `simulationDistance()` | `int` | server simulation distance in chunks |
| `reducedDebugInfo()` | `boolean` | the F3 screen is reduced |
| `showDeathScreen()` | `boolean` | show the death screen instead of respawning at once |
| `doLimitedCrafting()` | `boolean` | crafting needs a recipe-book unlock |
| `enforcesSecureChat()` | `boolean` | server requires signed chat |

## S2CGameStateChangePacket

Game-state change value; the reason is not exposed, so the value alone is ambiguous.

| Component | Type | Description |
|---|---|---|
| `value()` | `float` | reason-specific: gamemode id, rain gradient 0..1, demo screen id |

## S2CGameTestHighlightPosPacket

Game-test debug position highlight.

| Component | Type | Description |
|---|---|---|
| `absoluteX()` | `int` | world-space x |
| `absoluteY()` | `int` | world-space y |
| `absoluteZ()` | `int` | world-space z |
| `relativeX()` | `int` | x relative to the test structure origin |
| `relativeY()` | `int` | y relative to the test structure origin |
| `relativeZ()` | `int` | z relative to the test structure origin |

## S2CLightUpdatePacket

Chunk light data; the light arrays are not exposed.

| Component | Type | Description |
|---|---|---|
| `chunkX()` | `int` | chunk x |
| `chunkZ()` | `int` | chunk z |

## S2CMapUpdatePacket

Filled-map update; pixel colors, icons and the updated rectangle are not exposed.

| Component | Type | Description |
|---|---|---|
| `mapId()` | `int` | numeric map id |
| `scale()` | `byte` | zoom level 0..4, 0 is one block per pixel |
| `locked()` | `boolean` | locked in a cartography table |

## S2CParticlePacket

Particle spawn request; the particle type and its parameters are not exposed.

| Component | Type | Description |
|---|---|---|
| `x()` | `double` | spawn center x in blocks |
| `y()` | `double` | spawn center y in blocks |
| `z()` | `double` | spawn center z in blocks |
| `offsetX()` | `float` | gaussian spread on x in blocks |
| `offsetY()` | `float` | gaussian spread on y in blocks |
| `offsetZ()` | `float` | gaussian spread on z in blocks |
| `speed()` | `float` | particle speed multiplier |
| `count()` | `int` | particle count; 0 turns the offsets into a velocity |
| `forceSpawn()` | `boolean` | ignores the client's particle distance limit |
| `important()` | `boolean` | spawns even on the lowest particle setting |

## S2CPlaySoundFromEntityPacket

Sound anchored to an entity.

| Component | Type | Description |
|---|---|---|
| `sound()` | `String` | namespaced sound event id |
| `category()` | `SoundCategory?` | mixer channel, null when the constant is unmapped |
| `entityId()` | `int` | source entity network id |
| `volume()` | `float` | volume multiplier, 1.0 is nominal |
| `pitch()` | `float` | pitch multiplier, 1.0 is nominal |
| `seed()` | `long` | random seed picking the sound variant |

## S2CPlaySoundPacket

Positional sound.

| Component | Type | Description |
|---|---|---|
| `sound()` | `String` | namespaced sound event id |
| `category()` | `SoundCategory?` | mixer channel, null when the constant is unmapped |
| `x()` | `double` | sound x in blocks, wire value is 1/8-block fixed point |
| `y()` | `double` | sound y in blocks |
| `z()` | `double` | sound z in blocks |
| `volume()` | `float` | volume multiplier, 1.0 is nominal |
| `pitch()` | `float` | pitch multiplier, 1.0 is nominal |
| `seed()` | `long` | random seed picking the sound variant |

## S2CSimulationDistancePacket

Server simulation distance change.

| Component | Type | Description |
|---|---|---|
| `simulationDistance()` | `int` | simulation distance in chunks |

## S2CStartChunkSendPacket

Start of a chunk batch; no components.

## S2CStopSoundPacket

Stops playing sounds.

| Component | Type | Description |
|---|---|---|
| `soundId()` | `String?` | namespaced sound event id, null stops the whole category |
| `category()` | `SoundCategory?` | mixer channel, null means every category |

## S2CTestInstanceBlockStatusPacket

Test instance block status report.

| Component | Type | Description |
|---|---|---|
| `status()` | `String` | plain-text status message |
| `sizeX()` | `Integer?` | test area size x in blocks, null when the packet carries no size |
| `sizeY()` | `Integer?` | test area size y in blocks, null when the packet carries no size |
| `sizeZ()` | `Integer?` | test area size z in blocks, null when the packet carries no size |

## S2CTickStepPacket

How many ticks to step while the world is frozen.

| Component | Type | Description |
|---|---|---|
| `tickSteps()` | `int` | remaining ticks to step |

## S2CUnloadChunkPacket

Chunk removed from the client world.

| Component | Type | Description |
|---|---|---|
| `chunkX()` | `int` | chunk x |
| `chunkZ()` | `int` | chunk z |

## S2CUpdateTickRatePacket

Server tick rate and freeze state.

| Component | Type | Description |
|---|---|---|
| `tickRate()` | `float` | ticks per second, vanilla default 20 |
| `isFrozen()` | `boolean` | world ticking is frozen |

## S2CWaypointPacket

Locator-bar waypoint change; the waypoint id and its data are not exposed.

| Component | Type | Description |
|---|---|---|
| `operation()` | `WaypointOperation?` | track, update or untrack, null when unmapped |

## S2CWorldBorderCenterChangedPacket

World border center moved.

| Component | Type | Description |
|---|---|---|
| `centerX()` | `double` | border center x in blocks |
| `centerZ()` | `double` | border center z in blocks |

## S2CWorldBorderInitializePacket

Full world border state, sent on join.

| Component | Type | Description |
|---|---|---|
| `centerX()` | `double` | border center x in blocks |
| `centerZ()` | `double` | border center z in blocks |
| `size()` | `double` | current border diameter in blocks |
| `sizeLerpTarget()` | `double` | target border diameter in blocks |
| `sizeLerpTime()` | `long` | interpolation duration in milliseconds |
| `maxRadius()` | `int` | absolute world border limit in blocks |
| `warningBlocks()` | `int` | warning overlay distance in blocks |
| `warningTime()` | `int` | warning overlay lead time in seconds |

## S2CWorldBorderInterpolateSizePacket

World border starts resizing over time.

| Component | Type | Description |
|---|---|---|
| `size()` | `double` | current diameter in blocks |
| `sizeLerpTarget()` | `double` | target diameter in blocks |
| `sizeLerpTime()` | `long` | interpolation duration in milliseconds |

## S2CWorldBorderSizeChangedPacket

World border resized instantly.

| Component | Type | Description |
|---|---|---|
| `sizeLerpTarget()` | `double` | new diameter in blocks |

## S2CWorldBorderWarningBlocksChangedPacket

World border warning distance changed.

| Component | Type | Description |
|---|---|---|
| `warningBlocks()` | `int` | warning overlay distance in blocks |

## S2CWorldBorderWarningTimeChangedPacket

World border warning lead time changed.

| Component | Type | Description |
|---|---|---|
| `warningTime()` | `int` | warning overlay lead time in seconds |

## S2CWorldEventPacket

World event — block break sound and particles, door, portal, dispenser.

| Component | Type | Description |
|---|---|---|
| `eventId()` | `int` | vanilla WorldEvents id |
| `x()` | `int` | event block x |
| `y()` | `int` | event block y |
| `z()` | `int` | event block z |
| `data()` | `int` | event-specific parameter, often a packed block state id |
| `global()` | `boolean` | audible across the dimension regardless of distance |

## S2CWorldTimeUpdatePacket

World time sync.

| Component | Type | Description |
|---|---|---|
| `time()` | `long` | total world age in ticks |
| `timeOfDay()` | `long` | time of day in ticks, 0..23999 per day |
| `tickDayTime()` | `boolean` | the daylight cycle is advancing (`doDaylightCycle`) |

---

# Screen and chat packets

Server-to-client records about screen handlers, inventories, trades, the recipe book, chat, titles, the tab list, the scoreboard and connection housekeeping. All 63 arrive through `PacketReceiveEvent` and none of them can be sent; text in them is a plain string, an item is a namespaced id plus a count, and an enum component is `null` when the vanilla constant has no same-named twin — [Packets](https://docs.nursultan.fun/scripting/actions/packets).

```kotlin
on<PacketReceiveEvent> { e ->
    val packet = e.packet()
    if (packet !is S2CScreenHandlerSlotUpdatePacket) return@on
    if (packet.item() == "minecraft:air") return@on

    log.info("slot ${packet.slot()}: ${packet.item()} x${packet.count()}")
}
```

## S2CAdvancementUpdatePacket

Advancement list sync; the earned and progress maps and the display data are not exposed.

| Component | Type | Description |
|---|---|---|
| `clearCurrent()` | `boolean` | replace the whole advancement set instead of merging |
| `toRemove()` | `List<String>` | namespaced ids of the removed advancements |
| `showToast()` | `boolean` | show the toast for newly earned advancements |

## S2CBossBarPacket

Boss bar added, removed or updated; title, percent, colour and style are not exposed.

| Component | Type | Description |
|---|---|---|
| `uuid()` | `String` | boss bar uuid string |
| `action()` | `BossBarAction?` | which field group this packet changes |

## S2CBundleDelimiterPacket

Marks the boundary of a packet bundle. No components.

## S2CBundlePacket

Packet bundle wrapper; each contained packet fires its own event. No components.

## S2CChatMessagePacket

Signed player chat; the signed body text and the signature data are not exposed.

| Component | Type | Description |
|---|---|---|
| `globalIndex()` | `int` | server-wide message index |
| `sender()` | `String` | sender uuid string |
| `index()` | `int` | per-sender message index |
| `unsignedContent()` | `String?` | server-modified display text, null when the signed body is shown |

## S2CChatSuggestionsPacket

Server-driven chat completion list.

| Component | Type | Description |
|---|---|---|
| `action()` | `ChatSuggestionAction?` | add, remove or replace the list |
| `entries()` | `List<String>` | suggestion strings |

## S2CClearDialogPacket

Closes the open server dialog. No components.

## S2CClearTitlePacket

Clears the title and the subtitle.

| Component | Type | Description |
|---|---|---|
| `reset()` | `boolean` | also reset the fade-in, stay and fade-out timings |

## S2CCloseScreenPacket

The server closes a screen handler.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | screen handler sync id, 0 is the player inventory |

## S2CCommandSuggestionsPacket

Tab-completion reply; the suggestion tooltips are not exposed.

| Component | Type | Description |
|---|---|---|
| `id()` | `int` | completion id matching the request |
| `start()` | `int` | start index of the replaced range in the input |
| `length()` | `int` | length of the replaced range |
| `suggestions()` | `List<String>` | completion texts |

## S2CCommandTreePacket

Brigadier command tree; the tree itself is not exposed. No components.

## S2CCommonPingPacket

Server ping; the client answers with `C2SCommonPongPacket`.

| Component | Type | Description |
|---|---|---|
| `parameter()` | `int` | value to echo back |

## S2CCookieRequestPacket

The server asks for a stored cookie.

| Component | Type | Description |
|---|---|---|
| `key()` | `String` | namespaced cookie id |

## S2CCooldownUpdatePacket

Item-use cooldown set or cleared.

| Component | Type | Description |
|---|---|---|
| `cooldownGroup()` | `String` | namespaced cooldown group id |
| `cooldown()` | `int` | cooldown length in ticks, 0 clears it |

## S2CCraftFailedResponsePacket

A recipe-book craft request was rejected.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | screen handler sync id of the rejected request |

## S2CCustomPayloadPacket

Plugin-channel message; the payload bytes are not exposed.

| Component | Type | Description |
|---|---|---|
| `channel()` | `String` | namespaced channel id |

## S2CCustomReportDetailsPacket

Key/value details the server wants attached to crash reports.

| Component | Type | Description |
|---|---|---|
| `details()` | `Map<String, String>` | immutable copy of the detail entries |

## S2CDebugSamplePacket

Debug profiler sample push.

| Component | Type | Description |
|---|---|---|
| `sample()` | `List<Long>` | raw sample values, meaning depends on `debugSampleType()` |
| `debugSampleType()` | `DebugSampleType?` | which profiler produced the sample |

## S2CDisconnectPacket

The server disconnects the client.

| Component | Type | Description |
|---|---|---|
| `reason()` | `String` | plain-text disconnect reason |

## S2CEnterReconfigurationPacket

The connection moves to the configuration phase. No components.

## S2CEventDebugPacket

Debug event push; no fields are exposed. No components.

## S2CGameMessagePacket

System message; player chat arrives as `S2CChatMessagePacket` instead.

| Component | Type | Description |
|---|---|---|
| `content()` | `String` | plain-text message |
| `overlay()` | `boolean` | draw on the action bar instead of the chat log |

## S2CInventoryPacket

Full contents resend for one screen handler.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | screen handler sync id, 0 is the player inventory |
| `revision()` | `int` | handler state revision |
| `contents()` | `List<Stack>` | slot contents in slot order |
| `cursorItem()` | `String` | namespaced item id on the cursor, `minecraft:air` when empty |
| `cursorCount()` | `int` | cursor stack size |

### S2CInventoryPacket.Stack

One entry of `contents()`.

| Component | Type | Description |
|---|---|---|
| `item()` | `String` | namespaced item id, `minecraft:air` when empty |
| `count()` | `int` | stack size |

## S2CKeepAlivePacket

Keep-alive; the client echoes the id back in `C2SKeepAlivePacket`.

| Component | Type | Description |
|---|---|---|
| `id()` | `long` | keep-alive id to echo back |

## S2CNbtQueryResponsePacket

Reply to `C2SQueryBlockNbtPacket` or `C2SQueryEntityNbtPacket`.

| Component | Type | Description |
|---|---|---|
| `transactionId()` | `int` | id matching the request |
| `nbt()` | `String` | SNBT text of the result, empty when the query returned nothing |

## S2COpenMountScreenPacket

Opens the horse or mount inventory screen.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | screen handler sync id |
| `slotColumnCount()` | `int` | number of chest slot columns |
| `mountId()` | `int` | mount entity network id |

## S2COpenScreenPacket

Opens a container screen.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | screen handler sync id |
| `screenHandler()` | `String` | namespaced screen handler type id |
| `name()` | `String` | plain-text window title |

## S2COpenWrittenBookPacket

Opens the written-book reader for the held book.

| Component | Type | Description |
|---|---|---|
| `hand()` | `Hand?` | hand holding the book — [Inventory and items](https://docs.nursultan.fun/scripting/game/inventory) |

## S2COverlayMessagePacket

Action bar text.

| Component | Type | Description |
|---|---|---|
| `text()` | `String` | plain-text action bar message |

## S2CPlayerListHeaderPacket

Tab-list header and footer.

| Component | Type | Description |
|---|---|---|
| `header()` | `String` | plain-text header |
| `footer()` | `String` | plain-text footer |

## S2CPlayerListPacket

Tab-list update; the per-player entries are not exposed, only which fields changed.

| Component | Type | Description |
|---|---|---|
| `actions()` | `List<PlayerListAction>` | field groups this packet carries, unmapped constants dropped |

## S2CPlayerRemovePacket

Players removed from the tab list.

| Component | Type | Description |
|---|---|---|
| `profileIds()` | `List<String>` | removed player uuid strings |

## S2CProfilelessChatMessagePacket

Chat message with no player profile behind it: console output, command output.

| Component | Type | Description |
|---|---|---|
| `message()` | `String` | plain-text message |

## S2CRecipeBookAddPacket

Recipe-book entries added; the entries themselves are not exposed.

| Component | Type | Description |
|---|---|---|
| `replace()` | `boolean` | replace the whole known-recipe set instead of merging |

## S2CRecipeBookRemovePacket

Recipe-book entries removed.

| Component | Type | Description |
|---|---|---|
| `recipes()` | `List<Integer>` | removed network recipe indices |

## S2CRecipeBookSettingsPacket

Per-category recipe-book UI settings; no fields are exposed. No components.

## S2CRemoveMessagePacket

The server deletes a chat message it sent; the signature is not exposed. No components.

## S2CResourcePackRemovePacket

Removes a server resource pack.

| Component | Type | Description |
|---|---|---|
| `id()` | `String?` | pack uuid string, null removes every server pack |

## S2CResourcePackSendPacket

The server offers a resource pack.

| Component | Type | Description |
|---|---|---|
| `id()` | `String` | pack uuid string |
| `url()` | `String` | download URL |
| `hash()` | `String` | SHA-1 hex digest of the pack, empty when not provided |
| `required()` | `boolean` | declining disconnects the client |
| `prompt()` | `String?` | plain-text prompt shown in the dialog |

## S2CScoreboardDisplayPacket

Assigns an objective to a display slot.

| Component | Type | Description |
|---|---|---|
| `slot()` | `ScoreboardSlot?` | sidebar, tab list or below-name slot |
| `name()` | `String?` | objective name, null clears the slot |

## S2CScoreboardObjectiveUpdatePacket

Objective created, removed or updated; the number format is not exposed.

| Component | Type | Description |
|---|---|---|
| `name()` | `String` | internal objective name |
| `displayName()` | `String` | plain-text display title |
| `type()` | `ScoreboardRenderType?` | number or hearts rendering |
| `mode()` | `int` | 0 add, 1 remove, 2 update |

## S2CScoreboardScoreResetPacket

Removes score entries.

| Component | Type | Description |
|---|---|---|
| `scoreHolderName()` | `String` | score holder, a player name or a selector result |
| `objectiveName()` | `String?` | objective to clear, null clears the holder everywhere |

## S2CScoreboardScoreUpdatePacket

Score value set; the number format is not exposed.

| Component | Type | Description |
|---|---|---|
| `scoreHolderName()` | `String` | score holder name |
| `objectiveName()` | `String` | objective name |
| `score()` | `int` | new score value |
| `display()` | `String?` | plain-text override for the displayed line |

## S2CScreenHandlerPropertyUpdatePacket

One screen handler property: furnace progress, enchantment levels, beacon effect.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | screen handler sync id |
| `propertyId()` | `int` | handler-specific property index |
| `value()` | `int` | new property value |

## S2CScreenHandlerSlotUpdatePacket

One slot's contents changed.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | screen handler sync id, -1 targets the cursor stack |
| `revision()` | `int` | handler state revision |
| `slot()` | `int` | slot index |
| `item()` | `String` | namespaced item id, `minecraft:air` when empty |
| `count()` | `int` | stack size |

## S2CSelectAdvancementTabPacket

The server switches the open advancement tab.

| Component | Type | Description |
|---|---|---|
| `tabId()` | `String?` | namespaced advancement tab id, null deselects |

## S2CServerLinksPacket

Server-provided links; the link labels are not exposed.

| Component | Type | Description |
|---|---|---|
| `links()` | `List<String>` | link URLs |

## S2CServerMetadataPacket

In-play server metadata; the favicon bytes are not exposed.

| Component | Type | Description |
|---|---|---|
| `description()` | `String` | plain-text MOTD |

## S2CServerTransferPacket

The server tells the client to connect elsewhere.

| Component | Type | Description |
|---|---|---|
| `host()` | `String` | target hostname or address |
| `port()` | `int` | target port |

## S2CSetCursorItemPacket

Sets the stack held on the mouse cursor.

| Component | Type | Description |
|---|---|---|
| `item()` | `String` | namespaced item id, `minecraft:air` when empty |
| `count()` | `int` | stack size |

## S2CSetPlayerInventoryPacket

Sets one player-inventory slot outside any open handler.

| Component | Type | Description |
|---|---|---|
| `slot()` | `int` | player inventory slot index |
| `item()` | `String` | namespaced item id, `minecraft:air` when empty |
| `count()` | `int` | stack size |

## S2CSetTradeOffersPacket

Villager or wandering-trader offer list.

| Component | Type | Description |
|---|---|---|
| `syncId()` | `int` | merchant screen handler sync id |
| `levelProgress()` | `int` | merchant level, 1..5 |
| `experience()` | `int` | merchant experience points |
| `leveled()` | `boolean` | merchant can level up, false for a wandering trader |
| `refreshable()` | `boolean` | offers restock over time |
| `offers()` | `List<Offer>` | trades in display order |

### S2CSetTradeOffersPacket.Offer

One trade.

| Component | Type | Description |
|---|---|---|
| `buyItem()` | `String` | namespaced first input id, after price adjustment |
| `buyCount()` | `int` | first input stack size, after price adjustment |
| `secondBuyItem()` | `String?` | namespaced second input id, null on one-input trades |
| `secondBuyCount()` | `int` | second input stack size, 0 when absent |
| `sellItem()` | `String` | namespaced output item id |
| `sellCount()` | `int` | output stack size |
| `uses()` | `int` | times this trade has been used |
| `maxUses()` | `int` | uses before the trade locks |
| `disabled()` | `boolean` | trade is currently locked out |

## S2CShowDialogPacket

Opens a server dialog; the dialog contents are not exposed. No components.

## S2CSignEditorOpenPacket

Opens the sign text editor.

| Component | Type | Description |
|---|---|---|
| `x()` | `int` | sign block x |
| `y()` | `int` | sign block y |
| `z()` | `int` | sign block z |
| `front()` | `boolean` | true edits the front face, false the back |

## S2CStatisticsPacket

Statistics screen data.

| Component | Type | Description |
|---|---|---|
| `stats()` | `List<Stat>` | statistic entries |

### S2CStatisticsPacket.Stat

One statistic.

| Component | Type | Description |
|---|---|---|
| `stat()` | `String` | stat type and value joined, e.g. `minecraft:mined:minecraft:stone` |
| `value()` | `int` | raw counter, time stats in ticks, distance stats in cm |

## S2CStoreCookiePacket

The server stores a cookie on the client; the payload bytes are not exposed.

| Component | Type | Description |
|---|---|---|
| `key()` | `String` | namespaced cookie id |

## S2CSubtitlePacket

Title subtitle line.

| Component | Type | Description |
|---|---|---|
| `text()` | `String` | plain-text subtitle |

## S2CSynchronizeRecipesPacket

Recipe registry sync; the recipes are not exposed. No components.

## S2CSynchronizeTagsPacket

Registry tag sync; the tags are not exposed. No components.

## S2CTeamPacket

Scoreboard team created, updated or removed, or members added to it and removed from it.

| Component | Type | Description |
|---|---|---|
| `teamName()` | `String` | internal team name |
| `playerNames()` | `List<String>` | affected member names, empty on a pure team update |
| `teamOperation()` | `TeamOperation?` | what happens to the team itself |
| `playerListOperation()` | `TeamPlayerListOperation?` | what happens to the member list |
| `displayName()` | `String?` | plain-text team display name |
| `prefix()` | `String?` | plain-text name prefix |
| `suffix()` | `String?` | plain-text name suffix |
| `friendlyFlags()` | `Integer?` | bitmask, 1 friendly fire, 2 see invisible teammates |
| `color()` | `Formatting?` | team colour formatting code |
| `nameTagVisibilityRule()` | `TeamVisibilityRule?` | when nametags render |
| `collisionRule()` | `TeamCollisionRule?` | when entities collide |

The seven detail components from `displayName()` down are null unless the packet carries team data, that is on create and update.

## S2CTitleFadePacket

Title animation timings.

| Component | Type | Description |
|---|---|---|
| `fadeInTicks()` | `int` | fade-in duration in ticks |
| `stayTicks()` | `int` | hold duration in ticks |
| `fadeOutTicks()` | `int` | fade-out duration in ticks |

## S2CTitlePacket

Title main line.

| Component | Type | Description |
|---|---|---|
| `text()` | `String` | plain-text title |

## S2CUpdateSelectedSlotPacket

The server forces the hotbar selection.

| Component | Type | Description |
|---|---|---|
| `slot()` | `int` | hotbar index 0..8 |

---

# Packet enums

34 enums, 180 constants, used as field types on the packet records in [Packets](https://docs.nursultan.fun/scripting/actions/packets). Conversion is by constant name in both directions: a vanilla constant with no twin here decodes to `null`, and a constant with no vanilla twin makes the send fail.

```kotlin
on<PacketSendEvent> { e ->
    val packet = e.packet()
    if (packet !is C2SPlayerInteractEntityPacket) return@on
    if (packet.type() == InteractType.ATTACK) {
        log.info("attacked entity ${packet.entityId()}")
    }
}
```

Inside a `List<...>` field an unmapped constant is dropped from the list instead of becoming `null`.
`InteractType` is the one exception to name matching: it is rebuilt through the vanilla `PlayerInteractEntityC2SPacket.Handler` visitor on decode and branched on when sending.

## AdvancementTabAction

Field of `C2SAdvancementTabPacket`, vanilla `AdvancementTabC2SPacket.Action`. Decode only — that packet has no send builder.

| Constant | Description |
|---|---|
| `OPENED_TAB` | an advancement tab was opened |
| `CLOSED_SCREEN` | the advancements screen was closed |

## BlockMirror

Field of `C2SUpdateStructureBlockPacket`, vanilla `net.minecraft.util.BlockMirror`.

| Constant | Description |
|---|---|
| `NONE` | no mirroring |
| `LEFT_RIGHT` | mirrored across the left-right axis |
| `FRONT_BACK` | mirrored across the front-back axis |

## BlockRotation

Field of `C2SUpdateStructureBlockPacket`, vanilla `net.minecraft.util.BlockRotation`.

| Constant | Description |
|---|---|
| `NONE` | 0 degrees |
| `CLOCKWISE_90` | 90 degrees clockwise |
| `CLOCKWISE_180` | 180 degrees |
| `COUNTERCLOCKWISE_90` | 90 degrees counter-clockwise, 270 clockwise |

## BossBarAction

Field of `S2CBossBarPacket`, vanilla `BossBarS2CPacket.Type`.

| Constant | Description |
|---|---|
| `ADD` | new boss bar created |
| `REMOVE` | boss bar removed |
| `UPDATE_PROGRESS` | fill fraction changed, 0..1 |
| `UPDATE_NAME` | title text changed |
| `UPDATE_STYLE` | bar colour and notch division changed |
| `UPDATE_PROPERTIES` | darken-sky, dragon-music and fog flags changed |

## ChatSuggestionAction

Field of `S2CChatSuggestionsPacket`, vanilla `ChatSuggestionsS2CPacket.Action`.

| Constant | Description |
|---|---|
| `ADD` | append the entries to the current list |
| `REMOVE` | remove the entries from the list |
| `SET` | replace the whole list with the entries |

## ChatVisibility

Field of `C2SClientOptionsPacket`, vanilla `net.minecraft.network.message.ChatVisibility`.

| Constant | Description |
|---|---|
| `FULL` | all chat shown |
| `SYSTEM` | only system and command output shown |
| `HIDDEN` | chat hidden |

## ClientCommand

Field of `C2SClientCommandPacket`, vanilla `ClientCommandC2SPacket.Mode`.

| Constant | Description |
|---|---|
| `STOP_SLEEPING` | leave the bed |
| `START_SPRINTING` | begin sprinting |
| `STOP_SPRINTING` | end sprinting |
| `START_RIDING_JUMP` | begin charging a horse jump |
| `STOP_RIDING_JUMP` | release the horse jump |
| `OPEN_INVENTORY` | open the ridden entity's inventory |
| `START_FALL_FLYING` | start elytra flight |

The send builder re-attaches the local player as the packet's entity, so the send fails while `game.player()` is absent.

## ClientStatus

Field of `C2SClientStatusPacket`, vanilla `ClientStatusC2SPacket.Mode`.

| Constant | Description |
|---|---|
| `PERFORM_RESPAWN` | respawn after death |
| `REQUEST_STATS` | request statistics screen data |

## CommandBlockType

Field of `C2SUpdateCommandBlockPacket`, vanilla `CommandBlockBlockEntity.Type`.

| Constant | Description |
|---|---|
| `SEQUENCE` | chain command block |
| `AUTO` | repeating command block |
| `REDSTONE` | impulse command block |

## DebugSampleType

Field of `S2CDebugSamplePacket`, vanilla `net.minecraft.util.profiler.DebugSampleType`.

| Constant | Description |
|---|---|
| `TICK_TIME` | server tick timings, nanoseconds, in the packet's number list |

## Difficulty

Field of `C2SUpdateDifficultyPacket` and `S2CDifficultyPacket`, vanilla `net.minecraft.world.Difficulty`.

| Constant | Description |
|---|---|
| `PEACEFUL` | id 0, no hostile mobs |
| `EASY` | id 1 |
| `NORMAL` | id 2 |
| `HARD` | id 3 |

## EntityAnchor

Field of `S2CLookAtPacket`, vanilla `EntityAnchorArgumentType.EntityAnchor`.

| Constant | Description |
|---|---|
| `FEET` | anchor at the entity's feet, y offset 0 |
| `EYES` | anchor at the entity's eye height |

## Formatting

Team colour in `S2CTeamPacket`, vanilla `net.minecraft.util.Formatting`.

| Constant | Description |
|---|---|
| `BLACK` | colour, code `0` |
| `DARK_BLUE` | colour, code `1` |
| `DARK_GREEN` | colour, code `2` |
| `DARK_AQUA` | colour, code `3` |
| `DARK_RED` | colour, code `4` |
| `DARK_PURPLE` | colour, code `5` |
| `GOLD` | colour, code `6` |
| `GRAY` | colour, code `7` |
| `DARK_GRAY` | colour, code `8` |
| `BLUE` | colour, code `9` |
| `GREEN` | colour, code `a` |
| `AQUA` | colour, code `b` |
| `RED` | colour, code `c` |
| `LIGHT_PURPLE` | colour, code `d` |
| `YELLOW` | colour, code `e` |
| `WHITE` | colour, code `f` |
| `OBFUSCATED` | style, code `k` |
| `BOLD` | style, code `l` |
| `STRIKETHROUGH` | style, code `m` |
| `UNDERLINE` | style, code `n` |
| `ITALIC` | style, code `o` |
| `RESET` | style, code `r`; as a team colour means no colour |

## InteractType

Which of the three variants `C2SPlayerInteractEntityPacket` carries; rebuilt through the vanilla visitor, not by name.

| Constant | Description |
|---|---|
| `INTERACT` | right-click on entity; `hand` set, hit coordinates null |
| `INTERACT_AT` | right-click at a point; `hand` and hit coordinates set |
| `ATTACK` | left-click attack; `hand` and hit coordinates null |

## JigsawJoint

Field of `C2SUpdateJigsawPacket`, vanilla `JigsawBlockEntity.Joint`. Decode only — that packet has no send builder.

| Constant | Description |
|---|---|
| `ROLLABLE` | attached piece may rotate about the connection axis |
| `ALIGNED` | attached piece keeps a fixed orientation |

## ParticlesMode

Field of `C2SClientOptionsPacket`, vanilla `net.minecraft.particle.ParticlesMode`.

| Constant | Description |
|---|---|
| `ALL` | all particles |
| `DECREASED` | reduced particles |
| `MINIMAL` | minimal particles |

## PlayerAction

Field of `C2SPlayerActionPacket`, vanilla `PlayerActionC2SPacket.Action`.

| Constant | Description |
|---|---|
| `START_DESTROY_BLOCK` | begin breaking the block at the packet position |
| `ABORT_DESTROY_BLOCK` | cancel the in-progress break |
| `STOP_DESTROY_BLOCK` | finish breaking the block |
| `DROP_ALL_ITEMS` | drop the whole held stack |
| `DROP_ITEM` | drop one item from the held stack |
| `RELEASE_USE_ITEM` | release a charged or held-use item |
| `SWAP_ITEM_WITH_OFFHAND` | swap main hand and off hand |
| `STAB` | mace and spear stab, added in 1.21.11 |

## PlayerListAction

`S2CPlayerListPacket` carries a `List<PlayerListAction>`, vanilla `PlayerListS2CPacket.Action`.

| Constant | Description |
|---|---|
| `ADD_PLAYER` | new profile entry, name and skin properties |
| `INITIALIZE_CHAT` | chat session and public key data |
| `UPDATE_GAME_MODE` | game mode changed |
| `UPDATE_LISTED` | shown or hidden in the tab list |
| `UPDATE_LATENCY` | ping in ms changed |
| `UPDATE_DISPLAY_NAME` | tab-list display name changed |
| `UPDATE_LIST_ORDER` | explicit sort order changed |
| `UPDATE_HAT` | hat layer visibility changed |

## PositionFlag

`S2CEntityPositionPacket` carries a `List<PositionFlag>`, vanilla `net.minecraft.network.packet.s2c.play.PositionFlag`.

| Constant | Description |
|---|---|
| `X` | x is relative to the current x |
| `Y` | y is relative |
| `Z` | z is relative |
| `Y_ROT` | yaw is relative, degrees |
| `X_ROT` | pitch is relative, degrees |
| `DELTA_X` | x velocity is relative |
| `DELTA_Y` | y velocity is relative |
| `DELTA_Z` | z velocity is relative |
| `ROTATE_DELTA` | existing velocity is rotated by the rotation delta |

## RecipeBookCategory

Field of `C2SRecipeCategoryOptionsPacket`, vanilla `net.minecraft.recipe.book.RecipeBookType`.

| Constant | Description |
|---|---|
| `CRAFTING` | crafting table and inventory book |
| `FURNACE` | furnace book |
| `BLAST_FURNACE` | blast furnace book |
| `SMOKER` | smoker book |

## ResourcePackStatus

Field of `C2SResourcePackStatusPacket`, vanilla `ResourcePackStatusC2SPacket.Status`. Decode only — that packet has no send builder.

| Constant | Description |
|---|---|
| `SUCCESSFULLY_LOADED` | pack applied |
| `DECLINED` | user refused the pack |
| `FAILED_DOWNLOAD` | download failed |
| `ACCEPTED` | user accepted, download starting |
| `DOWNLOADED` | download finished, not yet applied |
| `INVALID_URL` | pack url could not be parsed |
| `FAILED_RELOAD` | resource reload failed after applying |
| `DISCARDED` | pack dropped without being applied |

## ScoreboardRenderType

Field of `S2CScoreboardObjectiveUpdatePacket`, vanilla `ScoreboardCriterion.RenderType`.

| Constant | Description |
|---|---|
| `INTEGER` | score drawn as a number |
| `HEARTS` | score drawn as hearts |

## ScoreboardSlot

Field of `S2CScoreboardDisplayPacket`, vanilla `net.minecraft.scoreboard.ScoreboardDisplaySlot`.

| Constant | Description |
|---|---|
| `LIST` | tab list |
| `SIDEBAR` | generic sidebar |
| `BELOW_NAME` | under the player's nametag |
| `TEAM_BLACK` | sidebar shown only to the black team |
| `TEAM_DARK_BLUE` | sidebar for the dark blue team |
| `TEAM_DARK_GREEN` | sidebar for the dark green team |
| `TEAM_DARK_AQUA` | sidebar for the dark aqua team |
| `TEAM_DARK_RED` | sidebar for the dark red team |
| `TEAM_DARK_PURPLE` | sidebar for the dark purple team |
| `TEAM_GOLD` | sidebar for the gold team |
| `TEAM_GRAY` | sidebar for the gray team |
| `TEAM_DARK_GRAY` | sidebar for the dark gray team |
| `TEAM_BLUE` | sidebar for the blue team |
| `TEAM_GREEN` | sidebar for the green team |
| `TEAM_AQUA` | sidebar for the aqua team |
| `TEAM_RED` | sidebar for the red team |
| `TEAM_LIGHT_PURPLE` | sidebar for the light purple team |
| `TEAM_YELLOW` | sidebar for the yellow team |
| `TEAM_WHITE` | sidebar for the white team |

## SlotActionType

Field of `C2SClickSlotPacket`, vanilla `net.minecraft.screen.slot.SlotActionType`. Decode only — that packet has no send builder.

| Constant | Description |
|---|---|
| `PICKUP` | normal left or right click pickup and place |
| `QUICK_MOVE` | shift-click transfer |
| `SWAP` | hotbar or offhand swap; `button` is the hotbar index, 40 = offhand |
| `CLONE` | creative middle-click clone |
| `THROW` | drop key; `button` 0 = one item, 1 = whole stack |
| `QUICK_CRAFT` | drag-distribute across slots |
| `PICKUP_ALL` | double-click collect of matching items |

## SoundCategory

Field of `S2CPlaySoundPacket`, `S2CPlaySoundFromEntityPacket` and `S2CStopSoundPacket`, vanilla `net.minecraft.sound.SoundCategory`.

| Constant | Description |
|---|---|
| `MASTER` | master channel |
| `MUSIC` | background music |
| `RECORDS` | jukebox and note blocks |
| `WEATHER` | rain and thunder |
| `BLOCKS` | block sounds |
| `HOSTILE` | hostile mob sounds |
| `NEUTRAL` | friendly mob sounds |
| `PLAYERS` | player sounds |
| `AMBIENT` | ambient and environment |
| `VOICE` | voice and speech |
| `UI` | interface sounds |

## StructureBlockAction

Field of `C2SUpdateStructureBlockPacket`, vanilla `StructureBlockBlockEntity.Action`.

| Constant | Description |
|---|---|
| `UPDATE_DATA` | write the settings without acting |
| `SAVE_AREA` | save the selected region to the template |
| `LOAD_AREA` | place the template into the world |
| `SCAN_AREA` | detect structure bounds from the corner blocks |

## StructureBlockMode

Field of `C2SUpdateStructureBlockPacket`, vanilla `net.minecraft.block.enums.StructureBlockMode`.

| Constant | Description |
|---|---|
| `SAVE` | save mode |
| `LOAD` | load mode |
| `CORNER` | corner marker mode |
| `DATA` | data marker mode |

## TeamCollisionRule

Field of `S2CTeamPacket`, null when the packet carries no team info, vanilla `AbstractTeam.CollisionRule`.

| Constant | Description |
|---|---|
| `ALWAYS` | always collides |
| `NEVER` | never collides |
| `PUSH_OTHER_TEAMS` | collides only with members of other teams |
| `PUSH_OWN_TEAM` | collides only with own team members |

## TeamOperation

What `S2CTeamPacket` does to the team itself, vanilla `TeamS2CPacket.Operation`.

| Constant | Description |
|---|---|
| `ADD` | team created or its info updated |
| `REMOVE` | team deleted |

## TeamPlayerListOperation

What `S2CTeamPacket` does to the team's member list; the same vanilla `TeamS2CPacket.Operation` on a separate field.

| Constant | Description |
|---|---|
| `ADD` | the listed players joined the team |
| `REMOVE` | the listed players left the team |

## TeamVisibilityRule

Field of `S2CTeamPacket`, null when the packet carries no team info, vanilla `AbstractTeam.VisibilityRule`.

| Constant | Description |
|---|---|
| `ALWAYS` | nametags always visible |
| `NEVER` | nametags never visible |
| `HIDE_FOR_OTHER_TEAMS` | hidden from players not on the team |
| `HIDE_FOR_OWN_TEAM` | hidden from the team's own members |

## TestBlockMode

Field of `C2SSetTestBlockPacket`, vanilla `net.minecraft.block.enums.TestBlockMode`.

| Constant | Description |
|---|---|
| `START` | starts the test run |
| `LOG` | logs its message when powered |
| `FAIL` | fails the test when powered |
| `ACCEPT` | marks the test passed when powered |

## TestInstanceBlockAction

Field of `C2STestInstanceBlockActionPacket`, vanilla `TestInstanceBlockActionC2SPacket.Action`. Decode only — that packet has no send builder.

| Constant | Description |
|---|---|
| `INIT` | create the test structure area |
| `QUERY` | ask the server for the block's current state |
| `SET` | write the edited settings |
| `RESET` | reset the test instance |
| `SAVE` | save the test structure |
| `EXPORT` | export the structure to a file |
| `RUN` | run the test |

## WaypointOperation

What `S2CWaypointPacket` does to a tracked waypoint on the locator bar, vanilla `WaypointS2CPacket.Operation`.

| Constant | Description |
|---|---|
| `TRACK` | start tracking a waypoint |
| `UNTRACK` | stop tracking a waypoint |
| `UPDATE` | update an already tracked waypoint |

---

# Prediction

`prediction` is `client.prediction()`. It simulates the local player forward on a shadow entity that copies the player's movement attributes, and it simulates projectile flight from the last sent position.

```kotlin
on<Render3DEvent> { e ->
    val fall = prediction.path(10) { it.onGround() }   // stops on the first grounded tick
    val landing = fall.last().position()
    e.render().box(Box.around(landing, 0.2), Colors.RED, true)
}
```

## Simulating movement

| Method | Type | Description |
|---|---|---|
| `prediction.after(ticks)` | `PredictionResult` | state after `ticks` simulated ticks, live keyboard input |
| `prediction.after(ticks, input)` | `PredictionResult` | same, with `input` held for every simulated tick |
| `prediction.path(ticks)` | `List<PredictionResult>` | one immutable entry per simulated tick, tick 0 excluded |
| `prediction.path(ticks, input)` | `List<PredictionResult>` | same, with a fixed input |
| `prediction.path(ticks, until)` | `List<PredictionResult>` | stops after the first entry matching `until`, that entry included |
| `prediction.path(ticks, input, until)` | `List<PredictionResult>` | fixed input plus stop predicate |

`ticks` is 1..100 on every method; movement runs on a shadow entity copying movement speed, sneak speed, jump strength, gravity, step height and movement efficiency.
All six need a world and the client thread (main thread only); an out-of-range `ticks` throws `ScriptException`, a call from inside a `path` predicate throws `ScriptStateException`.

## One simulated tick

| Method | Type | Description |
|---|---|---|
| `result.position()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math#vec) | predicted feet position in world blocks |
| `result.velocity()` | [`Vec`](https://docs.nursultan.fun/scripting/game/math#vec) | predicted velocity in blocks per tick |
| `result.box()` | [`Box`](https://docs.nursultan.fun/scripting/game/math#box) | predicted bounding box in world coordinates |
| `result.onGround()` | `boolean` | predicted on-ground flag |
| `result.inWater()` | `boolean` | predicted touching-water flag |
| `result.sneaking()` | `boolean` | sneak state used for this tick |
| `result.sprinting()` | `boolean` | sprint state used for this tick |
| `result.jumping()` | `boolean` | jump input used for this tick |
| `result.fallDistanceBlocks()` | `double` | accumulated fall distance in blocks |

## The input

| Method | Type | Description |
|---|---|---|
| `moveInput(forward, backward, left, right, jump, sneak, sprint)` | `MoveInput` | builds the input record, every argument defaults to `false` |
| `MoveInput.NONE` | `MoveInput` | all seven flags false |
| `input.forward()` | `boolean` | forward key held |
| `input.backward()` | `boolean` | backward key held |
| `input.left()` | `boolean` | strafe-left key held |
| `input.right()` | `boolean` | strafe-right key held |
| `input.jump()` | `boolean` | jump key held |
| `input.sneak()` | `boolean` | sneak key held |
| `input.sprint()` | `boolean` | sprint key held |
| `input.copy(forward, backward, left, right, jump, sneak, sprint)` | `MoveInput` | copy with named overrides, defaults read from the receiver |

`MoveInputEvent.toInput()` returns the keys currently held — see [Event list](https://docs.nursultan.fun/scripting/events/reference).

## Projectiles

| Method | Type | Description |
|---|---|---|
| `prediction.projectile(kind)` | `ProjectilePath` | trajectory on the last sent rotation, kind's default power |
| `prediction.projectile(kind, aim)` | `ProjectilePath` | `aim` null means the last sent rotation, kind's default power |
| `prediction.projectile(kind, aim, power)` | `ProjectilePath` | explicit launch power |
| `path.points()` | `List<Vec>` | trajectory positions, one per tick, from the launch point |
| `path.lands()` | `boolean` | a block or entity hit was found |
| `path.landingPosition()` | `Vec?` | position of the hit, null when nothing was hit |
| `path.hitEntity()` | [`Entity?`](https://docs.nursultan.fun/scripting/game/entities) | entity struck at the landing point, else null |
| `path.hitsBlock()` | `boolean` | the landing hit is a block |
| `path.flightTicks()` | `int` | `points().size() - 1`, minimum 0 |

Origin is the last sent position plus eye height, the launch velocity includes the player's current movement, and `aim` is a [`Rotation`](https://docs.nursultan.fun/scripting/game/math#rotation).
All three need a world and the client thread (main thread only); a null `kind` or `power` at or below 0 throws `ScriptException`.

### ProjectileKind

| Constant | Description |
|---|---|
| `ARROW` | arrow physics, default power 3.0 |
| `TRIDENT` | trident physics, default power 2.5 |
| `ENDER_PEARL` | ender pearl physics, default power 1.5 |
| `SPLASH_POTION` | splash potion physics, default power 0.5, aim pitch -20° |
| `SNOWBALL` | snowball physics, default power 1.5 |
| `WIND_CHARGE` | wind charge physics, default power 1.5 |

---

# Interface

Your own graphics on screen and in the world, shaders, and messages.

---

# 2D render

`Render2DEvent` hands you a drawing surface — `e.render()`. Coordinates are framebuffer pixels, not GUI-scaled units, and every call queues a command flushed after all handlers ran, so call order is draw order.

```kotlin
on<Render2DEvent> { e ->
    val r = e.render()
    val label = "fps " + client.fps()
    val w = r.textWidth(label, 10f) + 12f
    r.blur(8f, 8f, w, 22f, 12f, Colors.rgba(0, 0, 0, 160), 6f)
    r.roundedRect(8f, 8f, w, 22f, 6f, Colors.rgba(10, 12, 15, 120))
    r.text(label, 14f, 14f, 10f, Colors.WHITE)
}
```

## The surface

| Method | Type | Description |
|---|---|---|
| `r.width()` | `float` | framebuffer width in px, refreshed each 2D frame |
| `r.height()` | `float` | framebuffer height in px, refreshed each 2D frame |

At GUI Scale 2 a 1920×1080 window still reports `width()` = 1920. Divide by [`gameSettings.scaleFactor()`](https://docs.nursultan.fun/scripting/actions/control#game-settings) to get vanilla GUI units.

## Shapes

| Method | Type | Description |
|---|---|---|
| `r.rect(x, y, width, height, argb)` | `void` | filled rectangle |
| `r.roundedRect(x, y, width, height, radius, argb)` | `void` | radius clamped 0..min(width, height)/2 |
| `r.roundedRect(x, y, width, height, topLeft, topRight, bottomRight, bottomLeft, argb)` | `void` | per-corner radii, clockwise from top-left, each clamped the same way |
| `r.outline(x, y, width, height, thickness, argb)` | `void` | square border inside the rect, thickness clamped 0..min(w, h)/2 |
| `r.roundedOutline(x, y, width, height, radius, thickness, argb)` | `void` | rounded border, stroke aligned INSIDE |
| `r.roundedOutline(x, y, width, height, radius, thickness, align, argb)` | `void` | null align treated as INSIDE |
| `r.circle(centerX, centerY, radius, argb)` | `void` | filled circle, negative radius treated as 0 |
| `r.ring(centerX, centerY, radius, thickness, argb)` | `void` | thickness clamped 0..radius |
| `r.triangle(x1, y1, x2, y2, x3, y3, argb)` | `void` | filled triangle, bounding quad padded 2 px |

### StrokeAlign

| Constant | Description |
|---|---|
| `StrokeAlign.INSIDE` | stroke inside the rect edge, used when align is null |
| `StrokeAlign.CENTER` | stroke centred on the edge, rect grown by half the thickness |
| `StrokeAlign.OUTSIDE` | stroke outside the edge, rect grown by the full thickness |

The size you pass is always the shape itself; the stroke grows outwards from it.

## Gradients and blur

| Method | Type | Description |
|---|---|---|
| `r.gradient(x, y, width, height, argbFrom, argbTo, horizontal)` | `void` | horizontal true = left to right, false = top to bottom |
| `r.gradientAngle(x, y, width, height, argbFrom, argbTo, angleDegrees)` | `void` | linear gradient along (cos a, sin a) in degrees, screen Y grows downward |
| `r.radialGradient(x, y, width, height, argbCenter, argbEdge)` | `void` | gradient out of the centre, corner radius 0 |
| `r.radialGradient(x, y, width, height, radius, argbCenter, argbEdge)` | `void` | corner radius clamped 0..min(w, h)/2 |
| `r.blur(x, y, width, height, radius)` | `void` | blurs what is already drawn under the region, full opacity, square corners |
| `r.blur(x, y, width, height, radius, argb, cornerRadius)` | `void` | only the alpha byte of argb is used, one radius for all corners |
| `r.blur(x, y, width, height, radius, argb, tl, tr, bl, br)` | `void` | per-corner radii in order top-left, top-right, bottom-left, bottom-right (API 2) |

Blur reads the framebuffer at its own place in the queue, so it only blurs commands issued before it. The rect is snapped to whole pixels and the blur radius to `max(1, round(radius))` px; a width or height that rounds to 0 is skipped.

## Text

| Method | Type | Description |
|---|---|---|
| `r.text(text, x, y, sizePx, argb)` | `void` | font `inter`, weight REGULAR |
| `r.text(text, x, y, sizePx, argb, font)` | `void` | named family, weight REGULAR |
| `r.text(text, x, y, sizePx, argb, weight)` | `void` | font `inter` at that weight (API 2) |
| `r.text(text, x, y, sizePx, argb, font, weight)` | `void` | named family at that weight (API 2) |
| `r.textShadow(text, x, y, sizePx, argb, shadowArgb)` | `void` | shadow copy queued at +1, +1 px before the text |
| `r.textShadow(text, x, y, sizePx, argb, shadowArgb, font)` | `void` | named family, weight REGULAR |
| `r.textShadow(text, x, y, sizePx, argb, shadowArgb, weight)` | `void` | font `inter` at that weight (API 2) |
| `r.textShadow(text, x, y, sizePx, argb, shadowArgb, font, weight)` | `void` | named family at that weight (API 2) |

`y` is the line top; the baseline sits at `y + textAscent(...)`. An unknown family falls back to `inter`, and null or empty text is skipped.

## Measuring text

| Method | Type | Description |
|---|---|---|
| `r.textWidth(text, sizePx)` | `float` | advance width in px, font `inter`, REGULAR |
| `r.textWidth(text, sizePx, font)` | `float` | width in px for the named family |
| `r.textWidth(text, sizePx, weight)` | `float` | width in px, font `inter` (API 2) |
| `r.textWidth(text, sizePx, font, weight)` | `float` | 0 for null or empty text and for an unresolvable family (API 2) |
| `r.textHeight(sizePx)` | `float` | line height in px, font `inter`, REGULAR |
| `r.textHeight(sizePx, font)` | `float` | line height in px for the named family |
| `r.textHeight(sizePx, weight)` | `float` | line height in px, font `inter` (API 2) |
| `r.textHeight(sizePx, font, weight)` | `float` | single-line height, independent of any string (API 2) |
| `r.textAscent(sizePx)` | `float` | ascent above the baseline in px, font `inter`, REGULAR |
| `r.textAscent(sizePx, font)` | `float` | ascent in px for the named family |
| `r.textAscent(sizePx, weight)` | `float` | ascent in px, font `inter` (API 2) |
| `r.textAscent(sizePx, font, weight)` | `float` | 0 when no family resolves (API 2) |
| `r.textDescent(sizePx)` | `float` | line height minus ascent in px, font `inter`, REGULAR |
| `r.textDescent(sizePx, font)` | `float` | descent in px for the named family |
| `r.textDescent(sizePx, weight)` | `float` | descent in px, font `inter` (API 2) |
| `r.textDescent(sizePx, font, weight)` | `float` | 0 when no family resolves (API 2) |

`textHeight` equals `textAscent + textDescent` at the same size, family and weight.

## Fonts and weights

| Method | Type | Description |
|---|---|---|
| `font(name, ttfFileInAssetsFolder)` | `void` | registers a TTF from `scripts/assets` under that family name |
| `font(name, ttf)` | `void` | registers a family from TTF bytes, ignored when the name is taken, the array is empty or over 8 MiB (API 2) |
| `client.fonts().register(name, ttfFileInAssetsFolder)` | `void` | what `font(name, file)` calls, applied on the next render frame |
| `client.fonts().register(name, ttf)` | `void` | what `font(name, bytes)` calls, the array is cloned (API 2) |
| `client.fonts().registered(name)` | `boolean` | true when a live family has that name, a queued font is not visible yet |

A name that already exists — including the client's own `inter`, `jetbrains-mono` and `minecraft` — is ignored, and script families are dropped when the script unloads. The byte form pairs with `base64(...)`: see [assets inside the script](https://docs.nursultan.fun/scripting/extras/assets#assets-inside-the-script).

### Weight

| Constant | Description |
|---|---|
| `Weight.THIN` | `wght` 100 (API 2) |
| `Weight.EXTRA_LIGHT` | `wght` 200 (API 2) |
| `Weight.LIGHT` | `wght` 300 (API 2) |
| `Weight.REGULAR` | `wght` 400, used when the weight argument is omitted or null (API 2) |
| `Weight.MEDIUM` | `wght` 500 (API 2) |
| `Weight.SEMI_BOLD` | `wght` 600 (API 2) |
| `Weight.BOLD` | `wght` 700 (API 2) |
| `Weight.EXTRA_BOLD` | `wght` 800 (API 2) |
| `Weight.BLACK` | `wght` 900 (API 2) |

## Items, heads, icons

| Method | Type | Description |
|---|---|---|
| `r.item(item, x, y, sizePx)` | `void` | item stack icon, foreign `Item` implementations ignored |
| `r.item(itemId, x, y, sizePx)` | `void` | namespaced id, malformed id ignored, unknown id resolves to air |
| `r.head(player, x, y, sizePx)` | `void` | player skin head quad, no-op for sizePx ≤ 0, StreamerMode or a missing skin |
| `r.effectIcon(effectId, x, y, sizePx)` | `void` | status-effect sprite `mob_effect/<path>`, x/y/size floored to ints |

## Textures

| Method | Type | Description |
|---|---|---|
| `r.texture(identifier, x, y, width, height)` | `void` | Minecraft resource identifier, full 0..1 UV, malformed identifier ignored |
| `r.texture(texture, x, y, width, height)` | `void` | full 0..1 UV, skipped while the GL id is 0 |
| `r.texture(texture, x, y, width, height, u0, v0, u1, v1)` | `void` | explicit UV rectangle 0..1, u0/v0 top-left, v grows downward |
| `r.image(fileInAssetsFolder, x, y, width, height)` | `void` | PNG from `scripts/assets`, decoded and uploaded once |
| `texture(identifier)` | `Texture?` | handle for a Minecraft resource id, null when malformed or empty |
| `image(fileInAssetsFolder)` | `Texture?` | handle for a PNG in `scripts/assets`, null when rejected, missing or empty |
| `image(name, png)` | `Texture?` | handle for PNG bytes, null for a blank name, empty bytes or over 8 MiB (API 2) |
| `client.textures().resource(identifier)` | `Texture?` | what `texture(identifier)` calls |
| `client.textures().image(fileInAssetsFolder)` | `Texture?` | what `image(file)` calls, uploaded on first draw |
| `client.textures().image(name, png)` | `Texture?` | what `image(name, bytes)` calls, released when the script is unloaded (API 2) |
| `handle.name()` | `String` | resource identifier string or the image name |
| `handle.glId()` | `int` | OpenGL texture id, 0 off the client main thread or before upload |
| `handle.ready()` | `boolean` | true when `glId()` is non-zero |
| `handle.width()` | `int` | mip-0 width in px, 0 off the main thread or when unavailable |
| `handle.height()` | `int` | mip-0 height in px, 0 off the main thread or when unavailable |

A file path is resolved against `scripts/assets`, with a one-time-warned fallback to the scripts root — see [assets](https://docs.nursultan.fun/scripting/extras/assets). `skinTexture()` on a player or a tab entry returns the same kind of handle.

## Colours

Every colour is an `int` shaped `0xAARRGGBB`.

| Method | Type | Description |
|---|---|---|
| `Colors.TRANSPARENT` | `int` | `0x00000000` |
| `Colors.WHITE` | `int` | `0xFFFFFFFF` |
| `Colors.BLACK` | `int` | `0xFF000000` |
| `Colors.GRAY` | `int` | `0xFF808080` |
| `Colors.RED` | `int` | `0xFFFF5555` |
| `Colors.GREEN` | `int` | `0xFF55FF55` |
| `Colors.BLUE` | `int` | `0xFF5555FF` |
| `Colors.YELLOW` | `int` | `0xFFFFFF55` |
| `Colors.ORANGE` | `int` | `0xFFFFA500` |
| `Colors.CYAN` | `int` | `0xFF55FFFF` |
| `Colors.MAGENTA` | `int` | `0xFFFF55FF` |
| `Colors.rgb(red, green, blue)` | `int` | packs opaque ARGB, channels clamped 0..255 |
| `Colors.rgba(red, green, blue, alpha)` | `int` | packs ARGB, all channels clamped 0..255 |
| `Colors.red(argb)` | `int` | red channel 0..255 |
| `Colors.green(argb)` | `int` | green channel 0..255 |
| `Colors.blue(argb)` | `int` | blue channel 0..255 |
| `Colors.alpha(argb)` | `int` | alpha channel 0..255 |
| `Colors.withAlpha(argb, alpha)` | `int` | replaces alpha clamped 0..255, keeps RGB |
| `Colors.fade(argb, factor)` | `int` | multiplies alpha by factor clamped 0..1 |
| `Colors.mix(first, second, amount)` | `int` | per-channel lerp including alpha, amount clamped 0..1 |

## Client theme

The colours and scales the client menu and HUD draw with. `theme` is the DSL root, `client.theme()` the same object; every colour is ARGB, every value is read at the moment of the call, so the accent-derived ones change as soon as the user picks another accent.

| Method | Type | Description |
|---|---|---|
| `theme.defaultAccent()` | `int` | accent before the user picked one, `0xFF8BACFF` (API 8) |
| `theme.accent()` | `int` | current menu accent, follows the client settings (API 8) |
| `theme.background()` | `int` | window background (API 8) |
| `theme.border()` | `int` | window border (API 8) |
| `theme.divider()` | `int` | divider line, white at 2% alpha (API 8) |
| `theme.textPrimary()` | `int` | main text, opaque white (API 8) |
| `theme.textSecondary()` | `int` | secondary text, white at 72% alpha (API 8) |
| `theme.textTertiary()` | `int` | hint text, white at 48% alpha (API 8) |
| `theme.textQuaternary()` | `int` | faint text, white at 24% alpha (API 8) |
| `theme.textInactive()` | `int` | disabled text, `0xFF929292` (API 8) |
| `theme.textOnBrand()` | `int` | text over `accent()`, black on a bright accent (API 8) |
| `theme.iconSecondary()` | `int` | secondary icon, white at 72% alpha (API 8) |
| `theme.iconTertiary()` | `int` | hint icon, white at 48% alpha (API 8) |
| `theme.iconQuaternary()` | `int` | faint icon, white at 24% alpha (API 8) |
| `theme.iconOnBrand()` | `int` | icon over `accent()`, black on a bright accent (API 8) |
| `theme.backgroundBase()` | `int` | base menu layer (API 8) |
| `theme.backgroundSurface()` | `int` | panel over the base layer (API 8) |
| `theme.backgroundModal()` | `int` | modal window (API 8) |
| `theme.backgroundElevated()` | `int` | raised panel (API 8) |
| `theme.backgroundSurfaceSolid()` | `int` | opaque `backgroundSurface()` (API 8) |
| `theme.backgroundElevatedSolid()` | `int` | opaque `backgroundElevated()` (API 8) |
| `theme.backgroundScrollSurface()` | `int` | scrollbar track (API 8) |
| `theme.backgroundScrollBar()` | `int` | scrollbar thumb (API 8) |
| `theme.backgroundScrollBarHover()` | `int` | scrollbar thumb under the cursor (API 8) |
| `theme.backgroundScrollBarActive()` | `int` | scrollbar thumb while dragged (API 8) |
| `theme.backgroundActive()` | `int` | pressed or hovered item, white at 8% alpha (API 8) |
| `theme.borderSurface()` | `int` | panel border, white at 2% alpha (API 8) |
| `theme.fieldSurface()` | `int` | input field fill (API 8) |
| `theme.fieldItem()` | `int` | item inside an input field (API 8) |
| `theme.fieldSurfaceDisabled()` | `int` | disabled input field fill (API 8) |
| `theme.effectShadow()` | `int` | drop shadow (API 8) |
| `theme.surfaceBorder()` | `int` | card border (API 8) |
| `theme.hudShadow()` | `int` | HUD element shadow (API 8) |
| `theme.switchOffBg()` | `int` | disabled switch fill, white at 8% alpha (API 8) |
| `theme.switchOffThumb()` | `int` | disabled switch thumb, white at 48% alpha (API 8) |
| `theme.menuScale()` | `float` | menu scale setting, 1, 1.25, 1.5 or 2 (API 8) |
| `theme.hudScale()` | `float` | HUD scale setting, 1, 1.25, 1.5 or 2 (API 8) |

## A world point on the screen

| Method | Type | Description |
|---|---|---|
| `r.project(worldPosition)` | `Projection` | world position to screen pixels, rounded |
| `p.visible()` | `boolean` | false when the point projects behind the camera |
| `p.x()` | `float` | screen X in framebuffer px, 0 when not visible |
| `p.y()` | `float` | screen Y in framebuffer px, 0 when not visible |

## Clipping

| Method | Type | Description |
|---|---|---|
| `r.pushScissor(x, y, width, height)` | `void` | clips later draws to the rect, intersected with the enclosing one (API 5) |
| `r.popScissor()` | `void` | drops one clip level (API 5) (no effect: the scissor stack is empty) |

The rect is in framebuffer px, rounded and clamped to the frame; a negative width or height becomes 0.
Every scissor a render handler leaves open is dropped when that handler returns, and a blur samples the unclipped frame: only its output is cut.

## Blending

| Method | Type | Description |
|---|---|---|
| `r.blend()` | `BlendMode` | mode applied to later shapes and textures, ALPHA when a handler starts (API 7) |
| `r.blend(mode)` | `void` | sets it for later shapes and textures, null means ALPHA (API 7) |

Text, items, heads, blur and shader quads keep their own blending; the modes are listed on [Your own geometry](https://docs.nursultan.fun/scripting/ui/gpu#blendmode).
`INVERT` flips every pixel under the shape, weighted by its alpha — the blend of the vanilla crosshair.

## Shaders

| Method | Type | Description |
|---|---|---|
| `r.shader(shader, x, y, width, height)` | `void` | draws a quad with a script shader, uniforms snapshotted at call time |

Foreign `Shader` implementations are ignored, and the quad is skipped while compilation failed. Compiling one and setting uniforms: [shaders](https://docs.nursultan.fun/scripting/ui/shaders).

---

# 3D render

`Render3D` comes from `Render3DEvent` and draws in world coordinates; the camera position captured when the event fired is subtracted for you. The event's own members — `render()`, `tickDelta()`, `camera()`, `viewMatrix()` and `projectionMatrix()` (API 2) — are in the [event list](https://docs.nursultan.fun/scripting/events/reference).

```kotlin
on<Render3DEvent> { e ->
    val targets = world.entitiesNear(player.position(), 48.0, filters.attackable())
    for (target in targets) {
        e.render().entityBox(target, Colors.RED, true)
    }
    val nearest = targets.minByOrNull { it.distanceTo(player) } ?: return@on
    e.render().tracer(nearest.renderPosition().add(0.0, nearest.height() / 2.0, 0.0), Colors.RED, true)
}
```

## What you can draw

| Method | Type | Description |
|---|---|---|
| `line(from, to, argb, throughWalls)` | `void` | single world-space line |
| `box(box, argb, throughWalls)` | `void` | the 12 wireframe edges of the box |
| `filledBox(box, argb, throughWalls)` | `void` | solid box faces |
| `entityBox(entity, argb, throughWalls)` | `void` | wireframe box from interpolated position, width and height |
| `tracer(target, argb, throughWalls)` | `void` | line from the camera near-plane centre to the point |
| `triangle(a, b, c, argb, throughWalls)` | `void` | filled triangle |
| `quad(a, b, c, d, argb, throughWalls)` | `void` | filled quad |
| `polygon(points, argb, throughWalls)` | `void` | triangle fan from the first point, no-op below 3 points |

`Vec` points and `Box` are world coordinates in blocks — see [vectors, boxes, angles](https://docs.nursultan.fun/scripting/game/math). `argb` is packed `0xAARRGGBB`; the constants and helpers live on [2D render](https://docs.nursultan.fun/scripting/ui/render-2d).

## Through walls

`throughWalls` is the last argument of every call above and picks the mesh: `true` draws into the depth-test-less one, so the shape stays visible through blocks.

## Labels

There is no world-space text. Project the world point to screen coordinates with `render.project(...)` inside `Render2DEvent` and draw the label there — see [2D render](https://docs.nursultan.fun/scripting/ui/render-2d).

---

# Shaders

`client.shaders().compile(name, fragmentSource)` — or the top-level `shader(...)` shorthand — registers a GLSL program that the client compiles lazily, on the render thread, at the first draw. Uniforms are stored on the handle and snapshotted when the draw command is queued; drawing is [`render.shader(...)`](https://docs.nursultan.fun/scripting/ui/render-2d) or a [`gpu` pipeline](https://docs.nursultan.fun/scripting/ui/gpu).

```kotlin
val glow = shader("glow", """
    #version 330
    out vec4 out_color;
    uniform float u_time;
    uniform vec3 u_color;
    uniform float u_alpha;
    void main() {
        out_color = vec4(u_color, u_alpha * (0.5 + 0.5 * sin(u_time * 2.0)));
    }
""")

on<Render2DEvent> { e ->
    glow.set("u_color", 0.35f, 0.78f, 1.0f)
    glow.set("u_alpha", 0.6f)
    e.render().shader(glow, 8f, 8f, 160f, 40f)
}
```

## Compiling

| Method | Type | Description |
| --- | --- | --- |
| `shader(name, fragmentSource, vertexSource)` | `Shader` | top-level shorthand, `vertexSource` defaults to null |
| `client.shaders().compile(name, fragmentSource)` | `Shader` | fragment stage only, built-in vertex stage |
| `client.shaders().compile(name, fragmentSource, vertexSource)` | `Shader` | null or blank `vertexSource` falls back to the built-in stage (throws `IllegalStateException` when the script session is closed) |

Compilation runs on the render thread at the first draw, so a shader that is never drawn never compiles. Compile failures are logged to the script console, the shader draws nothing, and every shader is disposed when the script session closes.

## Checking it built

| Method | Type | Description |
| --- | --- | --- |
| `name()` | `String` | name passed to `compile` |
| `ready()` | `boolean` | true once compiled and not disposed, false before the first draw |
| `error()` | `String?` | compile error with stage names substituted, null before failure |

## Uniforms

| Method | Type | Description |
| --- | --- | --- |
| `set(uniform, float)` | `Shader` | float uniform |
| `set(uniform, x, y)` | `Shader` | vec2 uniform |
| `set(uniform, x, y, z)` | `Shader` | vec3 uniform |
| `set(uniform, x, y, z, w)` | `Shader` | vec4 uniform |
| `set(uniform, int)` | `Shader` | int uniform |
| `set(uniform, boolean)` | `Shader` | int uniform, 1 or 0 |
| `setArray(uniform, float[])` | `Shader` | length 2/3/4 become vec2/vec3/vec4, other lengths a float array, null or empty ignored |
| `setMat4(uniform, float[])` | `Shader` | column-major mat4, ignored unless exactly 16 floats (API 2) |

Values are stored on the handle, not uploaded; a null `uniform` name is ignored. Names the linked program does not declare are recorded once and skipped afterwards without error.

## Textures

| Method | Type | Description |
| --- | --- | --- |
| `set(uniform, texture)` | `Shader` | binds a `sampler2D` to the next unit, a non-script `Texture` removes the uniform |
| `set(uniform, texture, filter, wrap)` | `Shader` | same plus a GL sampler object, `gpu` render-type path only — under `render.shader` the texture is not bound at all (API 2) |

### TextureFilter

| Constant | Description |
| --- | --- |
| `TextureFilter.NEAREST` | `GL_NEAREST` for min and mag |
| `TextureFilter.LINEAR` | `GL_LINEAR` for min and mag |

### TextureWrap

| Constant | Description |
| --- | --- |
| `TextureWrap.CLAMP` | `GL_CLAMP_TO_EDGE` on S and T |
| `TextureWrap.REPEAT` | `GL_REPEAT` on S and T |

Sampler units are handed out in the order the textures were set, starting at 0; a texture whose `glId()` is 0 is skipped. `Texture` handles come from [`client.textures()`](https://docs.nursultan.fun/scripting/ui/render-2d).

## The built-in vertex stage

Used whenever `vertexSource` is null or blank.

### Attributes

| Attribute | Type | Description |
| --- | --- | --- |
| `pos` | `vec3` | location 0, corner position in framebuffer pixels, z is 0 |
| `uv` | `vec2` | location 1, UV across the drawn rect, 0..1 |
| `color` | `vec4` | location 2, vertex colour in BGRA order |

### Outputs

| Output | Type | Description |
| --- | --- | --- |
| `in_pos` | `vec4` | `u_projection * u_view * vec4(pos, 1.0)` |
| `in_screen_pos` | `vec2` | `pos.xy`, framebuffer pixels |
| `in_uv` | `vec2` | `uv`, 0..1 across the rect |
| `in_color` | `vec4` | `color.bgra`, i.e. RGBA |

### Built-in uniforms

| Uniform | Type | Description |
| --- | --- | --- |
| `u_projection` | `mat4` | current projection matrix |
| `u_view` | `mat4` | identity matrix |
| `u_time` | `float` | monotonic seconds since class init |
| `u_resolution` | `vec2` | framebuffer width and height in pixels |
| `u_rect` | `vec4` | x, y, width and height passed to `render.shader` |

Each of the five is filled only when the linked program declares it, and only on the `render.shader` path — [`gpu` draws](https://docs.nursultan.fun/scripting/ui/gpu) supply no built-in uniforms. A fragment stage reads the four outputs above as `in` declarations of the same name and type.

The stage in full:

```glsl
#version 330

layout(location=0) in vec3 pos;
layout(location=1) in vec2 uv;
layout(location=2) in vec4 color;

out vec4 in_pos;
out vec2 in_screen_pos;
out vec2 in_uv;
out vec4 in_color;

uniform mat4 u_projection;
uniform mat4 u_view;

void main() {
    in_uv = uv;
    in_screen_pos = pos.xy;
    in_pos = u_projection * u_view * vec4(pos, 1.0);
    gl_Position = in_pos;
    in_color = color.bgra;
}
```

---

# Your own geometry

`gpu` is `client.gpu()` — script-owned vertex formats, meshes, pipelines and draw calls. Vertex positions are relative to the camera, the buffers are freed while the script is off, and every type on this page is API 2.

```kotlin
val format = gpu.format(VertexAttribute.floats(3), VertexAttribute.color())
val mesh = gpu.indexedMesh(format)
val pipeline = gpu.pipeline(myShader, DrawMode.TRIANGLES, BlendMode.ALPHA, DepthMode.TEST)
val pass = gpu.renderType(pipeline, mesh)

on<Render3DEvent> { event ->
    val verts = mesh.verts()
    val base = verts.putVec3(0f, 0f, 0f).putColor(Colors.RED).next()
    verts.putVec3(1f, 0f, 0f).putColor(Colors.GREEN).next()
    verts.putVec3(0f, 1f, 0f).putColor(Colors.BLUE).next()
    mesh.idx()?.putTriangle(base, base + 1, base + 2)

    myShader.setMat4("u_view", event.viewMatrix())
    myShader.setMat4("u_projection", event.projectionMatrix())
    pass.draw()
}
```

## The factory

| Method | Type | Description |
|---|---|---|
| `gpu.format(attributes...)` | `VertexFormat` | interleaved vertex layout (throws `IllegalArgumentException` below 1 or above 16 attributes) |
| `gpu.mesh(format)` | `Mesh` | non-indexed mesh, 1024-byte initial vertex buffer (throws `IllegalArgumentException` on a foreign format) |
| `gpu.indexedMesh(format)` | `Mesh` | mesh with an index buffer, 1024 bytes each |
| `gpu.pipeline(shader, drawMode, blend, depth)` | `Pipeline` | culling disabled |
| `gpu.pipeline(shader, drawMode, blend, depth, cull)` | `Pipeline` | nulls default to `TRIANGLES`/`ALPHA`/`OFF` (throws `IllegalArgumentException` on a foreign shader) |
| `gpu.renderType(pipeline, mesh)` | `RenderType` | non-instanced draw pairing |
| `gpu.instancedRenderType(pipeline, mesh, verticesPerInstance)` | `RenderType` | `verticesPerInstance` clamped to 0 or more (throws `IllegalArgumentException` on a foreign pipeline or mesh) |

Every method throws `IllegalStateException` once the script session is closed. Meshes, pipelines and render types are tracked resources; formats are not.

## The vertex format

| Method | Type | Description |
|---|---|---|
| `VertexAttribute(count, type, normalized, instanced)` | `VertexAttribute` | canonical constructor |
| `attribute.count()` | `int` | component count |
| `attribute.type()` | `AttributeType` | component type |
| `attribute.normalized()` | `boolean` | normalization flag, ignored — only `UNSIGNED_BYTE` is normalized |
| `attribute.instanced()` | `boolean` | true when the attribute advances once per instance |
| `VertexAttribute.floats(count)` | `VertexAttribute` | static, `count` floats, per-vertex |
| `VertexAttribute.ints(count)` | `VertexAttribute` | static, `count` ints, per-vertex |
| `VertexAttribute.color()` | `VertexAttribute` | static, 4 normalized unsigned bytes, per-vertex |
| `attribute.perInstance()` | `VertexAttribute` | copy with `instanced = true` |

### AttributeType

| Constant | Description |
|---|---|
| `AttributeType.FLOAT` | 32-bit float components |
| `AttributeType.INT` | 32-bit signed integer components |
| `AttributeType.UNSIGNED_BYTE` | 4 normalized bytes regardless of the declared count |

### The format itself

| Method | Type | Description |
|---|---|---|
| `format.stride()` | `int` | bytes per vertex |
| `format.attributeCount()` | `int` | attributes in the layout |

Attributes map to the shader's `layout(location = N)` inputs in declaration order; nothing checks that what you write matches the format.

## Writing vertices

| Method | Type | Description |
|---|---|---|
| `mesh.format()` | `VertexFormat` | the format the mesh was created with |
| `mesh.verts()` | `VertexWriter` | vertex writer (throws `IllegalStateException` when the mesh is closed) |
| `mesh.idx()` | `IndexWriter?` | index writer, null on a non-indexed mesh |
| `mesh.indexed()` | `boolean` | true when created by `gpu.indexedMesh` |
| `mesh.clear()` | `void` | resets both writers, no-op if the mesh was never used |

The GL buffer is created on first use, and that first write must happen on the render thread. `draw()` uploads both writers and empties them, so each frame writes its geometry from scratch.

### The vertex writer

| Method | Type | Description |
|---|---|---|
| `verts.putFloat(value)` | `VertexWriter` | writes 4 bytes |
| `verts.putInt(value)` | `VertexWriter` | writes 4 bytes |
| `verts.putVec2(x, y)` | `VertexWriter` | writes two floats, identical to `putUv` |
| `verts.putVec3(x, y, z)` | `VertexWriter` | writes three floats |
| `verts.putVec3(position)` | `VertexWriter` | same from a [`Vec`](https://docs.nursultan.fun/scripting/game/math), components cast to float |
| `verts.putUv(u, v)` | `VertexWriter` | writes two floats |
| `verts.putColor(argb)` | `VertexWriter` | writes the ARGB int; reaches GLSL as BGRA |
| `verts.next()` | `int` | ends the vertex, returns its 0-based index (throws `IllegalStateException` at 1048576 vertices) |
| `verts.vertexCount()` | `int` | vertices finished so far, 0 when the mesh is closed |

## Indices

| Method | Type | Description |
|---|---|---|
| `idx.put(index)` | `IndexWriter` | appends one vertex index (throws `IllegalStateException` at 4194304 indices) |
| `idx.putTriangle(a, b, c)` | `IndexWriter` | appends three indices |
| `idx.putQuad(a, b, c, d)` | `IndexWriter` | appends triangles `(a, b, c)` and `(a, c, d)` |
| `idx.indexCount()` | `int` | indices written so far, 0 when the mesh is closed |

## The pipeline

| Method | Type | Description |
|---|---|---|
| `pipeline.shader()` | `Shader` | the shader this pipeline draws with — [Shaders](https://docs.nursultan.fun/scripting/ui/shaders) |
| `pipeline.drawMode()` | `DrawMode` | primitive topology |

### DrawMode

| Constant | Description |
|---|---|
| `DrawMode.TRIANGLES` | `GL_TRIANGLES`, also the fallback for a null mode |
| `DrawMode.TRIANGLE_STRIP` | `GL_TRIANGLE_STRIP` |
| `DrawMode.TRIANGLE_FAN` | `GL_TRIANGLE_FAN` |
| `DrawMode.LINES` | `GL_LINES` |
| `DrawMode.LINE_STRIP` | `GL_LINE_STRIP` |
| `DrawMode.POINTS` | `GL_POINTS` |

### BlendMode

| Constant | Description |
|---|---|
| `BlendMode.OFF` | blending disabled |
| `BlendMode.ALPHA` | `SRC_ALPHA, ONE_MINUS_SRC_ALPHA`, the fallback for a null mode |
| `BlendMode.PREMULTIPLIED` | `ONE, ONE_MINUS_SRC_ALPHA` on colour and alpha |
| `BlendMode.ADDITIVE` | `SRC_ALPHA, ONE` on colour and alpha |
| `BlendMode.INVERT` | `ONE_MINUS_DST_COLOR, ONE_MINUS_SRC_COLOR` on colour, `ONE, ZERO` on alpha, the blend of the vanilla crosshair (API 7) |

### DepthMode

| Constant | Description |
|---|---|
| `DepthMode.OFF` | depth test off, depth write off, the fallback for a null mode |
| `DepthMode.TEST` | depth test on, depth write off |
| `DepthMode.TEST_AND_WRITE` | depth test on, depth write on |

## Drawing

| Method | Type | Description |
|---|---|---|
| `pass.pipeline()` | `Pipeline` | the pipeline used |
| `pass.mesh()` | `Mesh` | the mesh used |
| `pass.draw()` | `void` | binds the client framebuffer and issues one draw call (throws `IllegalStateException` when the render type or mesh is closed) |
| `pass.drawInstanced()` | `void` | draws instances of `verticesPerInstance` vertices, `instancedRenderType` only |

No built-in uniforms are supplied, unlike `Render.shader`: `u_view`, `u_projection` and anything else are yours to set before the call. Both calls draw nothing while the mesh is empty or the shader failed to compile.

## Limits

| Limit | Value |
|---|---|
| live gpu resources per script | 64 meshes, pipelines and render types together |
| attributes per vertex format | 16 |
| vertices per mesh | 1 048 576 |
| indices per mesh | 4 194 304 |
| embedded font or PNG | 8 MiB |

The exception each limit throws: [Sandbox and limits](https://docs.nursultan.fun/scripting/extras/limits#resource-limits).

---

# Messages

`chat` prints locally and sends to the server, `log` writes to the script console, `notify` pushes a card onto the client notification stack, `clipboard` reads and writes the system clipboard. All four are roots of the script; `chat` is `client.chat()`, `log` is `client.log()`, `clipboard` is `client.clipboard()`.

```kotlin
on<ClientTickEvent> {
    if (player.health() > 6f) return@on
    chat.print(text.literal("low health").color(Colors.RED))
    notify("low health", NotifyKind.WARN)
    log.error("health " + player.health())
}
```

## Chat

| Method | Type | Description |
|---|---|---|
| `chat.print(message)` | `void` | prints `[<scriptId>] message` into your own chat only |
| `chat.printPrefixed(prefix, message)` | `void` | same with `[prefix] ` instead of the script id |
| `chat.sendToServer(message)` | `void` | sends a chat message, a leading `/` sends a server command (throws `NullPointerException` when not connected) |
| `chat.runCommand(command)` | `void` | re-sends the text with the client prefix `.` so a client command runs (throws `NullPointerException` when not connected) |

A `Text` argument to `print`/`printPrefixed` keeps its styling, anything else goes through `toString`, null prints `null` — see [Styled text](https://docs.nursultan.fun/scripting/ui/text).
`sendToServer` and `runCommand` ignore null and blank strings; `runCommand` strips one leading prefix character before re-adding it.

## Notifications

| Method | Type | Description |
|---|---|---|
| `notify(text, kind)` | `void` | pushes a notification card, `kind` defaults to `NotifyKind.OK` |
| `notifications.show(text)` | `void` | card with kind OK, null text becomes `""` |
| `notifications.show(text, kind)` | `void` | card with that style, null kind falls back to OK |

`notifications` is `client.notifications()`; `notify(...)` is the same call from the script root.

### NotifyKind

| Constant | Description |
|---|---|
| `OK` | success styling, the default |
| `WARN` | warning styling |
| `FAIL` | error styling |
| `ACCENT` | client accent-colour styling |

## The log

| Method | Type | Description |
|---|---|---|
| `log.info(message)` | `void` | INFO line in the script console and the client log |
| `log.warn(message)` | `void` | WARN line in the script console and the client log |
| `log.error(message)` | `void` | ERROR line in the script console and the client log |
| `log.error(message, cause)` | `void` | ERROR line plus `<file>.kts:<line>: <cause message>`, full stacktrace only in the client log |

The console is menu → **Scripts** → the terminal button; every line carries the time, the level and the script id, and it keeps the last 1000 lines.
Load, reload, toggle and compile errors are written there by the client itself, as is anything a script throws.

## Clipboard

| Method | Type | Description |
|---|---|---|
| `clipboard.get()` | `String` | clipboard text, `""` when empty or holding something that is not text (API 2) |
| `clipboard.set(text)` | `void` | replaces the clipboard, null ignored (API 2) (throws `ScriptException` above 65536 chars) |
| `clipboard.clear()` | `void` | writes an empty string (API 2) |
| `clipboard.empty()` | `boolean` | true when `get()` returns `""`, also true on a read timeout (API 2) |

Off the client thread `get()`/`empty()` hop onto it and wait up to 1000 ms, returning `""`/`true` on timeout, while `set`/`clear` are queued and do not block — see [getting onto the client thread](https://docs.nursultan.fun/scripting/extras/tasks#getting-onto-the-client-thread).

---

# Styled text

`text` is `client.text()`. Every styling call mutates the receiver and returns it, so a `Text` is a builder and a value at the same time — `copy()` is the only way to branch.

```kotlin
chat.print(
    text.literal("[teleport]")
        .color(Colors.CYAN)
        .bold(true)
        .runCommand("/spawn")
        .hoverText("go to spawn")
)
```

## Building one

| Method | Type | Description |
|---|---|---|
| `text.literal(value)` | `Text` | literal component; null becomes `""` |
| `text.empty()` | `Text` | empty component, usable as an append root |
| `text.translatable(key, args...)` | `Text` | translation component; `Text` arguments are unwrapped (throws `ScriptException` when the key is blank) |
| `text.keybind(key)` | `Text` | renders the key bound to a vanilla keybind id (throws `ScriptException` when the key is blank) |
| `text.legacy(value)` | `Text` | parses `§` codes into styled children; null gives an empty component |
| `text.fromJson(json)` | `Text` | parses a text-component json string (throws `ScriptException` when blank or invalid) |

In `legacy`, a colour code resets the style to that colour alone, `§r` resets to no style, and every other code accumulates onto the current style. A `§` with no valid code after it stays a literal character.

## Styling

| Method | Type | Description |
|---|---|---|
| `color(argb)` | `Text` | colour; the alpha byte is masked off, RGB only |
| `bold(value)` | `Text` | bold flag |
| `italic(value)` | `Text` | italic flag |
| `underlined(value)` | `Text` | underline flag |
| `strikethrough(value)` | `Text` | strikethrough flag |
| `obfuscated(value)` | `Text` | scrambled-glyph flag |
| `font(fontId)` | `Text` | font id; a bare id gets the `minecraft:` namespace (throws `ScriptException` when blank or unparsable) |
| `append(Text)` | `Text` | appends another component; null ignored (throws `ScriptException` when it was not built by `text.*`) |
| `append(String)` | `Text` | appends a literal string; null ignored |

A child appended after a style call inherits that style, as in vanilla.

## Clicks and hovers

| Method | Type | Description |
|---|---|---|
| `insertion(value)` | `Text` | what shift-click inserts into the chat box |
| `runCommand(command)` | `Text` | click runs the command (throws `ScriptException` when blank) |
| `suggestCommand(command)` | `Text` | click fills the chat box, unsent (throws `ScriptException` when blank) |
| `openUrl(url)` | `Text` | click opens a link; http and https only (throws `ScriptException` on any other scheme) |
| `copyToClipboard(value)` | `Text` | click copies the string (throws `ScriptException` when blank) |
| `hoverText(Text)` | `Text` | show-text hover; null ignored (throws `ScriptException` when it was not built by `text.*`) |
| `hoverText(String)` | `Text` | show-text hover from a literal string; null ignored |
| `hoverItem(item)` | `Text` | show-item hover; null, empty and foreign stacks are ignored |
| `hoverEntity(entity)` | `Text` | show-entity hover with type, uuid and name (throws `ScriptStateException` when the entity left the world) |

Clicks and hovers only fire from a message that is in the chat log; text drawn through `render` is not interactive.

## Reading it back

| Method | Type | Description |
|---|---|---|
| `copy()` | `Text` | deep copy of the component and its children, safe to mutate |
| `string()` | `String` | flattened plain text, no formatting codes |
| `toJson()` | `String` | text-component json (throws `ScriptException` when encoding fails) |
| `toString()` | `String` | same value as `string()` |

---

# More

Commands, client modules, your account, timers, waypoints, party messages, script files, the sandbox rules, API versions, and MCP for AI agents.

---

# Your own commands

`command("name") { }` registers a `.`-prefixed client command that lives as long as the script is switched on. Arguments are the raw tail after the node path, split on runs of whitespace.

```kotlin
command("home") {
    usage("<go|list>")
    alias("h")
    sub("go") {
        completes(0, "base", "farm")
        runs { reply("going to " + arg(0)) }
    }
}
```

## Declaring one

| Method | Type | Description |
|---|---|---|
| `command(name) { }` | `Subscription` | registers the command and its aliases (throws `ScriptException` when the name is blank, multi-word, a client command, taken by another script, or the command has neither `runs` nor `sub`) |
| `usage(text)` | `Unit` | usage text appended to missing-argument errors, null becomes `""` |
| `alias(name)` | `Unit` | extra label for the same command tree (throws `ScriptException` when blank, multi-word or taken) |
| `runs { }` | `Unit` | body run on the client thread when this node is invoked, throws are logged |
| `sub(name) { }` | `Unit` | subcommand, unlimited nesting, label lowercased to one word |
| `completes(argIndex, options)` | `Unit` | completion supplier for the 0-based argument, filtered by prefix, case-insensitive (throws `ScriptException` when argIndex < 0) |
| `completes(argIndex, vararg options)` | `Unit` | fixed completion list for that argument slot |

The name is trimmed, lowercased and loses one leading prefix character; while the script is off the command stops answering and leaves tab completion, but the name stays claimed.
A completion supplier runs while the player types; a throw inside it is logged and yields no suggestions.

## The Java builder

| Method | Type | Description |
|---|---|---|
| `client.commands().command(name)` | `CommandBuilder` | starts a definition (throws `ScriptException` when the name is empty or contains a space) |
| `client.commands().prefix()` | `String` | client command prefix as a one-char string, `.` by default |
| `usage(usage)` | `CommandBuilder` | usage text appended to missing-argument errors, null becomes `""` |
| `alias(alias)` | `CommandBuilder` | extra label for the same node (throws `ScriptException` on an empty or multi-word alias) |
| `runs(handler)` | `CommandBuilder` | handler run on the client thread (throws `ScriptException` on a null handler) |
| `sub(name, body)` | `CommandBuilder` | defines or extends a subcommand (throws `ScriptException` on an empty name or null body) |
| `completes(argIndex, options)` | `CommandBuilder` | completion supplier for the 0-based argument slot (throws `ScriptException` when argIndex < 0 or options is null) |
| `completes(argIndex, options...)` | `CommandBuilder` | fixed completion list, null array means no options |
| `register()` | `Subscription` | registers the label and every alias (throws `ScriptException` when the node has neither `runs` nor `sub`, the label is a client command, or another script owns it) |

Nothing is registered until `register()`; the Kotlin `command(name) { }` form calls it for you.
`unsubscribe()` on the returned subscription drops the label and every alias — [Subscribing](https://docs.nursultan.fun/scripting/events/basics).

## Inside `runs`

The receiver is a `CommandContext`.

| Method | Type | Description |
|---|---|---|
| `label()` | `String` | full node path, e.g. `home go` |
| `args()` | `List<String>` | arguments after the node path |
| `argCount()` | `int` | number of arguments |
| `arg(index)` | `String` | 0-based argument (throws `ScriptException` naming the position and the usage text when out of range) |
| `argOr(index, fallback)` | `String` | argument, or fallback when the index is out of range |
| `intArg(index)` | `int` | argument parsed as int (throws `ScriptException` when missing or not a whole number) |
| `doubleArg(index)` | `double` | argument parsed as double (throws `ScriptException` when missing or not a number) |
| `booleanArg(index)` | `boolean` | accepts true/on/yes/1 and false/off/no/0, case-insensitive (throws `ScriptException` otherwise) |
| `rest()` | `String` | the whole argument tail as one string |
| `rest(fromIndex)` | `String` | arguments from that index joined with single spaces, whole tail when fromIndex <= 0, `""` past the end |
| `reply(message)` | `void` | prints `[<label>] message` into your own chat |
| `replyError(message)` | `void` | identical output to `reply`, no separate styling |

---

# Client modules

`client.modules()` reaches the client's own built-in modules and their flattened setting trees. Every reference — to a module, a setting or an entry — is matched with `-`, `_`, `.` and whitespace dropped and the rest lowercased, so `AttackAura`, `attack aura` and `attack-aura` all hit the same module.

```kotlin
val aura = client.modules().get("AttackAura")

chat.print(aura.displayName() + " fov " + aura.slider("fov").value())
aura.slider("fov").value(120f)
if (!aura.enabled()) {
    aura.toggle()
}
```

## Finding a module

### Modules

| Method | Type | Description |
|---|---|---|
| `client.modules().all()` | `List<Module>` | every module in registry order, the order the menu shows |
| `client.modules().exists(name)` | `boolean` | true when a module matches that reference |
| `client.modules().find(name)` | `Module?` | matching module, null when nothing matches or the name is blank |
| `client.modules().get(name)` | `Module` | same lookup (throws ScriptException when nothing matches) |

Lookup tries the registry name first, then the spaced display name; the returned list is immutable and holds `DEVELOPMENT` modules only for administrator accounts.
The wrapper is cached on the module, so every lookup of the same module hands back the same `Module` instance.

## The module

### Module

| Method | Type | Description |
|---|---|---|
| `module.name()` | `String` | registry name, no spaces, e.g. `AttackAura` |
| `module.displayName()` | `String` | name with spaces before capitals, e.g. `Attack Aura` |
| `module.bind()` | `Bind` | the module's toggle keybind — [Keys and binds](https://docs.nursultan.fun/scripting/actions/keys) |
| `module.enabled()` | `boolean` | current toggle state |
| `module.setEnabled(value)` | `void` | sets the state; ignored when it already matches |
| `module.toggle()` | `void` | flips the state |

Both writes run at once on the client thread and are queued onto it from any other thread; a module can refuse the change in its own enable/disable code.
Every state change dispatches `ModuleToggleEvent` — [Event list](https://docs.nursultan.fun/scripting/events/reference).

## Its settings

### Module settings

| Method | Type | Description |
|---|---|---|
| `module.settings()` | `List<Setting>` | depth-first flattened tree, nested settings included, snapshotted at first access |
| `module.setting(reference)` | `Setting?` | by stable id, then full name, then leaf name; null when nothing matches |
| `module.checkBox(reference)` | `CheckBox` | typed lookup (throws ScriptException when missing or of another type) |
| `module.slider(reference)` | `Slider` | typed lookup (throws ScriptException when missing or of another type) |
| `module.rangeSlider(reference)` | `RangeSlider` | typed lookup (throws ScriptException when missing or of another type) |
| `module.input(reference)` | `Input` | typed lookup (throws ScriptException when missing or of another type) |
| `module.selectable(reference)` | `Selectable` | typed lookup (throws ScriptException when missing or of another type) |
| `module.combo(reference)` | `Combo` | typed lookup (throws ScriptException when missing or of another type) |
| `module.colorPicker(reference)` | `ColorPicker` | typed lookup (throws ScriptException when missing or of another type) |
| `module.hotkey(reference)` | `Hotkey` | typed lookup (throws ScriptException when missing or of another type) |

The members of those setting types are on [Kinds of settings](https://docs.nursultan.fun/scripting/settings/types); a group header has no script type and comes back as a plain `Setting`.
A built-in `name()` is the locale key after `.setting.` and `id()` is the whole key (`module.attackaura.setting.aim-range`); right-clicking a setting in the menu copies that key while development mode is on.

## What a module's settings refuse

| Method | Type | Description |
|---|---|---|
| `setting.id(stableId)` | `Setting` | throws ScriptException; the id is the module's locale key |
| `setting.visibleWhen(condition)` | `Setting` | throws ScriptException; the client owns menu visibility |
| `onChange(listener)` | `CheckBox` `Slider` `RangeSlider` `Input` `Selectable` `Combo` `ColorPicker` | throws ScriptException on all seven setting types |
| `postfix(unit)` | `Slider` `RangeSlider` | throws ScriptException; the unit comes from the module |
| `entry.onSelect(action)` | `Entry` | throws ScriptException on a module's entry |
| `entry.onDeselect(action)` | `Entry` | throws ScriptException on a module's entry |
| `entry.on(type, options, handler)` | `Subscription` | throws ScriptException on a module's entry |

Reads and value writes work on every built-in setting: `slider.value(v)` and `rangeSlider.value(from, to)` clamp into the module's own `min()..max()`, and each write is dispatched onto the client thread.
A module's entry is still switched through its own `Selectable`/`Combo` — [Entries with their own logic](https://docs.nursultan.fun/scripting/settings/entries).

---

# Your account

`user` is `client.user()` — the Nursultan account the launcher authenticated, not the Minecraft profile. Every member is read-only, and both types were added in API 2.

```kotlin
requireApi(2)

on<Render2DEvent> { e ->
    val days = user.subscribeTimeMinutes() / 1440L
    e.render().text("${user.username()}: $days d", 46f, 16f, 9f, Colors.WHITE)
    val avatar = user.avatar() ?: return@on
    e.render().texture(avatar, 10f, 10f, 32f, 32f)
}
```

## Who you are

| Method | Type | Description |
|---|---|---|
| `user.username()` | `String` | Nursultan login from the launcher, not the Minecraft nickname (API 2) |
| `user.uid()` | `int` | numeric Nursultan account id (API 2) |
| `user.subscribeTimeMinutes()` | `long` | subscription time left in minutes (API 2) |

All three are read from the launcher arguments at startup and stay fixed for the session; `subscribeTimeMinutes()` does not count down.

## Avatar

| Method | Type | Description |
|---|---|---|
| `user.avatar()` | `Texture?` | avatar texture handle, null when `avatarTextureId()` is 0 (API 2) |
| `user.avatarTextureId()` | `int` | OpenGL texture id of the avatar, 0 when there is none (API 2) |

On the handle, `glId()` returns 0 off the client thread and `width()`/`height()` are the size the launcher supplied, whatever it was. `Texture` itself is documented on [2D render](https://docs.nursultan.fun/scripting/ui/render-2d#textures).

## Discord

| Method | Type | Description |
|---|---|---|
| `user.discord()` | `DiscordUser?` | Rich Presence account, null when Discord is not connected (API 2) |
| `discord.id()` | `String` | Discord snowflake id as a string, `"0"` when absent (API 2) |
| `discord.username()` | `String` | Discord username, `"Unknown"` when absent (API 2) |
| `discord.discriminator()` | `String` | legacy 4-digit discriminator, `"0"` on migrated accounts (API 2) |
| `discord.globalName()` | `String?` | Discord display (global) name, null when unset (API 2) |
| `discord.displayName()` | `String` | global name when non-blank, otherwise the username (API 2) |
| `discord.tag()` | `String` | `username` when the discriminator is `"0"`, else `username#discriminator` (API 2) |
| `discord.avatarHash()` | `String?` | raw avatar hash, null without a custom avatar (API 2) |
| `discord.avatarUrl()` | `String?` | avatar CDN url, null without a custom avatar (API 2) |
| `discord.effectiveAvatarUrl()` | `String` | `avatarUrl()` or the default Discord avatar url, never null (API 2) |
| `discord.bot()` | `boolean` | true when the account is a bot (API 2) |

`user.discord()` is null until the Rich Presence handshake finishes, so it can turn non-null mid-session. `avatarUrl()` ends in `.gif` when `avatarHash()` starts with `a_`, otherwise `.png`.

---

# Timers and tasks

`timer()` returns a fresh independent stopwatch on every call. Scheduled actions run on the client thread and only while the script is switched on.

```kotlin
val sinceAttack = timer()

on<ClientTickEvent> {
    if (sinceAttack.passedAndReset(10)) interaction.attackCrosshair()
}

everyTicks(100) { chat.print("still here") }
```

## Timers

| Method | Type | Description |
|---|---|---|
| `timer()` | `Timer` | a new independent stopwatch, already started |
| `elapsedTicks()` | `int` | client ticks since the last reset, clamped to 0..2147483647 |
| `elapsedMillis()` | `long` | wall-clock milliseconds since the last reset, never negative |
| `passed(ticks)` | `boolean` | true when `elapsedTicks() >= ticks` |
| `passedMillis(ms)` | `boolean` | true when `elapsedMillis() >= ms` |
| `passedAndReset(ticks)` | `boolean` | `passed(ticks)`, and resets when it returns true |
| `passedMillisAndReset(ms)` | `boolean` | `passedMillis(ms)`, and resets when it returns true |
| `reset()` | `void` | restarts both the tick and millisecond baselines |

Timer fields are volatile, so a timer can be read and reset off the client thread.

## Scheduling

| Method | Type | Description |
|---|---|---|
| `nextTick(action)` | `Task` | runs once after 1 client tick |
| `afterTicks(ticks, action)` | `Task` | runs once after that many client ticks (throws `ScriptException` when ticks < 0) |
| `everyTicks(ticks, action)` | `Task` | repeats every `ticks` client ticks, first run after 2×`ticks` (throws `ScriptException` when ticks < 1) |
| `client.tasks().nextTick(action)` | `Task` | `Tasks` form of `nextTick` |
| `client.tasks().afterTicks(ticks, action)` | `Task` | `Tasks` form of `afterTicks` |
| `client.tasks().everyTicks(ticks, action)` | `Task` | `Tasks` form of `everyTicks` |

`afterTicks(0, ...)` is accepted and the task is dropped before it ever runs; a null action throws `NullPointerException`.
A scheduled action is skipped while the script is off or unloaded, a throw is reported to the script console instead of propagating, and every outstanding task is cancelled on unload.

## The handle

| Method | Type | Description |
|---|---|---|
| `cancel()` | `void` | stops further runs and drops the handle from the script |
| `cancelled()` | `boolean` | true once cancelled |
| `close()` | `void` | calls `cancel()`, `Task` is `AutoCloseable` |

## Getting onto the client thread

| Method | Type | Description |
|---|---|---|
| `onClientThread(action)` | `Unit` | queues the action on the client thread, skipped when the script is off by then |
| `client.tasks().onClientThread(action)` | `void` | runs inline when already on the client thread, otherwise queues |

`PacketReceiveEvent` (netty IO thread) and `PacketSendEvent` (the sending thread) are the only events that do not fire on the client thread — see [Packets](https://docs.nursultan.fun/scripting/actions/packets).
World, player, inventory, container, interaction and rotation calls throw [`ScriptThreadException`](https://docs.nursultan.fun/scripting/extras/limits#exceptions) off the client thread.

## Time

| Method | Type | Description |
|---|---|---|
| `client.tick()` | `long` | client ticks since launch, never resets in a session |
| `client.millis()` | `long` | wall-clock milliseconds, loses precision once stored in a `float` |
| `client.nanos()` | `long` | monotonic nanoseconds, `System.nanoTime()` |
| `client.fps()` | `int` | frames per second reported by the client |
| `client.tickDelta()` | `float` | render progress between the last two ticks, 0..1 |
| `client.onClientThread()` | `boolean` | true when the caller runs on the client thread |

---

# Waypoints

`client.waypoints()` places client waypoints bound to the current server domain. A duration makes one temporary; no duration makes it permanent and saved into the waypoint config.

```kotlin
val waypoints = client.waypoints()

waypoints.add("Base", player.position())            // permanent
waypoints.add("Drop", player.position(), 20 * 60)   // 60 seconds

waypoints.remove("Drop")
waypoints.all().forEach { log.info(it.name()) }
```

## Adding one

| Method | Type | Description |
|---|---|---|
| `waypoints.add(name, position, durationTicks)` | `Waypoint` | temporary waypoint, expires after `durationTicks × 50` ms (throws `ScriptException` on a blank name or a duration below 1) |
| `waypoints.add(name, position)` | `Waypoint` | permanent waypoint, saved in the waypoint config (throws `ScriptException` on a blank name) |
| `waypoints.remove(name)` | `void` | removes every waypoint carrying that name (throws `ScriptException` on a blank name) |
| `waypoints.all()` | `List<Waypoint>` | snapshot of all current waypoints, party ones included |

`position` is a [`Vec`](https://docs.nursultan.fun/scripting/game/math) in blocks; names are not unique. `client.waypoints()` throws `ScriptStateException` after the script is unloaded.

## The marker

| Method | Type | Description |
|---|---|---|
| `name()` | `String` | waypoint name as registered |
| `position()` | `Vec` | world position in blocks |
| `permanent()` | `boolean` | true for a stored waypoint, false for a timed one |
| `remove()` | `void` | removes every waypoint carrying this name |

---

# Party messages

`client.party()` — in the DSL just `party` — carries small binary messages between the scripts of everyone in your party, laid out by a shape you declare. An event reaches whoever is online at that moment; a state is the last value you published under a topic, and the server hands it to whoever joins later.

```kotlin
val Appearance = shape("appearance") {
    string(1, "hat")
    int(2, "tint", default = 0xFFFFFF)
}

val cosmetics = party.channel("crashsystem:cosmetics")
val worn = mutableMapOf<String, String>()

cosmetics.onState(Appearance) { message ->
    worn[message.sender().login()] = message.string("hat")
}

cosmetics.onStateCleared(Appearance) { message ->
    worn.remove(message.sender().login())
}

onEnable {
    cosmetics.publish(Appearance, "hat" to "halo")
}
```

## The party

| Method | Type | Description |
|---|---|---|
| `party.connected()` | `boolean` | the client has a live socket session (API 4) |
| `party.inParty()` | `boolean` | you are in a party right now (API 4) |
| `party.self()` | `PartyMember?` | you, null outside a party (API 4) |
| `party.leader()` | `PartyMember?` | current leader, null outside a party (API 4) |
| `party.isLeader()` | `boolean` | you lead this party (API 4) |
| `party.code()` | `String` | the join code, empty outside a party (API 5) |
| `party.members()` | `List<PartyMember>` | immutable snapshot, you included (API 4) |
| `party.member(login)` | `PartyMember?` | member by account login, null when absent (API 4) |
| `party.channel(namespace)` | `PartyChannel` | opens the channel, or returns the one already open (API 4) (throws `ScriptException` on a malformed namespace, on one another loaded script holds, or past 8 channels) |
| `party.buffer()` | `PartyPayloadWriter` | empty writer for packing a `bytes` field yourself (API 4) |
| `party.reader(data)` | `PartyPayloadReader` | reader over a `bytes` field you packed (API 4) (throws `ScriptException` when `data` is null) |
| `party.maxEventBytes()` | `int` | 2048 (API 4) |
| `party.maxStateBytes()` | `int` | 1024 (API 4) |
| `party.maxStateTopics()` | `int` | 8 (API 4) |

## A member

| Method | Type | Description |
|---|---|---|
| `login()` | `String` | account login, stable across servers and worlds (API 4) |
| `name()` | `String` | Minecraft name, changes with the account's nickname (API 4) |
| `leader()` | `boolean` | leads the party (API 4) |
| `self()` | `boolean` | this member is you (API 4) |
| `color()` | `int` | server-assigned member colour, opaque ARGB, 0 when the sender is unknown (API 5) |
| `position()` | `Vec?` | last known position, null until one arrives (API 5) |
| `positionAge()` | `long` | ms since that position, `0` for yourself, -1 when there is none (API 5) |

Positions arrive twice a second, only for the other members and only while they are online; `position()` interpolates between the last two and stops at the newest instead of running past it, and your own entry returns the live player position.
The colour comes from a ten entry palette, distinct per member for as long as the party lives, so two members draw the same person the same way.

## A shape

| Declaration | Takes | Description |
|---|---|---|
| `shape(topic) { … }` | | declares the shape, the name is the topic (API 4) |
| `bool(id, name)` | `Boolean` | one varint byte (API 4) |
| `int(id, name)` | `Int` | zigzag varint, 1 to 5 bytes (API 4) |
| `long(id, name)` | `Long` | zigzag varint, 1 to 10 bytes (API 4) |
| `float(id, name)` | `Float` | 4 bytes (API 4) |
| `double(id, name)` | `Double` | 8 bytes (API 4) |
| `string(id, name)` | `String` | length plus utf-8, at most 512 bytes (API 4) |
| `bytes(id, name)` | `ByteArray` | length plus the raw array (API 4) |
| `uuid(id, name)` | `UUID` | 16 bytes (API 4) |
| `vec(id, name)` | `Vec` | three doubles, 24 bytes (API 4) |
| `struct(id, name, shape)` | `PartyStruct` | one nested shape (API 4) |
| `list(id, name, type)` | `List<Any>` | a list of one `PartyFieldType` (API 4) |
| `list(id, name, shape)` | `List<PartyStruct>` | a list of nested shapes (API 4) |
| `ints(id, name)` | `List<Int>` | a list of `INT` (API 4) |
| `longs(id, name)` | `List<Long>` | a list of `LONG` (API 4) |
| `floats(id, name)` | `List<Float>` | a list of `FLOAT` (API 4) |
| `doubles(id, name)` | `List<Double>` | a list of `DOUBLE` (API 4) |
| `strings(id, name)` | `List<String>` | a list of `STRING` (API 4) |
| `vecs(id, name)` | `List<Vec>` | a list of `VEC` (API 4) |
| `uuids(id, name)` | `List<UUID>` | a list of `UUID` (API 4) |

Every declaration except `bytes`, `uuid`, `struct` and the list forms also takes `default = …`, used when the sender did not send that field. Ids 1 to 15 cost one byte on the wire.
Only the id and the type go on the wire, so writing and reading in different orders is fine and a field the receiver does not declare is skipped by its wire type; reusing or reordering an id makes two versions of a script read each other wrong.

### PartyShape

| Method | Type | Description |
|---|---|---|
| `PartyShape.builder(name)` | `PartyShapeBuilder` | starts a shape without the DSL (API 4) (throws `ScriptException` when the name is not lowercase ASCII or is over 32 characters) |
| `shape.name()` | `String` | the topic this shape names (API 4) |
| `shape.fields()` | `List<PartyField>` | declared fields, in declaration order (API 4) |
| `shape.field(name)` | `PartyField?` | field by name, null when absent (API 4) |
| `shape.field(id)` | `PartyField?` | field by id, null when absent (API 4) |
| `shape.capacity()` | `int` | highest declared id plus one (API 4) |
| `shape.fieldNames()` | `String` | names joined by a comma (API 4) |
| `shape.toString()` | `String` | `name {id:field type, …}` (API 4) |
| `PartyShape.MAX_FIELD_ID` | `int` | 2047 (API 4) |
| `PartyShape.MAX_FIELDS` | `int` | 64 (API 4) |
| `PartyShape.MAX_FIELD_NAME_LENGTH` | `int` | 32 (API 4) |
| `Shape("field" to value, …)` | `PartyStruct` | builds a value for a `struct` or list field (API 4) |

### PartyShapeBuilder

| Method | Type | Description |
|---|---|---|
| `boolField(id, field)` | `PartyShapeBuilder` | Java name behind `bool(id, name)` (API 4) |
| `boolField(id, field, default)` | `PartyShapeBuilder` | bool field with a default (API 4) |
| `intField(id, field)` | `PartyShapeBuilder` | Java name behind `int(id, name)` (API 4) |
| `intField(id, field, default)` | `PartyShapeBuilder` | int field with a default (API 4) |
| `longField(id, field)` | `PartyShapeBuilder` | Java name behind `long(id, name)` (API 4) |
| `longField(id, field, default)` | `PartyShapeBuilder` | long field with a default (API 4) |
| `floatField(id, field)` | `PartyShapeBuilder` | Java name behind `float(id, name)` (API 4) |
| `floatField(id, field, default)` | `PartyShapeBuilder` | float field with a default (API 4) |
| `doubleField(id, field)` | `PartyShapeBuilder` | Java name behind `double(id, name)` (API 4) |
| `doubleField(id, field, default)` | `PartyShapeBuilder` | double field with a default (API 4) |
| `stringField(id, field)` | `PartyShapeBuilder` | Java name behind `string(id, name)` (API 4) |
| `stringField(id, field, default)` | `PartyShapeBuilder` | string field with a default (API 4) |
| `bytesField(id, field)` | `PartyShapeBuilder` | Java name behind `bytes(id, name)`, no default form (API 4) |
| `uuidField(id, field)` | `PartyShapeBuilder` | Java name behind `uuid(id, name)`, no default form (API 4) |
| `vecField(id, field)` | `PartyShapeBuilder` | Java name behind `vec(id, name)` (API 4) |
| `vecField(id, field, default)` | `PartyShapeBuilder` | vec field with a default (API 4) |
| `structField(id, field, shape)` | `PartyShapeBuilder` | Java name behind `struct(id, name, shape)` (API 4) (throws `ScriptException` when `shape` is null) |
| `listField(id, field, type)` | `PartyShapeBuilder` | list of one `PartyFieldType` (API 4) (throws `ScriptException` when the type is `LIST` or `STRUCT`) |
| `listField(id, field, shape)` | `PartyShapeBuilder` | list of nested shapes (API 4) (throws `ScriptException` when `shape` is null) |
| `build()` | `PartyShape` | finishes the shape, what `shape(topic) { … }` calls last (API 4) (throws `ScriptException` when no field was declared) |

Every method returns the builder, and every field declaration throws `ScriptException` when the id is outside `1..2047`, the field name is not ASCII or is over 32 characters, the shape already holds 64 fields, or the name or the id is taken.

### PartyField

| Method | Type | Description |
|---|---|---|
| `field.id()` | `int` | wire id, `1..2047` (API 4) |
| `field.name()` | `String` | field name, never sent on the wire (API 4) |
| `field.type()` | `PartyFieldType` | declared type (API 4) |
| `field.element()` | `PartyFieldType?` | list element type, null unless the field is a list (API 4) |
| `field.shape()` | `PartyShape?` | nested shape, null unless struct or list of structs (API 4) |
| `field.hasDefault()` | `boolean` | a default was declared (API 4) |
| `field.defaultValue()` | `Object?` | the declared default, null when there is none (API 4) |
| `field.typeLabel()` | `String` | `list of vec`, the nested shape name, or the type (API 4) |
| `field.toString()` | `String` | `name (id N, type)` (API 4) |

### PartyFieldType

| Value | Type | Description |
|---|---|---|
| `BOOL` | `PartyFieldType` | varint, 0 or 1 (API 4) |
| `INT` | `PartyFieldType` | zigzag varint (API 4) |
| `LONG` | `PartyFieldType` | zigzag varint (API 4) |
| `FLOAT` | `PartyFieldType` | fixed 4 bytes (API 4) |
| `DOUBLE` | `PartyFieldType` | fixed 8 bytes (API 4) |
| `STRING` | `PartyFieldType` | length plus utf-8, at most 512 bytes (API 4) |
| `BYTES` | `PartyFieldType` | length plus the raw bytes (API 4) |
| `UUID` | `PartyFieldType` | length plus 16 bytes (API 4) |
| `VEC` | `PartyFieldType` | length plus three doubles (API 4) |
| `STRUCT` | `PartyFieldType` | length plus a nested shape (API 4) |
| `LIST` | `PartyFieldType` | length plus a count and the elements (API 4) |
| `type.wire()` | `PartyWire` | the wire type this one maps to (API 4) |
| `type.label()` | `String` | lowercase constant name (API 4) |

### PartyWire

| Value | Type | Description |
|---|---|---|
| `VARINT` | `PartyWire` | code 0 (API 4) |
| `FIXED64` | `PartyWire` | code 1 (API 4) |
| `LENGTH` | `PartyWire` | code 2, length prefixed (API 4) |
| `FIXED32` | `PartyWire` | code 5 (API 4) |
| `wire.code()` | `int` | the 3-bit code packed into a field tag (API 4) |

### PartyStruct

| Method | Type | Description |
|---|---|---|
| `PartyStruct(shape)` | `PartyStruct` | empty value of that shape (API 4) (throws `ScriptException` when `shape` is null) |
| `struct.set(name, value)` | `PartyStruct` | sets one field (API 4) (throws `ScriptException` on an unknown field or a null value) |
| `struct.shape()` | `PartyShape` | the shape this value belongs to (API 4) |
| `struct.values()` | `Map<String, Object>` | the fields set so far, in insertion order (API 4) |

## A channel

| Method | Type | Description |
|---|---|---|
| `channel.namespace()` | `String` | namespace this channel was opened on (API 4) |
| `channel.send(shape, "field" to value, …)` | `PartySendResult` | sends an event to the whole party (API 4) |
| `channel.send(shape, …, target = target)` | `PartySendResult` | same, to one target (API 4) |
| `channel.send(shape, target) { set(name, value) }` | `PartySendResult` | block form of the same event (API 4) |
| `channel.publish(shape, "field" to value, …)` | `PartySendResult` | publishes state under the shape's topic (API 4) |
| `channel.publish(shape) { set(name, value) }` | `PartySendResult` | block form of the same publish (API 4) |
| `channel.clearState(shape)` | `PartySendResult` | drops that state on every member and on the server (API 4) |
| `channel.clearStates()` | `void` | clears every state this channel published (API 4) |
| `channel.publishedStates()` | `List<String>` | topics this channel currently holds state on (API 4) |
| `channel.onEvent(shape, handler)` | `Subscription` | handler for events on that shape's topic (API 4) |
| `channel.onEvent(shape, rule, handler)` | `Subscription` | same, filtered by `SenderRule` (API 4) |
| `channel.onState(shape, handler)` | `Subscription` | handler for state, also replays every sender's last known value (API 4) |
| `channel.onState(shape, rule, handler)` | `Subscription` | same, filtered by `SenderRule` (API 4) |
| `channel.onStateCleared(shape, handler)` | `Subscription` | handler for a cleared state (API 4) |
| `channel.onStateCleared(shape, rule, handler)` | `Subscription` | same, filtered by `SenderRule` (API 4) |

A namespace is `author:feature`: lowercase ASCII `[a-z0-9][a-z0-9._-]*` on both sides of the colon, at most 48 characters, no empty half. One loaded script holds a namespace at a time.
Handlers run on the client thread, one message at a time, inside the same error handling and CPU budget as any other script handler, and only while the script is loaded and enabled.

### PartyChannel

| Method | Type | Description |
|---|---|---|
| `channel.sendEvent(shape, body)` | `PartySendResult` | Java name behind `send(shape, …)` (API 4) |
| `channel.sendEvent(shape, target, body)` | `PartySendResult` | Java name behind `send(shape, …, target = …)` (API 4) |
| `channel.publishState(shape, body)` | `PartySendResult` | Java name behind `publish(shape, …)` (API 4) |
| `channel.clearState(topic)` | `PartySendResult` | topic form, for a shape you do not declare (API 4) (throws `ScriptException` on a malformed topic) |
| `channel.onStateCleared(topic, handler)` | `Subscription` | topic form of the cleared-state handler (API 4) |
| `channel.onStateCleared(topic, rule, handler)` | `Subscription` | same, filtered by `SenderRule` (API 4) |

### PartyShapedWriter

| Method | Type | Description |
|---|---|---|
| `writer.shape()` | `PartyShape` | the shape being written (API 4) |
| `writer.set(name, value)` | `PartyShapedWriter` | writes one field (API 4) (throws `ScriptException` on an unknown field, a null value, a wrong type, a field set twice, or a payload that no longer fits) |
| `writer.size()` | `int` | bytes written, including the 1-byte format marker (API 4) |
| `writer.remaining()` | `int` | bytes left before the limit (API 4) |
| `writer.limit()` | `int` | 2048 for an event, 1024 for state (API 4) |

The writer is the receiver of the `{ set(name, value) }` block. The order of `set` calls does not matter, and a field left unset never goes on the wire, so the receiver reads its declared default.

## Choosing who receives

| Method | Type | Description |
|---|---|---|
| `PartyTarget.all()` | `PartyTarget` | every other online member; you never receive your own broadcast (API 4) |
| `PartyTarget.leader()` | `PartyTarget` | the current leader only, nobody when you are the leader (API 4) |
| `PartyTarget.member(login)` | `PartyTarget` | one member by account login (API 4) |
| `PartyTarget.member(member)` | `PartyTarget` | one member by `PartyMember`, a null member sends `INVALID_TARGET` (API 4) |
| `target.kind()` | `PartyTargetKind` | `ALL`, `LEADER` or `MEMBER` (API 4) |
| `target.login()` | `String?` | login for `MEMBER`, null otherwise (API 4) |
| `target.toString()` | `String` | `all`, `leader` or `member(login)` (API 4) |

State is always party-wide: `publish` and `clearState` take no target.

### PartyTargetKind

| Value | Type | Description |
|---|---|---|
| `ALL` | `PartyTargetKind` | every other member (API 4) |
| `LEADER` | `PartyTargetKind` | the leader only (API 4) |
| `MEMBER` | `PartyTargetKind` | one named member (API 4) |

## Filtering who sent it

| Value | Type | Description |
|---|---|---|
| `SenderRule.ANY_MEMBER` | `SenderRule` | default, any member of your party (API 4) |
| `SenderRule.LEADER_ONLY` | `SenderRule` | only what the server marked as sent by the leader (API 4) |

## The result of a send

| Value | Type | Description |
|---|---|---|
| `SENT` | `PartySendResult` | handed to the socket (API 4) |
| `COALESCED` | `PartySendResult` | replaced a state publish that had not gone out yet (API 4) |
| `NOT_CONNECTED` | `PartySendResult` | no socket session; a state publish is remembered and republished on reconnect (API 4) |
| `NOT_IN_PARTY` | `PartySendResult` | you are in no party; a state publish is remembered and republished on join (API 4) |
| `INVALID_TARGET` | `PartySendResult` | the target login is not a current party member (API 4) |
| `TOO_LARGE` | `PartySendResult` | payload over the limit for its kind (API 4) |
| `STATE_LIMIT` | `PartySendResult` | you already hold 8 state topics (API 4) |
| `RATE_LIMITED` | `PartySendResult` | the client rate limiter dropped it (API 4) |
| `result.ok()` | `boolean` | true for `SENT` and `COALESCED` (API 4) |

## The message

| Method | Type | Description |
|---|---|---|
| `sender()` | `PartyMember` | filled in by the server, never by the payload (API 4) |
| `namespace()` | `String` | namespace it arrived on (API 4) |
| `topic()` | `String` | topic it arrived on (API 4) |
| `kind()` | `PartyMessageKind` | `EVENT`, `STATE_SET` or `STATE_CLEAR` (API 4) |

`sender().self()` is always false on a received message. An `onEvent` or `onState` handler receives a `PartyShapedMessage`, which is this table plus the decoded fields below; an `onStateCleared` handler receives this table only.

### PartyMessageKind

| Value | Type | Description |
|---|---|---|
| `EVENT` | `PartyMessageKind` | one-shot, never stored (API 4) |
| `STATE_SET` | `PartyMessageKind` | the last value for a topic (API 4) |
| `STATE_CLEAR` | `PartyMessageKind` | a stored state was dropped (API 4) |

## Reading fields

| Method | Type | Description |
|---|---|---|
| `shape()` | `PartyShape` | the shape it was decoded with (API 4) |
| `has(name)` | `boolean` | the sender actually sent this field (API 4) |
| `bool(name)` | `boolean` | (API 4) |
| `int(name)` | `int` | (API 4) |
| `long(name)` | `long` | (API 4) |
| `float(name)` | `float` | (API 4) |
| `double(name)` | `double` | (API 4) |
| `string(name)` | `String` | (API 4) |
| `bytes(name)` | `ByteArray` | fresh array (API 4) |
| `uuid(name)` | `UUID` | (API 4) |
| `vec(name)` | `Vec` | (API 4) |
| `struct(name)` | `PartyFields` | one nested shape, read with these same methods (API 4) |
| `structs(name)` | `List<PartyFields>` | a list of nested shapes (API 4) |
| `ints(name)` | `List<Int>` | a list of int (API 4) |
| `floats(name)` | `List<Float>` | a list of float (API 4) |
| `doubles(name)` | `List<Double>` | a list of double (API 4) |
| `strings(name)` | `List<String>` | a list of string (API 4) |
| `vecs(name)` | `List<Vec>` | a list of vec (API 4) |
| `dump()` | `String` | every field as one line, defaults marked (API 4) |

A field the sender left out returns its declared default; without a default it throws `ScriptException` naming the field. Asking for the wrong type throws too, and so does a name the shape does not declare.

### PartyFields

| Method | Type | Description |
|---|---|---|
| `booleanValue(name)` | `boolean` | Java name behind `bool(name)` (API 4) |
| `intValue(name)` | `int` | Java name behind `int(name)` (API 4) |
| `longValue(name)` | `long` | Java name behind `long(name)` (API 4) |
| `floatValue(name)` | `float` | Java name behind `float(name)` (API 4) |
| `doubleValue(name)` | `double` | Java name behind `double(name)` (API 4) |
| `values(name)` | `List<Object>` | boxed list field, behind `ints` `floats` `doubles` `strings` `vecs` `structs` (API 4) |

## Packing bytes yourself

| Method | Type | Description |
|---|---|---|
| `writeBoolean(value)` | `PartyPayloadWriter` | 1 byte (API 4) |
| `writeByte(value)` | `PartyPayloadWriter` | 1 byte, low 8 bits of the int (API 4) |
| `writeShort(value)` | `PartyPayloadWriter` | 2 bytes, big endian (API 4) |
| `writeInt(value)` | `PartyPayloadWriter` | 4 bytes, big endian (API 4) |
| `writeLong(value)` | `PartyPayloadWriter` | 8 bytes, big endian (API 4) |
| `writeFloat(value)` | `PartyPayloadWriter` | 4 bytes (API 4) |
| `writeDouble(value)` | `PartyPayloadWriter` | 8 bytes (API 4) |
| `writeString(value)` | `PartyPayloadWriter` | 2-byte length plus utf-8, at most 512 bytes (API 4) (throws `ScriptException` when null or longer) |
| `writeBytes(value)` | `PartyPayloadWriter` | 2-byte length plus a copy of the array (API 4) (throws `ScriptException` when null) |
| `writeUuid(value)` | `PartyPayloadWriter` | 16 bytes (API 4) (throws `ScriptException` when null) |
| `toByteArray()` | `ByteArray` | what you wrote, ready for a `bytes` field (API 4) |
| `size()` | `int` | bytes written (API 4) |
| `remaining()` | `int` | bytes left before the limit (API 4) |
| `limit()` | `int` | 2048 from `party.buffer()` (API 4) |

A `bytes` field carries whatever you put in it: `party.buffer()` hands out the writer, `party.reader(data)` reads it back, and both are positional, so read order has to match write order. Any write past the limit throws `ScriptException`.

### PartyPayloadReader

| Method | Type | Description |
|---|---|---|
| `readBoolean()` | `boolean` | 1 byte, non-zero is true (API 4) |
| `readByte()` | `byte` | one signed byte (API 4) |
| `readShort()` | `short` | 2 bytes, big endian (API 4) |
| `readInt()` | `int` | 4 bytes, big endian (API 4) |
| `readLong()` | `long` | 8 bytes, big endian (API 4) |
| `readFloat()` | `float` | 4 bytes (API 4) |
| `readDouble()` | `double` | 8 bytes (API 4) |
| `readString()` | `String` | 2-byte length plus utf-8 (API 4) |
| `readBytes()` | `ByteArray` | 2-byte length plus the bytes (API 4) |
| `readUuid()` | `UUID` | 16 bytes (API 4) |
| `size()` | `int` | payload length (API 4) |
| `remaining()` | `int` | bytes not read yet (API 4) |
| `hasMore()` | `boolean` | whether any bytes are left (API 4) |

Reading past the end throws `ScriptException`; the payload is a plain array, so a truncated or reordered read gives garbage rather than an error.

## Limits

| Limit | Value | Description |
|---|---|---|
| Event payload | `2048` | bytes per message |
| State payload | `1024` | bytes per topic |
| String inside a payload | `512` | bytes, and it counts toward the payload budget |
| Fields in a shape | `64` | |
| Field id | `1..2047` | 1 to 15 take one byte on the wire |
| Field name | `32` | ASCII characters |
| State topics | `8` | per account, across all your scripts |
| Namespace | `48` | ASCII characters |
| Topic | `32` | ASCII characters, the shape name is the topic |
| Channels | `8` | per script |
| State lifetime | `5 min` | since the last publish, unless republished |

Sends beyond the client rate limiter come back `RATE_LIMITED`; the server keeps its own, stricter budgets and drops what exceeds them without an error. State publishes coalesce per topic, so publishing on every tick costs one packet every few ticks and only the newest value goes out.

## What the server decides

| Fact | Description |
|---|---|
| Payload | opaque bytes; the server never reads a field or knows your shape |
| Sender | derived from the authenticated session, so a payload cannot claim to be someone else |
| Party | derived from the sender's current party; a message never leaves it |
| Leader | derived from the party, so `SenderRule.LEADER_ONLY` cannot be spoofed |
| Recipients | derived from the party; the client never sends a recipient list |
| State snapshot | sent to a member on join, with events never replayed |
| State cleanup | on leave, kick, disband, disconnect and after the lifetime above |

A namespace is a routing name, not an identity: it proves nothing about which script sent a message, only which account did.

---

# The assets folder

`assets` is `client.assets()` and reads files under `%APPDATA%\Nursultan\scripts\assets`. `base64(...)` is the alternative: it turns string literals in the `.kts` itself into bytes a font or an image can be built from. Everything on this page is API 2 except `sound`, which is API 9.

```kotlin
val greeting = assets.text("messages/hello.txt") ?: "no file"

val FONT = base64(
    "AAEAAAAOAIAAAwBgT1MvMg…",
    "…AAAAAAAAAAAAAAAAAAAA=",
)
font("myfont", FONT)

var siren: SoundHandle? = null
onEnable { siren = sound.loop("sounds/siren.ogg", 0.3f, 1f) }

on<Render2DEvent> { e ->
    e.render().text(greeting, 10f, 10f, 12f, Colors.WHITE, "myfont")
}

on<AttackEvent> {
    siren?.stop()
    sound.play("sounds/hit.wav", 0.6f, 1.2f)
}
```

## Reading a file

| Method | Type | Description |
|---|---|---|
| `assets.exists(path)` | `boolean` | true when the path resolves inside `scripts/assets` and is a regular file (API 2) |
| `assets.bytes(path)` | `byte[]?` | whole file, null when rejected, missing, over 8 MiB or unreadable (API 2) |
| `assets.text(path)` | `String?` | the same bytes decoded as UTF-8, null under the same conditions (API 2) |
| `assets.list()` | `List<String>` | sorted file names directly in the assets root, capped at 1024 (API 2) |
| `assets.list(directory)` | `List<String>` | same for one subfolder, empty when it does not resolve or is not a directory; null, blank or `"."` means the root (API 2) |

Paths are relative to `scripts/assets`, forward or backslash separated. Nothing here throws: a rejected, missing or oversized file gives `null` or an empty list plus one warning in the script console.
`list` returns file names only — no paths, no directories, no recursion.

## Playing a sound

`sound` is `client.sound()` and plays a `.wav` or `.ogg` file out of the same folder.

| Method | Type | Description |
|---|---|---|
| `sound.play(path)` | `SoundHandle?` | plays the file once at full volume, null when rejected (API 9) |
| `sound.play(path, volume, pitch)` | `SoundHandle?` | the same with volume `0..1` and pitch `0.5..2`, both clamped (API 9) |
| `sound.loop(path)` | `SoundHandle?` | plays the file over and over until it is stopped (API 9) |
| `sound.loop(path, volume, pitch)` | `SoundHandle?` | the same with volume `0..1` and pitch `0.5..2`, both clamped (API 9) |
| `sound.stopAll()` | `void` | stops every sound this script started (API 9) |
| `handle.path()` | `String` | the path the handle was made from (API 9) |
| `handle.stop()` | `void` | stops that one sound (API 9) |

`.wav` and `.ogg` decode, `.mp3` gives null; paths and rejections are the ones above.
A sound is flat and `volume` is its only level; every sound of a script stops when it is switched off or unloaded.

| Limit | Value |
|---|---|
| file size | 8 MiB |
| looping sounds at a time | 8 |
| calls per second | 32 |

Going over a limit warns once in the script console and returns null.

## What is rejected

| Rejected | What you get |
|---|---|
| `..` in any path segment | `null` / empty list |
| absolute path, drive letter or UNC path | `null` / empty list |
| empty, blank or malformed path | `null` / empty list |
| a path whose real target leaves `scripts/assets` | `null` / empty list |
| a file larger than 8 MiB | `null` from `bytes` and `text` |
| more than 1024 files in one folder | the first 1024 names, the rest skipped |

Each case warns once per path in the script console. There is no way to open a file by absolute path and nothing in the API writes files — for a script's own data see [Saving data](https://docs.nursultan.fun/scripting/settings/storage).

## Assets inside the script

| Method | Type | Description |
|---|---|---|
| `base64(vararg parts)` | `ByteArray` | joins the parts and MIME-decodes them, empty vararg gives an empty array (API 2) (throws `ScriptApiException` when the payload is not valid base64) |
| `base64Encode(bytes)` | `String` | standard base64 on one line, the other direction (API 2) |
| `font(name, ttf)` | `void` | registers a TTF family from bytes, ignored when the name is taken, the array is empty or over 8 MiB (API 2) |
| `image(name, png)` | `Texture?` | PNG from bytes cached under `name`, null for a blank name, empty bytes or over 8 MiB (API 2) |

The joined text may be a `data:` URL: everything up to and including `;base64,` is dropped, and a `data:` prefix without that marker throws `ScriptApiException`. Whitespace and line breaks inside a part are ignored.
A single string literal in a class file cannot exceed 64 KB, and Kotlin folds `"a" + "b"` back into one — that is why `base64` takes a vararg. `name` in `image(name, png)` is a per-script cache key, not a path; both byte overloads are also listed on [2D render](https://docs.nursultan.fun/scripting/ui/render-2d).

## Files from older scripts

`font(name, file)`, `image(file)`, `client.fonts().register(name, file)`, `client.textures().image(file)` and `Render.image(file, …)` fall back to the scripts root when the file is not in `scripts/assets`, and warn once in the console.
`exists`, `bytes`, `text` and `list` have no fallback — they only ever read `scripts/assets`. `texture(identifier)` takes a Minecraft resource id, not a file, and touches neither folder.

---

# Sandbox and limits

A script runs against a whitelist: the Kotlin standard library, `java.time`, `java.math`, `kotlin.random.Random` and the whole `nursultan.*` API. Every handler invocation carries a 250 ms budget.

```kotlin
on<ClientTickEvent> {
    try {
        if (world.block(player.position()).liquid()) control.jump()
    } catch (error: ScriptStateException) {
        log.warn("no world: ${error.message}")
    }
}
```

## What you get

| Package | Description |
|---|---|
| `nursultan.**` | the whole script API |
| `kotlin.*` | every class directly in the `kotlin` package, subpackages excluded |
| `kotlin.collections.**` | lists, maps, sets and their operators |
| `kotlin.sequences.**` | lazy sequences |
| `kotlin.ranges.**` | ranges and progressions |
| `kotlin.text.**` | strings, regex, `StringBuilder` |
| `kotlin.comparisons.**` | comparator builders |
| `kotlin.math.**` | math functions and constants |
| `kotlin.random.**` | `Random` |
| `kotlin.enums.**` | `entries` on enums |
| `kotlin.annotation.**` | annotation targets and retention |
| `kotlin.jvm.internal.**`, `kotlin.jvm.functions.**` | intrinsics and lambda types the compiler emits |
| `java.util.stream.**` | streams and collectors |
| `java.util.function.**` | functional interfaces |
| `java.time.**` | instants, durations, dates |
| `java.math.**` | `BigInteger`, `BigDecimal` |
| `java.lang` (single classes) | `String`, `StringBuilder`, `Math`, number wrappers, common exceptions |
| `java.util` (single classes) | collections, `Optional`, `UUID`, `Random`, `Locale`, `BitSet`, `Objects` |
| `java.util.concurrent.ThreadLocalRandom` | the only class allowed out of `java.util.concurrent` |
| `kotlin.reflect.KProperty*` | as a type only, for `by` delegates |

`nursultan.**` and `kotlin.random.Random` are default imports; the `kotlin.*` rows are Kotlin's own defaults.

## What is blocked

| Blocked | Description |
|---|---|
| `java.io`, `java.nio` | no file access; only [assets](https://docs.nursultan.fun/scripting/extras/assets) and [configs](https://docs.nursultan.fun/scripting/settings/storage) touch the disk |
| `java.net` | no sockets, no http |
| `java.lang.Thread`, `java.util.concurrent` | no threads, pools or timers, `ThreadLocalRandom` aside |
| `java.lang.Class`, `java.lang.reflect`, `kotlin.reflect` | no reflection; only the `KProperty` types pass |
| `java.lang.ClassLoader`, `java.lang.System` | no class loading, no process or environment access |
| `net.minecraft.**`, `fun.nursultan.**` | no direct game or client internals |
| `nursultan.internal.BudgetControl` | the one denied class inside `nursultan` |
| native methods | a `native` method in a script class is rejected |
| `invokedynamic` | only `LambdaMetafactory` and `StringConcatFactory` bootstraps pass |

The check runs over the compiled classes before the script executes: a violation fails the load with `script class <name> references blocked symbol: <symbol>` and nothing runs.

## Budgets

| What | Limit |
|---|---|
| one handler, command or callback invocation | 250 ms |
| the top level of the file at load | 5 s |
| throws in a row before the script switches off | 5 |
| error reports per script | one per 3000 ms, the rest counted as `(+N suppressed)` |

Overrunning throws `ScriptTimeoutError`, reports it and switches the script off; the deadline is checked every 512th instrumented jump.
One successful invocation resets the throw counter.

## Exceptions

| Exception | Extends | Thrown when |
|---|---|---|
| `ScriptException` | `RuntimeException` | bad argument, unknown module/setting/entry reference, invalid id or url |
| `ScriptStateException` | `ScriptException` | no world or player, entity left the world, script already unloaded |
| `ScriptThreadException` | `ScriptException` | an API call that needs the client thread ran off it |
| `ScriptApiException` | `ScriptException` | `requireApi(n)` with `n` above `ApiVersion.CURRENT` |
| `ScriptTimeoutError` | `Error` | the handler budget ran out |

Each takes a `String message`; `ScriptException` also has a `(message, cause)` constructor.
`ScriptTimeoutError` is an `Error`, not a `ScriptException` — catching it changes nothing, the script is reported and switched off anyway.

## Resource limits

| Resource | Limit |
|---|---|
| keys per config | 4096, `ScriptException` on the next new key |
| chars per config value | 65536, `ScriptException` above it |
| asset file | 8 MiB, `bytes()` and `text()` return null above it |
| entries per `assets.list()` | 1024, extra names dropped with one console warning |
| embedded font or PNG | 8 MiB, ignored with one console warning above it |
| live gpu resources per script | 64 meshes, pipelines and render types together, `IllegalStateException` |
| attributes per vertex format | 16, `IllegalArgumentException` |
| vertices per mesh | 1 048 576, `IllegalStateException` |
| indices per mesh | 4 194 304, `IllegalStateException` |

Mesh buffers are freed while the script is switched off; the resources still count against the 64 until the script unloads.

---

# API versions

`ApiVersion.CURRENT` is 10. `requireApi(n)` fails the script at load when the running client is older; it cannot rescue a compile error, because a name that does not exist on the older SDK never compiles in the first place.

```kotlin
requireApi(2)

name("Mesh demo")

// gpu arrived in API 2; on a v1 client this file refuses to load
val format = gpu.format(VertexAttribute.floats(3), VertexAttribute.color())
val mesh = gpu.indexedMesh(format)
```

## Requiring a version

| Method | Type | Description |
|---|---|---|
| `ApiVersion.CURRENT` | `int` | script API version of this client, currently 10 |
| `ApiVersion.require(minimum)` | `void` | static (throws `ScriptApiException` when `CURRENT` < `minimum`) |
| `requireApi(minimum)` | `Unit` | the DSL form of `ApiVersion.require` (throws `ScriptApiException` when `CURRENT` < `minimum`) |

`ApiVersion` has a private constructor: no instance, only the two static members, and the client appends `this client provides v10` to every `Unresolved reference` compile error.
Packet records follow the Minecraft version, not this number — see [Packets](https://docs.nursultan.fun/scripting/actions/packets).

## What each version added

### API 3

| Added in 3 | Documented on |
|---|---|
| `combat.explosionExposure(target, source)` | [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `combat.explosionDamage(target, source, power)` | [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `combat.explosionDamageTaken(target, source, power)` | [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `combat.damageAfterArmor(target, damage)` | [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `living.visibleEffects()` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `block.collisionBoxes()` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `block.outlineBoxes()` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `world.blockCollisionsIn(box)` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `world.isBlockSpaceFree(box)` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `RenderItemEvent.translate(x, y, z)` | [Event list](https://docs.nursultan.fun/scripting/events/reference) |
| `RenderItemEvent.rotate(degrees, axisX, axisY, axisZ)` | [Event list](https://docs.nursultan.fun/scripting/events/reference) |
| `RenderItemEvent.rotateX(degrees)` | [Event list](https://docs.nursultan.fun/scripting/events/reference) |
| `RenderItemEvent.rotateY(degrees)` | [Event list](https://docs.nursultan.fun/scripting/events/reference) |
| `RenderItemEvent.rotateZ(degrees)` | [Event list](https://docs.nursultan.fun/scripting/events/reference) |
| `RenderItemEvent.scale(x, y, z)` | [Event list](https://docs.nursultan.fun/scripting/events/reference) |
| `RenderItemEvent.Matrix` | [Event list](https://docs.nursultan.fun/scripting/events/reference) |

### API 4

| Added in 4 | Documented on |
|---|---|
| `client.party()` | [How a script works](https://docs.nursultan.fun/scripting/start/lifecycle) |
| `party` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `Party` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyChannel` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyMember` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyMessage` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyShapedMessage` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyMessageKind` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyFields` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyShape` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyShapeBuilder` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyField` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyFieldType` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyWire` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyStruct` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyShapedWriter` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyPayloadWriter` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyPayloadReader` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyTarget` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyTargetKind` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `SenderRule` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartySendResult` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| 43 `nursultan.dsl` party helpers — `shape`, the field builders, `send`, `publish`, the typed field readers | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `nursultan.party.*` as a default import | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `entity.isItem()` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `entity.asItemEntity()` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `ItemEntity` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |

### API 5

| Added in 5 | Documented on |
|---|---|
| `party.code()` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyMember.color()` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyMember.position()` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `PartyMember.positionAge()` | [Party messages](https://docs.nursultan.fun/scripting/extras/party) |
| `player.serverSprinting()` | [Your player](https://docs.nursultan.fun/scripting/game/player) |
| `player.velocity(value)` | [Your player](https://docs.nursultan.fun/scripting/game/player) |
| `render.pushScissor(x, y, width, height)` | [2D render](https://docs.nursultan.fun/scripting/ui/render-2d) |
| `render.popScissor()` | [2D render](https://docs.nursultan.fun/scripting/ui/render-2d) |

### API 6

| Added in 6 | Documented on |
|---|---|
| `rotations.quantized(rotation)` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `BackRotation` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `BackRotation.step(from, to, tick)` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `BackRotation.maxTicks()` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `BackRotations` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `BackRotations.SNAP` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `BackRotations.INSTANT` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `BackRotations.HUMANIZED` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `backRotation(maxTicks) { }` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `rotations.locked()` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `slots.hold(hotbarSlot)` | [Slots and armor](https://docs.nursultan.fun/scripting/actions/slots) |
| `slots.selected()` | [Slots and armor](https://docs.nursultan.fun/scripting/actions/slots) |
| `HeldSlot.holding()` | [Slots and armor](https://docs.nursultan.fun/scripting/actions/slots) |
| `interaction.useBlock(x, y, z, side, hand, hit)` | [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `interaction.placeBlock(x, y, z, side, hand, hit)` | [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `combat.explosionExposure(target, source, cover)` | [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `combat.explosionDamage(target, source, power, cover)` | [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `entity.serverPosition()` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `entity.interpolating()` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `world.canPlace(itemId, x, y, z)` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `world.respawnAnchorWorks(x, y, z)` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |

### API 7

| Added in 7 | Documented on |
|---|---|
| `entity.yaw(value)` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `entity.pitch(value)` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `entity.velocity(value)` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `entity.fallDistanceBlocks(value)` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `entity.noClip()` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `entity.noClip(value)` | [Entities and filters](https://docs.nursultan.fun/scripting/game/entities) |
| `render.blend()` | [2D render](https://docs.nursultan.fun/scripting/ui/render-2d) |
| `render.blend(mode)` | [2D render](https://docs.nursultan.fun/scripting/ui/render-2d) |
| `BlendMode.INVERT` | [Your own geometry](https://docs.nursultan.fun/scripting/ui/gpu) |
| `RotationOptions.lock()` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `RotationOptions.lock(value)` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `RotationOptions(priority, clientSide, strongCorrection, smoothBackRotation, normalizeMouseMovement, backRotation, lock)` | [Rotations](https://docs.nursultan.fun/scripting/actions/rotations) |
| `interaction.pendingAck()` | [Interaction](https://docs.nursultan.fun/scripting/actions/interaction) |
| `world.blockPending(x, y, z)` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |

### API 8

| Added in 8 | Documented on |
|---|---|
| `client.theme()` | [How a script works](https://docs.nursultan.fun/scripting/start/lifecycle) |
| `client.language()` | [How a script works](https://docs.nursultan.fun/scripting/start/lifecycle) |
| `language` | [How a script works](https://docs.nursultan.fun/scripting/start/lifecycle) |
| `theme` | [2D render](https://docs.nursultan.fun/scripting/ui/render-2d) |
| `Theme` | [2D render](https://docs.nursultan.fun/scripting/ui/render-2d) |

### API 9

| Added in 9 | Documented on |
|---|---|
| `client.sound()` | [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) |
| `sound` | [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) |
| `Sound` | [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) |
| `SoundHandle` | [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) |
| `sound.play(path)` | [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) |
| `sound.play(path, volume, pitch)` | [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) |
| `sound.loop(path)` | [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) |
| `sound.loop(path, volume, pitch)` | [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) |
| `sound.stopAll()` | [The assets folder](https://docs.nursultan.fun/scripting/extras/assets) |

### API 10

| Added in 10 | Documented on |
|---|---|
| `world.hideEntity(entity)` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `world.showEntity(entity)` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `world.entityHidden(entity)` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `world.captureModel(entity)` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `EntityModel` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |
| `ModelCuboid` | [World and blocks](https://docs.nursultan.fun/scripting/game/world) |

Nothing is gated per member: every addition above is present unconditionally in a client of that version, and `requireApi(n)` is the only check that exists.
API 1 is the surface that carries no marker at all; API 2 members are marked `(API 2)` in the tables of the page that documents them.

## Things that no longer do anything

`@NoEffect` marks an element that still exists and still compiles but whose value the client never reads.

| Method | Type | Description |
|---|---|---|
| `NoEffect.value()` | `String` | sentence saying why the element is never read |

`@Retention(CLASS)` — visible in the IDE and in the SDK jar, never through reflection.
Targets: type, method, field, parameter, record component.

### What is marked

| Member | Type | Description |
|---|---|---|
| `Priority` | `enum` | whole type marked, five constants kept so old scripts compile (no effect on dispatch order) |
| `EventOptions.priority()` | `Priority` | record component and its accessor (deprecated) (no effect: the value is never read) |
| `EventOptions.priority(priority)` | `EventOptions` | copy of `DEFAULT` carrying the value (deprecated) (no effect: the value is never read) |
| `ScriptScope.on<E>(priority, ignoreCancelled) { }` | `Subscription` | discards the argument (deprecated, drop the argument) |
| `ScriptScope.on(type, priority, ignoreCancelled) { }` | `Subscription` | discards the argument (deprecated, drop the argument) |
| `EntryScope.on<E>(priority, ignoreCancelled) { }` | `Subscription` | discards the argument (deprecated, drop the argument) |
| `EntryScope.on(type, priority, ignoreCancelled) { }` | `Subscription` | discards the argument (deprecated, drop the argument) |
| `RotationOptions.clientSide()` | `boolean` | record component and its accessor (deprecated) (no effect: the rotation always reaches the server) |
| `RotationOptions.clientSide(value)` | `RotationOptions` | copy carrying the value (deprecated) (no effect: the rotation always reaches the server) |
| `RotationOptions.normalizeMouseMovement()` | `boolean` | record component and its accessor (deprecated, use `rotations.quantized`) (no effect: the value is never read) |
| `RotationOptions.normalizeMouseMovement(value)` | `RotationOptions` | copy carrying the value (deprecated, use `rotations.quantized`) (no effect: the value is never read) |

All eleven still compile and still store what you give them; nothing reads the stored value.
The order that replaced `Priority` is on [Subscribing](https://docs.nursultan.fun/scripting/events/basics#priority-does-nothing), the two rotation flags on [Rotations](https://docs.nursultan.fun/scripting/actions/rotations#options).
Every one of them raises a compile warning in the script console, with the line it sits on.

### Deprecated but still working

| Member | Type | Description |
|---|---|---|
| `RotationOptions.smoothBackRotation()` | `boolean` | record component and its accessor (deprecated, use `backRotation`) |
| `RotationOptions.smoothBackRotation(value)` | `RotationOptions` | true turns a `SNAP` return into `HUMANIZED` (deprecated, use `backRotation`) |
| `BackRotation.FAST` | `BackRotation` | the return `BackRotations.SNAP` gives (deprecated, use `BackRotations.SNAP`) |
| `BackRotation.SMOOTH` | `BackRotation` | the return `BackRotations.HUMANIZED` gives (deprecated, use `BackRotations.HUMANIZED`) |

These four are aliases, not stubs: they kept their old shape of return when API 6 rewrote it, so a script written before it behaves the same.

## What a bump costs

The SDK api jar is named `nursultan-script-api-v<N>.jar`, so an update drops in a new file and rewrites `build.gradle.kts` to point at it; IDEA re-syncs the project once.
`ApiVersion.CURRENT` is part of the compile-cache key, so a bump invalidates every cached compiled script and forces a full recompile on the first launch after the update.

---

# MCP for AI agents

The client can expose its scripting runtime as an MCP server, so an agent can deploy, enable, configure and read
scripts; it is off by default and turned on in the Scripts tab. The script API itself is the rest of these docs,
starting at [Your first script](https://docs.nursultan.fun/scripting/start/first-script) and [Sandbox and limits](https://docs.nursultan.fun/scripting/extras/limits).

## Turning it on

Open the **Scripts** tab, press the **MCP** button in the header — left of the console button — and tick
**Enabled**. A notification reports whether the server came up; on success the link is already in the clipboard,
and the header button stays lit while the server runs.

| Control | Effect |
|---|---|
| `Enabled` | starts or stops the server; saved and restored on the next launch |
| `Copy link` | puts the current link back in the clipboard |
| `New token` | issues a new 32-byte token and restarts; the old link stops working at once |
| `New port` | takes a free port and restarts; the link changes |

The last three appear only while the server runs. The link is `http://127.0.0.1:<port>/mcp/<token>`; port and
token are saved, so it stays the same across launches.

The server binds `127.0.0.1` only and speaks JSON-RPC over HTTP POST (MCP protocol `2025-06-18`, 1 MiB body
limit); the token in the path is the only credential it checks, and a request carrying an `Origin` header or a
foreign `Host` gets a 404.

Register the link with the agent:

```bash
claude mcp add --transport http nursultan http://127.0.0.1:PORT/mcp/TOKEN
```

## The tools

| Tool | Arguments | Returns |
|---|---|---|
| `scripts_list` | — | `scriptsDir`, `assetsDir`, and per script `id`, `file`, `name`, `description`, `enabled`, `status` (`LOADING`/`WAITING`/`READY`/`ERROR`), `phase` (`Reading`/`Compiling`/`Starting`, absent once loaded), `error` |
| `script_source` | `id` | `id`, `file`, `source` |
| `script_deploy` | `name` (1..48 chars of `A-Za-z0-9 _-`), `source` (max 256 KiB) | writes `<name>.kts` into the scripts folder; `written`, `bytes` |
| `script_delete` | `id` | unloads the script and deletes its file; `unloaded`, `deleted` |
| `script_enable` | `id` | switches the script on, as its bind does; `enabled` |
| `script_disable` | `id` | switches the script off; `enabled` |
| `script_settings` | `id` | `id`, `name`, `enabled`, `status`, `bind`, and every setting |
| `script_setting_set` | `id`, `key`, `value` | writes one setting; `kind` plus the whole `settings` list |
| `script_bind_set` | `id`, `key` (`UNKNOWN` clears the bind), `mods` (GLFW bitmask, 0 when omitted) | rebinds the script; the new `bind` |
| `console_tail` | `sinceId` (omit for the whole buffer), `limit` (default 200, capped at the 1000-line buffer) | `lines` of `id`, `time`, `level` (`INFO`/`WARN`/`ERROR`), `text`, plus `lastId`, `revision`, `dropped` |
| `game_state` | — | `inGame`, `singleplayer`, `server`, and `dimension`, `x`, `y`, `z`, `username` while in a world |

No tool plays the game: nothing here moves the player, opens a screen or clicks a block. Every tool except
`scripts_list`, `script_source` and `script_deploy` runs on the client thread and fails after 5 s if the client
does not answer.

`script_deploy` only writes the file — the watcher recompiles on its own, so the outcome shows up in the next
`scripts_list`. `console_tail` is incremental: pass the previous `lastId` as `sinceId`; a `sinceId` past the
newest id returns the whole buffer with `reset: true`, because line ids restart with the client.

## Setting value shapes

`script_settings` reports a `kind` per setting, and `script_setting_set` expects a value shaped to match it.

| Kind | Value to send |
|---|---|
| `checkbox` | `true` / `false` |
| `slider` | a number; the report carries `min`, `max`, `step` |
| `rangeSlider` | `{"min": 1, "max": 4}`; the report carries `limitMin`, `limitMax`, `step` |
| `input` | a string; the report carries `placeholder` when the setting has one |
| `colorPicker` | an ARGB integer |
| `selectable` | the `name` of one option, matched case-insensitively |
| `combo` | an array of option names; every option not listed is deselected |
| `hotkey` | `"G"` or `{"key": "G", "mods": 2}`; `mods` is a GLFW bitmask |
| `button` | any value; sending it presses the button |
| `group` | nothing — a group holds no value and the write fails |

Every reported setting carries `key`, `label`, `kind`, `visible`, `modified` and `value`; a nested setting adds
`parent` and uses a dotted key (`Toggle.Only when toggled`) for both reading and writing.

Objects and arrays are accepted either as real JSON or as a JSON string; option names come from `options[].name`,
not from `label`.

---

# Examples

Four complete scripts you can drop into the scripts folder as they are. Each one is a whole working file rather than a fragment, and each shows a different side of the API.

* [**MineBlaze auto duel**](https://docs.nursultan.fun/scripting/examples/mineblaze-auto-duel) — a chat packet answered with a command: the smallest useful shape for a server-specific script.
* [**Bridge builder**](https://docs.nursultan.fun/scripting/examples/bridge-builder) — movement prediction, a crosshair raycast and a borrowed hotbar slot.
* [**Auto soup**](https://docs.nursultan.fun/scripting/examples/auto-soup) — held slots, inventory batches, and staying out of the client's way.
* [**Anarchy helper**](https://docs.nursultan.fun/scripting/examples/anarchyhelper) — packets, a config, a command and notifications tied together.

---

# MineBlaze auto duel

Answers `/next` when the server offers another round, and can throw an `ez` in first. The smallest useful shape a server-specific script has: read the chat out of the packet, act on the client thread.

```kotlin
name("MineBlaze Auto Duel")
description("Answers /next when a duel offers another round, and can say ez first")

val autoEz = checkBox("Auto EZ", false)

val PREFIX = "Дуэли"
val TRIGGER = "Хотите продолжить?"
val COOLDOWN_MS = 5000L

var lastSent = 0L

onEnable { lastSent = 0L }

on<PacketReceiveEvent> { e ->
    val text = when (val packet = e.packet()) {
        is S2CGameMessagePacket -> if (packet.overlay()) null else packet.content()
        is S2CProfilelessChatMessagePacket -> packet.message()
        is S2CChatMessagePacket -> packet.unsignedContent()
        else -> null
    }
    if (text == null || !text.contains(PREFIX) || !text.contains(TRIGGER)) return@on
    onClientThread {
        val now = client.millis()
        if (now - lastSent < COOLDOWN_MS) return@onClientThread
        lastSent = now
        if (autoEz.value()) {
            chat.sendToServer("ez")
        }
        chat.sendToServer("/next")
        log.info("offer to continue -> /next")
    }
}
```

## Things worth noticing

**The constants are the server's own words.** `PREFIX` and `TRIGGER` are matched against what MineBlaze prints, so they are written exactly as the server writes them — including the language. Point this at another server and those two lines are what you change.

**Three different packets for one chat message.** The same text arrives in a different shape depending on how the server sent it, which is why the `when` has three branches. `overlay()` is the action bar, not the chat, so it is skipped.

**Parsing on the network thread, sending on the client one.** The `when` runs where the packet arrives. Everything after it — reading the setting, sending chat — is inside `onClientThread`.

**A cooldown, because the offer can arrive twice.** Servers repeat that line, and two `/next` in a row would queue you into a round you did not want. `COOLDOWN_MS` makes the second one a no-op. Real time is right here rather than ticks, because the interval is the server's, not the game's.

**`chat.sendToServer` is exactly what typing it would do.** `ez` goes out as a chat message and `/next` as a command, for the same reason they would from the chat box.

---

# Bridge builder

Places a block under your feet on the face you are aiming at, and sneaks when the next step would drop you off the edge. An example of movement prediction, a crosshair raycast and a borrowed hotbar slot working together.

```kotlin
name("BridgeBuilder")
description("Places a block under your feet at the face you aim at, and sneaks when a step would drop you")

val safeWalk = checkBox("Safe walk", true)
val safeWalkTicks = slider("Safe walk ticks", 3, 1, 10)
val predictTicks = slider("Predict ticks", 2, 0, 6)
val maxDrop = slider("Max drop", 1f, 0f, 3f, 0.1f)
val delayTicks = slider("Delay in ticks", 1, 0, 10)
val swing = checkBox("Swing hand", true)
val debug = checkBox("Debug", false)

val sincePlace = timer()

fun offset(side: Side): Triple<Int, Int, Int> = when (side) {
    Side.DOWN -> Triple(0, -1, 0)
    Side.UP -> Triple(0, 1, 0)
    Side.NORTH -> Triple(0, 0, -1)
    Side.SOUTH -> Triple(0, 0, 1)
    Side.WEST -> Triple(-1, 0, 0)
    Side.EAST -> Triple(1, 0, 0)
}

fun blockSlot(): Slot? = (0 until Slot.HOTBAR_SIZE)
    .map { Slot.hotbar(it) }
    .firstOrNull { inventory.item(it).buildable() }

fun underFeet(box: Box, x: Int, y: Int, z: Int): Boolean {
    if (box.maxX() <= x || box.minX() >= x + 1.0) return false
    if (box.maxZ() <= z || box.minZ() >= z + 1.0) return false
    val top = y + 1.0
    return top <= box.minY() + 0.01 && box.minY() - top <= maxDrop.value()
}

on<MoveInputEvent> { e ->
    if (!safeWalk.value() || !inGame) return@on
    if (!player.onGround() || player.flying() || player.riding()) return@on

    val backOrSide = e.backward() || e.left() || e.right()
    if (!backOrSide) return@on

    val input = e.toInput().copy(forward = false, jump = false, sprint = false)
    if (prediction.after(safeWalkTicks.intValue(), input).onGround()) return@on
    e.sneak(true)
}

on<PrePlayerTickEvent> {
    if (!player.alive() || player.flying() || player.riding()) return@on
    if (!sincePlace.passed(delayTicks.intValue())) return@on
    if (inventory.busy() || game.screenOpen()) return@on

    val hit = raycast.crosshair(player.blockReachBlocks())
    if (hit !is Hit.OnBlock) return@on

    val against = world.block(hit.blockX(), hit.blockY(), hit.blockZ())
    if (!against.blocksMovement()) return@on

    val (dx, dy, dz) = offset(hit.side())
    val x = hit.blockX() + dx
    val y = hit.blockY() + dy
    val z = hit.blockZ() + dz

    val cell = world.block(x, y, z)
    if (cell.blocksMovement() || !cell.replaceable()) return@on

    val cellBox = Box(x.toDouble(), y.toDouble(), z.toDouble(), x + 1.0, y + 1.0, z + 1.0)
    if (!world.isFree(cellBox)) {
        if (debug.value()) chat.print("bridge: $x $y $z blocked by an entity")
        return@on
    }

    val ticks = predictTicks.intValue()
    val soon = if (ticks <= 0) null else prediction.after(ticks).box()
    if (!underFeet(player.box(), x, y, z) && (soon == null || !underFeet(soon, x, y, z))) {
        return@on
    }

    val slot = blockSlot() ?: return@on

    slots.using(slot) {
        interaction.placeBlock(hit.blockX(), hit.blockY(), hit.blockZ(), hit.side(), Hand.MAIN_HAND)
        if (swing.value()) {
            interaction.swing(Hand.MAIN_HAND)
        }
    }
    sincePlace.reset()

    if (debug.value()) {
        chat.print("bridge: $x $y $z against ${hit.blockX()} ${hit.blockY()} ${hit.blockZ()} ${hit.side()}")
    }
}
```

## Things worth noticing

**Two events, two jobs.** `MoveInputEvent` is the input the game is about to use, so that is where safe walk belongs — rewriting `sneak` there is the same as you having held shift. Placement lives in `PrePlayerTickEvent`, which runs before the tick that moves you.

**Safe walk asks the prediction, not the block below.** `prediction.after(ticks, input)` replays your movement with `forward`, `jump` and `sprint` stripped out, so the question is only about the sideways or backwards step that triggered it. If you would still be on the ground, nothing happens; if not, `e.sneak(true)`. Looking at the block under your feet instead would get slabs, stairs and edges wrong — the prediction runs the real physics.

**The block goes next to the face you hit, not into it.** `hit.side()` is the face the raycast landed on, `offset(...)` turns it into a step, and the cell that comes out has to be `replaceable()` before anything is sent. `world.isFree(cellBox)` is the second half of that check: a mob or a player standing in the cell blocks the placement just as well as a block would.

**`underFeet` is why it builds a bridge and not a wall.** A cell only counts if your hitbox overhangs it in x and z and its top sits at or just below your feet, no further down than `maxDrop`. `predictTicks` runs the same test against the box you will occupy in a couple of ticks, so the block is already there when you step off.

**`slots.using(slot) { }` borrows the hotbar and gives it back.** The blocks are found by asking each hotbar item whether it is `buildable()` — not `placeable()`, which would happily hand you sand, ice or a cobweb — and the swap lasts exactly as long as the place and the swing, so you never end a tick holding something you did not choose.

**Nothing runs while the client is busy with items.** `inventory.busy()` and `game.screenOpen()` keep the script out of the way while you or another module is moving things around.

---

# Auto soup

Eats mushroom stew when your health drops: swaps to it in the hotbar, right clicks, and hands the slot back. Refills the hotbar from the rest of the inventory and can throw the empty bowls away. An example of held slots, inventory batches and staying out of the client's way.

```kotlin
name("AutoSoup")
description("Swaps to soup in the hotbar, right clicks it and swaps back when health drops")

val health = slider("Health", 12, 1, 19)
val delayTicks = rangeSlider("Delay in ticks", 3f, 5f, 0f, 20f)
val holdTicks = slider("Hold before eating in ticks", 2, 0, 20)
val keepItemUse = checkBox("Don't interrupt item use", true)
val refill = checkBox("Refill hotbar", true)
val dropBowls = checkBox("Drop bowls", false)
val perBatch = slider("Items per batch", 2, 1, 9)
val batchDelay = slider("Batch delay in ticks", 1, 0, 10)

val SOUP = "minecraft:mushroom_stew"
val BOWL = "minecraft:bowl"

val sinceSoup = timer()
val sinceHold = timer()
val sinceDrop = timer()

var nextDelay = 0
var refilling = false
var held: HeldSlot? = null

fun releaseHold() {
    held?.restoreWhenSafe()
    held = null
}

fun rollDelay() {
    val from = delayTicks.from().toInt()
    val to = delayTicks.to().toInt()
    nextDelay = if (to <= from) from else Random.nextInt(from, to)
}

fun canMoveItems(): Boolean {
    val screen = game.screenKind()
    return screen == ScreenKind.NONE || screen == ScreenKind.INVENTORY || screen == ScreenKind.CHAT
}

fun hotbarSpace(): List<Slot> = (0 until Slot.HOTBAR_SIZE)
    .map { Slot.hotbar(it) }
    .filter { slot ->
        val item = inventory.item(slot)
        item.empty() || item.isA(BOWL)
    }

fun refillStep(): Boolean {
    if (!canMoveItems()) return false

    val space = hotbarSpace()
    val stock = inventory.findAll { it.isA(SOUP) }.filter { !it.inHotbar() }
    if (space.isEmpty() || stock.isEmpty()) {
        refilling = false
        return false
    }

    val moves = minOf(perBatch.intValue(), space.size, stock.size)
    val gap = batchDelay.intValue()
    inventory.batch { batch ->
        for (i in 0 until moves) {
            if (i > 0 && gap > 0) batch.delay(gap)
            batch.swap(stock[i], space[i])
        }
    }
    return true
}

fun dropStep() {
    if (!canMoveItems()) return
    if (!sinceDrop.passed(maxOf(batchDelay.intValue(), 1))) return

    val bowls = inventory.findAll { it.isA(BOWL) }
    if (bowls.isEmpty()) return

    val moves = minOf(perBatch.intValue(), bowls.size)
    val gap = batchDelay.intValue()
    inventory.batch { batch ->
        for (i in 0 until moves) {
            if (i > 0 && gap > 0) batch.delay(gap)
            batch.drop(bowls[i], true)
        }
    }
    sinceDrop.reset()
}

onEnable {
    sinceSoup.reset()
    nextDelay = 0
    refilling = false
}

onDisable {
    releaseHold()
}

on<PrePlayerTickEvent> {
    if (!player.alive()) {
        releaseHold()
        return@on
    }
    if (inventory.busy()) return@on

    val soup = inventory.findInHotbar(SOUP)
    val handFree = !keepItemUse.value() || !player.usingItem()

    if (held == null
        && soup.found()
        && handFree
        && player.health() <= health.intValue()
        && sinceSoup.passed(nextDelay)
    ) {
        held = slots.select(soup)
        sinceHold.reset()
    }

    val holding = held
    if (holding != null) {
        if (!inventory.item(Slot.hotbar(holding.slot())).isA(SOUP)) {
            releaseHold()
        } else if (sinceHold.passed(holdTicks.intValue())) {
            interaction.useItem(Hand.MAIN_HAND)
            releaseHold()
            rollDelay()
            sinceSoup.reset()
        }
        return@on
    }

    if (!refill.value()) {
        refilling = false
    } else if (!soup.found()) {
        refilling = true
    }

    if (refilling && refillStep()) return@on

    if (dropBowls.value()) {
        dropStep()
    }
}
```

## Things worth noticing

**The swap and the click are not the same tick.** `slots.using { }` would do both at once; here the slot is taken with `slots.select(...)`, held for `holdTicks`, and only then right clicked. That is what the manual form of a held slot is for, and `restoreWhenSafe()` gives the slot back without cutting the use short.

**The hold is re-checked every tick.** If the stew leaves the slot while it is held — eaten, dropped, moved by something else — `isA(SOUP)` fails and the slot goes straight back. A held slot that nobody releases is the one bug this shape can produce, which is also why `onDisable` releases it.

**A random gap between meals.** `rangeSlider` gives a from/to pair and `rollDelay()` picks a number inside it after every soup, so the interval is never the same twice.

**Item moves go through `inventory.batch`.** Each batch does at most `perBatch` moves with `batch.delay(gap)` between them. Clicking thirty-six slots inside one tick is exactly the thing a server notices; this spreads them out and lets the next tick decide whether to continue.

**Dropping bowls keeps a timer of its own on top of that.** With a zero gap a batch is over almost as soon as it started, and `inventory.busy()` stops guarding — the next tick would queue another one, plus a full inventory scan looking for bowls. `sinceDrop` puts at least a tick between batches. Refilling needs no such timer: it stops itself the moment there is no stock or no space, and it runs when you are already low, where waiting is the wrong answer.

**Moves only happen on screens where they are legal.** `game.screenKind()` has to be `NONE`, `INVENTORY` or `CHAT` — with a chest open, the click ids belong to that container, not to your inventory.

**`inventory.busy()` first, everything else after.** It is `true` while the client is already moving items, yours or another module's. Starting a batch on top of that is how two features fight over the same slot.

**`keepItemUse` is there because eating is not the only thing a right click does.** Without it the script would cut off a bow you were drawing or a potion you were drinking.

---

# Anarchy helper

Watches chat and your health, marks nearby deaths, warns on low health, and remembers spots via a command. An example of a script that ties packets, a config, a command and notifications together.

```kotlin
name("AnarchyHelper")
description("Marks, warnings and notes for anarchy")

key(Key.H)

val warnHealth = slider("Warn at health", 8f, 1f, 20f, 1f)
val markDeaths = checkBox("Mark deaths", true)
val deathMinutes = slider("Mark lives, minutes", 2, 1, 10)
    .visibleWhen { markDeaths.value() }
val notifyChat = checkBox("Catch mentions", true)
val watchWords = input("Words, comma separated", "tp,tpa,help")

val notes = config("notes")
val sinceWarn = timer()

var lastHealth = 20f

onEnable {
    lastHealth = 20f
    sinceWarn.reset()
}

fun words(): List<String> =
    watchWords.value()
        .split(",")
        .map { it.trim().lowercase() }
        .filter { it.isNotEmpty() }

on<ClientTickEvent> {
    whenInGame {
        val health = player.health()
        if (health < warnHealth.value() && health < lastHealth && sinceWarn.passedAndReset(40)) {
            notify("health " + health.toInt(), NotifyKind.WARN)
        }
        lastHealth = health
    }
}

on<PacketReceiveEvent> { e ->
    if (!notifyChat.value()) return@on
    val text = when (val packet = e.packet()) {
        is S2CGameMessagePacket -> if (packet.overlay()) null else packet.content()
        is S2CProfilelessChatMessagePacket -> packet.message()
        is S2CChatMessagePacket -> packet.unsignedContent()
        else -> null
    } ?: return@on

    val lower = text.lowercase()
    if (words().none { lower.contains(it) }) return@on

    onClientThread {
        notify("chat: " + text.take(48), NotifyKind.ACCENT)
    }
}

on<EntityRemoveEvent> { e ->
    if (!markDeaths.value()) return@on
    val entity = e.entity()
    if (!entity.isPlayer() || entity.isSelf()) return@on
    val living = entity.asLiving() ?: return@on
    if (living.health() > 0f) return@on
    if (entity.distanceTo(player.position()) > 48.0) return@on

    client.waypoints().add(entity.name(), entity.position(), deathMinutes.intValue() * 20 * 60)
    chat.print("marked where " + entity.name() + " went down")
}

command("note") {
    usage("<add|go|list|del>")
    alias("n")

    sub("add") {
        usage("<name>")
        runs {
            val name = arg(0)
            val position = player.position()
            notes.put(name, position.x().toInt().toString() + " "
                + position.y().toInt() + " " + position.z().toInt())
            notes.save()
            reply("saved " + name)
        }
    }

    sub("go") {
        usage("<name>")
        completes(0) { notes.keys().toList() }
        runs {
            val value = notes.get(arg(0), "")
            if (value.isEmpty()) {
                replyError("no note called " + arg(0))
                return@runs
            }
            val parts = value.split(" ")
            client.waypoints().add(arg(0), Vec.of(
                parts[0].toDouble(), parts[1].toDouble(), parts[2].toDouble()
            ))
            reply("marked " + value)
        }
    }

    sub("del") {
        usage("<name>")
        completes(0) { notes.keys().toList() }
        runs {
            notes.remove(arg(0))
            notes.save()
            reply("removed " + arg(0))
        }
    }

    sub("list") {
        runs {
            if (notes.keys().isEmpty()) {
                reply("no notes")
                return@runs
            }
            reply("notes: " + notes.keys().joinToString(", "))
        }
    }
}
```

## Things worth noticing

**Packets are read on the network thread, notifications shown on the client one.** Parsing the text can happen right away; anything touching the game is wrapped in `onClientThread`.

**Three different packets for the same thing.** A chat message arrives in different shapes depending on how the server sent it, which is why the `when` has three branches.

**A warning with a cooldown.** Without `sinceWarn` the notification would fire every tick while health is low. `passedAndReset(40)` limits it to once every two seconds, and only when health actually dropped.

**A config instead of a variable.** Notes have to survive a restart, so they live in `config("notes")` and are saved right after a change — the command runs rarely, so the disk is fine.

**Completions come from the same data.** `completes(0) { notes.keys().toList() }` means Tab offers exactly what is written down.

**A setting that hides itself.** `deathMinutes` means nothing when marks are off, so it has a `visibleWhen`.

---

# AutoBuy

AutoBuy snipes items off the FT auction for you: you describe once what you want and what you'll pay, and the client finds the listing and takes it faster than you could move the cursor.

It runs on **two clients at the same time**. One scrolls the auction, the other buys. A single client will not work — that is the whole point of the setup: while the checker refreshes `/ah`, the buyer is already opening the seller's listing.

![The Auto Buy tab](https://docs.nursultan.fun/assets/en/autobuy-01-tab.png)

---

## How it works

| Role | What it does |
| --- | --- |
| **Buyer** | Starts a local server and waits. When a match arrives, it runs `/ah <seller>`, finds the listing in their menu and buys it |
| **Checker** | Keeps the auction open, clicks the refresh button, reads price and seller from every listing's lore, and forwards the matching ones to the buyer |

The two clients talk **over the local network**.

Hence the one hard requirement: **both clients must run on the same computer and be the same version** — otherwise they look into different game folders and never find each other.

---

## Before you start

- Two FT accounts, both in a world on an anarchy server.
- Two Nursultan clients of the same version running on one PC.
- Money on the buyer's account. If the balance is below the listing price, the buyer silently skips the match.

---

## Step 1. Build your shopping list

Open the client menu and go to the **"Auto Buy"** tab. Items are grouped into categories: armor, arrows, blocks, consumables, potions, spheres, talismans, tools, other.

The switch on the right of a row adds the item to the list. Disabled items are ignored entirely — the checker never even looks at them.

![An item row](https://docs.nursultan.fun/assets/en/autobuy-02-item-row.png)

---

## Step 2. Configure each item

Click the **three dots** on the right of a row (or **right-click** the row) to open its settings.

![Item settings](https://docs.nursultan.fun/assets/en/autobuy-03-item-settings.png)

| Setting | What it does |
| --- | --- |
| **Max Price for Item** | Your price ceiling. Counted **per unit**: a stack of 16 for 32,000 is 2,000 apiece. While this is `0`, the item is never bought |
| **Include in Auto Parser** | Lets the auto-parser overwrite this item's price. On by default |
| **Min Count** | Stackable items only. Listings below that count are skipped |
| **Min Durability Percentage** | Damageable items only. Filters out worn-out armor and tools |
| **Ignore Thorns** | Armor only. Skips pieces enchanted with Thorns |

You can type prices by hand, but the auto-parser is faster.

---

## Step 3. Fill in prices with the auto-parser

The auto-parser walks the auction on its own, checks what the item currently sells for, and writes the result into "Max Price for Item".

The module's own settings live in **Misc → Auto Buy** (the three dots next to the module).

![Auto Buy module settings](https://docs.nursultan.fun/assets/en/autobuy-04-module-settings.png)

| Setting | What it does |
| --- | --- |
| **Mode** | This client's role: "Buyer" or "Checker" |
| **Decrease Prices** | How many percent to cut off the market price while parsing. 40 % by default |
| **Auto Parser** | Starts the auction sweep |

**How the price is calculated.** The parser runs `/ah search <item>`, collects the prices of every matching listing on the page, converts them to per-unit prices, takes the median, subtracts the "Decrease Prices" percentage and rounds to thousands.

**How to run it:**

1. Enable the Auto Buy module — without it the parser gets no game events.
2. Make sure the two clients aren't linked yet: the parser won't start while a checker is connected to a buyer.
3. Press **"Auto Parser"** and leave the game alone until it finishes.

The parser only visits items that are **enabled** and have **"Include in Auto Parser"** ticked. For every item it prices it logs a line with the name and the new price, and finishes with "Auto Parser successfully completed work".

![The auto-parser in chat](https://docs.nursultan.fun/assets/en/autobuy-05-autoparser-chat.png)

The parser understands the server's replies: if an item isn't listed it moves on; if the server asks it to wait after joining or complains about AFK, it postpones the item and comes back to it later.

---

## Step 4. Set up the buyer

On the first client:

1. **Misc → Auto Buy**, mode — **"Buyer"**.
2. Join a world on an anarchy server.
3. Enable the module.

The chat prints "AutoBuy is running on port …". That means the local server is up and waiting for a checker.

There is nothing else to do on this client — you don't open the auction, it opens on its own when a match comes in.

---

## Step 5. Set up the checker and go

On the second client:

1. **Misc → Auto Buy**, mode — **"Checker"**.
2. Join a world on an anarchy server.
3. Enable the module — the chat prints "Connected to …", and the buyer sees "Checker … connected".
4. Open the auction: `/ah`, or `/ah search <whatever you're after>`.

From here the client clicks refresh and reads the listings itself. Your job is to leave the menu open.

While the menu is open and the link is alive, **your movement is blocked** — walking and the rest are cut off. That's intended, not a bug: disable the module and control comes back.

---

## What happens on its own

- **Buying.** On a match, the checker forwards the listing to the buyer and pauses so it doesn't bury its partner in finds. The buyer runs `/ah <seller>`, locates the listing and takes it, then closes the menu and tells the checker to resume.
- **Price confirmation.** If the server asks about a suspicious price, the buyer confirms the purchase itself.
- **Balance check.** Listings above the buyer's current balance are skipped.
- **Shulkers.** A shulker is also checked by its contents: if something from your list is inside, the listing counts as a match — priced at the **whole shulker**.
- **Server hopping.** If the auction menu opens too slowly five times in a row, the client moves to the next anarchy server (`/an…`) and waits about 11 seconds before trying again. The checker reopens the auction with the last search you typed.

---

## Chat messages

| Message | Meaning |
| --- | --- |
| `AutoBuy is running on port …` | The buyer's local server is up |
| `Checker … connected` | The checker found the buyer (seen on the buyer) |
| `Connected to …` | The link is established (seen on the checker) |
| `Checker … disconnected` / `Disconnected from …` | The link dropped |
| `Port for AutoBuy not found…` | The checker couldn't find a buyer — see below |
| `Auto Parser successfully completed work` | The auction sweep is done |

---

## If something doesn't work

### "Port for AutoBuy not found…"

The buyer isn't running, or it started after the checker. Check in order: the second client is open, its mode is "Buyer", it is in a world, the module is enabled, and the chat showed "AutoBuy is running on port …". Order matters: buyer first, checker second.

### The clients don't see each other

Both must be the same version and run on the same computer — they find each other through a file in the game folder. Different versions mean different folders.

### Nothing gets bought even though listings exist

Usually the price: "Max Price for Item" is still zero, or below market. Also check that the item's switch is on, that the listing's count isn't below "Min Count", and that durability clears the threshold. And make sure the buyer can actually afford it.

### The auto-parser won't start

It refuses to run while the clients are linked. Disable the module on one of them, run the parser, then link them back up.

### The auto-parser skipped an item

That means nothing is listed right now, or no listing passed the checks. The old price is left alone — the parser never writes a zero.

---

## In short

1. Enable the items you want on the "Auto Buy" tab.
2. Run the auto-parser to fill in prices.
3. First client — "Buyer", join a world, enable the module.
4. Second client — "Checker", join a world, enable the module, open `/ah`.
5. Leave the auction open.
