@minecraftbot-com/plugin 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +188 -177
- package/README.md +47 -46
- package/dist/api.d.ts +4 -1
- package/dist/cli/api.d.ts +23 -0
- package/dist/cli/api.js +8 -0
- package/dist/cli/build.d.ts +1 -0
- package/dist/cli/build.js +9 -2
- package/dist/cli/check.d.ts +7 -0
- package/dist/cli/check.js +2 -1
- package/dist/cli/deploy.d.ts +13 -0
- package/dist/cli/deploy.js +51 -0
- package/dist/cli/main.js +7 -0
- package/dist/hosted/fetch.d.ts +53 -0
- package/dist/hosted/fetch.js +216 -0
- package/dist/hosted/index.d.ts +3 -0
- package/dist/hosted/index.js +81 -0
- package/dist/runtime/runtime.d.ts +1 -1
- package/dist/runtime/runtime.js +1 -1
- package/package.json +6 -1
- package/src/api.ts +4 -1
- package/src/cli/api.ts +105 -79
- package/src/cli/build.ts +9 -2
- package/src/cli/check.ts +104 -103
- package/src/cli/deploy.ts +60 -0
- package/src/cli/main.ts +7 -0
- package/src/hosted/fetch.ts +224 -0
- package/src/hosted/index.ts +121 -0
- package/src/runtime/runtime.ts +281 -281
- package/templates/basic/AGENTS.md +32 -31
- package/templates/basic/README.md +14 -13
- package/templates/basic/package.json +1 -0
package/src/runtime/runtime.ts
CHANGED
|
@@ -1,281 +1,281 @@
|
|
|
1
|
-
import { isStopped, PluginError } from "../errors.js";
|
|
2
|
-
import type { Logger, Stats, Warnings, DefinedPlugin } from "../plugin.js";
|
|
3
|
-
import type { BotInfo, DevOptions, Manifest, SettingSchema, WelcomeFrame } from "../protocol.js";
|
|
4
|
-
import { toPosition } from "../types.js";
|
|
5
|
-
import type { ProfileBot } from "../api.js";
|
|
6
|
-
import { Connection, type CallOutcome, type Transport } from "./connection.js";
|
|
7
|
-
import { BotHandle, ProfileBotHandle, ProfileHandle, type HandleHost } from "./handles.js";
|
|
8
|
-
import { Scope } from "./scope.js";
|
|
9
|
-
import { createStorage } from "./storage-runtime.js";
|
|
10
|
-
|
|
11
|
-
export const SDK_VERSION = "0.
|
|
12
|
-
|
|
13
|
-
export type LogLevel = "debug" | "info" | "warn" | "error";
|
|
14
|
-
|
|
15
|
-
export interface RuntimeOptions {
|
|
16
|
-
/** Called for every log line, warning and statistic, e.g. to print them under `minebot dev`. */
|
|
17
|
-
onLog?(level: LogLevel, message: string, bot: BotInfo | null): void;
|
|
18
|
-
/** Called once the connection ends. */
|
|
19
|
-
onClosed?(code: number, reason: string): void;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** Builds the manifest the container checks, from the plugin's definition. */
|
|
23
|
-
export function buildManifest(plugin: DefinedPlugin, version: string): Manifest {
|
|
24
|
-
const d = plugin.definition;
|
|
25
|
-
const settings: Record<string, SettingSchema> = {};
|
|
26
|
-
for (const [key, setting] of Object.entries(d.settings ?? {})) settings[key] = setting.schema;
|
|
27
|
-
const storage: Manifest["storage"] = {};
|
|
28
|
-
for (const [key, entry] of Object.entries(d.storage ?? {})) storage[key] = entry.schema;
|
|
29
|
-
return {
|
|
30
|
-
name: d.name,
|
|
31
|
-
version,
|
|
32
|
-
permissions: [...new Set(d.permissions as readonly string[])],
|
|
33
|
-
exclusive: [...new Set((d.exclusive ?? []) as readonly string[])],
|
|
34
|
-
settings,
|
|
35
|
-
storage,
|
|
36
|
-
profile: typeof d.runProfile === "function",
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function applyDefaults(manifest: Manifest, values: Record<string, unknown>): Record<string, unknown> {
|
|
41
|
-
const out: Record<string, unknown> = {};
|
|
42
|
-
for (const [key, schema] of Object.entries(manifest.settings)) {
|
|
43
|
-
const v = values[key];
|
|
44
|
-
out[key] = v === undefined || v === null ? schema.default : v;
|
|
45
|
-
if (schema.type === "position" && out[key]) out[key] = toPosition(out[key]);
|
|
46
|
-
}
|
|
47
|
-
return Object.freeze(out);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function describe(error: unknown): string {
|
|
51
|
-
if (error instanceof Error) return error.stack && !(error instanceof PluginError) ? error.stack : error.message;
|
|
52
|
-
return String(error);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Runs one plugin instance over a connection: starts `runProfile` and `run(bot)` when the container says so,
|
|
57
|
-
* stops them when it says so, and routes events to listeners.
|
|
58
|
-
*/
|
|
59
|
-
export class PluginRuntime implements HandleHost {
|
|
60
|
-
private readonly root = new Scope();
|
|
61
|
-
private readonly botScopes = new Map<string, Scope>();
|
|
62
|
-
private profileScope: Scope | null = null;
|
|
63
|
-
private readonly bots = new Map<string, BotInfo>();
|
|
64
|
-
private readonly listeners = new Map<string, Set<(data: unknown) => unknown>>();
|
|
65
|
-
private readonly profileBots = new Map<string, ProfileBotHandle>();
|
|
66
|
-
private readonly stats = new Map<string, number>();
|
|
67
|
-
|
|
68
|
-
constructor(
|
|
69
|
-
private readonly plugin: DefinedPlugin,
|
|
70
|
-
private readonly manifest: Manifest,
|
|
71
|
-
private readonly connection: Connection,
|
|
72
|
-
readonly welcome: WelcomeFrame,
|
|
73
|
-
private readonly options: RuntimeOptions = {},
|
|
74
|
-
) {
|
|
75
|
-
for (const bot of welcome.bots) this.bots.set(bot.id, bot);
|
|
76
|
-
connection.attach({
|
|
77
|
-
start: (bot, settings, version) => this.start(bot, settings, version),
|
|
78
|
-
stop: (bot, reason) => this.stop(bot, reason),
|
|
79
|
-
event: (bot, event, data) => this.dispatch(bot, event, data),
|
|
80
|
-
bots: frame => {
|
|
81
|
-
this.bots.clear();
|
|
82
|
-
for (const bot of frame.bots) this.bots.set(bot.id, bot);
|
|
83
|
-
},
|
|
84
|
-
dropped: count => this.emitLog("warn", `${count} events were dropped because the plugin didn't keep up`, null),
|
|
85
|
-
closed: (code, reason) => {
|
|
86
|
-
this.root.stop("Disconnected");
|
|
87
|
-
this.options.onClosed?.(code, reason);
|
|
88
|
-
},
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** Connects, sends hello and starts running once welcomed. Rejects if the container refuses. */
|
|
93
|
-
static async connect(plugin: DefinedPlugin, transport: Transport, token: string, version: string, options: RuntimeOptions = {}, dev?: DevOptions): Promise<PluginRuntime> {
|
|
94
|
-
const manifest = buildManifest(plugin, version);
|
|
95
|
-
const connection = new Connection(transport);
|
|
96
|
-
const welcome = await connection.open(token, manifest, SDK_VERSION, dev);
|
|
97
|
-
return new PluginRuntime(plugin, manifest, connection, welcome, options);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** The profile's bots as the container last reported them. */
|
|
101
|
-
get currentBots(): BotInfo[] {
|
|
102
|
-
return [...this.bots.values()];
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/** The bots `run(bot)` is currently running on. */
|
|
106
|
-
get runningBots(): string[] {
|
|
107
|
-
return [...this.botScopes.keys()];
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/** Stops everything and closes the connection. */
|
|
111
|
-
close(): void {
|
|
112
|
-
this.root.stop("Disconnected");
|
|
113
|
-
this.connection.close();
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// ---- HandleHost ----
|
|
117
|
-
|
|
118
|
-
call(scope: Scope, bot: string | null, op: string, args: Record<string, unknown> = {}): Promise<CallOutcome> {
|
|
119
|
-
return this.connection.call(scope, bot, op, args);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
subscribe(scope: Scope, bot: string | null, event: string, listener: (data: unknown) => unknown): () => void {
|
|
123
|
-
scope.check();
|
|
124
|
-
const key = `${bot ?? ""}|${event}`;
|
|
125
|
-
let set = this.listeners.get(key);
|
|
126
|
-
if (!set) {
|
|
127
|
-
set = new Set();
|
|
128
|
-
this.listeners.set(key, set);
|
|
129
|
-
this.connection.send({ type: "subscribe", bot, event });
|
|
130
|
-
}
|
|
131
|
-
set.add(listener);
|
|
132
|
-
return scope.onStop(() => {
|
|
133
|
-
const current = this.listeners.get(key);
|
|
134
|
-
if (!current) return;
|
|
135
|
-
current.delete(listener);
|
|
136
|
-
if (current.size === 0) {
|
|
137
|
-
this.listeners.delete(key);
|
|
138
|
-
if (!this.root.stopped) this.connection.send({ type: "unsubscribe", bot, event });
|
|
139
|
-
}
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
botInfo(id: string): BotInfo | undefined {
|
|
144
|
-
return this.bots.get(id);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
profileBot(id: string): ProfileBot {
|
|
148
|
-
let handle = this.profileBots.get(id);
|
|
149
|
-
if (!handle) {
|
|
150
|
-
handle = new ProfileBotHandle(this.profileScope ?? this.root, this, id);
|
|
151
|
-
this.profileBots.set(id, handle);
|
|
152
|
-
}
|
|
153
|
-
return handle;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
logError(bot: string | null, error: unknown): void {
|
|
157
|
-
this.emitLog("error", describe(error), bot);
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
// ---- lifecycle ----
|
|
161
|
-
|
|
162
|
-
private start(bot: string | null, settingsFrame: Record<string, unknown>, version: string): void {
|
|
163
|
-
const settings = applyDefaults(this.manifest, settingsFrame);
|
|
164
|
-
const d = this.plugin.definition;
|
|
165
|
-
|
|
166
|
-
if (bot === null) {
|
|
167
|
-
if (!d.runProfile || this.profileScope) return;
|
|
168
|
-
const scope = this.root.child();
|
|
169
|
-
this.profileScope = scope;
|
|
170
|
-
this.profileBots.clear();
|
|
171
|
-
const profile = new ProfileHandle(scope, this, this.welcome.profile.id, this.welcome.profile.name, () => [...this.bots.values()]);
|
|
172
|
-
const context = this.context(scope, null, settings);
|
|
173
|
-
this.supervise(null, () => d.runProfile!(profile, context as any), scope);
|
|
174
|
-
return;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
if (!d.run) return;
|
|
178
|
-
this.botScopes.get(bot)?.stop("Replaced");
|
|
179
|
-
const scope = this.root.child();
|
|
180
|
-
this.botScopes.set(bot, scope);
|
|
181
|
-
const handle = new BotHandle(scope, this, bot, version);
|
|
182
|
-
const context = this.context(scope, bot, settings);
|
|
183
|
-
this.supervise(bot, () => d.run!(handle, context as any), scope);
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
private stop(bot: string | null, reason: string): void {
|
|
187
|
-
if (bot === null) {
|
|
188
|
-
this.profileScope?.stop(reason);
|
|
189
|
-
this.profileScope = null;
|
|
190
|
-
this.profileBots.clear();
|
|
191
|
-
return;
|
|
192
|
-
}
|
|
193
|
-
this.botScopes.get(bot)?.stop(reason);
|
|
194
|
-
this.botScopes.delete(bot);
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/** Runs `run`/`runProfile`. Returning keeps listeners alive until stopped; throwing ends the run and is reported. */
|
|
198
|
-
private supervise(bot: string | null, body: () => Promise<void>, scope: Scope): void {
|
|
199
|
-
Promise.resolve()
|
|
200
|
-
.then(body)
|
|
201
|
-
.catch(error => {
|
|
202
|
-
if (isStopped(error) || scope.stopped) return;
|
|
203
|
-
this.emitLog("error", describe(error), bot);
|
|
204
|
-
this.connection.send({ type: "done", bot, error: error instanceof Error ? error.message : String(error) });
|
|
205
|
-
scope.stop("Failed");
|
|
206
|
-
if (bot === null) this.profileScope = null;
|
|
207
|
-
else if (this.botScopes.get(bot) === scope) this.botScopes.delete(bot);
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
private context(scope: Scope, bot: string | null, settings: Record<string, unknown>) {
|
|
212
|
-
const log: Logger = {
|
|
213
|
-
debug: m => this.emitLog("debug", String(m), bot),
|
|
214
|
-
info: m => this.emitLog("info", String(m), bot),
|
|
215
|
-
warn: m => this.emitLog("warn", String(m), bot),
|
|
216
|
-
error: m => this.emitLog("error", m instanceof Error ? describe(m) : String(m), bot),
|
|
217
|
-
};
|
|
218
|
-
const statKey = (name: string) => `${bot ?? ""}|${name}`;
|
|
219
|
-
const stats: Stats = {
|
|
220
|
-
set: (name, value) => {
|
|
221
|
-
this.stats.set(statKey(name), value);
|
|
222
|
-
this.connection.send({ type: "stat", bot, key: name, value });
|
|
223
|
-
},
|
|
224
|
-
add: (name, amount = 1) => {
|
|
225
|
-
const value = (this.stats.get(statKey(name)) ?? 0) + amount;
|
|
226
|
-
this.stats.set(statKey(name), value);
|
|
227
|
-
this.connection.send({ type: "stat", bot, key: name, value });
|
|
228
|
-
},
|
|
229
|
-
};
|
|
230
|
-
const warnings: Warnings = {
|
|
231
|
-
set: (key, message) => this.connection.send({ type: "warning", bot, key, message }),
|
|
232
|
-
clear: key => this.connection.send({ type: "warning", bot, key, message: null }),
|
|
233
|
-
};
|
|
234
|
-
const botUuid = bot === null ? null : this.bots.get(bot)?.uuid ?? null;
|
|
235
|
-
const storage = createStorage(this.manifest.storage, (s, op, args) => this.connection.call(s, bot, op, args), scope, bot === null ? null : botUuid ?? bot);
|
|
236
|
-
return { settings, storage, log, stats, warnings };
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
private emitLog(level: LogLevel, message: string, bot: string | null): void {
|
|
240
|
-
const trimmed = message.length > 4000 ? `${message.slice(0, 4000)}…` : message;
|
|
241
|
-
this.connection.send({ type: "log", bot, level, message: trimmed });
|
|
242
|
-
this.options.onLog?.(level, trimmed, bot === null ? null : this.bots.get(bot) ?? null);
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// ---- events ----
|
|
246
|
-
|
|
247
|
-
private dispatch(bot: string | null, event: string, data: unknown): void {
|
|
248
|
-
if (event === "__error") {
|
|
249
|
-
const e = data as { code: string; message: string };
|
|
250
|
-
this.emitLog("error", `${e.code}: ${e.message}`, null);
|
|
251
|
-
return;
|
|
252
|
-
}
|
|
253
|
-
const set = this.listeners.get(`${bot ?? ""}|${event}`);
|
|
254
|
-
if (!set) return;
|
|
255
|
-
const payload = this.decorate(data);
|
|
256
|
-
for (const listener of [...set]) {
|
|
257
|
-
try {
|
|
258
|
-
const r = listener(payload);
|
|
259
|
-
if (r && typeof (r as Promise<unknown>).then === "function") {
|
|
260
|
-
(r as Promise<unknown>).catch(error => {
|
|
261
|
-
if (!isStopped(error)) this.emitLog("error", describe(error), bot);
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
} catch (error) {
|
|
265
|
-
if (!isStopped(error)) this.emitLog("error", describe(error), bot);
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/** Turns bot ids in event data into ProfileBot handles, and positions into Positions. */
|
|
271
|
-
private decorate(data: unknown): unknown {
|
|
272
|
-
if (!data || typeof data !== "object") return data;
|
|
273
|
-
const out: Record<string, unknown> = { ...(data as Record<string, unknown>) };
|
|
274
|
-
if (typeof out.botId === "string") {
|
|
275
|
-
out.bot = this.profileBot(out.botId);
|
|
276
|
-
delete out.botId;
|
|
277
|
-
}
|
|
278
|
-
if (out.position && typeof out.position === "object") out.position = toPosition(out.position);
|
|
279
|
-
return Object.freeze(out);
|
|
280
|
-
}
|
|
281
|
-
}
|
|
1
|
+
import { isStopped, PluginError } from "../errors.js";
|
|
2
|
+
import type { Logger, Stats, Warnings, DefinedPlugin } from "../plugin.js";
|
|
3
|
+
import type { BotInfo, DevOptions, Manifest, SettingSchema, WelcomeFrame } from "../protocol.js";
|
|
4
|
+
import { toPosition } from "../types.js";
|
|
5
|
+
import type { ProfileBot } from "../api.js";
|
|
6
|
+
import { Connection, type CallOutcome, type Transport } from "./connection.js";
|
|
7
|
+
import { BotHandle, ProfileBotHandle, ProfileHandle, type HandleHost } from "./handles.js";
|
|
8
|
+
import { Scope } from "./scope.js";
|
|
9
|
+
import { createStorage } from "./storage-runtime.js";
|
|
10
|
+
|
|
11
|
+
export const SDK_VERSION = "0.2.0";
|
|
12
|
+
|
|
13
|
+
export type LogLevel = "debug" | "info" | "warn" | "error";
|
|
14
|
+
|
|
15
|
+
export interface RuntimeOptions {
|
|
16
|
+
/** Called for every log line, warning and statistic, e.g. to print them under `minebot dev`. */
|
|
17
|
+
onLog?(level: LogLevel, message: string, bot: BotInfo | null): void;
|
|
18
|
+
/** Called once the connection ends. */
|
|
19
|
+
onClosed?(code: number, reason: string): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Builds the manifest the container checks, from the plugin's definition. */
|
|
23
|
+
export function buildManifest(plugin: DefinedPlugin, version: string): Manifest {
|
|
24
|
+
const d = plugin.definition;
|
|
25
|
+
const settings: Record<string, SettingSchema> = {};
|
|
26
|
+
for (const [key, setting] of Object.entries(d.settings ?? {})) settings[key] = setting.schema;
|
|
27
|
+
const storage: Manifest["storage"] = {};
|
|
28
|
+
for (const [key, entry] of Object.entries(d.storage ?? {})) storage[key] = entry.schema;
|
|
29
|
+
return {
|
|
30
|
+
name: d.name,
|
|
31
|
+
version,
|
|
32
|
+
permissions: [...new Set(d.permissions as readonly string[])],
|
|
33
|
+
exclusive: [...new Set((d.exclusive ?? []) as readonly string[])],
|
|
34
|
+
settings,
|
|
35
|
+
storage,
|
|
36
|
+
profile: typeof d.runProfile === "function",
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function applyDefaults(manifest: Manifest, values: Record<string, unknown>): Record<string, unknown> {
|
|
41
|
+
const out: Record<string, unknown> = {};
|
|
42
|
+
for (const [key, schema] of Object.entries(manifest.settings)) {
|
|
43
|
+
const v = values[key];
|
|
44
|
+
out[key] = v === undefined || v === null ? schema.default : v;
|
|
45
|
+
if (schema.type === "position" && out[key]) out[key] = toPosition(out[key]);
|
|
46
|
+
}
|
|
47
|
+
return Object.freeze(out);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function describe(error: unknown): string {
|
|
51
|
+
if (error instanceof Error) return error.stack && !(error instanceof PluginError) ? error.stack : error.message;
|
|
52
|
+
return String(error);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Runs one plugin instance over a connection: starts `runProfile` and `run(bot)` when the container says so,
|
|
57
|
+
* stops them when it says so, and routes events to listeners.
|
|
58
|
+
*/
|
|
59
|
+
export class PluginRuntime implements HandleHost {
|
|
60
|
+
private readonly root = new Scope();
|
|
61
|
+
private readonly botScopes = new Map<string, Scope>();
|
|
62
|
+
private profileScope: Scope | null = null;
|
|
63
|
+
private readonly bots = new Map<string, BotInfo>();
|
|
64
|
+
private readonly listeners = new Map<string, Set<(data: unknown) => unknown>>();
|
|
65
|
+
private readonly profileBots = new Map<string, ProfileBotHandle>();
|
|
66
|
+
private readonly stats = new Map<string, number>();
|
|
67
|
+
|
|
68
|
+
constructor(
|
|
69
|
+
private readonly plugin: DefinedPlugin,
|
|
70
|
+
private readonly manifest: Manifest,
|
|
71
|
+
private readonly connection: Connection,
|
|
72
|
+
readonly welcome: WelcomeFrame,
|
|
73
|
+
private readonly options: RuntimeOptions = {},
|
|
74
|
+
) {
|
|
75
|
+
for (const bot of welcome.bots) this.bots.set(bot.id, bot);
|
|
76
|
+
connection.attach({
|
|
77
|
+
start: (bot, settings, version) => this.start(bot, settings, version),
|
|
78
|
+
stop: (bot, reason) => this.stop(bot, reason),
|
|
79
|
+
event: (bot, event, data) => this.dispatch(bot, event, data),
|
|
80
|
+
bots: frame => {
|
|
81
|
+
this.bots.clear();
|
|
82
|
+
for (const bot of frame.bots) this.bots.set(bot.id, bot);
|
|
83
|
+
},
|
|
84
|
+
dropped: count => this.emitLog("warn", `${count} events were dropped because the plugin didn't keep up`, null),
|
|
85
|
+
closed: (code, reason) => {
|
|
86
|
+
this.root.stop("Disconnected");
|
|
87
|
+
this.options.onClosed?.(code, reason);
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Connects, sends hello and starts running once welcomed. Rejects if the container refuses. */
|
|
93
|
+
static async connect(plugin: DefinedPlugin, transport: Transport, token: string, version: string, options: RuntimeOptions = {}, dev?: DevOptions): Promise<PluginRuntime> {
|
|
94
|
+
const manifest = buildManifest(plugin, version);
|
|
95
|
+
const connection = new Connection(transport);
|
|
96
|
+
const welcome = await connection.open(token, manifest, SDK_VERSION, dev);
|
|
97
|
+
return new PluginRuntime(plugin, manifest, connection, welcome, options);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The profile's bots as the container last reported them. */
|
|
101
|
+
get currentBots(): BotInfo[] {
|
|
102
|
+
return [...this.bots.values()];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The bots `run(bot)` is currently running on. */
|
|
106
|
+
get runningBots(): string[] {
|
|
107
|
+
return [...this.botScopes.keys()];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Stops everything and closes the connection. */
|
|
111
|
+
close(): void {
|
|
112
|
+
this.root.stop("Disconnected");
|
|
113
|
+
this.connection.close();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ---- HandleHost ----
|
|
117
|
+
|
|
118
|
+
call(scope: Scope, bot: string | null, op: string, args: Record<string, unknown> = {}): Promise<CallOutcome> {
|
|
119
|
+
return this.connection.call(scope, bot, op, args);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
subscribe(scope: Scope, bot: string | null, event: string, listener: (data: unknown) => unknown): () => void {
|
|
123
|
+
scope.check();
|
|
124
|
+
const key = `${bot ?? ""}|${event}`;
|
|
125
|
+
let set = this.listeners.get(key);
|
|
126
|
+
if (!set) {
|
|
127
|
+
set = new Set();
|
|
128
|
+
this.listeners.set(key, set);
|
|
129
|
+
this.connection.send({ type: "subscribe", bot, event });
|
|
130
|
+
}
|
|
131
|
+
set.add(listener);
|
|
132
|
+
return scope.onStop(() => {
|
|
133
|
+
const current = this.listeners.get(key);
|
|
134
|
+
if (!current) return;
|
|
135
|
+
current.delete(listener);
|
|
136
|
+
if (current.size === 0) {
|
|
137
|
+
this.listeners.delete(key);
|
|
138
|
+
if (!this.root.stopped) this.connection.send({ type: "unsubscribe", bot, event });
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
botInfo(id: string): BotInfo | undefined {
|
|
144
|
+
return this.bots.get(id);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
profileBot(id: string): ProfileBot {
|
|
148
|
+
let handle = this.profileBots.get(id);
|
|
149
|
+
if (!handle) {
|
|
150
|
+
handle = new ProfileBotHandle(this.profileScope ?? this.root, this, id);
|
|
151
|
+
this.profileBots.set(id, handle);
|
|
152
|
+
}
|
|
153
|
+
return handle;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
logError(bot: string | null, error: unknown): void {
|
|
157
|
+
this.emitLog("error", describe(error), bot);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ---- lifecycle ----
|
|
161
|
+
|
|
162
|
+
private start(bot: string | null, settingsFrame: Record<string, unknown>, version: string): void {
|
|
163
|
+
const settings = applyDefaults(this.manifest, settingsFrame);
|
|
164
|
+
const d = this.plugin.definition;
|
|
165
|
+
|
|
166
|
+
if (bot === null) {
|
|
167
|
+
if (!d.runProfile || this.profileScope) return;
|
|
168
|
+
const scope = this.root.child();
|
|
169
|
+
this.profileScope = scope;
|
|
170
|
+
this.profileBots.clear();
|
|
171
|
+
const profile = new ProfileHandle(scope, this, this.welcome.profile.id, this.welcome.profile.name, () => [...this.bots.values()]);
|
|
172
|
+
const context = this.context(scope, null, settings);
|
|
173
|
+
this.supervise(null, () => d.runProfile!(profile, context as any), scope);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (!d.run) return;
|
|
178
|
+
this.botScopes.get(bot)?.stop("Replaced");
|
|
179
|
+
const scope = this.root.child();
|
|
180
|
+
this.botScopes.set(bot, scope);
|
|
181
|
+
const handle = new BotHandle(scope, this, bot, version);
|
|
182
|
+
const context = this.context(scope, bot, settings);
|
|
183
|
+
this.supervise(bot, () => d.run!(handle, context as any), scope);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
private stop(bot: string | null, reason: string): void {
|
|
187
|
+
if (bot === null) {
|
|
188
|
+
this.profileScope?.stop(reason);
|
|
189
|
+
this.profileScope = null;
|
|
190
|
+
this.profileBots.clear();
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
this.botScopes.get(bot)?.stop(reason);
|
|
194
|
+
this.botScopes.delete(bot);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Runs `run`/`runProfile`. Returning keeps listeners alive until stopped; throwing ends the run and is reported. */
|
|
198
|
+
private supervise(bot: string | null, body: () => Promise<void>, scope: Scope): void {
|
|
199
|
+
Promise.resolve()
|
|
200
|
+
.then(body)
|
|
201
|
+
.catch(error => {
|
|
202
|
+
if (isStopped(error) || scope.stopped) return;
|
|
203
|
+
this.emitLog("error", describe(error), bot);
|
|
204
|
+
this.connection.send({ type: "done", bot, error: error instanceof Error ? error.message : String(error) });
|
|
205
|
+
scope.stop("Failed");
|
|
206
|
+
if (bot === null) this.profileScope = null;
|
|
207
|
+
else if (this.botScopes.get(bot) === scope) this.botScopes.delete(bot);
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private context(scope: Scope, bot: string | null, settings: Record<string, unknown>) {
|
|
212
|
+
const log: Logger = {
|
|
213
|
+
debug: m => this.emitLog("debug", String(m), bot),
|
|
214
|
+
info: m => this.emitLog("info", String(m), bot),
|
|
215
|
+
warn: m => this.emitLog("warn", String(m), bot),
|
|
216
|
+
error: m => this.emitLog("error", m instanceof Error ? describe(m) : String(m), bot),
|
|
217
|
+
};
|
|
218
|
+
const statKey = (name: string) => `${bot ?? ""}|${name}`;
|
|
219
|
+
const stats: Stats = {
|
|
220
|
+
set: (name, value) => {
|
|
221
|
+
this.stats.set(statKey(name), value);
|
|
222
|
+
this.connection.send({ type: "stat", bot, key: name, value });
|
|
223
|
+
},
|
|
224
|
+
add: (name, amount = 1) => {
|
|
225
|
+
const value = (this.stats.get(statKey(name)) ?? 0) + amount;
|
|
226
|
+
this.stats.set(statKey(name), value);
|
|
227
|
+
this.connection.send({ type: "stat", bot, key: name, value });
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
const warnings: Warnings = {
|
|
231
|
+
set: (key, message) => this.connection.send({ type: "warning", bot, key, message }),
|
|
232
|
+
clear: key => this.connection.send({ type: "warning", bot, key, message: null }),
|
|
233
|
+
};
|
|
234
|
+
const botUuid = bot === null ? null : this.bots.get(bot)?.uuid ?? null;
|
|
235
|
+
const storage = createStorage(this.manifest.storage, (s, op, args) => this.connection.call(s, bot, op, args), scope, bot === null ? null : botUuid ?? bot);
|
|
236
|
+
return { settings, storage, log, stats, warnings };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private emitLog(level: LogLevel, message: string, bot: string | null): void {
|
|
240
|
+
const trimmed = message.length > 4000 ? `${message.slice(0, 4000)}…` : message;
|
|
241
|
+
this.connection.send({ type: "log", bot, level, message: trimmed });
|
|
242
|
+
this.options.onLog?.(level, trimmed, bot === null ? null : this.bots.get(bot) ?? null);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ---- events ----
|
|
246
|
+
|
|
247
|
+
private dispatch(bot: string | null, event: string, data: unknown): void {
|
|
248
|
+
if (event === "__error") {
|
|
249
|
+
const e = data as { code: string; message: string };
|
|
250
|
+
this.emitLog("error", `${e.code}: ${e.message}`, null);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const set = this.listeners.get(`${bot ?? ""}|${event}`);
|
|
254
|
+
if (!set) return;
|
|
255
|
+
const payload = this.decorate(data);
|
|
256
|
+
for (const listener of [...set]) {
|
|
257
|
+
try {
|
|
258
|
+
const r = listener(payload);
|
|
259
|
+
if (r && typeof (r as Promise<unknown>).then === "function") {
|
|
260
|
+
(r as Promise<unknown>).catch(error => {
|
|
261
|
+
if (!isStopped(error)) this.emitLog("error", describe(error), bot);
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
} catch (error) {
|
|
265
|
+
if (!isStopped(error)) this.emitLog("error", describe(error), bot);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Turns bot ids in event data into ProfileBot handles, and positions into Positions. */
|
|
271
|
+
private decorate(data: unknown): unknown {
|
|
272
|
+
if (!data || typeof data !== "object") return data;
|
|
273
|
+
const out: Record<string, unknown> = { ...(data as Record<string, unknown>) };
|
|
274
|
+
if (typeof out.botId === "string") {
|
|
275
|
+
out.bot = this.profileBot(out.botId);
|
|
276
|
+
delete out.botId;
|
|
277
|
+
}
|
|
278
|
+
if (out.position && typeof out.position === "object") out.position = toPosition(out.position);
|
|
279
|
+
return Object.freeze(out);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
@@ -1,31 +1,32 @@
|
|
|
1
|
-
# AGENTS.md: writing this MineBot plugin
|
|
2
|
-
|
|
3
|
-
This is a MineBot plugin: TypeScript that controls Minecraft bots through `@minecraftbot-com/plugin`. The plugin runs on
|
|
4
|
-
the developer's machine under `minebot dev` and, once uploaded, on MineBot's servers. Read
|
|
5
|
-
`node_modules/@minecraftbot-com/plugin/AGENTS.md` for the whole API; this file is the short version.
|
|
6
|
-
|
|
7
|
-
## Commands
|
|
8
|
-
|
|
9
|
-
| Command | What it does |
|
|
10
|
-
|---|---|
|
|
11
|
-
| `npm run dev` | Runs the plugin on the user's running profile, restarting on every save. Logs print here. |
|
|
12
|
-
| `npm test` | Runs `test/*.test.ts` against a fake bot (no server). |
|
|
13
|
-
| `npm run check` | Builds the plugin as it would be uploaded and lists the permissions users will be asked for. |
|
|
14
|
-
| `npm run
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
-
|
|
23
|
-
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
-
|
|
29
|
-
-
|
|
30
|
-
-
|
|
31
|
-
-
|
|
1
|
+
# AGENTS.md: writing this MineBot plugin
|
|
2
|
+
|
|
3
|
+
This is a MineBot plugin: TypeScript that controls Minecraft bots through `@minecraftbot-com/plugin`. The plugin runs on
|
|
4
|
+
the developer's machine under `minebot dev` and, once uploaded, on MineBot's servers. Read
|
|
5
|
+
`node_modules/@minecraftbot-com/plugin/AGENTS.md` for the whole API; this file is the short version.
|
|
6
|
+
|
|
7
|
+
## Commands
|
|
8
|
+
|
|
9
|
+
| Command | What it does |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `npm run dev` | Runs the plugin on the user's running profile, restarting on every save. Logs print here. |
|
|
12
|
+
| `npm test` | Runs `test/*.test.ts` against a fake bot (no server). |
|
|
13
|
+
| `npm run check` | Builds the plugin as it would be uploaded and lists the permissions users will be asked for. |
|
|
14
|
+
| `npm run deploy -- --profile <name>` | Uploads it to run on MineBot's servers whenever that profile runs (only when the user asks to deploy). |
|
|
15
|
+
| `npm run typecheck` | TypeScript errors. Run it after every change. |
|
|
16
|
+
|
|
17
|
+
While `npm run dev` runs, its MCP endpoint (`http://127.0.0.1:7788/mcp`, printed at start) gives you the plugin's
|
|
18
|
+
status and logs, a `reload` that waits for the result, and read-only `query` calls on its bots.
|
|
19
|
+
|
|
20
|
+
## Rules that save time
|
|
21
|
+
|
|
22
|
+
- Everything comes from one import: `import { definePlugin, Block, Item, BotEvent, Permission, ... } from "@minecraftbot-com/plugin"`.
|
|
23
|
+
- Use the enums, never strings: `Block.Wheat`, `Item.Bread`, `Entity.Zombie`, `BotEvent.Chat`. Typos are compile errors.
|
|
24
|
+
- Declare every permission the code needs in `permissions`. A missing one throws `PermissionDeniedError` whose
|
|
25
|
+
message names the permission to add. Network access is `Permission.network("api.example.com")`.
|
|
26
|
+
- Actions that can fail for normal reasons return `{ ok, reason }`; check `ok` instead of catching:
|
|
27
|
+
`const moved = await bot.goto(pos, { within: 2 }); if (!moved.ok) log.warn(moved.reason);`
|
|
28
|
+
- Durations name their unit: `{ seconds: 5 }`, `{ ticks: 20 }`. Distances are blocks.
|
|
29
|
+
- Use `bot.loop(async () => { ... })` for repeating work; it backs off on errors and stops with the bot.
|
|
30
|
+
- Never `while (true)` without `await`: hosted plugins are cut off after 50 ms of busy CPU.
|
|
31
|
+
- Keep data in `storage` (declared in `definePlugin`), not in global variables, if it must survive a restart.
|
|
32
|
+
- Hosted plugins have about 1.5 MB of memory after start. Avoid large libraries.
|