@minecraftbot-com/plugin 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/AGENTS.md +188 -0
  2. package/README.md +47 -3
  3. package/dist/api.d.ts +354 -0
  4. package/dist/api.js +2 -0
  5. package/dist/cli/api.d.ts +49 -0
  6. package/dist/cli/api.js +69 -0
  7. package/dist/cli/build.d.ts +24 -0
  8. package/dist/cli/build.js +72 -0
  9. package/dist/cli/check.d.ts +17 -0
  10. package/dist/cli/check.js +99 -0
  11. package/dist/cli/config.d.ts +11 -0
  12. package/dist/cli/config.js +38 -0
  13. package/dist/cli/create.d.ts +2 -0
  14. package/dist/cli/create.js +39 -0
  15. package/dist/cli/deploy.d.ts +13 -0
  16. package/dist/cli/deploy.js +51 -0
  17. package/dist/cli/dev-mcp.d.ts +36 -0
  18. package/dist/cli/dev-mcp.js +101 -0
  19. package/dist/cli/dev.d.ts +15 -0
  20. package/dist/cli/dev.js +261 -0
  21. package/dist/cli/fetch-guard.d.ts +7 -0
  22. package/dist/cli/fetch-guard.js +66 -0
  23. package/dist/cli/main.d.ts +2 -0
  24. package/dist/cli/main.js +119 -0
  25. package/dist/cli/mcp.d.ts +24 -0
  26. package/dist/cli/mcp.js +136 -0
  27. package/dist/cli/output.d.ts +11 -0
  28. package/dist/cli/output.js +25 -0
  29. package/dist/cli/test.d.ts +2 -0
  30. package/dist/cli/test.js +39 -0
  31. package/dist/errors.d.ts +22 -0
  32. package/dist/errors.js +35 -0
  33. package/dist/generated/block-states.d.ts +4087 -0
  34. package/dist/generated/block-states.js +2 -0
  35. package/dist/generated/blocks.d.ts +1289 -0
  36. package/dist/generated/blocks.js +1291 -0
  37. package/dist/generated/contracts.d.ts +304 -0
  38. package/dist/generated/contracts.js +327 -0
  39. package/dist/generated/effects.d.ts +43 -0
  40. package/dist/generated/effects.js +45 -0
  41. package/dist/generated/entities.d.ts +164 -0
  42. package/dist/generated/entities.js +166 -0
  43. package/dist/generated/items.d.ts +1661 -0
  44. package/dist/generated/items.js +1663 -0
  45. package/dist/generated/operations.d.ts +7 -0
  46. package/dist/generated/operations.js +65 -0
  47. package/dist/generated/permission-labels.d.ts +3 -0
  48. package/dist/generated/permission-labels.js +17 -0
  49. package/dist/generated/version.d.ts +2 -0
  50. package/dist/generated/version.js +3 -0
  51. package/dist/host/index.d.ts +7 -0
  52. package/dist/host/index.js +5 -0
  53. package/dist/hosted/fetch.d.ts +53 -0
  54. package/dist/hosted/fetch.js +216 -0
  55. package/dist/hosted/index.d.ts +3 -0
  56. package/dist/hosted/index.js +81 -0
  57. package/dist/index.d.ts +19 -0
  58. package/dist/index.js +13 -0
  59. package/dist/permissions.d.ts +11 -0
  60. package/dist/permissions.js +18 -0
  61. package/dist/plugin.d.ts +86 -0
  62. package/dist/plugin.js +26 -0
  63. package/dist/protocol.d.ts +167 -0
  64. package/dist/protocol.js +4 -0
  65. package/dist/runtime/connection.d.ts +52 -0
  66. package/dist/runtime/connection.js +132 -0
  67. package/dist/runtime/handles.d.ts +95 -0
  68. package/dist/runtime/handles.js +289 -0
  69. package/dist/runtime/memory-transport.d.ts +6 -0
  70. package/dist/runtime/memory-transport.js +39 -0
  71. package/dist/runtime/runtime.d.ts +57 -0
  72. package/dist/runtime/runtime.js +265 -0
  73. package/dist/runtime/scope.d.ts +25 -0
  74. package/dist/runtime/scope.js +94 -0
  75. package/dist/runtime/storage-runtime.d.ts +10 -0
  76. package/dist/runtime/storage-runtime.js +131 -0
  77. package/dist/settings.d.ts +111 -0
  78. package/dist/settings.js +78 -0
  79. package/dist/storage.d.ts +78 -0
  80. package/dist/storage.js +24 -0
  81. package/dist/testing/fake-container.d.ts +175 -0
  82. package/dist/testing/fake-container.js +483 -0
  83. package/dist/testing/index.d.ts +37 -0
  84. package/dist/testing/index.js +54 -0
  85. package/dist/types.d.ts +65 -0
  86. package/dist/types.js +54 -0
  87. package/llms.txt +11 -0
  88. package/package.json +60 -4
  89. package/src/api.ts +337 -0
  90. package/src/cli/api.ts +105 -0
  91. package/src/cli/build.ts +83 -0
  92. package/src/cli/check.ts +104 -0
  93. package/src/cli/config.ts +48 -0
  94. package/src/cli/create.ts +38 -0
  95. package/src/cli/deploy.ts +60 -0
  96. package/src/cli/dev-mcp.ts +131 -0
  97. package/src/cli/dev.ts +272 -0
  98. package/src/cli/fetch-guard.ts +61 -0
  99. package/src/cli/main.ts +120 -0
  100. package/src/cli/mcp.ts +168 -0
  101. package/src/cli/output.ts +30 -0
  102. package/src/cli/test.ts +38 -0
  103. package/src/errors.ts +34 -0
  104. package/src/generated/block-states.ts +892 -0
  105. package/src/generated/blocks.ts +1291 -0
  106. package/src/generated/contracts.ts +329 -0
  107. package/src/generated/effects.ts +45 -0
  108. package/src/generated/entities.ts +166 -0
  109. package/src/generated/items.ts +1663 -0
  110. package/src/generated/operations.ts +69 -0
  111. package/src/generated/permission-labels.ts +19 -0
  112. package/src/generated/version.ts +3 -0
  113. package/src/host/index.ts +9 -0
  114. package/src/hosted/fetch.ts +224 -0
  115. package/src/hosted/index.ts +121 -0
  116. package/src/index.ts +34 -0
  117. package/src/permissions.ts +23 -0
  118. package/src/plugin.ts +105 -0
  119. package/src/protocol.ts +107 -0
  120. package/src/runtime/connection.ts +167 -0
  121. package/src/runtime/handles.ts +337 -0
  122. package/src/runtime/memory-transport.ts +41 -0
  123. package/src/runtime/runtime.ts +281 -0
  124. package/src/runtime/scope.ts +101 -0
  125. package/src/runtime/storage-runtime.ts +138 -0
  126. package/src/settings.ts +118 -0
  127. package/src/storage.ts +82 -0
  128. package/src/testing/fake-container.ts +571 -0
  129. package/src/testing/index.ts +70 -0
  130. package/src/types.ts +88 -0
  131. package/templates/basic/AGENTS.md +32 -0
  132. package/templates/basic/README.md +14 -0
  133. package/templates/basic/gitignore +3 -0
  134. package/templates/basic/package.json +19 -0
  135. package/templates/basic/src/index.ts +20 -0
  136. package/templates/basic/test/plugin.test.ts +14 -0
  137. package/templates/basic/tsconfig.json +14 -0
@@ -0,0 +1,107 @@
1
+ // The wire protocol between a plugin and the bot container (protocol v1). JSON text frames, one websocket
2
+ // per running plugin instance. The bot container is the authority: it checks every frame, so anything here
3
+ // is a convenience for the SDK, not a guarantee.
4
+
5
+ export const PROTOCOL_VERSION = 1;
6
+
7
+ /** The manifest the CLI builds from `definePlugin` and the plugin sends in `hello`. */
8
+ export interface Manifest {
9
+ name: string;
10
+ version: string;
11
+ permissions: string[];
12
+ exclusive: string[];
13
+ settings: Record<string, SettingSchema>;
14
+ storage: Record<string, StorageSchema>;
15
+ /** True when the plugin defines `runProfile`. */
16
+ profile: boolean;
17
+ }
18
+
19
+ export interface SettingSchema {
20
+ type: "text" | "number" | "boolean" | "block" | "item" | "entity" | "url" | "secret" | "select" | "radius" | "position" | "list";
21
+ label: string;
22
+ description?: string;
23
+ optional?: boolean;
24
+ default?: unknown;
25
+ min?: number;
26
+ max?: number;
27
+ options?: unknown[];
28
+ /** `url`: the hosts a user may enter. Empty or missing means any public HTTPS host. */
29
+ hosts?: string[];
30
+ secret?: boolean;
31
+ /** `list`: the schema of one entry. */
32
+ of?: SettingSchema;
33
+ }
34
+
35
+ export interface StorageSchema {
36
+ kind: "value" | "map";
37
+ scope: string;
38
+ default?: unknown;
39
+ }
40
+
41
+ export interface Limits {
42
+ callsPerSecond: number;
43
+ concurrentCalls: number;
44
+ frameBytes: number;
45
+ eventQueue: number;
46
+ storageBytes: number;
47
+ storageValueBytes: number;
48
+ }
49
+
50
+ export interface BotInfo {
51
+ id: string;
52
+ name: string;
53
+ uuid: string;
54
+ connected: boolean;
55
+ enabled: boolean;
56
+ }
57
+
58
+ export interface ProfileInfo {
59
+ id: string;
60
+ name: string;
61
+ }
62
+
63
+ // ---- plugin -> container ----
64
+
65
+ /** Only honoured for dev tokens: which bots to run on and the settings to use (the dashboard doesn't know a dev session). */
66
+ export interface DevOptions {
67
+ /** Bot ids, names or uuids; null runs on every bot of the profile. */
68
+ bots: string[] | null;
69
+ settings: Record<string, unknown>;
70
+ }
71
+
72
+ export interface HelloFrame { type: "hello"; protocol: number; sdk: string; token: string; manifest: Manifest; dev?: DevOptions }
73
+ export interface CallFrame { type: "call"; id: number; bot: string | null; op: string; args: Record<string, unknown> }
74
+ export interface CancelFrame { type: "cancel"; id: number }
75
+ export interface SubscribeFrame { type: "subscribe"; bot: string | null; event: string }
76
+ export interface UnsubscribeFrame { type: "unsubscribe"; bot: string | null; event: string }
77
+ export interface LogFrame { type: "log"; bot: string | null; level: "debug" | "info" | "warn" | "error"; message: string }
78
+ export interface WarningFrame { type: "warning"; bot: string | null; key: string; message: string | null }
79
+ export interface StatFrame { type: "stat"; bot: string | null; key: string; value: number }
80
+ /** The plugin finished a run(bot) on its own (returned or threw), so the container can show it stopped. */
81
+ export interface DoneFrame { type: "done"; bot: string | null; error: string | null }
82
+
83
+ export type PluginFrame = HelloFrame | CallFrame | CancelFrame | SubscribeFrame | UnsubscribeFrame | LogFrame | WarningFrame | StatFrame | DoneFrame;
84
+
85
+ // ---- container -> plugin ----
86
+
87
+ export interface WelcomeFrame {
88
+ type: "welcome";
89
+ installation: string;
90
+ mode: "Dev" | "Hosted";
91
+ profile: ProfileInfo;
92
+ bots: BotInfo[];
93
+ granted: string[];
94
+ settings: Record<string, unknown>;
95
+ limits: Limits;
96
+ }
97
+ export interface RejectedFrame { type: "rejected"; reason: string; message: string }
98
+ export interface ResultFrame { type: "result"; id: number; ok: boolean; value?: unknown; failure?: string; message?: string }
99
+ export interface ErrorFrame { type: "error"; id: number | null; code: string; message: string }
100
+ /** `version` is the server's Minecraft version for a bot. */
101
+ export interface StartFrame { type: "start"; bot: string | null; settings: Record<string, unknown>; version?: string }
102
+ export interface StopFrame { type: "stop"; bot: string | null; reason: string }
103
+ export interface EventFrame { type: "event"; bot: string | null; event: string; data: unknown }
104
+ export interface DroppedFrame { type: "dropped"; count: number }
105
+ export interface BotsFrame { type: "bots"; bots: BotInfo[] }
106
+
107
+ export type ContainerFrame = WelcomeFrame | RejectedFrame | ResultFrame | ErrorFrame | StartFrame | StopFrame | EventFrame | DroppedFrame | BotsFrame;
@@ -0,0 +1,167 @@
1
+ import { PermissionDeniedError, PluginError, StoppedError } from "../errors.js";
2
+ import {
3
+ PROTOCOL_VERSION,
4
+ type ContainerFrame,
5
+ type DevOptions,
6
+ type Manifest,
7
+ type PluginFrame,
8
+ type WelcomeFrame,
9
+ } from "../protocol.js";
10
+ import type { Scope } from "./scope.js";
11
+
12
+ /** What carries frames: a websocket locally, the runner's host functions when hosted, memory in tests. */
13
+ export interface Transport {
14
+ send(text: string): void;
15
+ close(code?: number, reason?: string): void;
16
+ /** Set by the connection before the first frame arrives. */
17
+ onmessage: ((text: string) => void) | null;
18
+ onclose: ((code: number, reason: string) => void) | null;
19
+ }
20
+
21
+ /** The outcome of a call, before the bot API turns it into a value or a Result. */
22
+ export type CallOutcome = { ok: true; value: unknown } | { ok: false; failure: string; message: string };
23
+
24
+ export interface ConnectionHandlers {
25
+ start(bot: string | null, settings: Record<string, unknown>, version: string): void;
26
+ stop(bot: string | null, reason: string): void;
27
+ event(bot: string | null, event: string, data: unknown): void;
28
+ bots(frame: Extract<ContainerFrame, { type: "bots" }>): void;
29
+ dropped(count: number): void;
30
+ /** The connection closed; every scope is stopped by the caller. */
31
+ closed(code: number, reason: string): void;
32
+ }
33
+
34
+ interface Pending {
35
+ resolve(outcome: CallOutcome): void;
36
+ reject(error: Error): void;
37
+ }
38
+
39
+ /** One plugin instance's socket: the hello handshake, call ids, and routing of what comes back. */
40
+ export class Connection {
41
+ private nextId = 1;
42
+ private readonly pending = new Map<number, Pending>();
43
+ private handlers: ConnectionHandlers | null = null;
44
+ private welcomeWaiter: { resolve(w: WelcomeFrame): void; reject(e: Error): void } | null = null;
45
+ private closed = false;
46
+
47
+ constructor(private readonly transport: Transport) {
48
+ transport.onmessage = text => this.receive(text);
49
+ transport.onclose = (code, reason) => this.onClose(code, reason);
50
+ }
51
+
52
+ /** Sends `hello` and waits for `welcome`. Rejects with the container's reason if it refuses. */
53
+ open(token: string, manifest: Manifest, sdk: string, dev?: DevOptions): Promise<WelcomeFrame> {
54
+ return new Promise<WelcomeFrame>((resolve, reject) => {
55
+ this.welcomeWaiter = { resolve, reject };
56
+ this.send({ type: "hello", protocol: PROTOCOL_VERSION, sdk, token, manifest, ...(dev ? { dev } : {}) });
57
+ });
58
+ }
59
+
60
+ attach(handlers: ConnectionHandlers): void {
61
+ this.handlers = handlers;
62
+ }
63
+
64
+ send(frame: PluginFrame): void {
65
+ if (this.closed) return;
66
+ this.transport.send(JSON.stringify(frame));
67
+ }
68
+
69
+ /**
70
+ * Sends a call and waits for its result within `scope`. When the scope stops first, the call is cancelled
71
+ * on the container and the promise rejects with StoppedError.
72
+ */
73
+ call(scope: Scope, bot: string | null, op: string, args: Record<string, unknown>): Promise<CallOutcome> {
74
+ scope.check();
75
+ if (this.closed) return Promise.reject(new StoppedError("Disconnected"));
76
+ const id = this.nextId++;
77
+ return new Promise<CallOutcome>((resolve, reject) => {
78
+ const cancel = () => {
79
+ if (this.pending.delete(id)) {
80
+ this.send({ type: "cancel", id });
81
+ reject(new StoppedError(scope.reason ?? "Stopped"));
82
+ }
83
+ };
84
+ scope.onStop(cancel);
85
+ this.pending.set(id, {
86
+ resolve: outcome => {
87
+ scope.forget(cancel);
88
+ resolve(outcome);
89
+ },
90
+ reject: error => {
91
+ scope.forget(cancel);
92
+ reject(error);
93
+ },
94
+ });
95
+ this.send({ type: "call", id, bot, op, args });
96
+ });
97
+ }
98
+
99
+ close(): void {
100
+ this.transport.close(1000, "Plugin stopped");
101
+ }
102
+
103
+ private receive(text: string): void {
104
+ let frame: ContainerFrame;
105
+ try {
106
+ frame = JSON.parse(text) as ContainerFrame;
107
+ } catch {
108
+ return;
109
+ }
110
+ switch (frame.type) {
111
+ case "welcome":
112
+ this.welcomeWaiter?.resolve(frame);
113
+ this.welcomeWaiter = null;
114
+ break;
115
+ case "rejected":
116
+ this.welcomeWaiter?.reject(new PluginError(frame.reason, frame.message));
117
+ this.welcomeWaiter = null;
118
+ break;
119
+ case "result": {
120
+ const p = this.pending.get(frame.id);
121
+ if (!p) break;
122
+ this.pending.delete(frame.id);
123
+ p.resolve(frame.ok ? { ok: true, value: frame.value } : { ok: false, failure: frame.failure ?? "Failed", message: frame.message ?? "" });
124
+ break;
125
+ }
126
+ case "error": {
127
+ const error = frame.code === "PermissionDenied" ? new PermissionDeniedError(frame.message) : new PluginError(frame.code, frame.message);
128
+ if (frame.id === null) {
129
+ // A connection-level error (for example a frame the container refused); log through the handler.
130
+ this.handlers?.event(null, "__error", { code: frame.code, message: frame.message });
131
+ break;
132
+ }
133
+ const p = this.pending.get(frame.id);
134
+ if (!p) break;
135
+ this.pending.delete(frame.id);
136
+ p.reject(error);
137
+ break;
138
+ }
139
+ case "start":
140
+ this.handlers?.start(frame.bot, frame.settings ?? {}, frame.version ?? "");
141
+ break;
142
+ case "stop":
143
+ this.handlers?.stop(frame.bot, frame.reason);
144
+ break;
145
+ case "event":
146
+ this.handlers?.event(frame.bot, frame.event, frame.data);
147
+ break;
148
+ case "bots":
149
+ this.handlers?.bots(frame);
150
+ break;
151
+ case "dropped":
152
+ this.handlers?.dropped(frame.count);
153
+ break;
154
+ }
155
+ }
156
+
157
+ private onClose(code: number, reason: string): void {
158
+ if (this.closed) return;
159
+ this.closed = true;
160
+ const error = new StoppedError("Disconnected");
161
+ for (const p of this.pending.values()) p.reject(error);
162
+ this.pending.clear();
163
+ this.welcomeWaiter?.reject(new PluginError("Disconnected", reason || `Connection closed (${code})`));
164
+ this.welcomeWaiter = null;
165
+ this.handlers?.closed(code, reason);
166
+ }
167
+ }
@@ -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
+ }