@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
package/src/cli/api.ts ADDED
@@ -0,0 +1,105 @@
1
+ import { hostname } from "node:os";
2
+ import { apiUrl, readCredentials } from "./config.js";
3
+ import { fail } from "./output.js";
4
+
5
+ export interface DeviceStart {
6
+ deviceCode: string;
7
+ userCode: string;
8
+ verificationUrl: string;
9
+ interval: number;
10
+ expiresIn: number;
11
+ }
12
+
13
+ export interface ProfileEntry {
14
+ id: string;
15
+ name: string;
16
+ running: boolean;
17
+ }
18
+
19
+ export interface DevToken {
20
+ token: string;
21
+ address: string;
22
+ profileId: string;
23
+ profileName: string;
24
+ expiresAt: string;
25
+ }
26
+
27
+ async function request<T>(method: string, path: string, body?: unknown, auth = false): Promise<{ status: number; data: T | { message?: string } }> {
28
+ const headers: Record<string, string> = { "content-type": "application/json", "user-agent": "minebot-cli" };
29
+ if (auth) {
30
+ const credentials = readCredentials();
31
+ if (!credentials) fail("You're not signed in.", "Run `minebot login` first.");
32
+ headers.authorization = `Bearer ${credentials.token}`;
33
+ }
34
+ let response: Response;
35
+ try {
36
+ response = await fetch(`${apiUrl()}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
37
+ } catch (e) {
38
+ fail(`Couldn't reach ${apiUrl()}: ${(e as Error).message}`, "Check your internet connection, or MINEBOT_API_URL if you set it.");
39
+ }
40
+ const text = await response.text();
41
+ let data: unknown = {};
42
+ try {
43
+ data = text ? JSON.parse(text) : {};
44
+ } catch {
45
+ data = { message: text.slice(0, 200) };
46
+ }
47
+ return { status: response.status, data: data as T };
48
+ }
49
+
50
+ function message(data: unknown, fallback: string): string {
51
+ return (data as { message?: string })?.message ?? fallback;
52
+ }
53
+
54
+ export async function startDevice(): Promise<DeviceStart> {
55
+ const r = await request<DeviceStart>("POST", "/plugins/cli/device", { clientName: `minebot CLI on ${hostname()}` });
56
+ if (r.status !== 200) fail(message(r.data, `Sign-in failed (HTTP ${r.status})`));
57
+ return r.data as DeviceStart;
58
+ }
59
+
60
+ export async function pollDevice(deviceCode: string): Promise<{ status: string; token: string | null }> {
61
+ const r = await request<{ status: string; token: string | null }>("POST", "/plugins/cli/token", { deviceCode });
62
+ if (r.status !== 200) return { status: "pending", token: null };
63
+ return r.data as { status: string; token: string | null };
64
+ }
65
+
66
+ export async function listProfiles(): Promise<ProfileEntry[]> {
67
+ const r = await request<ProfileEntry[]>("GET", "/plugins/cli/profiles", undefined, true);
68
+ if (r.status === 401) fail(message(r.data, "Your sign-in expired."), "Run `minebot login` again.");
69
+ if (r.status !== 200) fail(message(r.data, `Couldn't list your profiles (HTTP ${r.status})`));
70
+ return r.data as ProfileEntry[];
71
+ }
72
+
73
+ export interface DeployRequest {
74
+ manifest: unknown;
75
+ bundle: string;
76
+ sdk: string;
77
+ profile?: string;
78
+ settings?: Record<string, unknown>;
79
+ bots?: string[];
80
+ }
81
+
82
+ export interface DeployResult {
83
+ pluginId: string;
84
+ name: string;
85
+ version: string;
86
+ bundleHash: string;
87
+ newVersion: boolean;
88
+ installations: { id: string; profileId: string; profileName: string; enabled: boolean }[];
89
+ dashboard: string;
90
+ }
91
+
92
+ export async function deployBundle(body: DeployRequest): Promise<DeployResult> {
93
+ const r = await request<DeployResult>("POST", "/plugins/cli/deploy", body, true);
94
+ if (r.status === 401) fail(message(r.data, "Your sign-in expired."), "Run `minebot login` again.");
95
+ if (r.status !== 200) fail(message(r.data, `The deploy failed (HTTP ${r.status})`));
96
+ return r.data as DeployResult;
97
+ }
98
+
99
+ export async function devToken(profileId: string): Promise<DevToken> {
100
+ const r = await request<DevToken>("POST", "/plugins/cli/dev-token", { profileId }, true);
101
+ if (r.status === 401) fail(message(r.data, "Your sign-in expired."), "Run `minebot login` again.");
102
+ if (r.status === 409) fail(message(r.data, "The profile isn't running."), "Start it on the dashboard, then run `minebot dev` again.");
103
+ if (r.status !== 200) fail(message(r.data, `Couldn't get a dev token (HTTP ${r.status})`));
104
+ return r.data as DevToken;
105
+ }
@@ -0,0 +1,83 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import * as esbuild from "esbuild";
5
+ import { isDefinedPlugin, type DefinedPlugin } from "../plugin.js";
6
+ import { fail } from "./output.js";
7
+
8
+ export interface Project {
9
+ root: string;
10
+ entry: string;
11
+ name: string;
12
+ version: string;
13
+ }
14
+
15
+ /** The plugin project in the current folder: a package.json and src/index.ts (or the `minebot.entry` it names). */
16
+ export function findProject(root = process.cwd()): Project {
17
+ const packageFile = join(root, "package.json");
18
+ if (!existsSync(packageFile)) fail("No package.json here.", "Run minebot in your plugin's folder, or create one with `npx @minecraftbot-com/plugin create my-plugin`.");
19
+ const pkg = JSON.parse(readFileSync(packageFile, "utf8")) as { name?: string; version?: string; minebot?: { entry?: string } };
20
+ const entry = resolve(root, pkg.minebot?.entry ?? "src/index.ts");
21
+ if (!existsSync(entry)) fail(`No ${entry}.`, "Your plugin's code goes in src/index.ts, with `export default definePlugin({ ... })`.");
22
+ return { root, entry, name: pkg.name ?? "plugin", version: pkg.version ?? "0.0.0" };
23
+ }
24
+
25
+ /**
26
+ * The bundle `minebot dev` runs in Node: the SDK stays an import so the plugin and the CLI share one copy of it
27
+ * (errors thrown by the SDK are the classes the plugin imports).
28
+ */
29
+ export function devBuildOptions(project: Project, outfile: string): esbuild.BuildOptions {
30
+ return {
31
+ entryPoints: [project.entry],
32
+ outfile,
33
+ bundle: true,
34
+ format: "esm",
35
+ platform: "node",
36
+ target: "node22",
37
+ sourcemap: "inline",
38
+ external: ["@minecraftbot-com/plugin", "@minecraftbot-com/plugin/*"],
39
+ logLevel: "silent",
40
+ };
41
+ }
42
+
43
+ /**
44
+ * The bundle a hosted runner runs: everything included, minified, and the SDK compiled from its TypeScript
45
+ * source (the `minebot-source` condition) so enum members become plain strings and the enum objects drop out.
46
+ * It is one script (QuickJS evaluates it as a global script) that hands the plugin to `serveHosted`.
47
+ */
48
+ export function hostedBuildOptions(project: Project, outfile: string): esbuild.BuildOptions {
49
+ const entry = JSON.stringify(project.entry.replace(/\\/g, "/"));
50
+ return {
51
+ stdin: {
52
+ contents: `import plugin from ${entry};\nimport { serveHosted } from "@minecraftbot-com/plugin/hosted";\nserveHosted(plugin);\n`,
53
+ resolveDir: project.root,
54
+ sourcefile: "minebot-hosted-entry.js",
55
+ loader: "js",
56
+ },
57
+ outfile,
58
+ bundle: true,
59
+ format: "iife",
60
+ platform: "neutral",
61
+ target: "es2022",
62
+ minify: true,
63
+ treeShaking: true,
64
+ conditions: ["minebot-source"],
65
+ mainFields: ["module", "main"],
66
+ legalComments: "none",
67
+ metafile: true,
68
+ logLevel: "silent",
69
+ };
70
+ }
71
+
72
+ export function formatErrors(errors: esbuild.Message[]): string {
73
+ return errors.map(e => (e.location ? `${e.location.file}:${e.location.line}:${e.location.column}: ${e.text}` : e.text)).join("\n");
74
+ }
75
+
76
+ /** Imports a built plugin module and returns its default export, which must be `definePlugin(...)`. */
77
+ export async function loadPlugin(file: string, cacheBust: number | string = Date.now()): Promise<DefinedPlugin> {
78
+ const module = await import(`${pathToFileURL(file).href}?v=${cacheBust}`);
79
+ if (!isDefinedPlugin(module.default)) {
80
+ fail("The plugin's entry file has no plugin as its default export.", "End src/index.ts with `export default definePlugin({ name: ..., permissions: [...], async run(bot) { ... } })`.");
81
+ }
82
+ return module.default;
83
+ }
@@ -0,0 +1,104 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import * as esbuild from "esbuild";
4
+ import { PERMISSION_LABELS } from "../generated/permission-labels.js";
5
+ import { networkHost } from "../permissions.js";
6
+ import { buildManifest } from "../runtime/runtime.js";
7
+ import type { Manifest } from "../protocol.js";
8
+ import { devBuildOptions, findProject, formatErrors, hostedBuildOptions, loadPlugin } from "./build.js";
9
+ import { bold, dim, fail, green, info, warn, yellow } from "./output.js";
10
+
11
+ /** Above this a hosted plugin probably won't fit its memory after start (about 1.5 MB, mostly bundled code). */
12
+ const BUNDLE_WARNING_BYTES = 256 * 1024;
13
+
14
+ export interface Built {
15
+ manifest: Manifest;
16
+ bundle: string;
17
+ bytes: number;
18
+ }
19
+
20
+ /** Builds the manifest (by running the plugin in Node) and the hosted bundle into outDir. */
21
+ export async function buildAll(outDir: string): Promise<Built> {
22
+ const project = findProject();
23
+ mkdirSync(outDir, { recursive: true });
24
+
25
+ // The manifest comes from running the plugin's module in Node; that build stays out of the output folder.
26
+ mkdirSync(join(project.root, ".minebot"), { recursive: true });
27
+ const devFile = join(project.root, ".minebot", "probe.mjs");
28
+ try {
29
+ await esbuild.build(devBuildOptions(project, devFile));
30
+ } catch (e) {
31
+ fail(`Build failed:\n${formatErrors((e as esbuild.BuildFailure).errors ?? [])}`);
32
+ }
33
+ const plugin = await loadPlugin(devFile);
34
+ const manifest = buildManifest(plugin, project.version);
35
+
36
+ const bundle = join(outDir, "plugin.js");
37
+ let result: esbuild.BuildResult;
38
+ try {
39
+ result = await esbuild.build(hostedBuildOptions(project, bundle));
40
+ } catch (e) {
41
+ fail(`Hosted build failed:\n${formatErrors((e as esbuild.BuildFailure).errors ?? [])}`);
42
+ }
43
+ const bytes = Object.values(result.metafile!.outputs).reduce((n, o) => n + o.bytes, 0);
44
+ return { manifest, bundle, bytes };
45
+ }
46
+
47
+ /** Problems with a manifest: each is a sentence a person (or an AI) can act on. */
48
+ export function review(manifest: Manifest, bytes: number): { problems: string[]; notes: string[] } {
49
+ const problems: string[] = [];
50
+ const notes: string[] = [];
51
+ const permissions = new Set(manifest.permissions);
52
+ const hosts = manifest.permissions.map(networkHost).filter((h): h is string => h !== null);
53
+ const urlSettings = Object.entries(manifest.settings).filter(([, s]) => s.type === "url");
54
+
55
+ if (manifest.name.length > 64) problems.push("The name is longer than 64 characters.");
56
+ if (hosts.some(h => h === "*" || h.startsWith("*.") && h.split(".").length < 3)) problems.push("A network permission covers too much; name the hosts you call.");
57
+ if (permissions.has("ChatRead") && (hosts.length > 0 || urlSettings.length > 0)) {
58
+ notes.push(`Users will be told this plugin "can read chat and send it to ${[...hosts, ...urlSettings.map(([k]) => `the URL in "${k}"`)].join(", ")}".`);
59
+ }
60
+ if (permissions.has("ProfileBots")) notes.push("ProfileBots lets the plugin connect and disconnect every bot of the profile; users see that at install.");
61
+ if (manifest.exclusive.length === 0 && (permissions.has("Move") || permissions.has("Interact"))) {
62
+ notes.push("The plugin moves or digs but declares no exclusive control units; another plugin may drive the same bot at once. Add exclusive: [ControlUnit.Movement, ...].");
63
+ }
64
+ if (bytes > BUNDLE_WARNING_BYTES) {
65
+ problems.push(`The hosted bundle is ${(bytes / 1024).toFixed(0)} KB; hosted plugins have about 1.5 MB after start, and bundled libraries are the usual cause. Import only what you use.`);
66
+ }
67
+ return { problems, notes };
68
+ }
69
+
70
+ /** `minebot check`: builds the plugin as it would be uploaded and reports what users will be asked to allow. */
71
+ export async function check(): Promise<void> {
72
+ const project = findProject();
73
+ const { manifest, bytes } = await buildAll(join(project.root, ".minebot", "check"));
74
+
75
+ info(`${bold(manifest.name)} ${dim(manifest.version)}`);
76
+ info("\nUsers will be asked to allow:");
77
+ if (manifest.permissions.length === 0) info(dim(" nothing (logs, settings, storage and timers are always allowed)"));
78
+ for (const p of manifest.permissions) {
79
+ const host = networkHost(p);
80
+ info(` • ${host ? `Can send and receive data from ${host}` : PERMISSION_LABELS[p as keyof typeof PERMISSION_LABELS] ?? p}`);
81
+ }
82
+ const settings = Object.entries(manifest.settings);
83
+ if (settings.length) info(`\nSettings: ${settings.map(([k, s]) => `${k} (${s.type}${s.secret ? ", secret" : ""})`).join(", ")}`);
84
+ const storage = Object.entries(manifest.storage);
85
+ if (storage.length) info(`Storage: ${storage.map(([k, s]) => `${k} (${s.kind}, ${s.scope})`).join(", ")}`);
86
+ info(`Hosted bundle: ${(bytes / 1024).toFixed(1)} KB`);
87
+
88
+ const { problems, notes } = review(manifest, bytes);
89
+ for (const n of notes) info(`\n${yellow("note:")} ${n}`);
90
+ for (const p of problems) warn(p);
91
+ if (problems.length) process.exit(1);
92
+ info(`\n${green("ok")}`);
93
+ }
94
+
95
+ /** `minebot build`: writes dist/plugin.js (the hosted bundle) and dist/manifest.json, for upload. */
96
+ export async function build(): Promise<void> {
97
+ const project = findProject();
98
+ const outDir = join(project.root, "dist");
99
+ const { manifest, bytes } = await buildAll(outDir);
100
+ writeFileSync(join(outDir, "manifest.json"), JSON.stringify(manifest, null, 2));
101
+ const { problems } = review(manifest, bytes);
102
+ for (const p of problems) warn(p);
103
+ info(`Wrote dist/plugin.js (${(bytes / 1024).toFixed(1)} KB) and dist/manifest.json`);
104
+ }
@@ -0,0 +1,48 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync, chmodSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ /** The public API. `MINEBOT_API_URL` overrides it (for MineBot's own staging and local development). */
6
+ export const DEFAULT_API_URL = "https://api-v3.minecraftbot.com";
7
+
8
+ export interface Credentials {
9
+ apiUrl: string;
10
+ token: string;
11
+ }
12
+
13
+ function folder(): string {
14
+ return process.env.MINEBOT_CONFIG_DIR ?? join(homedir(), ".minebot");
15
+ }
16
+
17
+ function file(): string {
18
+ return join(folder(), "credentials.json");
19
+ }
20
+
21
+ export function apiUrl(): string {
22
+ return (process.env.MINEBOT_API_URL ?? readCredentials()?.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, "");
23
+ }
24
+
25
+ export function readCredentials(): Credentials | null {
26
+ try {
27
+ const parsed = JSON.parse(readFileSync(file(), "utf8")) as Credentials;
28
+ return typeof parsed.token === "string" ? parsed : null;
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+
34
+ /** Saved readable by the user only: the token lets anyone ask dev tokens for the user's profiles. */
35
+ export function saveCredentials(credentials: Credentials): string {
36
+ mkdirSync(folder(), { recursive: true, mode: 0o700 });
37
+ writeFileSync(file(), JSON.stringify(credentials, null, 2), { mode: 0o600 });
38
+ try {
39
+ chmodSync(file(), 0o600);
40
+ } catch {
41
+ // Windows has no POSIX modes; the file is in the user's profile folder.
42
+ }
43
+ return file();
44
+ }
45
+
46
+ export function deleteCredentials(): void {
47
+ rmSync(file(), { force: true });
48
+ }
@@ -0,0 +1,38 @@
1
+ import { cpSync, existsSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
2
+ import { basename, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { SDK_VERSION } from "../runtime/runtime.js";
5
+ import { bold, dim, fail, green, info } from "./output.js";
6
+
7
+ const TEMPLATES = fileURLToPath(new URL("../../templates/", import.meta.url));
8
+
9
+ /** `minebot create <folder>`: a new plugin project from the template. */
10
+ export function create(target: string | undefined, template = "basic"): void {
11
+ if (!target) fail("Name the folder: `minebot create my-plugin`.");
12
+ const folder = resolve(target);
13
+ if (existsSync(folder) && readdirSync(folder).length > 0) fail(`${folder} isn't empty.`);
14
+ const source = join(TEMPLATES, template);
15
+ if (!existsSync(source)) fail(`No template "${template}".`, `Templates: ${readdirSync(TEMPLATES).join(", ")}`);
16
+
17
+ const name = basename(folder).toLowerCase().replace(/[^a-z0-9-_.]/g, "-");
18
+ const title = basename(folder).replace(/[-_]+/g, " ").replace(/\b\w/g, c => c.toUpperCase());
19
+ cpSync(source, folder, { recursive: true });
20
+ // npm drops files named .gitignore from published packages, so the template carries it without the dot.
21
+ if (existsSync(join(folder, "gitignore"))) renameSync(join(folder, "gitignore"), join(folder, ".gitignore"));
22
+
23
+ const fill = (dir: string) => {
24
+ for (const entry of readdirSync(dir)) {
25
+ const path = join(dir, entry);
26
+ if (statSync(path).isDirectory()) fill(path);
27
+ else writeFileSync(path, readFileSync(path, "utf8").replaceAll("__NAME__", name).replaceAll("__TITLE__", title).replaceAll("__SDK_VERSION__", SDK_VERSION));
28
+ }
29
+ };
30
+ fill(folder);
31
+
32
+ info(`${green("Created")} ${bold(folder)}\n`);
33
+ info(` cd ${target}`);
34
+ info(" npm install");
35
+ info(" npx minebot login");
36
+ info(" npm run dev\n");
37
+ info(dim("src/index.ts is the plugin; AGENTS.md explains the API to AI assistants."));
38
+ }
@@ -0,0 +1,60 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { SDK_VERSION } from "../runtime/runtime.js";
4
+ import { deployBundle } from "./api.js";
5
+ import { findProject } from "./build.js";
6
+ import { buildAll, review } from "./check.js";
7
+ import { bold, cyan, dim, fail, green, info, warn } from "./output.js";
8
+
9
+ export interface DeployArgs {
10
+ /** Run it on this profile (name or id) from now on. */
11
+ profile?: string;
12
+ /** Only these bots (names or ids) on that profile; default every bot. */
13
+ bots: string[];
14
+ /** Setting values for that profile. */
15
+ settingsFile?: string;
16
+ }
17
+
18
+ /**
19
+ * `minebot deploy`: builds the hosted bundle and uploads it as the plugin's new version, so it runs on MineBot's
20
+ * servers instead of your machine. Profiles it runs on move to the new version; `--profile` adds one.
21
+ */
22
+ export async function deploy(args: DeployArgs): Promise<void> {
23
+ const project = findProject();
24
+ const { manifest, bundle, bytes } = await buildAll(join(project.root, ".minebot", "deploy"));
25
+ const { problems } = review(manifest, bytes);
26
+ if (problems.length) {
27
+ for (const p of problems) warn(p);
28
+ fail("Fix these before deploying.", "`minebot check` shows the same list.");
29
+ }
30
+ if ((args.bots.length || args.settingsFile) && !args.profile) fail("--bot and --settings need --profile.");
31
+
32
+ let settings: Record<string, unknown> | undefined;
33
+ if (args.settingsFile) {
34
+ try {
35
+ settings = JSON.parse(readFileSync(args.settingsFile, "utf8")) as Record<string, unknown>;
36
+ } catch (e) {
37
+ fail(`Couldn't read ${args.settingsFile}: ${(e as Error).message}`);
38
+ }
39
+ }
40
+
41
+ info(`Deploying ${bold(manifest.name)} ${dim(manifest.version)} (${(bytes / 1024).toFixed(1)} KB)…`);
42
+ const result = await deployBundle({
43
+ manifest,
44
+ bundle: readFileSync(bundle, "utf8"),
45
+ sdk: SDK_VERSION,
46
+ profile: args.profile,
47
+ settings,
48
+ bots: args.bots.length ? args.bots : undefined,
49
+ });
50
+
51
+ info(result.newVersion ? green(`Deployed ${result.name} ${result.version}.`) : `${result.name} ${result.version} is already deployed; nothing to upload.`);
52
+ const enabled = result.installations.filter(i => i.enabled);
53
+ if (enabled.length === 0) {
54
+ info(`\nIt doesn't run anywhere yet: ${cyan("minebot deploy --profile <name>")}, or Plugins → Custom Plugins on the dashboard.`);
55
+ return;
56
+ }
57
+ info("\nRuns on MineBot's servers whenever these profiles run:");
58
+ for (const i of enabled) info(` • ${bold(i.profileName)}`);
59
+ info(dim(`\nIts console and status are on the dashboard: ${result.dashboard}`));
60
+ }
@@ -0,0 +1,131 @@
1
+ import type { McpTool } from "./mcp.js";
2
+
3
+ export type DevLogLevel = "debug" | "info" | "warn" | "error" | "system";
4
+
5
+ /** A line of `minebot dev`: the plugin's logs, plus `system` lines for builds and connections. */
6
+ export interface DevLogLine {
7
+ seq: number;
8
+ time: string;
9
+ level: DevLogLevel;
10
+ bot: string | null;
11
+ message: string;
12
+ }
13
+
14
+ const LEVEL_ORDER: Record<DevLogLevel, number> = { debug: 0, info: 1, system: 1, warn: 2, error: 3 };
15
+
16
+ /** The last lines of a dev session, numbered so an agent can ask for what's new since it last looked. */
17
+ export class DevLog {
18
+ private readonly lines: DevLogLine[] = [];
19
+ private seq = 0;
20
+
21
+ constructor(private readonly capacity = 1000) {}
22
+
23
+ add(level: DevLogLevel, message: string, bot: string | null = null): void {
24
+ this.lines.push({ seq: ++this.seq, time: new Date().toISOString(), level, bot, message });
25
+ if (this.lines.length > this.capacity) this.lines.splice(0, this.lines.length - this.capacity);
26
+ }
27
+
28
+ /** Lines after `since` at `minLevel` or above, oldest first; `next` is the cursor for the following read. */
29
+ read(since = 0, minLevel: DevLogLevel = "debug", limit = 100): { lines: DevLogLine[]; next: number } {
30
+ const min = LEVEL_ORDER[minLevel] ?? 0;
31
+ const matching = this.lines.filter(l => l.seq > since && LEVEL_ORDER[l.level] >= min);
32
+ const lines = matching.slice(-Math.max(1, Math.min(limit, 500)));
33
+ return { lines, next: this.seq };
34
+ }
35
+ }
36
+
37
+ /** Operations `query` may run: reads only, so an agent can look around without moving or breaking anything. */
38
+ export const QUERY_OPERATIONS = [
39
+ "bot.status",
40
+ "bot.position",
41
+ "world.block",
42
+ "world.findBlocks",
43
+ "entities.nearby",
44
+ "entities.players",
45
+ "inventory.items",
46
+ "inventory.held",
47
+ "bot.recipes",
48
+ "storage.get",
49
+ "storage.entries",
50
+ ] as const;
51
+
52
+ /** What the dev MCP tools need from `minebot dev`. */
53
+ export interface DevSession {
54
+ readonly log: DevLog;
55
+ status(): unknown;
56
+ /** Rebuilds and reconnects; resolves with how that went. */
57
+ reload(): Promise<unknown>;
58
+ /** Runs a read-only operation as the plugin; `bot` is a name or id, ignored for storage. */
59
+ query(bot: string | undefined, op: string, args: Record<string, unknown>): Promise<unknown>;
60
+ }
61
+
62
+ export const DEV_MCP_INSTRUCTIONS = `This is \`minebot dev\`: a MineBot plugin (TypeScript, @minecraftbot-com/plugin) running on the developer's machine,
63
+ connected to one of their Minecraft bot profiles. It rebuilds and restarts the plugin when a source file is saved.
64
+ Use \`status\` first, \`logs\` to see what the plugin printed (pass \`since\` from the last call's \`next\`), \`reload\`
65
+ after editing if you want to wait for the result, and \`query\` to look at a bot's surroundings, inventory or the
66
+ plugin's storage. Queries run as the plugin, so they need its permissions; they never move or change anything.
67
+ The SDK's own guide for writing plugins is AGENTS.md in node_modules/@minecraftbot-com/plugin.`;
68
+
69
+ export function devTools(session: DevSession): McpTool[] {
70
+ return [
71
+ {
72
+ name: "status",
73
+ description: "The plugin, the profile it runs on, whether it's connected, its bots (and which it's running on), granted permissions, settings, and the last build's errors.",
74
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
75
+ run: () => session.status(),
76
+ },
77
+ {
78
+ name: "logs",
79
+ description: "Lines the plugin logged (log.info/warn/error/debug, with the bot), plus `system` lines for builds, connections and disconnections. Oldest first. Pass `since` = the previous call's `next` to get only new lines.",
80
+ inputSchema: {
81
+ type: "object",
82
+ properties: {
83
+ since: { type: "integer", minimum: 0, description: "Only lines after this cursor (the `next` of an earlier call)." },
84
+ level: { type: "string", enum: ["debug", "info", "warn", "error"], description: "Minimum level (default debug)." },
85
+ limit: { type: "integer", minimum: 1, maximum: 500, description: "At most this many lines, the newest (default 100)." },
86
+ },
87
+ additionalProperties: false,
88
+ },
89
+ run: args =>
90
+ session.log.read(
91
+ typeof args.since === "number" ? args.since : 0,
92
+ (args.level as DevLogLevel | undefined) ?? "debug",
93
+ typeof args.limit === "number" ? args.limit : 100,
94
+ ),
95
+ },
96
+ {
97
+ name: "reload",
98
+ description: "Rebuilds the plugin and restarts it on the profile, then reports whether the build passed and the plugin connected. Saving a file does the same on its own; use this to wait for the outcome.",
99
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
100
+ run: () => session.reload(),
101
+ },
102
+ {
103
+ name: "query",
104
+ description: [
105
+ "Runs one read-only operation on a bot as the plugin and returns the raw result ({ ok, value } or { ok: false, failure, message }).",
106
+ "The plugin must be running on the bot and hold the permission the operation needs. Arguments by operation:",
107
+ "bot.status {}; bot.position {} (WorldRead); world.block { x, y, z } (WorldRead);",
108
+ 'world.findBlocks { blocks: ["minecraft:wheat"], state?: { age: 7 }, radius?: 16, limit?: 16 } (WorldRead);',
109
+ "entities.nearby { types?: [], radius?: 16, limit?: 32 } and entities.players {} (EntitiesRead);",
110
+ "inventory.items {} and inventory.held {} (InventoryRead); bot.recipes { item: \"minecraft:bread\" } (what crafting it takes);",
111
+ 'storage.get { name, key?, bot?: "<uuid for Bot scope>" } and storage.entries { name, after?, limit? } (no bot needed).',
112
+ ].join(" "),
113
+ inputSchema: {
114
+ type: "object",
115
+ properties: {
116
+ op: { type: "string", enum: [...QUERY_OPERATIONS] },
117
+ bot: { type: "string", description: "Bot name or id (default: the first bot the plugin runs on)." },
118
+ args: { type: "object", description: "The operation's arguments (see the description).", additionalProperties: true },
119
+ },
120
+ required: ["op"],
121
+ additionalProperties: false,
122
+ },
123
+ run: args => {
124
+ const op = String(args.op);
125
+ if (!(QUERY_OPERATIONS as readonly string[]).includes(op)) throw new Error(`op must be one of ${QUERY_OPERATIONS.join(", ")}`);
126
+ const opArgs = args.args && typeof args.args === "object" ? (args.args as Record<string, unknown>) : {};
127
+ return session.query(typeof args.bot === "string" ? args.bot : undefined, op, opArgs);
128
+ },
129
+ },
130
+ ];
131
+ }