@minecraftbot-com/plugin 0.0.0-stage → 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.
Files changed (137) hide show
  1. package/AGENTS.md +188 -0
  2. package/README.md +47 -3
  3. package/dist/api.d.ts +354 -0
  4. package/dist/api.js +2 -0
  5. package/dist/cli/api.d.ts +49 -0
  6. package/dist/cli/api.js +69 -0
  7. package/dist/cli/build.d.ts +24 -0
  8. package/dist/cli/build.js +72 -0
  9. package/dist/cli/check.d.ts +17 -0
  10. package/dist/cli/check.js +99 -0
  11. package/dist/cli/config.d.ts +11 -0
  12. package/dist/cli/config.js +38 -0
  13. package/dist/cli/create.d.ts +2 -0
  14. package/dist/cli/create.js +39 -0
  15. package/dist/cli/deploy.d.ts +13 -0
  16. package/dist/cli/deploy.js +51 -0
  17. package/dist/cli/dev-mcp.d.ts +36 -0
  18. package/dist/cli/dev-mcp.js +101 -0
  19. package/dist/cli/dev.d.ts +15 -0
  20. package/dist/cli/dev.js +261 -0
  21. package/dist/cli/fetch-guard.d.ts +7 -0
  22. package/dist/cli/fetch-guard.js +66 -0
  23. package/dist/cli/main.d.ts +2 -0
  24. package/dist/cli/main.js +119 -0
  25. package/dist/cli/mcp.d.ts +24 -0
  26. package/dist/cli/mcp.js +136 -0
  27. package/dist/cli/output.d.ts +11 -0
  28. package/dist/cli/output.js +25 -0
  29. package/dist/cli/test.d.ts +2 -0
  30. package/dist/cli/test.js +39 -0
  31. package/dist/errors.d.ts +22 -0
  32. package/dist/errors.js +35 -0
  33. package/dist/generated/block-states.d.ts +4087 -0
  34. package/dist/generated/block-states.js +2 -0
  35. package/dist/generated/blocks.d.ts +1289 -0
  36. package/dist/generated/blocks.js +1291 -0
  37. package/dist/generated/contracts.d.ts +304 -0
  38. package/dist/generated/contracts.js +327 -0
  39. package/dist/generated/effects.d.ts +43 -0
  40. package/dist/generated/effects.js +45 -0
  41. package/dist/generated/entities.d.ts +164 -0
  42. package/dist/generated/entities.js +166 -0
  43. package/dist/generated/items.d.ts +1661 -0
  44. package/dist/generated/items.js +1663 -0
  45. package/dist/generated/operations.d.ts +7 -0
  46. package/dist/generated/operations.js +65 -0
  47. package/dist/generated/permission-labels.d.ts +3 -0
  48. package/dist/generated/permission-labels.js +17 -0
  49. package/dist/generated/version.d.ts +2 -0
  50. package/dist/generated/version.js +3 -0
  51. package/dist/host/index.d.ts +7 -0
  52. package/dist/host/index.js +5 -0
  53. package/dist/hosted/fetch.d.ts +53 -0
  54. package/dist/hosted/fetch.js +216 -0
  55. package/dist/hosted/index.d.ts +3 -0
  56. package/dist/hosted/index.js +81 -0
  57. package/dist/index.d.ts +19 -0
  58. package/dist/index.js +13 -0
  59. package/dist/permissions.d.ts +11 -0
  60. package/dist/permissions.js +18 -0
  61. package/dist/plugin.d.ts +86 -0
  62. package/dist/plugin.js +26 -0
  63. package/dist/protocol.d.ts +167 -0
  64. package/dist/protocol.js +4 -0
  65. package/dist/runtime/connection.d.ts +52 -0
  66. package/dist/runtime/connection.js +132 -0
  67. package/dist/runtime/handles.d.ts +95 -0
  68. package/dist/runtime/handles.js +289 -0
  69. package/dist/runtime/memory-transport.d.ts +6 -0
  70. package/dist/runtime/memory-transport.js +39 -0
  71. package/dist/runtime/runtime.d.ts +57 -0
  72. package/dist/runtime/runtime.js +265 -0
  73. package/dist/runtime/scope.d.ts +25 -0
  74. package/dist/runtime/scope.js +94 -0
  75. package/dist/runtime/storage-runtime.d.ts +10 -0
  76. package/dist/runtime/storage-runtime.js +131 -0
  77. package/dist/settings.d.ts +111 -0
  78. package/dist/settings.js +78 -0
  79. package/dist/storage.d.ts +78 -0
  80. package/dist/storage.js +24 -0
  81. package/dist/testing/fake-container.d.ts +175 -0
  82. package/dist/testing/fake-container.js +483 -0
  83. package/dist/testing/index.d.ts +37 -0
  84. package/dist/testing/index.js +54 -0
  85. package/dist/types.d.ts +65 -0
  86. package/dist/types.js +54 -0
  87. package/llms.txt +11 -0
  88. package/package.json +60 -4
  89. package/src/api.ts +337 -0
  90. package/src/cli/api.ts +105 -0
  91. package/src/cli/build.ts +83 -0
  92. package/src/cli/check.ts +104 -0
  93. package/src/cli/config.ts +48 -0
  94. package/src/cli/create.ts +38 -0
  95. package/src/cli/deploy.ts +60 -0
  96. package/src/cli/dev-mcp.ts +131 -0
  97. package/src/cli/dev.ts +272 -0
  98. package/src/cli/fetch-guard.ts +61 -0
  99. package/src/cli/main.ts +120 -0
  100. package/src/cli/mcp.ts +168 -0
  101. package/src/cli/output.ts +30 -0
  102. package/src/cli/test.ts +38 -0
  103. package/src/errors.ts +34 -0
  104. package/src/generated/block-states.ts +892 -0
  105. package/src/generated/blocks.ts +1291 -0
  106. package/src/generated/contracts.ts +329 -0
  107. package/src/generated/effects.ts +45 -0
  108. package/src/generated/entities.ts +166 -0
  109. package/src/generated/items.ts +1663 -0
  110. package/src/generated/operations.ts +69 -0
  111. package/src/generated/permission-labels.ts +19 -0
  112. package/src/generated/version.ts +3 -0
  113. package/src/host/index.ts +9 -0
  114. package/src/hosted/fetch.ts +224 -0
  115. package/src/hosted/index.ts +121 -0
  116. package/src/index.ts +34 -0
  117. package/src/permissions.ts +23 -0
  118. package/src/plugin.ts +105 -0
  119. package/src/protocol.ts +107 -0
  120. package/src/runtime/connection.ts +167 -0
  121. package/src/runtime/handles.ts +337 -0
  122. package/src/runtime/memory-transport.ts +41 -0
  123. package/src/runtime/runtime.ts +281 -0
  124. package/src/runtime/scope.ts +101 -0
  125. package/src/runtime/storage-runtime.ts +138 -0
  126. package/src/settings.ts +118 -0
  127. package/src/storage.ts +82 -0
  128. package/src/testing/fake-container.ts +571 -0
  129. package/src/testing/index.ts +70 -0
  130. package/src/types.ts +88 -0
  131. package/templates/basic/AGENTS.md +32 -0
  132. package/templates/basic/README.md +14 -0
  133. package/templates/basic/gitignore +3 -0
  134. package/templates/basic/package.json +19 -0
  135. package/templates/basic/src/index.ts +20 -0
  136. package/templates/basic/test/plugin.test.ts +14 -0
  137. package/templates/basic/tsconfig.json +14 -0
package/AGENTS.md ADDED
@@ -0,0 +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` (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,3 +1,47 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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 ADDED
@@ -0,0 +1,354 @@
1
+ import type { Block } from "./generated/blocks.js";
2
+ import type { Item } from "./generated/items.js";
3
+ import type { Entity } from "./generated/entities.js";
4
+ import type { BlockStates } from "./generated/block-states.js";
5
+ import type { AttackFailure, BotControlFailure, BotEvent, BuiltInPlugin, ContainerFailure, CraftFailure, DigFailure, EquipmentSlot, GameMode, InteractFailure, InventoryFailure, MoveFailure, PlaceFailure, PluginControlFailure, ProfileEvent } from "./generated/contracts.js";
6
+ import type { Duration, Position, Result, Vec3 } from "./types.js";
7
+ /** The properties a block can have, all optional: what `findBlocks` matches on. */
8
+ export type BlockStateFilter<B> = B extends keyof BlockStates ? Partial<BlockStates[B]> : Record<string, never>;
9
+ /** A block in the world. */
10
+ export interface BlockInfo {
11
+ readonly position: Position;
12
+ readonly block: Block;
13
+ /** The block's properties, e.g. `{ age: 7 }`. */
14
+ readonly state: Readonly<Record<string, string | number | boolean>>;
15
+ }
16
+ /** An entity near the bot: a mob, an animal, another player, an item on the ground. */
17
+ export interface EntityInfo {
18
+ /** The id the server gave it; valid while it stays loaded. Pass it to `bot.attack` or `bot.follow`. */
19
+ readonly id: number;
20
+ readonly type: Entity;
21
+ readonly uuid: string | null;
22
+ /** The player name for players, the custom name for named mobs. */
23
+ readonly name: string | null;
24
+ readonly position: Position;
25
+ /** Distance from the bot in blocks. */
26
+ readonly distance: number;
27
+ }
28
+ /** A player on the server's player list. */
29
+ export interface PlayerInfo {
30
+ readonly name: string;
31
+ readonly uuid: string;
32
+ /** Latency in milliseconds. */
33
+ readonly ping: number;
34
+ readonly gameMode: GameMode | null;
35
+ }
36
+ /** A stack of items in the bot's inventory or in a container. */
37
+ export interface ItemStack {
38
+ readonly item: Item;
39
+ readonly count: number;
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
+ */
44
+ readonly slot: number;
45
+ /** The custom name, if renamed in an anvil. */
46
+ readonly name: string | null;
47
+ }
48
+ /** The bot's health and similar. */
49
+ export interface BotStatus {
50
+ /** 0 to 20; 0 means dead. */
51
+ readonly health: number;
52
+ /** 0 to 20. */
53
+ readonly food: number;
54
+ readonly saturation: number;
55
+ readonly alive: boolean;
56
+ readonly gameMode: GameMode | null;
57
+ /** e.g. `"minecraft:overworld"`. */
58
+ readonly dimension: string | null;
59
+ readonly experienceLevel: number;
60
+ }
61
+ export interface ChatMessage {
62
+ /** The message as plain text, without formatting codes. */
63
+ readonly text: string;
64
+ /** The sending player's name, or null for system messages (server announcements, plugin output). */
65
+ readonly sender: string | null;
66
+ readonly senderUuid: string | null;
67
+ readonly system: boolean;
68
+ }
69
+ /** The data each `BotEvent` hands its listeners. */
70
+ export interface BotEventData {
71
+ [BotEvent.Chat]: ChatMessage;
72
+ [BotEvent.PlayerJoined]: {
73
+ readonly player: {
74
+ readonly name: string;
75
+ readonly uuid: string;
76
+ };
77
+ };
78
+ [BotEvent.PlayerLeft]: {
79
+ readonly player: {
80
+ readonly name: string;
81
+ readonly uuid: string;
82
+ };
83
+ };
84
+ [BotEvent.Died]: Record<string, never>;
85
+ [BotEvent.Respawned]: Record<string, never>;
86
+ [BotEvent.HealthChanged]: {
87
+ readonly health: number;
88
+ readonly food: number;
89
+ };
90
+ }
91
+ /** The data each `ProfileEvent` hands its listeners. */
92
+ export interface ProfileEventData {
93
+ [ProfileEvent.BotConnected]: {
94
+ readonly bot: ProfileBot;
95
+ };
96
+ [ProfileEvent.BotDisconnected]: {
97
+ readonly bot: ProfileBot;
98
+ readonly reason: string;
99
+ };
100
+ }
101
+ /** A listener; return a promise to have errors logged. */
102
+ export type Listener<T> = (data: T) => unknown;
103
+ /** Starts and stops other plugins on one bot. Needs `Permission.ProfilePlugins`. */
104
+ export interface BotPlugins {
105
+ /**
106
+ * Starts a plugin instance on this bot, as a macro would. The profile must already have an instance of it
107
+ * (added on the dashboard).
108
+ *
109
+ * @example await bot.plugins.start(BuiltInPlugin.AutoEater);
110
+ */
111
+ start(plugin: BuiltInPlugin): Promise<Result<PluginControlFailure>>;
112
+ stop(plugin: BuiltInPlugin): Promise<Result<PluginControlFailure>>;
113
+ }
114
+ /**
115
+ * Any bot of the profile, connected or not. Its name and uuid are always available; connecting and
116
+ * disconnecting need `Permission.ProfileBots`.
117
+ */
118
+ export interface ProfileBot {
119
+ /** The bot's id in the profile. */
120
+ readonly id: string;
121
+ /** The Minecraft name. */
122
+ readonly name: string;
123
+ /** The Minecraft account's uuid. */
124
+ readonly uuid: string;
125
+ /** True while it is connected to the server. */
126
+ readonly connected: boolean;
127
+ /** True if this plugin is enabled on it (then `run(bot)` runs while it is connected). */
128
+ readonly enabled: boolean;
129
+ connect(): Promise<Result<BotControlFailure>>;
130
+ disconnect(): Promise<Result<BotControlFailure>>;
131
+ /** Disconnects and connects again, optionally after a pause: `bot.reconnect({ after: { seconds: 30 } })`. */
132
+ reconnect(options?: {
133
+ after?: Duration;
134
+ }): Promise<Result<BotControlFailure>>;
135
+ readonly plugins: BotPlugins;
136
+ }
137
+ /** The world as the bot sees it. Needs `Permission.WorldRead`. */
138
+ export interface World {
139
+ /** The block at a position, or null if that part of the world isn't loaded. */
140
+ block(position: Vec3): Promise<BlockInfo | null>;
141
+ /**
142
+ * Blocks near the bot (or near `from`), closest first.
143
+ *
144
+ * @example
145
+ * const ripe = await bot.world.findBlocks({ block: Block.Wheat, state: { age: 7 }, radius: 16, limit: 8 });
146
+ * const logs = await bot.world.findBlocks({ block: [Block.OakLog, Block.BirchLog], radius: 32 });
147
+ */
148
+ findBlocks<B extends Block>(query: {
149
+ block: B | readonly B[];
150
+ state?: BlockStateFilter<B>;
151
+ /** In blocks, at most 64. Default 16. */
152
+ radius?: number;
153
+ /** At most 256. Default 16. */
154
+ limit?: number;
155
+ from?: Vec3;
156
+ }): Promise<BlockInfo[]>;
157
+ }
158
+ /** Entities and players. Needs `Permission.EntitiesRead`. */
159
+ export interface Entities {
160
+ /**
161
+ * Entities near the bot, closest first.
162
+ *
163
+ * @example const zombies = await bot.entities.nearby({ type: Entity.Zombie, radius: 8 });
164
+ */
165
+ nearby(query?: {
166
+ type?: Entity | readonly Entity[];
167
+ radius?: number;
168
+ limit?: number;
169
+ }): Promise<EntityInfo[]>;
170
+ /** Everyone on the server's player list. */
171
+ players(): Promise<PlayerInfo[]>;
172
+ }
173
+ /** The bot's inventory. Reading needs `Permission.InventoryRead`, changing `Permission.InventoryManage`. */
174
+ export interface Inventory {
175
+ items(): Promise<ItemStack[]>;
176
+ /** The item in the main hand, or null. */
177
+ held(): Promise<ItemStack | null>;
178
+ /** How many of an item the bot has in total. */
179
+ count(item: Item): Promise<number>;
180
+ /** Holds (or wears) an item: `await bot.inventory.equip(Item.DiamondSword)`. */
181
+ equip(item: Item, slot?: EquipmentSlot): Promise<Result<InventoryFailure>>;
182
+ /** Drops items on the ground: all of that item, or `count` of them. */
183
+ drop(item: Item, options?: {
184
+ count?: number;
185
+ }): Promise<Result<InventoryFailure>>;
186
+ }
187
+ /** A crafting recipe, as `bot.recipes` lists it. */
188
+ export interface Recipe {
189
+ readonly result: Item;
190
+ /** How many one craft makes (4 sticks from 2 planks). */
191
+ readonly count: number;
192
+ /** True if it needs a crafting table's 3x3 grid; false if the inventory's 2x2 grid will do. */
193
+ readonly table: boolean;
194
+ /** What one craft takes: per ingredient, the items that will do and how many. */
195
+ readonly ingredients: readonly {
196
+ readonly items: readonly Item[];
197
+ readonly count: number;
198
+ }[];
199
+ }
200
+ /**
201
+ * A chest, barrel, shulker box, hopper, furnace, ... the bot has open (from `bot.containers.open`). One container
202
+ * is open per bot at a time; it stays open until `close()`, another one opens, or the plugin stops on the bot.
203
+ */
204
+ export interface Container {
205
+ readonly position: Position;
206
+ readonly block: Block;
207
+ /** How many slots it has. */
208
+ readonly size: number;
209
+ /** What it holds now (`slot` is the container's slot). */
210
+ items(): Promise<ItemStack[]>;
211
+ /** How many of an item it holds. */
212
+ count(item: Item): Promise<number>;
213
+ /**
214
+ * Moves items from the inventory into the container: all of that item, or `count`. `value.moved` says how many went
215
+ * in; fewer than asked means it ran out of room or items.
216
+ *
217
+ * @example
218
+ * const stored = await chest.deposit(Item.Wheat);
219
+ * if (!stored.ok) log.warn(`Couldn't store wheat: ${stored.reason}`);
220
+ */
221
+ deposit(item: Item, options?: {
222
+ count?: number;
223
+ }): Promise<Result<ContainerFailure, {
224
+ moved: number;
225
+ }>>;
226
+ /** Moves items from the container into the inventory: all of that item, or `count`. */
227
+ withdraw(item: Item, options?: {
228
+ count?: number;
229
+ }): Promise<Result<ContainerFailure, {
230
+ moved: number;
231
+ }>>;
232
+ close(): Promise<void>;
233
+ }
234
+ /** Containers the bot can open. Needs `Permission.InventoryManage`. */
235
+ export interface Containers {
236
+ /**
237
+ * Opens the container at a position within reach (walk there first).
238
+ *
239
+ * @example
240
+ * await bot.goto(chestPosition, { within: 3 });
241
+ * const opened = await bot.containers.open(chestPosition);
242
+ * if (opened.ok) {
243
+ * await opened.value.deposit(Item.Wheat);
244
+ * await opened.value.close();
245
+ * }
246
+ */
247
+ open(position: Vec3): Promise<Result<ContainerFailure, Container>>;
248
+ }
249
+ /** One bot the plugin runs on, handed to `run(bot)`. */
250
+ export interface Bot extends ProfileBot {
251
+ readonly world: World;
252
+ readonly entities: Entities;
253
+ readonly inventory: Inventory;
254
+ readonly containers: Containers;
255
+ /** The server's Minecraft version, e.g. `"1.21.4"`. */
256
+ readonly version: string;
257
+ /**
258
+ * Listens to an event of this bot until the bot stops. Returns a function that stops listening.
259
+ *
260
+ * @example
261
+ * bot.on(BotEvent.Chat, async message => {
262
+ * if (message.text === "!ping") await bot.say("pong");
263
+ * });
264
+ */
265
+ on<E extends BotEvent>(event: E, listener: Listener<BotEventData[E]>): () => void;
266
+ status(): Promise<BotStatus>;
267
+ /** Where the bot stands. Needs `Permission.WorldRead`. */
268
+ position(): Promise<Position>;
269
+ /** True if the server's version has this block or item (older servers lack newer ones). */
270
+ supports(id: Block | Item | Entity): Promise<boolean>;
271
+ /**
272
+ * Walks to a position with the bot's pathfinder. Needs `Permission.Move`.
273
+ *
274
+ * @example
275
+ * const moved = await bot.goto(chest, { within: 2 });
276
+ * if (!moved.ok) log.warn(`Can't reach the chest: ${moved.reason}`);
277
+ */
278
+ goto(target: Vec3, options?: {
279
+ within?: number;
280
+ timeout?: Duration;
281
+ }): Promise<Result<MoveFailure>>;
282
+ /** Follows an entity until it is lost, `timeout` passes or the plugin stops. Needs `Permission.Move`. */
283
+ follow(entity: EntityInfo | number, options?: {
284
+ distance?: number;
285
+ timeout?: Duration;
286
+ }): Promise<Result<MoveFailure>>;
287
+ stopMoving(): Promise<void>;
288
+ /** Turns to look at a position. Needs `Permission.Move`. */
289
+ lookAt(target: Vec3): Promise<void>;
290
+ jump(): Promise<void>;
291
+ /** Breaks the block at a position (it must be within reach). Needs `Permission.Interact`. */
292
+ dig(position: Vec3): Promise<Result<DigFailure>>;
293
+ /** Places a block from the inventory at a position. Needs `Permission.Interact`. */
294
+ place(position: Vec3, item: Item): Promise<Result<PlaceFailure>>;
295
+ /** Right-clicks a block: opens doors, presses buttons, flips levers. Needs `Permission.Interact`. */
296
+ activateBlock(position: Vec3): Promise<Result<InteractFailure>>;
297
+ /** Uses the held item (eats food, throws a pearl). Needs `Permission.Interact`. */
298
+ useItem(): Promise<Result<InteractFailure>>;
299
+ /** Hits an entity within reach. Needs `Permission.Attack`. */
300
+ attack(entity: EntityInfo | number): Promise<Result<AttackFailure>>;
301
+ /**
302
+ * Crafts at least `count` of an item (default 1, rounded up to whole crafts) from the inventory. Small recipes use
303
+ * the inventory's 2x2 grid; bigger ones a crafting table within reach (`table`, or the nearest one). `value.crafted`
304
+ * says how many it made. Needs `Permission.InventoryManage`.
305
+ *
306
+ * @example
307
+ * const made = await bot.craft(Item.Bread, { count: 3 });
308
+ * if (!made.ok) log.warn(`No bread: ${made.message}`);
309
+ */
310
+ craft(item: Item, options?: {
311
+ count?: number;
312
+ table?: Vec3;
313
+ }): Promise<Result<CraftFailure, {
314
+ crafted: number;
315
+ }>>;
316
+ /** The crafting recipes that make an item on this server, with what each takes. */
317
+ recipes(item: Item): Promise<Recipe[]>;
318
+ /** Sends a chat message. Needs `Permission.ChatSend`; commands go through `command`. */
319
+ say(message: string): Promise<void>;
320
+ /** Runs a server command, with or without the slash: `bot.command("home")`. Needs `Permission.Commands`. */
321
+ command(command: string): Promise<void>;
322
+ /** Waits. Ends early (with the rest of `run`) when the bot stops. */
323
+ wait(duration: Duration): Promise<void>;
324
+ /**
325
+ * Runs `body` again and again until the bot stops: at most every `every` (default one tick), backing off
326
+ * when it throws (the error is logged), so a mistake can't spin the CPU.
327
+ *
328
+ * @example
329
+ * await bot.loop(async () => {
330
+ * const food = await bot.inventory.count(Item.Bread);
331
+ * if (food < 5) log.warn("Low on bread");
332
+ * }, { every: { seconds: 10 } });
333
+ */
334
+ loop(body: () => unknown, options?: {
335
+ every?: Duration;
336
+ }): Promise<never>;
337
+ }
338
+ /** The profile, handed to `runProfile(profile)`. */
339
+ export interface Profile {
340
+ readonly id: string;
341
+ readonly name: string;
342
+ /** Every bot of the profile, enabled or not. */
343
+ bots(): readonly ProfileBot[];
344
+ /** A bot by id, name or uuid. */
345
+ bot(idNameOrUuid: string): ProfileBot | undefined;
346
+ /** Listens to a profile event until the plugin stops. */
347
+ on<E extends ProfileEvent>(event: E, listener: Listener<ProfileEventData[E]>): () => void;
348
+ /** Waits. */
349
+ wait(duration: Duration): Promise<void>;
350
+ /** As `bot.loop`, for the profile. */
351
+ loop(body: () => unknown, options?: {
352
+ every?: Duration;
353
+ }): Promise<never>;
354
+ }
package/dist/api.js ADDED
@@ -0,0 +1,2 @@
1
+ // The bot and profile API plugin code sees. Implemented in runtime/handles.ts on top of protocol calls.
2
+ export {};
@@ -0,0 +1,49 @@
1
+ export interface DeviceStart {
2
+ deviceCode: string;
3
+ userCode: string;
4
+ verificationUrl: string;
5
+ interval: number;
6
+ expiresIn: number;
7
+ }
8
+ export interface ProfileEntry {
9
+ id: string;
10
+ name: string;
11
+ running: boolean;
12
+ }
13
+ export interface DevToken {
14
+ token: string;
15
+ address: string;
16
+ profileId: string;
17
+ profileName: string;
18
+ expiresAt: string;
19
+ }
20
+ export declare function startDevice(): Promise<DeviceStart>;
21
+ export declare function pollDevice(deviceCode: string): Promise<{
22
+ status: string;
23
+ token: string | null;
24
+ }>;
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>;
49
+ export declare function devToken(profileId: string): Promise<DevToken>;