@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.
@@ -0,0 +1,300 @@
1
+ // Runs a JavaScript program in a process of its own. See the meeting point of sandbox.
2
+ //
3
+ // Lines on the program process's standard input (from here):
4
+ // { t: "init", code, tools, state, shell, progress, library } once, first; state is JSON text, or null when none
5
+ // was given; shell is true when the program finds `$`, `read`, `write`
6
+ // and `edit`; progress is true when it finds `progress`; library is
7
+ // the list of { name, params, code }, or null when none was given
8
+ // { t: "result", id, status, text } the answer of a tool call: status "ok" (text is JSON),
9
+ // "undefined" or "error" (text is the message)
10
+ // Lines on its standard output (to here):
11
+ // { t: "log", s } { t: "progress", s } { t: "use", name, ok } { t: "call", id, server, tool, args }
12
+ // { t: "done", kind, text, state }
13
+ // state is JSON text, or null when the state cannot be held; it is absent when none was given.
14
+ // checkWalls runs probe.mjs in a process started by the same code (launch), and reads one line of it.
15
+ import { spawn } from "node:child_process";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ const CHILD = fileURLToPath(new URL("./child.mjs", import.meta.url));
19
+ const PROBE = fileURLToPath(new URL("./probe.mjs", import.meta.url));
20
+ const FILES = [CHILD, fileURLToPath(new URL("./last-expression.mjs", import.meta.url))];
21
+ const DEFAULT_MEMORY_MB = 256;
22
+ const NOT_KEPT = "state was not kept: it cannot be sent as JSON";
23
+ const LONGEST_TIMER = 2 ** 31 - 1;
24
+
25
+ const running = new Set();
26
+ let listening = false;
27
+
28
+ function kill(child) {
29
+ if (child.exitCode === null && child.signalCode === null) {
30
+ try {
31
+ child.kill("SIGKILL");
32
+ } catch {
33
+ // already gone
34
+ }
35
+ }
36
+ }
37
+
38
+ function listen() {
39
+ if (listening) return;
40
+ listening = true;
41
+ process.on("exit", () => {
42
+ for (const child of running) kill(child);
43
+ });
44
+ }
45
+
46
+ // The one place a process of the sandbox is started: a program and the probe of checkWalls differ only in the
47
+ // file they run (and the files they may read).
48
+ function launch(script, { files, memoryMb, args = [] }) {
49
+ const child = spawn(
50
+ process.execPath,
51
+ ["--permission", ...files.map((file) => `--allow-fs-read=${file}`), `--max-old-space-size=${memoryMb}`, script, ...args],
52
+ { env: {}, stdio: ["pipe", "pipe", "ignore"], windowsHide: true },
53
+ );
54
+ running.add(child);
55
+ child.stdout.setEncoding("utf8");
56
+ child.stdout.on("error", () => {});
57
+ child.stdin.on("error", () => {});
58
+ return child;
59
+ }
60
+
61
+ function onLines(child, onLine) {
62
+ let buffer = "";
63
+ child.stdout.on("data", (chunk) => {
64
+ buffer += chunk;
65
+ let end;
66
+ while ((end = buffer.indexOf("\n")) >= 0) {
67
+ const line = buffer.slice(0, end);
68
+ buffer = buffer.slice(end + 1);
69
+ onLine(line);
70
+ }
71
+ });
72
+ }
73
+
74
+ // The JSON text of a state the caller gave, or a TypeError.
75
+ function stateText(state) {
76
+ if (typeof state !== "object" || state === null || Array.isArray(state)) {
77
+ throw new TypeError("state must be a plain object that JSON.stringify can turn to text");
78
+ }
79
+ let text;
80
+ try {
81
+ text = JSON.stringify(state);
82
+ } catch {
83
+ throw new TypeError("state must be a plain object that JSON.stringify can turn to text");
84
+ }
85
+ const back = typeof text === "string" ? JSON.parse(text) : null;
86
+ if (typeof back !== "object" || back === null || Array.isArray(back)) {
87
+ throw new TypeError("state must be a plain object that JSON.stringify can turn to text");
88
+ }
89
+ return text;
90
+ }
91
+
92
+ function isPlainObject(value) {
93
+ if (typeof value !== "object" || value === null) return false;
94
+ const prototype = Object.getPrototypeOf(value);
95
+ return prototype === Object.prototype || prototype === null;
96
+ }
97
+
98
+ function checkLibrary(library) {
99
+ const bad = new TypeError("library must be a list of { name, params, code }: a string, a list of strings, a string");
100
+ if (!Array.isArray(library)) throw bad;
101
+ for (const item of library) {
102
+ if (!isPlainObject(item) || typeof item.name !== "string" || typeof item.code !== "string") throw bad;
103
+ if (!Array.isArray(item.params) || !item.params.every((param) => typeof param === "string")) throw bad;
104
+ }
105
+ }
106
+
107
+ function check(code, { tools, callTool, timeoutMs, memoryMb, shell, onProgress, signal, library, onLibrary }) {
108
+ if (typeof code !== "string") throw new TypeError("code must be a string");
109
+ if (typeof tools !== "object" || tools === null || Array.isArray(tools)) {
110
+ throw new TypeError("tools must be an object of arrays of strings");
111
+ }
112
+ let named = false;
113
+ for (const list of Object.values(tools)) {
114
+ if (!Array.isArray(list) || !list.every((name) => typeof name === "string")) {
115
+ throw new TypeError("tools must be an object of arrays of strings");
116
+ }
117
+ if (list.length > 0) named = true;
118
+ }
119
+ if (typeof shell !== "boolean") throw new TypeError("shell must be true or false");
120
+ if ((named || shell) && typeof callTool !== "function") {
121
+ throw new TypeError("callTool must be a function when tools names a tool or shell is true");
122
+ }
123
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
124
+ throw new TypeError("timeoutMs must be a finite number above 0");
125
+ }
126
+ if (typeof memoryMb !== "number" || !Number.isInteger(memoryMb) || memoryMb < 16) {
127
+ throw new TypeError("memoryMb must be a whole number of 16 or more");
128
+ }
129
+ if (onProgress !== undefined && typeof onProgress !== "function") throw new TypeError("onProgress must be a function");
130
+ if (signal !== undefined && !(signal instanceof AbortSignal)) throw new TypeError("signal must be an AbortSignal");
131
+ if (library !== undefined) {
132
+ checkLibrary(library);
133
+ if (typeof callTool !== "function") throw new TypeError("callTool must be a function when library is given");
134
+ }
135
+ if (onLibrary !== undefined && typeof onLibrary !== "function") throw new TypeError("onLibrary must be a function");
136
+ }
137
+
138
+ // A line goes to the caller's function; what it does or returns is no concern of the program.
139
+ function post(onProgress, line) {
140
+ try {
141
+ const returned = onProgress(line);
142
+ if (returned instanceof Promise) returned.catch(() => {});
143
+ } catch {
144
+ // the program is not told
145
+ }
146
+ }
147
+
148
+ function messageOf(thrown) {
149
+ try {
150
+ const message = thrown?.message;
151
+ if (message !== undefined && message !== null) return String(message);
152
+ } catch {
153
+ // fall through
154
+ }
155
+ try {
156
+ return String(thrown);
157
+ } catch {
158
+ return "";
159
+ }
160
+ }
161
+
162
+ export async function runProgram(
163
+ code,
164
+ { tools = {}, callTool, timeoutMs = 60000, memoryMb = DEFAULT_MEMORY_MB, state, shell = false, onProgress, signal, library, onLibrary } = {},
165
+ ) {
166
+ check(code, { tools, callTool, timeoutMs, memoryMb, shell, onProgress, signal, library, onLibrary });
167
+ const given = state === undefined ? undefined : stateText(state);
168
+ const stopped = () => {
169
+ const result = { ok: false, error: { kind: "stopped", message: "stopped by the caller" }, logs: [] };
170
+ if (given !== undefined) result.state = JSON.parse(given);
171
+ return result;
172
+ };
173
+ if (signal?.aborted) return stopped();
174
+ listen();
175
+
176
+ return new Promise((resolve) => {
177
+ const logs = [];
178
+ let finished = false;
179
+
180
+ const child = launch(CHILD, { files: FILES, memoryMb });
181
+
182
+ const timer = setTimeout(
183
+ () => finish({ ok: false, error: { kind: "timeout", message: `stopped after ${timeoutMs} ms` }, logs }),
184
+ Math.min(timeoutMs, LONGEST_TIMER),
185
+ );
186
+
187
+ // childState: the state text the program's process sent; anything else gives the argument back.
188
+ function finish(result, childState) {
189
+ if (finished) return;
190
+ finished = true;
191
+ if (given !== undefined) result.state = JSON.parse(typeof childState === "string" ? childState : given);
192
+ clearTimeout(timer);
193
+ signal?.removeEventListener("abort", onAbort);
194
+ running.delete(child);
195
+ kill(child);
196
+ resolve(result);
197
+ }
198
+ const onAbort = () => fail("stopped", "stopped by the caller");
199
+ const fail = (kind, message, childState) => finish({ ok: false, error: { kind, message }, logs }, childState);
200
+
201
+ const send = (message) => {
202
+ if (child.stdin.writable) child.stdin.write(JSON.stringify(message) + "\n");
203
+ };
204
+
205
+ async function answer({ id, server, tool, args }) {
206
+ let reply;
207
+ try {
208
+ if (finished) return;
209
+ const value = await callTool(server, tool, JSON.parse(args));
210
+ const json = value === undefined ? undefined : JSON.stringify(value);
211
+ reply = json === undefined ? { status: "undefined" } : { status: "ok", text: json };
212
+ } catch (thrown) {
213
+ reply = { status: "error", text: messageOf(thrown) };
214
+ }
215
+ if (!finished) send({ t: "result", id, ...reply });
216
+ }
217
+
218
+ function onLine(line) {
219
+ if (finished) return;
220
+ let message;
221
+ try {
222
+ message = JSON.parse(line);
223
+ } catch {
224
+ return;
225
+ }
226
+ if (message.t === "log") logs.push(message.s);
227
+ else if (message.t === "progress") {
228
+ if (onProgress !== undefined) post(onProgress, message.s);
229
+ }
230
+ else if (message.t === "use") {
231
+ if (onLibrary !== undefined) post(onLibrary, { name: String(message.name), ok: message.ok === true });
232
+ }
233
+ else if (message.t === "call") answer(message);
234
+ else if (message.t === "done") {
235
+ if (message.kind === "error") fail("error", message.text, message.state);
236
+ else if (given !== undefined && typeof message.state !== "string") fail("error", NOT_KEPT);
237
+ else finish({ ok: true, value: message.kind === "value" ? JSON.parse(message.text) : undefined, logs }, message.state);
238
+ }
239
+ }
240
+
241
+ onLines(child, onLine);
242
+ child.on("error", () => fail("crash", "code null, signal null"));
243
+ child.on("close", (exitCode, signal) => fail("crash", `code ${exitCode}, signal ${signal}`));
244
+
245
+ signal?.addEventListener("abort", onAbort, { once: true });
246
+ send({
247
+ t: "init",
248
+ code,
249
+ tools,
250
+ state: given ?? null,
251
+ shell,
252
+ progress: onProgress !== undefined,
253
+ library: library === undefined ? null : library.map(({ name, params, code }) => ({ name, params, code })),
254
+ });
255
+ });
256
+ }
257
+
258
+ const WALL = new Set(["refused", "done", "failed"]);
259
+
260
+ export async function checkWalls(probePath, { timeoutMs = 10000 } = {}) {
261
+ if (typeof probePath !== "string" || probePath === "") throw new TypeError("probePath must be the path of a file");
262
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
263
+ throw new TypeError("timeoutMs must be a finite number above 0");
264
+ }
265
+ listen();
266
+
267
+ return new Promise((resolve, reject) => {
268
+ let settled = false;
269
+ const child = launch(PROBE, { files: [...FILES, PROBE], memoryMb: DEFAULT_MEMORY_MB, args: [probePath] });
270
+
271
+ const timer = setTimeout(
272
+ () => settle(() => reject(new Error(`the probe did not answer in ${timeoutMs} ms`))),
273
+ Math.min(timeoutMs, LONGEST_TIMER),
274
+ );
275
+
276
+ function settle(outcome) {
277
+ if (settled) return;
278
+ settled = true;
279
+ clearTimeout(timer);
280
+ running.delete(child);
281
+ kill(child);
282
+ outcome();
283
+ }
284
+
285
+ onLines(child, (line) => {
286
+ let walls;
287
+ try {
288
+ walls = JSON.parse(line);
289
+ } catch {
290
+ return;
291
+ }
292
+ const keys = ["read", "write", "spawn", "worker"];
293
+ if (walls === null || typeof walls !== "object" || !keys.every((key) => WALL.has(walls[key]))) return;
294
+ settle(() => resolve(Object.fromEntries(keys.map((key) => [key, walls[key]]))));
295
+ });
296
+ const ended = () => settle(() => reject(new Error("the probe ended before it answered")));
297
+ child.on("error", ended);
298
+ child.on("close", ended);
299
+ });
300
+ }
@@ -0,0 +1,134 @@
1
+ // Finds the value of a program without a parser. The text is cut at the ends of lines and after semicolons that
2
+ // stand outside every bracket, string, template and comment; each cut gives a text whose tail is wrapped in
3
+ // `return (...)`. The caller compiles the texts in turn and keeps the first that is valid JavaScript.
4
+
5
+ const KEYWORDS_BEFORE_REGEX = new Set([
6
+ "return", "typeof", "case", "do", "else", "in", "of", "instanceof", "new", "void", "delete", "throw", "yield", "await",
7
+ ]);
8
+ const WORD = /[\w$]/;
9
+ // A tail that starts like this is a declaration: as an expression it would lose its hoisting.
10
+ const DECLARATION = /^\s*(async\s+function|function|class)\b/;
11
+ const MOST_CUTS = 64;
12
+
13
+ function regexAllowed(src, p) {
14
+ if (p < 0) return true;
15
+ const c = src[p];
16
+ if (WORD.test(c)) {
17
+ let s = p;
18
+ while (s >= 0 && WORD.test(src[s])) s--;
19
+ return KEYWORDS_BEFORE_REGEX.has(src.slice(s + 1, p + 1));
20
+ }
21
+ return c !== ")" && c !== "]" && c !== '"' && c !== "'" && c !== "`";
22
+ }
23
+
24
+ function scan(src) {
25
+ const n = src.length;
26
+ const cuts = [];
27
+ const semicolons = new Map(); // position of a `;` -> position of the significant character before it
28
+ const stack = [];
29
+ let lastSig = -1;
30
+ let i = 0;
31
+
32
+ const cut = (p) => {
33
+ if (cuts[cuts.length - 1] !== p) cuts.push(p);
34
+ };
35
+ const skipString = (j) => {
36
+ const quote = src[j++];
37
+ while (j < n) {
38
+ const c = src[j];
39
+ if (c === "\\") j += 2;
40
+ else if (c === quote) return j + 1;
41
+ else if (c === "\n") return j;
42
+ else j++;
43
+ }
44
+ return n;
45
+ };
46
+ // From inside a template: to after its closing backquote, or to after a `${`, which opens code again.
47
+ const skipTemplate = (j) => {
48
+ while (j < n) {
49
+ const c = src[j];
50
+ if (c === "\\") j += 2;
51
+ else if (c === "`") return j + 1;
52
+ else if (c === "$" && src[j + 1] === "{") {
53
+ stack.push("${");
54
+ return j + 2;
55
+ } else j++;
56
+ }
57
+ return n;
58
+ };
59
+ const skipRegex = (j) => {
60
+ let inClass = false;
61
+ j++;
62
+ while (j < n) {
63
+ const c = src[j];
64
+ if (c === "\\") j += 2;
65
+ else if (c === "\n") return j;
66
+ else {
67
+ j++;
68
+ if (c === "[") inClass = true;
69
+ else if (c === "]") inClass = false;
70
+ else if (c === "/" && !inClass) break;
71
+ }
72
+ }
73
+ while (j < n && WORD.test(src[j])) j++;
74
+ return j;
75
+ };
76
+
77
+ while (i < n) {
78
+ const c = src[i];
79
+ if (c === "\n") {
80
+ if (!stack.length) cut(i + 1);
81
+ i++;
82
+ } else if (/\s/.test(c)) {
83
+ i++;
84
+ } else if (c === "/" && src[i + 1] === "/") {
85
+ while (i < n && src[i] !== "\n") i++;
86
+ } else if (c === "/" && src[i + 1] === "*") {
87
+ const close = src.indexOf("*/", i + 2);
88
+ i = close < 0 ? n : close + 2;
89
+ } else if (c === '"' || c === "'") {
90
+ i = skipString(i);
91
+ lastSig = i - 1;
92
+ } else if (c === "`") {
93
+ i = skipTemplate(i + 1);
94
+ lastSig = i - 1;
95
+ } else if (c === "/" && regexAllowed(src, lastSig)) {
96
+ i = skipRegex(i);
97
+ lastSig = i - 1;
98
+ } else if (c === "}" && stack[stack.length - 1] === "${") {
99
+ stack.pop();
100
+ i = skipTemplate(i + 1);
101
+ lastSig = i - 1;
102
+ } else {
103
+ if (c === "(" || c === "[" || c === "{") stack.push(c);
104
+ else if (c === ")" || c === "]" || c === "}") stack.pop();
105
+ else if (c === ";") {
106
+ semicolons.set(i, lastSig);
107
+ if (!stack.length) cut(i + 1);
108
+ }
109
+ lastSig = i;
110
+ i++;
111
+ }
112
+ }
113
+
114
+ // The end of the program's code: without comments, white space and final semicolons.
115
+ let end = lastSig + 1;
116
+ while (end > 0 && src[end - 1] === ";" && semicolons.has(end - 1)) end = semicolons.get(end - 1) + 1;
117
+ return { cuts, end };
118
+ }
119
+
120
+ // The texts to try, the one that gives the most to the last expression first. None when the program has no code.
121
+ export function* withLastExpression(src) {
122
+ const { cuts, end } = scan(src);
123
+ if (end === 0) return;
124
+ let tried = 0;
125
+ for (let k = cuts.length - 1; k >= 0 && tried < MOST_CUTS; k--) {
126
+ if (cuts[k] >= end) continue;
127
+ const tail = src.slice(cuts[k], end);
128
+ if (DECLARATION.test(tail)) continue;
129
+ tried++;
130
+ yield src.slice(0, cuts[k]) + "\nreturn (\n" + tail + "\n)";
131
+ }
132
+ const whole = src.slice(0, end);
133
+ if (!DECLARATION.test(whole)) yield "return (\n" + whole + "\n)";
134
+ }
@@ -0,0 +1,42 @@
1
+ // The probe of checkWalls, run in a process started as the process of a program is. argv[2] is the path of a file
2
+ // that exists outside sandbox/src. It tries four things the program may not do and writes one line to standard
3
+ // output: { read, write, spawn, worker }, each "refused" (ERR_ACCESS_DENIED), "done" or "failed" (anything else).
4
+ import fs from "node:fs";
5
+ import { spawn } from "node:child_process";
6
+ import { Worker } from "node:worker_threads";
7
+
8
+ const target = process.argv[2];
9
+ const cleanup = [];
10
+
11
+ function attempt(fn) {
12
+ try {
13
+ fn();
14
+ return "done";
15
+ } catch (thrown) {
16
+ return thrown?.code === "ERR_ACCESS_DENIED" ? "refused" : "failed";
17
+ }
18
+ }
19
+
20
+ const walls = {
21
+ read: attempt(() => fs.readFileSync(target)),
22
+ write: attempt(() => fs.writeFileSync(target + ".written", "written by the probe\n")),
23
+ spawn: attempt(() => {
24
+ const child = spawn(process.execPath, ["--version"], { stdio: "ignore" });
25
+ child.on("error", () => {});
26
+ cleanup.push(() => child.kill("SIGKILL"));
27
+ }),
28
+ worker: attempt(() => {
29
+ const worker = new Worker("0", { eval: true });
30
+ worker.on("error", () => {});
31
+ cleanup.push(() => worker.terminate());
32
+ }),
33
+ };
34
+
35
+ for (const stop of cleanup) {
36
+ try {
37
+ stop();
38
+ } catch {
39
+ // nothing to stop
40
+ }
41
+ }
42
+ process.stdout.write(JSON.stringify(walls) + "\n", () => process.exit(0));
@@ -0,0 +1,128 @@
1
+ // The connection to one listed server: start its process, speak MCP to it, read its list of tools.
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
4
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
5
+ import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
6
+
7
+ /** The transport of the package, which also knows when the process of the server has ended. */
8
+ class Transport extends StdioClientTransport {
9
+ ended = false;
10
+
11
+ async start() {
12
+ await super.start();
13
+ this._process?.once("close", () => {
14
+ this.ended = true;
15
+ });
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Whether `err` is a JSON-RPC error that the server itself answered, and not one the package makes when its own
21
+ * request is given up or its connection is gone.
22
+ */
23
+ export function isServerError(err) {
24
+ if (!(err instanceof McpError)) return false;
25
+ if (err.code === ErrorCode.RequestTimeout) return false;
26
+ return !(err.code === ErrorCode.ConnectionClosed && err.message === `MCP error ${err.code}: Connection closed`);
27
+ }
28
+
29
+ /**
30
+ * One listed server. `tools` is its list once connected; `error` the reason when it is not. `connect()` never
31
+ * rejects: it settles `tools` or `error`.
32
+ */
33
+ export class Connection {
34
+ constructor(name, entry, connectSeconds, version) {
35
+ this.name = name;
36
+ this.entry = entry;
37
+ this.connectSeconds = connectSeconds;
38
+ this.version = version;
39
+ this.tools = null;
40
+ this.error = null;
41
+ this.client = null;
42
+ this.transport = null;
43
+ this.closing = null;
44
+ }
45
+
46
+ /** Whether it is reached at an address: it then has no process of its own. */
47
+ get remote() {
48
+ return Object.hasOwn(this.entry, "url");
49
+ }
50
+
51
+ get connected() {
52
+ return this.tools !== null && (this.remote || !this.transport.ended);
53
+ }
54
+
55
+ makeTransport() {
56
+ if (this.remote) {
57
+ const { url, headers } = this.entry;
58
+ return new StreamableHTTPClientTransport(new URL(url), { requestInit: { headers } });
59
+ }
60
+ const { command, args, env } = this.entry;
61
+ return new Transport({ command, args, env, stderr: "inherit" });
62
+ }
63
+
64
+ async connect() {
65
+ const ms = this.connectSeconds * 1000;
66
+ try {
67
+ this.transport = this.makeTransport();
68
+ } catch {
69
+ this.error = "could not connect";
70
+ return this;
71
+ }
72
+ this.client = new Client({ name: "onetool", version: this.version });
73
+ let timer;
74
+ const timeout = new Promise((resolve) => {
75
+ timer = setTimeout(() => resolve("timeout"), ms);
76
+ });
77
+ // the package's own request limit is kept above ours, so that ours speaks first
78
+ const options = { timeout: ms + 5000 };
79
+ const work = (async () => {
80
+ await this.client.connect(this.transport, options);
81
+ const tools = [];
82
+ let cursor;
83
+ do {
84
+ const page = await this.client.listTools(cursor === undefined ? undefined : { cursor }, options);
85
+ tools.push(...page.tools);
86
+ cursor = page.nextCursor;
87
+ } while (cursor);
88
+ return tools;
89
+ })();
90
+ work.catch(() => {});
91
+ try {
92
+ const got = await Promise.race([work, timeout]);
93
+ if (got === "timeout") {
94
+ this.error = `no answer in ${String(this.connectSeconds)} seconds`;
95
+ } else {
96
+ this.tools = got;
97
+ }
98
+ } catch (err) {
99
+ if (this.remote) {
100
+ this.error = isServerError(err) ? "refused the connection" : "could not connect";
101
+ } else {
102
+ const refused = err instanceof McpError && !this.transport.ended;
103
+ this.error = refused ? "refused the connection" : "could not start";
104
+ }
105
+ } finally {
106
+ clearTimeout(timer);
107
+ }
108
+ if (this.error !== null) this.close();
109
+ return this;
110
+ }
111
+
112
+ /** Ends the connection and its process. Gives a promise that is settled once they are gone. */
113
+ close() {
114
+ if (!this.transport) return Promise.resolve();
115
+ this.closing ??= this.transport.close().catch(() => {});
116
+ return this.closing;
117
+ }
118
+
119
+ /** Ends the process at once, whatever it does. */
120
+ kill() {
121
+ const pid = this.transport?.pid;
122
+ if (pid) {
123
+ try {
124
+ process.kill(pid, "SIGKILL");
125
+ } catch {}
126
+ }
127
+ }
128
+ }
@@ -0,0 +1,61 @@
1
+ // The fixed texts of the two tools: they name no real server and no real tool.
2
+
3
+ export const RUN_DESCRIPTION =
4
+ "Runs a JavaScript program that calls the tools of the listed servers and gives back only what it returns or prints. " +
5
+ "Call a tool as `await tools.<server>.<tool>(args)` (args an object); filter and count inside, so that only a small answer comes back. " +
6
+ "The answer is the value of the last expression; `console.log` lines follow. " +
7
+ "`state` is kept from one call to the next. " +
8
+ "`background: true` starts a job and answers at once with its id; `progress(...)` posts a line. " +
9
+ "Use `search` first to find tools.";
10
+
11
+ // added to the description of `run`, after one space, when the shell is on
12
+ export const SHELL_DESCRIPTION =
13
+ "Shell, in the listed folders: await $`command`.text() gives the output, $`command`.nothrow() does not throw; " +
14
+ "read(path), write(path, text), edit(path, old, new) do files.";
15
+
16
+ export const CODE_DESCRIPTION = "The program: the body of an async function; `await` and `return` work.";
17
+
18
+ export const BACKGROUND_DESCRIPTION = "true: start the program as a job and answer at once with its id.";
19
+
20
+ export const JOB_DESCRIPTION = "The id of a job: says how it is doing, its lines and its answer.";
21
+
22
+ export const STOP_DESCRIPTION = "true, with job: stops the job.";
23
+
24
+ export const JOBS_DESCRIPTION = "true: lists the jobs.";
25
+
26
+ export const SEARCH_DESCRIPTION =
27
+ "Finds tools and saved programs. With no words it counts them; with words it shows the matches, one line each: " +
28
+ "`server.tool(arguments) - what it does`.";
29
+
30
+ export const WORDS_DESCRIPTION = "Words to look for in names, descriptions and arguments.";
31
+
32
+ export const TOOLS = [
33
+ {
34
+ name: "run",
35
+ description: RUN_DESCRIPTION,
36
+ inputSchema: {
37
+ type: "object",
38
+ properties: {
39
+ code: { type: "string", description: CODE_DESCRIPTION },
40
+ background: { type: "boolean", description: BACKGROUND_DESCRIPTION },
41
+ job: { type: "string", description: JOB_DESCRIPTION },
42
+ stop: { type: "boolean", description: STOP_DESCRIPTION },
43
+ jobs: { type: "boolean", description: JOBS_DESCRIPTION },
44
+ },
45
+ },
46
+ },
47
+ {
48
+ name: "search",
49
+ description: SEARCH_DESCRIPTION,
50
+ inputSchema: {
51
+ type: "object",
52
+ properties: { words: { type: "string", description: WORDS_DESCRIPTION } },
53
+ },
54
+ },
55
+ ];
56
+
57
+ /** The two tools: `run` says what the library holds (`libraryText`) and, with the shell on, what else the program finds. */
58
+ export const toolsWith = (libraryText, withShell) => [
59
+ { ...TOOLS[0], description: `${RUN_DESCRIPTION} ${libraryText}${withShell ? ` ${SHELL_DESCRIPTION}` : ""}` },
60
+ TOOLS[1],
61
+ ];