@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
@@ -0,0 +1,69 @@
1
+ // Generated from Minecraft 26.3 and the MineBot plugin protocol. Do not edit.
2
+
3
+ import { BotEvent, Permission } from "./contracts.js";
4
+
5
+ /** Every operation the bot container accepts and the permission it needs (null: always allowed). For the test kit and `minebot check`; not part of the runtime. */
6
+ export const OPERATIONS: Readonly<Record<string, Permission | null>> = {
7
+ "bot.activateBlock": Permission.Interact,
8
+ "bot.attack": Permission.Attack,
9
+ "bot.command": Permission.Commands,
10
+ "bot.connect": Permission.ProfileBots,
11
+ "bot.craft": Permission.InventoryManage,
12
+ "bot.dig": Permission.Interact,
13
+ "bot.disconnect": Permission.ProfileBots,
14
+ "bot.follow": Permission.Move,
15
+ "bot.goto": Permission.Move,
16
+ "bot.jump": Permission.Move,
17
+ "bot.lookAt": Permission.Move,
18
+ "bot.place": Permission.Interact,
19
+ "bot.position": Permission.WorldRead,
20
+ "bot.recipes": null,
21
+ "bot.reconnect": Permission.ProfileBots,
22
+ "bot.say": Permission.ChatSend,
23
+ "bot.status": null,
24
+ "bot.stopMoving": Permission.Move,
25
+ "bot.supports": null,
26
+ "bot.useItem": Permission.Interact,
27
+ "container.close": Permission.InventoryManage,
28
+ "container.deposit": Permission.InventoryManage,
29
+ "container.items": Permission.InventoryManage,
30
+ "container.open": Permission.InventoryManage,
31
+ "container.withdraw": Permission.InventoryManage,
32
+ "entities.nearby": Permission.EntitiesRead,
33
+ "entities.players": Permission.EntitiesRead,
34
+ "inventory.drop": Permission.InventoryManage,
35
+ "inventory.equip": Permission.InventoryManage,
36
+ "inventory.held": Permission.InventoryRead,
37
+ "inventory.items": Permission.InventoryRead,
38
+ "plugins.start": Permission.ProfilePlugins,
39
+ "plugins.stop": Permission.ProfilePlugins,
40
+ "storage.delete": null,
41
+ "storage.entries": null,
42
+ "storage.get": null,
43
+ "storage.set": null,
44
+ "world.block": Permission.WorldRead,
45
+ "world.findBlocks": Permission.WorldRead,
46
+ };
47
+
48
+ /** Operations on any bot of the profile, not only those the plugin runs on. */
49
+ export const PROFILE_WIDE_OPERATIONS: ReadonlySet<string> = new Set([
50
+ "bot.connect",
51
+ "bot.disconnect",
52
+ "bot.reconnect",
53
+ "plugins.start",
54
+ "plugins.stop",
55
+ "storage.delete",
56
+ "storage.entries",
57
+ "storage.get",
58
+ "storage.set",
59
+ ]);
60
+
61
+ /** The permission a subscription needs (null: always allowed). */
62
+ export const EVENT_PERMISSIONS: Readonly<Record<BotEvent, Permission | null>> = {
63
+ [BotEvent.Chat]: Permission.ChatRead,
64
+ [BotEvent.PlayerJoined]: Permission.EntitiesRead,
65
+ [BotEvent.PlayerLeft]: Permission.EntitiesRead,
66
+ [BotEvent.Died]: null,
67
+ [BotEvent.Respawned]: null,
68
+ [BotEvent.HealthChanged]: null,
69
+ };
@@ -0,0 +1,19 @@
1
+ // Generated from Minecraft 26.3 and the MineBot plugin protocol. Do not edit.
2
+
3
+ import { Permission } from "./contracts.js";
4
+
5
+ /** What the install dialog shows for each permission. Used by `minebot check`; not part of the runtime. */
6
+ export const PERMISSION_LABELS: Readonly<Record<Permission, string>> = {
7
+ [Permission.WorldRead]: "Can see the world around the bot",
8
+ [Permission.EntitiesRead]: "Can see nearby players and mobs",
9
+ [Permission.Move]: "Can move the bot",
10
+ [Permission.Interact]: "Can break, place and use blocks",
11
+ [Permission.Attack]: "Can attack players and mobs",
12
+ [Permission.InventoryRead]: "Can see the bot's inventory",
13
+ [Permission.InventoryManage]: "Can move, drop, equip and craft items, and use chests",
14
+ [Permission.ChatRead]: "Can read chat",
15
+ [Permission.ChatSend]: "Can send chat messages",
16
+ [Permission.Commands]: "Can run server commands (e.g. /pay, /tpa)",
17
+ [Permission.ProfileBots]: "Can control every bot in this profile",
18
+ [Permission.ProfilePlugins]: "Can start and stop other plugins",
19
+ };
@@ -0,0 +1,3 @@
1
+ // Generated from Minecraft 26.3 and the MineBot plugin protocol. Do not edit.
2
+ /** The Minecraft version the generated enums come from. */
3
+ export const GAME_VERSION = "26.3";
@@ -0,0 +1,9 @@
1
+ // @minecraftbot-com/plugin/host: what runs a plugin (the minebot CLI, the hosted runner). Plugin code doesn't need it.
2
+
3
+ export { PluginRuntime, buildManifest, SDK_VERSION } from "../runtime/runtime.js";
4
+ export type { LogLevel, RuntimeOptions } from "../runtime/runtime.js";
5
+ export { Connection } from "../runtime/connection.js";
6
+ export type { CallOutcome, Transport } from "../runtime/connection.js";
7
+ export { memoryTransportPair } from "../runtime/memory-transport.js";
8
+ export { PROTOCOL_VERSION } from "../protocol.js";
9
+ export type * from "../protocol.js";
@@ -0,0 +1,224 @@
1
+ // fetch() for hosted plugins: the standard API on top of the runner's __host_fetch. The runner checks and makes
2
+ // every request (allowed hosts and URL settings, HTTPS, public addresses, sizes, rates) and logs it in the plugin
3
+ // console; this side only shapes the request and gives back a Response. QuickJS has no fetch, Headers or
4
+ // Response of its own, so minimal ones are defined here.
5
+ import { PluginError } from "../errors.js";
6
+
7
+ declare function __host_fetch(id: number, request: string): void;
8
+
9
+ interface WireResponse {
10
+ status: number;
11
+ statusText: string;
12
+ url: string;
13
+ redirected: boolean;
14
+ headers: [string, string][];
15
+ body: string;
16
+ bodyBase64: boolean;
17
+ }
18
+
19
+ type Outcome = { ok: true; response: WireResponse } | { ok: false; code: string; message: string };
20
+
21
+ type HeadersInit = Record<string, string> | [string, string][] | HostedHeaders;
22
+
23
+ /** Case-insensitive header names, as in browsers and Node. */
24
+ export class HostedHeaders {
25
+ private readonly map = new Map<string, string[]>();
26
+
27
+ constructor(init?: HeadersInit) {
28
+ if (!init) return;
29
+ if (init instanceof HostedHeaders) init.forEach((value, name) => this.append(name, value));
30
+ else if (Array.isArray(init)) for (const [name, value] of init) this.append(name, value);
31
+ else for (const name of Object.keys(init)) this.append(name, init[name]);
32
+ }
33
+
34
+ append(name: string, value: string): void {
35
+ const key = String(name).toLowerCase();
36
+ const list = this.map.get(key);
37
+ if (list) list.push(String(value));
38
+ else this.map.set(key, [String(value)]);
39
+ }
40
+ set(name: string, value: string): void {
41
+ this.map.set(String(name).toLowerCase(), [String(value)]);
42
+ }
43
+ get(name: string): string | null {
44
+ return this.map.get(String(name).toLowerCase())?.join(", ") ?? null;
45
+ }
46
+ has(name: string): boolean {
47
+ return this.map.has(String(name).toLowerCase());
48
+ }
49
+ delete(name: string): void {
50
+ this.map.delete(String(name).toLowerCase());
51
+ }
52
+ forEach(callback: (value: string, name: string) => void): void {
53
+ for (const [name, values] of this.map) callback(values.join(", "), name);
54
+ }
55
+ *entries(): IterableIterator<[string, string]> {
56
+ for (const [name, values] of this.map) yield [name, values.join(", ")];
57
+ }
58
+ keys(): IterableIterator<string> {
59
+ return this.map.keys();
60
+ }
61
+ *values(): IterableIterator<string> {
62
+ for (const values of this.map.values()) yield values.join(", ");
63
+ }
64
+ [Symbol.iterator](): IterableIterator<[string, string]> {
65
+ return this.entries();
66
+ }
67
+ }
68
+
69
+ /** The parts of a Response plugins use: status, headers and the body as text, JSON or bytes (once). */
70
+ export class HostedResponse {
71
+ readonly status: number;
72
+ readonly statusText: string;
73
+ readonly ok: boolean;
74
+ readonly url: string;
75
+ readonly redirected: boolean;
76
+ readonly headers: HostedHeaders;
77
+ readonly type = "basic";
78
+ private used = false;
79
+
80
+ constructor(private readonly wire: WireResponse) {
81
+ this.status = wire.status;
82
+ this.statusText = wire.statusText;
83
+ this.ok = wire.status >= 200 && wire.status < 300;
84
+ this.url = wire.url;
85
+ this.redirected = wire.redirected;
86
+ this.headers = new HostedHeaders(wire.headers);
87
+ }
88
+
89
+ get bodyUsed(): boolean {
90
+ return this.used;
91
+ }
92
+
93
+ private take(): WireResponse {
94
+ if (this.used) throw new TypeError("The response body was already read");
95
+ this.used = true;
96
+ return this.wire;
97
+ }
98
+
99
+ async text(): Promise<string> {
100
+ const w = this.take();
101
+ return w.bodyBase64 ? utf8Decode(base64Decode(w.body)) : w.body;
102
+ }
103
+ async json(): Promise<unknown> {
104
+ return JSON.parse(await this.text());
105
+ }
106
+ async bytes(): Promise<Uint8Array> {
107
+ const w = this.take();
108
+ return w.bodyBase64 ? base64Decode(w.body) : utf8Encode(w.body);
109
+ }
110
+ async arrayBuffer(): Promise<ArrayBuffer> {
111
+ const b = await this.bytes();
112
+ return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer;
113
+ }
114
+ clone(): HostedResponse {
115
+ if (this.used) throw new TypeError("The response body was already read");
116
+ return new HostedResponse(this.wire);
117
+ }
118
+ }
119
+
120
+ interface FetchInit {
121
+ method?: string;
122
+ headers?: HeadersInit;
123
+ body?: string | Uint8Array | ArrayBuffer | null;
124
+ }
125
+
126
+ /** Installs fetch, Headers and Response; returns what the runner calls with each outcome. */
127
+ export function installFetch(g: Record<string, unknown>): (id: number, outcome: string) => void {
128
+ const pending = new Map<number, { resolve(r: HostedResponse): void; reject(e: Error): void }>();
129
+ let next = 1;
130
+
131
+ g.Headers ??= HostedHeaders;
132
+ g.Response ??= HostedResponse;
133
+ g.fetch = (input: string | { href?: string; url?: string; method?: string; headers?: HeadersInit }, init: FetchInit = {}): Promise<HostedResponse> => {
134
+ const url = typeof input === "string" ? input : (input?.href ?? input?.url ?? String(input));
135
+ const method = (init.method ?? (typeof input === "object" ? input?.method : undefined) ?? "GET").toUpperCase();
136
+ const headers: [string, string][] = [...new HostedHeaders(init.headers ?? (typeof input === "object" ? input?.headers : undefined))];
137
+ let body: string | null = null;
138
+ let bodyBase64 = false;
139
+ if (init.body !== undefined && init.body !== null) {
140
+ if (typeof init.body === "string") body = init.body;
141
+ else if (init.body instanceof Uint8Array) [body, bodyBase64] = [base64Encode(init.body), true];
142
+ else if (init.body instanceof ArrayBuffer) [body, bodyBase64] = [base64Encode(new Uint8Array(init.body)), true];
143
+ else return Promise.reject(new TypeError("fetch: the body must be a string (e.g. JSON.stringify(...)) or bytes"));
144
+ }
145
+ const id = next++;
146
+ return new Promise((resolve, reject) => {
147
+ pending.set(id, { resolve, reject });
148
+ __host_fetch(id, JSON.stringify({ url, method, headers, body, bodyBase64 }));
149
+ });
150
+ };
151
+
152
+ return (id, text) => {
153
+ const p = pending.get(id);
154
+ if (!p) return;
155
+ pending.delete(id);
156
+ const outcome = JSON.parse(text) as Outcome;
157
+ if (outcome.ok) p.resolve(new HostedResponse(outcome.response));
158
+ else if (outcome.code === "NetworkDenied") p.reject(new PluginError("NetworkDenied", outcome.message));
159
+ else p.reject(new TypeError(outcome.message));
160
+ };
161
+ }
162
+
163
+ // ---- bytes, without TextEncoder or atob (QuickJS has neither) ----
164
+
165
+ const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
166
+
167
+ export function base64Encode(bytes: Uint8Array): string {
168
+ let out = "";
169
+ for (let i = 0; i < bytes.length; i += 3) {
170
+ const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
171
+ out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (i + 1 < bytes.length ? B64[(n >> 6) & 63] : "=") + (i + 2 < bytes.length ? B64[n & 63] : "=");
172
+ }
173
+ return out;
174
+ }
175
+
176
+ export function base64Decode(text: string): Uint8Array {
177
+ const clean = text.replace(/[^A-Za-z0-9+/]/g, "");
178
+ const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
179
+ let o = 0;
180
+ for (let i = 0; i < clean.length; i += 4) {
181
+ const n = (B64.indexOf(clean[i]) << 18) | (B64.indexOf(clean[i + 1]) << 12) | ((B64.indexOf(clean[i + 2] ?? "A") & 63) << 6) | (B64.indexOf(clean[i + 3] ?? "A") & 63);
182
+ out[o++] = (n >> 16) & 255;
183
+ if (i + 2 < clean.length) out[o++] = (n >> 8) & 255;
184
+ if (i + 3 < clean.length) out[o++] = n & 255;
185
+ }
186
+ return out.subarray(0, o);
187
+ }
188
+
189
+ export function utf8Encode(text: string): Uint8Array {
190
+ const out: number[] = [];
191
+ for (const ch of text) {
192
+ const c = ch.codePointAt(0)!;
193
+ if (c < 0x80) out.push(c);
194
+ else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));
195
+ else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
196
+ else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
197
+ }
198
+ return new Uint8Array(out);
199
+ }
200
+
201
+ /** UTF-8 to text; malformed sequences become U+FFFD. */
202
+ export function utf8Decode(bytes: Uint8Array): string {
203
+ let out = "";
204
+ let i = 0;
205
+ while (i < bytes.length) {
206
+ const b = bytes[i];
207
+ const need = b < 0x80 ? 0 : (b & 0xe0) === 0xc0 ? 1 : (b & 0xf0) === 0xe0 ? 2 : (b & 0xf8) === 0xf0 ? 3 : -1;
208
+ let c = need <= 0 ? b : b & (0xff >> (need + 2));
209
+ let ok = need >= 0 && i + need < bytes.length;
210
+ for (let k = 1; ok && k <= need; k++) {
211
+ const n = bytes[i + k];
212
+ if ((n & 0xc0) !== 0x80) ok = false;
213
+ else c = (c << 6) | (n & 63);
214
+ }
215
+ if (!ok || c > 0x10ffff) {
216
+ out += "\uFFFD";
217
+ i++;
218
+ continue;
219
+ }
220
+ out += String.fromCodePoint(c);
221
+ i += need + 1;
222
+ }
223
+ return out;
224
+ }
@@ -0,0 +1,121 @@
1
+ // @minecraftbot-com/plugin/hosted: what runs a plugin inside MineBot's runner (QuickJS in WebAssembly). `minebot
2
+ // build` and `minebot deploy` wrap the plugin with it; plugin code never imports it.
3
+ //
4
+ // The runner gives the instance its host functions (frames out, closing, its own log, timers, fetch) and drives it through
5
+ // `__minebot`: the bundle's protocol frames are exactly what `minebot dev` sends over its websocket, and the runner
6
+ // carries them to the bot container unchanged.
7
+ import type { DefinedPlugin } from "../plugin.js";
8
+ import type { Transport } from "../runtime/connection.js";
9
+ import { PluginRuntime } from "../runtime/runtime.js";
10
+ import { installFetch } from "./fetch.js";
11
+
12
+ declare function __host_send(text: string): void;
13
+ declare function __host_close(code: number, reason: string): void;
14
+ /** The runner's own log (0 info, 1 warn, 2 error), for what can't reach the plugin console. */
15
+ declare function __host_log(level: number, message: string): void;
16
+ declare function __host_timer_set(id: number, ms: number): void;
17
+ declare function __host_timer_clear(id: number): void;
18
+
19
+ /** What the runner passes to `__minebot.start`. */
20
+ interface HostedConfig {
21
+ token: string;
22
+ /** The deployed version (package.json), sent in the manifest. */
23
+ version: string;
24
+ }
25
+
26
+ /** What the runner calls; one call is one turn, which runs until the plugin awaits again. */
27
+ interface HostedEntry {
28
+ start(config: string): void;
29
+ receive(frame: string): void;
30
+ timer(id: number): void;
31
+ closed(code: number, reason: string): void;
32
+ /** The outcome of fetch call `id` (JSON). */
33
+ fetchDone(id: number, outcome: string): void;
34
+ }
35
+
36
+ type Timer = () => void;
37
+
38
+ function describe(error: unknown): string {
39
+ return error instanceof Error ? (error.stack ?? error.message) : String(error);
40
+ }
41
+
42
+ /** Installs the hosted environment and waits for the runner to start the plugin. */
43
+ export function serveHosted(plugin: DefinedPlugin): void {
44
+ const g = globalThis as Record<string, unknown>;
45
+
46
+ const timers = new Map<number, Timer>();
47
+ let nextTimer = 1;
48
+ g.setTimeout = (fn: Timer, ms?: number): number => {
49
+ const id = nextTimer++;
50
+ timers.set(id, fn);
51
+ __host_timer_set(id, Math.max(0, Math.floor(Number(ms) || 0)));
52
+ return id;
53
+ };
54
+ g.clearTimeout = (id: number): void => {
55
+ if (timers.delete(id)) __host_timer_clear(id);
56
+ };
57
+
58
+ const fetchDone = installFetch(g);
59
+
60
+ const transport: Transport = {
61
+ send: text => __host_send(text),
62
+ close: (code, reason) => __host_close(code ?? 1000, reason ?? ""),
63
+ onmessage: null,
64
+ onclose: null,
65
+ };
66
+
67
+ // console.* goes to the plugin console once connected (before that, to the runner's log), as it would show
68
+ // in the terminal under `minebot dev`.
69
+ let connected = false;
70
+ const write = (level: "debug" | "info" | "warn" | "error", args: unknown[]) => {
71
+ const message = args.map(a => (typeof a === "string" ? a : a instanceof Error ? describe(a) : safeJson(a))).join(" ");
72
+ const trimmed = message.length > 4000 ? `${message.slice(0, 4000)}…` : message;
73
+ if (connected) __host_send(JSON.stringify({ type: "log", bot: null, level, message: trimmed }));
74
+ else __host_log(level === "error" ? 2 : level === "warn" ? 1 : 0, trimmed);
75
+ };
76
+ g.console = {
77
+ log: (...a: unknown[]) => write("info", a),
78
+ info: (...a: unknown[]) => write("info", a),
79
+ debug: (...a: unknown[]) => write("debug", a),
80
+ warn: (...a: unknown[]) => write("warn", a),
81
+ error: (...a: unknown[]) => write("error", a),
82
+ };
83
+
84
+ const entry: HostedEntry = {
85
+ start(text) {
86
+ const config = JSON.parse(text) as HostedConfig;
87
+ PluginRuntime.connect(plugin, transport, config.token, config.version).then(
88
+ () => (connected = true),
89
+ error => {
90
+ __host_log(2, `Couldn't start: ${describe(error)}`);
91
+ transport.close(1000, "Rejected");
92
+ },
93
+ );
94
+ },
95
+ receive(frame) {
96
+ transport.onmessage?.(frame);
97
+ },
98
+ timer(id) {
99
+ const fn = timers.get(id);
100
+ if (!fn) return;
101
+ timers.delete(id);
102
+ fn();
103
+ },
104
+ closed(code, reason) {
105
+ connected = false;
106
+ transport.onclose?.(code, reason);
107
+ },
108
+ fetchDone(id, outcome) {
109
+ fetchDone(id, outcome);
110
+ },
111
+ };
112
+ g.__minebot = entry;
113
+ }
114
+
115
+ function safeJson(value: unknown): string {
116
+ try {
117
+ return JSON.stringify(value) ?? String(value);
118
+ } catch {
119
+ return String(value);
120
+ }
121
+ }
package/src/index.ts ADDED
@@ -0,0 +1,34 @@
1
+ // @minecraftbot-com/plugin: write MineBot plugins in TypeScript. Start with `definePlugin`; see AGENTS.md for a tour.
2
+
3
+ export { definePlugin, isDefinedPlugin } from "./plugin.js";
4
+ export type { DefinedPlugin, Logger, PluginDefinition, ProfileRunContext, RunContext, Stats, Warnings } from "./plugin.js";
5
+
6
+ export { Setting } from "./settings.js";
7
+ export type { SettingDefinition, SettingValues } from "./settings.js";
8
+
9
+ export { Storage } from "./storage.js";
10
+ export type { BotStorage, PerBot, ProfileStorage, StorageDefinition, StoredMap, StoredValue } from "./storage.js";
11
+
12
+ export type {
13
+ Bot, BlockInfo, BlockStateFilter, BotEventData, BotPlugins, BotStatus, ChatMessage, Container, Containers, Entities,
14
+ EntityInfo, Inventory, ItemStack, Listener, PlayerInfo, Profile, ProfileBot, ProfileEventData, Recipe, World,
15
+ } from "./api.js";
16
+
17
+ export { Position, vec3, toMilliseconds } from "./types.js";
18
+ export type { Duration, JsonValue, Result, Vec3 } from "./types.js";
19
+
20
+ export { PluginError, PermissionDeniedError, StoppedError, isStopped } from "./errors.js";
21
+ export { network } from "./permissions.js";
22
+ export type { NetworkPermission } from "./permissions.js";
23
+
24
+ export { Block } from "./generated/blocks.js";
25
+ export { Item } from "./generated/items.js";
26
+ export { Entity } from "./generated/entities.js";
27
+ export { Effect } from "./generated/effects.js";
28
+ export type { BlockStates } from "./generated/block-states.js";
29
+ export { GAME_VERSION } from "./generated/version.js";
30
+ export {
31
+ AttackFailure, BotControlFailure, BotEvent, BuiltInPlugin, ContainerFailure, ControlUnit, CraftFailure, DigFailure,
32
+ EquipmentSlot, ErrorCode, GameMode, InteractFailure, InventoryFailure, MoveFailure, Permission, PlaceFailure,
33
+ PluginControlFailure, PluginMode, ProfileEvent, RejectReason, StopReason, StorageScope,
34
+ } from "./generated/contracts.js";
@@ -0,0 +1,23 @@
1
+ /** A permission to `fetch` one host: build it with `network("api.example.com")`. */
2
+ export type NetworkPermission = `network:${string}`;
3
+
4
+ const HOST = /^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}(:\d{1,5})?$/;
5
+
6
+ /**
7
+ * Lets the plugin `fetch` a host over HTTPS. `"*.example.com"` covers every subdomain (shown to the user as
8
+ * such); a bare `*` is never allowed. Add a port when it isn't 443: `"example.com:8443"`.
9
+ *
10
+ * @example permissions: [Permission.ChatRead, network("api.example.com")]
11
+ */
12
+ export function network(host: string): NetworkPermission {
13
+ const h = host.trim().toLowerCase();
14
+ if (!HOST.test(h)) {
15
+ throw new TypeError(`network("${host}"): expected a host name such as "api.example.com" or "*.example.com", without https:// or a path`);
16
+ }
17
+ return `network:${h}`;
18
+ }
19
+
20
+ /** The host part of a network permission, or null for any other permission. */
21
+ export function networkHost(permission: string): string | null {
22
+ return permission.startsWith("network:") ? permission.slice("network:".length) : null;
23
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,105 @@
1
+ import type { ControlUnit, Permission } from "./generated/contracts.js";
2
+ import type { SettingDefinition, SettingValues } from "./settings.js";
3
+ import type { BotStorage, ProfileStorage, StorageDefinition } from "./storage.js";
4
+ import type { Bot, Profile } from "./api.js";
5
+ import type { NetworkPermission } from "./permissions.js";
6
+
7
+ /** Writes to the plugin console on the dashboard (and your terminal under `minebot dev`). */
8
+ export interface Logger {
9
+ debug(message: string): void;
10
+ info(message: string): void;
11
+ warn(message: string): void;
12
+ error(message: string | Error): void;
13
+ }
14
+
15
+ /** Numbers shown on the plugin's card on the dashboard. */
16
+ export interface Stats {
17
+ /** Sets a statistic, e.g. `stats.set("Crops harvested", 41)`. */
18
+ set(name: string, value: number): void;
19
+ /** Adds to a statistic (starting from 0). */
20
+ add(name: string, amount?: number): void;
21
+ }
22
+
23
+ /** Problems shown on the plugin's card until cleared, e.g. "No hoe in the inventory". */
24
+ export interface Warnings {
25
+ set(key: string, message: string): void;
26
+ clear(key: string): void;
27
+ }
28
+
29
+ export interface RunContext<S, T> {
30
+ /** The values the user set for this bot. */
31
+ readonly settings: SettingValues<S>;
32
+ /** Stored data; bot-scoped entries are bound to this bot. */
33
+ readonly storage: BotStorage<T>;
34
+ readonly log: Logger;
35
+ readonly stats: Stats;
36
+ readonly warnings: Warnings;
37
+ }
38
+
39
+ export interface ProfileRunContext<S, T> {
40
+ /** The values the user set for the plugin on this profile. */
41
+ readonly settings: SettingValues<S>;
42
+ /** Stored data; bot-scoped entries need `.for(bot)`. */
43
+ readonly storage: ProfileStorage<T>;
44
+ readonly log: Logger;
45
+ readonly stats: Stats;
46
+ readonly warnings: Warnings;
47
+ }
48
+
49
+ type AnySettings = Record<string, SettingDefinition<unknown>>;
50
+ type AnyStorage = Record<string, StorageDefinition<any, "value" | "map", any>>;
51
+
52
+ export interface PluginDefinition<S extends AnySettings = {}, T extends AnyStorage = {}> {
53
+ /** Shown on the dashboard. */
54
+ name: string;
55
+ /** What your plugin is allowed to do. Calls outside this list fail with a message naming the permission. */
56
+ permissions: readonly (Permission | NetworkPermission)[];
57
+ /**
58
+ * Parts of the bot only this plugin may drive while it runs. Other plugins (and macros) that need them
59
+ * wait. Declare `ControlUnit.Movement` if you walk, `ControlUnit.Look` if you aim, `ControlUnit.Hand` if
60
+ * you dig, place or attack.
61
+ */
62
+ exclusive?: readonly ControlUnit[];
63
+ /** What the user can configure per bot. */
64
+ settings?: S;
65
+ /** Data kept between runs. */
66
+ storage?: T;
67
+ /** Runs once per bot the plugin is enabled on. Return (or throw) to finish; stopping the bot ends it. */
68
+ run?(bot: Bot, context: RunContext<S, T>): Promise<void>;
69
+ /** Runs once per profile while the plugin is installed and the profile runs. */
70
+ runProfile?(profile: Profile, context: ProfileRunContext<S, T>): Promise<void>;
71
+ }
72
+
73
+ /** What `definePlugin` returns: the definition, marked for the CLI and the runtime. */
74
+ export interface DefinedPlugin<S extends AnySettings = AnySettings, T extends AnyStorage = AnyStorage> {
75
+ readonly __minebotPlugin: 1;
76
+ readonly definition: PluginDefinition<S, T>;
77
+ }
78
+
79
+ /**
80
+ * Declares a plugin. Export the result as your module's default export.
81
+ *
82
+ * @example
83
+ * export default definePlugin({
84
+ * name: "Greeter",
85
+ * permissions: [Permission.ChatRead, Permission.ChatSend],
86
+ * async run(bot) {
87
+ * bot.on(BotEvent.PlayerJoined, async ({ player }) => {
88
+ * await bot.say(`Welcome, ${player.name}!`);
89
+ * });
90
+ * },
91
+ * });
92
+ */
93
+ export function definePlugin<const S extends AnySettings = {}, const T extends AnyStorage = {}>(definition: PluginDefinition<S, T>): DefinedPlugin<S, T> {
94
+ if (!definition || typeof definition.name !== "string" || definition.name.trim() === "") {
95
+ throw new TypeError("definePlugin needs a name, e.g. definePlugin({ name: \"Harvester\", ... })");
96
+ }
97
+ if (!definition.run && !definition.runProfile) {
98
+ throw new TypeError(`Plugin "${definition.name}" needs run(bot) or runProfile(profile)`);
99
+ }
100
+ return { __minebotPlugin: 1, definition };
101
+ }
102
+
103
+ export function isDefinedPlugin(value: unknown): value is DefinedPlugin {
104
+ return typeof value === "object" && value !== null && (value as DefinedPlugin).__minebotPlugin === 1;
105
+ }