@koneeric/onetool 0.0.0-stage → 0.3.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,843 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { isAbsolute, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ // -- settings ----------------------------------------------------------------
6
+
7
+ export class SettingsError extends Error {
8
+ constructor(problems) {
9
+ super(problems.join("; "));
10
+ this.name = "SettingsError";
11
+ this.problems = problems;
12
+ }
13
+ }
14
+
15
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
16
+ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
17
+ const isWhole = (value, min, max) => Number.isInteger(value) && value >= min && value <= max;
18
+ const isPattern = (value) => typeof value === "string" && value !== "" && !/\s/.test(value);
19
+ const isPatternList = (value) => Array.isArray(value) && value.every(isPattern);
20
+ const isCommandPattern = (value) => typeof value === "string" && /\S/.test(value);
21
+ const isCommandPatternList = (value) => Array.isArray(value) && value.every(isCommandPattern);
22
+ const isFullPath = (value) => typeof value === "string" && isAbsolute(value);
23
+ const isBoolean = (value) => typeof value === "boolean";
24
+
25
+ const ONETOOL_KEYS = {
26
+ answerLimit: {
27
+ fallback: 8000,
28
+ valid: (v) => isWhole(v, 100, 1000000),
29
+ problem: "must be a whole number from 100 to 1000000",
30
+ },
31
+ timeoutSeconds: {
32
+ fallback: 60,
33
+ valid: (v) => isNumber(v) && v > 0 && v <= 3600,
34
+ problem: "must be a number above 0, at most 3600",
35
+ },
36
+ connectSeconds: {
37
+ fallback: 30,
38
+ valid: (v) => isNumber(v) && v > 0 && v <= 600,
39
+ problem: "must be a number above 0, at most 600",
40
+ },
41
+ searchLimit: {
42
+ fallback: 10,
43
+ valid: (v) => isWhole(v, 1, 100),
44
+ problem: "must be a whole number from 1 to 100",
45
+ },
46
+ stateLimit: {
47
+ fallback: 10000000,
48
+ valid: (v) => isWhole(v, 1000, 100000000),
49
+ problem: "must be a whole number from 1000 to 100000000",
50
+ },
51
+ allow: { fallback: [], valid: isPatternList, problem: "must be a list of patterns" },
52
+ deny: { fallback: [], valid: isPatternList, problem: "must be a list of patterns" },
53
+ ask: { fallback: [], valid: isPatternList, problem: "must be a list of patterns" },
54
+ };
55
+
56
+ const EXTRA_KEYS = ["shell", "trail", "log", "logFolder", "hostRules", "hostServers", "backgroundSeconds", "maxJobs", "libraryCap", "instructions"];
57
+
58
+ const isTexts = (list) => Array.isArray(list) && list.every((item) => typeof item === "string");
59
+ const isObjectOfTexts = (value) => isObject(value) && Object.values(value).every((item) => typeof item === "string");
60
+
61
+ const OAUTH_KEYS = ["clientId", "clientSecret", "scopes", "port", "redirectHost"];
62
+
63
+ /** The reason the `oauth` of an entry is not valid, or null when it is. */
64
+ function oauthReason(oauth) {
65
+ if (!isObject(oauth) || typeof oauth.clientId !== "string" || oauth.clientId.trim() === "") return "oauth has no clientId";
66
+ const has = (key) => Object.hasOwn(oauth, key);
67
+ if (has("clientSecret") && (typeof oauth.clientSecret !== "string" || oauth.clientSecret === "")) {
68
+ return "oauth.clientSecret is not a text";
69
+ }
70
+ if (has("scopes") && !(Array.isArray(oauth.scopes) && oauth.scopes.every((scope) => typeof scope === "string" && /^\S+$/.test(scope)))) {
71
+ return "oauth.scopes is not a list of words";
72
+ }
73
+ if (has("port") && !isWhole(oauth.port, 1, 65535)) return "oauth.port is not a port";
74
+ if (has("redirectHost") && oauth.redirectHost !== "127.0.0.1" && oauth.redirectHost !== "localhost") {
75
+ return "oauth.redirectHost is not 127.0.0.1 or localhost";
76
+ }
77
+ if (Object.keys(oauth).some((key) => !OAUTH_KEYS.includes(key))) return "oauth has an unknown key";
78
+ return null;
79
+ }
80
+
81
+ /** The `oauth` of a usable entry as `servers` holds it: a new object with the keys the file has. */
82
+ function oauthValue(oauth) {
83
+ const value = { clientId: oauth.clientId };
84
+ if (Object.hasOwn(oauth, "clientSecret")) value.clientSecret = oauth.clientSecret;
85
+ if (Object.hasOwn(oauth, "scopes")) value.scopes = [...oauth.scopes];
86
+ if (Object.hasOwn(oauth, "port")) value.port = oauth.port;
87
+ if (Object.hasOwn(oauth, "redirectHost")) value.redirectHost = oauth.redirectHost;
88
+ return value;
89
+ }
90
+
91
+ const isToolNames = (list) => Array.isArray(list) && list.every((name) => typeof name === "string" && name.trim() !== "");
92
+
93
+ /** The reason an entry of mcpServers is unusable, or null when it is usable. */
94
+ function badReason(name, entry, shellOn) {
95
+ if (name.trim() === "") return "the name is empty";
96
+ if (name.includes(".")) return "the name holds a dot";
97
+ if (shellOn && name === "shell") return "the name is taken by the built-in shell";
98
+ if (name === "library") return "the name is taken by the built-in library";
99
+ if (!isObject(entry)) return "not an object";
100
+ const has = (key) => Object.hasOwn(entry, key);
101
+ if (has("command") && has("url")) return "both command and url";
102
+ if (has("url")) {
103
+ const { url } = entry;
104
+ if (typeof url !== "string" || !URL.canParse(url) || !/^https?:$/.test(new URL(url).protocol)) {
105
+ return "url is not an http address";
106
+ }
107
+ if (entry.type === "sse") return "the old SSE transport is not supported";
108
+ if (has("headers") && !isObjectOfTexts(entry.headers)) return "headers is not an object of texts";
109
+ if (has("oauth")) {
110
+ const why = oauthReason(entry.oauth);
111
+ if (why !== null) return why;
112
+ if (has("headers") && Object.keys(entry.headers).some((key) => key.toLowerCase() === "authorization")) {
113
+ return "both oauth and an Authorization header";
114
+ }
115
+ }
116
+ return toolsReason(entry);
117
+ }
118
+ if (typeof entry.command !== "string" || entry.command === "") return "no command";
119
+ if (has("args") && !isTexts(entry.args)) return "args is not a list of texts";
120
+ if (has("env") && !isObjectOfTexts(entry.env)) return "env is not an object of texts";
121
+ return toolsReason(entry);
122
+ }
123
+
124
+ /** The reason the `tools` of an entry is not valid, or null when it is (or the entry has none). */
125
+ function toolsReason(entry) {
126
+ if (Object.hasOwn(entry, "tools") && !isToolNames(entry.tools)) return "tools is not a list of tool names";
127
+ return null;
128
+ }
129
+
130
+ const SHELL_KEYS = ["folders", "allow", "deny", "ask"];
131
+
132
+ /** The problems of the `shell` key of `onetool`, in their order. */
133
+ function shellProblems(shell) {
134
+ if (!isObject(shell)) return ["onetool.shell: not an object"];
135
+ const problems = [];
136
+ for (const key of Object.keys(shell)) {
137
+ if (!SHELL_KEYS.includes(key)) problems.push(`onetool.shell.${key}: unknown key`);
138
+ }
139
+ const { folders } = shell;
140
+ if (Object.hasOwn(shell, "folders") && (!Array.isArray(folders) || folders.length === 0 || !folders.every(isFullPath))) {
141
+ problems.push("onetool.shell.folders: must be a list of full paths, at least one");
142
+ }
143
+ for (const key of ["allow", "deny", "ask"]) {
144
+ if (Object.hasOwn(shell, key) && !isCommandPatternList(shell[key])) {
145
+ problems.push(`onetool.shell.${key}: must be a list of command patterns`);
146
+ }
147
+ }
148
+ return problems;
149
+ }
150
+
151
+ export function readSettings(path) {
152
+ let raw;
153
+ try {
154
+ raw = readFileSync(path, "utf8");
155
+ } catch {
156
+ throw new SettingsError([`settings file not found: ${path}`]);
157
+ }
158
+ let file;
159
+ try {
160
+ file = JSON.parse(raw);
161
+ } catch {
162
+ throw new SettingsError(["settings file is not JSON"]);
163
+ }
164
+ if (!isObject(file)) throw new SettingsError(["settings file is not a JSON object"]);
165
+
166
+ const problems = [];
167
+ if (!("mcpServers" in file)) problems.push("mcpServers: missing");
168
+ else if (!isObject(file.mcpServers)) problems.push("mcpServers: not an object");
169
+
170
+ const onetool = file.onetool === undefined ? {} : file.onetool;
171
+ const values = {};
172
+ let shell = null;
173
+ let trail = true;
174
+ let log = true;
175
+ let logFolder = null;
176
+ let hostRules = true;
177
+ let hostServers = [];
178
+ let backgroundSeconds = 7200;
179
+ let maxJobs = 3;
180
+ let libraryCap = 50;
181
+ let instructions = true;
182
+ if (!isObject(onetool)) {
183
+ problems.push("onetool: not an object");
184
+ } else {
185
+ for (const key of Object.keys(onetool)) {
186
+ if (!Object.hasOwn(ONETOOL_KEYS, key) && !EXTRA_KEYS.includes(key)) problems.push(`onetool.${key}: unknown key`);
187
+ }
188
+ for (const [key, rule] of Object.entries(ONETOOL_KEYS)) {
189
+ if (!Object.hasOwn(onetool, key)) values[key] = rule.fallback;
190
+ else if (rule.valid(onetool[key])) values[key] = onetool[key];
191
+ else problems.push(`onetool.${key}: ${rule.problem}`);
192
+ }
193
+ const shellOn = Object.hasOwn(onetool, "shell");
194
+ if (shellOn) {
195
+ const found = shellProblems(onetool.shell);
196
+ if (found.length === 0) {
197
+ const { folders = null, allow = [], deny = [], ask = [] } = onetool.shell;
198
+ shell = { folders, allow, deny, ask };
199
+ } else {
200
+ problems.push(...found);
201
+ }
202
+ }
203
+ if (Object.hasOwn(onetool, "trail")) {
204
+ if (isBoolean(onetool.trail)) trail = onetool.trail;
205
+ else problems.push("onetool.trail: must be true or false");
206
+ }
207
+ if (Object.hasOwn(onetool, "log")) {
208
+ if (isBoolean(onetool.log)) log = onetool.log;
209
+ else problems.push("onetool.log: must be true or false");
210
+ }
211
+ if (Object.hasOwn(onetool, "logFolder")) {
212
+ if (isFullPath(onetool.logFolder)) logFolder = onetool.logFolder;
213
+ else problems.push("onetool.logFolder: must be a full path");
214
+ }
215
+ if (Object.hasOwn(onetool, "hostRules")) {
216
+ if (isBoolean(onetool.hostRules)) hostRules = onetool.hostRules;
217
+ else problems.push("onetool.hostRules: must be true or false");
218
+ }
219
+ if (Object.hasOwn(onetool, "hostServers")) {
220
+ const names = onetool.hostServers;
221
+ if (Array.isArray(names) && names.every((name) => typeof name === "string" && name.trim() !== "")) hostServers = names;
222
+ else problems.push("onetool.hostServers: must be a list of server names");
223
+ }
224
+ if (Object.hasOwn(onetool, "backgroundSeconds")) {
225
+ const seconds = onetool.backgroundSeconds;
226
+ if (isNumber(seconds) && seconds > 0 && seconds <= 86400) backgroundSeconds = seconds;
227
+ else problems.push("onetool.backgroundSeconds: must be a number above 0, at most 86400");
228
+ }
229
+ if (Object.hasOwn(onetool, "maxJobs")) {
230
+ if (isWhole(onetool.maxJobs, 0, 100)) maxJobs = onetool.maxJobs;
231
+ else problems.push("onetool.maxJobs: must be a whole number from 0 to 100");
232
+ }
233
+ if (Object.hasOwn(onetool, "libraryCap")) {
234
+ if (isWhole(onetool.libraryCap, 1, 1000)) libraryCap = onetool.libraryCap;
235
+ else problems.push("onetool.libraryCap: must be a whole number from 1 to 1000");
236
+ }
237
+ if (Object.hasOwn(onetool, "instructions")) {
238
+ if (typeof onetool.instructions === "boolean") instructions = onetool.instructions;
239
+ else problems.push("onetool.instructions: must be true or false");
240
+ }
241
+ }
242
+ if (problems.length > 0) throw new SettingsError(problems);
243
+
244
+ const servers = [];
245
+ const bad = [];
246
+ for (const [name, entry] of Object.entries(file.mcpServers)) {
247
+ const reason = badReason(name, entry, shell !== null);
248
+ if (reason !== null) bad.push({ name, reason });
249
+ else {
250
+ let server;
251
+ if (Object.hasOwn(entry, "url")) {
252
+ server = { name, url: entry.url, headers: entry.headers ?? {} };
253
+ if (Object.hasOwn(entry, "oauth")) server.oauth = oauthValue(entry.oauth);
254
+ } else {
255
+ server = { name, command: entry.command, args: entry.args ?? [], env: entry.env ?? {} };
256
+ }
257
+ if (Object.hasOwn(entry, "tools")) server.tools = [...entry.tools];
258
+ servers.push(server);
259
+ }
260
+ }
261
+ const { answerLimit, timeoutSeconds, connectSeconds, searchLimit, stateLimit, allow, deny, ask } = values;
262
+ return { servers, bad, answerLimit, timeoutSeconds, connectSeconds, searchLimit, stateLimit, allow, deny, ask, shell, trail, log, logFolder, hostRules, hostServers, backgroundSeconds, maxJobs, libraryCap, instructions };
263
+ }
264
+
265
+ // -- allow and deny ----------------------------------------------------------
266
+
267
+ /** Whether `pattern` matches the whole of `text`; `*` stands for any run of characters. */
268
+ function globMatches(pattern, text) {
269
+ let p = 0;
270
+ let t = 0;
271
+ let starAt = -1;
272
+ let resume = 0;
273
+ while (t < text.length) {
274
+ if (p < pattern.length && pattern[p] === "*") {
275
+ starAt = p++;
276
+ resume = t;
277
+ } else if (p < pattern.length && pattern[p] === text[t]) {
278
+ p++;
279
+ t++;
280
+ } else if (starAt >= 0) {
281
+ p = starAt + 1;
282
+ t = ++resume;
283
+ } else {
284
+ return false;
285
+ }
286
+ }
287
+ while (p < pattern.length && pattern[p] === "*") p++;
288
+ return p === pattern.length;
289
+ }
290
+
291
+ export function decide(rules, server, tool) {
292
+ if (rules !== undefined && !isObject(rules)) throw new TypeError("decide: the rules must be an object");
293
+ const { allow = [], deny = [], ask = [] } = rules ?? {};
294
+ if (!Array.isArray(allow)) throw new TypeError("decide: allow must be a list");
295
+ if (!Array.isArray(deny)) throw new TypeError("decide: deny must be a list");
296
+ if (!Array.isArray(ask)) throw new TypeError("decide: ask must be a list");
297
+ const id = `${server}.${tool}`;
298
+ for (const rule of deny) {
299
+ if (globMatches(rule, id)) {
300
+ return { allowed: false, list: "deny", rule, message: `onetool: ${id} is denied by the rule deny "${rule}"` };
301
+ }
302
+ }
303
+ if (allow.length > 0 && !allow.some((rule) => globMatches(rule, id))) {
304
+ return {
305
+ allowed: false,
306
+ list: "allow",
307
+ rule: null,
308
+ message: `onetool: ${id} is not allowed: it matches no rule of allow`,
309
+ };
310
+ }
311
+ const asked = ask.find((rule) => globMatches(rule, id));
312
+ return asked === undefined ? { allowed: true } : { allowed: true, ask: asked };
313
+ }
314
+
315
+ /** The question the person reads before a call under a rule of `ask`. */
316
+ export function askMessage(id, rule, args, { limit = 300, file } = {}) {
317
+ const json = JSON.stringify(args);
318
+ const shown = json.length > limit ? `${json.slice(0, limit)}... (${json.length} characters)` : json;
319
+ return `onetool: a program wants to call ${id}.\nArguments: ${shown}\nThe rule ask "${rule}"${file === undefined ? "" : ` of the host program (${file})`} asks for your consent. Allow this call?`;
320
+ }
321
+
322
+ const ASK_CAUSES = {
323
+ unsupported: "the host program cannot ask the person",
324
+ decline: "the person said no",
325
+ cancel: "the person gave no answer",
326
+ failed: "the question failed",
327
+ };
328
+
329
+ /** The message of the error a program gets when a call under `ask` is not made. */
330
+ export function askRefusal(id, rule, why, file) {
331
+ if (typeof why !== "string" || !Object.hasOwn(ASK_CAUSES, why)) {
332
+ throw new TypeError("askRefusal: why must be unsupported, decline, cancel or failed");
333
+ }
334
+ return `onetool: ${id} is refused by the rule ask "${rule}"${file === undefined ? "" : ` of the host program (${file})`}: ${ASK_CAUSES[why]}`;
335
+ }
336
+
337
+ /** The message of the error a program gets when a rule deny of the host program refuses its call. */
338
+ export function hostDenial(id, rule, file) {
339
+ return `onetool: ${id} is denied by the rule deny "${rule}" of the host program (${file})`;
340
+ }
341
+
342
+ // -- search ------------------------------------------------------------------
343
+
344
+ function typeOf(property) {
345
+ const type = property?.type;
346
+ if (typeof type === "string") return type;
347
+ if (Array.isArray(type)) return type.join("|");
348
+ return "any";
349
+ }
350
+
351
+ function sentenceOf(description) {
352
+ if (typeof description !== "string") return "";
353
+ const text = description.replace(/\s+/g, " ").trim();
354
+ const end = text.search(/[.!?](?: |$)/);
355
+ const sentence = end === -1 ? text : text.slice(0, end + 1);
356
+ return sentence.length > 160 ? `${sentence.slice(0, 157)}...` : sentence;
357
+ }
358
+
359
+ /** The tools of a server that onetool keeps: all of them, or those whose name is in `keep`. */
360
+ export function keptTools(tools, keep) {
361
+ if (!Array.isArray(tools)) throw new TypeError("keptTools takes a list of tools");
362
+ if (keep === undefined) return [...tools];
363
+ if (!Array.isArray(keep)) throw new TypeError("keptTools takes a list of names, or undefined");
364
+ const names = new Set(keep);
365
+ return tools.filter((tool) => names.has(tool.name));
366
+ }
367
+
368
+ /** Whether onetool may sign in to this server: at an address, with no Authorization header. */
369
+ export function signsIn(entry) {
370
+ if (!isObject(entry)) throw new TypeError("signsIn takes an entry of settings.servers");
371
+ if (!Object.hasOwn(entry, "url")) return false;
372
+ return !Object.keys(entry.headers).some((key) => key.toLowerCase() === "authorization");
373
+ }
374
+
375
+ /** The text a program gets when it calls a tool of a server that needs a sign-in. */
376
+ export function signInMessage(server, configPath) {
377
+ for (const value of [server, configPath]) {
378
+ if (typeof value !== "string" || value === "") throw new TypeError("signInMessage takes two texts that are not empty");
379
+ }
380
+ return `sign in needed: run "onetool login ${server} --config ${configPath}" in a terminal`;
381
+ }
382
+
383
+ export function toolLine(server, tool) {
384
+ const schema = tool.inputSchema;
385
+ const properties = isObject(schema?.properties) ? schema.properties : {};
386
+ const required = new Set(Array.isArray(schema?.required) ? schema.required : []);
387
+ const args = Object.keys(properties)
388
+ .map((name) => `${name}${required.has(name) ? "" : "?"}: ${typeOf(properties[name])}`)
389
+ .join(", ");
390
+ const sentence = sentenceOf(tool.description);
391
+ return `${server}.${tool.name}(${args})${sentence === "" ? "" : ` - ${sentence}`}`;
392
+ }
393
+
394
+ function score(server, tool, words) {
395
+ const id = `${server}.${tool.name}`.toLowerCase();
396
+ const description = typeof tool.description === "string" ? tool.description.toLowerCase() : "";
397
+ const properties = isObject(tool.inputSchema?.properties) ? tool.inputSchema.properties : {};
398
+ const argumentNames = Object.keys(properties).map((name) => name.toLowerCase());
399
+ let total = 0;
400
+ for (const word of words) {
401
+ if (id.includes(word)) total += 2;
402
+ else if (description.includes(word) || argumentNames.some((name) => name.includes(word))) total += 1;
403
+ }
404
+ return total;
405
+ }
406
+
407
+ /** `lib.<name>(<arguments>) - <sentence>`: how a saved program is called. */
408
+ export function programLine(program) {
409
+ const params = program.params.length === 0 ? "" : `{ ${program.params.join(", ")} }`;
410
+ const about = program.about.replace(/\s+/g, " ").trim();
411
+ const sentence = about.length > 160 ? `${about.slice(0, 157)}...` : about;
412
+ return `lib.${program.name}(${params})${sentence === "" ? "" : ` - ${sentence}`}`;
413
+ }
414
+
415
+ function programScore(program, words) {
416
+ const id = `lib.${program.name}`.toLowerCase();
417
+ const about = program.about.toLowerCase();
418
+ const params = program.params.map((param) => param.toLowerCase());
419
+ let total = 0;
420
+ for (const word of words) {
421
+ if (id.includes(word)) total += 2;
422
+ else if (about.includes(word) || params.some((param) => param.includes(word))) total += 1;
423
+ }
424
+ return total;
425
+ }
426
+
427
+ export function searchTools(catalog, words, { limit = 10, programs = [], session } = {}) {
428
+ const query = typeof words === "string" ? words.trim() : "";
429
+ if (query === "") {
430
+ const lines = catalog.map((entry) =>
431
+ entry.signIn === true
432
+ ? `${entry.server}: sign in needed`
433
+ : entry.error !== undefined && entry.error !== null
434
+ ? `${entry.server}: not connected (${entry.error})`
435
+ : `${entry.server}: ${entry.tools.length} tools`,
436
+ );
437
+ if (programs.length > 0) lines.push(`library: ${programs.length} programs`);
438
+ const answer = lines.length === 0 ? "No server is listed." : lines.join("\n");
439
+ const line = session === undefined || session === null ? "" : sessionLine(session.programs, session.calls);
440
+ return line === "" ? answer : `${answer}\n${line}`;
441
+ }
442
+
443
+ const terms = query.toLowerCase().split(/\s+/);
444
+ const matches = [];
445
+ for (const [order, program] of programs.entries()) {
446
+ const points = programScore(program, terms);
447
+ if (points > 0) matches.push({ points, line: programLine(program), order });
448
+ }
449
+ matches.sort((a, b) => b.points - a.points || a.order - b.order);
450
+ const found = [];
451
+ for (const entry of catalog) {
452
+ if (entry.error !== undefined && entry.error !== null) continue;
453
+ for (const tool of entry.tools) {
454
+ const points = score(entry.server, tool, terms);
455
+ if (points > 0) found.push({ points, line: toolLine(entry.server, tool), order: found.length });
456
+ }
457
+ }
458
+ found.sort((a, b) => b.points - a.points || a.order - b.order);
459
+ matches.push(...found);
460
+ if (matches.length === 0) return "No tool matches.";
461
+ const lines = matches.slice(0, limit).map((m) => m.line);
462
+ if (matches.length > limit) lines.push(`(${matches.length - limit} more match: add a word)`);
463
+ return lines.join("\n");
464
+ }
465
+
466
+ // -- answers -----------------------------------------------------------------
467
+
468
+ export class ToolError extends Error {
469
+ constructor(message) {
470
+ super(message);
471
+ this.name = "ToolError";
472
+ }
473
+ }
474
+
475
+ export function toolValue(result) {
476
+ if (!isObject(result)) throw new TypeError("toolValue: the result must be an object");
477
+ const items = Array.isArray(result.content) ? result.content : [];
478
+ const texts = items.filter((item) => isObject(item) && item.type === "text").map((item) => String(item.text ?? ""));
479
+ const text = texts.join("\n");
480
+ if (result.isError === true) throw new ToolError(text === "" ? "the tool failed" : text);
481
+ if (result.structuredContent !== null && typeof result.structuredContent === "object") {
482
+ return result.structuredContent;
483
+ }
484
+ if (texts.length === 0) return null;
485
+ try {
486
+ return JSON.parse(text);
487
+ } catch {
488
+ return text;
489
+ }
490
+ }
491
+
492
+ export function formatRun(result, { timeoutSeconds = 60 } = {}) {
493
+ let text;
494
+ if (result.ok) {
495
+ if (result.value === undefined) text = "undefined";
496
+ else if (typeof result.value === "string") text = result.value;
497
+ else text = JSON.stringify(result.value) ?? String(result.value);
498
+ } else {
499
+ const { kind, message } = result.error;
500
+ if (kind === "timeout") text = `The program was stopped after ${String(timeoutSeconds)} seconds.`;
501
+ else if (kind === "stopped") text = "The program was stopped on request.";
502
+ else if (kind === "crash") text = `The program's process ended before it answered (${message}).`;
503
+ else text = `The program failed: ${message}`;
504
+ }
505
+ const logs = result.logs ?? [];
506
+ if (logs.length > 0) text += `\n--- console.log ---\n${logs.join("\n")}`;
507
+ return text;
508
+ }
509
+
510
+ export function cutAnswer(text, limit = 8000) {
511
+ if (typeof text !== "string") throw new TypeError("cutAnswer: text must be a string");
512
+ if (text.length <= limit) return text;
513
+ const notice = `\n[cut: the answer was ${text.length} characters, the limit is ${limit}]`;
514
+ return text.slice(0, limit - notice.length) + notice;
515
+ }
516
+
517
+ // -- jobs --------------------------------------------------------------------
518
+
519
+ const RUN_NEEDS_CODE = 'onetool: run needs "code", a text';
520
+ const flagProblem = (name) => `onetool: run takes "${name}", true or false`;
521
+
522
+ /** What a call of `run` asks for: a program, a job, the list of jobs, or a problem with the arguments. */
523
+ export function runRequest(args) {
524
+ if (!isObject(args)) return { problem: RUN_NEEDS_CODE };
525
+ const get = (key) => (Object.hasOwn(args, key) ? args[key] : undefined);
526
+ const flags = {};
527
+ for (const name of ["background", "stop", "jobs"]) {
528
+ const value = get(name);
529
+ if (value !== undefined && value !== null && !isBoolean(value)) return { problem: flagProblem(name) };
530
+ flags[name] = value === true;
531
+ }
532
+ const job = get("job");
533
+ if (job !== undefined && job !== null && typeof job !== "string") {
534
+ return { problem: 'onetool: run takes "job", the id of a job' };
535
+ }
536
+ const asksJob = typeof job === "string" && job !== "";
537
+ const asksJobs = flags.jobs;
538
+ const code = get("code");
539
+ const given = code !== undefined && !((asksJob || asksJobs) && (code === null || code === ""));
540
+ const asked = [given, asksJob, asksJobs].filter(Boolean).length;
541
+ if (asked === 0) return { problem: RUN_NEEDS_CODE };
542
+ if (asked > 1) return { problem: 'onetool: run takes one of "code", "job" and "jobs", not several' };
543
+ if (given) {
544
+ if (typeof code !== "string") return { problem: RUN_NEEDS_CODE };
545
+ if (flags.stop) return { problem: 'onetool: run takes "stop" only with "job"' };
546
+ return { mode: "run", code, background: flags.background };
547
+ }
548
+ if (asksJob) {
549
+ if (flags.background) return { problem: 'onetool: run takes "background" only with "code"' };
550
+ return { mode: "job", job, stop: flags.stop };
551
+ }
552
+ if (flags.background) return { problem: flagProblem("background") };
553
+ if (flags.stop) return { problem: flagProblem("stop") };
554
+ return { mode: "jobs" };
555
+ }
556
+
557
+ /** The state a job ends in, from what part `sandbox` returned for its program. */
558
+ export function jobState(result) {
559
+ if (result.ok) return "done";
560
+ const { kind } = result.error;
561
+ return kind === "timeout" || kind === "stopped" ? "stopped" : "failed";
562
+ }
563
+
564
+ export const jobStarted = (id) =>
565
+ `Job ${String(id)} started. Its state: run({ job: "${String(id)}" }). To stop it: run({ job: "${String(id)}", stop: true }).`;
566
+
567
+ export const jobLimitMessage = (maxJobs) =>
568
+ `onetool: the job was not started: no more than ${String(maxJobs)} jobs may run at once (onetool.maxJobs). Wait for one to end, or stop one.`;
569
+
570
+ export const noJobMessage = (id) => `onetool: no job ${String(id)} in this session. run({ jobs: true }) lists them.`;
571
+
572
+ /** `<id>: <state>, <n> s`, the seconds the job has run. */
573
+ export function jobLine(job, now) {
574
+ const end = typeof job.endedAt === "number" ? job.endedAt : now;
575
+ const seconds = Math.max(0, Math.floor((end - job.startedAt) / 1000));
576
+ return `${job.id}: ${job.state}, ${seconds} s`;
577
+ }
578
+
579
+ export function formatJobs(jobs, now) {
580
+ if (jobs.length === 0) return "No job in this session.";
581
+ return jobs.map((job) => jobLine(job, now)).join("\n");
582
+ }
583
+
584
+ /** The text `run` answers for one job: its line, the progress kept, and its answer once it has ended. */
585
+ export function formatJob(job, now, { lineLimit = 200 } = {}) {
586
+ const lines = [`job ${jobLine(job, now)}`];
587
+ if (Array.isArray(job.progress) && job.progress.length > 0) {
588
+ lines.push("--- progress ---");
589
+ if (job.progressCount > job.progress.length) lines.push(`(${job.progressCount - job.progress.length} earlier lines not shown)`);
590
+ for (const item of job.progress) {
591
+ const flat = item.replace(/\r\n|\n|\r/g, " ");
592
+ lines.push(flat.length > lineLimit ? `${flat.slice(0, lineLimit)}...` : flat);
593
+ }
594
+ }
595
+ if (typeof job.answer === "string") lines.push("--- answer ---", job.answer);
596
+ return lines.join("\n");
597
+ }
598
+
599
+ // -- the library -------------------------------------------------------------
600
+
601
+ const LIBRARY_HOW = ". Call one as await lib.<name>(args); search finds them; library.save(name, { about, params, code }) keeps a new one.";
602
+
603
+ /** The text added to the description of `run`: how many programs are saved, the most used, and how to call and save one. */
604
+ export function libraryText(programs, { limit = 298, most = 5 } = {}) {
605
+ const head = `Saved programs: ${programs.length}`;
606
+ const names = [];
607
+ const sorted = [...programs].sort((a, b) => b.uses - a.uses || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
608
+ for (const { name } of sorted.slice(0, most)) {
609
+ const text = `${head} (most used: ${[...names, name].join(", ")})${LIBRARY_HOW}`;
610
+ if (text.length > limit) break;
611
+ names.push(name);
612
+ }
613
+ return `${head}${names.length === 0 ? "" : ` (most used: ${names.join(", ")})`}${LIBRARY_HOW}`;
614
+ }
615
+
616
+ export const saveItNote = (times) =>
617
+ `(this sequence of calls has run ${String(times)} times: save it as a program with library.save)`;
618
+
619
+ export const sameAsNote = (name) => `(lib.${String(name)} does this: call it)`;
620
+
621
+ export const archivedNote = (name, failures) =>
622
+ `(lib.${String(name)} failed ${String(failures)} times in a row: it was moved to the archive)`;
623
+
624
+ // -- the session -------------------------------------------------------------
625
+
626
+ export const INSTRUCTIONS =
627
+ "onetool gives you two tools, run and search. It saves context only when one program does several steps. " +
628
+ "Before the first run, list the steps of the task. Put every step that needs no decision into one program: " +
629
+ "loops, filters, several tools. Return only the small result you need to decide what comes next. " +
630
+ "Keep large results in state and look at them in a later program. " +
631
+ "Never use run for one tool call when the next call is already known: put both calls in one program.";
632
+
633
+ export function nextStreak(streak, program, { times = 3 } = {}) {
634
+ const counts = program.ok === true && program.calls === 1 && program.asked === false && program.lib === 0;
635
+ if (!counts) return { streak: 0, say: false };
636
+ if (streak + 1 >= times) return { streak: 0, say: true };
637
+ return { streak: streak + 1, say: false };
638
+ }
639
+
640
+ export const oneProgramNote = (times) =>
641
+ `(the last ${String(times)} programs each made one call: they could have been one program)`;
642
+
643
+ export function sessionLine(programs, calls) {
644
+ if (programs === 0) return "";
645
+ return `this session: ${programs} programs, ${calls} calls, ${(calls / programs).toFixed(1)} calls per program`;
646
+ }
647
+
648
+ // -- state -------------------------------------------------------------------
649
+
650
+ export function nextState(kept, before, after, { limit = 10000000 } = {}) {
651
+ const removed = new Set();
652
+ const changed = new Set();
653
+ for (const key of Object.keys(after)) {
654
+ if (!Object.hasOwn(before, key) || JSON.stringify(before[key]) !== JSON.stringify(after[key])) changed.add(key);
655
+ }
656
+ for (const key of Object.keys(before)) {
657
+ if (!Object.hasOwn(after, key)) removed.add(key);
658
+ }
659
+ const entries = [];
660
+ for (const [key, value] of Object.entries(kept)) {
661
+ if (removed.has(key)) continue;
662
+ entries.push([key, changed.has(key) ? after[key] : value]);
663
+ }
664
+ for (const key of Object.keys(after)) {
665
+ if (changed.has(key) && !Object.hasOwn(kept, key)) entries.push([key, after[key]]);
666
+ }
667
+ if (removed.size === 0 && changed.size === 0) return { state: Object.fromEntries(Object.entries(kept)), problem: null };
668
+ const state = Object.fromEntries(entries);
669
+ const n = JSON.stringify(state).length;
670
+ if (n > limit) {
671
+ return { state: kept, problem: `state was not kept: it is ${n} characters as JSON, the limit is ${limit}` };
672
+ }
673
+ return { state, problem: null };
674
+ }
675
+
676
+ // -- the shell ---------------------------------------------------------------
677
+
678
+ /** Whether a shell command may be run, by its text: `settings.shell` is the first argument. */
679
+ export function decideCommand(rules, command) {
680
+ if (!isObject(rules)) throw new TypeError("decideCommand: the rules must be an object");
681
+ const { allow = [], deny = [], ask = [] } = rules;
682
+ if (!Array.isArray(allow)) throw new TypeError("decideCommand: allow must be a list");
683
+ if (!Array.isArray(deny)) throw new TypeError("decideCommand: deny must be a list");
684
+ if (!Array.isArray(ask)) throw new TypeError("decideCommand: ask must be a list");
685
+ if (typeof command !== "string") throw new TypeError("decideCommand: the command must be a string");
686
+ const text = command.trim();
687
+ for (const rule of deny) {
688
+ if (globMatches(rule, text)) {
689
+ return {
690
+ allowed: false,
691
+ list: "deny",
692
+ rule,
693
+ message: `onetool: shell.run is denied by the rule deny "${rule}" of onetool.shell`,
694
+ };
695
+ }
696
+ }
697
+ if (allow.length > 0 && !allow.some((rule) => globMatches(rule, text))) {
698
+ return {
699
+ allowed: false,
700
+ list: "allow",
701
+ rule: null,
702
+ message: "onetool: shell.run is not allowed: the command matches no rule of allow of onetool.shell",
703
+ };
704
+ }
705
+ const asked = ask.find((rule) => globMatches(rule, text));
706
+ return asked === undefined ? { allowed: true } : { allowed: true, ask: asked };
707
+ }
708
+
709
+ const stringProperty = () => ({ type: "string" });
710
+ const shellTool = (name, description, properties) =>
711
+ Object.freeze({
712
+ name,
713
+ description,
714
+ inputSchema: Object.freeze({
715
+ type: "object",
716
+ properties: Object.freeze(Object.fromEntries(properties.map((property) => [property, stringProperty()]))),
717
+ required: Object.freeze([...properties]),
718
+ }),
719
+ });
720
+
721
+ export const SHELL_TOOLS = Object.freeze([
722
+ shellTool("run", "Runs a shell command in the first listed folder. In a program: $`command`.", ["command"]),
723
+ shellTool("read", "Reads a text file of the listed folders. In a program: read(path).", ["path"]),
724
+ shellTool(
725
+ "write",
726
+ "Writes a text file in the listed folders, replacing what it holds. In a program: write(path, text).",
727
+ ["path", "text"],
728
+ ),
729
+ shellTool(
730
+ "edit",
731
+ "Replaces one text by another in a file of the listed folders. In a program: edit(path, old, new).",
732
+ ["path", "old", "new"],
733
+ ),
734
+ ]);
735
+
736
+ const SHELL_NAMES = ["$", "read", "write", "edit"];
737
+
738
+ export const SHELL_NO_FOLDERS = "no folder: onetool.shell.folders is not set and the host program gave none";
739
+
740
+ /** Says why a program that uses `$`, `read`, `write` or `edit` without a working shell got a ReferenceError. */
741
+ export function shellOffMessage(message, why = "off") {
742
+ if (why !== "off" && why !== "no-folders") throw new TypeError("shellOffMessage: why must be off or no-folders");
743
+ if (typeof message === "string" && SHELL_NAMES.some((name) => message === `ReferenceError: ${name} is not defined`)) {
744
+ return why === "off"
745
+ ? `${message} (the shell is not switched on: see onetool.shell in the settings file)`
746
+ : `${message} (the shell has ${SHELL_NO_FOLDERS})`;
747
+ }
748
+ return message;
749
+ }
750
+
751
+ /** The full paths of the folders of a list of MCP roots, `file://` roots only, none twice. */
752
+ export function rootFolders(roots) {
753
+ if (!Array.isArray(roots)) return [];
754
+ const folders = [];
755
+ for (const root of roots) {
756
+ if (!isObject(root) || typeof root.uri !== "string" || !root.uri.startsWith("file://")) continue;
757
+ let folder;
758
+ try {
759
+ folder = resolve(fileURLToPath(root.uri));
760
+ } catch {
761
+ continue;
762
+ }
763
+ if (!folders.includes(folder)) folders.push(folder);
764
+ }
765
+ return folders;
766
+ }
767
+
768
+ // -- the trail ---------------------------------------------------------------
769
+
770
+ /** The size of the answer of one call, in characters. */
771
+ export function callSize(value) {
772
+ if (value === undefined) return 0;
773
+ if (typeof value === "string") return value.length;
774
+ return JSON.stringify(value).length;
775
+ }
776
+
777
+ /** The trail of one program: one line per call, in the order the calls started. */
778
+ export function formatTrail(calls, { limit = 20, notes = [] } = {}) {
779
+ if (calls.length === 0 && notes.length === 0) return "";
780
+ const lines = calls.slice(0, limit).map((call) =>
781
+ call.outcome === "ok" ? `${call.id} ${call.ms} ms ${call.size} chars` : `${call.id} ${call.ms} ms ${call.outcome}`,
782
+ );
783
+ if (calls.length > limit) lines.push(`(${calls.length - limit} more not shown)`);
784
+ return ["--- calls ---", ...lines, ...notes].join("\n");
785
+ }
786
+
787
+ /** The answer of `run` and its trail within the limit of an answer, the trail whole unless the limit is too small. */
788
+ export function withTrail(text, trail, limit = 8000) {
789
+ if (typeof text !== "string") throw new TypeError("withTrail: text must be a string");
790
+ if (typeof trail !== "string") throw new TypeError("withTrail: trail must be a string");
791
+ if (trail === "") return cutAnswer(text, limit);
792
+ const whole = `${text}\n${trail}`;
793
+ if (whole.length <= limit) return whole;
794
+ const notice = `\n[cut: the answer was ${whole.length} characters, the limit is ${limit}]`;
795
+ const room = limit - notice.length - 1 - trail.length;
796
+ if (room < 0) return cutAnswer(whole, limit);
797
+ return `${text.slice(0, room)}${notice}\n${trail}`;
798
+ }
799
+
800
+ // -- the log -----------------------------------------------------------------
801
+
802
+ const lengthOrNull = (value) => (typeof value === "string" ? value.length : null);
803
+
804
+ /** What the log keeps of the arguments of a call of the built-in server `shell`: never the text of a file. */
805
+ export function shellLogArgs(tool, args) {
806
+ if (!isObject(args)) return null;
807
+ switch (tool) {
808
+ case "run":
809
+ return { command: args.command ?? null };
810
+ case "read":
811
+ return { path: args.path ?? null };
812
+ case "write":
813
+ return { path: args.path ?? null, size: lengthOrNull(args.text) };
814
+ case "edit":
815
+ return { path: args.path ?? null, oldSize: lengthOrNull(args.old), newSize: lengthOrNull(args.new) };
816
+ default:
817
+ return null;
818
+ }
819
+ }
820
+
821
+ /** One line of the log file, with no line break in it or after it. */
822
+ export function logLine(entry, { argsLimit = 2000 } = {}) {
823
+ const json = JSON.stringify(entry.args);
824
+ let args = null;
825
+ if (json !== undefined) {
826
+ args = json.length <= argsLimit ? entry.args : `${json.slice(0, argsLimit)}... (${json.length} characters)`;
827
+ }
828
+ return JSON.stringify({
829
+ time: new Date(entry.time).toISOString(),
830
+ session: entry.session,
831
+ id: entry.id,
832
+ args,
833
+ decision: entry.decision,
834
+ ms: entry.ms,
835
+ size: entry.size,
836
+ fault: entry.fault,
837
+ });
838
+ }
839
+
840
+ /** The name of the file a line goes to: one file per day, in UTC. */
841
+ export function logFileName(time) {
842
+ return `calls-${new Date(time).toISOString().slice(0, 10)}.jsonl`;
843
+ }