@minecraftbot-com/plugin 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -1,177 +1,188 @@
1
- # @minecraftbot-com/plugin: guide for AI assistants (and people)
2
-
3
- MineBot runs Minecraft bots for its users. A **plugin** is TypeScript that controls those bots. It runs in its
4
- own process: on the developer's machine under `minebot dev`, or on MineBot's servers once uploaded. It talks to
5
- the bots over a socket; it never runs inside the bot.
6
-
7
- ## Shape of a plugin
8
-
9
- ```ts
10
- import { definePlugin, Block, BotEvent, ControlUnit, Permission, Setting, Storage, StorageScope } from "@minecraftbot-com/plugin";
11
-
12
- export default definePlugin({
13
- name: "Harvester",
14
- // Everything the code does must be declared here. A call outside the list throws PermissionDeniedError,
15
- // whose message names the permission to add.
16
- permissions: [Permission.WorldRead, Permission.Move, Permission.Interact, Permission.ChatRead, Permission.ChatSend],
17
- // Parts of the bot only this plugin drives while it runs.
18
- exclusive: [ControlUnit.Movement, ControlUnit.Look, ControlUnit.Hand],
19
- // Filled in per bot by the user on the dashboard (or with --settings under minebot dev).
20
- settings: {
21
- crop: Setting.block({ label: "Crop", options: [Block.Wheat, Block.Carrots], default: Block.Wheat }),
22
- radius: Setting.radius({ label: "Search radius", default: 16, max: 48 }),
23
- },
24
- // Kept between runs. Belongs to the user who installed the plugin; 1 MB per scope, 64 KB per value, JSON only.
25
- storage: {
26
- harvested: Storage.value({ scope: StorageScope.Bot, default: 0 }),
27
- },
28
-
29
- // Once per bot the plugin is enabled on. Returning keeps listeners alive; the bot stopping ends everything.
30
- async run(bot, { settings, storage, log, stats, warnings }) {
31
- bot.on(BotEvent.Chat, async message => {
32
- if (message.text === "!stats") await bot.say(`Harvested ${await storage.harvested.get()}`);
33
- });
34
-
35
- await bot.loop(async () => {
36
- const crops = await bot.world.findBlocks({ block: settings.crop, state: { age: 7 }, radius: settings.radius, limit: 8 });
37
- if (crops.length === 0) return bot.wait({ seconds: 5 });
38
- for (const crop of crops) {
39
- const moved = await bot.goto(crop.position, { within: 3 });
40
- if (!moved.ok) { log.warn(`Can't reach ${crop.position}: ${moved.reason}`); continue; }
41
- if ((await bot.dig(crop.position)).ok) stats.set("Harvested", await storage.harvested.update(n => n + 1));
42
- }
43
- });
44
- },
45
- });
46
- ```
47
-
48
- `runProfile(profile, context)` is the profile-wide counterpart of `run`: it runs once while the profile runs
49
- (see "Profile" below).
50
-
51
- ## Rules
52
-
53
- 1. **One import.** Everything comes from `@minecraftbot-com/plugin`; tests use `@minecraftbot-com/plugin/testing`.
54
- 2. **Enums, not strings.** `Block.OakLog`, `Item.Bread`, `Entity.Zombie`, `Effect.Speed`, `BotEvent.Chat`,
55
- `Permission.Move`, `BuiltInPlugin.AutoEater`. Their values are namespaced ids (`"minecraft:oak_log"`) and the
56
- names come from the newest Minecraft version; on an older server a missing block finds nothing
57
- (`await bot.supports(Block.X)` checks first).
58
- 3. **Expected failures are values.** `goto`, `dig`, `place`, `attack`, `equip`... return
59
- `{ ok: true } | { ok: false, reason, message }`; `reason` is an enum (`MoveFailure.NoPath`,
60
- `DigFailure.OutOfReach`). Exceptions (`PluginError`) mean a mistake in the code: a missing permission, bad
61
- arguments, too many calls.
62
- 4. **Units are in the name.** `{ seconds: 5 }`, `{ ticks: 20 }`, `{ minutes: 1 }`. Distances and radii are blocks.
63
- 5. **Lifetimes are automatic.** When a bot stops (user stopped it, it disconnected), everything waiting in its
64
- `run` ends with a `StoppedError` the SDK swallows. You don't need cancellation tokens or cleanup.
65
- 6. **Repeat with `bot.loop`.** It runs the body again and again with a floor between runs (one tick, or
66
- `{ every }`) and backs off when it throws (the error is logged). Never write `while (true)` without awaiting
67
- something: hosted plugins are cut off after 50 ms of continuous CPU.
68
- 7. **No tick hooks, no packets.** The API is intent-level (walk there, dig this). Movement, anti-cheat and world
69
- data stay in the bot.
70
- 8. **Positions** the SDK returns are `Position` objects: they print as `x y z` in template strings and have
71
- `offset`, `distanceTo`, `floored`, `equals`. Anything with `x`, `y`, `z` works as input; `vec3(x, y, z)` makes one.
72
-
73
- ## The bot (`run(bot)`)
74
-
75
- | Call | Permission | Returns |
76
- |---|---|---|
77
- | `bot.name`, `bot.uuid`, `bot.id`, `bot.version` | none | the bot's Minecraft name, account uuid, profile id, server version |
78
- | `bot.status()` | none | `{ health, food, saturation, alive, gameMode, dimension, experienceLevel }` |
79
- | `bot.position()` | WorldRead | `Position` |
80
- | `bot.goto(pos, { within?, timeout? })` | Move | `Result<MoveFailure>` |
81
- | `bot.follow(entity, { distance?, timeout? })` | Move | `Result<MoveFailure>` when the target is lost or time runs out |
82
- | `bot.stopMoving()`, `bot.lookAt(pos)`, `bot.jump()` | Move | |
83
- | `bot.dig(pos)` | Interact | `Result<DigFailure>`; the block must be within reach (~4.5 blocks) |
84
- | `bot.place(pos, item)` | Interact | `Result<PlaceFailure>` |
85
- | `bot.activateBlock(pos)` | Interact | `Result<InteractFailure>`: doors, buttons, levers, chests |
86
- | `bot.useItem()` | Interact | `Result<InteractFailure>`: the held item (eat, throw) |
87
- | `bot.attack(entity)` | Attack | `Result<AttackFailure>`; within ~3 blocks |
88
- | `bot.say(text)` | ChatSend | chat only; a leading `/` is refused |
89
- | `bot.command("home")` | Commands | runs `/home` |
90
- | `bot.world.block(pos)` | WorldRead | `{ position, block, state }` or null if not loaded |
91
- | `bot.world.findBlocks({ block, state?, radius?, limit?, from? })` | WorldRead | closest first; `state` is typed per block |
92
- | `bot.entities.nearby({ type?, radius?, limit? })` | EntitiesRead | `EntityInfo[]` closest first |
93
- | `bot.entities.players()` | EntitiesRead | the server's player list |
94
- | `bot.inventory.items()`, `.held()`, `.count(item)` | InventoryRead | |
95
- | `bot.inventory.equip(item, slot?)`, `.drop(item, { count? })` | InventoryManage | `Result<InventoryFailure>` |
96
- | `bot.craft(item, { count?, table? })` | InventoryManage | `Result<CraftFailure, { crafted }>`; 2x2 recipes in the inventory, bigger ones on a crafting table within reach |
97
- | `bot.recipes(item)` | none | `Recipe[]`: `{ result, count, table, ingredients: [{ items, count }] }` on this server |
98
- | `bot.containers.open(pos)` | InventoryManage | `Result<ContainerFailure, Container>`; chest, barrel, shulker box, hopper, furnace, ... within reach |
99
- | `container.items()`, `.count(item)` | InventoryManage | what the open container holds |
100
- | `container.deposit(item, { count? })`, `.withdraw(item, { count? })` | InventoryManage | `Result<ContainerFailure, { moved }>`: all of the item, or `count` |
101
- | `container.close()` | InventoryManage | one container is open per bot; it closes on its own when another opens or the plugin stops |
102
- | `bot.plugins.start(BuiltInPlugin.X)`, `.stop(...)` | ProfilePlugins | starts a plugin instance the profile already has |
103
- | `bot.connect()`, `bot.disconnect()`, `bot.reconnect({ after? })` | ProfileBots | `Result<BotControlFailure>` |
104
- | `bot.on(BotEvent.X, listener)` | see below | returns a function that stops listening |
105
- | `bot.wait(duration)`, `bot.loop(body, { every? })` | none | |
106
-
107
- Events: `Chat` (needs ChatRead) gives `{ text, sender, senderUuid, system }`; `PlayerJoined` and `PlayerLeft`
108
- (EntitiesRead) give `{ player: { name, uuid } }`; `Died`, `Respawned`, `HealthChanged` (`{ health, food }`) need
109
- nothing.
110
-
111
- ## Context (`run(bot, context)`)
112
-
113
- - `settings`: typed from the `settings` declaration; missing values are the defaults.
114
- - `storage.name.get()`, `.set(v)`, `.delete()`, `.update(fn)`; maps add `get(key)`, `set(key, v)`, `keys()`,
115
- `entries()`. `update` is lossless when several bots write at once. Bot-scoped entries are bound to the bot in
116
- `run`; in `runProfile` pick one with `storage.name.for(bot)`.
117
- - `log.info/warn/error/debug(message)`: the plugin console on the dashboard and the terminal under `minebot dev`.
118
- - `stats.set(name, n)`, `stats.add(name, n?)`: numbers on the plugin's card.
119
- - `warnings.set(key, message)`, `warnings.clear(key)`: problems shown on the plugin's card until cleared.
120
-
121
- ## Profile (`runProfile(profile)`)
122
-
123
- `profile.bots()` lists every bot of the profile (`ProfileBot`: `id`, `name`, `uuid`, `connected`, `enabled`,
124
- `connect()`, `disconnect()`, `reconnect()`, `plugins`); `profile.bot(nameOrUuid)` finds one;
125
- `profile.on(ProfileEvent.BotConnected | BotDisconnected, listener)` gives `{ bot }` / `{ bot, reason }`.
126
- Connecting and disconnecting need `Permission.ProfileBots`.
127
-
128
- ## Network
129
-
130
- `fetch` is the standard one, limited to what the plugin declares: `Permission.network("api.example.com")`,
131
- `Permission.network("*.example.com")` for subdomains, or the exact origin a user typed into a `Setting.url`.
132
- HTTPS only; redirects are followed only to allowed hosts. Hosted: 10 s timeout, 64 KB request and 256 KB
133
- response bodies, about 60 requests a minute. Keys and webhooks belong in `Setting.secret()` or
134
- `Setting.url({ secret: true })`: stored encrypted and never shown to the plugin's author.
135
-
136
- ## Testing
137
-
138
- ```ts
139
- import { test } from "node:test";
140
- import assert from "node:assert/strict";
141
- import { Block } from "@minecraftbot-com/plugin";
142
- import { testPlugin } from "@minecraftbot-com/plugin/testing";
143
- import plugin from "../src/index.js";
144
-
145
- test("digs ripe wheat", async () => {
146
- const run = await testPlugin(plugin, {
147
- bots: [{ id: "bot-1", name: "Farmer", position: { x: 0, y: 64, z: 0 } }],
148
- blocks: [{ position: { x: 2, y: 64, z: 0 }, block: Block.Wheat, state: { age: 7 } }],
149
- });
150
- await run.until(() => run.container.blocks.size === 0);
151
- await run.stop();
152
- });
153
- ```
154
-
155
- The fake bot (`run.container`) checks permissions like the real one and records `said`, `commands`, `calls`,
156
- `logs`, `stats`, `warnings`, `storage` and `chests`. It crafts what `recipes: [{ result, ingredients: { [Item.Wheat]: 3 },
157
- count?, table? }]` lists, and opens what `containers: [{ position, items?, size? }]` places; `chat(bot, text, sender)`, `emit(bot, event, data)`,
158
- `disconnectBot(bot)`, `stopBot(bot)` drive it. `minebot test` runs `test/*.test.ts`.
159
-
160
- ## Live, under `minebot dev`
161
-
162
- `minebot dev` serves MCP at `http://127.0.0.1:7788/mcp` (it prints the address; `--mcp-port`, `--no-mcp`), for
163
- agents working on the plugin while it runs on the user's bots:
164
-
165
- - `status`: build and connection state, the profile's bots and which the plugin runs on, granted permissions, settings.
166
- - `logs`: what the plugin logged, plus build and connection lines; pass `since` (the last call's `next`) for new ones.
167
- - `reload`: rebuild and restart, then report whether the build passed and the plugin connected.
168
- - `query`: one read-only call as the plugin (`bot.position`, `world.findBlocks`, `entities.nearby`,
169
- `inventory.items`, `storage.get`, ...). It needs the plugin's permissions and never moves or changes anything.
170
-
171
- Saving a file restarts the plugin on its own; `reload` is for waiting on the outcome.
172
-
173
- ## Limits when hosted
174
-
175
- About 1.5 MB of memory after start (bundled libraries are the usual cost; import only what you use), 50 ms of
176
- CPU at a time, roughly 50 calls per second per bot, 256 queued events (the oldest are dropped first). No Node
177
- built-ins (`fs`, `child_process`, ...), no `Intl`. `minebot check` reports the bundle size and the permissions.
1
+ # @minecraftbot-com/plugin: guide for AI assistants (and people)
2
+
3
+ MineBot runs Minecraft bots for its users. A **plugin** is TypeScript that controls those bots. It runs in its
4
+ own process: on the developer's machine under `minebot dev`, or on MineBot's servers once uploaded. It talks to
5
+ the bots over a socket; it never runs inside the bot.
6
+
7
+ ## Shape of a plugin
8
+
9
+ ```ts
10
+ import { definePlugin, Block, BotEvent, ControlUnit, Permission, Setting, Storage, StorageScope } from "@minecraftbot-com/plugin";
11
+
12
+ export default definePlugin({
13
+ name: "Harvester",
14
+ // Everything the code does must be declared here. A call outside the list throws PermissionDeniedError,
15
+ // whose message names the permission to add.
16
+ permissions: [Permission.WorldRead, Permission.Move, Permission.Interact, Permission.ChatRead, Permission.ChatSend],
17
+ // Parts of the bot only this plugin drives while it runs.
18
+ exclusive: [ControlUnit.Movement, ControlUnit.Look, ControlUnit.Hand],
19
+ // Filled in per bot by the user on the dashboard (or with --settings under minebot dev).
20
+ settings: {
21
+ crop: Setting.block({ label: "Crop", options: [Block.Wheat, Block.Carrots], default: Block.Wheat }),
22
+ radius: Setting.radius({ label: "Search radius", default: 16, max: 48 }),
23
+ },
24
+ // Kept between runs. Belongs to the user who installed the plugin; 1 MB per scope, 64 KB per value, JSON only.
25
+ storage: {
26
+ harvested: Storage.value({ scope: StorageScope.Bot, default: 0 }),
27
+ },
28
+
29
+ // Once per bot the plugin is enabled on. Returning keeps listeners alive; the bot stopping ends everything.
30
+ async run(bot, { settings, storage, log, stats, warnings }) {
31
+ bot.on(BotEvent.Chat, async message => {
32
+ if (message.text === "!stats") await bot.say(`Harvested ${await storage.harvested.get()}`);
33
+ });
34
+
35
+ await bot.loop(async () => {
36
+ const crops = await bot.world.findBlocks({ block: settings.crop, state: { age: 7 }, radius: settings.radius, limit: 8 });
37
+ if (crops.length === 0) return bot.wait({ seconds: 5 });
38
+ for (const crop of crops) {
39
+ const moved = await bot.goto(crop.position, { within: 3 });
40
+ if (!moved.ok) { log.warn(`Can't reach ${crop.position}: ${moved.reason}`); continue; }
41
+ if ((await bot.dig(crop.position)).ok) stats.set("Harvested", await storage.harvested.update(n => n + 1));
42
+ }
43
+ });
44
+ },
45
+ });
46
+ ```
47
+
48
+ `runProfile(profile, context)` is the profile-wide counterpart of `run`: it runs once while the profile runs
49
+ (see "Profile" below).
50
+
51
+ ## Rules
52
+
53
+ 1. **One import.** Everything comes from `@minecraftbot-com/plugin`; tests use `@minecraftbot-com/plugin/testing`.
54
+ 2. **Enums, not strings.** `Block.OakLog`, `Item.Bread`, `Entity.Zombie`, `Effect.Speed`, `BotEvent.Chat`,
55
+ `Permission.Move`, `BuiltInPlugin.AutoEater`. Their values are namespaced ids (`"minecraft:oak_log"`) and the
56
+ names come from the newest Minecraft version; on an older server a missing block finds nothing
57
+ (`await bot.supports(Block.X)` checks first).
58
+ 3. **Expected failures are values.** `goto`, `dig`, `place`, `attack`, `equip`... return
59
+ `{ ok: true } | { ok: false, reason, message }`; `reason` is an enum (`MoveFailure.NoPath`,
60
+ `DigFailure.OutOfReach`). Exceptions (`PluginError`) mean a mistake in the code: a missing permission, bad
61
+ arguments, too many calls.
62
+ 4. **Units are in the name.** `{ seconds: 5 }`, `{ ticks: 20 }`, `{ minutes: 1 }`. Distances and radii are blocks.
63
+ 5. **Lifetimes are automatic.** When a bot stops (user stopped it, it disconnected), everything waiting in its
64
+ `run` ends with a `StoppedError` the SDK swallows. You don't need cancellation tokens or cleanup.
65
+ 6. **Repeat with `bot.loop`.** It runs the body again and again with a floor between runs (one tick, or
66
+ `{ every }`) and backs off when it throws (the error is logged). Never write `while (true)` without awaiting
67
+ something: hosted plugins are cut off after 50 ms of continuous CPU.
68
+ 7. **No tick hooks, no packets.** The API is intent-level (walk there, dig this). Movement, anti-cheat and world
69
+ data stay in the bot.
70
+ 8. **Positions** the SDK returns are `Position` objects: they print as `x y z` in template strings and have
71
+ `offset`, `distanceTo`, `floored`, `equals`. Anything with `x`, `y`, `z` works as input; `vec3(x, y, z)` makes one.
72
+
73
+ ## The bot (`run(bot)`)
74
+
75
+ | Call | Permission | Returns |
76
+ |---|---|---|
77
+ | `bot.name`, `bot.uuid`, `bot.id`, `bot.version` | none | the bot's Minecraft name, account uuid, profile id, server version |
78
+ | `bot.status()` | none | `{ health, food, saturation, alive, gameMode, dimension, experienceLevel }` |
79
+ | `bot.position()` | WorldRead | `Position` |
80
+ | `bot.goto(pos, { within?, timeout? })` | Move | `Result<MoveFailure>` |
81
+ | `bot.follow(entity, { distance?, timeout? })` | Move | `Result<MoveFailure>` when the target is lost or time runs out |
82
+ | `bot.stopMoving()`, `bot.lookAt(pos)`, `bot.jump()` | Move | |
83
+ | `bot.dig(pos)` | Interact | `Result<DigFailure>`; the block must be within reach (~4.5 blocks) |
84
+ | `bot.place(pos, item)` | Interact | `Result<PlaceFailure>` |
85
+ | `bot.activateBlock(pos)` | Interact | `Result<InteractFailure>`: doors, buttons, levers, chests |
86
+ | `bot.useItem()` | Interact | `Result<InteractFailure>`: the held item (eat, throw) |
87
+ | `bot.attack(entity)` | Attack | `Result<AttackFailure>`; within ~3 blocks |
88
+ | `bot.say(text)` | ChatSend | chat only; a leading `/` is refused |
89
+ | `bot.command("home")` | Commands | runs `/home` |
90
+ | `bot.world.block(pos)` | WorldRead | `{ position, block, state }` or null if not loaded |
91
+ | `bot.world.findBlocks({ block, state?, radius?, limit?, from? })` | WorldRead | closest first; `state` is typed per block |
92
+ | `bot.entities.nearby({ type?, radius?, limit? })` | EntitiesRead | `EntityInfo[]` closest first |
93
+ | `bot.entities.players()` | EntitiesRead | the server's player list |
94
+ | `bot.inventory.items()`, `.held()`, `.count(item)` | InventoryRead | |
95
+ | `bot.inventory.equip(item, slot?)`, `.drop(item, { count? })` | InventoryManage | `Result<InventoryFailure>` |
96
+ | `bot.craft(item, { count?, table? })` | InventoryManage | `Result<CraftFailure, { crafted }>`; 2x2 recipes in the inventory, bigger ones on a crafting table within reach |
97
+ | `bot.recipes(item)` | none | `Recipe[]`: `{ result, count, table, ingredients: [{ items, count }] }` on this server |
98
+ | `bot.containers.open(pos)` | InventoryManage | `Result<ContainerFailure, Container>`; chest, barrel, shulker box, hopper, furnace, ... within reach |
99
+ | `container.items()`, `.count(item)` | InventoryManage | what the open container holds |
100
+ | `container.deposit(item, { count? })`, `.withdraw(item, { count? })` | InventoryManage | `Result<ContainerFailure, { moved }>`: all of the item, or `count` |
101
+ | `container.close()` | InventoryManage | one container is open per bot; it closes on its own when another opens or the plugin stops |
102
+ | `bot.plugins.start(BuiltInPlugin.X)`, `.stop(...)` | ProfilePlugins | starts a plugin instance the profile already has |
103
+ | `bot.connect()`, `bot.disconnect()`, `bot.reconnect({ after? })` | ProfileBots | `Result<BotControlFailure>` |
104
+ | `bot.on(BotEvent.X, listener)` | see below | returns a function that stops listening |
105
+ | `bot.wait(duration)`, `bot.loop(body, { every? })` | none | |
106
+
107
+ Events: `Chat` (needs ChatRead) gives `{ text, sender, senderUuid, system }`; `PlayerJoined` and `PlayerLeft`
108
+ (EntitiesRead) give `{ player: { name, uuid } }`; `Died`, `Respawned`, `HealthChanged` (`{ health, food }`) need
109
+ nothing.
110
+
111
+ ## Context (`run(bot, context)`)
112
+
113
+ - `settings`: typed from the `settings` declaration; missing values are the defaults.
114
+ - `storage.name.get()`, `.set(v)`, `.delete()`, `.update(fn)`; maps add `get(key)`, `set(key, v)`, `keys()`,
115
+ `entries()`. `update` is lossless when several bots write at once. Bot-scoped entries are bound to the bot in
116
+ `run`; in `runProfile` pick one with `storage.name.for(bot)`.
117
+ - `log.info/warn/error/debug(message)`: the plugin console on the dashboard and the terminal under `minebot dev`.
118
+ - `stats.set(name, n)`, `stats.add(name, n?)`: numbers on the plugin's card.
119
+ - `warnings.set(key, message)`, `warnings.clear(key)`: problems shown on the plugin's card until cleared.
120
+
121
+ ## Profile (`runProfile(profile)`)
122
+
123
+ `profile.bots()` lists every bot of the profile (`ProfileBot`: `id`, `name`, `uuid`, `connected`, `enabled`,
124
+ `connect()`, `disconnect()`, `reconnect()`, `plugins`); `profile.bot(nameOrUuid)` finds one;
125
+ `profile.on(ProfileEvent.BotConnected | BotDisconnected, listener)` gives `{ bot }` / `{ bot, reason }`.
126
+ Connecting and disconnecting need `Permission.ProfileBots`.
127
+
128
+ ## Network
129
+
130
+ `fetch` is the standard one, limited to what the plugin declares: `Permission.network("api.example.com")`,
131
+ `Permission.network("*.example.com")` for subdomains, or the exact origin a user typed into a `Setting.url` (with
132
+ `hosts`, only one of those hosts or their subdomains).
133
+ HTTPS only; redirects are followed only to allowed hosts. Hosted: 10 s timeout, 64 KB request and 256 KB
134
+ response bodies, about 60 requests a minute. Keys and webhooks belong in `Setting.secret()` or
135
+ `Setting.url({ secret: true })`: stored encrypted and never shown to the plugin's author.
136
+
137
+ ## Testing
138
+
139
+ ```ts
140
+ import { test } from "node:test";
141
+ import assert from "node:assert/strict";
142
+ import { Block } from "@minecraftbot-com/plugin";
143
+ import { testPlugin } from "@minecraftbot-com/plugin/testing";
144
+ import plugin from "../src/index.js";
145
+
146
+ test("digs ripe wheat", async () => {
147
+ const run = await testPlugin(plugin, {
148
+ bots: [{ id: "bot-1", name: "Farmer", position: { x: 0, y: 64, z: 0 } }],
149
+ blocks: [{ position: { x: 2, y: 64, z: 0 }, block: Block.Wheat, state: { age: 7 } }],
150
+ });
151
+ await run.until(() => run.container.blocks.size === 0);
152
+ await run.stop();
153
+ });
154
+ ```
155
+
156
+ The fake bot (`run.container`) checks permissions like the real one and records `said`, `commands`, `calls`,
157
+ `logs`, `stats`, `warnings`, `storage` and `chests`. It crafts what `recipes: [{ result, ingredients: { [Item.Wheat]: 3 },
158
+ count?, table? }]` lists, and opens what `containers: [{ position, items?, size? }]` places; `chat(bot, text, sender)`, `emit(bot, event, data)`,
159
+ `disconnectBot(bot)`, `stopBot(bot)` drive it. `minebot test` runs `test/*.test.ts`.
160
+
161
+ ## Live, under `minebot dev`
162
+
163
+ `minebot dev` serves MCP at `http://127.0.0.1:7788/mcp` (it prints the address; `--mcp-port`, `--no-mcp`), for
164
+ agents working on the plugin while it runs on the user's bots:
165
+
166
+ - `status`: build and connection state, the profile's bots and which the plugin runs on, granted permissions, settings.
167
+ - `logs`: what the plugin logged, plus build and connection lines; pass `since` (the last call's `next`) for new ones.
168
+ - `reload`: rebuild and restart, then report whether the build passed and the plugin connected.
169
+ - `query`: one read-only call as the plugin (`bot.position`, `world.findBlocks`, `entities.nearby`,
170
+ `inventory.items`, `storage.get`, ...). It needs the plugin's permissions and never moves or changes anything.
171
+
172
+ Saving a file restarts the plugin on its own; `reload` is for waiting on the outcome.
173
+
174
+ ## Deploying
175
+
176
+ `minebot deploy --profile <name>` uploads the plugin (the same bundle `minebot build` writes) and runs it on
177
+ MineBot's servers whenever that profile runs; the dashboard's Plugins → Custom Plugins page starts and stops it per
178
+ profile and shows how it is doing. Deploying again updates it everywhere it runs. Settings for a profile:
179
+ `--settings settings.json`. Debug with `minebot dev`, then deploy.
180
+
181
+ ## Limits when hosted
182
+
183
+ About 1.5 MB of memory after start (bundled libraries are the usual cost; import only what you use), 50 ms of
184
+ CPU at a time, roughly 50 calls per second per bot, 256 queued events (the oldest are dropped first). No Node
185
+ built-ins (`fs`, `child_process`, ...), no `Intl`, `URL`, `URLSearchParams`, `TextEncoder` or `AbortController`
186
+ (build URLs as strings). `fetch`, `Headers` and `Response` are there (text, JSON and bytes); request bodies are
187
+ strings or bytes. Every request shows in the plugin console by host (never the path). `minebot check` reports the
188
+ bundle size and the permissions.
package/README.md CHANGED
@@ -1,46 +1,47 @@
1
- # @minecraftbot-com/plugin
2
-
3
- Write [MineBot](https://minecraftbot.com) plugins in TypeScript: a typed API for your bots, enums for every
4
- block, item, entity and event, and the `minebot` CLI to run them.
5
-
6
- ```sh
7
- npx @minecraftbot-com/plugin create my-plugin
8
- cd my-plugin && npm install
9
- npx minebot login # approve the sign-in on the dashboard
10
- npm run dev # runs on your running profile, restarting on every save
11
- ```
12
-
13
- ```ts
14
- import { definePlugin, BotEvent, Permission } from "@minecraftbot-com/plugin";
15
-
16
- export default definePlugin({
17
- name: "Greeter",
18
- permissions: [Permission.ChatRead, Permission.ChatSend],
19
- async run(bot) {
20
- bot.on(BotEvent.Chat, async message => {
21
- if (message.text === "!hello") await bot.say(`Hello, ${message.sender}!`);
22
- });
23
- },
24
- });
25
- ```
26
-
27
- - **Permissions you can read.** A plugin declares what it does; users approve the list; calls outside it fail
28
- with a message naming the permission to add.
29
- - **Failures are values.** `const moved = await bot.goto(pos); if (!moved.ok) log.warn(moved.reason);`
30
- - **Lifetimes are handled.** Everything a bot's `run` started ends when the bot stops.
31
- - **Test without a server.** `@minecraftbot-com/plugin/testing` runs your plugin against a fake bot.
32
-
33
- [AGENTS.md](./AGENTS.md) documents the whole API (written for AI assistants, readable by people).
34
-
35
- ## Commands
36
-
37
- | | |
38
- |---|---|
39
- | `minebot create <folder>` | new plugin project |
40
- | `minebot login` / `logout` | sign in with your MineBot account |
41
- | `minebot dev [--profile <name>] [--bot <name>] [--settings file.json]` | run the plugin on your profile, restarting on every save; serves MCP for AI agents at `http://127.0.0.1:7788/mcp` (`--mcp-port`, `--no-mcp`) |
42
- | `minebot test` | run `test/*.test.ts` against a fake bot |
43
- | `minebot check` | permissions users will be asked for, bundle size, problems |
44
- | `minebot build` | `dist/plugin.js` and `dist/manifest.json` |
45
-
46
- Node 22 or newer.
1
+ # @minecraftbot-com/plugin
2
+
3
+ Write [MineBot](https://minecraftbot.com) plugins in TypeScript: a typed API for your bots, enums for every
4
+ block, item, entity and event, and the `minebot` CLI to run them.
5
+
6
+ ```sh
7
+ npx @minecraftbot-com/plugin create my-plugin
8
+ cd my-plugin && npm install
9
+ npx minebot login # approve the sign-in on the dashboard
10
+ npm run dev # runs on your running profile, restarting on every save
11
+ ```
12
+
13
+ ```ts
14
+ import { definePlugin, BotEvent, Permission } from "@minecraftbot-com/plugin";
15
+
16
+ export default definePlugin({
17
+ name: "Greeter",
18
+ permissions: [Permission.ChatRead, Permission.ChatSend],
19
+ async run(bot) {
20
+ bot.on(BotEvent.Chat, async message => {
21
+ if (message.text === "!hello") await bot.say(`Hello, ${message.sender}!`);
22
+ });
23
+ },
24
+ });
25
+ ```
26
+
27
+ - **Permissions you can read.** A plugin declares what it does; users approve the list; calls outside it fail
28
+ with a message naming the permission to add.
29
+ - **Failures are values.** `const moved = await bot.goto(pos); if (!moved.ok) log.warn(moved.reason);`
30
+ - **Lifetimes are handled.** Everything a bot's `run` started ends when the bot stops.
31
+ - **Test without a server.** `@minecraftbot-com/plugin/testing` runs your plugin against a fake bot.
32
+
33
+ [AGENTS.md](./AGENTS.md) documents the whole API (written for AI assistants, readable by people).
34
+
35
+ ## Commands
36
+
37
+ | | |
38
+ |---|---|
39
+ | `minebot create <folder>` | new plugin project |
40
+ | `minebot login` / `logout` | sign in with your MineBot account |
41
+ | `minebot dev [--profile <name>] [--bot <name>] [--settings file.json]` | run the plugin on your profile, restarting on every save; serves MCP for AI agents at `http://127.0.0.1:7788/mcp` (`--mcp-port`, `--no-mcp`) |
42
+ | `minebot test` | run `test/*.test.ts` against a fake bot |
43
+ | `minebot check` | permissions users will be asked for, bundle size, problems |
44
+ | `minebot build` | `dist/plugin.js` and `dist/manifest.json` |
45
+ | `minebot deploy [--profile <name>] [--bot <name>] [--settings file.json]` | upload it so it runs on MineBot's servers whenever the profile runs, without your machine; deploy again to update it everywhere |
46
+
47
+ Node 22 or newer.
package/dist/api.d.ts CHANGED
@@ -37,7 +37,10 @@ export interface PlayerInfo {
37
37
  export interface ItemStack {
38
38
  readonly item: Item;
39
39
  readonly count: number;
40
- /** The slot in the inventory (or in the container, for a container's items). */
40
+ /**
41
+ * Where the stack is, numbered as Minecraft's commands do (`/item replace entity <bot> container.N`): the hotbar
42
+ * 0-8, the inventory 9-35, armor 100 (feet) to 103 (head), the offhand 98. A container's items: its own slot from 0.
43
+ */
41
44
  readonly slot: number;
42
45
  /** The custom name, if renamed in an anvil. */
43
46
  readonly name: string | null;
package/dist/cli/api.d.ts CHANGED
@@ -23,4 +23,27 @@ export declare function pollDevice(deviceCode: string): Promise<{
23
23
  token: string | null;
24
24
  }>;
25
25
  export declare function listProfiles(): Promise<ProfileEntry[]>;
26
+ export interface DeployRequest {
27
+ manifest: unknown;
28
+ bundle: string;
29
+ sdk: string;
30
+ profile?: string;
31
+ settings?: Record<string, unknown>;
32
+ bots?: string[];
33
+ }
34
+ export interface DeployResult {
35
+ pluginId: string;
36
+ name: string;
37
+ version: string;
38
+ bundleHash: string;
39
+ newVersion: boolean;
40
+ installations: {
41
+ id: string;
42
+ profileId: string;
43
+ profileName: string;
44
+ enabled: boolean;
45
+ }[];
46
+ dashboard: string;
47
+ }
48
+ export declare function deployBundle(body: DeployRequest): Promise<DeployResult>;
26
49
  export declare function devToken(profileId: string): Promise<DevToken>;
package/dist/cli/api.js CHANGED
@@ -49,6 +49,14 @@ export async function listProfiles() {
49
49
  fail(message(r.data, `Couldn't list your profiles (HTTP ${r.status})`));
50
50
  return r.data;
51
51
  }
52
+ export async function deployBundle(body) {
53
+ const r = await request("POST", "/plugins/cli/deploy", body, true);
54
+ if (r.status === 401)
55
+ fail(message(r.data, "Your sign-in expired."), "Run `minebot login` again.");
56
+ if (r.status !== 200)
57
+ fail(message(r.data, `The deploy failed (HTTP ${r.status})`));
58
+ return r.data;
59
+ }
52
60
  export async function devToken(profileId) {
53
61
  const r = await request("POST", "/plugins/cli/dev-token", { profileId }, true);
54
62
  if (r.status === 401)
@@ -16,6 +16,7 @@ export declare function devBuildOptions(project: Project, outfile: string): esbu
16
16
  /**
17
17
  * The bundle a hosted runner runs: everything included, minified, and the SDK compiled from its TypeScript
18
18
  * source (the `minebot-source` condition) so enum members become plain strings and the enum objects drop out.
19
+ * It is one script (QuickJS evaluates it as a global script) that hands the plugin to `serveHosted`.
19
20
  */
20
21
  export declare function hostedBuildOptions(project: Project, outfile: string): esbuild.BuildOptions;
21
22
  export declare function formatErrors(errors: esbuild.Message[]): string;
package/dist/cli/build.js CHANGED
@@ -34,13 +34,20 @@ export function devBuildOptions(project, outfile) {
34
34
  /**
35
35
  * The bundle a hosted runner runs: everything included, minified, and the SDK compiled from its TypeScript
36
36
  * source (the `minebot-source` condition) so enum members become plain strings and the enum objects drop out.
37
+ * It is one script (QuickJS evaluates it as a global script) that hands the plugin to `serveHosted`.
37
38
  */
38
39
  export function hostedBuildOptions(project, outfile) {
40
+ const entry = JSON.stringify(project.entry.replace(/\\/g, "/"));
39
41
  return {
40
- entryPoints: [project.entry],
42
+ stdin: {
43
+ contents: `import plugin from ${entry};\nimport { serveHosted } from "@minecraftbot-com/plugin/hosted";\nserveHosted(plugin);\n`,
44
+ resolveDir: project.root,
45
+ sourcefile: "minebot-hosted-entry.js",
46
+ loader: "js",
47
+ },
41
48
  outfile,
42
49
  bundle: true,
43
- format: "esm",
50
+ format: "iife",
44
51
  platform: "neutral",
45
52
  target: "es2022",
46
53
  minify: true,
@@ -1,4 +1,11 @@
1
1
  import type { Manifest } from "../protocol.js";
2
+ export interface Built {
3
+ manifest: Manifest;
4
+ bundle: string;
5
+ bytes: number;
6
+ }
7
+ /** Builds the manifest (by running the plugin in Node) and the hosted bundle into outDir. */
8
+ export declare function buildAll(outDir: string): Promise<Built>;
2
9
  /** Problems with a manifest: each is a sentence a person (or an AI) can act on. */
3
10
  export declare function review(manifest: Manifest, bytes: number): {
4
11
  problems: string[];
package/dist/cli/check.js CHANGED
@@ -8,7 +8,8 @@ import { devBuildOptions, findProject, formatErrors, hostedBuildOptions, loadPlu
8
8
  import { bold, dim, fail, green, info, warn, yellow } from "./output.js";
9
9
  /** Above this a hosted plugin probably won't fit its memory after start (about 1.5 MB, mostly bundled code). */
10
10
  const BUNDLE_WARNING_BYTES = 256 * 1024;
11
- async function buildAll(outDir) {
11
+ /** Builds the manifest (by running the plugin in Node) and the hosted bundle into outDir. */
12
+ export async function buildAll(outDir) {
12
13
  const project = findProject();
13
14
  mkdirSync(outDir, { recursive: true });
14
15
  // The manifest comes from running the plugin's module in Node; that build stays out of the output folder.
@@ -0,0 +1,13 @@
1
+ export interface DeployArgs {
2
+ /** Run it on this profile (name or id) from now on. */
3
+ profile?: string;
4
+ /** Only these bots (names or ids) on that profile; default every bot. */
5
+ bots: string[];
6
+ /** Setting values for that profile. */
7
+ settingsFile?: string;
8
+ }
9
+ /**
10
+ * `minebot deploy`: builds the hosted bundle and uploads it as the plugin's new version, so it runs on MineBot's
11
+ * servers instead of your machine. Profiles it runs on move to the new version; `--profile` adds one.
12
+ */
13
+ export declare function deploy(args: DeployArgs): Promise<void>;