@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,544 @@
1
+ // The saved programs of onetool: names, the file of a program, whether a save is taken, the library
2
+ // folders on disk with their counts of uses and their archive. See the meeting point of library.
3
+ import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { basename, dirname, join } from "node:path";
5
+
6
+ const CANNOT_WRITE = "the library cannot be written";
7
+ const NAME = /^[A-Za-z][A-Za-z0-9_]{0,39}$/;
8
+ const PARAM = /^[A-Za-z_$][A-Za-z0-9_$]{0,39}$/;
9
+ const MAX_FILE_BYTES = 200000;
10
+
11
+ export class LibraryError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "LibraryError";
15
+ }
16
+ }
17
+
18
+ const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
19
+ const byString = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
20
+
21
+ // ---- names and the arguments of a save ----------------------------------------------------------------
22
+
23
+ export function isProgramName(name) {
24
+ return typeof name === "string" && NAME.test(name);
25
+ }
26
+
27
+ const SAVE_PROBLEMS = [
28
+ "library.save failed: it takes a name and { about, params, code }",
29
+ "library.save failed: the name must be 1 to 40 letters, digits or _, starting with a letter",
30
+ 'library.save failed: "about" must be one sentence on one line, at most 200 characters',
31
+ 'library.save failed: "params" must be a list of at most 20 argument names, each once',
32
+ 'library.save failed: "code" must be the text of the program, at most 100000 characters',
33
+ 'library.save failed: "replace" must be true or false',
34
+ ];
35
+
36
+ function checkParams(params) {
37
+ if (!Array.isArray(params) || params.length > 20) return false;
38
+ for (const param of params) if (typeof param !== "string" || !PARAM.test(param)) return false;
39
+ return new Set(params).size === params.length;
40
+ }
41
+
42
+ export function checkSave(args) {
43
+ try {
44
+ if (!isPlainObject(args)) return { problem: SAVE_PROBLEMS[0] };
45
+ const { name, about, params, code, replace } = args;
46
+ if (!isProgramName(name)) return { problem: SAVE_PROBLEMS[1] };
47
+ const sentence = typeof about === "string" ? about.trim() : "";
48
+ if (sentence === "" || sentence.length > 200 || /[\n\r]/.test(sentence)) return { problem: SAVE_PROBLEMS[2] };
49
+ if (params !== undefined && !checkParams(params)) return { problem: SAVE_PROBLEMS[3] };
50
+ if (typeof code !== "string" || code.length > 100000 || code.trim() === "") return { problem: SAVE_PROBLEMS[4] };
51
+ if (replace !== undefined && replace !== true && replace !== false) return { problem: SAVE_PROBLEMS[5] };
52
+ return { program: { name, about: sentence, params: params === undefined ? [] : [...params], code }, replace: replace === true };
53
+ } catch {
54
+ return { problem: SAVE_PROBLEMS[0] };
55
+ }
56
+ }
57
+
58
+ // ---- the tools a text calls, in order -----------------------------------------------------------------
59
+
60
+ const BEFORE_WORD = /[\p{L}\p{N}_$.]/u;
61
+ const MEMBER = String.raw`(?:\s*\.\s*([A-Za-z_$][A-Za-z0-9_$]*)|\s*\[\s*(?:"([^"\\]*)"|'([^'\\]*)')\s*\])`;
62
+ const PLACE = new RegExp(String.raw`tools${MEMBER}${MEMBER}`, "y");
63
+ // the match of PLACE has one group per form, per member: server 1..3, tool 4..6
64
+ const pick = (m, from) => m[from] ?? m[from + 1] ?? m[from + 2];
65
+
66
+ export function callSequence(code) {
67
+ const sequence = [];
68
+ if (typeof code !== "string") return sequence;
69
+ let at = code.indexOf("tools");
70
+ while (at !== -1) {
71
+ let next = at + 5;
72
+ if (at === 0 || !BEFORE_WORD.test(lastChar(code, at))) {
73
+ PLACE.lastIndex = at;
74
+ const m = PLACE.exec(code);
75
+ if (m) {
76
+ sequence.push(`${pick(m, 1)}.${pick(m, 4)}`);
77
+ next = PLACE.lastIndex;
78
+ }
79
+ }
80
+ at = code.indexOf("tools", next);
81
+ }
82
+ return sequence;
83
+ }
84
+
85
+ // the character (a whole code point) that ends right before `at`
86
+ function lastChar(text, at) {
87
+ const low = text.charCodeAt(at - 1);
88
+ if (low >= 0xdc00 && low <= 0xdfff && at >= 2) {
89
+ const high = text.charCodeAt(at - 2);
90
+ if (high >= 0xd800 && high <= 0xdbff) return text.slice(at - 2, at);
91
+ }
92
+ return text[at - 1];
93
+ }
94
+
95
+ const sameSequence = (a, b) => a.length > 0 && a.length === b.length && a.every((id, i) => id === b[i]);
96
+
97
+ // ---- whether a save is taken --------------------------------------------------------------------------
98
+
99
+ function leastUsed(saved) {
100
+ const order = (p) => (p.lastUse === null ? -Infinity : p.lastUse);
101
+ return [...saved]
102
+ .sort((a, b) => a.uses - b.uses || (order(a) === order(b) ? 0 : order(a) < order(b) ? -1 : 1) || byString(a.name, b.name))
103
+ .slice(0, 3)
104
+ .map((p) => p.name);
105
+ }
106
+
107
+ export function saveDecision(saved, program, { replace = false, cap = 50 } = {}) {
108
+ const { name } = program;
109
+ if (saved.some((p) => p.name === name)) {
110
+ return replace
111
+ ? { save: true, replaces: name }
112
+ : { save: false, problem: `library.save failed: a program named ${name} is saved already; replace: true updates it` };
113
+ }
114
+ const lower = name.toLowerCase();
115
+ const twin = saved.find((p) => p.name.toLowerCase() === lower);
116
+ if (twin) {
117
+ return { save: false, problem: `library.save failed: the name ${name} differs from the saved program ${twin.name} only by case` };
118
+ }
119
+ const wanted = callSequence(program.code);
120
+ const like = saved.find((p) => sameSequence(callSequence(p.code), wanted));
121
+ if (like) {
122
+ return replace
123
+ ? { save: true, replaces: like.name }
124
+ : {
125
+ save: false,
126
+ problem: `library.save failed: lib.${like.name} calls the same tools in the same order: call it, or save with replace: true to put this program in its place`,
127
+ };
128
+ }
129
+ if (saved.length >= cap) {
130
+ return {
131
+ save: false,
132
+ problem: `library.save failed: the library holds ${saved.length} programs, the limit is ${cap} (onetool.libraryCap). The least used: ${leastUsed(saved).join(", ")}. Remove one with library.remove(name), or replace one.`,
133
+ };
134
+ }
135
+ return { save: true, replaces: null };
136
+ }
137
+
138
+ export function logArgs(tool, args) {
139
+ if (!isPlainObject(args)) return null;
140
+ const name = typeof args.name === "string" ? args.name : null;
141
+ if (tool === "save") {
142
+ return { name, codeSize: typeof args.code === "string" ? args.code.length : null, replace: args.replace === true };
143
+ }
144
+ if (tool === "remove" || tool === "restore" || tool === "read") return { name };
145
+ if (tool === "report") return {};
146
+ return null;
147
+ }
148
+
149
+ // ---- the file of a program ----------------------------------------------------------------------------
150
+
151
+ export function formatProgram({ about, params, code }) {
152
+ const list = params.join(", ");
153
+ return `// about: ${about}\n// params:${list === "" ? "" : " " + list}\n${code}${code.endsWith("\n") ? "" : "\n"}`;
154
+ }
155
+
156
+ export function parseProgram(text) {
157
+ if (typeof text !== "string") return null;
158
+ const lines = text.split("\n");
159
+ if (lines.length < 3) return null;
160
+ const first = lines[0].trim();
161
+ const second = lines[1].trim();
162
+ if (!first.startsWith("// about:") || !second.startsWith("// params:")) return null;
163
+ const about = first.slice("// about:".length).trim();
164
+ if (about === "") return null;
165
+ const params = second
166
+ .slice("// params:".length)
167
+ .split(",")
168
+ .map((piece) => piece.trim())
169
+ .filter((piece) => piece !== "");
170
+ if (!checkParams(params)) return null;
171
+ const code = lines.slice(2).join("\n");
172
+ if (code.trim() === "") return null;
173
+ return { about, params, code };
174
+ }
175
+
176
+ // ---- the library folders ------------------------------------------------------------------------------
177
+
178
+ export function archiveFolder(folder) {
179
+ return join(dirname(folder), "archive");
180
+ }
181
+
182
+ export function joinLibraries(project, user) {
183
+ const taken = new Set(project.map((p) => p.name));
184
+ const joined = [
185
+ ...project.map((p) => ({ ...p, where: "project" })),
186
+ ...user.filter((p) => !taken.has(p.name)).map((p) => ({ ...p, where: "user" })),
187
+ ];
188
+ return joined.sort((a, b) => byString(a.name, b.name));
189
+ }
190
+
191
+ const statsPath = (folder) => join(folder, "stats.json");
192
+
193
+ const wholeNumber = (value) => (Number.isInteger(value) && value >= 0 ? value : 0);
194
+
195
+ // The counts of stats.json as a Map of name -> { uses, lastUse (ms or null), failures }; only the keys
196
+ // whose entry is an object. A stats.json that cannot be read or is not an object gives an empty Map.
197
+ async function readStats(folder) {
198
+ const stats = new Map();
199
+ let parsed;
200
+ try {
201
+ parsed = JSON.parse(await readFile(statsPath(folder), "utf8"));
202
+ } catch {
203
+ return stats;
204
+ }
205
+ if (!isPlainObject(parsed)) return stats;
206
+ for (const name of Object.keys(parsed)) {
207
+ const entry = parsed[name];
208
+ if (!isPlainObject(entry)) continue;
209
+ const at = typeof entry.lastUse === "string" ? Date.parse(entry.lastUse) : NaN;
210
+ stats.set(name, { uses: wholeNumber(entry.uses), lastUse: Number.isNaN(at) ? null : at, failures: wholeNumber(entry.failures) });
211
+ }
212
+ return stats;
213
+ }
214
+
215
+ const emptyCounts = () => ({ uses: 0, lastUse: null, failures: 0 });
216
+
217
+ // Writes the Map as stats.json, keys by name; the file is made beside it and moved into place.
218
+ async function writeStats(folder, stats) {
219
+ const out = {};
220
+ for (const name of [...stats.keys()].sort()) {
221
+ const { uses, lastUse, failures } = stats.get(name);
222
+ out[name] = { uses, lastUse: lastUse === null ? null : new Date(lastUse).toISOString(), failures };
223
+ }
224
+ await writeFileInPlace(statsPath(folder), `${JSON.stringify(out, null, 2)}\n`);
225
+ }
226
+
227
+ async function writeFileInPlace(path, text) {
228
+ const temp = join(dirname(path), `.${basename(path)}.${process.pid}.tmp`);
229
+ try {
230
+ await writeFile(temp, text, "utf8");
231
+ await rename(temp, path);
232
+ } catch (err) {
233
+ await rm(temp, { force: true }).catch(() => {});
234
+ throw err;
235
+ }
236
+ }
237
+
238
+ async function isFile(path) {
239
+ try {
240
+ return (await stat(path)).isFile();
241
+ } catch {
242
+ return false;
243
+ }
244
+ }
245
+
246
+ export async function readLibrary(folder) {
247
+ let entries;
248
+ try {
249
+ entries = (await readdir(folder)).filter((entry) => entry.endsWith(".js")).sort();
250
+ } catch {
251
+ return { programs: [], bad: [] };
252
+ }
253
+ const stats = await readStats(folder);
254
+ const programs = [];
255
+ const bad = [];
256
+ for (const entry of entries) {
257
+ const path = join(folder, entry);
258
+ const name = entry.slice(0, -".js".length);
259
+ const parsed = isProgramName(name) ? await readProgramFile(path) : null;
260
+ if (parsed === null) {
261
+ bad.push(path);
262
+ continue;
263
+ }
264
+ programs.push({ name, ...parsed, ...(stats.get(name) ?? emptyCounts()) });
265
+ }
266
+ return { programs, bad };
267
+ }
268
+
269
+ async function readProgramFile(path) {
270
+ try {
271
+ const info = await stat(path);
272
+ if (!info.isFile() || info.size > MAX_FILE_BYTES) return null;
273
+ return parseProgram(await readFile(path, "utf8"));
274
+ } catch {
275
+ return null;
276
+ }
277
+ }
278
+
279
+ function cannotWrite() {
280
+ return new LibraryError(CANNOT_WRITE);
281
+ }
282
+
283
+ // Moves <folder>/<name>.js to the archive. Resolves false when there is no such file, true when moved.
284
+ async function archiveFile(folder, name, now) {
285
+ const from = join(folder, `${name}.js`);
286
+ if (!(await isFile(from))) return false;
287
+ const stamp = new Date(now).toISOString().replace(/[:.]/g, "-");
288
+ const archive = archiveFolder(folder);
289
+ try {
290
+ await mkdir(archive, { recursive: true });
291
+ await rename(from, join(archive, `${name}.${stamp}.js`));
292
+ } catch {
293
+ throw cannotWrite();
294
+ }
295
+ return true;
296
+ }
297
+
298
+ export async function saveProgram(folder, program, { replaces = null, now = Date.now() } = {}) {
299
+ const { name } = program;
300
+ try {
301
+ await mkdir(folder, { recursive: true });
302
+ } catch {
303
+ throw cannotWrite();
304
+ }
305
+ const stats = await readStats(folder);
306
+ let carried = emptyCounts();
307
+ if (typeof replaces === "string" && isProgramName(replaces)) {
308
+ if (await archiveFile(folder, replaces, now)) {
309
+ const had = stats.get(replaces);
310
+ if (had) carried = { uses: had.uses, lastUse: had.lastUse, failures: 0 };
311
+ }
312
+ }
313
+ try {
314
+ await writeFileInPlace(join(folder, `${name}.js`), formatProgram(program));
315
+ } catch {
316
+ throw cannotWrite();
317
+ }
318
+ if (typeof replaces === "string" && replaces !== name) stats.delete(replaces);
319
+ stats.set(name, { ...carried, failures: 0 });
320
+ try {
321
+ await writeStats(folder, stats);
322
+ } catch {
323
+ throw cannotWrite();
324
+ }
325
+ }
326
+
327
+ export async function removeProgram(folder, name, { now = Date.now() } = {}) {
328
+ if (!isProgramName(name)) return false;
329
+ if (!(await archiveFile(folder, name, now))) return false;
330
+ const stats = await readStats(folder);
331
+ if (stats.delete(name)) {
332
+ try {
333
+ await writeStats(folder, stats);
334
+ } catch {
335
+ throw cannotWrite();
336
+ }
337
+ }
338
+ return true;
339
+ }
340
+
341
+ export async function noteUses(folder, uses, { now = Date.now(), failuresLimit = 5 } = {}) {
342
+ try {
343
+ if (uses.length === 0 || !(await stat(folder)).isDirectory()) return [];
344
+ const stats = await readStats(folder);
345
+ const touched = new Set();
346
+ for (const { name, ok } of uses) {
347
+ if (!isProgramName(name) || !(await isFile(join(folder, `${name}.js`)))) continue;
348
+ const counts = stats.get(name) ?? emptyCounts();
349
+ counts.uses += 1;
350
+ counts.lastUse = now;
351
+ counts.failures = ok ? 0 : counts.failures + 1;
352
+ stats.set(name, counts);
353
+ touched.add(name);
354
+ }
355
+ if (touched.size === 0) return [];
356
+ for (const name of [...stats.keys()]) {
357
+ if (!touched.has(name) && !(isProgramName(name) && (await isFile(join(folder, `${name}.js`))))) stats.delete(name);
358
+ }
359
+ const moved = [];
360
+ for (const name of [...touched].sort()) {
361
+ if (stats.get(name).failures < failuresLimit) continue;
362
+ try {
363
+ if (await archiveFile(folder, name, now)) {
364
+ moved.push(name);
365
+ stats.delete(name);
366
+ }
367
+ } catch {
368
+ // the file stays, and so does its entry
369
+ }
370
+ }
371
+ try {
372
+ await writeStats(folder, stats);
373
+ } catch {
374
+ // the counts are left undone
375
+ }
376
+ return moved;
377
+ } catch {
378
+ return [];
379
+ }
380
+ }
381
+
382
+ // ---- bringing an archived program back ----------------------------------------------------------------
383
+
384
+ const RESTORE_NAME = "library.restore failed: the name must be 1 to 40 letters, digits or _, starting with a letter";
385
+ const STAMP_JS = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.js$/;
386
+
387
+ // The entries of the archive that are archived files of `name`, by file name (the greatest is the newest).
388
+ async function archivedFilesOf(folder, name) {
389
+ let entries;
390
+ try {
391
+ entries = await readdir(archiveFolder(folder));
392
+ } catch {
393
+ return [];
394
+ }
395
+ const head = `${name}.`;
396
+ return entries.filter((entry) => entry.startsWith(head) && STAMP_JS.test(entry.slice(head.length))).sort();
397
+ }
398
+
399
+ export async function restoreProgram(folder, name, { cap = 50 } = {}) {
400
+ const refused = (missing, problem) => ({ restored: false, missing, problem });
401
+ if (!isProgramName(name)) return refused(false, RESTORE_NAME);
402
+ const files = await archivedFilesOf(folder, name);
403
+ if (files.length === 0) return refused(true, `library.restore failed: no program named ${name} is in the archive`);
404
+ const { programs } = await readLibrary(folder);
405
+ if (programs.some((p) => p.name === name)) {
406
+ return refused(false, `library.restore failed: a program named ${name} is saved already: remove it first`);
407
+ }
408
+ const lower = name.toLowerCase();
409
+ const twin = programs.find((p) => p.name.toLowerCase() === lower);
410
+ if (twin) return refused(false, `library.restore failed: the name ${name} differs from the saved program ${twin.name} only by case`);
411
+ if (programs.length >= cap) {
412
+ return refused(
413
+ false,
414
+ `library.restore failed: the library holds ${programs.length} programs, the limit is ${cap} (onetool.libraryCap). Remove one with library.remove(name) first.`,
415
+ );
416
+ }
417
+ const file = files[files.length - 1];
418
+ const from = join(archiveFolder(folder), file);
419
+ if ((await readProgramFile(from)) === null) {
420
+ return refused(false, `library.restore failed: the archived file of ${name} is not a saved program`);
421
+ }
422
+ try {
423
+ await mkdir(folder, { recursive: true });
424
+ // the program comes back with no count: an entry left in stats.json for the name goes
425
+ const stats = await readStats(folder);
426
+ if (stats.delete(name)) await writeStats(folder, stats);
427
+ await rename(from, join(folder, `${name}.js`));
428
+ } catch {
429
+ throw cannotWrite();
430
+ }
431
+ return { restored: true, file };
432
+ }
433
+
434
+ // ---- the lines of the sequences -----------------------------------------------------------------------
435
+
436
+ export function sequenceLine(sequence, { time, session }) {
437
+ return JSON.stringify({ time: new Date(time).toISOString(), session, sequence: [...sequence] });
438
+ }
439
+
440
+ const isSequence = (value) => Array.isArray(value) && value.length > 0 && value.every((id) => typeof id === "string");
441
+
442
+ export function readSequences(text) {
443
+ const found = [];
444
+ if (typeof text !== "string") return found;
445
+ for (const line of text.split("\n")) {
446
+ let parsed;
447
+ try {
448
+ parsed = JSON.parse(line);
449
+ } catch {
450
+ continue;
451
+ }
452
+ if (isPlainObject(parsed) && isSequence(parsed.sequence)) found.push([...parsed.sequence]);
453
+ }
454
+ return found;
455
+ }
456
+
457
+ // ---- the text of the report ---------------------------------------------------------------------------
458
+
459
+ const DAY_MS = 86400000;
460
+ const LINE_MAX = 120;
461
+ const LINES_SHOWN = 8;
462
+ const NAMES_SHOWN = 20;
463
+
464
+ const cutLine = (line) => (line.length > LINE_MAX ? `${line.slice(0, LINE_MAX - 3)}...` : line);
465
+
466
+ // At most 8 lines, then one line for the others.
467
+ const shownLines = (lines) =>
468
+ lines.length > LINES_SHOWN ? [...lines.slice(0, LINES_SHOWN), `(${lines.length - LINES_SHOWN} more not shown)`] : lines;
469
+
470
+ function pairLines(programs) {
471
+ const tools = programs.map((p) => [...new Set(callSequence(p.code))]);
472
+ const pairs = [];
473
+ for (let i = 0; i < programs.length; i++) {
474
+ if (tools[i].length === 0) continue;
475
+ for (let j = i + 1; j < programs.length; j++) {
476
+ if (tools[j].length === 0) continue;
477
+ const shared = tools[i].filter((id) => tools[j].includes(id));
478
+ const all = tools[i].length + tools[j].length - shared.length;
479
+ if (shared.length * 2 >= all) pairs.push({ a: programs[i].name, b: programs[j].name, shared, all });
480
+ }
481
+ }
482
+ pairs.sort((p, q) => q.shared.length * p.all - p.shared.length * q.all || q.shared.length - p.shared.length);
483
+ return shownLines(
484
+ pairs.map(({ a, b, shared, all }) => cutLine(`lib.${a} and lib.${b}: ${shared.length} of ${all} tools (${shared.join(", ")})`)),
485
+ );
486
+ }
487
+
488
+ function unusedLine(programs, now, unusedDays) {
489
+ const names = programs
490
+ .filter((p) => typeof p.lastUse === "number" && now - p.lastUse > unusedDays * DAY_MS)
491
+ .sort((a, b) => a.lastUse - b.lastUse || byString(a.name, b.name))
492
+ .map((p) => `lib.${p.name}`);
493
+ if (names.length === 0) return "(none)";
494
+ if (names.length <= NAMES_SHOWN) return names.join(", ");
495
+ return `${names.slice(0, NAMES_SHOWN).join(", ")}, and ${names.length - NAMES_SHOWN} more`;
496
+ }
497
+
498
+ function sequenceLines(programs, sequences, times) {
499
+ const saved = new Set(programs.map((p) => JSON.stringify(callSequence(p.code))));
500
+ const counts = new Map();
501
+ for (const sequence of Array.isArray(sequences) ? sequences : []) {
502
+ if (!isSequence(sequence)) continue;
503
+ const key = JSON.stringify(sequence);
504
+ if (saved.has(key)) continue;
505
+ const seen = counts.get(key);
506
+ if (seen) seen.count += 1;
507
+ else counts.set(key, { count: 1, text: sequence.join(" > ") });
508
+ }
509
+ const named = [...counts.values()].filter((s) => s.count >= times);
510
+ named.sort((a, b) => b.count - a.count || byString(a.text, b.text));
511
+ return shownLines(named.map(({ count, text }) => cutLine(`${count} times: ${text}`)));
512
+ }
513
+
514
+ const programLine = (p) =>
515
+ `lib.${p.name} (${p.where}): ${p.uses} uses, ${p.failures} failures, ${p.lastUse === null ? "never" : new Date(p.lastUse).toISOString().slice(0, 10)}`;
516
+
517
+ export function reportText(programs, { sequences = [], log = true, now = Date.now(), unusedDays = 30, times = 3, limit = 6000 } = {}) {
518
+ const n = programs.length;
519
+ const byUse = (p) => (p.lastUse === null ? -Infinity : p.lastUse);
520
+ const ordered = [...programs].sort((a, b) => a.uses - b.uses || (byUse(a) === byUse(b) ? 0 : byUse(a) < byUse(b) ? -1 : 1) || byString(a.name, b.name));
521
+ const programLines = ordered.map(programLine);
522
+ const rest = [
523
+ "--- programs that share most of their tools ---",
524
+ ...orNone(pairLines(programs)),
525
+ `--- not used for ${String(unusedDays)} days ---`,
526
+ unusedLine(programs, now, unusedDays),
527
+ `--- sequences of calls run ${times} times or more and not saved ---`,
528
+ ...(log ? orNone(sequenceLines(programs, sequences, times)) : ["(the log is switched off: no sequence is counted)"]),
529
+ ];
530
+ const textWith = (k) =>
531
+ [
532
+ `Library report: ${n} programs`,
533
+ "--- programs: uses, failures in a row, last use ---",
534
+ ...(n === 0 ? ["(none)"] : [...programLines.slice(0, k), ...(k < n ? [`(${n - k} more not shown)`] : [])]),
535
+ ...rest,
536
+ ].join("\n");
537
+ for (let k = n; k > 0; k--) {
538
+ const text = textWith(k);
539
+ if (text.length <= limit) return text;
540
+ }
541
+ return textWith(0).slice(0, limit);
542
+ }
543
+
544
+ const orNone = (lines) => (lines.length === 0 ? ["(none)"] : lines);
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@koneeric/onetool",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "One MCP server that runs programs over all the others",
5
+ "type": "module",
6
+ "bin": {
7
+ "onetool": "bin/onetool.js"
8
+ },
9
+ "engines": {
10
+ "node": ">=22"
11
+ },
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/KoneEric/onetool.git"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "scripts": {
21
+ "test": "node --test \"*/test/**/*.test.js\""
22
+ },
23
+ "files": [
24
+ "bin/",
25
+ "core/src/",
26
+ "guide/pages/",
27
+ "hosts/src/",
28
+ "library/src/",
29
+ "practice/src/",
30
+ "sandbox/src/",
31
+ "server/src/",
32
+ "shell/src/"
33
+ ],
34
+ "dependencies": {
35
+ "@modelcontextprotocol/sdk": "^1.32.2"
36
+ }
37
+ }
@@ -0,0 +1,15 @@
1
+ export const CITIES = ["Paris", "Lyon", "Lille", "Nantes", "Nice", "Brest", "Tours", "Dijon"];
2
+
3
+ /** The practice table: 5,000 rows, a new array on each call. */
4
+ export function allRows() {
5
+ const rows = [];
6
+ for (let id = 1; id <= 5000; id++) {
7
+ rows.push({
8
+ id,
9
+ name: `row-${String(id).padStart(4, "0")}`,
10
+ city: CITIES[(id - 1) % 8],
11
+ amount: (id * 37) % 1000,
12
+ });
13
+ }
14
+ return rows;
15
+ }