@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.
- package/AGENTS.md +188 -0
- package/README.md +47 -3
- package/dist/api.d.ts +354 -0
- package/dist/api.js +2 -0
- package/dist/cli/api.d.ts +49 -0
- package/dist/cli/api.js +69 -0
- package/dist/cli/build.d.ts +24 -0
- package/dist/cli/build.js +72 -0
- package/dist/cli/check.d.ts +17 -0
- package/dist/cli/check.js +99 -0
- package/dist/cli/config.d.ts +11 -0
- package/dist/cli/config.js +38 -0
- package/dist/cli/create.d.ts +2 -0
- package/dist/cli/create.js +39 -0
- package/dist/cli/deploy.d.ts +13 -0
- package/dist/cli/deploy.js +51 -0
- package/dist/cli/dev-mcp.d.ts +36 -0
- package/dist/cli/dev-mcp.js +101 -0
- package/dist/cli/dev.d.ts +15 -0
- package/dist/cli/dev.js +261 -0
- package/dist/cli/fetch-guard.d.ts +7 -0
- package/dist/cli/fetch-guard.js +66 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +119 -0
- package/dist/cli/mcp.d.ts +24 -0
- package/dist/cli/mcp.js +136 -0
- package/dist/cli/output.d.ts +11 -0
- package/dist/cli/output.js +25 -0
- package/dist/cli/test.d.ts +2 -0
- package/dist/cli/test.js +39 -0
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +35 -0
- package/dist/generated/block-states.d.ts +4087 -0
- package/dist/generated/block-states.js +2 -0
- package/dist/generated/blocks.d.ts +1289 -0
- package/dist/generated/blocks.js +1291 -0
- package/dist/generated/contracts.d.ts +304 -0
- package/dist/generated/contracts.js +327 -0
- package/dist/generated/effects.d.ts +43 -0
- package/dist/generated/effects.js +45 -0
- package/dist/generated/entities.d.ts +164 -0
- package/dist/generated/entities.js +166 -0
- package/dist/generated/items.d.ts +1661 -0
- package/dist/generated/items.js +1663 -0
- package/dist/generated/operations.d.ts +7 -0
- package/dist/generated/operations.js +65 -0
- package/dist/generated/permission-labels.d.ts +3 -0
- package/dist/generated/permission-labels.js +17 -0
- package/dist/generated/version.d.ts +2 -0
- package/dist/generated/version.js +3 -0
- package/dist/host/index.d.ts +7 -0
- package/dist/host/index.js +5 -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/index.d.ts +19 -0
- package/dist/index.js +13 -0
- package/dist/permissions.d.ts +11 -0
- package/dist/permissions.js +18 -0
- package/dist/plugin.d.ts +86 -0
- package/dist/plugin.js +26 -0
- package/dist/protocol.d.ts +167 -0
- package/dist/protocol.js +4 -0
- package/dist/runtime/connection.d.ts +52 -0
- package/dist/runtime/connection.js +132 -0
- package/dist/runtime/handles.d.ts +95 -0
- package/dist/runtime/handles.js +289 -0
- package/dist/runtime/memory-transport.d.ts +6 -0
- package/dist/runtime/memory-transport.js +39 -0
- package/dist/runtime/runtime.d.ts +57 -0
- package/dist/runtime/runtime.js +265 -0
- package/dist/runtime/scope.d.ts +25 -0
- package/dist/runtime/scope.js +94 -0
- package/dist/runtime/storage-runtime.d.ts +10 -0
- package/dist/runtime/storage-runtime.js +131 -0
- package/dist/settings.d.ts +111 -0
- package/dist/settings.js +78 -0
- package/dist/storage.d.ts +78 -0
- package/dist/storage.js +24 -0
- package/dist/testing/fake-container.d.ts +175 -0
- package/dist/testing/fake-container.js +483 -0
- package/dist/testing/index.d.ts +37 -0
- package/dist/testing/index.js +54 -0
- package/dist/types.d.ts +65 -0
- package/dist/types.js +54 -0
- package/llms.txt +11 -0
- package/package.json +60 -4
- package/src/api.ts +337 -0
- package/src/cli/api.ts +105 -0
- package/src/cli/build.ts +83 -0
- package/src/cli/check.ts +104 -0
- package/src/cli/config.ts +48 -0
- package/src/cli/create.ts +38 -0
- package/src/cli/deploy.ts +60 -0
- package/src/cli/dev-mcp.ts +131 -0
- package/src/cli/dev.ts +272 -0
- package/src/cli/fetch-guard.ts +61 -0
- package/src/cli/main.ts +120 -0
- package/src/cli/mcp.ts +168 -0
- package/src/cli/output.ts +30 -0
- package/src/cli/test.ts +38 -0
- package/src/errors.ts +34 -0
- package/src/generated/block-states.ts +892 -0
- package/src/generated/blocks.ts +1291 -0
- package/src/generated/contracts.ts +329 -0
- package/src/generated/effects.ts +45 -0
- package/src/generated/entities.ts +166 -0
- package/src/generated/items.ts +1663 -0
- package/src/generated/operations.ts +69 -0
- package/src/generated/permission-labels.ts +19 -0
- package/src/generated/version.ts +3 -0
- package/src/host/index.ts +9 -0
- package/src/hosted/fetch.ts +224 -0
- package/src/hosted/index.ts +121 -0
- package/src/index.ts +34 -0
- package/src/permissions.ts +23 -0
- package/src/plugin.ts +105 -0
- package/src/protocol.ts +107 -0
- package/src/runtime/connection.ts +167 -0
- package/src/runtime/handles.ts +337 -0
- package/src/runtime/memory-transport.ts +41 -0
- package/src/runtime/runtime.ts +281 -0
- package/src/runtime/scope.ts +101 -0
- package/src/runtime/storage-runtime.ts +138 -0
- package/src/settings.ts +118 -0
- package/src/storage.ts +82 -0
- package/src/testing/fake-container.ts +571 -0
- package/src/testing/index.ts +70 -0
- package/src/types.ts +88 -0
- package/templates/basic/AGENTS.md +32 -0
- package/templates/basic/README.md +14 -0
- package/templates/basic/gitignore +3 -0
- package/templates/basic/package.json +19 -0
- package/templates/basic/src/index.ts +20 -0
- package/templates/basic/test/plugin.test.ts +14 -0
- package/templates/basic/tsconfig.json +14 -0
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { PluginError, isStopped } from "../errors.js";
|
|
2
|
+
import { toMilliseconds, toPosition } from "../types.js";
|
|
3
|
+
function vec(p) {
|
|
4
|
+
if (!p || typeof p.x !== "number" || typeof p.y !== "number" || typeof p.z !== "number") {
|
|
5
|
+
throw new TypeError(`Expected a position like { x: 10, y: 64, z: -3 }, got ${JSON.stringify(p)}`);
|
|
6
|
+
}
|
|
7
|
+
return { x: p.x, y: p.y, z: p.z };
|
|
8
|
+
}
|
|
9
|
+
function toResult(outcome) {
|
|
10
|
+
return outcome.ok ? { ok: true } : { ok: false, reason: outcome.failure, message: outcome.message };
|
|
11
|
+
}
|
|
12
|
+
function toValueResult(outcome, map) {
|
|
13
|
+
return outcome.ok ? { ok: true, value: map(outcome.value) } : { ok: false, reason: outcome.failure, message: outcome.message };
|
|
14
|
+
}
|
|
15
|
+
function value(outcome) {
|
|
16
|
+
if (!outcome.ok)
|
|
17
|
+
throw new PluginError(outcome.failure, outcome.message);
|
|
18
|
+
return outcome.value;
|
|
19
|
+
}
|
|
20
|
+
function toBlockInfo(raw) {
|
|
21
|
+
return { position: toPosition(raw.position), block: raw.block, state: raw.state ?? {} };
|
|
22
|
+
}
|
|
23
|
+
function toEntityInfo(raw) {
|
|
24
|
+
return { id: raw.id, type: raw.type, uuid: raw.uuid ?? null, name: raw.name ?? null, position: toPosition(raw.position), distance: raw.distance };
|
|
25
|
+
}
|
|
26
|
+
function entityId(entity) {
|
|
27
|
+
const id = typeof entity === "number" ? entity : entity?.id;
|
|
28
|
+
if (typeof id !== "number")
|
|
29
|
+
throw new TypeError("Expected an entity from bot.entities.nearby() or its id");
|
|
30
|
+
return id;
|
|
31
|
+
}
|
|
32
|
+
/** The container `container.open` opened; its calls fail with `Closed` once it isn't open any more. */
|
|
33
|
+
function containerHandle(call, raw) {
|
|
34
|
+
const items = async () => value(await call("container.items"));
|
|
35
|
+
return {
|
|
36
|
+
position: toPosition(raw.position),
|
|
37
|
+
block: raw.block,
|
|
38
|
+
size: raw.size,
|
|
39
|
+
items,
|
|
40
|
+
async count(item) {
|
|
41
|
+
return (await items()).filter(s => s.item === item).reduce((n, s) => n + s.count, 0);
|
|
42
|
+
},
|
|
43
|
+
async deposit(item, options) {
|
|
44
|
+
return toValueResult(await call("container.deposit", { item, count: options?.count ?? null }), r => ({ moved: r.moved }));
|
|
45
|
+
},
|
|
46
|
+
async withdraw(item, options) {
|
|
47
|
+
return toValueResult(await call("container.withdraw", { item, count: options?.count ?? null }), r => ({ moved: r.moved }));
|
|
48
|
+
},
|
|
49
|
+
async close() {
|
|
50
|
+
value(await call("container.close"));
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** `bot.loop` and `profile.loop`: repeat until the scope stops, with a floor between runs and backoff on errors. */
|
|
55
|
+
export async function loop(scope, host, bot, body, every) {
|
|
56
|
+
const floor = every ? Math.max(toMilliseconds(every), 50) : 50;
|
|
57
|
+
let failures = 0;
|
|
58
|
+
for (;;) {
|
|
59
|
+
scope.check();
|
|
60
|
+
const started = Date.now();
|
|
61
|
+
try {
|
|
62
|
+
await body();
|
|
63
|
+
failures = 0;
|
|
64
|
+
}
|
|
65
|
+
catch (e) {
|
|
66
|
+
if (isStopped(e))
|
|
67
|
+
throw e;
|
|
68
|
+
failures++;
|
|
69
|
+
host.logError(bot, e);
|
|
70
|
+
await scope.sleep(Math.min(60_000, 1000 * 2 ** Math.min(failures - 1, 6)));
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const left = floor - (Date.now() - started);
|
|
74
|
+
await scope.sleep(left > 0 ? left : 0);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
class BotPluginsHandle {
|
|
78
|
+
scope;
|
|
79
|
+
host;
|
|
80
|
+
id;
|
|
81
|
+
constructor(scope, host, id) {
|
|
82
|
+
this.scope = scope;
|
|
83
|
+
this.host = host;
|
|
84
|
+
this.id = id;
|
|
85
|
+
}
|
|
86
|
+
async start(plugin) {
|
|
87
|
+
return toResult(await this.host.call(this.scope, this.id, "plugins.start", { plugin }));
|
|
88
|
+
}
|
|
89
|
+
async stop(plugin) {
|
|
90
|
+
return toResult(await this.host.call(this.scope, this.id, "plugins.stop", { plugin }));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** A bot of the profile as seen from a scope: live name and state from the runtime's bot list. */
|
|
94
|
+
export class ProfileBotHandle {
|
|
95
|
+
scope;
|
|
96
|
+
host;
|
|
97
|
+
id;
|
|
98
|
+
plugins;
|
|
99
|
+
constructor(scope, host, id) {
|
|
100
|
+
this.scope = scope;
|
|
101
|
+
this.host = host;
|
|
102
|
+
this.id = id;
|
|
103
|
+
this.plugins = new BotPluginsHandle(scope, host, id);
|
|
104
|
+
}
|
|
105
|
+
get info() {
|
|
106
|
+
return this.host.botInfo(this.id) ?? { id: this.id, name: "", uuid: "", connected: false, enabled: false };
|
|
107
|
+
}
|
|
108
|
+
get name() { return this.info.name; }
|
|
109
|
+
get uuid() { return this.info.uuid; }
|
|
110
|
+
get connected() { return this.info.connected; }
|
|
111
|
+
get enabled() { return this.info.enabled; }
|
|
112
|
+
async connect() {
|
|
113
|
+
return toResult(await this.host.call(this.scope, this.id, "bot.connect"));
|
|
114
|
+
}
|
|
115
|
+
async disconnect() {
|
|
116
|
+
return toResult(await this.host.call(this.scope, this.id, "bot.disconnect"));
|
|
117
|
+
}
|
|
118
|
+
async reconnect(options) {
|
|
119
|
+
return toResult(await this.host.call(this.scope, this.id, "bot.reconnect", { afterMs: options?.after ? toMilliseconds(options.after) : 0 }));
|
|
120
|
+
}
|
|
121
|
+
toString() {
|
|
122
|
+
return this.name || this.id;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
export class BotHandle extends ProfileBotHandle {
|
|
126
|
+
version;
|
|
127
|
+
world;
|
|
128
|
+
entities;
|
|
129
|
+
inventory;
|
|
130
|
+
containers;
|
|
131
|
+
constructor(scope, host, id, version) {
|
|
132
|
+
super(scope, host, id);
|
|
133
|
+
this.version = version;
|
|
134
|
+
const call = (op, args) => host.call(scope, id, op, args);
|
|
135
|
+
this.world = {
|
|
136
|
+
async block(position) {
|
|
137
|
+
const raw = value(await call("world.block", vec(position)));
|
|
138
|
+
return raw ? toBlockInfo(raw) : null;
|
|
139
|
+
},
|
|
140
|
+
async findBlocks(query) {
|
|
141
|
+
const blocks = Array.isArray(query.block) ? [...query.block] : [query.block];
|
|
142
|
+
if (blocks.length === 0)
|
|
143
|
+
throw new TypeError("findBlocks needs at least one block");
|
|
144
|
+
const raw = value(await call("world.findBlocks", {
|
|
145
|
+
blocks,
|
|
146
|
+
state: query.state ?? {},
|
|
147
|
+
radius: query.radius ?? 16,
|
|
148
|
+
limit: query.limit ?? 16,
|
|
149
|
+
from: query.from ? vec(query.from) : null,
|
|
150
|
+
}));
|
|
151
|
+
return raw.map(toBlockInfo);
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
this.entities = {
|
|
155
|
+
async nearby(query = {}) {
|
|
156
|
+
const types = query.type === undefined ? null : Array.isArray(query.type) ? [...query.type] : [query.type];
|
|
157
|
+
const raw = value(await call("entities.nearby", { types, radius: query.radius ?? 16, limit: query.limit ?? 32 }));
|
|
158
|
+
return raw.map(toEntityInfo);
|
|
159
|
+
},
|
|
160
|
+
async players() {
|
|
161
|
+
return value(await call("entities.players"));
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
this.inventory = {
|
|
165
|
+
async items() {
|
|
166
|
+
return value(await call("inventory.items"));
|
|
167
|
+
},
|
|
168
|
+
async held() {
|
|
169
|
+
return value(await call("inventory.held"));
|
|
170
|
+
},
|
|
171
|
+
async count(item) {
|
|
172
|
+
const items = value(await call("inventory.items"));
|
|
173
|
+
return items.filter(s => s.item === item).reduce((n, s) => n + s.count, 0);
|
|
174
|
+
},
|
|
175
|
+
async equip(item, slot) {
|
|
176
|
+
return toResult(await call("inventory.equip", { item, slot: slot ?? "Hand" }));
|
|
177
|
+
},
|
|
178
|
+
async drop(item, options) {
|
|
179
|
+
return toResult(await call("inventory.drop", { item, count: options?.count ?? null }));
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
this.containers = {
|
|
183
|
+
async open(position) {
|
|
184
|
+
return toValueResult(await call("container.open", vec(position)), raw => containerHandle(call, raw));
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
async craft(item, options) {
|
|
189
|
+
return toValueResult(await this.call("bot.craft", { item, count: options?.count ?? 1, table: options?.table ? vec(options.table) : null }), raw => ({ crafted: raw.crafted }));
|
|
190
|
+
}
|
|
191
|
+
async recipes(item) {
|
|
192
|
+
return value(await this.call("bot.recipes", { item }));
|
|
193
|
+
}
|
|
194
|
+
call(op, args) {
|
|
195
|
+
return this.host.call(this.scope, this.id, op, args);
|
|
196
|
+
}
|
|
197
|
+
on(event, listener) {
|
|
198
|
+
return this.host.subscribe(this.scope, this.id, event, listener);
|
|
199
|
+
}
|
|
200
|
+
async status() {
|
|
201
|
+
return value(await this.call("bot.status"));
|
|
202
|
+
}
|
|
203
|
+
async position() {
|
|
204
|
+
return toPosition(value(await this.call("bot.position")));
|
|
205
|
+
}
|
|
206
|
+
async supports(id) {
|
|
207
|
+
return value(await this.call("bot.supports", { id }));
|
|
208
|
+
}
|
|
209
|
+
async goto(target, options) {
|
|
210
|
+
return toResult(await this.call("bot.goto", { ...vec(target), within: options?.within ?? 0, timeoutMs: options?.timeout ? toMilliseconds(options.timeout) : null }));
|
|
211
|
+
}
|
|
212
|
+
async follow(entity, options) {
|
|
213
|
+
return toResult(await this.call("bot.follow", { entity: entityId(entity), distance: options?.distance ?? 2, timeoutMs: options?.timeout ? toMilliseconds(options.timeout) : null }));
|
|
214
|
+
}
|
|
215
|
+
async stopMoving() {
|
|
216
|
+
value(await this.call("bot.stopMoving"));
|
|
217
|
+
}
|
|
218
|
+
async lookAt(target) {
|
|
219
|
+
value(await this.call("bot.lookAt", vec(target)));
|
|
220
|
+
}
|
|
221
|
+
async jump() {
|
|
222
|
+
value(await this.call("bot.jump"));
|
|
223
|
+
}
|
|
224
|
+
async dig(position) {
|
|
225
|
+
return toResult(await this.call("bot.dig", vec(position)));
|
|
226
|
+
}
|
|
227
|
+
async place(position, item) {
|
|
228
|
+
return toResult(await this.call("bot.place", { ...vec(position), item }));
|
|
229
|
+
}
|
|
230
|
+
async activateBlock(position) {
|
|
231
|
+
return toResult(await this.call("bot.activateBlock", vec(position)));
|
|
232
|
+
}
|
|
233
|
+
async useItem() {
|
|
234
|
+
return toResult(await this.call("bot.useItem"));
|
|
235
|
+
}
|
|
236
|
+
async attack(entity) {
|
|
237
|
+
return toResult(await this.call("bot.attack", { entity: entityId(entity) }));
|
|
238
|
+
}
|
|
239
|
+
async say(message) {
|
|
240
|
+
if (typeof message !== "string" || message.length === 0)
|
|
241
|
+
throw new TypeError("bot.say needs a non-empty message");
|
|
242
|
+
if (message.startsWith("/"))
|
|
243
|
+
throw new TypeError(`bot.say doesn't run commands; use bot.command("${message.slice(1)}") (needs Permission.Commands)`);
|
|
244
|
+
value(await this.call("bot.say", { text: message }));
|
|
245
|
+
}
|
|
246
|
+
async command(command) {
|
|
247
|
+
const text = command.startsWith("/") ? command.slice(1) : command;
|
|
248
|
+
if (text.trim().length === 0)
|
|
249
|
+
throw new TypeError("bot.command needs a command, e.g. bot.command(\"home\")");
|
|
250
|
+
value(await this.call("bot.command", { command: text }));
|
|
251
|
+
}
|
|
252
|
+
wait(duration) {
|
|
253
|
+
return this.scope.sleep(toMilliseconds(duration));
|
|
254
|
+
}
|
|
255
|
+
loop(body, options) {
|
|
256
|
+
return loop(this.scope, this.host, this.id, body, options?.every);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
export class ProfileHandle {
|
|
260
|
+
scope;
|
|
261
|
+
host;
|
|
262
|
+
id;
|
|
263
|
+
name;
|
|
264
|
+
list;
|
|
265
|
+
constructor(scope, host, id, name, list) {
|
|
266
|
+
this.scope = scope;
|
|
267
|
+
this.host = host;
|
|
268
|
+
this.id = id;
|
|
269
|
+
this.name = name;
|
|
270
|
+
this.list = list;
|
|
271
|
+
}
|
|
272
|
+
bots() {
|
|
273
|
+
return this.list().map(b => this.host.profileBot(b.id));
|
|
274
|
+
}
|
|
275
|
+
bot(idNameOrUuid) {
|
|
276
|
+
const needle = idNameOrUuid.toLowerCase();
|
|
277
|
+
const info = this.list().find(b => b.id === idNameOrUuid || b.uuid.toLowerCase() === needle || b.name.toLowerCase() === needle);
|
|
278
|
+
return info ? this.host.profileBot(info.id) : undefined;
|
|
279
|
+
}
|
|
280
|
+
on(event, listener) {
|
|
281
|
+
return this.host.subscribe(this.scope, null, event, listener);
|
|
282
|
+
}
|
|
283
|
+
wait(duration) {
|
|
284
|
+
return this.scope.sleep(toMilliseconds(duration));
|
|
285
|
+
}
|
|
286
|
+
loop(body, options) {
|
|
287
|
+
return loop(this.scope, this.host, null, body, options?.every);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Transport } from "./connection.js";
|
|
2
|
+
/**
|
|
3
|
+
* Two transports joined back to back, for tests and the fake bot: what one side sends, the other receives
|
|
4
|
+
* on a later microtask, as over a real socket.
|
|
5
|
+
*/
|
|
6
|
+
export declare function memoryTransportPair(): [Transport, Transport];
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Two transports joined back to back, for tests and the fake bot: what one side sends, the other receives
|
|
3
|
+
* on a later microtask, as over a real socket.
|
|
4
|
+
*/
|
|
5
|
+
export function memoryTransportPair() {
|
|
6
|
+
const a = new MemoryTransport();
|
|
7
|
+
const b = new MemoryTransport();
|
|
8
|
+
a.peer = b;
|
|
9
|
+
b.peer = a;
|
|
10
|
+
return [a, b];
|
|
11
|
+
}
|
|
12
|
+
class MemoryTransport {
|
|
13
|
+
peer = null;
|
|
14
|
+
onmessage = null;
|
|
15
|
+
onclose = null;
|
|
16
|
+
open = true;
|
|
17
|
+
send(text) {
|
|
18
|
+
if (!this.open)
|
|
19
|
+
return;
|
|
20
|
+
const peer = this.peer;
|
|
21
|
+
queueMicrotask(() => {
|
|
22
|
+
if (peer?.open)
|
|
23
|
+
peer.onmessage?.(text);
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
close(code = 1000, reason = "") {
|
|
27
|
+
if (!this.open)
|
|
28
|
+
return;
|
|
29
|
+
this.open = false;
|
|
30
|
+
const peer = this.peer;
|
|
31
|
+
queueMicrotask(() => {
|
|
32
|
+
this.onclose?.(code, reason);
|
|
33
|
+
if (peer?.open) {
|
|
34
|
+
peer.open = false;
|
|
35
|
+
peer.onclose?.(code, reason);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { DefinedPlugin } from "../plugin.js";
|
|
2
|
+
import type { BotInfo, DevOptions, Manifest, WelcomeFrame } from "../protocol.js";
|
|
3
|
+
import type { ProfileBot } from "../api.js";
|
|
4
|
+
import { Connection, type CallOutcome, type Transport } from "./connection.js";
|
|
5
|
+
import { type HandleHost } from "./handles.js";
|
|
6
|
+
import { Scope } from "./scope.js";
|
|
7
|
+
export declare const SDK_VERSION = "0.2.0";
|
|
8
|
+
export type LogLevel = "debug" | "info" | "warn" | "error";
|
|
9
|
+
export interface RuntimeOptions {
|
|
10
|
+
/** Called for every log line, warning and statistic, e.g. to print them under `minebot dev`. */
|
|
11
|
+
onLog?(level: LogLevel, message: string, bot: BotInfo | null): void;
|
|
12
|
+
/** Called once the connection ends. */
|
|
13
|
+
onClosed?(code: number, reason: string): void;
|
|
14
|
+
}
|
|
15
|
+
/** Builds the manifest the container checks, from the plugin's definition. */
|
|
16
|
+
export declare function buildManifest(plugin: DefinedPlugin, version: string): Manifest;
|
|
17
|
+
/**
|
|
18
|
+
* Runs one plugin instance over a connection: starts `runProfile` and `run(bot)` when the container says so,
|
|
19
|
+
* stops them when it says so, and routes events to listeners.
|
|
20
|
+
*/
|
|
21
|
+
export declare class PluginRuntime implements HandleHost {
|
|
22
|
+
private readonly plugin;
|
|
23
|
+
private readonly manifest;
|
|
24
|
+
private readonly connection;
|
|
25
|
+
readonly welcome: WelcomeFrame;
|
|
26
|
+
private readonly options;
|
|
27
|
+
private readonly root;
|
|
28
|
+
private readonly botScopes;
|
|
29
|
+
private profileScope;
|
|
30
|
+
private readonly bots;
|
|
31
|
+
private readonly listeners;
|
|
32
|
+
private readonly profileBots;
|
|
33
|
+
private readonly stats;
|
|
34
|
+
constructor(plugin: DefinedPlugin, manifest: Manifest, connection: Connection, welcome: WelcomeFrame, options?: RuntimeOptions);
|
|
35
|
+
/** Connects, sends hello and starts running once welcomed. Rejects if the container refuses. */
|
|
36
|
+
static connect(plugin: DefinedPlugin, transport: Transport, token: string, version: string, options?: RuntimeOptions, dev?: DevOptions): Promise<PluginRuntime>;
|
|
37
|
+
/** The profile's bots as the container last reported them. */
|
|
38
|
+
get currentBots(): BotInfo[];
|
|
39
|
+
/** The bots `run(bot)` is currently running on. */
|
|
40
|
+
get runningBots(): string[];
|
|
41
|
+
/** Stops everything and closes the connection. */
|
|
42
|
+
close(): void;
|
|
43
|
+
call(scope: Scope, bot: string | null, op: string, args?: Record<string, unknown>): Promise<CallOutcome>;
|
|
44
|
+
subscribe(scope: Scope, bot: string | null, event: string, listener: (data: unknown) => unknown): () => void;
|
|
45
|
+
botInfo(id: string): BotInfo | undefined;
|
|
46
|
+
profileBot(id: string): ProfileBot;
|
|
47
|
+
logError(bot: string | null, error: unknown): void;
|
|
48
|
+
private start;
|
|
49
|
+
private stop;
|
|
50
|
+
/** Runs `run`/`runProfile`. Returning keeps listeners alive until stopped; throwing ends the run and is reported. */
|
|
51
|
+
private supervise;
|
|
52
|
+
private context;
|
|
53
|
+
private emitLog;
|
|
54
|
+
private dispatch;
|
|
55
|
+
/** Turns bot ids in event data into ProfileBot handles, and positions into Positions. */
|
|
56
|
+
private decorate;
|
|
57
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { isStopped, PluginError } from "../errors.js";
|
|
2
|
+
import { toPosition } from "../types.js";
|
|
3
|
+
import { Connection } from "./connection.js";
|
|
4
|
+
import { BotHandle, ProfileBotHandle, ProfileHandle } from "./handles.js";
|
|
5
|
+
import { Scope } from "./scope.js";
|
|
6
|
+
import { createStorage } from "./storage-runtime.js";
|
|
7
|
+
export const SDK_VERSION = "0.2.0";
|
|
8
|
+
/** Builds the manifest the container checks, from the plugin's definition. */
|
|
9
|
+
export function buildManifest(plugin, version) {
|
|
10
|
+
const d = plugin.definition;
|
|
11
|
+
const settings = {};
|
|
12
|
+
for (const [key, setting] of Object.entries(d.settings ?? {}))
|
|
13
|
+
settings[key] = setting.schema;
|
|
14
|
+
const storage = {};
|
|
15
|
+
for (const [key, entry] of Object.entries(d.storage ?? {}))
|
|
16
|
+
storage[key] = entry.schema;
|
|
17
|
+
return {
|
|
18
|
+
name: d.name,
|
|
19
|
+
version,
|
|
20
|
+
permissions: [...new Set(d.permissions)],
|
|
21
|
+
exclusive: [...new Set((d.exclusive ?? []))],
|
|
22
|
+
settings,
|
|
23
|
+
storage,
|
|
24
|
+
profile: typeof d.runProfile === "function",
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function applyDefaults(manifest, values) {
|
|
28
|
+
const out = {};
|
|
29
|
+
for (const [key, schema] of Object.entries(manifest.settings)) {
|
|
30
|
+
const v = values[key];
|
|
31
|
+
out[key] = v === undefined || v === null ? schema.default : v;
|
|
32
|
+
if (schema.type === "position" && out[key])
|
|
33
|
+
out[key] = toPosition(out[key]);
|
|
34
|
+
}
|
|
35
|
+
return Object.freeze(out);
|
|
36
|
+
}
|
|
37
|
+
function describe(error) {
|
|
38
|
+
if (error instanceof Error)
|
|
39
|
+
return error.stack && !(error instanceof PluginError) ? error.stack : error.message;
|
|
40
|
+
return String(error);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Runs one plugin instance over a connection: starts `runProfile` and `run(bot)` when the container says so,
|
|
44
|
+
* stops them when it says so, and routes events to listeners.
|
|
45
|
+
*/
|
|
46
|
+
export class PluginRuntime {
|
|
47
|
+
plugin;
|
|
48
|
+
manifest;
|
|
49
|
+
connection;
|
|
50
|
+
welcome;
|
|
51
|
+
options;
|
|
52
|
+
root = new Scope();
|
|
53
|
+
botScopes = new Map();
|
|
54
|
+
profileScope = null;
|
|
55
|
+
bots = new Map();
|
|
56
|
+
listeners = new Map();
|
|
57
|
+
profileBots = new Map();
|
|
58
|
+
stats = new Map();
|
|
59
|
+
constructor(plugin, manifest, connection, welcome, options = {}) {
|
|
60
|
+
this.plugin = plugin;
|
|
61
|
+
this.manifest = manifest;
|
|
62
|
+
this.connection = connection;
|
|
63
|
+
this.welcome = welcome;
|
|
64
|
+
this.options = options;
|
|
65
|
+
for (const bot of welcome.bots)
|
|
66
|
+
this.bots.set(bot.id, bot);
|
|
67
|
+
connection.attach({
|
|
68
|
+
start: (bot, settings, version) => this.start(bot, settings, version),
|
|
69
|
+
stop: (bot, reason) => this.stop(bot, reason),
|
|
70
|
+
event: (bot, event, data) => this.dispatch(bot, event, data),
|
|
71
|
+
bots: frame => {
|
|
72
|
+
this.bots.clear();
|
|
73
|
+
for (const bot of frame.bots)
|
|
74
|
+
this.bots.set(bot.id, bot);
|
|
75
|
+
},
|
|
76
|
+
dropped: count => this.emitLog("warn", `${count} events were dropped because the plugin didn't keep up`, null),
|
|
77
|
+
closed: (code, reason) => {
|
|
78
|
+
this.root.stop("Disconnected");
|
|
79
|
+
this.options.onClosed?.(code, reason);
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/** Connects, sends hello and starts running once welcomed. Rejects if the container refuses. */
|
|
84
|
+
static async connect(plugin, transport, token, version, options = {}, dev) {
|
|
85
|
+
const manifest = buildManifest(plugin, version);
|
|
86
|
+
const connection = new Connection(transport);
|
|
87
|
+
const welcome = await connection.open(token, manifest, SDK_VERSION, dev);
|
|
88
|
+
return new PluginRuntime(plugin, manifest, connection, welcome, options);
|
|
89
|
+
}
|
|
90
|
+
/** The profile's bots as the container last reported them. */
|
|
91
|
+
get currentBots() {
|
|
92
|
+
return [...this.bots.values()];
|
|
93
|
+
}
|
|
94
|
+
/** The bots `run(bot)` is currently running on. */
|
|
95
|
+
get runningBots() {
|
|
96
|
+
return [...this.botScopes.keys()];
|
|
97
|
+
}
|
|
98
|
+
/** Stops everything and closes the connection. */
|
|
99
|
+
close() {
|
|
100
|
+
this.root.stop("Disconnected");
|
|
101
|
+
this.connection.close();
|
|
102
|
+
}
|
|
103
|
+
// ---- HandleHost ----
|
|
104
|
+
call(scope, bot, op, args = {}) {
|
|
105
|
+
return this.connection.call(scope, bot, op, args);
|
|
106
|
+
}
|
|
107
|
+
subscribe(scope, bot, event, listener) {
|
|
108
|
+
scope.check();
|
|
109
|
+
const key = `${bot ?? ""}|${event}`;
|
|
110
|
+
let set = this.listeners.get(key);
|
|
111
|
+
if (!set) {
|
|
112
|
+
set = new Set();
|
|
113
|
+
this.listeners.set(key, set);
|
|
114
|
+
this.connection.send({ type: "subscribe", bot, event });
|
|
115
|
+
}
|
|
116
|
+
set.add(listener);
|
|
117
|
+
return scope.onStop(() => {
|
|
118
|
+
const current = this.listeners.get(key);
|
|
119
|
+
if (!current)
|
|
120
|
+
return;
|
|
121
|
+
current.delete(listener);
|
|
122
|
+
if (current.size === 0) {
|
|
123
|
+
this.listeners.delete(key);
|
|
124
|
+
if (!this.root.stopped)
|
|
125
|
+
this.connection.send({ type: "unsubscribe", bot, event });
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
botInfo(id) {
|
|
130
|
+
return this.bots.get(id);
|
|
131
|
+
}
|
|
132
|
+
profileBot(id) {
|
|
133
|
+
let handle = this.profileBots.get(id);
|
|
134
|
+
if (!handle) {
|
|
135
|
+
handle = new ProfileBotHandle(this.profileScope ?? this.root, this, id);
|
|
136
|
+
this.profileBots.set(id, handle);
|
|
137
|
+
}
|
|
138
|
+
return handle;
|
|
139
|
+
}
|
|
140
|
+
logError(bot, error) {
|
|
141
|
+
this.emitLog("error", describe(error), bot);
|
|
142
|
+
}
|
|
143
|
+
// ---- lifecycle ----
|
|
144
|
+
start(bot, settingsFrame, version) {
|
|
145
|
+
const settings = applyDefaults(this.manifest, settingsFrame);
|
|
146
|
+
const d = this.plugin.definition;
|
|
147
|
+
if (bot === null) {
|
|
148
|
+
if (!d.runProfile || this.profileScope)
|
|
149
|
+
return;
|
|
150
|
+
const scope = this.root.child();
|
|
151
|
+
this.profileScope = scope;
|
|
152
|
+
this.profileBots.clear();
|
|
153
|
+
const profile = new ProfileHandle(scope, this, this.welcome.profile.id, this.welcome.profile.name, () => [...this.bots.values()]);
|
|
154
|
+
const context = this.context(scope, null, settings);
|
|
155
|
+
this.supervise(null, () => d.runProfile(profile, context), scope);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (!d.run)
|
|
159
|
+
return;
|
|
160
|
+
this.botScopes.get(bot)?.stop("Replaced");
|
|
161
|
+
const scope = this.root.child();
|
|
162
|
+
this.botScopes.set(bot, scope);
|
|
163
|
+
const handle = new BotHandle(scope, this, bot, version);
|
|
164
|
+
const context = this.context(scope, bot, settings);
|
|
165
|
+
this.supervise(bot, () => d.run(handle, context), scope);
|
|
166
|
+
}
|
|
167
|
+
stop(bot, reason) {
|
|
168
|
+
if (bot === null) {
|
|
169
|
+
this.profileScope?.stop(reason);
|
|
170
|
+
this.profileScope = null;
|
|
171
|
+
this.profileBots.clear();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
this.botScopes.get(bot)?.stop(reason);
|
|
175
|
+
this.botScopes.delete(bot);
|
|
176
|
+
}
|
|
177
|
+
/** Runs `run`/`runProfile`. Returning keeps listeners alive until stopped; throwing ends the run and is reported. */
|
|
178
|
+
supervise(bot, body, scope) {
|
|
179
|
+
Promise.resolve()
|
|
180
|
+
.then(body)
|
|
181
|
+
.catch(error => {
|
|
182
|
+
if (isStopped(error) || scope.stopped)
|
|
183
|
+
return;
|
|
184
|
+
this.emitLog("error", describe(error), bot);
|
|
185
|
+
this.connection.send({ type: "done", bot, error: error instanceof Error ? error.message : String(error) });
|
|
186
|
+
scope.stop("Failed");
|
|
187
|
+
if (bot === null)
|
|
188
|
+
this.profileScope = null;
|
|
189
|
+
else if (this.botScopes.get(bot) === scope)
|
|
190
|
+
this.botScopes.delete(bot);
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
context(scope, bot, settings) {
|
|
194
|
+
const log = {
|
|
195
|
+
debug: m => this.emitLog("debug", String(m), bot),
|
|
196
|
+
info: m => this.emitLog("info", String(m), bot),
|
|
197
|
+
warn: m => this.emitLog("warn", String(m), bot),
|
|
198
|
+
error: m => this.emitLog("error", m instanceof Error ? describe(m) : String(m), bot),
|
|
199
|
+
};
|
|
200
|
+
const statKey = (name) => `${bot ?? ""}|${name}`;
|
|
201
|
+
const stats = {
|
|
202
|
+
set: (name, value) => {
|
|
203
|
+
this.stats.set(statKey(name), value);
|
|
204
|
+
this.connection.send({ type: "stat", bot, key: name, value });
|
|
205
|
+
},
|
|
206
|
+
add: (name, amount = 1) => {
|
|
207
|
+
const value = (this.stats.get(statKey(name)) ?? 0) + amount;
|
|
208
|
+
this.stats.set(statKey(name), value);
|
|
209
|
+
this.connection.send({ type: "stat", bot, key: name, value });
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
const warnings = {
|
|
213
|
+
set: (key, message) => this.connection.send({ type: "warning", bot, key, message }),
|
|
214
|
+
clear: key => this.connection.send({ type: "warning", bot, key, message: null }),
|
|
215
|
+
};
|
|
216
|
+
const botUuid = bot === null ? null : this.bots.get(bot)?.uuid ?? null;
|
|
217
|
+
const storage = createStorage(this.manifest.storage, (s, op, args) => this.connection.call(s, bot, op, args), scope, bot === null ? null : botUuid ?? bot);
|
|
218
|
+
return { settings, storage, log, stats, warnings };
|
|
219
|
+
}
|
|
220
|
+
emitLog(level, message, bot) {
|
|
221
|
+
const trimmed = message.length > 4000 ? `${message.slice(0, 4000)}…` : message;
|
|
222
|
+
this.connection.send({ type: "log", bot, level, message: trimmed });
|
|
223
|
+
this.options.onLog?.(level, trimmed, bot === null ? null : this.bots.get(bot) ?? null);
|
|
224
|
+
}
|
|
225
|
+
// ---- events ----
|
|
226
|
+
dispatch(bot, event, data) {
|
|
227
|
+
if (event === "__error") {
|
|
228
|
+
const e = data;
|
|
229
|
+
this.emitLog("error", `${e.code}: ${e.message}`, null);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const set = this.listeners.get(`${bot ?? ""}|${event}`);
|
|
233
|
+
if (!set)
|
|
234
|
+
return;
|
|
235
|
+
const payload = this.decorate(data);
|
|
236
|
+
for (const listener of [...set]) {
|
|
237
|
+
try {
|
|
238
|
+
const r = listener(payload);
|
|
239
|
+
if (r && typeof r.then === "function") {
|
|
240
|
+
r.catch(error => {
|
|
241
|
+
if (!isStopped(error))
|
|
242
|
+
this.emitLog("error", describe(error), bot);
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
if (!isStopped(error))
|
|
248
|
+
this.emitLog("error", describe(error), bot);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/** Turns bot ids in event data into ProfileBot handles, and positions into Positions. */
|
|
253
|
+
decorate(data) {
|
|
254
|
+
if (!data || typeof data !== "object")
|
|
255
|
+
return data;
|
|
256
|
+
const out = { ...data };
|
|
257
|
+
if (typeof out.botId === "string") {
|
|
258
|
+
out.bot = this.profileBot(out.botId);
|
|
259
|
+
delete out.botId;
|
|
260
|
+
}
|
|
261
|
+
if (out.position && typeof out.position === "object")
|
|
262
|
+
out.position = toPosition(out.position);
|
|
263
|
+
return Object.freeze(out);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A lifetime: one run(bot), one runProfile, or the whole plugin. Everything started inside it (calls,
|
|
3
|
+
* listeners, timers, child scopes) ends when it stops, so plugin code never needs cancellation plumbing.
|
|
4
|
+
*/
|
|
5
|
+
export declare class Scope {
|
|
6
|
+
private readonly parent;
|
|
7
|
+
private readonly cleanups;
|
|
8
|
+
private readonly children;
|
|
9
|
+
private stoppedReason;
|
|
10
|
+
constructor(parent?: Scope | null);
|
|
11
|
+
get stopped(): boolean;
|
|
12
|
+
get reason(): string | null;
|
|
13
|
+
/** Throws StoppedError if this scope has stopped. */
|
|
14
|
+
check(): void;
|
|
15
|
+
child(): Scope;
|
|
16
|
+
/** Runs `cleanup` when the scope stops. Returns a function that runs it early and forgets it. */
|
|
17
|
+
onStop(cleanup: () => void): () => void;
|
|
18
|
+
/** Forgets a cleanup without running it. */
|
|
19
|
+
forget(cleanup: () => void): void;
|
|
20
|
+
stop(reason: string): void;
|
|
21
|
+
/** A promise that settles like `promise` but rejects with StoppedError as soon as the scope stops. */
|
|
22
|
+
guard<T>(promise: Promise<T>): Promise<T>;
|
|
23
|
+
/** Waits `ms`, or rejects with StoppedError when the scope stops first. */
|
|
24
|
+
sleep(ms: number): Promise<void>;
|
|
25
|
+
}
|