@minecraftbot-com/plugin 0.0.0-stage → 0.1.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 (128) hide show
  1. package/AGENTS.md +177 -0
  2. package/README.md +45 -2
  3. package/dist/api.d.ts +351 -0
  4. package/dist/api.js +2 -0
  5. package/dist/cli/api.d.ts +26 -0
  6. package/dist/cli/api.js +61 -0
  7. package/dist/cli/build.d.ts +23 -0
  8. package/dist/cli/build.js +65 -0
  9. package/dist/cli/check.d.ts +10 -0
  10. package/dist/cli/check.js +98 -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/dev-mcp.d.ts +36 -0
  16. package/dist/cli/dev-mcp.js +101 -0
  17. package/dist/cli/dev.d.ts +15 -0
  18. package/dist/cli/dev.js +261 -0
  19. package/dist/cli/fetch-guard.d.ts +7 -0
  20. package/dist/cli/fetch-guard.js +66 -0
  21. package/dist/cli/main.d.ts +2 -0
  22. package/dist/cli/main.js +112 -0
  23. package/dist/cli/mcp.d.ts +24 -0
  24. package/dist/cli/mcp.js +136 -0
  25. package/dist/cli/output.d.ts +11 -0
  26. package/dist/cli/output.js +25 -0
  27. package/dist/cli/test.d.ts +2 -0
  28. package/dist/cli/test.js +39 -0
  29. package/dist/errors.d.ts +22 -0
  30. package/dist/errors.js +35 -0
  31. package/dist/generated/block-states.d.ts +4087 -0
  32. package/dist/generated/block-states.js +2 -0
  33. package/dist/generated/blocks.d.ts +1289 -0
  34. package/dist/generated/blocks.js +1291 -0
  35. package/dist/generated/contracts.d.ts +304 -0
  36. package/dist/generated/contracts.js +327 -0
  37. package/dist/generated/effects.d.ts +43 -0
  38. package/dist/generated/effects.js +45 -0
  39. package/dist/generated/entities.d.ts +164 -0
  40. package/dist/generated/entities.js +166 -0
  41. package/dist/generated/items.d.ts +1661 -0
  42. package/dist/generated/items.js +1663 -0
  43. package/dist/generated/operations.d.ts +7 -0
  44. package/dist/generated/operations.js +65 -0
  45. package/dist/generated/permission-labels.d.ts +3 -0
  46. package/dist/generated/permission-labels.js +17 -0
  47. package/dist/generated/version.d.ts +2 -0
  48. package/dist/generated/version.js +3 -0
  49. package/dist/host/index.d.ts +7 -0
  50. package/dist/host/index.js +5 -0
  51. package/dist/index.d.ts +19 -0
  52. package/dist/index.js +13 -0
  53. package/dist/permissions.d.ts +11 -0
  54. package/dist/permissions.js +18 -0
  55. package/dist/plugin.d.ts +86 -0
  56. package/dist/plugin.js +26 -0
  57. package/dist/protocol.d.ts +167 -0
  58. package/dist/protocol.js +4 -0
  59. package/dist/runtime/connection.d.ts +52 -0
  60. package/dist/runtime/connection.js +132 -0
  61. package/dist/runtime/handles.d.ts +95 -0
  62. package/dist/runtime/handles.js +289 -0
  63. package/dist/runtime/memory-transport.d.ts +6 -0
  64. package/dist/runtime/memory-transport.js +39 -0
  65. package/dist/runtime/runtime.d.ts +57 -0
  66. package/dist/runtime/runtime.js +265 -0
  67. package/dist/runtime/scope.d.ts +25 -0
  68. package/dist/runtime/scope.js +94 -0
  69. package/dist/runtime/storage-runtime.d.ts +10 -0
  70. package/dist/runtime/storage-runtime.js +131 -0
  71. package/dist/settings.d.ts +111 -0
  72. package/dist/settings.js +78 -0
  73. package/dist/storage.d.ts +78 -0
  74. package/dist/storage.js +24 -0
  75. package/dist/testing/fake-container.d.ts +175 -0
  76. package/dist/testing/fake-container.js +483 -0
  77. package/dist/testing/index.d.ts +37 -0
  78. package/dist/testing/index.js +54 -0
  79. package/dist/types.d.ts +65 -0
  80. package/dist/types.js +54 -0
  81. package/llms.txt +11 -0
  82. package/package.json +55 -4
  83. package/src/api.ts +334 -0
  84. package/src/cli/api.ts +79 -0
  85. package/src/cli/build.ts +76 -0
  86. package/src/cli/check.ts +103 -0
  87. package/src/cli/config.ts +48 -0
  88. package/src/cli/create.ts +38 -0
  89. package/src/cli/dev-mcp.ts +131 -0
  90. package/src/cli/dev.ts +272 -0
  91. package/src/cli/fetch-guard.ts +61 -0
  92. package/src/cli/main.ts +113 -0
  93. package/src/cli/mcp.ts +168 -0
  94. package/src/cli/output.ts +30 -0
  95. package/src/cli/test.ts +38 -0
  96. package/src/errors.ts +34 -0
  97. package/src/generated/block-states.ts +892 -0
  98. package/src/generated/blocks.ts +1291 -0
  99. package/src/generated/contracts.ts +329 -0
  100. package/src/generated/effects.ts +45 -0
  101. package/src/generated/entities.ts +166 -0
  102. package/src/generated/items.ts +1663 -0
  103. package/src/generated/operations.ts +69 -0
  104. package/src/generated/permission-labels.ts +19 -0
  105. package/src/generated/version.ts +3 -0
  106. package/src/host/index.ts +9 -0
  107. package/src/index.ts +34 -0
  108. package/src/permissions.ts +23 -0
  109. package/src/plugin.ts +105 -0
  110. package/src/protocol.ts +107 -0
  111. package/src/runtime/connection.ts +167 -0
  112. package/src/runtime/handles.ts +337 -0
  113. package/src/runtime/memory-transport.ts +41 -0
  114. package/src/runtime/runtime.ts +281 -0
  115. package/src/runtime/scope.ts +101 -0
  116. package/src/runtime/storage-runtime.ts +138 -0
  117. package/src/settings.ts +118 -0
  118. package/src/storage.ts +82 -0
  119. package/src/testing/fake-container.ts +571 -0
  120. package/src/testing/index.ts +70 -0
  121. package/src/types.ts +88 -0
  122. package/templates/basic/AGENTS.md +31 -0
  123. package/templates/basic/README.md +13 -0
  124. package/templates/basic/gitignore +3 -0
  125. package/templates/basic/package.json +18 -0
  126. package/templates/basic/src/index.ts +20 -0
  127. package/templates/basic/test/plugin.test.ts +14 -0
  128. package/templates/basic/tsconfig.json +14 -0
package/dist/types.js ADDED
@@ -0,0 +1,54 @@
1
+ /** A Duration in milliseconds (one tick is 50 ms). */
2
+ export function toMilliseconds(d) {
3
+ const ms = (d.ticks ?? 0) * 50 + (d.milliseconds ?? 0) + (d.seconds ?? 0) * 1000 + (d.minutes ?? 0) * 60_000;
4
+ if (!Number.isFinite(ms) || ms < 0)
5
+ throw new TypeError(`Invalid duration ${JSON.stringify(d)}: use e.g. { seconds: 5 }`);
6
+ return ms;
7
+ }
8
+ /**
9
+ * A position the SDK hands you. It prints as `x y z` in template strings and has a few helpers.
10
+ *
11
+ * @example
12
+ * log.info(`Going to ${chest}`); // "Going to 10 64 -3"
13
+ * const above = chest.offset(0, 1, 0);
14
+ */
15
+ export class Position {
16
+ x;
17
+ y;
18
+ z;
19
+ constructor(x, y, z) {
20
+ this.x = x;
21
+ this.y = y;
22
+ this.z = z;
23
+ }
24
+ /** A new position moved by the given amounts. */
25
+ offset(dx, dy, dz) {
26
+ return new Position(this.x + dx, this.y + dy, this.z + dz);
27
+ }
28
+ /** Straight-line distance in blocks. */
29
+ distanceTo(other) {
30
+ return Math.hypot(this.x - other.x, this.y - other.y, this.z - other.z);
31
+ }
32
+ /** The block this position is in (rounded down). */
33
+ floored() {
34
+ return new Position(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
35
+ }
36
+ equals(other) {
37
+ return this.x === other.x && this.y === other.y && this.z === other.z;
38
+ }
39
+ toString() {
40
+ return `${this.x} ${this.y} ${this.z}`;
41
+ }
42
+ toJSON() {
43
+ return { x: this.x, y: this.y, z: this.z };
44
+ }
45
+ }
46
+ /** Makes a position: `vec3(10, 64, -3)`. */
47
+ export function vec3(x, y, z) {
48
+ return new Position(x, y, z);
49
+ }
50
+ /** @internal Turns a position from a frame into a Position. */
51
+ export function toPosition(v) {
52
+ const p = v;
53
+ return new Position(p.x, p.y, p.z);
54
+ }
package/llms.txt ADDED
@@ -0,0 +1,11 @@
1
+ # @minecraftbot-com/plugin
2
+
3
+ > TypeScript SDK and CLI for MineBot plugins: programs that control Minecraft bots through an intent-level API
4
+ > (walk, dig, place, chat, inventory) with declared permissions.
5
+
6
+ - [AGENTS.md](./AGENTS.md): the whole API, rules, testing and limits. Read this first.
7
+ - [README.md](./README.md): install and commands.
8
+ - Types: `dist/index.d.ts` (plugin API), `dist/testing/index.d.ts` (fake bot for tests).
9
+ - Enums: `src/generated/blocks.ts`, `items.ts`, `entities.ts`, `effects.ts`, `block-states.ts` (every block's properties), `contracts.ts` (permissions, events, failure reasons, built-in plugins).
10
+ - Template: `templates/basic/` (what `minebot create` writes).
11
+ - Live: `minebot dev` serves MCP at `http://127.0.0.1:7788/mcp` (tools `status`, `logs`, `reload`, `query`).
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@minecraftbot-com/plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Write MineBot plugins in TypeScript: typed bot API, enums for every block, item and event, and the minebot CLI.",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "engines": {
11
+ "node": ">=22"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "minebot-source": "./src/index.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./testing": {
20
+ "types": "./dist/testing/index.d.ts",
21
+ "minebot-source": "./src/testing/index.ts",
22
+ "default": "./dist/testing/index.js"
23
+ },
24
+ "./host": {
25
+ "types": "./dist/host/index.d.ts",
26
+ "minebot-source": "./src/host/index.ts",
27
+ "default": "./dist/host/index.js"
28
+ }
29
+ },
30
+ "bin": {
31
+ "minebot": "dist/cli/main.js"
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "src",
36
+ "!src/**/*.test.ts",
37
+ "!dist/**/*.test.*",
38
+ "templates",
39
+ "AGENTS.md",
40
+ "llms.txt",
41
+ "README.md"
42
+ ],
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.build.json",
45
+ "check": "tsc -p tsconfig.json --noEmit",
46
+ "test": "tsc -p tsconfig.build.json && node --test \"dist/**/*.test.js\"",
47
+ "pack:check": "npm run build && node scripts/pack-check.mjs",
48
+ "prepublishOnly": "npm run pack:check"
49
+ },
50
+ "dependencies": {
51
+ "esbuild": "^0.28.2"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^22.20.5",
55
+ "typescript": "^7.0.2"
56
+ }
57
+ }
package/src/api.ts ADDED
@@ -0,0 +1,334 @@
1
+ // The bot and profile API plugin code sees. Implemented in runtime/handles.ts on top of protocol calls.
2
+
3
+ import type { Block } from "./generated/blocks.js";
4
+ import type { Item } from "./generated/items.js";
5
+ import type { Entity } from "./generated/entities.js";
6
+ import type { BlockStates } from "./generated/block-states.js";
7
+ import type {
8
+ AttackFailure, BotControlFailure, BotEvent, BuiltInPlugin, ContainerFailure, CraftFailure, DigFailure, EquipmentSlot,
9
+ GameMode, InteractFailure, InventoryFailure, MoveFailure, PlaceFailure, PluginControlFailure, ProfileEvent,
10
+ } from "./generated/contracts.js";
11
+ import type { Duration, Position, Result, Vec3 } from "./types.js";
12
+
13
+ /** The properties a block can have, all optional: what `findBlocks` matches on. */
14
+ export type BlockStateFilter<B> = B extends keyof BlockStates ? Partial<BlockStates[B]> : Record<string, never>;
15
+
16
+ /** A block in the world. */
17
+ export interface BlockInfo {
18
+ readonly position: Position;
19
+ readonly block: Block;
20
+ /** The block's properties, e.g. `{ age: 7 }`. */
21
+ readonly state: Readonly<Record<string, string | number | boolean>>;
22
+ }
23
+
24
+ /** An entity near the bot: a mob, an animal, another player, an item on the ground. */
25
+ export interface EntityInfo {
26
+ /** The id the server gave it; valid while it stays loaded. Pass it to `bot.attack` or `bot.follow`. */
27
+ readonly id: number;
28
+ readonly type: Entity;
29
+ readonly uuid: string | null;
30
+ /** The player name for players, the custom name for named mobs. */
31
+ readonly name: string | null;
32
+ readonly position: Position;
33
+ /** Distance from the bot in blocks. */
34
+ readonly distance: number;
35
+ }
36
+
37
+ /** A player on the server's player list. */
38
+ export interface PlayerInfo {
39
+ readonly name: string;
40
+ readonly uuid: string;
41
+ /** Latency in milliseconds. */
42
+ readonly ping: number;
43
+ readonly gameMode: GameMode | null;
44
+ }
45
+
46
+ /** A stack of items in the bot's inventory or in a container. */
47
+ export interface ItemStack {
48
+ readonly item: Item;
49
+ readonly count: number;
50
+ /** The slot in the inventory (or in the container, for a container's items). */
51
+ readonly slot: number;
52
+ /** The custom name, if renamed in an anvil. */
53
+ readonly name: string | null;
54
+ }
55
+
56
+ /** The bot's health and similar. */
57
+ export interface BotStatus {
58
+ /** 0 to 20; 0 means dead. */
59
+ readonly health: number;
60
+ /** 0 to 20. */
61
+ readonly food: number;
62
+ readonly saturation: number;
63
+ readonly alive: boolean;
64
+ readonly gameMode: GameMode | null;
65
+ /** e.g. `"minecraft:overworld"`. */
66
+ readonly dimension: string | null;
67
+ readonly experienceLevel: number;
68
+ }
69
+
70
+ export interface ChatMessage {
71
+ /** The message as plain text, without formatting codes. */
72
+ readonly text: string;
73
+ /** The sending player's name, or null for system messages (server announcements, plugin output). */
74
+ readonly sender: string | null;
75
+ readonly senderUuid: string | null;
76
+ readonly system: boolean;
77
+ }
78
+
79
+ /** The data each `BotEvent` hands its listeners. */
80
+ export interface BotEventData {
81
+ [BotEvent.Chat]: ChatMessage;
82
+ [BotEvent.PlayerJoined]: { readonly player: { readonly name: string; readonly uuid: string } };
83
+ [BotEvent.PlayerLeft]: { readonly player: { readonly name: string; readonly uuid: string } };
84
+ [BotEvent.Died]: Record<string, never>;
85
+ [BotEvent.Respawned]: Record<string, never>;
86
+ [BotEvent.HealthChanged]: { readonly health: number; readonly food: number };
87
+ }
88
+
89
+ /** The data each `ProfileEvent` hands its listeners. */
90
+ export interface ProfileEventData {
91
+ [ProfileEvent.BotConnected]: { readonly bot: ProfileBot };
92
+ [ProfileEvent.BotDisconnected]: { readonly bot: ProfileBot; readonly reason: string };
93
+ }
94
+
95
+ /** A listener; return a promise to have errors logged. */
96
+ export type Listener<T> = (data: T) => unknown;
97
+
98
+ /** Starts and stops other plugins on one bot. Needs `Permission.ProfilePlugins`. */
99
+ export interface BotPlugins {
100
+ /**
101
+ * Starts a plugin instance on this bot, as a macro would. The profile must already have an instance of it
102
+ * (added on the dashboard).
103
+ *
104
+ * @example await bot.plugins.start(BuiltInPlugin.AutoEater);
105
+ */
106
+ start(plugin: BuiltInPlugin): Promise<Result<PluginControlFailure>>;
107
+ stop(plugin: BuiltInPlugin): Promise<Result<PluginControlFailure>>;
108
+ }
109
+
110
+ /**
111
+ * Any bot of the profile, connected or not. Its name and uuid are always available; connecting and
112
+ * disconnecting need `Permission.ProfileBots`.
113
+ */
114
+ export interface ProfileBot {
115
+ /** The bot's id in the profile. */
116
+ readonly id: string;
117
+ /** The Minecraft name. */
118
+ readonly name: string;
119
+ /** The Minecraft account's uuid. */
120
+ readonly uuid: string;
121
+ /** True while it is connected to the server. */
122
+ readonly connected: boolean;
123
+ /** True if this plugin is enabled on it (then `run(bot)` runs while it is connected). */
124
+ readonly enabled: boolean;
125
+
126
+ connect(): Promise<Result<BotControlFailure>>;
127
+ disconnect(): Promise<Result<BotControlFailure>>;
128
+ /** Disconnects and connects again, optionally after a pause: `bot.reconnect({ after: { seconds: 30 } })`. */
129
+ reconnect(options?: { after?: Duration }): Promise<Result<BotControlFailure>>;
130
+
131
+ readonly plugins: BotPlugins;
132
+ }
133
+
134
+ /** The world as the bot sees it. Needs `Permission.WorldRead`. */
135
+ export interface World {
136
+ /** The block at a position, or null if that part of the world isn't loaded. */
137
+ block(position: Vec3): Promise<BlockInfo | null>;
138
+
139
+ /**
140
+ * Blocks near the bot (or near `from`), closest first.
141
+ *
142
+ * @example
143
+ * const ripe = await bot.world.findBlocks({ block: Block.Wheat, state: { age: 7 }, radius: 16, limit: 8 });
144
+ * const logs = await bot.world.findBlocks({ block: [Block.OakLog, Block.BirchLog], radius: 32 });
145
+ */
146
+ findBlocks<B extends Block>(query: {
147
+ block: B | readonly B[];
148
+ state?: BlockStateFilter<B>;
149
+ /** In blocks, at most 64. Default 16. */
150
+ radius?: number;
151
+ /** At most 256. Default 16. */
152
+ limit?: number;
153
+ from?: Vec3;
154
+ }): Promise<BlockInfo[]>;
155
+ }
156
+
157
+ /** Entities and players. Needs `Permission.EntitiesRead`. */
158
+ export interface Entities {
159
+ /**
160
+ * Entities near the bot, closest first.
161
+ *
162
+ * @example const zombies = await bot.entities.nearby({ type: Entity.Zombie, radius: 8 });
163
+ */
164
+ nearby(query?: { type?: Entity | readonly Entity[]; radius?: number; limit?: number }): Promise<EntityInfo[]>;
165
+ /** Everyone on the server's player list. */
166
+ players(): Promise<PlayerInfo[]>;
167
+ }
168
+
169
+ /** The bot's inventory. Reading needs `Permission.InventoryRead`, changing `Permission.InventoryManage`. */
170
+ export interface Inventory {
171
+ items(): Promise<ItemStack[]>;
172
+ /** The item in the main hand, or null. */
173
+ held(): Promise<ItemStack | null>;
174
+ /** How many of an item the bot has in total. */
175
+ count(item: Item): Promise<number>;
176
+ /** Holds (or wears) an item: `await bot.inventory.equip(Item.DiamondSword)`. */
177
+ equip(item: Item, slot?: EquipmentSlot): Promise<Result<InventoryFailure>>;
178
+ /** Drops items on the ground: all of that item, or `count` of them. */
179
+ drop(item: Item, options?: { count?: number }): Promise<Result<InventoryFailure>>;
180
+ }
181
+
182
+ /** A crafting recipe, as `bot.recipes` lists it. */
183
+ export interface Recipe {
184
+ readonly result: Item;
185
+ /** How many one craft makes (4 sticks from 2 planks). */
186
+ readonly count: number;
187
+ /** True if it needs a crafting table's 3x3 grid; false if the inventory's 2x2 grid will do. */
188
+ readonly table: boolean;
189
+ /** What one craft takes: per ingredient, the items that will do and how many. */
190
+ readonly ingredients: readonly { readonly items: readonly Item[]; readonly count: number }[];
191
+ }
192
+
193
+ /**
194
+ * A chest, barrel, shulker box, hopper, furnace, ... the bot has open (from `bot.containers.open`). One container
195
+ * is open per bot at a time; it stays open until `close()`, another one opens, or the plugin stops on the bot.
196
+ */
197
+ export interface Container {
198
+ readonly position: Position;
199
+ readonly block: Block;
200
+ /** How many slots it has. */
201
+ readonly size: number;
202
+ /** What it holds now (`slot` is the container's slot). */
203
+ items(): Promise<ItemStack[]>;
204
+ /** How many of an item it holds. */
205
+ count(item: Item): Promise<number>;
206
+ /**
207
+ * Moves items from the inventory into the container: all of that item, or `count`. `value.moved` says how many went
208
+ * in; fewer than asked means it ran out of room or items.
209
+ *
210
+ * @example
211
+ * const stored = await chest.deposit(Item.Wheat);
212
+ * if (!stored.ok) log.warn(`Couldn't store wheat: ${stored.reason}`);
213
+ */
214
+ deposit(item: Item, options?: { count?: number }): Promise<Result<ContainerFailure, { moved: number }>>;
215
+ /** Moves items from the container into the inventory: all of that item, or `count`. */
216
+ withdraw(item: Item, options?: { count?: number }): Promise<Result<ContainerFailure, { moved: number }>>;
217
+ close(): Promise<void>;
218
+ }
219
+
220
+ /** Containers the bot can open. Needs `Permission.InventoryManage`. */
221
+ export interface Containers {
222
+ /**
223
+ * Opens the container at a position within reach (walk there first).
224
+ *
225
+ * @example
226
+ * await bot.goto(chestPosition, { within: 3 });
227
+ * const opened = await bot.containers.open(chestPosition);
228
+ * if (opened.ok) {
229
+ * await opened.value.deposit(Item.Wheat);
230
+ * await opened.value.close();
231
+ * }
232
+ */
233
+ open(position: Vec3): Promise<Result<ContainerFailure, Container>>;
234
+ }
235
+
236
+ /** One bot the plugin runs on, handed to `run(bot)`. */
237
+ export interface Bot extends ProfileBot {
238
+ readonly world: World;
239
+ readonly entities: Entities;
240
+ readonly inventory: Inventory;
241
+ readonly containers: Containers;
242
+ /** The server's Minecraft version, e.g. `"1.21.4"`. */
243
+ readonly version: string;
244
+
245
+ /**
246
+ * Listens to an event of this bot until the bot stops. Returns a function that stops listening.
247
+ *
248
+ * @example
249
+ * bot.on(BotEvent.Chat, async message => {
250
+ * if (message.text === "!ping") await bot.say("pong");
251
+ * });
252
+ */
253
+ on<E extends BotEvent>(event: E, listener: Listener<BotEventData[E]>): () => void;
254
+
255
+ status(): Promise<BotStatus>;
256
+ /** Where the bot stands. Needs `Permission.WorldRead`. */
257
+ position(): Promise<Position>;
258
+ /** True if the server's version has this block or item (older servers lack newer ones). */
259
+ supports(id: Block | Item | Entity): Promise<boolean>;
260
+
261
+ /**
262
+ * Walks to a position with the bot's pathfinder. Needs `Permission.Move`.
263
+ *
264
+ * @example
265
+ * const moved = await bot.goto(chest, { within: 2 });
266
+ * if (!moved.ok) log.warn(`Can't reach the chest: ${moved.reason}`);
267
+ */
268
+ goto(target: Vec3, options?: { within?: number; timeout?: Duration }): Promise<Result<MoveFailure>>;
269
+ /** Follows an entity until it is lost, `timeout` passes or the plugin stops. Needs `Permission.Move`. */
270
+ follow(entity: EntityInfo | number, options?: { distance?: number; timeout?: Duration }): Promise<Result<MoveFailure>>;
271
+ stopMoving(): Promise<void>;
272
+ /** Turns to look at a position. Needs `Permission.Move`. */
273
+ lookAt(target: Vec3): Promise<void>;
274
+ jump(): Promise<void>;
275
+
276
+ /** Breaks the block at a position (it must be within reach). Needs `Permission.Interact`. */
277
+ dig(position: Vec3): Promise<Result<DigFailure>>;
278
+ /** Places a block from the inventory at a position. Needs `Permission.Interact`. */
279
+ place(position: Vec3, item: Item): Promise<Result<PlaceFailure>>;
280
+ /** Right-clicks a block: opens doors, presses buttons, flips levers. Needs `Permission.Interact`. */
281
+ activateBlock(position: Vec3): Promise<Result<InteractFailure>>;
282
+ /** Uses the held item (eats food, throws a pearl). Needs `Permission.Interact`. */
283
+ useItem(): Promise<Result<InteractFailure>>;
284
+ /** Hits an entity within reach. Needs `Permission.Attack`. */
285
+ attack(entity: EntityInfo | number): Promise<Result<AttackFailure>>;
286
+
287
+ /**
288
+ * Crafts at least `count` of an item (default 1, rounded up to whole crafts) from the inventory. Small recipes use
289
+ * the inventory's 2x2 grid; bigger ones a crafting table within reach (`table`, or the nearest one). `value.crafted`
290
+ * says how many it made. Needs `Permission.InventoryManage`.
291
+ *
292
+ * @example
293
+ * const made = await bot.craft(Item.Bread, { count: 3 });
294
+ * if (!made.ok) log.warn(`No bread: ${made.message}`);
295
+ */
296
+ craft(item: Item, options?: { count?: number; table?: Vec3 }): Promise<Result<CraftFailure, { crafted: number }>>;
297
+ /** The crafting recipes that make an item on this server, with what each takes. */
298
+ recipes(item: Item): Promise<Recipe[]>;
299
+
300
+ /** Sends a chat message. Needs `Permission.ChatSend`; commands go through `command`. */
301
+ say(message: string): Promise<void>;
302
+ /** Runs a server command, with or without the slash: `bot.command("home")`. Needs `Permission.Commands`. */
303
+ command(command: string): Promise<void>;
304
+
305
+ /** Waits. Ends early (with the rest of `run`) when the bot stops. */
306
+ wait(duration: Duration): Promise<void>;
307
+ /**
308
+ * Runs `body` again and again until the bot stops: at most every `every` (default one tick), backing off
309
+ * when it throws (the error is logged), so a mistake can't spin the CPU.
310
+ *
311
+ * @example
312
+ * await bot.loop(async () => {
313
+ * const food = await bot.inventory.count(Item.Bread);
314
+ * if (food < 5) log.warn("Low on bread");
315
+ * }, { every: { seconds: 10 } });
316
+ */
317
+ loop(body: () => unknown, options?: { every?: Duration }): Promise<never>;
318
+ }
319
+
320
+ /** The profile, handed to `runProfile(profile)`. */
321
+ export interface Profile {
322
+ readonly id: string;
323
+ readonly name: string;
324
+ /** Every bot of the profile, enabled or not. */
325
+ bots(): readonly ProfileBot[];
326
+ /** A bot by id, name or uuid. */
327
+ bot(idNameOrUuid: string): ProfileBot | undefined;
328
+ /** Listens to a profile event until the plugin stops. */
329
+ on<E extends ProfileEvent>(event: E, listener: Listener<ProfileEventData[E]>): () => void;
330
+ /** Waits. */
331
+ wait(duration: Duration): Promise<void>;
332
+ /** As `bot.loop`, for the profile. */
333
+ loop(body: () => unknown, options?: { every?: Duration }): Promise<never>;
334
+ }
package/src/cli/api.ts ADDED
@@ -0,0 +1,79 @@
1
+ import { hostname } from "node:os";
2
+ import { apiUrl, readCredentials } from "./config.js";
3
+ import { fail } from "./output.js";
4
+
5
+ export interface DeviceStart {
6
+ deviceCode: string;
7
+ userCode: string;
8
+ verificationUrl: string;
9
+ interval: number;
10
+ expiresIn: number;
11
+ }
12
+
13
+ export interface ProfileEntry {
14
+ id: string;
15
+ name: string;
16
+ running: boolean;
17
+ }
18
+
19
+ export interface DevToken {
20
+ token: string;
21
+ address: string;
22
+ profileId: string;
23
+ profileName: string;
24
+ expiresAt: string;
25
+ }
26
+
27
+ async function request<T>(method: string, path: string, body?: unknown, auth = false): Promise<{ status: number; data: T | { message?: string } }> {
28
+ const headers: Record<string, string> = { "content-type": "application/json", "user-agent": "minebot-cli" };
29
+ if (auth) {
30
+ const credentials = readCredentials();
31
+ if (!credentials) fail("You're not signed in.", "Run `minebot login` first.");
32
+ headers.authorization = `Bearer ${credentials.token}`;
33
+ }
34
+ let response: Response;
35
+ try {
36
+ response = await fetch(`${apiUrl()}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
37
+ } catch (e) {
38
+ fail(`Couldn't reach ${apiUrl()}: ${(e as Error).message}`, "Check your internet connection, or MINEBOT_API_URL if you set it.");
39
+ }
40
+ const text = await response.text();
41
+ let data: unknown = {};
42
+ try {
43
+ data = text ? JSON.parse(text) : {};
44
+ } catch {
45
+ data = { message: text.slice(0, 200) };
46
+ }
47
+ return { status: response.status, data: data as T };
48
+ }
49
+
50
+ function message(data: unknown, fallback: string): string {
51
+ return (data as { message?: string })?.message ?? fallback;
52
+ }
53
+
54
+ export async function startDevice(): Promise<DeviceStart> {
55
+ const r = await request<DeviceStart>("POST", "/plugins/cli/device", { clientName: `minebot CLI on ${hostname()}` });
56
+ if (r.status !== 200) fail(message(r.data, `Sign-in failed (HTTP ${r.status})`));
57
+ return r.data as DeviceStart;
58
+ }
59
+
60
+ export async function pollDevice(deviceCode: string): Promise<{ status: string; token: string | null }> {
61
+ const r = await request<{ status: string; token: string | null }>("POST", "/plugins/cli/token", { deviceCode });
62
+ if (r.status !== 200) return { status: "pending", token: null };
63
+ return r.data as { status: string; token: string | null };
64
+ }
65
+
66
+ export async function listProfiles(): Promise<ProfileEntry[]> {
67
+ const r = await request<ProfileEntry[]>("GET", "/plugins/cli/profiles", undefined, true);
68
+ if (r.status === 401) fail(message(r.data, "Your sign-in expired."), "Run `minebot login` again.");
69
+ if (r.status !== 200) fail(message(r.data, `Couldn't list your profiles (HTTP ${r.status})`));
70
+ return r.data as ProfileEntry[];
71
+ }
72
+
73
+ export async function devToken(profileId: string): Promise<DevToken> {
74
+ const r = await request<DevToken>("POST", "/plugins/cli/dev-token", { profileId }, true);
75
+ if (r.status === 401) fail(message(r.data, "Your sign-in expired."), "Run `minebot login` again.");
76
+ if (r.status === 409) fail(message(r.data, "The profile isn't running."), "Start it on the dashboard, then run `minebot dev` again.");
77
+ if (r.status !== 200) fail(message(r.data, `Couldn't get a dev token (HTTP ${r.status})`));
78
+ return r.data as DevToken;
79
+ }
@@ -0,0 +1,76 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import * as esbuild from "esbuild";
5
+ import { isDefinedPlugin, type DefinedPlugin } from "../plugin.js";
6
+ import { fail } from "./output.js";
7
+
8
+ export interface Project {
9
+ root: string;
10
+ entry: string;
11
+ name: string;
12
+ version: string;
13
+ }
14
+
15
+ /** The plugin project in the current folder: a package.json and src/index.ts (or the `minebot.entry` it names). */
16
+ export function findProject(root = process.cwd()): Project {
17
+ const packageFile = join(root, "package.json");
18
+ if (!existsSync(packageFile)) fail("No package.json here.", "Run minebot in your plugin's folder, or create one with `npx @minecraftbot-com/plugin create my-plugin`.");
19
+ const pkg = JSON.parse(readFileSync(packageFile, "utf8")) as { name?: string; version?: string; minebot?: { entry?: string } };
20
+ const entry = resolve(root, pkg.minebot?.entry ?? "src/index.ts");
21
+ if (!existsSync(entry)) fail(`No ${entry}.`, "Your plugin's code goes in src/index.ts, with `export default definePlugin({ ... })`.");
22
+ return { root, entry, name: pkg.name ?? "plugin", version: pkg.version ?? "0.0.0" };
23
+ }
24
+
25
+ /**
26
+ * The bundle `minebot dev` runs in Node: the SDK stays an import so the plugin and the CLI share one copy of it
27
+ * (errors thrown by the SDK are the classes the plugin imports).
28
+ */
29
+ export function devBuildOptions(project: Project, outfile: string): esbuild.BuildOptions {
30
+ return {
31
+ entryPoints: [project.entry],
32
+ outfile,
33
+ bundle: true,
34
+ format: "esm",
35
+ platform: "node",
36
+ target: "node22",
37
+ sourcemap: "inline",
38
+ external: ["@minecraftbot-com/plugin", "@minecraftbot-com/plugin/*"],
39
+ logLevel: "silent",
40
+ };
41
+ }
42
+
43
+ /**
44
+ * The bundle a hosted runner runs: everything included, minified, and the SDK compiled from its TypeScript
45
+ * source (the `minebot-source` condition) so enum members become plain strings and the enum objects drop out.
46
+ */
47
+ export function hostedBuildOptions(project: Project, outfile: string): esbuild.BuildOptions {
48
+ return {
49
+ entryPoints: [project.entry],
50
+ outfile,
51
+ bundle: true,
52
+ format: "esm",
53
+ platform: "neutral",
54
+ target: "es2022",
55
+ minify: true,
56
+ treeShaking: true,
57
+ conditions: ["minebot-source"],
58
+ mainFields: ["module", "main"],
59
+ legalComments: "none",
60
+ metafile: true,
61
+ logLevel: "silent",
62
+ };
63
+ }
64
+
65
+ export function formatErrors(errors: esbuild.Message[]): string {
66
+ return errors.map(e => (e.location ? `${e.location.file}:${e.location.line}:${e.location.column}: ${e.text}` : e.text)).join("\n");
67
+ }
68
+
69
+ /** Imports a built plugin module and returns its default export, which must be `definePlugin(...)`. */
70
+ export async function loadPlugin(file: string, cacheBust: number | string = Date.now()): Promise<DefinedPlugin> {
71
+ const module = await import(`${pathToFileURL(file).href}?v=${cacheBust}`);
72
+ if (!isDefinedPlugin(module.default)) {
73
+ fail("The plugin's entry file has no plugin as its default export.", "End src/index.ts with `export default definePlugin({ name: ..., permissions: [...], async run(bot) { ... } })`.");
74
+ }
75
+ return module.default;
76
+ }