@koneeric/onetool 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +68 -2
- package/bin/onetool.js +4 -0
- package/core/src/index.js +732 -0
- package/guide/pages/INSTALL.md +636 -0
- package/guide/pages/settings.example.json +6 -0
- package/hosts/src/adapters/claude-code.js +136 -0
- package/hosts/src/index.js +107 -0
- package/library/src/index.js +544 -0
- package/package.json +35 -4
- package/practice/src/rows.js +15 -0
- package/practice/src/server.js +162 -0
- package/sandbox/src/child.mjs +421 -0
- package/sandbox/src/index.js +300 -0
- package/sandbox/src/last-expression.mjs +134 -0
- package/sandbox/src/probe.mjs +42 -0
- package/server/src/connect.js +128 -0
- package/server/src/descriptions.js +61 -0
- package/server/src/host.js +116 -0
- package/server/src/library.js +207 -0
- package/server/src/main.js +106 -0
- package/server/src/prompt.js +15 -0
- package/server/src/record.js +131 -0
- package/server/src/tools.js +461 -0
- package/shell/src/index.js +270 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
5
|
+
import { CallToolRequestSchema, ListToolsRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
|
|
6
|
+
import { allRows } from "./rows.js";
|
|
7
|
+
|
|
8
|
+
const str = { type: "string" };
|
|
9
|
+
|
|
10
|
+
const TOOLS = [
|
|
11
|
+
{
|
|
12
|
+
name: "rows",
|
|
13
|
+
description: "Returns the practice table: 5,000 rows of id, name, city and amount. Use it to try programs on a large result.",
|
|
14
|
+
inputSchema: { type: "object", properties: { city: str } },
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: "count",
|
|
18
|
+
description: "Counts the rows of the practice table. Answers as JSON text.",
|
|
19
|
+
inputSchema: { type: "object", properties: { city: str } },
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
name: "echo",
|
|
23
|
+
description: "Answers with the text it was given. Plain text.",
|
|
24
|
+
inputSchema: { type: "object", properties: { text: str }, required: ["text"] },
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
name: "fail",
|
|
28
|
+
description: "Always fails. Use it to try what a program does with a failing tool.",
|
|
29
|
+
inputSchema: { type: "object", properties: { reason: str } },
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
name: "wipe",
|
|
33
|
+
description: "Pretends to delete the practice table. It deletes nothing.",
|
|
34
|
+
inputSchema: { type: "object", properties: {} },
|
|
35
|
+
},
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
const text = (t) => ({ content: [{ type: "text", text: t }] });
|
|
39
|
+
const failed = (t) => ({ isError: true, ...text(t) });
|
|
40
|
+
|
|
41
|
+
/** The rows of the table, or those of the city given; `undefined` when `city` is given and is not a string. */
|
|
42
|
+
function chosen(args) {
|
|
43
|
+
if (args.city !== undefined && typeof args.city !== "string") return undefined;
|
|
44
|
+
const rows = allRows();
|
|
45
|
+
return args.city === undefined ? rows : rows.filter((r) => r.city === args.city);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const notString = (property) => failed(`practice: ${property} must be a string`);
|
|
49
|
+
|
|
50
|
+
const HANDLERS = {
|
|
51
|
+
rows(args) {
|
|
52
|
+
const rows = chosen(args);
|
|
53
|
+
if (rows === undefined) return notString("city");
|
|
54
|
+
return { content: [{ type: "text", text: JSON.stringify({ rows }) }], structuredContent: { rows } };
|
|
55
|
+
},
|
|
56
|
+
count(args) {
|
|
57
|
+
const rows = chosen(args);
|
|
58
|
+
if (rows === undefined) return notString("city");
|
|
59
|
+
return text(JSON.stringify({ count: rows.length }));
|
|
60
|
+
},
|
|
61
|
+
echo(args) {
|
|
62
|
+
if (typeof args.text !== "string") return notString("text");
|
|
63
|
+
return text(args.text);
|
|
64
|
+
},
|
|
65
|
+
fail(args) {
|
|
66
|
+
if (args.reason !== undefined && typeof args.reason !== "string") return notString("reason");
|
|
67
|
+
return failed(`practice failure: ${args.reason ?? "asked to fail"}`);
|
|
68
|
+
},
|
|
69
|
+
wipe() {
|
|
70
|
+
return text("wiped");
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
function createServer() {
|
|
75
|
+
const server = new Server({ name: "practice", version: "1.0.0" }, { capabilities: { tools: {} } });
|
|
76
|
+
|
|
77
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
|
78
|
+
|
|
79
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
80
|
+
const { name, arguments: given } = request.params;
|
|
81
|
+
if (!Object.hasOwn(HANDLERS, name)) throw new McpError(ErrorCode.InvalidParams, `unknown tool: ${name}`);
|
|
82
|
+
const args = given !== null && typeof given === "object" ? given : {};
|
|
83
|
+
return HANDLERS[name](args);
|
|
84
|
+
});
|
|
85
|
+
return server;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const USAGE = "usage: node practice/src/server.js [--port <number> [--token <text>]]";
|
|
89
|
+
|
|
90
|
+
/** `{port, token}` from the arguments (`token` is `undefined` when not given); `undefined` when they are not a form of the usage. */
|
|
91
|
+
function parseArguments(argv) {
|
|
92
|
+
if (argv.length === 0) return { port: undefined, token: undefined };
|
|
93
|
+
if (argv.length % 2 !== 0 || argv.length > 4) return undefined;
|
|
94
|
+
const given = {};
|
|
95
|
+
for (let i = 0; i < argv.length; i += 2) {
|
|
96
|
+
const option = argv[i];
|
|
97
|
+
if ((option !== "--port" && option !== "--token") || Object.hasOwn(given, option)) return undefined;
|
|
98
|
+
given[option] = argv[i + 1];
|
|
99
|
+
}
|
|
100
|
+
const { "--port": port, "--token": token } = given;
|
|
101
|
+
if (port === undefined || !/^[0-9]+$/.test(port) || Number(port) > 65535) return undefined;
|
|
102
|
+
if (token === "") return undefined;
|
|
103
|
+
return { port: Number(port), token };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The header may reach us as Latin-1 text of the bytes a client wrote in UTF-8; both spellings of the token are accepted. */
|
|
107
|
+
function authorized(header, token) {
|
|
108
|
+
if (header === undefined) return false;
|
|
109
|
+
return header === `Bearer ${token}` || Buffer.from(header, "latin1").toString("utf8") === `Bearer ${token}`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function serveRequest(req, res) {
|
|
113
|
+
const server = createServer();
|
|
114
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
115
|
+
res.on("close", () => {
|
|
116
|
+
transport.close().catch(() => {});
|
|
117
|
+
server.close().catch(() => {});
|
|
118
|
+
});
|
|
119
|
+
await server.connect(transport);
|
|
120
|
+
await transport.handleRequest(req, res);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function listen(port, token) {
|
|
124
|
+
const httpServer = http.createServer((req, res) => {
|
|
125
|
+
const path = (req.url ?? "").split("?")[0];
|
|
126
|
+
if (path !== "/mcp") {
|
|
127
|
+
res.writeHead(404).end();
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (token !== undefined && !authorized(req.headers.authorization, token)) {
|
|
131
|
+
res.writeHead(401).end();
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
serveRequest(req, res).catch(() => {
|
|
135
|
+
if (!res.headersSent) res.writeHead(500);
|
|
136
|
+
res.end();
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
const cannot = () => {
|
|
140
|
+
process.stderr.write(`practice: cannot listen on port ${port}\n`);
|
|
141
|
+
process.exit(1);
|
|
142
|
+
};
|
|
143
|
+
httpServer.once("error", cannot);
|
|
144
|
+
httpServer.listen(port, "127.0.0.1", () => {
|
|
145
|
+
httpServer.off("error", cannot);
|
|
146
|
+
process.stdout.write(`practice: listening on http://127.0.0.1:${httpServer.address().port}/mcp\n`);
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const options = parseArguments(process.argv.slice(2));
|
|
151
|
+
if (options === undefined) {
|
|
152
|
+
process.stderr.write(`${USAGE}\n`);
|
|
153
|
+
process.exit(2);
|
|
154
|
+
} else if (options.port !== undefined) {
|
|
155
|
+
listen(options.port, options.token);
|
|
156
|
+
} else {
|
|
157
|
+
const server = createServer();
|
|
158
|
+
process.stdin.on("end", () => {
|
|
159
|
+
server.close().catch(() => {});
|
|
160
|
+
});
|
|
161
|
+
await server.connect(new StdioServerTransport());
|
|
162
|
+
}
|
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
// The process of the program. It reads one JSON object per line on standard input and writes one per line on
|
|
2
|
+
// standard output; see index.js for the lines. The program runs in a context of its own, and only strings cross
|
|
3
|
+
// between that context and this code, so nothing of this realm (and so no `process`) reaches the program.
|
|
4
|
+
import vm from "node:vm";
|
|
5
|
+
import { withLastExpression } from "./last-expression.mjs";
|
|
6
|
+
|
|
7
|
+
// Runs inside the context. It may use nothing from outside but `host`, which is held by its closures alone.
|
|
8
|
+
function bootstrap(host) {
|
|
9
|
+
"use strict";
|
|
10
|
+
const { stringify, parse } = JSON;
|
|
11
|
+
const text = String;
|
|
12
|
+
const AsyncFunction = (async function () {}).constructor;
|
|
13
|
+
const { getPrototypeOf } = Object;
|
|
14
|
+
const ObjectPrototype = Object.prototype;
|
|
15
|
+
const define = (name, value) =>
|
|
16
|
+
Object.defineProperty(globalThis, name, { value, writable: true, configurable: true, enumerable: false });
|
|
17
|
+
|
|
18
|
+
// A stack trace would hand the program the functions of the frames that made it.
|
|
19
|
+
Object.defineProperty(Error, "prepareStackTrace", { value: undefined, writable: false, configurable: false });
|
|
20
|
+
|
|
21
|
+
const describe = (thrown) => {
|
|
22
|
+
try {
|
|
23
|
+
return thrown instanceof Error ? thrown.name + ": " + thrown.message : text(thrown);
|
|
24
|
+
} catch (_) {
|
|
25
|
+
return "";
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const toText = (argument) => {
|
|
30
|
+
if (typeof argument === "string") return argument;
|
|
31
|
+
if (argument === undefined) return "undefined";
|
|
32
|
+
try {
|
|
33
|
+
const json = stringify(argument);
|
|
34
|
+
if (json !== undefined) return json;
|
|
35
|
+
} catch (_) {}
|
|
36
|
+
try {
|
|
37
|
+
return text(argument);
|
|
38
|
+
} catch (_) {
|
|
39
|
+
return "";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const console = {};
|
|
43
|
+
for (const name of ["log", "info", "warn", "error", "debug"]) {
|
|
44
|
+
console[name] = (...args) => host.log(args.map(toText).join(" "));
|
|
45
|
+
}
|
|
46
|
+
define("console", console);
|
|
47
|
+
|
|
48
|
+
// `progress`, when the caller gave onProgress: a line built as console.log builds its string, posted at once.
|
|
49
|
+
const defineProgress = () => {
|
|
50
|
+
define("progress", function progress(...args) {
|
|
51
|
+
host.progress(args.map(toText).join(" "));
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const timers = new Map();
|
|
56
|
+
let timerId = 0;
|
|
57
|
+
define("setTimeout", function setTimeout(callback, delay, ...args) {
|
|
58
|
+
if (typeof callback !== "function") throw new TypeError("The callback must be a function");
|
|
59
|
+
delay = Number(delay);
|
|
60
|
+
if (!(delay >= 1)) delay = 1;
|
|
61
|
+
const id = ++timerId;
|
|
62
|
+
timers.set(id, [callback, args]);
|
|
63
|
+
host.timer(id, Math.min(delay, 2147483647));
|
|
64
|
+
return id;
|
|
65
|
+
});
|
|
66
|
+
define("clearTimeout", function clearTimeout(id) {
|
|
67
|
+
if (timers.delete(id)) host.untimer(id);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// The global `state`, when the caller gave one; the object the result is read from.
|
|
71
|
+
let kept = null;
|
|
72
|
+
const readState = () => {
|
|
73
|
+
if (kept === null) return undefined;
|
|
74
|
+
try {
|
|
75
|
+
const json = stringify(kept);
|
|
76
|
+
const back = typeof json === "string" ? parse(json) : null;
|
|
77
|
+
if (typeof back === "object" && back !== null && !Array.isArray(back)) return json;
|
|
78
|
+
} catch (_) {}
|
|
79
|
+
return null;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const pending = new Map();
|
|
83
|
+
let callId = 0;
|
|
84
|
+
const makeTool = (server, tool) =>
|
|
85
|
+
async function (args) {
|
|
86
|
+
let json;
|
|
87
|
+
try {
|
|
88
|
+
json = args === undefined ? "{}" : stringify(args);
|
|
89
|
+
} catch (_) {
|
|
90
|
+
throw new Error("the arguments cannot be sent as JSON");
|
|
91
|
+
}
|
|
92
|
+
if (json === undefined) json = "{}";
|
|
93
|
+
return new Promise((resolve, reject) => {
|
|
94
|
+
const id = ++callId;
|
|
95
|
+
pending.set(id, [resolve, reject]);
|
|
96
|
+
host.call(id, server, tool, json);
|
|
97
|
+
});
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
// The four names of `shell: true`: more ways to make a tool call of the server "shell", nothing else.
|
|
101
|
+
const defineShell = () => {
|
|
102
|
+
const callRead = makeTool("shell", "read");
|
|
103
|
+
const callWrite = makeTool("shell", "write");
|
|
104
|
+
const callEdit = makeTool("shell", "edit");
|
|
105
|
+
const callRun = makeTool("shell", "run");
|
|
106
|
+
|
|
107
|
+
define("read", async function read(path) {
|
|
108
|
+
return callRead({ path });
|
|
109
|
+
});
|
|
110
|
+
define("write", async function write(path, text) {
|
|
111
|
+
return callWrite({ path, text });
|
|
112
|
+
});
|
|
113
|
+
define("edit", async function edit(path, old, replacement) {
|
|
114
|
+
return callEdit({ path, old, new: replacement });
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
const quote = (value) => "'" + value.split("'").join("'\\''") + "'";
|
|
118
|
+
const word = (value) => {
|
|
119
|
+
const kind = typeof value;
|
|
120
|
+
if (kind === "string") return quote(value);
|
|
121
|
+
if (kind === "number" || kind === "boolean") return quote(text(value));
|
|
122
|
+
throw new TypeError("a value in a command must be a string, a number, a boolean or a list of them");
|
|
123
|
+
};
|
|
124
|
+
const insert = (value) => {
|
|
125
|
+
if (!Array.isArray(value)) return word(value);
|
|
126
|
+
let out = "";
|
|
127
|
+
for (let i = 0; i < value.length; i++) out += (i > 0 ? " " : "") + word(value[i]);
|
|
128
|
+
return out;
|
|
129
|
+
};
|
|
130
|
+
const failure = ({ exitCode, stdout, stderr }) => {
|
|
131
|
+
const detail = stderr.trim().slice(0, 500);
|
|
132
|
+
const error = new Error("the command failed with exit code " + exitCode + (detail === "" ? "" : ": " + detail));
|
|
133
|
+
error.exitCode = exitCode;
|
|
134
|
+
error.stdout = stdout;
|
|
135
|
+
error.stderr = stderr;
|
|
136
|
+
return error;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
// A command object starts nothing until `then` or `text` is called; then it makes the one call.
|
|
140
|
+
const command = (commandText) => {
|
|
141
|
+
let started = null;
|
|
142
|
+
let throws = true;
|
|
143
|
+
const start = () => {
|
|
144
|
+
if (started === null) {
|
|
145
|
+
started = callRun({ command: commandText }).then((result) => {
|
|
146
|
+
if (throws && result.exitCode !== 0) throw failure(result);
|
|
147
|
+
return result;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
return started;
|
|
151
|
+
};
|
|
152
|
+
const object = {
|
|
153
|
+
then: (onDone, onFail) => start().then(onDone, onFail),
|
|
154
|
+
text: () => start().then((result) => result.stdout),
|
|
155
|
+
nothrow() {
|
|
156
|
+
throws = false;
|
|
157
|
+
return object;
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
return object;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
define("$", function $(first) {
|
|
164
|
+
if (typeof first === "string") return command(first);
|
|
165
|
+
if (Array.isArray(first) && Array.isArray(first.raw)) {
|
|
166
|
+
const raw = first.raw;
|
|
167
|
+
let out = raw[0];
|
|
168
|
+
for (let i = 1; i < arguments.length; i++) out += insert(arguments[i]) + raw[i];
|
|
169
|
+
return command(out);
|
|
170
|
+
}
|
|
171
|
+
throw new TypeError("$ takes a template or one string");
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// `lib` and `library`, when the caller gave a library: the saved programs run here, in this world, as one more
|
|
176
|
+
// way to run text; `library.save`, `remove`, `report`, `restore` and `read` are five more ways to make a tool call
|
|
177
|
+
// of the server "library". Nothing else is given to the program.
|
|
178
|
+
const IDENTIFIER = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
|
|
179
|
+
const defineLibrary = (items) => {
|
|
180
|
+
const isPlain = (value) => {
|
|
181
|
+
if (typeof value !== "object" || value === null) return false;
|
|
182
|
+
const prototype = getPrototypeOf(value);
|
|
183
|
+
return prototype === ObjectPrototype || prototype === null;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
// Each name of params is checked as a bare identifier before it is handed to the compiler, so that no text of
|
|
187
|
+
// params can end the parameter list; the compiler then refuses what the language refuses.
|
|
188
|
+
const compileItem = (params, code) => {
|
|
189
|
+
for (const param of params) {
|
|
190
|
+
if (!IDENTIFIER.test(param)) throw new SyntaxError("Invalid parameter name: " + param);
|
|
191
|
+
}
|
|
192
|
+
let fn = new AsyncFunction(...params, code);
|
|
193
|
+
for (const variant of parse(host.variants(code))) {
|
|
194
|
+
try {
|
|
195
|
+
fn = new AsyncFunction(...params, variant);
|
|
196
|
+
break;
|
|
197
|
+
} catch (_) {}
|
|
198
|
+
}
|
|
199
|
+
return fn;
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const makeSaved = (name, params, code) => {
|
|
203
|
+
let compiled = null;
|
|
204
|
+
return async function (args) {
|
|
205
|
+
let ok = false;
|
|
206
|
+
try {
|
|
207
|
+
if (args === undefined) args = {};
|
|
208
|
+
else if (!isPlain(args)) throw new TypeError("the arguments of a saved program must be an object");
|
|
209
|
+
if (compiled === null) {
|
|
210
|
+
try {
|
|
211
|
+
compiled = { fn: compileItem(params, code) };
|
|
212
|
+
} catch (thrown) {
|
|
213
|
+
compiled = { thrown };
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if ("thrown" in compiled) throw compiled.thrown;
|
|
217
|
+
const values = [];
|
|
218
|
+
for (const param of params) values.push(args[param]);
|
|
219
|
+
const value = await compiled.fn(...values);
|
|
220
|
+
ok = true;
|
|
221
|
+
return value;
|
|
222
|
+
} finally {
|
|
223
|
+
host.use(name, ok);
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
const lib = {};
|
|
229
|
+
for (const { name, params, code } of items) {
|
|
230
|
+
Object.defineProperty(lib, name, { value: makeSaved(name, params, code), writable: true, enumerable: true, configurable: true });
|
|
231
|
+
}
|
|
232
|
+
define("lib", lib);
|
|
233
|
+
|
|
234
|
+
const callSave = makeTool("library", "save");
|
|
235
|
+
const callRemove = makeTool("library", "remove");
|
|
236
|
+
const library = {};
|
|
237
|
+
Object.defineProperty(library, "save", {
|
|
238
|
+
value: async function save(name, options) {
|
|
239
|
+
const given = typeof options === "object" && options !== null ? options : {};
|
|
240
|
+
return callSave({ name, about: given.about, params: given.params, code: given.code, replace: given.replace });
|
|
241
|
+
},
|
|
242
|
+
writable: true, enumerable: true, configurable: true,
|
|
243
|
+
});
|
|
244
|
+
Object.defineProperty(library, "remove", {
|
|
245
|
+
value: async function remove(name) {
|
|
246
|
+
return callRemove({ name });
|
|
247
|
+
},
|
|
248
|
+
writable: true, enumerable: true, configurable: true,
|
|
249
|
+
});
|
|
250
|
+
const callReport = makeTool("library", "report");
|
|
251
|
+
const callRestore = makeTool("library", "restore");
|
|
252
|
+
const callRead = makeTool("library", "read");
|
|
253
|
+
Object.defineProperty(library, "report", {
|
|
254
|
+
value: async function report() {
|
|
255
|
+
return callReport({});
|
|
256
|
+
},
|
|
257
|
+
writable: true, enumerable: true, configurable: true,
|
|
258
|
+
});
|
|
259
|
+
Object.defineProperty(library, "restore", {
|
|
260
|
+
value: async function restore(name) {
|
|
261
|
+
return callRestore({ name });
|
|
262
|
+
},
|
|
263
|
+
writable: true, enumerable: true, configurable: true,
|
|
264
|
+
});
|
|
265
|
+
Object.defineProperty(library, "read", {
|
|
266
|
+
value: async function read(name) {
|
|
267
|
+
return callRead({ name });
|
|
268
|
+
},
|
|
269
|
+
writable: true, enumerable: true, configurable: true,
|
|
270
|
+
});
|
|
271
|
+
define("library", library);
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
return {
|
|
275
|
+
init(toolsJson, stateJson, shell, posts, libraryJson) {
|
|
276
|
+
if (shell) defineShell();
|
|
277
|
+
if (posts) defineProgress();
|
|
278
|
+
if (stateJson !== null) {
|
|
279
|
+
kept = parse(stateJson);
|
|
280
|
+
Object.defineProperty(globalThis, "state", { value: kept, writable: false, configurable: false, enumerable: false });
|
|
281
|
+
}
|
|
282
|
+
const spec = parse(toolsJson);
|
|
283
|
+
const tools = {};
|
|
284
|
+
for (const server of Object.keys(spec)) {
|
|
285
|
+
const entry = {};
|
|
286
|
+
for (const tool of spec[server]) {
|
|
287
|
+
Object.defineProperty(entry, tool, {
|
|
288
|
+
value: makeTool(server, tool), writable: true, enumerable: true, configurable: true,
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
Object.defineProperty(tools, server, { value: entry, writable: true, enumerable: true, configurable: true });
|
|
292
|
+
}
|
|
293
|
+
define("tools", tools);
|
|
294
|
+
if (libraryJson !== null) defineLibrary(parse(libraryJson));
|
|
295
|
+
},
|
|
296
|
+
compile: (body) => new AsyncFunction(body),
|
|
297
|
+
fail: (thrown) => host.done("error", describe(thrown), readState()),
|
|
298
|
+
start(fn) {
|
|
299
|
+
(async () => {
|
|
300
|
+
let value;
|
|
301
|
+
try {
|
|
302
|
+
value = await fn();
|
|
303
|
+
} catch (thrown) {
|
|
304
|
+
host.done("error", describe(thrown), readState());
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
const state = readState();
|
|
308
|
+
let json;
|
|
309
|
+
try {
|
|
310
|
+
json = stringify(value);
|
|
311
|
+
} catch (_) {
|
|
312
|
+
host.done("error", "the value cannot be sent as JSON", state);
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
if (json === undefined) host.done("undefined", "", state);
|
|
316
|
+
else host.done("value", json, state);
|
|
317
|
+
})();
|
|
318
|
+
},
|
|
319
|
+
fire(id) {
|
|
320
|
+
const timer = timers.get(id);
|
|
321
|
+
if (!timer) return;
|
|
322
|
+
timers.delete(id);
|
|
323
|
+
try {
|
|
324
|
+
timer[0](...timer[1]);
|
|
325
|
+
} catch (thrown) {
|
|
326
|
+
host.done("error", describe(thrown), readState());
|
|
327
|
+
}
|
|
328
|
+
},
|
|
329
|
+
deliver(id, status, answer) {
|
|
330
|
+
const call = pending.get(id);
|
|
331
|
+
if (!call) return;
|
|
332
|
+
pending.delete(id);
|
|
333
|
+
if (status === "ok") call[0](parse(answer));
|
|
334
|
+
else if (status === "undefined") call[0](undefined);
|
|
335
|
+
else call[1](new Error(answer));
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const send = (message) => process.stdout.write(JSON.stringify(message) + "\n");
|
|
341
|
+
// Whatever goes wrong here must not reach the program, nor end this process.
|
|
342
|
+
const quiet = (fn) => {
|
|
343
|
+
try {
|
|
344
|
+
fn();
|
|
345
|
+
} catch (_) {}
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
const timeouts = new Map();
|
|
349
|
+
let boot;
|
|
350
|
+
const host = {
|
|
351
|
+
log: (line) => quiet(() => send({ t: "log", s: String(line) })),
|
|
352
|
+
progress: (line) => quiet(() => send({ t: "progress", s: String(line) })),
|
|
353
|
+
use: (name, ok) => quiet(() => send({ t: "use", name: String(name), ok: ok === true })),
|
|
354
|
+
// the texts a saved program may be run as (see last-expression.mjs), as JSON text: only strings cross
|
|
355
|
+
variants: (code) => {
|
|
356
|
+
try {
|
|
357
|
+
return JSON.stringify([...withLastExpression(String(code))]);
|
|
358
|
+
} catch (_) {
|
|
359
|
+
return "[]";
|
|
360
|
+
}
|
|
361
|
+
},
|
|
362
|
+
call: (id, server, tool, args) => quiet(() => send({ t: "call", id, server, tool, args })),
|
|
363
|
+
// state: JSON text; null when it cannot be held; undefined (left out of the line) when none was given
|
|
364
|
+
done: (kind, answer, state) => quiet(() => send({ t: "done", kind, text: String(answer), state })),
|
|
365
|
+
timer: (id, delay) =>
|
|
366
|
+
quiet(() =>
|
|
367
|
+
timeouts.set(
|
|
368
|
+
id,
|
|
369
|
+
setTimeout(() => {
|
|
370
|
+
timeouts.delete(id);
|
|
371
|
+
quiet(() => boot.fire(id));
|
|
372
|
+
}, delay),
|
|
373
|
+
),
|
|
374
|
+
),
|
|
375
|
+
untimer: (id) =>
|
|
376
|
+
quiet(() => {
|
|
377
|
+
clearTimeout(timeouts.get(id));
|
|
378
|
+
timeouts.delete(id);
|
|
379
|
+
}),
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
const context = vm.createContext(Object.create(null));
|
|
383
|
+
boot = vm.runInContext("(" + bootstrap.toString() + ")", context)(host);
|
|
384
|
+
|
|
385
|
+
function run({ code, tools, state, shell, progress, library }) {
|
|
386
|
+
boot.init(JSON.stringify(tools), state, shell === true, progress === true, Array.isArray(library) ? JSON.stringify(library) : null);
|
|
387
|
+
let fn;
|
|
388
|
+
try {
|
|
389
|
+
fn = boot.compile(code);
|
|
390
|
+
} catch (thrown) {
|
|
391
|
+
boot.fail(thrown);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
for (const text of withLastExpression(code)) {
|
|
395
|
+
try {
|
|
396
|
+
fn = boot.compile(text);
|
|
397
|
+
break;
|
|
398
|
+
} catch (_) {}
|
|
399
|
+
}
|
|
400
|
+
boot.start(fn);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function onMessage(message) {
|
|
404
|
+
if (message.t === "init") run(message);
|
|
405
|
+
else if (message.t === "result") quiet(() => boot.deliver(message.id, message.status, message.text));
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// A caller that has gone, or has no more to say, leaves nothing to run for.
|
|
409
|
+
process.on("unhandledRejection", () => {});
|
|
410
|
+
process.stdin.setEncoding("utf8");
|
|
411
|
+
let buffer = "";
|
|
412
|
+
process.stdin.on("data", (chunk) => {
|
|
413
|
+
buffer += chunk;
|
|
414
|
+
let end;
|
|
415
|
+
while ((end = buffer.indexOf("\n")) >= 0) {
|
|
416
|
+
const line = buffer.slice(0, end);
|
|
417
|
+
buffer = buffer.slice(end + 1);
|
|
418
|
+
onMessage(JSON.parse(line));
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
process.stdin.on("end", () => process.exit(0));
|