@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.
Files changed (128) hide show
  1. package/AGENTS.md +177 -0
  2. package/README.md +45 -2
  3. package/dist/api.d.ts +351 -0
  4. package/dist/api.js +2 -0
  5. package/dist/cli/api.d.ts +26 -0
  6. package/dist/cli/api.js +61 -0
  7. package/dist/cli/build.d.ts +23 -0
  8. package/dist/cli/build.js +65 -0
  9. package/dist/cli/check.d.ts +10 -0
  10. package/dist/cli/check.js +98 -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/dev-mcp.d.ts +36 -0
  16. package/dist/cli/dev-mcp.js +101 -0
  17. package/dist/cli/dev.d.ts +15 -0
  18. package/dist/cli/dev.js +261 -0
  19. package/dist/cli/fetch-guard.d.ts +7 -0
  20. package/dist/cli/fetch-guard.js +66 -0
  21. package/dist/cli/main.d.ts +2 -0
  22. package/dist/cli/main.js +112 -0
  23. package/dist/cli/mcp.d.ts +24 -0
  24. package/dist/cli/mcp.js +136 -0
  25. package/dist/cli/output.d.ts +11 -0
  26. package/dist/cli/output.js +25 -0
  27. package/dist/cli/test.d.ts +2 -0
  28. package/dist/cli/test.js +39 -0
  29. package/dist/errors.d.ts +22 -0
  30. package/dist/errors.js +35 -0
  31. package/dist/generated/block-states.d.ts +4087 -0
  32. package/dist/generated/block-states.js +2 -0
  33. package/dist/generated/blocks.d.ts +1289 -0
  34. package/dist/generated/blocks.js +1291 -0
  35. package/dist/generated/contracts.d.ts +304 -0
  36. package/dist/generated/contracts.js +327 -0
  37. package/dist/generated/effects.d.ts +43 -0
  38. package/dist/generated/effects.js +45 -0
  39. package/dist/generated/entities.d.ts +164 -0
  40. package/dist/generated/entities.js +166 -0
  41. package/dist/generated/items.d.ts +1661 -0
  42. package/dist/generated/items.js +1663 -0
  43. package/dist/generated/operations.d.ts +7 -0
  44. package/dist/generated/operations.js +65 -0
  45. package/dist/generated/permission-labels.d.ts +3 -0
  46. package/dist/generated/permission-labels.js +17 -0
  47. package/dist/generated/version.d.ts +2 -0
  48. package/dist/generated/version.js +3 -0
  49. package/dist/host/index.d.ts +7 -0
  50. package/dist/host/index.js +5 -0
  51. package/dist/index.d.ts +19 -0
  52. package/dist/index.js +13 -0
  53. package/dist/permissions.d.ts +11 -0
  54. package/dist/permissions.js +18 -0
  55. package/dist/plugin.d.ts +86 -0
  56. package/dist/plugin.js +26 -0
  57. package/dist/protocol.d.ts +167 -0
  58. package/dist/protocol.js +4 -0
  59. package/dist/runtime/connection.d.ts +52 -0
  60. package/dist/runtime/connection.js +132 -0
  61. package/dist/runtime/handles.d.ts +95 -0
  62. package/dist/runtime/handles.js +289 -0
  63. package/dist/runtime/memory-transport.d.ts +6 -0
  64. package/dist/runtime/memory-transport.js +39 -0
  65. package/dist/runtime/runtime.d.ts +57 -0
  66. package/dist/runtime/runtime.js +265 -0
  67. package/dist/runtime/scope.d.ts +25 -0
  68. package/dist/runtime/scope.js +94 -0
  69. package/dist/runtime/storage-runtime.d.ts +10 -0
  70. package/dist/runtime/storage-runtime.js +131 -0
  71. package/dist/settings.d.ts +111 -0
  72. package/dist/settings.js +78 -0
  73. package/dist/storage.d.ts +78 -0
  74. package/dist/storage.js +24 -0
  75. package/dist/testing/fake-container.d.ts +175 -0
  76. package/dist/testing/fake-container.js +483 -0
  77. package/dist/testing/index.d.ts +37 -0
  78. package/dist/testing/index.js +54 -0
  79. package/dist/types.d.ts +65 -0
  80. package/dist/types.js +54 -0
  81. package/llms.txt +11 -0
  82. package/package.json +55 -4
  83. package/src/api.ts +334 -0
  84. package/src/cli/api.ts +79 -0
  85. package/src/cli/build.ts +76 -0
  86. package/src/cli/check.ts +103 -0
  87. package/src/cli/config.ts +48 -0
  88. package/src/cli/create.ts +38 -0
  89. package/src/cli/dev-mcp.ts +131 -0
  90. package/src/cli/dev.ts +272 -0
  91. package/src/cli/fetch-guard.ts +61 -0
  92. package/src/cli/main.ts +113 -0
  93. package/src/cli/mcp.ts +168 -0
  94. package/src/cli/output.ts +30 -0
  95. package/src/cli/test.ts +38 -0
  96. package/src/errors.ts +34 -0
  97. package/src/generated/block-states.ts +892 -0
  98. package/src/generated/blocks.ts +1291 -0
  99. package/src/generated/contracts.ts +329 -0
  100. package/src/generated/effects.ts +45 -0
  101. package/src/generated/entities.ts +166 -0
  102. package/src/generated/items.ts +1663 -0
  103. package/src/generated/operations.ts +69 -0
  104. package/src/generated/permission-labels.ts +19 -0
  105. package/src/generated/version.ts +3 -0
  106. package/src/host/index.ts +9 -0
  107. package/src/index.ts +34 -0
  108. package/src/permissions.ts +23 -0
  109. package/src/plugin.ts +105 -0
  110. package/src/protocol.ts +107 -0
  111. package/src/runtime/connection.ts +167 -0
  112. package/src/runtime/handles.ts +337 -0
  113. package/src/runtime/memory-transport.ts +41 -0
  114. package/src/runtime/runtime.ts +281 -0
  115. package/src/runtime/scope.ts +101 -0
  116. package/src/runtime/storage-runtime.ts +138 -0
  117. package/src/settings.ts +118 -0
  118. package/src/storage.ts +82 -0
  119. package/src/testing/fake-container.ts +571 -0
  120. package/src/testing/index.ts +70 -0
  121. package/src/types.ts +88 -0
  122. package/templates/basic/AGENTS.md +31 -0
  123. package/templates/basic/README.md +13 -0
  124. package/templates/basic/gitignore +3 -0
  125. package/templates/basic/package.json +18 -0
  126. package/templates/basic/src/index.ts +20 -0
  127. package/templates/basic/test/plugin.test.ts +14 -0
  128. package/templates/basic/tsconfig.json +14 -0
@@ -0,0 +1,103 @@
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
+ interface Built {
15
+ manifest: Manifest;
16
+ bundle: string;
17
+ bytes: number;
18
+ }
19
+
20
+ async function buildAll(outDir: string): Promise<Built> {
21
+ const project = findProject();
22
+ mkdirSync(outDir, { recursive: true });
23
+
24
+ // The manifest comes from running the plugin's module in Node; that build stays out of the output folder.
25
+ mkdirSync(join(project.root, ".minebot"), { recursive: true });
26
+ const devFile = join(project.root, ".minebot", "probe.mjs");
27
+ try {
28
+ await esbuild.build(devBuildOptions(project, devFile));
29
+ } catch (e) {
30
+ fail(`Build failed:\n${formatErrors((e as esbuild.BuildFailure).errors ?? [])}`);
31
+ }
32
+ const plugin = await loadPlugin(devFile);
33
+ const manifest = buildManifest(plugin, project.version);
34
+
35
+ const bundle = join(outDir, "plugin.js");
36
+ let result: esbuild.BuildResult;
37
+ try {
38
+ result = await esbuild.build(hostedBuildOptions(project, bundle));
39
+ } catch (e) {
40
+ fail(`Hosted build failed:\n${formatErrors((e as esbuild.BuildFailure).errors ?? [])}`);
41
+ }
42
+ const bytes = Object.values(result.metafile!.outputs).reduce((n, o) => n + o.bytes, 0);
43
+ return { manifest, bundle, bytes };
44
+ }
45
+
46
+ /** Problems with a manifest: each is a sentence a person (or an AI) can act on. */
47
+ export function review(manifest: Manifest, bytes: number): { problems: string[]; notes: string[] } {
48
+ const problems: string[] = [];
49
+ const notes: string[] = [];
50
+ const permissions = new Set(manifest.permissions);
51
+ const hosts = manifest.permissions.map(networkHost).filter((h): h is string => h !== null);
52
+ const urlSettings = Object.entries(manifest.settings).filter(([, s]) => s.type === "url");
53
+
54
+ if (manifest.name.length > 64) problems.push("The name is longer than 64 characters.");
55
+ if (hosts.some(h => h === "*" || h.startsWith("*.") && h.split(".").length < 3)) problems.push("A network permission covers too much; name the hosts you call.");
56
+ if (permissions.has("ChatRead") && (hosts.length > 0 || urlSettings.length > 0)) {
57
+ notes.push(`Users will be told this plugin "can read chat and send it to ${[...hosts, ...urlSettings.map(([k]) => `the URL in "${k}"`)].join(", ")}".`);
58
+ }
59
+ if (permissions.has("ProfileBots")) notes.push("ProfileBots lets the plugin connect and disconnect every bot of the profile; users see that at install.");
60
+ if (manifest.exclusive.length === 0 && (permissions.has("Move") || permissions.has("Interact"))) {
61
+ 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, ...].");
62
+ }
63
+ if (bytes > BUNDLE_WARNING_BYTES) {
64
+ 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.`);
65
+ }
66
+ return { problems, notes };
67
+ }
68
+
69
+ /** `minebot check`: builds the plugin as it would be uploaded and reports what users will be asked to allow. */
70
+ export async function check(): Promise<void> {
71
+ const project = findProject();
72
+ const { manifest, bytes } = await buildAll(join(project.root, ".minebot", "check"));
73
+
74
+ info(`${bold(manifest.name)} ${dim(manifest.version)}`);
75
+ info("\nUsers will be asked to allow:");
76
+ if (manifest.permissions.length === 0) info(dim(" nothing (logs, settings, storage and timers are always allowed)"));
77
+ for (const p of manifest.permissions) {
78
+ const host = networkHost(p);
79
+ info(` • ${host ? `Can send and receive data from ${host}` : PERMISSION_LABELS[p as keyof typeof PERMISSION_LABELS] ?? p}`);
80
+ }
81
+ const settings = Object.entries(manifest.settings);
82
+ if (settings.length) info(`\nSettings: ${settings.map(([k, s]) => `${k} (${s.type}${s.secret ? ", secret" : ""})`).join(", ")}`);
83
+ const storage = Object.entries(manifest.storage);
84
+ if (storage.length) info(`Storage: ${storage.map(([k, s]) => `${k} (${s.kind}, ${s.scope})`).join(", ")}`);
85
+ info(`Hosted bundle: ${(bytes / 1024).toFixed(1)} KB`);
86
+
87
+ const { problems, notes } = review(manifest, bytes);
88
+ for (const n of notes) info(`\n${yellow("note:")} ${n}`);
89
+ for (const p of problems) warn(p);
90
+ if (problems.length) process.exit(1);
91
+ info(`\n${green("ok")}`);
92
+ }
93
+
94
+ /** `minebot build`: writes dist/plugin.js (the hosted bundle) and dist/manifest.json, for upload. */
95
+ export async function build(): Promise<void> {
96
+ const project = findProject();
97
+ const outDir = join(project.root, "dist");
98
+ const { manifest, bytes } = await buildAll(outDir);
99
+ writeFileSync(join(outDir, "manifest.json"), JSON.stringify(manifest, null, 2));
100
+ const { problems } = review(manifest, bytes);
101
+ for (const p of problems) warn(p);
102
+ info(`Wrote dist/plugin.js (${(bytes / 1024).toFixed(1)} KB) and dist/manifest.json`);
103
+ }
@@ -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,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
+ }
package/src/cli/dev.ts ADDED
@@ -0,0 +1,272 @@
1
+ import { mkdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import * as esbuild from "esbuild";
4
+ import { PluginError } from "../errors.js";
5
+ import type { BotInfo, DevOptions } from "../protocol.js";
6
+ import type { Transport } from "../runtime/connection.js";
7
+ import { buildManifest, PluginRuntime, SDK_VERSION, type LogLevel } from "../runtime/runtime.js";
8
+ import { Scope } from "../runtime/scope.js";
9
+ import { devToken, listProfiles, type DevToken } from "./api.js";
10
+ import { devBuildOptions, findProject, formatErrors, loadPlugin } from "./build.js";
11
+ import { DEV_MCP_INSTRUCTIONS, DevLog, devTools, type DevSession } from "./dev-mcp.js";
12
+ import { guardFetch } from "./fetch-guard.js";
13
+ import { startMcpServer, type McpServer } from "./mcp.js";
14
+ import { bold, cyan, dim, fail, green, info, red, timestamp, warn, yellow } from "./output.js";
15
+
16
+ export interface DevArgs {
17
+ profile?: string;
18
+ bots: string[];
19
+ settingsFile?: string;
20
+ watch: boolean;
21
+ /** Port for the MCP endpoint (the next free one up to +9 is used), or null for none. */
22
+ mcpPort: number | null;
23
+ }
24
+
25
+ /** Rejections a reconnect can't fix: stop and tell the user what to do. */
26
+ const FINAL_REJECTIONS = new Set(["UnsupportedProtocol", "BadManifest", "WrongProfile", "PermissionsChanged", "FeatureDisabled"]);
27
+
28
+ /** Closes a reconnect would undo (`StopReason`): wait for the next rebuild instead. */
29
+ const NO_RECONNECT: Record<string, string> = {
30
+ Replaced: "Another copy of this plugin connected to the profile (minebot dev running somewhere else?)",
31
+ EndedByUser: "The session was ended from the dashboard",
32
+ };
33
+
34
+ class WebSocketTransport implements Transport {
35
+ onmessage: ((text: string) => void) | null = null;
36
+ onclose: ((code: number, reason: string) => void) | null = null;
37
+
38
+ constructor(private readonly socket: WebSocket) {
39
+ socket.onmessage = event => this.onmessage?.(typeof event.data === "string" ? event.data : String(event.data));
40
+ socket.onclose = event => this.onclose?.(event.code, event.reason);
41
+ }
42
+
43
+ send(text: string): void {
44
+ if (this.socket.readyState === WebSocket.OPEN) this.socket.send(text);
45
+ }
46
+
47
+ close(code = 1000, reason = ""): void {
48
+ this.socket.close(code, reason);
49
+ }
50
+
51
+ static open(url: string): Promise<WebSocketTransport> {
52
+ return new Promise((resolve, reject) => {
53
+ const socket = new WebSocket(url);
54
+ socket.onopen = () => resolve(new WebSocketTransport(socket));
55
+ socket.onerror = () => reject(new Error(`Couldn't connect to ${url}`));
56
+ });
57
+ }
58
+ }
59
+
60
+ async function pickProfile(requested: string | undefined): Promise<string> {
61
+ const profiles = await listProfiles();
62
+ if (profiles.length === 0) fail("You have no profiles.", "Create one on the dashboard first.");
63
+ if (requested) {
64
+ const match = profiles.find(p => p.id === requested || p.name.toLowerCase() === requested.toLowerCase());
65
+ if (!match) fail(`No profile "${requested}".`, `Yours: ${profiles.map(p => `"${p.name}"`).join(", ")}`);
66
+ return match.id;
67
+ }
68
+ const running = profiles.filter(p => p.running);
69
+ if (running.length === 1) return running[0].id;
70
+ const list = profiles.map(p => ` ${p.running ? green("running") : dim("stopped")} ${p.name} ${dim(p.id)}`).join("\n");
71
+ fail(running.length === 0 ? "None of your profiles is running." : "Several profiles are running; pick one with --profile.", `\n${list}\n minebot dev --profile "<name>"`);
72
+ }
73
+
74
+ function logLine(level: LogLevel, message: string, bot: BotInfo | null): void {
75
+ const who = bot ? cyan(bot.name || bot.id) : dim("profile");
76
+ const tag = level === "error" ? red("error") : level === "warn" ? yellow("warn ") : level === "debug" ? dim("debug") : "info ";
77
+ console.log(`${timestamp()} ${tag} ${who} ${message}`);
78
+ }
79
+
80
+ /**
81
+ * `minebot dev`: builds the plugin, runs it on your machine connected to one of your running profiles, and
82
+ * rebuilds and reconnects when a file changes. Your code, your profile: the manifest's permissions are granted
83
+ * without a prompt, and storage lives in a dev namespace apart from installed copies. An MCP endpoint lets an AI
84
+ * agent read the plugin's state and logs, look at its bots and reload it.
85
+ */
86
+ export async function dev(args: DevArgs): Promise<void> {
87
+ const project = findProject();
88
+ const outDir = join(project.root, ".minebot", "dev");
89
+ mkdirSync(outDir, { recursive: true });
90
+ const outfile = join(outDir, "plugin.mjs");
91
+ const settings = args.settingsFile ? (JSON.parse(readFileSync(args.settingsFile, "utf8")) as Record<string, unknown>) : {};
92
+ const devOptions: DevOptions = { bots: args.bots.length ? args.bots : null, settings };
93
+
94
+ const profileId = await pickProfile(args.profile);
95
+ let token: DevToken = await devToken(profileId);
96
+ info(`${bold(project.name)} → profile ${bold(token.profileName)} ${dim(`(${token.address})`)}`);
97
+
98
+ const log = new DevLog();
99
+ let runtime: PluginRuntime | null = null;
100
+ let generation = 0;
101
+ let unguard: (() => void) | null = null;
102
+ let stopping = false;
103
+ let retryTimer: ReturnType<typeof setTimeout> | null = null;
104
+ let state = "building";
105
+ let buildErrors: string | null = null;
106
+
107
+ // The reload tool waits for the next outcome: connected, refused, or a failed build or load.
108
+ let outcomeWaiters: ((outcome: string) => void)[] = [];
109
+ const settle = (outcome: string) => {
110
+ state = outcome;
111
+ log.add("system", outcome);
112
+ const waiters = outcomeWaiters;
113
+ outcomeWaiters = [];
114
+ for (const resolve of waiters) resolve(outcome);
115
+ };
116
+
117
+ const connect = async (attempt = 0): Promise<void> => {
118
+ const mine = ++generation;
119
+ if (retryTimer) clearTimeout(retryTimer);
120
+ if (new Date(token.expiresAt).getTime() - Date.now() < 10 * 60_000) token = await devToken(profileId);
121
+
122
+ let plugin;
123
+ try {
124
+ plugin = await loadPlugin(outfile, mine);
125
+ } catch (e) {
126
+ console.error(red(`The plugin failed to load: ${(e as Error).stack ?? e}`));
127
+ settle(`The plugin failed to load: ${(e as Error).stack ?? e}`);
128
+ return;
129
+ }
130
+
131
+ unguard?.();
132
+ unguard = guardFetch(buildManifest(plugin, project.version), () => runtime?.welcome.settings ?? settings);
133
+
134
+ const url = `${token.address.replace(/^http/, "ws").replace(/\/+$/, "")}/plugins/${profileId}`;
135
+ state = "connecting";
136
+ try {
137
+ const transport = await WebSocketTransport.open(url);
138
+ if (mine !== generation) return transport.close();
139
+ runtime = await PluginRuntime.connect(plugin, transport, token.token, project.version, {
140
+ onLog: (level, message, bot) => {
141
+ logLine(level, message, bot);
142
+ log.add(level, message, bot ? bot.name || bot.id : null);
143
+ },
144
+ onClosed: (code, reason) => {
145
+ if (stopping || mine !== generation) return;
146
+ if (NO_RECONNECT[reason]) {
147
+ warn(`${NO_RECONNECT[reason]}. ${args.watch ? "Save a file to connect again." : "Stopped."}`);
148
+ settle(`Disconnected: ${NO_RECONNECT[reason]}. Not reconnecting until the next rebuild.`);
149
+ if (!args.watch) void shutdown();
150
+ return;
151
+ }
152
+ warn(`Disconnected (${code}${reason ? `: ${reason}` : ""}); reconnecting…`);
153
+ settle(`Disconnected (${code}${reason ? `: ${reason}` : ""}); reconnecting`);
154
+ retryTimer = setTimeout(() => void connect(attempt + 1), Math.min(30_000, 1000 * 2 ** Math.min(attempt, 5)));
155
+ },
156
+ }, devOptions);
157
+ const enabled = runtime.welcome.bots.filter(b => b.enabled);
158
+ info(`${green("connected")} running on ${enabled.length ? enabled.map(b => cyan(b.name || b.id) + (b.connected ? "" : dim(" (offline)"))).join(", ") : yellow("no bots")}`);
159
+ settle(`Connected, running on ${enabled.length ? enabled.map(b => b.name || b.id).join(", ") : "no bots"}`);
160
+ attempt = 0;
161
+ } catch (e) {
162
+ if (e instanceof PluginError && FINAL_REJECTIONS.has(e.code)) {
163
+ settle(`Refused by the bot: ${e.message}`);
164
+ fail(`The bot refused the plugin: ${e.message}`);
165
+ }
166
+ if (e instanceof PluginError && e.code === "InvalidToken") token = await devToken(profileId);
167
+ if (stopping || mine !== generation) return;
168
+ warn(`${(e as Error).message}; retrying…`);
169
+ settle(`Not connected: ${(e as Error).message}; retrying`);
170
+ retryTimer = setTimeout(() => void connect(attempt + 1), Math.min(30_000, 1000 * 2 ** Math.min(attempt, 5)));
171
+ }
172
+ };
173
+
174
+ const reload = async () => {
175
+ const previous = runtime;
176
+ runtime = null;
177
+ previous?.close();
178
+ await connect();
179
+ };
180
+
181
+ const context = await esbuild.context({
182
+ ...devBuildOptions(project, outfile),
183
+ plugins: [{
184
+ name: "minebot-dev",
185
+ setup(build) {
186
+ let first = true;
187
+ build.onEnd(result => {
188
+ if (result.errors.length) {
189
+ buildErrors = formatErrors(result.errors);
190
+ console.error(red(`Build failed:\n${buildErrors}`));
191
+ settle(`Build failed:\n${buildErrors}`);
192
+ return;
193
+ }
194
+ buildErrors = null;
195
+ if (!first) info(dim("Rebuilt; restarting the plugin…"));
196
+ log.add("system", first ? "Built" : "Rebuilt; restarting the plugin");
197
+ first = false;
198
+ void reload();
199
+ });
200
+ },
201
+ }],
202
+ });
203
+
204
+ const session: DevSession = {
205
+ log,
206
+ status: () => ({
207
+ plugin: { name: project.name, version: project.version, folder: project.root },
208
+ profile: { id: profileId, name: token.profileName },
209
+ state,
210
+ build: buildErrors ? { ok: false, errors: buildErrors } : { ok: true },
211
+ bots: runtime ? runtime.currentBots.map(b => ({ ...b, running: runtime!.runningBots.includes(b.id) })) : [],
212
+ granted: runtime?.welcome.granted ?? [],
213
+ settings: runtime?.welcome.settings ?? settings,
214
+ limits: runtime?.welcome.limits,
215
+ }),
216
+ reload: async () => {
217
+ const outcome = new Promise<string>(resolve => outcomeWaiters.push(resolve));
218
+ await context.rebuild();
219
+ const timeout = new Promise<string>(resolve => setTimeout(() => resolve(`Still ${state} after 30 seconds`), 30_000).unref());
220
+ return { outcome: await Promise.race([outcome, timeout]), status: session.status() };
221
+ },
222
+ query: async (botName, op, opArgs) => {
223
+ const current = runtime;
224
+ if (!current) throw new Error(`The plugin is not connected (${state}).`);
225
+ let bot: string | null = null;
226
+ if (!op.startsWith("storage.")) {
227
+ const bots = current.currentBots;
228
+ const running = current.runningBots;
229
+ const match = botName
230
+ ? bots.find(b => b.id === botName || b.name.toLowerCase() === botName.toLowerCase())
231
+ : bots.find(b => running.includes(b.id));
232
+ if (!match) throw new Error(botName ? `No bot "${botName}". The profile's bots: ${bots.map(b => b.name || b.id).join(", ")}` : "The plugin is not running on any bot yet.");
233
+ bot = match.id;
234
+ }
235
+ const scope = new Scope();
236
+ try {
237
+ return await current.call(scope, bot, op, opArgs);
238
+ } finally {
239
+ scope.stop("Done");
240
+ }
241
+ },
242
+ };
243
+
244
+ let mcp: McpServer | null = null;
245
+ if (args.mcpPort !== null) {
246
+ try {
247
+ mcp = await startMcpServer(devTools(session), { port: args.mcpPort, name: "minebot-dev", version: SDK_VERSION, instructions: DEV_MCP_INSTRUCTIONS });
248
+ info(dim(`MCP for AI agents: ${mcp.url} (claude mcp add --transport http minebot-dev ${mcp.url})`));
249
+ } catch (e) {
250
+ warn(`No MCP endpoint: ${(e as Error).message}`);
251
+ }
252
+ }
253
+
254
+ const shutdown = async () => {
255
+ stopping = true;
256
+ if (retryTimer) clearTimeout(retryTimer);
257
+ runtime?.close();
258
+ await context.dispose();
259
+ await mcp?.close();
260
+ unguard?.();
261
+ process.exit(0);
262
+ };
263
+ process.on("SIGINT", () => void shutdown());
264
+ process.on("SIGTERM", () => void shutdown());
265
+
266
+ if (args.watch) {
267
+ await context.watch();
268
+ info(dim("Watching for changes. Ctrl+C stops."));
269
+ } else {
270
+ await context.rebuild();
271
+ }
272
+ }
@@ -0,0 +1,61 @@
1
+ import type { Manifest } from "../protocol.js";
2
+ import { networkHost } from "../permissions.js";
3
+ import { PluginError } from "../errors.js";
4
+
5
+ /**
6
+ * Applies the hosted runner's fetch rules under `minebot dev`, so a missing network permission fails on your
7
+ * machine exactly as it would hosted: HTTPS only, and only to declared hosts or the origin of a URL setting.
8
+ * (The hosted runner also blocks private addresses and limits sizes and rates; this guard doesn't need to.)
9
+ */
10
+ export function guardFetch(manifest: Manifest, settings: () => Record<string, unknown>): () => void {
11
+ const original = globalThis.fetch;
12
+ const hosts = manifest.permissions.map(networkHost).filter((h): h is string => h !== null);
13
+
14
+ const allowed = (url: URL): boolean => {
15
+ if (url.protocol !== "https:") return false;
16
+ const port = url.port || "443";
17
+ for (const entry of hosts) {
18
+ const [host, declaredPort = "443"] = entry.split(":");
19
+ if (declaredPort !== port) continue;
20
+ if (host.startsWith("*.") ? url.hostname.endsWith(host.slice(1)) && url.hostname !== host.slice(2) : url.hostname === host) return true;
21
+ }
22
+ for (const [key, schema] of Object.entries(manifest.settings)) {
23
+ if (schema.type !== "url") continue;
24
+ const value = settings()[key];
25
+ if (typeof value !== "string") continue;
26
+ try {
27
+ if (new URL(value).origin === url.origin) return true;
28
+ } catch {
29
+ // not a URL
30
+ }
31
+ }
32
+ return false;
33
+ };
34
+
35
+ const check = (url: URL) => {
36
+ if (url.protocol !== "https:") throw new PluginError("NetworkDenied", `fetch(${url.href}): only https:// is allowed`);
37
+ if (!allowed(url)) {
38
+ throw new PluginError("NetworkDenied", `fetch(${url.origin}): add Permission.network("${url.hostname}${url.port ? `:${url.port}` : ""}") to permissions in definePlugin`);
39
+ }
40
+ };
41
+
42
+ // Redirects are followed by hand so every hop is checked, as the runner does.
43
+ globalThis.fetch = async (input: string | URL | Request, init?: RequestInit) => {
44
+ let url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
45
+ let request: string | URL | Request = input;
46
+ let options: RequestInit | undefined = init;
47
+ for (let hop = 0; hop <= 5; hop++) {
48
+ check(url);
49
+ const response = await original(request, { ...options, redirect: "manual" });
50
+ const location = response.headers.get("location");
51
+ if (response.status < 300 || response.status >= 400 || !location) return response;
52
+ url = new URL(location, url);
53
+ request = url.href;
54
+ if (response.status === 303) options = { ...options, method: "GET", body: undefined };
55
+ }
56
+ throw new PluginError("NetworkDenied", `fetch: more than 5 redirects`);
57
+ };
58
+ return () => {
59
+ globalThis.fetch = original;
60
+ };
61
+ }