slatebox-mcp 0.1.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,24 +1,61 @@
1
1
  {
2
2
  "name": "slatebox-mcp",
3
- "version": "0.1.0",
4
- "description": "Authenticated MCP server for reading and editing Slatebox slates",
3
+ "version": "0.3.2",
4
+ "mcpName": "com.slatebox/slatebox",
5
+ "description": "Slatebox for AI assistants: create and edit mind maps, diagrams, project plans and presentations on a shared canvas.",
6
+ "keywords": [
7
+ "mcp",
8
+ "mcp-server",
9
+ "modelcontextprotocol",
10
+ "mind-map",
11
+ "mindmap",
12
+ "diagram",
13
+ "flowchart",
14
+ "whiteboard",
15
+ "project-planning",
16
+ "gantt",
17
+ "timeline",
18
+ "presentation",
19
+ "mermaid",
20
+ "collaboration",
21
+ "open-source",
22
+ "miro-alternative"
23
+ ],
24
+ "homepage": "https://docs.slatebox.com/developers/slateboxapi/mcp/",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/Slatebox/slatebox.git",
28
+ "directory": "packages/slatebox-mcp"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/Slatebox/slatebox/issues"
32
+ },
33
+ "license": "MIT",
5
34
  "type": "module",
6
35
  "bin": {
7
- "slatebox-mcp": "src/cli.js"
36
+ "slatebox-mcp": "src/cli.js",
37
+ "slatebox": "src/slatebox.js"
38
+ },
39
+ "exports": {
40
+ "./client": {
41
+ "types": "./generated/slatebox.d.ts",
42
+ "default": "./src/client/index.js"
43
+ },
44
+ "./exec": "./src/exec/index.js"
8
45
  },
9
46
  "files": [
10
47
  "src",
11
- "README.md"
48
+ "generated",
49
+ "README.md",
50
+ "LICENSE.md"
12
51
  ],
13
52
  "scripts": {
14
53
  "test": "node --test"
15
54
  },
16
55
  "engines": {
17
- "node": ">=20"
56
+ "node": ">=22.13.0"
18
57
  },
19
58
  "dependencies": {
20
- "@modelcontextprotocol/sdk": "^1.29.0",
21
- "zod": "^4.4.3"
22
- },
23
- "license": "MIT"
59
+ "@modelcontextprotocol/sdk": "^1.29.0"
60
+ }
24
61
  }
package/src/cli.js CHANGED
@@ -1,24 +1,57 @@
1
1
  #!/usr/bin/env node
2
+ // slatebox-mcp: the MCP server: exec and describe, one typed tool per client method, prompts
3
+ // and resources.
4
+ // stdio (default) for agent hosts that start a command
5
+ // --http [--port N] loopback Streamable HTTP at http://127.0.0.1:N/mcp
6
+ // --typed-tools on|off list the typed tools (default on; or SLATEBOX_MCP_TYPED_TOOLS).
7
+ // exec and describe are always listed.
8
+ // SLATEBOX_API_TOKEN is your personal access token; SLATEBOX_BASE_URL (or --base-url) your
9
+ // Slatebox origin. A script runs in this process with your rights: there is no sandbox.
10
+ import { parseArgs } from "node:util";
2
11
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
- import { SlateboxClient } from "./client.js";
12
+ import { apiOrigin, createClient, DEFAULT_ORIGIN, UsageError } from "./client/index.js";
13
+ import { createExec } from "./exec/index.js";
14
+ import { defaultGenerated } from "./generated.js";
4
15
  import { createSlateboxMcpServer } from "./server.js";
16
+ import { startHttp } from "./http-server.js";
17
+ import { typedToolsEnabled } from "./typed-tools.js";
5
18
 
6
- function argument(name) {
7
- const index = process.argv.indexOf(name);
8
- return index >= 0 ? process.argv[index + 1] : null;
9
- }
19
+ export const DEFAULT_HTTP_PORT = 3917;
10
20
 
11
- const baseUrl =
12
- argument("--base-url") ||
13
- process.env.SLATEBOX_BASE_URL ||
14
- "https://app.slatebox.com";
15
- const token = process.env.SLATEBOX_API_TOKEN;
21
+ async function main() {
22
+ let values;
23
+ try {
24
+ ({ values } = parseArgs({ args: process.argv.slice(2), options: {
25
+ http: { type: "boolean" }, port: { type: "string" }, host: { type: "string" }, "base-url": { type: "string" },
26
+ "typed-tools": { type: "string" },
27
+ } }));
28
+ } catch {
29
+ throw new UsageError("Usage: slatebox-mcp [--base-url ORIGIN] [--typed-tools on|off] [--http [--port N]]");
30
+ }
31
+ const typedOption = values["typed-tools"] ?? process.env.SLATEBOX_MCP_TYPED_TOOLS;
32
+ if (typedOption !== undefined && typedOption !== "" && !/^(on|off|true|false|1|0|yes|no)$/i.test(String(typedOption).trim()))
33
+ throw new UsageError("--typed-tools (or SLATEBOX_MCP_TYPED_TOOLS) is on or off.");
34
+ const typedTools = typedToolsEnabled(typedOption);
35
+ const token = process.env.SLATEBOX_API_TOKEN;
36
+ if (!token) throw new UsageError("Set SLATEBOX_API_TOKEN to a personal access token.");
37
+ const baseUrl = apiOrigin(values["base-url"] || process.env.SLATEBOX_BASE_URL || DEFAULT_ORIGIN);
38
+ const generated = defaultGenerated();
39
+ const client = createClient({ baseUrl, token, generated });
40
+ const exec = createExec({ baseUrl, token, generated });
41
+ const instance = client.instance?.describe ? () => client.instance.describe({}) : undefined;
42
+ const createServerForRequest = () => createSlateboxMcpServer({ exec, generated, instance, typedTools });
43
+ if (!values.http) {
44
+ if (values.port !== undefined || values.host !== undefined) throw new UsageError("--port and --host go with --http.");
45
+ await createServerForRequest().connect(new StdioServerTransport());
46
+ return;
47
+ }
48
+ const port = values.port === undefined ? DEFAULT_HTTP_PORT : Number(values.port);
49
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new UsageError("--port is a port number.");
50
+ const listening = await startHttp({ host: values.host ?? "127.0.0.1", port, token, createServerForRequest });
51
+ process.stderr.write(`Slatebox MCP listening at ${listening.url} (loopback only; send your Slatebox token as the bearer token)\n`);
52
+ }
16
53
 
17
- try {
18
- const client = new SlateboxClient({ baseUrl, token });
19
- const server = createSlateboxMcpServer(client);
20
- await server.connect(new StdioServerTransport());
21
- } catch (error) {
54
+ main().catch((error) => {
22
55
  process.stderr.write(`Slatebox MCP could not start: ${error.message}\n`);
23
- process.exitCode = 1;
24
- }
56
+ process.exitCode = error instanceof UsageError ? 2 : 1;
57
+ });
@@ -0,0 +1,136 @@
1
+ // The typed HTTP client, built at runtime from generated/client.json: one method per bound
2
+ // action, named by its action id (slatebox.slates.get(input)). Types: generated/slatebox.d.ts.
3
+ // Use it in your own code (an AI SDK tool, a script). Outside an exec run it sends no
4
+ // Slatebox-Exec-* headers, so each call is an ordinary API call.
5
+ import { defaultGenerated } from "../generated.js";
6
+
7
+ export class SlateboxError extends Error {
8
+ constructor({ code = "error", status = 0, message, details, retryAfter } = {}) {
9
+ super(message || `Slatebox returned HTTP ${status}.`);
10
+ this.name = "SlateboxError";
11
+ this.code = code;
12
+ this.status = status;
13
+ if (details !== undefined) this.details = details;
14
+ if (retryAfter !== undefined) this.retryAfter = retryAfter;
15
+ }
16
+ }
17
+
18
+ export class UsageError extends Error {}
19
+
20
+ /** Slatebox Cloud: the app serves /api/v1 and /mcp. A self-hosted instance passes its own origin. */
21
+ export const DEFAULT_ORIGIN = "https://app.slatebox.com";
22
+
23
+ /** An http(s) origin with nothing after it. */
24
+ export function apiOrigin(input) {
25
+ let url;
26
+ try { url = new URL(input); } catch { throw new UsageError("Invalid Slatebox API origin."); }
27
+ if (!["http:", "https:"].includes(url.protocol) || url.pathname !== "/" || url.username || url.password || url.search || url.hash) {
28
+ throw new UsageError("Supply an HTTP or HTTPS origin without credentials, path, query or fragment.");
29
+ }
30
+ return url.origin;
31
+ }
32
+
33
+ const isPlainObject = (value) => {
34
+ if (!value || typeof value !== "object") return false;
35
+ const proto = Object.getPrototypeOf(value);
36
+ return proto === Object.prototype || proto === null;
37
+ };
38
+
39
+ /** Where each input field travels: path, query or body, from the manifest's http layout. */
40
+ export function buildRequest(baseUrl, method, input) {
41
+ const { http } = method;
42
+ let path = http.path;
43
+ const rest = { ...input };
44
+ for (const name of http.pathParams) {
45
+ if (rest[name] === undefined || rest[name] === null) {
46
+ throw new SlateboxError({ code: "invalid_request", status: 400, message: `${method.name} needs ${name}.`, details: { field: name } });
47
+ }
48
+ const segment = String(rest[name]);
49
+ // encodeURIComponent leaves "." and ".." as they are, and a URL normalises them away.
50
+ if (segment === "." || segment === "..") {
51
+ throw new SlateboxError({ code: "invalid_request", status: 400, message: `${method.name}: ${name} cannot be "${segment}".`, details: { field: name } });
52
+ }
53
+ path = path.replace(`{${name}}`, encodeURIComponent(segment));
54
+ delete rest[name];
55
+ }
56
+ const takesBody = !["GET", "DELETE"].includes(http.method);
57
+ const query = new URLSearchParams();
58
+ // A field the route does not carry in its body goes in the query, where the server refuses
59
+ // it by name. Nothing is dropped silently.
60
+ for (const [name, value] of Object.entries(rest)) {
61
+ if (value === undefined) continue;
62
+ if (!takesBody || http.queryParams.includes(name)) {
63
+ query.append(name, typeof value === "string" ? value : JSON.stringify(value));
64
+ delete rest[name];
65
+ }
66
+ }
67
+ const url = baseUrl + path + (query.size ? "?" + query : "");
68
+ const init = { method: http.method, headers: {} };
69
+ if (takesBody) {
70
+ init.headers["content-type"] = "application/json";
71
+ init.body = JSON.stringify(rest);
72
+ }
73
+ return { url, init };
74
+ }
75
+
76
+ function retryAfterSeconds(payload, response) {
77
+ const stated = payload?.error?.retryAfter ?? response.headers.get("retry-after");
78
+ const seconds = Number(stated);
79
+ return stated !== null && stated !== undefined && Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;
80
+ }
81
+
82
+ /**
83
+ * One HTTP call. Returns {ok, status, body, headers} and never throws for an HTTP refusal:
84
+ * a refusal comes back as {ok:false, error:{code,status,message,details?,retryAfter?}}.
85
+ */
86
+ export async function sendCall({ baseUrl, token, fetchImpl = fetch, method, input, headers = {} }) {
87
+ const { url, init } = buildRequest(baseUrl, method, input);
88
+ init.headers = { ...init.headers, authorization: `Bearer ${token}`, ...headers };
89
+ let response;
90
+ try {
91
+ response = await fetchImpl(url, init);
92
+ } catch (failure) {
93
+ return { ok: false, status: 0, headers: new Headers(), error: { code: "network_error", status: 0, message: "Slatebox could not be reached: " + (failure?.message || "network error") } };
94
+ }
95
+ const text = await response.text();
96
+ let payload;
97
+ try { payload = text ? JSON.parse(text) : {}; } catch { payload = undefined; }
98
+ if (payload === undefined) {
99
+ return { ok: false, status: response.status, headers: response.headers,
100
+ error: { code: "not_json", status: response.status, message: "The endpoint did not return JSON. Check the Slatebox API origin." } };
101
+ }
102
+ if (!response.ok) {
103
+ const error = { code: payload.error?.code || "http_" + response.status, status: response.status,
104
+ message: payload.error?.message || `Slatebox returned HTTP ${response.status}.` };
105
+ if (payload.error?.details !== undefined) error.details = payload.error.details;
106
+ const retryAfter = retryAfterSeconds(payload, response);
107
+ if (retryAfter !== undefined) error.retryAfter = retryAfter;
108
+ return { ok: false, status: response.status, headers: response.headers, error };
109
+ }
110
+ return { ok: true, status: response.status, headers: response.headers, body: payload };
111
+ }
112
+
113
+ /**
114
+ * createClient({baseUrl, token}) returns the namespace tree: client.slates.get({shareId}).
115
+ * Each method takes one plain object; an optional second argument {idempotencyKey} sets the
116
+ * Idempotency-Key header for an ordinary API call (exec scripts never pass keys: theirs are derived).
117
+ */
118
+ export function createClient({ baseUrl = DEFAULT_ORIGIN, token, fetch: fetchImpl = fetch, generated = defaultGenerated() } = {}) {
119
+ if (!token) throw new UsageError("SLATEBOX_API_TOKEN is required.");
120
+ const origin = apiOrigin(baseUrl.replace(/\/$/, "") + "/");
121
+ const tree = {};
122
+ for (const method of generated.methods.values()) {
123
+ const parts = method.name.split(".");
124
+ let node = tree;
125
+ for (const part of parts.slice(0, -1)) node = node[part] ??= {};
126
+ node[parts.at(-1)] = async (input = {}, options = {}) => {
127
+ if (!isPlainObject(input)) throw new SlateboxError({ code: "invalid_request", status: 400, message: `${method.name} takes one plain object.` });
128
+ const headers = options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {};
129
+ const outcome = await sendCall({ baseUrl: origin, token, fetchImpl, method, input, headers });
130
+ if (!outcome.ok) throw new SlateboxError(outcome.error);
131
+ return outcome.body;
132
+ };
133
+ }
134
+ const freeze = (node) => { for (const value of Object.values(node)) if (typeof value === "object") freeze(value); return Object.freeze(node); };
135
+ return freeze(tree);
136
+ }
@@ -0,0 +1,84 @@
1
+ // describe: how an agent learns the generated `slatebox` client before writing an exec script.
2
+ // A port of describeClient in the app's web/app/server/actions/client-render.mjs, so the local
3
+ // and hosted describe tools answer alike (test/describe-parity.test.js holds them equal).
4
+ // Everything comes from generated/client.json.
5
+
6
+ export const DESCRIBE_BUDGET = 40000;
7
+
8
+ export class DescribeInputError extends Error {
9
+ constructor(message) { super(message); this.code = "invalid_request"; this.status = 400; }
10
+ }
11
+
12
+ // The describe tool's inputSchema, checked here because this server serves raw JSON schemas.
13
+ function checkInput(input) {
14
+ if (input === null || typeof input !== "object" || Array.isArray(input)) throw new DescribeInputError("describe takes an object.");
15
+ const extra = Object.keys(input).filter((key) => key !== "query" && key !== "methods");
16
+ if (extra.length) throw new DescribeInputError(`describe takes query and methods only, not ${extra.join(", ")}.`);
17
+ if (input.query !== undefined && (typeof input.query !== "string" || input.query.length > 200)) throw new DescribeInputError("query is text of at most 200 characters.");
18
+ if (input.methods !== undefined && (!Array.isArray(input.methods) || input.methods.length > 12 || input.methods.some((n) => typeof n !== "string" || n.length > 80)))
19
+ throw new DescribeInputError("methods is a list of at most 12 method names.");
20
+ }
21
+
22
+ export function describeClient(manifest, input = {}, { instance } = {}) {
23
+ const { query, methods: names } = input || {};
24
+ let chosen = manifest.methods;
25
+ let detailed = false;
26
+ if (Array.isArray(names) && names.length) {
27
+ const wanted = new Set(names);
28
+ chosen = manifest.methods.filter((method) => wanted.has(method.name));
29
+ detailed = true;
30
+ } else if (typeof query === "string" && query.trim()) {
31
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
32
+ chosen = manifest.methods
33
+ .filter((method) => {
34
+ const hay = `${method.name} ${method.title} ${method.summary}`.toLowerCase();
35
+ return words.some((word) => hay.includes(word));
36
+ })
37
+ .slice(0, 12);
38
+ detailed = true;
39
+ }
40
+ const typeNames = new Set(detailed ? chosen.flatMap((method) => method.types) : []);
41
+ const out = {
42
+ contract: manifest.contract,
43
+ rules: manifest.rules,
44
+ methods: chosen.map((method) => ({
45
+ name: method.name,
46
+ title: method.title,
47
+ summary: method.summary,
48
+ kind: method.kind,
49
+ flags: [
50
+ method.readOnly ? "read" : "write",
51
+ method.destructive && "destructive",
52
+ method.openWorld && "openWorld",
53
+ method.confirm && "confirm",
54
+ ].filter(Boolean),
55
+ scope: method.scope,
56
+ modes: method.modes,
57
+ ...(detailed ? { dts: method.dts } : { index: method.index }),
58
+ })),
59
+ types: [manifest.errorDeclaration, ...[...typeNames].sort().map((name) => manifest.types[name])].join("\n\n"),
60
+ errors: manifest.errors,
61
+ limits: manifest.limits,
62
+ ...(!detailed && { recipes: manifest.recipes }),
63
+ ...(instance && { instance }),
64
+ };
65
+ const text = JSON.stringify(out);
66
+ if (text.length > DESCRIBE_BUDGET) {
67
+ out.types = out.types.slice(0, Math.max(0, out.types.length - (text.length - DESCRIBE_BUDGET) - 200));
68
+ out.truncated = true;
69
+ }
70
+ return out;
71
+ }
72
+
73
+ /**
74
+ * The describe tool. instance: an async function returning the instance descriptor once the
75
+ * client binds instance.describe (wave 2, P08); until then the field is left out.
76
+ */
77
+ export async function describe(input = {}, { generated, instance } = {}) {
78
+ checkInput(input ?? {});
79
+ let descriptor;
80
+ if (instance && generated.methods.has("instance.describe")) {
81
+ try { descriptor = await instance(); } catch { /* optional: describe still answers */ }
82
+ }
83
+ return describeClient(generated.manifest, input, { instance: descriptor });
84
+ }
@@ -0,0 +1,27 @@
1
+ // Exec entry points. runLocal: the script runs here, in this process, with no sandbox (the
2
+ // person's own machine). runRemote: the script is sent to POST /api/v1/exec and runs in the
3
+ // instance's sealed runner.
4
+ import { defaultGenerated } from "../generated.js";
5
+ import { SlateboxError, sendCall } from "../client/index.js";
6
+ import { runLocal, localLimits } from "./local-runner.js";
7
+ import { validateExecInput } from "./result.js";
8
+
9
+ export { runLocal, localLimits };
10
+ export { summaryLine, ExecInputError } from "./result.js";
11
+
12
+ const EXEC_ROUTE = { name: "exec.run", kind: "write", http: { method: "POST", path: "/api/v1/exec", pathParams: [], queryParams: [], bodyParams: [] } };
13
+
14
+ export async function runRemote({ code, intent, mode = "save", confirm, idempotencyKey, baseUrl, token, fetchImpl = fetch }) {
15
+ validateExecInput({ code, intent, mode, confirm, idempotencyKey });
16
+ const outcome = await sendCall({ baseUrl, token, fetchImpl, method: EXEC_ROUTE,
17
+ input: { intent, code, mode, confirm, idempotencyKey } });
18
+ if (!outcome.ok) throw new SlateboxError(outcome.error);
19
+ return outcome.body;
20
+ }
21
+
22
+ /** The exec function the MCP server calls: local unless remote is true. */
23
+ export function createExec({ baseUrl, token, fetchImpl = fetch, generated = defaultGenerated(), remote = false }) {
24
+ return (args) => (remote
25
+ ? runRemote({ ...args, baseUrl, token, fetchImpl })
26
+ : runLocal({ ...args, baseUrl, token, fetchImpl, generated }));
27
+ }
@@ -0,0 +1,257 @@
1
+ // The local runner (exec-plan 8.1): an exec script runs on the person's own machine, with
2
+ // no sandbox, in a child process of the MCP server or CLI (script-process.js). The child is not
3
+ // a boundary the script cannot cross: it has the person's rights. It exists so the script's
4
+ // stdout is not the MCP stdio stream, a stuck script is killed at the wall clock, and a script
5
+ // that crashes takes only its own process down. Each client call is an HTTP request to the person's Slatebox with their token
6
+ // and the Slatebox-Exec-* headers; the server applies every script rule (preview, confirm
7
+ // before save, call caps, derived idempotency keys, audit). This file implements no rule
8
+ // except the local limits below, which the server enforces as well.
9
+ import { createHash, randomUUID } from "node:crypto";
10
+ import { fork } from "node:child_process";
11
+ import { stripTypeScriptTypes } from "node:module";
12
+ import { fileURLToPath } from "node:url";
13
+ import vm from "node:vm";
14
+ import { defaultGenerated } from "../generated.js";
15
+ import { sendCall } from "../client/index.js";
16
+ import { assembleResult, validateExecInput } from "./result.js";
17
+
18
+ /** The published limits (client.json limits), as the local runner applies them. */
19
+ export function localLimits(generated = defaultGenerated()) {
20
+ const { wallSeconds, callsPerScript, callsInFlight, resultChars, logKiB } = generated.manifest.limits;
21
+ return Object.freeze({ wallMs: wallSeconds * 1000, maxCalls: callsPerScript, callsInFlight, resultChars, logBytes: logKiB * 1024, maxOldGenerationSizeMb: 256 });
22
+ }
23
+
24
+ const WRAP_OPEN = "(async () => {";
25
+ const WRAP_CLOSE = "\n})()";
26
+
27
+ // stripTypeScriptTypes announces itself as experimental on stderr; that line is not the
28
+ // person's business, and the CLI keeps stderr to one summary line.
29
+ function quietStrip(source) {
30
+ const emit = process.emitWarning;
31
+ process.emitWarning = (warning, ...rest) => {
32
+ const text = typeof warning === "string" ? warning : warning?.message;
33
+ if (/stripTypeScriptTypes|Type Stripping/i.test(String(text))) return;
34
+ return emit.call(process, warning, ...rest);
35
+ };
36
+ try {
37
+ return stripTypeScriptTypes(source, { mode: "strip" });
38
+ } finally {
39
+ process.emitWarning = emit;
40
+ }
41
+ }
42
+
43
+ /** The caller's code as one async function body; TypeScript is stripped in place (same lines). */
44
+ export function prepareSource({ prelude, trailer }, code) {
45
+ const body = "\n" + code + WRAP_CLOSE;
46
+ const plain = (text) => text.slice(0, -WRAP_CLOSE.length);
47
+ let parsed = body;
48
+ try {
49
+ new vm.Script(WRAP_OPEN + body);
50
+ } catch (syntax) {
51
+ if (!(syntax instanceof SyntaxError)) throw syntax;
52
+ try {
53
+ // Strip the wrapped text so top-level await and return parse; whitespace keeps positions.
54
+ parsed = quietStrip(WRAP_OPEN + body).slice(WRAP_OPEN.length);
55
+ } catch {
56
+ parsed = body; // not TypeScript either: the script process reports the JavaScript syntax error
57
+ }
58
+ }
59
+ // The prelude is one line, inside the wrapper, so the caller's line 1 is the file's line 2.
60
+ return WRAP_OPEN + prelude + plain(parsed) + trailer + WRAP_CLOSE;
61
+ }
62
+
63
+ const SCRIPT_PROCESS = fileURLToPath(new URL("./script-process.js", import.meta.url));
64
+ // The script's environment is empty, as on the server; Windows needs SystemRoot to start Node.
65
+ const scriptEnv = () => (process.platform === "win32" && process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {});
66
+
67
+ const headerSafe = (text) => encodeURIComponent(text).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
68
+
69
+ // The script rules (preview, confirm before save, the audit record) are the server's. A
70
+ // Slatebox that does not run exec would take each call as an ordinary API call and save it, a
71
+ // preview run's writes included, so nothing is sent until the instance says it runs exec:
72
+ // GET /api/v1/instance names exec's limits (limits.exec). A yes is kept for ten minutes.
73
+ const EXEC_INSTANCE_MS = 10 * 60 * 1000;
74
+ const execInstances = new Map();
75
+ const INSTANCE_ROUTE = { name: "instance.describe", kind: "read", http: { method: "GET", path: "/api/v1/instance", pathParams: [], queryParams: [], bodyParams: [] } };
76
+
77
+ export async function checkExecInstance({ baseUrl, token, fetchImpl = fetch, now = Date.now }) {
78
+ if ((execInstances.get(baseUrl) ?? 0) > now()) return null;
79
+ const answer = await sendCall({ baseUrl, token, fetchImpl, method: INSTANCE_ROUTE, input: {} });
80
+ if (answer.ok && answer.body?.limits?.exec) {
81
+ execInstances.set(baseUrl, now() + EXEC_INSTANCE_MS);
82
+ return null;
83
+ }
84
+ if (!answer.ok && [0, 401, 429].includes(answer.status)) return answer.error;
85
+ return { code: "exec_unavailable", status: answer.status,
86
+ message: `${baseUrl} does not run exec scripts (GET /api/v1/instance names no exec limits), so nothing was sent. Point --base-url or SLATEBOX_BASE_URL at a Slatebox that runs exec.` };
87
+ }
88
+
89
+ /**
90
+ * Run a script locally. Throws {code:'invalid_request'} for bad exec input; otherwise always
91
+ * resolves with the exec result (status completed, failed or confirmation_required).
92
+ */
93
+ export async function runLocal({ code, intent, mode = "save", confirm, idempotencyKey, baseUrl, token, fetchImpl = fetch,
94
+ generated = defaultGenerated(), limits = localLimits(generated) }) {
95
+ validateExecInput({ code, intent, mode, confirm, idempotencyKey });
96
+ const execId = randomUUID();
97
+ const execKey = idempotencyKey ?? execId;
98
+ const codeSha256 = createHash("sha256").update(code).digest("hex");
99
+ const baseHeaders = {
100
+ "slatebox-exec-id": execId,
101
+ "slatebox-exec-key": execKey,
102
+ "slatebox-exec-code-sha256": codeSha256,
103
+ "slatebox-exec-mode": mode,
104
+ "slatebox-exec-intent": headerSafe(intent),
105
+ ...(confirm ? { "slatebox-exec-confirm": confirm } : {}),
106
+ };
107
+ const started = Date.now();
108
+ const state = { calls: [], responses: [], logs: [], held: null, outcome: null };
109
+ const unavailable = await checkExecInstance({ baseUrl, token, fetchImpl });
110
+ if (unavailable)
111
+ return assembleResult({ execId, mode, execKey, outcome: { ok: false, error: unavailable }, calls: [], responses: [],
112
+ logs: [], held: null, limits, wallMs: Date.now() - started });
113
+ const source = prepareSource(generated, code);
114
+
115
+ const child = fork(SCRIPT_PROCESS, [], {
116
+ env: scriptEnv(),
117
+ // Our own flags only: the host's (--test, --input-type, an inspector) are not the script's.
118
+ execArgv: [`--max-old-space-size=${limits.maxOldGenerationSizeMb}`],
119
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
120
+ serialization: "json",
121
+ });
122
+ const toScript = (message) => {
123
+ if (child.connected) child.send(message, (failure) => void failure);
124
+ };
125
+ // Node reports a heap overflow on stderr before it aborts.
126
+ let outOfMemory = false;
127
+ let stderrTail = "";
128
+ child.stderr.on("data", (chunk) => {
129
+ stderrTail = (stderrTail + chunk).slice(-256);
130
+ if (/heap out of memory|allocation failed/i.test(stderrTail)) outOfMemory = true;
131
+ });
132
+ const capture = (stream, prefix) => {
133
+ let buffer = "";
134
+ stream.setEncoding("utf8");
135
+ stream.on("data", (chunk) => {
136
+ buffer += chunk;
137
+ let index;
138
+ while ((index = buffer.indexOf("\n")) >= 0) {
139
+ state.logs.push(prefix + buffer.slice(0, index));
140
+ buffer = buffer.slice(index + 1);
141
+ }
142
+ });
143
+ stream.on("end", () => { if (buffer) state.logs.push(prefix + buffer); });
144
+ };
145
+ capture(child.stdout, "");
146
+ capture(child.stderr, "stderr: ");
147
+
148
+ const inFlight = new Set();
149
+ let count = 0;
150
+ // At most callsInFlight requests at once, as in the sealed runner; the rest wait their turn.
151
+ const maxInFlight = Number.isSafeInteger(limits.callsInFlight) && limits.callsInFlight > 0 ? limits.callsInFlight : 1;
152
+ let active = 0;
153
+ const waiting = [];
154
+ const takeSlot = () => (active < maxInFlight ?(active += 1, Promise.resolve()) : new Promise((resolve) => waiting.push(resolve)));
155
+ const giveSlot = () => { const next = waiting.shift(); if (next) next(); else active -= 1; };
156
+ let finished;
157
+ const done = new Promise((resolve) => { finished = resolve; });
158
+ const finish = (outcome) => {
159
+ if (state.outcome) return;
160
+ state.outcome = outcome;
161
+ finished();
162
+ };
163
+
164
+ async function call({ seq, method: name, input }) {
165
+ count += 1;
166
+ if (count > limits.maxCalls) {
167
+ finish({ ok: false, error: { code: "call_limit", message: `A script may make ${limits.maxCalls} calls.` } });
168
+ return;
169
+ }
170
+ const method = generated.methods.get(name);
171
+ const t0 = Date.now();
172
+ if (!method) {
173
+ state.calls.push({ n: seq, method: name, mode: null, ok: false, status: 404, code: "unknown_method", ms: 0 });
174
+ toScript({ t: "reply", seq, envelope: { ok: false, error: { code: "unknown_method", status: 404, message: `There is no method ${name}. Call describe.` } } });
175
+ return;
176
+ }
177
+ // A preview run previews every write here as well as on the server: each write is sent as a
178
+ // preview, and a write that cannot be previewed is refused before it is sent.
179
+ let sent = input;
180
+ if (mode === "preview" && method.kind === "write") {
181
+ if (!(method.modes ?? []).includes("preview")) {
182
+ state.calls.push({ n: seq, method: name, mode: "preview", ok: false, status: 400, code: "preview_unavailable", ms: 0 });
183
+ toScript({ t: "reply", seq, envelope: { ok: false, error: { code: "preview_unavailable", status: 400,
184
+ message: `${name} cannot be previewed, so this preview run stops here.`, details: { method: name } } } });
185
+ return;
186
+ }
187
+ // Not one plain object: the server refuses it as it stands.
188
+ if (input && typeof input === "object" && !Array.isArray(input)) sent = { ...input, mode: "preview" };
189
+ }
190
+ await takeSlot();
191
+ let outcome;
192
+ try {
193
+ outcome = await sendCall({ baseUrl, token, fetchImpl, method, input: sent,
194
+ headers: { ...baseHeaders, "slatebox-exec-call": String(seq) } });
195
+ } finally {
196
+ giveSlot();
197
+ }
198
+ const record = { n: seq, method: name, mode: null, ok: outcome.ok, status: outcome.status };
199
+ if (method.kind === "write") record.mode = outcome.body?.mode ?? (mode === "preview" ? "preview" : input?.mode ?? "save");
200
+ if (!outcome.ok) record.code = outcome.error.code;
201
+ const heldId = outcome.headers.get("slatebox-exec-held");
202
+ if (heldId) {
203
+ record.held = true;
204
+ const details = outcome.error?.details ?? {};
205
+ state.held ??= {
206
+ id: heldId,
207
+ ...(details.expiresAt ? { expiresAt: details.expiresAt } : {}),
208
+ reasons: (details.reasons ?? []).map((reason) => ({ n: seq, ...reason })),
209
+ };
210
+ }
211
+ if (outcome.headers.get("idempotent-replayed") === "true") record.replayed = true;
212
+ record.ms = Date.now() - t0;
213
+ state.calls.push(record);
214
+ if (outcome.ok) state.responses.push({ method, body: outcome.body });
215
+ toScript({ t: "reply", seq, envelope: outcome.ok ? { ok: true, value: outcome.body } : { ok: false, error: outcome.error } });
216
+ }
217
+
218
+ child.on("message", (message) => {
219
+ if (message?.t === "call") {
220
+ const pendingCall = call(message).catch((failure) => finish({ ok: false, error: { code: "internal_error", message: failure.message } }));
221
+ inFlight.add(pendingCall);
222
+ pendingCall.finally(() => inFlight.delete(pendingCall));
223
+ } else if (message?.t === "done") {
224
+ const { outcome } = message;
225
+ state.logs.unshift(...(Array.isArray(outcome?.logs) ? outcome.logs.map(String) : []));
226
+ if (outcome?.ok && message.inFlight > 0) {
227
+ finish({ ok: false, error: { code: "detached_call", message: "The script returned while a call was still running. Await every call." } });
228
+ } else if (outcome?.ok) {
229
+ finish({ ok: true, json: outcome.json === null ? "null" : String(outcome.json) });
230
+ } else {
231
+ finish({ ok: false, error: { code: "script_error", message: "The script failed.", ...outcome?.error } });
232
+ }
233
+ }
234
+ });
235
+ child.on("error", (error) => finish({ ok: false, error: { code: "script_error", message: `The script could not start: ${error?.message ?? error}` } }));
236
+ // The process ended before it said done: read its stderr to the end to say why.
237
+ const ended = () => finish({ ok: false, error: outOfMemory
238
+ ? { code: "memory", message: "The script ran out of memory." }
239
+ : { code: "script_error", message: "The script stopped unexpectedly." } });
240
+ child.once("exit", () => setTimeout(ended, 500).unref());
241
+ const closed = new Promise((resolve) => child.once("close", () => { ended(); resolve(); }));
242
+ const timer = setTimeout(() => finish({ ok: false, error: { code: "timeout", message: `The script ran past ${limits.wallMs / 1000} s.` } }), limits.wallMs);
243
+ toScript({ t: "run", source });
244
+
245
+ await done;
246
+ clearTimeout(timer);
247
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
248
+ // Its output is read to the end, unless something it started still holds the pipes open.
249
+ await Promise.race([closed, new Promise((resolve) => setTimeout(resolve, 1000).unref())]);
250
+ child.stdout.destroy();
251
+ child.stderr.destroy();
252
+ // Calls already sent finish, so the result lists every request that reached the server.
253
+ await Promise.allSettled([...inFlight]);
254
+
255
+ return assembleResult({ execId, mode, execKey, outcome: state.outcome, calls: state.calls, responses: state.responses,
256
+ logs: state.logs, held: state.held, limits, wallMs: Date.now() - started });
257
+ }