@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/src/storage.ts ADDED
@@ -0,0 +1,82 @@
1
+ import type { StorageSchema } from "./protocol.js";
2
+ import { StorageScope } from "./generated/contracts.js";
3
+ import type { JsonValue } from "./types.js";
4
+
5
+ /** Declares one stored value. Build it with `Storage.value` or `Storage.map`. */
6
+ export interface StorageDefinition<T, K extends "value" | "map", S extends StorageScope> {
7
+ readonly schema: StorageSchema;
8
+ readonly __value?: T;
9
+ readonly __kind?: K;
10
+ readonly __scope?: S;
11
+ }
12
+
13
+ /**
14
+ * Data your plugin keeps between runs. It belongs to the user who installed the plugin, is limited to
15
+ * 1 MB per scope and 64 KB per value, and holds JSON values only.
16
+ *
17
+ * Scopes: `StorageScope.Profile` (default, shared by every bot of the profile), `StorageScope.Bot` (one per
18
+ * account, survives renames), `StorageScope.User` (shared by all of the user's profiles).
19
+ *
20
+ * @example
21
+ * storage: {
22
+ * harvested: Storage.value({ scope: StorageScope.Bot, default: 0 }),
23
+ * homes: Storage.map<Vec3>(),
24
+ * }
25
+ */
26
+ export const Storage = {
27
+ /** A single value. `get()` returns `default` until something is set. */
28
+ value<T, S extends StorageScope = StorageScope.Profile>(o: { scope?: S; default: T & JsonValue }): StorageDefinition<T, "value", NoInfer<S>> {
29
+ return { schema: { kind: "value", scope: o.scope ?? StorageScope.Profile, default: o.default } };
30
+ },
31
+
32
+ /** Keys (strings, up to 128 characters) to values. */
33
+ map<T extends JsonValue, S extends StorageScope = StorageScope.Profile>(o: { scope?: S } = {}): StorageDefinition<T, "map", NoInfer<S>> {
34
+ return { schema: { kind: "map", scope: o.scope ?? StorageScope.Profile } };
35
+ },
36
+ };
37
+
38
+ /** A stored value. */
39
+ export interface StoredValue<T> {
40
+ /** The current value, or the declared default. */
41
+ get(): Promise<T>;
42
+ set(value: T): Promise<void>;
43
+ /** Back to the default. */
44
+ delete(): Promise<void>;
45
+ /**
46
+ * Read, change and write in one step. If another bot wrote in between, `fn` runs again on the newer
47
+ * value, so concurrent updates are never lost.
48
+ *
49
+ * @example await storage.harvested.update(n => n + 1);
50
+ */
51
+ update(fn: (current: T) => T): Promise<T>;
52
+ }
53
+
54
+ /** A stored map from string keys to values. */
55
+ export interface StoredMap<T> {
56
+ get(key: string): Promise<T | undefined>;
57
+ set(key: string, value: T): Promise<void>;
58
+ delete(key: string): Promise<void>;
59
+ /** Change one entry in one step; `fn` gets `undefined` for a missing key. */
60
+ update(key: string, fn: (current: T | undefined) => T): Promise<T>;
61
+ /** Every key, in order. */
62
+ keys(): Promise<string[]>;
63
+ /** Every entry, in key order. */
64
+ entries(): Promise<[string, T][]>;
65
+ }
66
+
67
+ /** A bot-scoped value seen from `runProfile`: pick the bot first. */
68
+ export interface PerBot<S> {
69
+ for(bot: { readonly uuid: string }): S;
70
+ }
71
+
72
+ type Stored<T, K> = K extends "map" ? StoredMap<T> : StoredValue<T>;
73
+
74
+ type Accessor<D, InRun extends boolean> =
75
+ D extends StorageDefinition<infer T, infer K, infer S>
76
+ ? InRun extends true ? Stored<T, K> : S extends StorageScope.Bot ? PerBot<Stored<T, K>> : Stored<T, K>
77
+ : never;
78
+
79
+ /** `storage` inside `run(bot)`: bot-scoped entries are already bound to that bot. */
80
+ export type BotStorage<S> = { readonly [K in keyof S]: Accessor<S[K], true> };
81
+ /** `storage` inside `runProfile`: bot-scoped entries need `.for(bot)`. */
82
+ export type ProfileStorage<S> = { readonly [K in keyof S]: Accessor<S[K], false> };
@@ -0,0 +1,571 @@
1
+ import { OPERATIONS, PROFILE_WIDE_OPERATIONS, EVENT_PERMISSIONS } from "../generated/operations.js";
2
+ import { BotEvent, ProfileEvent, StorageScope } from "../generated/contracts.js";
3
+ import type { BotInfo, CallFrame, ContainerFrame, HelloFrame, Limits, Manifest, PluginFrame } from "../protocol.js";
4
+ import { networkHost } from "../permissions.js";
5
+ import type { Transport } from "../runtime/connection.js";
6
+ import type { Vec3 } from "../types.js";
7
+
8
+ /** A block in the fake world. */
9
+ export interface FakeBlock {
10
+ position: Vec3;
11
+ block: string;
12
+ state?: Record<string, string | number | boolean>;
13
+ }
14
+
15
+ export interface FakeEntity {
16
+ id: number;
17
+ type: string;
18
+ position: Vec3;
19
+ uuid?: string;
20
+ name?: string;
21
+ }
22
+
23
+ export interface FakeItem {
24
+ item: string;
25
+ count: number;
26
+ slot?: number;
27
+ name?: string;
28
+ }
29
+
30
+ /** A recipe the fake bot can craft: what one craft takes, what it makes. */
31
+ export interface FakeRecipe {
32
+ result: string;
33
+ /** Made per craft (default 1). */
34
+ count?: number;
35
+ /** Item to how many one craft takes. */
36
+ ingredients: Record<string, number>;
37
+ /** Needs a crafting table (a `minecraft:crafting_table` block within reach). */
38
+ table?: boolean;
39
+ }
40
+
41
+ /** A chest (or other container) of the fake world; its block is added to `blocks`. */
42
+ export interface FakeChest {
43
+ position: Vec3;
44
+ /** Default `minecraft:chest`. */
45
+ block?: string;
46
+ /** Slots (default 27). */
47
+ size?: number;
48
+ items?: FakeItem[];
49
+ }
50
+
51
+ /** One bot of the fake profile. */
52
+ export interface FakeBotOptions {
53
+ id?: string;
54
+ name?: string;
55
+ uuid?: string;
56
+ position?: Vec3;
57
+ health?: number;
58
+ food?: number;
59
+ inventory?: FakeItem[];
60
+ connected?: boolean;
61
+ /** Whether the plugin runs on it (default true). */
62
+ enabled?: boolean;
63
+ version?: string;
64
+ }
65
+
66
+ export interface FakeContainerOptions {
67
+ bots?: FakeBotOptions[];
68
+ blocks?: FakeBlock[];
69
+ entities?: FakeEntity[];
70
+ players?: { name: string; uuid: string; ping?: number }[];
71
+ /** Positions `goto` can't reach (NoPath). */
72
+ unreachable?: Vec3[];
73
+ /** Settings per bot id (or "*" for all). Missing keys fall back to the manifest's defaults. */
74
+ settings?: Record<string, Record<string, unknown>>;
75
+ /** Grant only these; default: whatever the manifest declares, as `minebot dev` does. */
76
+ granted?: string[];
77
+ /** Recipes `bot.craft` and `bot.recipes` know (the real container uses the game's). */
78
+ recipes?: FakeRecipe[];
79
+ containers?: FakeChest[];
80
+ profile?: { id: string; name: string };
81
+ }
82
+
83
+ export interface RecordedCall {
84
+ bot: string | null;
85
+ op: string;
86
+ args: Record<string, unknown>;
87
+ }
88
+
89
+ interface BotState {
90
+ info: BotInfo;
91
+ position: Vec3;
92
+ health: number;
93
+ food: number;
94
+ inventory: FakeItem[];
95
+ version: string;
96
+ /** The container open on this bot (a key of `chests`). */
97
+ open: string | null;
98
+ }
99
+
100
+ interface ChestState {
101
+ position: Vec3;
102
+ block: string;
103
+ size: number;
104
+ items: FakeItem[];
105
+ }
106
+
107
+ const STACK = 64;
108
+ const INVENTORY_SLOTS = 36;
109
+
110
+ function countOf(items: FakeItem[], item: string): number {
111
+ return items.filter(s => s.item === item).reduce((n, s) => n + s.count, 0);
112
+ }
113
+
114
+ /** Takes up to `count` of an item out of a slot list; returns how many it took. */
115
+ function takeFrom(items: FakeItem[], item: string, count: number): number {
116
+ let taken = 0;
117
+ for (const s of items) {
118
+ if (s.item !== item || taken >= count) continue;
119
+ const n = Math.min(s.count, count - taken);
120
+ s.count -= n;
121
+ taken += n;
122
+ }
123
+ for (let i = items.length - 1; i >= 0; i--) if (items[i].count <= 0) items.splice(i, 1);
124
+ return taken;
125
+ }
126
+
127
+ /** Puts up to `count` of an item into a slot list of `slots` slots, stacking to 64; returns how many fit. */
128
+ function putInto(items: FakeItem[], slots: number, item: string, count: number): number {
129
+ let put = 0;
130
+ for (const s of items) {
131
+ if (s.item !== item || s.count >= STACK || put >= count) continue;
132
+ const n = Math.min(STACK - s.count, count - put);
133
+ s.count += n;
134
+ put += n;
135
+ }
136
+ while (put < count && items.length < slots) {
137
+ const used = new Set(items.map(s => s.slot));
138
+ let slot = 0;
139
+ while (used.has(slot)) slot++;
140
+ const n = Math.min(STACK, count - put);
141
+ items.push({ item, count: n, slot });
142
+ put += n;
143
+ }
144
+ return put;
145
+ }
146
+
147
+ const REACH = 4.5;
148
+ const LIMITS: Limits = { callsPerSecond: 50, concurrentCalls: 64, frameBytes: 131072, eventQueue: 256, storageBytes: 1_048_576, storageValueBytes: 65_536 };
149
+
150
+ function key(p: Vec3): string {
151
+ return `${p.x},${p.y},${p.z}`;
152
+ }
153
+
154
+ function distance(a: Vec3, b: Vec3): number {
155
+ return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
156
+ }
157
+
158
+ /**
159
+ * An in-memory bot container for tests: a tiny world, inventories, chat, storage, and the same permission
160
+ * checks as the real one. It speaks the real protocol over a Transport, so the SDK is exercised end to end.
161
+ */
162
+ export class FakeContainer {
163
+ readonly calls: RecordedCall[] = [];
164
+ readonly said: { bot: string; text: string }[] = [];
165
+ readonly commands: { bot: string; command: string }[] = [];
166
+ readonly logs: { bot: string | null; level: string; message: string }[] = [];
167
+ readonly warnings = new Map<string, string>();
168
+ readonly stats = new Map<string, number>();
169
+ readonly errors: { op: string; code: string; message: string }[] = [];
170
+ readonly blocks = new Map<string, FakeBlock>();
171
+ readonly storage = new Map<string, { value: unknown; version: number }>();
172
+ manifest: Manifest | null = null;
173
+
174
+ private readonly bots = new Map<string, BotState>();
175
+ private readonly subscriptions = new Set<string>();
176
+ private readonly running = new Set<string>();
177
+ private granted = new Set<string>();
178
+ private entities: FakeEntity[];
179
+ private readonly players: { name: string; uuid: string; ping: number }[];
180
+ private readonly unreachable: Set<string>;
181
+ private readonly pendingFollows = new Map<number, () => void>();
182
+ /** The fake world's containers by position, readable from tests. */
183
+ readonly chests = new Map<string, ChestState>();
184
+
185
+ constructor(private readonly transport: Transport, private readonly options: FakeContainerOptions = {}) {
186
+ const bots = options.bots?.length ? options.bots : [{}];
187
+ bots.forEach((b, i) => {
188
+ const id = b.id ?? `bot-${i + 1}`;
189
+ this.bots.set(id, {
190
+ info: { id, name: b.name ?? `Bot${i + 1}`, uuid: b.uuid ?? `00000000-0000-0000-0000-${String(i + 1).padStart(12, "0")}`, connected: b.connected ?? true, enabled: b.enabled ?? true },
191
+ position: b.position ?? { x: 0, y: 64, z: 0 },
192
+ health: b.health ?? 20,
193
+ food: b.food ?? 20,
194
+ inventory: (b.inventory ?? []).map((it, slot) => ({ slot, ...it })),
195
+ version: b.version ?? "1.21.4",
196
+ open: null,
197
+ });
198
+ });
199
+ for (const b of options.blocks ?? []) this.blocks.set(key(b.position), { ...b, state: b.state ?? {} });
200
+ for (const c of options.containers ?? []) {
201
+ const block = c.block ?? "minecraft:chest";
202
+ this.chests.set(key(c.position), { position: c.position, block, size: c.size ?? 27, items: (c.items ?? []).map((it, slot) => ({ slot, ...it })) });
203
+ this.blocks.set(key(c.position), { position: c.position, block, state: {} });
204
+ }
205
+ this.entities = [...(options.entities ?? [])];
206
+ this.players = (options.players ?? []).map(p => ({ ping: 20, ...p }));
207
+ this.unreachable = new Set((options.unreachable ?? []).map(key));
208
+ transport.onmessage = text => this.receive(text);
209
+ transport.onclose = () => {};
210
+ }
211
+
212
+ bot(id: string): BotState {
213
+ const b = this.bots.get(id);
214
+ if (!b) throw new Error(`No fake bot ${id}`);
215
+ return b;
216
+ }
217
+
218
+ /** Starts run(bot) on every enabled, connected bot (and runProfile), as the container does after welcome. */
219
+ startAll(): void {
220
+ if (this.manifest?.profile) this.send({ type: "start", bot: null, settings: this.settingsFor("*") });
221
+ for (const b of this.bots.values()) if (b.info.enabled && b.info.connected) this.startBot(b.info.id);
222
+ }
223
+
224
+ startBot(id: string): void {
225
+ this.running.add(id);
226
+ this.send({ type: "start", bot: id, settings: this.settingsFor(id), version: this.bot(id).version });
227
+ }
228
+
229
+ stopBot(id: string, reason = "UserStopped"): void {
230
+ this.running.delete(id);
231
+ this.send({ type: "stop", bot: id, reason });
232
+ }
233
+
234
+ /** Sends a bot event if the plugin subscribed to it. Returns whether it was sent. */
235
+ emit(bot: string, event: BotEvent, data: unknown): boolean {
236
+ if (!this.subscriptions.has(`${bot}|${event}`)) return false;
237
+ this.send({ type: "event", bot, event, data });
238
+ return true;
239
+ }
240
+
241
+ /** Sends a profile event (`botId` in data becomes a ProfileBot in the SDK). */
242
+ emitProfile(event: ProfileEvent, data: unknown): boolean {
243
+ if (!this.subscriptions.has(`|${event}`)) return false;
244
+ this.send({ type: "event", bot: null, event, data });
245
+ return true;
246
+ }
247
+
248
+ /** A chat message from a player (or the server, without sender) to a bot. */
249
+ chat(bot: string, text: string, sender: string | null = "Steve"): boolean {
250
+ return this.emit(bot, BotEvent.Chat, { text, sender, senderUuid: null, system: sender === null });
251
+ }
252
+
253
+ disconnectBot(id: string, reason = "Kicked"): void {
254
+ const b = this.bot(id);
255
+ b.info.connected = false;
256
+ if (this.running.has(id)) this.stopBot(id, "BotDisconnected");
257
+ this.send({ type: "bots", bots: [...this.bots.values()].map(x => x.info) });
258
+ this.emitProfile(ProfileEvent.BotDisconnected, { botId: id, reason });
259
+ }
260
+
261
+ setEntities(entities: FakeEntity[]): void {
262
+ this.entities = [...entities];
263
+ }
264
+
265
+ close(): void {
266
+ this.transport.close(1000, "Test finished");
267
+ }
268
+
269
+ private settingsFor(id: string): Record<string, unknown> {
270
+ return { ...(this.options.settings?.["*"] ?? {}), ...(this.options.settings?.[id] ?? {}) };
271
+ }
272
+
273
+ private send(frame: ContainerFrame): void {
274
+ this.transport.send(JSON.stringify(frame));
275
+ }
276
+
277
+ private receive(text: string): void {
278
+ const frame = JSON.parse(text) as PluginFrame;
279
+ switch (frame.type) {
280
+ case "hello":
281
+ this.hello(frame);
282
+ break;
283
+ case "call":
284
+ this.call(frame);
285
+ break;
286
+ case "cancel": {
287
+ const resolve = this.pendingFollows.get(frame.id);
288
+ this.pendingFollows.delete(frame.id);
289
+ resolve?.();
290
+ break;
291
+ }
292
+ case "subscribe": {
293
+ const event = frame.event as BotEvent;
294
+ const needs = frame.bot === null ? null : EVENT_PERMISSIONS[event];
295
+ if (needs && !this.granted.has(needs)) {
296
+ this.errors.push({ op: `subscribe ${event}`, code: "PermissionDenied", message: `BotEvent.${event} needs Permission.${needs}` });
297
+ this.send({ type: "error", id: null, code: "PermissionDenied", message: `BotEvent.${event} needs Permission.${needs}` });
298
+ break;
299
+ }
300
+ this.subscriptions.add(`${frame.bot ?? ""}|${frame.event}`);
301
+ break;
302
+ }
303
+ case "unsubscribe":
304
+ this.subscriptions.delete(`${frame.bot ?? ""}|${frame.event}`);
305
+ break;
306
+ case "log":
307
+ this.logs.push({ bot: frame.bot, level: frame.level, message: frame.message });
308
+ break;
309
+ case "warning":
310
+ if (frame.message === null) this.warnings.delete(`${frame.bot ?? ""}|${frame.key}`);
311
+ else this.warnings.set(`${frame.bot ?? ""}|${frame.key}`, frame.message);
312
+ break;
313
+ case "stat":
314
+ this.stats.set(`${frame.bot ?? ""}|${frame.key}`, frame.value);
315
+ break;
316
+ case "done":
317
+ if (frame.bot) this.running.delete(frame.bot);
318
+ break;
319
+ }
320
+ }
321
+
322
+ private hello(frame: HelloFrame): void {
323
+ this.manifest = frame.manifest;
324
+ this.granted = new Set(this.options.granted ?? frame.manifest.permissions);
325
+ this.send({
326
+ type: "welcome",
327
+ installation: "test-installation",
328
+ mode: "Dev",
329
+ profile: this.options.profile ?? { id: "test-profile", name: "Test profile" },
330
+ bots: [...this.bots.values()].map(b => b.info),
331
+ granted: [...this.granted],
332
+ settings: this.settingsFor("*"),
333
+ limits: LIMITS,
334
+ });
335
+ }
336
+
337
+ private fail(frame: CallFrame, failure: string, message: string): void {
338
+ this.send({ type: "result", id: frame.id, ok: false, failure, message });
339
+ }
340
+
341
+ private ok(frame: CallFrame, value: unknown = null): void {
342
+ this.send({ type: "result", id: frame.id, ok: true, value });
343
+ }
344
+
345
+ private error(frame: CallFrame, code: string, message: string): void {
346
+ this.errors.push({ op: frame.op, code, message });
347
+ this.send({ type: "error", id: frame.id, code, message });
348
+ }
349
+
350
+ private call(frame: CallFrame): void {
351
+ this.calls.push({ bot: frame.bot, op: frame.op, args: frame.args });
352
+ if (!(frame.op in OPERATIONS)) return this.error(frame, "UnknownOperation", `Unknown operation ${frame.op}`);
353
+ const needs = OPERATIONS[frame.op];
354
+ if (needs && !this.granted.has(needs)) return this.error(frame, "PermissionDenied", `${frame.op} needs Permission.${needs}: add it to permissions in definePlugin`);
355
+ if (frame.bot !== null && !PROFILE_WIDE_OPERATIONS.has(frame.op) && !this.running.has(frame.bot)) {
356
+ return this.error(frame, "BotNotRunning", `The plugin isn't running on bot ${frame.bot}`);
357
+ }
358
+ const a = frame.args as any;
359
+ const b = frame.bot ? this.bots.get(frame.bot) : undefined;
360
+ if (frame.bot && !b) return this.fail(frame, "UnknownBot", `No bot ${frame.bot}`);
361
+
362
+ switch (frame.op) {
363
+ case "bot.status":
364
+ return this.ok(frame, { health: b!.health, food: b!.food, saturation: 5, alive: b!.health > 0, gameMode: "Survival", dimension: "minecraft:overworld", experienceLevel: 0 });
365
+ case "bot.position":
366
+ return this.ok(frame, b!.position);
367
+ case "bot.supports":
368
+ return this.ok(frame, true);
369
+ case "bot.goto": {
370
+ const target = { x: a.x, y: a.y, z: a.z };
371
+ if (this.unreachable.has(key(target))) return this.fail(frame, "NoPath", `No path to ${key(target)}`);
372
+ b!.position = target;
373
+ return this.ok(frame);
374
+ }
375
+ case "bot.follow":
376
+ // Follows until cancelled: resolves when the plugin stops or cancels the call.
377
+ this.pendingFollows.set(frame.id, () => {});
378
+ return;
379
+ case "bot.stopMoving":
380
+ case "bot.lookAt":
381
+ case "bot.jump":
382
+ return this.ok(frame);
383
+ case "bot.dig": {
384
+ const at = { x: a.x, y: a.y, z: a.z };
385
+ if (distance(b!.position, at) > REACH) return this.fail(frame, "OutOfReach", "Too far away");
386
+ if (!this.blocks.delete(key(at))) return this.fail(frame, "NothingThere", "No block there");
387
+ return this.ok(frame);
388
+ }
389
+ case "bot.place": {
390
+ const at = { x: a.x, y: a.y, z: a.z };
391
+ if (distance(b!.position, at) > REACH) return this.fail(frame, "OutOfReach", "Too far away");
392
+ if (this.blocks.has(key(at))) return this.fail(frame, "Occupied", "Something is already there");
393
+ const stack = b!.inventory.find(s => s.item === a.item && s.count > 0);
394
+ if (!stack) return this.fail(frame, "NoItem", `No ${a.item} in the inventory`);
395
+ stack.count--;
396
+ this.blocks.set(key(at), { position: at, block: a.item, state: {} });
397
+ return this.ok(frame);
398
+ }
399
+ case "bot.activateBlock":
400
+ case "bot.useItem":
401
+ return this.ok(frame);
402
+ case "bot.attack": {
403
+ const target = this.entities.find(e => e.id === a.entity);
404
+ if (!target) return this.fail(frame, "NotFound", "No such entity");
405
+ if (distance(b!.position, target.position) > 3) return this.fail(frame, "OutOfReach", "Too far away");
406
+ return this.ok(frame);
407
+ }
408
+ case "bot.say":
409
+ this.said.push({ bot: frame.bot!, text: a.text });
410
+ return this.ok(frame);
411
+ case "bot.command":
412
+ this.commands.push({ bot: frame.bot!, command: a.command });
413
+ return this.ok(frame);
414
+ case "bot.connect":
415
+ if (b!.info.connected) return this.fail(frame, "AlreadyConnected", "Already connected");
416
+ b!.info.connected = true;
417
+ return this.ok(frame);
418
+ case "bot.disconnect":
419
+ if (!b!.info.connected) return this.fail(frame, "AlreadyDisconnected", "Already disconnected");
420
+ b!.info.connected = false;
421
+ return this.ok(frame);
422
+ case "bot.reconnect":
423
+ return this.ok(frame);
424
+ case "world.block": {
425
+ const found = this.blocks.get(key(a));
426
+ return this.ok(frame, found ? { position: found.position, block: found.block, state: found.state ?? {} } : null);
427
+ }
428
+ case "world.findBlocks": {
429
+ const from = a.from ?? b!.position;
430
+ const wanted = new Set<string>(a.blocks);
431
+ const matches = [...this.blocks.values()]
432
+ .filter(x => wanted.has(x.block) && distance(from, x.position) <= a.radius)
433
+ .filter(x => Object.entries(a.state ?? {}).every(([k, v]) => String(x.state?.[k]) === String(v)))
434
+ .sort((p, q) => distance(from, p.position) - distance(from, q.position))
435
+ .slice(0, a.limit);
436
+ return this.ok(frame, matches.map(x => ({ position: x.position, block: x.block, state: x.state ?? {} })));
437
+ }
438
+ case "entities.nearby": {
439
+ const types = a.types ? new Set<string>(a.types) : null;
440
+ const list = this.entities
441
+ .map(e => ({ ...e, distance: distance(b!.position, e.position) }))
442
+ .filter(e => e.distance <= a.radius && (!types || types.has(e.type)))
443
+ .sort((p, q) => p.distance - q.distance)
444
+ .slice(0, a.limit)
445
+ .map(e => ({ id: e.id, type: e.type, uuid: e.uuid ?? null, name: e.name ?? null, position: e.position, distance: e.distance }));
446
+ return this.ok(frame, list);
447
+ }
448
+ case "entities.players":
449
+ return this.ok(frame, this.players.map(p => ({ ...p, gameMode: "Survival" })));
450
+ case "inventory.items":
451
+ return this.ok(frame, b!.inventory.filter(s => s.count > 0).map(s => ({ item: s.item, count: s.count, slot: s.slot ?? 0, name: s.name ?? null })));
452
+ case "inventory.held": {
453
+ const s = b!.inventory.find(x => x.count > 0);
454
+ return this.ok(frame, s ? { item: s.item, count: s.count, slot: s.slot ?? 0, name: s.name ?? null } : null);
455
+ }
456
+ case "inventory.equip":
457
+ return b!.inventory.some(s => s.item === a.item && s.count > 0) ? this.ok(frame) : this.fail(frame, "NoItem", `No ${a.item}`);
458
+ case "inventory.drop": {
459
+ const s = b!.inventory.find(x => x.item === a.item && x.count > 0);
460
+ if (!s) return this.fail(frame, "NoItem", `No ${a.item}`);
461
+ s.count = a.count === null ? 0 : Math.max(0, s.count - a.count);
462
+ return this.ok(frame);
463
+ }
464
+ case "bot.recipes":
465
+ return this.ok(frame, (this.options.recipes ?? []).filter(r => r.result === a.item).map(r => ({
466
+ result: r.result, count: r.count ?? 1, table: r.table ?? false,
467
+ ingredients: Object.entries(r.ingredients).map(([item, count]) => ({ items: [item], count })),
468
+ })));
469
+ case "bot.craft":
470
+ return this.craft(frame, b!, a);
471
+ case "container.open": {
472
+ const at = { x: a.x, y: a.y, z: a.z };
473
+ const chest = this.chests.get(key(at));
474
+ if (!chest) return this.fail(frame, "NotAContainer", `${this.blocks.get(key(at))?.block ?? "Nothing"} at ${key(at)} isn't a container`);
475
+ if (distance(b!.position, at) > REACH) return this.fail(frame, "OutOfReach", "Too far away");
476
+ b!.open = key(at);
477
+ return this.ok(frame, { position: chest.position, block: chest.block, size: chest.size, items: this.describe(chest.items) });
478
+ }
479
+ case "container.items": {
480
+ const chest = b!.open ? this.chests.get(b!.open) : undefined;
481
+ return chest ? this.ok(frame, this.describe(chest.items)) : this.fail(frame, "Closed", "No container is open");
482
+ }
483
+ case "container.deposit":
484
+ case "container.withdraw": {
485
+ const chest = b!.open ? this.chests.get(b!.open) : undefined;
486
+ if (!chest) return this.fail(frame, "Closed", "No container is open");
487
+ const deposit = frame.op === "container.deposit";
488
+ const [from, to, toSlots] = deposit ? [b!.inventory, chest.items, chest.size] : [chest.items, b!.inventory, INVENTORY_SLOTS];
489
+ const wanted = Math.min(a.count ?? Infinity, countOf(from, a.item));
490
+ if (wanted === 0) return this.fail(frame, "NoItem", `No ${a.item} to move`);
491
+ const moved = putInto(to, toSlots, a.item, wanted);
492
+ takeFrom(from, a.item, moved);
493
+ return moved > 0 ? this.ok(frame, { moved }) : this.fail(frame, "Full", "No room");
494
+ }
495
+ case "container.close":
496
+ b!.open = null;
497
+ return this.ok(frame);
498
+ case "plugins.start":
499
+ case "plugins.stop":
500
+ return this.ok(frame);
501
+ case "storage.get":
502
+ case "storage.set":
503
+ case "storage.delete":
504
+ case "storage.entries":
505
+ return this.storageCall(frame, a);
506
+ }
507
+ return this.error(frame, "UnknownOperation", `The fake container doesn't implement ${frame.op}`);
508
+ }
509
+
510
+ private describe(items: FakeItem[]) {
511
+ return items.filter(s => s.count > 0).map(s => ({ item: s.item, count: s.count, slot: s.slot ?? 0, name: s.name ?? null }));
512
+ }
513
+
514
+ /** Crafts as the real container does: whole crafts, ingredients from the inventory, a table within reach if needed. */
515
+ private craft(frame: CallFrame, b: BotState, a: any): void {
516
+ const recipe = (this.options.recipes ?? []).find(r => r.result === a.item);
517
+ if (!recipe) return this.fail(frame, "NoRecipe", `No crafting recipe makes ${a.item}`);
518
+ const per = recipe.count ?? 1;
519
+ const crafts = Math.ceil((a.count ?? 1) / per);
520
+ const missing = Object.entries(recipe.ingredients).filter(([item, n]) => countOf(b.inventory, item) < n * crafts);
521
+ if (missing.length) return this.fail(frame, "MissingIngredients", `Crafting ${a.item} needs ${missing.map(([item, n]) => `${n * crafts} ${item}`).join(", ")}`);
522
+ if (recipe.table) {
523
+ const tables = [...this.blocks.values()].filter(x => x.block === "minecraft:crafting_table" && distance(b.position, x.position) <= REACH);
524
+ const at = a.table ? tables.find(t => key(t.position) === key(a.table)) : tables[0];
525
+ if (!at) return this.fail(frame, "NoCraftingTable", `${a.item} needs a crafting table and none is within reach`);
526
+ }
527
+ for (const [item, n] of Object.entries(recipe.ingredients)) takeFrom(b.inventory, item, n * crafts);
528
+ const made = putInto(b.inventory, INVENTORY_SLOTS, recipe.result, per * crafts);
529
+ if (made === 0) return this.fail(frame, "InventoryFull", "No room in the inventory");
530
+ b.open = null;
531
+ return this.ok(frame, { crafted: made });
532
+ }
533
+
534
+ private storageCall(frame: CallFrame, a: any): void {
535
+ const declared = this.manifest?.storage[a.name];
536
+ if (!declared) return this.error(frame, "BadArguments", `storage.${a.name} isn't declared in definePlugin's storage`);
537
+ if (declared.scope === StorageScope.Bot && !a.bot) return this.error(frame, "BadArguments", `storage.${a.name} is bot-scoped: use storage.${a.name}.for(bot)`);
538
+ const base = `${a.name}|${declared.scope}|${a.bot ?? ""}`;
539
+ switch (frame.op) {
540
+ case "storage.get": {
541
+ const entry = this.storage.get(`${base}|${a.key ?? ""}`);
542
+ return this.ok(frame, { value: entry?.value ?? null, version: entry?.version ?? 0 });
543
+ }
544
+ case "storage.set": {
545
+ const k = `${base}|${a.key ?? ""}`;
546
+ const entry = this.storage.get(k);
547
+ const version = entry?.version ?? 0;
548
+ if (a.ifVersion !== null && a.ifVersion !== version) return this.fail(frame, "Conflict", "Changed since it was read");
549
+ if (JSON.stringify(a.value).length > LIMITS.storageValueBytes) return this.error(frame, "ValueTooLarge", "Values are limited to 64 KB");
550
+ this.storage.set(k, { value: JSON.parse(JSON.stringify(a.value)), version: version + 1 });
551
+ return this.ok(frame, { version: version + 1 });
552
+ }
553
+ case "storage.delete":
554
+ this.storage.delete(`${base}|${a.key ?? ""}`);
555
+ return this.ok(frame);
556
+ case "storage.entries": {
557
+ const prefix = `${base}|`;
558
+ const keys = [...this.storage.keys()].filter(k => k.startsWith(prefix) && k !== prefix).map(k => k.slice(prefix.length)).sort();
559
+ const start = a.after ? keys.findIndex(k => k > a.after) : 0;
560
+ const page = start < 0 ? [] : keys.slice(start, start + a.limit);
561
+ const next = start >= 0 && start + a.limit < keys.length ? page[page.length - 1] : null;
562
+ return this.ok(frame, { entries: page.map(k => [k, this.storage.get(prefix + k)!.value]), next });
563
+ }
564
+ }
565
+ }
566
+ }
567
+
568
+ /** Hosts a declared network permission covers, for tests of fetch rules. */
569
+ export function declaredHosts(manifest: Manifest): string[] {
570
+ return manifest.permissions.map(networkHost).filter((h): h is string => h !== null);
571
+ }