@minecraftbot-com/plugin 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +177 -0
- package/README.md +45 -2
- package/dist/api.d.ts +351 -0
- package/dist/api.js +2 -0
- package/dist/cli/api.d.ts +26 -0
- package/dist/cli/api.js +61 -0
- package/dist/cli/build.d.ts +23 -0
- package/dist/cli/build.js +65 -0
- package/dist/cli/check.d.ts +10 -0
- package/dist/cli/check.js +98 -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/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 +112 -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/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 +55 -4
- package/src/api.ts +334 -0
- package/src/cli/api.ts +79 -0
- package/src/cli/build.ts +76 -0
- package/src/cli/check.ts +103 -0
- package/src/cli/config.ts +48 -0
- package/src/cli/create.ts +38 -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 +113 -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/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 +31 -0
- package/templates/basic/README.md +13 -0
- package/templates/basic/gitignore +3 -0
- package/templates/basic/package.json +18 -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,337 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Bot, BlockInfo, BotEventData, BotPlugins, BotStatus, Container, Containers, Entities, EntityInfo, Inventory, ItemStack,
|
|
3
|
+
Listener, PlayerInfo, Profile, ProfileBot, ProfileEventData, Recipe, World,
|
|
4
|
+
} from "../api.js";
|
|
5
|
+
import type { BotEvent, BuiltInPlugin, ContainerFailure, CraftFailure, EquipmentSlot, ProfileEvent } from "../generated/contracts.js";
|
|
6
|
+
import type { Block } from "../generated/blocks.js";
|
|
7
|
+
import type { Item } from "../generated/items.js";
|
|
8
|
+
import type { Entity } from "../generated/entities.js";
|
|
9
|
+
import { PluginError, isStopped } from "../errors.js";
|
|
10
|
+
import type { BotInfo } from "../protocol.js";
|
|
11
|
+
import { toMilliseconds, toPosition, type Duration, type Position, type Result, type Vec3 } from "../types.js";
|
|
12
|
+
import type { CallOutcome } from "./connection.js";
|
|
13
|
+
import type { Scope } from "./scope.js";
|
|
14
|
+
|
|
15
|
+
/** What the handles need from the runtime: calls, subscriptions and logging, all within a scope. */
|
|
16
|
+
export interface HandleHost {
|
|
17
|
+
call(scope: Scope, bot: string | null, op: string, args?: Record<string, unknown>): Promise<CallOutcome>;
|
|
18
|
+
subscribe(scope: Scope, bot: string | null, event: string, listener: (data: unknown) => unknown): () => void;
|
|
19
|
+
botInfo(id: string): BotInfo | undefined;
|
|
20
|
+
profileBot(id: string): ProfileBot;
|
|
21
|
+
logError(bot: string | null, error: unknown): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function vec(p: Vec3): { x: number; y: number; z: number } {
|
|
25
|
+
if (!p || typeof p.x !== "number" || typeof p.y !== "number" || typeof p.z !== "number") {
|
|
26
|
+
throw new TypeError(`Expected a position like { x: 10, y: 64, z: -3 }, got ${JSON.stringify(p)}`);
|
|
27
|
+
}
|
|
28
|
+
return { x: p.x, y: p.y, z: p.z };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function toResult<F extends string>(outcome: CallOutcome): Result<F> {
|
|
32
|
+
return outcome.ok ? ({ ok: true } as Result<F>) : { ok: false, reason: outcome.failure as F, message: outcome.message };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function toValueResult<F extends string, T>(outcome: CallOutcome, map: (raw: any) => T): Result<F, T> {
|
|
36
|
+
return outcome.ok ? ({ ok: true, value: map(outcome.value) } as Result<F, T>) : { ok: false, reason: outcome.failure as F, message: outcome.message };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function value<T>(outcome: CallOutcome): T {
|
|
40
|
+
if (!outcome.ok) throw new PluginError(outcome.failure, outcome.message);
|
|
41
|
+
return outcome.value as T;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function toBlockInfo(raw: any): BlockInfo {
|
|
45
|
+
return { position: toPosition(raw.position), block: raw.block as Block, state: raw.state ?? {} };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function toEntityInfo(raw: any): EntityInfo {
|
|
49
|
+
return { id: raw.id, type: raw.type, uuid: raw.uuid ?? null, name: raw.name ?? null, position: toPosition(raw.position), distance: raw.distance };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function entityId(entity: EntityInfo | number): number {
|
|
53
|
+
const id = typeof entity === "number" ? entity : entity?.id;
|
|
54
|
+
if (typeof id !== "number") throw new TypeError("Expected an entity from bot.entities.nearby() or its id");
|
|
55
|
+
return id;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The container `container.open` opened; its calls fail with `Closed` once it isn't open any more. */
|
|
59
|
+
function containerHandle(call: (op: string, args?: Record<string, unknown>) => Promise<CallOutcome>, raw: any): Container {
|
|
60
|
+
const items = async () => value<ItemStack[]>(await call("container.items"));
|
|
61
|
+
return {
|
|
62
|
+
position: toPosition(raw.position),
|
|
63
|
+
block: raw.block as Block,
|
|
64
|
+
size: raw.size,
|
|
65
|
+
items,
|
|
66
|
+
async count(item: Item) {
|
|
67
|
+
return (await items()).filter(s => s.item === item).reduce((n, s) => n + s.count, 0);
|
|
68
|
+
},
|
|
69
|
+
async deposit(item: Item, options?: { count?: number }) {
|
|
70
|
+
return toValueResult<ContainerFailure, { moved: number }>(await call("container.deposit", { item, count: options?.count ?? null }), r => ({ moved: r.moved }));
|
|
71
|
+
},
|
|
72
|
+
async withdraw(item: Item, options?: { count?: number }) {
|
|
73
|
+
return toValueResult<ContainerFailure, { moved: number }>(await call("container.withdraw", { item, count: options?.count ?? null }), r => ({ moved: r.moved }));
|
|
74
|
+
},
|
|
75
|
+
async close() {
|
|
76
|
+
value(await call("container.close"));
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** `bot.loop` and `profile.loop`: repeat until the scope stops, with a floor between runs and backoff on errors. */
|
|
82
|
+
export async function loop(scope: Scope, host: HandleHost, bot: string | null, body: () => unknown, every?: Duration): Promise<never> {
|
|
83
|
+
const floor = every ? Math.max(toMilliseconds(every), 50) : 50;
|
|
84
|
+
let failures = 0;
|
|
85
|
+
for (;;) {
|
|
86
|
+
scope.check();
|
|
87
|
+
const started = Date.now();
|
|
88
|
+
try {
|
|
89
|
+
await body();
|
|
90
|
+
failures = 0;
|
|
91
|
+
} catch (e) {
|
|
92
|
+
if (isStopped(e)) throw e;
|
|
93
|
+
failures++;
|
|
94
|
+
host.logError(bot, e);
|
|
95
|
+
await scope.sleep(Math.min(60_000, 1000 * 2 ** Math.min(failures - 1, 6)));
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const left = floor - (Date.now() - started);
|
|
99
|
+
await scope.sleep(left > 0 ? left : 0);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
class BotPluginsHandle implements BotPlugins {
|
|
104
|
+
constructor(private readonly scope: Scope, private readonly host: HandleHost, private readonly id: string) {}
|
|
105
|
+
|
|
106
|
+
async start(plugin: BuiltInPlugin): Promise<Result<any>> {
|
|
107
|
+
return toResult(await this.host.call(this.scope, this.id, "plugins.start", { plugin }));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async stop(plugin: BuiltInPlugin): Promise<Result<any>> {
|
|
111
|
+
return toResult(await this.host.call(this.scope, this.id, "plugins.stop", { plugin }));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A bot of the profile as seen from a scope: live name and state from the runtime's bot list. */
|
|
116
|
+
export class ProfileBotHandle implements ProfileBot {
|
|
117
|
+
readonly plugins: BotPlugins;
|
|
118
|
+
|
|
119
|
+
constructor(protected readonly scope: Scope, protected readonly host: HandleHost, readonly id: string) {
|
|
120
|
+
this.plugins = new BotPluginsHandle(scope, host, id);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private get info(): BotInfo {
|
|
124
|
+
return this.host.botInfo(this.id) ?? { id: this.id, name: "", uuid: "", connected: false, enabled: false };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
get name(): string { return this.info.name; }
|
|
128
|
+
get uuid(): string { return this.info.uuid; }
|
|
129
|
+
get connected(): boolean { return this.info.connected; }
|
|
130
|
+
get enabled(): boolean { return this.info.enabled; }
|
|
131
|
+
|
|
132
|
+
async connect(): Promise<Result<any>> {
|
|
133
|
+
return toResult(await this.host.call(this.scope, this.id, "bot.connect"));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async disconnect(): Promise<Result<any>> {
|
|
137
|
+
return toResult(await this.host.call(this.scope, this.id, "bot.disconnect"));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async reconnect(options?: { after?: Duration }): Promise<Result<any>> {
|
|
141
|
+
return toResult(await this.host.call(this.scope, this.id, "bot.reconnect", { afterMs: options?.after ? toMilliseconds(options.after) : 0 }));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
toString(): string {
|
|
145
|
+
return this.name || this.id;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export class BotHandle extends ProfileBotHandle implements Bot {
|
|
150
|
+
readonly world: World;
|
|
151
|
+
readonly entities: Entities;
|
|
152
|
+
readonly inventory: Inventory;
|
|
153
|
+
readonly containers: Containers;
|
|
154
|
+
|
|
155
|
+
constructor(scope: Scope, host: HandleHost, id: string, readonly version: string) {
|
|
156
|
+
super(scope, host, id);
|
|
157
|
+
const call = (op: string, args?: Record<string, unknown>) => host.call(scope, id, op, args);
|
|
158
|
+
|
|
159
|
+
this.world = {
|
|
160
|
+
async block(position) {
|
|
161
|
+
const raw = value<any>(await call("world.block", vec(position)));
|
|
162
|
+
return raw ? toBlockInfo(raw) : null;
|
|
163
|
+
},
|
|
164
|
+
async findBlocks(query) {
|
|
165
|
+
const blocks = Array.isArray(query.block) ? [...query.block] : [query.block];
|
|
166
|
+
if (blocks.length === 0) throw new TypeError("findBlocks needs at least one block");
|
|
167
|
+
const raw = value<any[]>(await call("world.findBlocks", {
|
|
168
|
+
blocks,
|
|
169
|
+
state: query.state ?? {},
|
|
170
|
+
radius: query.radius ?? 16,
|
|
171
|
+
limit: query.limit ?? 16,
|
|
172
|
+
from: query.from ? vec(query.from) : null,
|
|
173
|
+
}));
|
|
174
|
+
return raw.map(toBlockInfo);
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
this.entities = {
|
|
179
|
+
async nearby(query = {}) {
|
|
180
|
+
const types = query.type === undefined ? null : Array.isArray(query.type) ? [...query.type] : [query.type as Entity];
|
|
181
|
+
const raw = value<any[]>(await call("entities.nearby", { types, radius: query.radius ?? 16, limit: query.limit ?? 32 }));
|
|
182
|
+
return raw.map(toEntityInfo);
|
|
183
|
+
},
|
|
184
|
+
async players() {
|
|
185
|
+
return value<PlayerInfo[]>(await call("entities.players"));
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
this.inventory = {
|
|
190
|
+
async items() {
|
|
191
|
+
return value<ItemStack[]>(await call("inventory.items"));
|
|
192
|
+
},
|
|
193
|
+
async held() {
|
|
194
|
+
return value<ItemStack | null>(await call("inventory.held"));
|
|
195
|
+
},
|
|
196
|
+
async count(item: Item) {
|
|
197
|
+
const items = value<ItemStack[]>(await call("inventory.items"));
|
|
198
|
+
return items.filter(s => s.item === item).reduce((n, s) => n + s.count, 0);
|
|
199
|
+
},
|
|
200
|
+
async equip(item: Item, slot?: EquipmentSlot) {
|
|
201
|
+
return toResult(await call("inventory.equip", { item, slot: slot ?? "Hand" }));
|
|
202
|
+
},
|
|
203
|
+
async drop(item: Item, options?: { count?: number }) {
|
|
204
|
+
return toResult(await call("inventory.drop", { item, count: options?.count ?? null }));
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
this.containers = {
|
|
209
|
+
async open(position: Vec3) {
|
|
210
|
+
return toValueResult<ContainerFailure, Container>(await call("container.open", vec(position)), raw => containerHandle(call, raw));
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async craft(item: Item, options?: { count?: number; table?: Vec3 }) {
|
|
216
|
+
return toValueResult<CraftFailure, { crafted: number }>(
|
|
217
|
+
await this.call("bot.craft", { item, count: options?.count ?? 1, table: options?.table ? vec(options.table) : null }),
|
|
218
|
+
raw => ({ crafted: raw.crafted }),
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async recipes(item: Item): Promise<Recipe[]> {
|
|
223
|
+
return value<Recipe[]>(await this.call("bot.recipes", { item }));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
private call(op: string, args?: Record<string, unknown>): Promise<CallOutcome> {
|
|
227
|
+
return this.host.call(this.scope, this.id, op, args);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
on<E extends BotEvent>(event: E, listener: Listener<BotEventData[E]>): () => void {
|
|
231
|
+
return this.host.subscribe(this.scope, this.id, event, listener as (data: unknown) => unknown);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async status(): Promise<BotStatus> {
|
|
235
|
+
return value<BotStatus>(await this.call("bot.status"));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async position(): Promise<Position> {
|
|
239
|
+
return toPosition(value(await this.call("bot.position")));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async supports(id: Block | Item | Entity): Promise<boolean> {
|
|
243
|
+
return value<boolean>(await this.call("bot.supports", { id }));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async goto(target: Vec3, options?: { within?: number; timeout?: Duration }): Promise<Result<any>> {
|
|
247
|
+
return toResult(await this.call("bot.goto", { ...vec(target), within: options?.within ?? 0, timeoutMs: options?.timeout ? toMilliseconds(options.timeout) : null }));
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async follow(entity: EntityInfo | number, options?: { distance?: number; timeout?: Duration }): Promise<Result<any>> {
|
|
251
|
+
return toResult(await this.call("bot.follow", { entity: entityId(entity), distance: options?.distance ?? 2, timeoutMs: options?.timeout ? toMilliseconds(options.timeout) : null }));
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async stopMoving(): Promise<void> {
|
|
255
|
+
value(await this.call("bot.stopMoving"));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async lookAt(target: Vec3): Promise<void> {
|
|
259
|
+
value(await this.call("bot.lookAt", vec(target)));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async jump(): Promise<void> {
|
|
263
|
+
value(await this.call("bot.jump"));
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async dig(position: Vec3): Promise<Result<any>> {
|
|
267
|
+
return toResult(await this.call("bot.dig", vec(position)));
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async place(position: Vec3, item: Item): Promise<Result<any>> {
|
|
271
|
+
return toResult(await this.call("bot.place", { ...vec(position), item }));
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async activateBlock(position: Vec3): Promise<Result<any>> {
|
|
275
|
+
return toResult(await this.call("bot.activateBlock", vec(position)));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async useItem(): Promise<Result<any>> {
|
|
279
|
+
return toResult(await this.call("bot.useItem"));
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async attack(entity: EntityInfo | number): Promise<Result<any>> {
|
|
283
|
+
return toResult(await this.call("bot.attack", { entity: entityId(entity) }));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async say(message: string): Promise<void> {
|
|
287
|
+
if (typeof message !== "string" || message.length === 0) throw new TypeError("bot.say needs a non-empty message");
|
|
288
|
+
if (message.startsWith("/")) throw new TypeError(`bot.say doesn't run commands; use bot.command("${message.slice(1)}") (needs Permission.Commands)`);
|
|
289
|
+
value(await this.call("bot.say", { text: message }));
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async command(command: string): Promise<void> {
|
|
293
|
+
const text = command.startsWith("/") ? command.slice(1) : command;
|
|
294
|
+
if (text.trim().length === 0) throw new TypeError("bot.command needs a command, e.g. bot.command(\"home\")");
|
|
295
|
+
value(await this.call("bot.command", { command: text }));
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
wait(duration: Duration): Promise<void> {
|
|
299
|
+
return this.scope.sleep(toMilliseconds(duration));
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
loop(body: () => unknown, options?: { every?: Duration }): Promise<never> {
|
|
303
|
+
return loop(this.scope, this.host, this.id, body, options?.every);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export class ProfileHandle implements Profile {
|
|
308
|
+
constructor(
|
|
309
|
+
private readonly scope: Scope,
|
|
310
|
+
private readonly host: HandleHost,
|
|
311
|
+
readonly id: string,
|
|
312
|
+
readonly name: string,
|
|
313
|
+
private readonly list: () => readonly BotInfo[],
|
|
314
|
+
) {}
|
|
315
|
+
|
|
316
|
+
bots(): readonly ProfileBot[] {
|
|
317
|
+
return this.list().map(b => this.host.profileBot(b.id));
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
bot(idNameOrUuid: string): ProfileBot | undefined {
|
|
321
|
+
const needle = idNameOrUuid.toLowerCase();
|
|
322
|
+
const info = this.list().find(b => b.id === idNameOrUuid || b.uuid.toLowerCase() === needle || b.name.toLowerCase() === needle);
|
|
323
|
+
return info ? this.host.profileBot(info.id) : undefined;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
on<E extends ProfileEvent>(event: E, listener: Listener<ProfileEventData[E]>): () => void {
|
|
327
|
+
return this.host.subscribe(this.scope, null, event, listener as (data: unknown) => unknown);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
wait(duration: Duration): Promise<void> {
|
|
331
|
+
return this.scope.sleep(toMilliseconds(duration));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
loop(body: () => unknown, options?: { every?: Duration }): Promise<never> {
|
|
335
|
+
return loop(this.scope, this.host, null, body, options?.every);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Transport } from "./connection.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Two transports joined back to back, for tests and the fake bot: what one side sends, the other receives
|
|
5
|
+
* on a later microtask, as over a real socket.
|
|
6
|
+
*/
|
|
7
|
+
export function memoryTransportPair(): [Transport, Transport] {
|
|
8
|
+
const a = new MemoryTransport();
|
|
9
|
+
const b = new MemoryTransport();
|
|
10
|
+
a.peer = b;
|
|
11
|
+
b.peer = a;
|
|
12
|
+
return [a, b];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
class MemoryTransport implements Transport {
|
|
16
|
+
peer: MemoryTransport | null = null;
|
|
17
|
+
onmessage: ((text: string) => void) | null = null;
|
|
18
|
+
onclose: ((code: number, reason: string) => void) | null = null;
|
|
19
|
+
private open = true;
|
|
20
|
+
|
|
21
|
+
send(text: string): void {
|
|
22
|
+
if (!this.open) return;
|
|
23
|
+
const peer = this.peer;
|
|
24
|
+
queueMicrotask(() => {
|
|
25
|
+
if (peer?.open) peer.onmessage?.(text);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
close(code = 1000, reason = ""): void {
|
|
30
|
+
if (!this.open) return;
|
|
31
|
+
this.open = false;
|
|
32
|
+
const peer = this.peer;
|
|
33
|
+
queueMicrotask(() => {
|
|
34
|
+
this.onclose?.(code, reason);
|
|
35
|
+
if (peer?.open) {
|
|
36
|
+
peer.open = false;
|
|
37
|
+
peer.onclose?.(code, reason);
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +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.1.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
|
+
}
|