@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,62 @@
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
+ "Put every step that needs no decision into one program. " +
8
+ "`state` is kept from one call to the next. " +
9
+ "`background: true` starts a job and answers at once with its id; `progress(...)` posts a line. " +
10
+ "Use `search` first to find tools.";
11
+
12
+ // added to the description of `run`, after one space, when the shell is on
13
+ export const SHELL_DESCRIPTION =
14
+ "Shell, in the listed folders: await $`command`.text() gives the output, $`command`.nothrow() does not throw; " +
15
+ "read(path), write(path, text), edit(path, old, new) do files.";
16
+
17
+ export const CODE_DESCRIPTION = "The program: the body of an async function; `await` and `return` work.";
18
+
19
+ export const BACKGROUND_DESCRIPTION = "true: start the program as a job and answer at once with its id.";
20
+
21
+ export const JOB_DESCRIPTION = "The id of a job: says how it is doing, its lines and its answer.";
22
+
23
+ export const STOP_DESCRIPTION = "true, with job: stops the job.";
24
+
25
+ export const JOBS_DESCRIPTION = "true: lists the jobs.";
26
+
27
+ export const SEARCH_DESCRIPTION =
28
+ "Finds tools and saved programs. With no words it counts them; with words it shows the matches, one line each: " +
29
+ "`server.tool(arguments) - what it does`.";
30
+
31
+ export const WORDS_DESCRIPTION = "Words to look for in names, descriptions and arguments.";
32
+
33
+ export const TOOLS = [
34
+ {
35
+ name: "run",
36
+ description: RUN_DESCRIPTION,
37
+ inputSchema: {
38
+ type: "object",
39
+ properties: {
40
+ code: { type: "string", description: CODE_DESCRIPTION },
41
+ background: { type: "boolean", description: BACKGROUND_DESCRIPTION },
42
+ job: { type: "string", description: JOB_DESCRIPTION },
43
+ stop: { type: "boolean", description: STOP_DESCRIPTION },
44
+ jobs: { type: "boolean", description: JOBS_DESCRIPTION },
45
+ },
46
+ },
47
+ },
48
+ {
49
+ name: "search",
50
+ description: SEARCH_DESCRIPTION,
51
+ inputSchema: {
52
+ type: "object",
53
+ properties: { words: { type: "string", description: WORDS_DESCRIPTION } },
54
+ },
55
+ },
56
+ ];
57
+
58
+ /** The two tools: `run` says what the library holds (`libraryText`) and, with the shell on, what else the program finds. */
59
+ export const toolsWith = (libraryText, withShell) => [
60
+ { ...TOOLS[0], description: `${RUN_DESCRIPTION} ${libraryText}${withShell ? ` ${SHELL_DESCRIPTION}` : ""}` },
61
+ TOOLS[1],
62
+ ];
@@ -0,0 +1,116 @@
1
+ // What onetool knows of the host program: its roots (the folders of the shell) and its own permission rules.
2
+ import os from "node:os";
3
+ import { RootsListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
4
+ import { rootFolders } from "../../core/src/index.js";
5
+ import { missingFolders } from "../../shell/src/index.js";
6
+ import { hostRules } from "../../hosts/src/index.js";
7
+
8
+ const say = (line) => process.stderr.write(`${line}\n`);
9
+
10
+ /**
11
+ * The host's side of one session. `server` is the `Server` that speaks to the host. Readings of the roots are made one
12
+ * after the other; `idle()` resolves when none is in progress or waits for its turn.
13
+ */
14
+ export function makeHost(settings, server) {
15
+ const shell = settings.shell;
16
+ const wanted = settings.hostRules && (shell !== null || settings.hostServers.length > 0);
17
+ const needsFolders = shell !== null && shell.folders === null;
18
+ let folders = [];
19
+ let rules = null;
20
+ let begun = false;
21
+ let tail = Promise.resolve();
22
+ const unreadableTold = new Set();
23
+
24
+ const hasFolders = () => shell !== null && inEffect().length > 0;
25
+ const inEffect = () => (shell === null ? [] : (shell.folders ?? folders));
26
+
27
+ async function read() {
28
+ let found = [];
29
+ try {
30
+ const answer = await server.listRoots(undefined, { timeout: settings.connectSeconds * 1000 });
31
+ const list = rootFolders(answer.roots);
32
+ const missing = new Set(await missingFolders(list));
33
+ found = list.filter((_, position) => !missing.has(position));
34
+ } catch {
35
+ found = [];
36
+ }
37
+ folders = found;
38
+ }
39
+
40
+ function enqueue(task) {
41
+ tail = tail.then(task, task);
42
+ return tail;
43
+ }
44
+
45
+ async function readRoots(first) {
46
+ if (!(needsFolders || rules !== null) || server.getClientCapabilities()?.roots === undefined) return;
47
+ const before = hasFolders();
48
+ await read();
49
+ if (!first && needsFolders && hasFolders() !== before) {
50
+ try {
51
+ await server.sendToolListChanged();
52
+ } catch {
53
+ // a failure of the sending is ignored
54
+ }
55
+ }
56
+ }
57
+
58
+ async function first() {
59
+ if (wanted) {
60
+ try {
61
+ rules = await hostRules(server.getClientVersion()?.name, { home: os.homedir() });
62
+ } catch {
63
+ rules = null;
64
+ }
65
+ if (rules === null) say("onetool: host rules: this host program is not known, onetool's own rules only");
66
+ }
67
+ await readRoots(true);
68
+ }
69
+
70
+ const self = {
71
+ /** The host's rules, or `null` when they are not in use. */
72
+ get rules() {
73
+ return rules;
74
+ },
75
+ /** The folders in effect, and whether the shell has some. */
76
+ folders: inEffect,
77
+ hasFolders,
78
+ /** Begins the first reading, once. */
79
+ start() {
80
+ if (begun) return;
81
+ begun = true;
82
+ void enqueue(first);
83
+ },
84
+ /** Resolves when no reading is in progress or waiting for its turn. */
85
+ async idle() {
86
+ let seen;
87
+ do {
88
+ seen = tail;
89
+ await seen;
90
+ } while (seen !== tail);
91
+ },
92
+ /** The host's files are read again, for a program about to start. */
93
+ async refresh() {
94
+ if (rules === null) return;
95
+ let unreadable = [];
96
+ try {
97
+ unreadable = await rules.refresh(folders);
98
+ } catch {
99
+ return;
100
+ }
101
+ for (const file of unreadable) {
102
+ if (unreadableTold.has(file)) continue;
103
+ unreadableTold.add(file);
104
+ say(`onetool: host rules: ${file} cannot be read, its rules are not applied`);
105
+ }
106
+ },
107
+ };
108
+
109
+ server.oninitialized = () => self.start();
110
+ server.setNotificationHandler(RootsListChangedNotificationSchema, () => {
111
+ if (!begun) return self.start();
112
+ void enqueue(() => readRoots(false));
113
+ return undefined;
114
+ });
115
+ return self;
116
+ }
@@ -0,0 +1,243 @@
1
+ // The command `onetool init`: sets up the settings file and proposes Claude Code as a server behind onetool.
2
+ import { accessSync, chmodSync, constants, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, delimiter, dirname, join, resolve } from "node:path";
5
+ import { createInterface } from "node:readline";
6
+
7
+ export const INIT_USAGE = "usage: onetool init [--config <settings file>] [--yes] [--no-claude]";
8
+
9
+ const SIX = ["Bash", "Read", "Edit", "Write", "Grep", "Glob"];
10
+ const PACKAGE_NAME = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).name;
11
+
12
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13
+
14
+ /** The arguments after `init`: `{ config, yes, noClaude }` (`config` is `null` when not given), or `null` when they are wrong. */
15
+ export function parseInitArgs(argv) {
16
+ const parsed = { config: null, yes: false, noClaude: false };
17
+ for (let i = 0; i < argv.length; i += 1) {
18
+ const option = argv[i];
19
+ if (option === "--config" && parsed.config === null) {
20
+ if (i + 1 >= argv.length || argv[i + 1] === "") return null;
21
+ parsed.config = argv[(i += 1)];
22
+ } else if (option === "--yes" && !parsed.yes) {
23
+ parsed.yes = true;
24
+ } else if (option === "--no-claude" && !parsed.noClaude) {
25
+ parsed.noClaude = true;
26
+ } else {
27
+ return null;
28
+ }
29
+ }
30
+ return parsed;
31
+ }
32
+
33
+ /** The place of `claude` in a text of folders, found by reading, never by starting anything; `null` when it is not found. */
34
+ export function findClaude(pathText) {
35
+ for (const item of pathText.split(delimiter)) {
36
+ if (item === "") continue;
37
+ const candidate = join(resolve(item), "claude");
38
+ try {
39
+ if (!statSync(candidate).isFile()) continue;
40
+ accessSync(candidate, constants.X_OK);
41
+ return candidate;
42
+ } catch {
43
+ // passed over
44
+ }
45
+ }
46
+ return null;
47
+ }
48
+
49
+ /** Whether an entry of `mcpServers` is `claude mcp serve`. */
50
+ function startsClaudeCode(entry) {
51
+ return (
52
+ isObject(entry) &&
53
+ typeof entry.command === "string" &&
54
+ basename(entry.command) === "claude" &&
55
+ Array.isArray(entry.args) &&
56
+ entry.args[0] === "mcp" &&
57
+ entry.args[1] === "serve"
58
+ );
59
+ }
60
+
61
+ /** The key of the first entry of `mcpServers` that is Claude Code, or `null`. */
62
+ function claudeCodeKey(mcpServers, hostServers) {
63
+ const named = Array.isArray(hostServers) ? hostServers : [];
64
+ return Object.keys(mcpServers).find((key) => named.includes(key) || startsClaudeCode(mcpServers[key])) ?? null;
65
+ }
66
+
67
+ /** The text at `path`, or `null` when nothing is there; throws for any other fault. */
68
+ function readText(path) {
69
+ try {
70
+ return readFileSync(path, "utf8");
71
+ } catch (err) {
72
+ if (err?.code === "ENOENT") return null;
73
+ throw err;
74
+ }
75
+ }
76
+
77
+ /** Writes `text` at `path`, which exists: beside it and renamed over it when that can be, else in place. A link stays a link. */
78
+ function rewrite(path, text) {
79
+ const real = realpathSync(path);
80
+ const mode = statSync(real).mode & 0o7777;
81
+ const beside = join(dirname(real), `.${basename(real)}.${process.pid}.tmp`);
82
+ try {
83
+ writeFileSync(beside, text, { mode });
84
+ chmodSync(beside, mode);
85
+ renameSync(beside, real);
86
+ } catch {
87
+ try {
88
+ unlinkSync(beside);
89
+ } catch {
90
+ // there was none
91
+ }
92
+ writeFileSync(real, text, "utf8");
93
+ }
94
+ }
95
+
96
+ /** Makes the file, with the folders it lacks, and gives it the mode 600 whatever the umask. */
97
+ function make(path, text) {
98
+ mkdirSync(dirname(path), { recursive: true });
99
+ writeFileSync(path, text, { mode: 0o600 });
100
+ chmodSync(path, 0o600);
101
+ }
102
+
103
+ const textOf = (value) => `${JSON.stringify(value, null, 2)}\n`;
104
+
105
+ /** Asks on standard output, reads one line of standard input, then lets go of it; `null` at the end of the input. */
106
+ function askStdin(question) {
107
+ return new Promise((done) => {
108
+ process.stdout.write(question);
109
+ const lines = createInterface({ input: process.stdin });
110
+ let answered = false;
111
+ lines.once("line", (line) => {
112
+ answered = true;
113
+ lines.close();
114
+ process.stdin.pause();
115
+ done(line);
116
+ });
117
+ lines.once("close", () => {
118
+ if (!answered) done(null);
119
+ });
120
+ });
121
+ }
122
+
123
+ const outDefault = (text) => process.stdout.write(`${text}\n`);
124
+ const errDefault = (text) => process.stderr.write(`${text}\n`);
125
+
126
+ /** `onetool init`: `argv` is what follows the word. Resolves with the exit code. */
127
+ export async function runInit(
128
+ argv,
129
+ { home = homedir(), pathText = process.env.PATH ?? "", terminal = process.stdin.isTTY === true, ask = askStdin, out = outDefault, err = errDefault } = {},
130
+ ) {
131
+ const parsed = parseInitArgs(argv);
132
+ if (parsed === null) {
133
+ err(INIT_USAGE);
134
+ return 2;
135
+ }
136
+ const P = parsed.config === null ? join(home, ".config", "onetool", "settings.json") : resolve(parsed.config);
137
+ const fault = (reason) => {
138
+ err(`onetool: init: ${P}: ${reason}`);
139
+ return 1;
140
+ };
141
+
142
+ let text;
143
+ try {
144
+ text = readText(P);
145
+ } catch {
146
+ return fault("cannot be read");
147
+ }
148
+
149
+ let value;
150
+ if (text === null) {
151
+ value = { mcpServers: {} };
152
+ try {
153
+ make(P, textOf(value));
154
+ } catch {
155
+ return fault("cannot be written");
156
+ }
157
+ out(`onetool: init: made ${P}`);
158
+ } else {
159
+ try {
160
+ value = JSON.parse(text);
161
+ } catch {
162
+ return fault("not JSON");
163
+ }
164
+ if (!isObject(value)) return fault("not a JSON object");
165
+ if (Object.hasOwn(value, "mcpServers") && !isObject(value.mcpServers)) return fault("mcpServers is not an object");
166
+ if (Object.hasOwn(value, "onetool") && !isObject(value.onetool)) return fault("onetool is not an object");
167
+ if (isObject(value.onetool) && Object.hasOwn(value.onetool, "hostServers") && !Array.isArray(value.onetool.hostServers)) {
168
+ return fault("onetool.hostServers is not a list");
169
+ }
170
+ out(`onetool: init: found ${P}`);
171
+ if (!Object.hasOwn(value, "mcpServers")) {
172
+ value.mcpServers = {};
173
+ try {
174
+ rewrite(P, textOf(value));
175
+ } catch {
176
+ return fault("cannot be written");
177
+ }
178
+ out(`onetool: init: added an empty mcpServers to ${P}`);
179
+ }
180
+ }
181
+
182
+ if (!parsed.noClaude) {
183
+ const code = await proposeClaude(P, value, parsed, { pathText, terminal, ask, out });
184
+ if (code !== 0) return fault("cannot be written");
185
+ }
186
+
187
+ out("onetool: init: add this entry to the MCP settings of your host program:");
188
+ out(JSON.stringify({ mcpServers: { onetool: { command: "npx", args: ["-y", PACKAGE_NAME, "--config", P] } } }, null, 2));
189
+ return 0;
190
+ }
191
+
192
+ /** "`onetool init`: Claude Code". Gives 0, or 1 when the write failed. */
193
+ async function proposeClaude(P, value, { yes }, { pathText, terminal, ask, out }) {
194
+ const named = claudeCodeKey(value.mcpServers, value.onetool?.hostServers);
195
+ if (named !== null) {
196
+ out(`onetool: init: ${P} already has Claude Code as the server ${named}, nothing is proposed`);
197
+ return 0;
198
+ }
199
+ if (Object.hasOwn(value.mcpServers, "claude")) {
200
+ out(`onetool: init: ${P} has another server named claude, nothing is proposed`);
201
+ return 0;
202
+ }
203
+ const place = findClaude(pathText);
204
+ if (place === null) {
205
+ out("onetool: init: the command claude was not found on this machine, Claude Code is not proposed");
206
+ return 0;
207
+ }
208
+ out("onetool: init: Claude Code can be a server behind onetool: the assistant's programs can then run commands and read, search and edit files through Claude Code's own tools.");
209
+ out("onetool: init: Claude Code as a server asks no permission question: the rules of onetool are the control.");
210
+
211
+ if (!yes) {
212
+ if (terminal !== true) {
213
+ out(`onetool: init: nobody to ask, nothing is added. To add it, run: onetool init --config ${P} --yes`);
214
+ return 0;
215
+ }
216
+ let answer;
217
+ try {
218
+ answer = await ask(`Add the server claude to ${P}? [Y/n] `);
219
+ } catch {
220
+ answer = null;
221
+ }
222
+ const said = typeof answer === "string" ? answer.trim().toLowerCase() : null;
223
+ if (said !== "" && said !== "y" && said !== "yes") {
224
+ out("onetool: init: Claude Code is not added");
225
+ return 0;
226
+ }
227
+ }
228
+
229
+ value.mcpServers.claude = { command: place, args: ["mcp", "serve"], tools: SIX };
230
+ if (!Object.hasOwn(value, "onetool")) value.onetool = { hostServers: ["claude"] };
231
+ else if (!Object.hasOwn(value.onetool, "hostServers")) value.onetool.hostServers = ["claude"];
232
+ else if (!value.onetool.hostServers.includes("claude")) value.onetool.hostServers.push("claude");
233
+ try {
234
+ rewrite(P, textOf(value));
235
+ } catch {
236
+ return 1;
237
+ }
238
+ out(`onetool: init: added the server claude to ${P} (claude mcp serve), with the tools ${SIX.join(", ")}`);
239
+ if (Array.isArray(value.onetool.allow) && value.onetool.allow.length > 0) {
240
+ out(`onetool: init: onetool.allow of ${P} is not empty: add "claude.*" to it to open these tools`);
241
+ }
242
+ return 0;
243
+ }
@@ -0,0 +1,207 @@
1
+ // What onetool does with the library of saved programs: reading both folders, a save, a removal, the uses and the notes.
2
+ import { appendFile, mkdir, open } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { archivedNote, sameAsNote, saveItNote } from "../../core/src/index.js";
6
+ import {
7
+ callSequence,
8
+ formatProgram,
9
+ joinLibraries,
10
+ noteUses,
11
+ readLibrary,
12
+ readSequences,
13
+ removeProgram,
14
+ reportText,
15
+ restoreProgram,
16
+ saveDecision,
17
+ saveProgram,
18
+ sequenceLine,
19
+ } from "../../library/src/index.js";
20
+
21
+ const say = (line) => process.stderr.write(`${line}\n`);
22
+
23
+ const FAILURES = 5;
24
+ const SAVE_IT_AT = 3;
25
+
26
+ // the last bytes of the file of the sequences that the report reads
27
+ const SEQUENCES_READ = 2000000;
28
+
29
+ const folderIn = (base) => join(base, ".onetool", "library");
30
+
31
+ /**
32
+ * The library of the process. `host` gives the folders in effect; `session` is the text of the lines of the log and
33
+ * `failed()` tells, once, that a line cannot be written. Every reading and every writing is done in its turn, after the one
34
+ * before it has ended, so that a reading never meets a half-written file.
35
+ */
36
+ export function makeLibrary(settings, host, { session, failed }) {
37
+ const userFolder = folderIn(os.homedir());
38
+ const sequencesFile = join(dirname(userFolder), "sequences.jsonl");
39
+ const toldBad = new Set();
40
+ const sequences = new Map();
41
+ let tail = Promise.resolve();
42
+
43
+ /** `fn` runs after every work queued before it has ended; resolves or rejects as `fn` does. */
44
+ function enqueue(fn) {
45
+ const run = tail.then(fn);
46
+ tail = run.then(
47
+ () => undefined,
48
+ () => undefined,
49
+ );
50
+ return run;
51
+ }
52
+
53
+ const projectFolder = () => {
54
+ const folders = host.folders();
55
+ return host.hasFolders() && folders.length > 0 ? folderIn(folders[0]) : null;
56
+ };
57
+
58
+ const told = (bad) => {
59
+ for (const path of bad) {
60
+ if (toldBad.has(path)) continue;
61
+ toldBad.add(path);
62
+ say(`onetool: library: ${path} is not a saved program, it is left out`);
63
+ }
64
+ };
65
+
66
+ /** One folder read, its bad files told. */
67
+ async function readFolder(folder) {
68
+ if (folder === null) return [];
69
+ const { programs, bad } = await readLibrary(folder);
70
+ told(bad);
71
+ return programs;
72
+ }
73
+
74
+ /** The library of the moment, and the project's folder it was read with (`null` when there is none). */
75
+ const read = () =>
76
+ enqueue(async () => {
77
+ const project = projectFolder();
78
+ const programs = joinLibraries(await readFolder(project), await readFolder(userFolder));
79
+ return { programs, project, user: userFolder };
80
+ });
81
+
82
+ /** `library.save`: `program` and `replace` are what `checkSave` accepted. */
83
+ const save = (program, replace) =>
84
+ enqueue(async () => {
85
+ const project = projectFolder();
86
+ const target = project ?? userFolder;
87
+ const saved = await readFolder(target);
88
+ const decision = saveDecision(saved, program, { replace, cap: settings.libraryCap });
89
+ if (!decision.save) throw new Error(decision.problem);
90
+ await saveProgram(target, program, { replaces: decision.replaces });
91
+ const place = project === null ? "user" : "project";
92
+ return typeof decision.replaces === "string"
93
+ ? `lib.${program.name} is saved in the ${place} library; lib.${decision.replaces} went to the archive.`
94
+ : `lib.${program.name} is saved in the ${place} library.`;
95
+ });
96
+
97
+ /** `library.remove`: the project's library first, then the user's. */
98
+ const remove = (name) =>
99
+ enqueue(async () => {
100
+ const project = projectFolder();
101
+ if (project !== null && (await removeProgram(project, name))) return `lib.${name} went to the archive of the project library.`;
102
+ if (await removeProgram(userFolder, name)) return `lib.${name} went to the archive of the user library.`;
103
+ throw new Error(`library.remove failed: no program named ${name} is saved`);
104
+ });
105
+
106
+ /** `library.read`: the text of the file of a saved program, as onetool would write it. */
107
+ const readProgram = (name) =>
108
+ enqueue(async () => {
109
+ const project = projectFolder();
110
+ const programs = joinLibraries(await readFolder(project), await readFolder(userFolder));
111
+ const found = programs.find((program) => program.name === name);
112
+ if (found === undefined) throw new Error(`library.read failed: no program named ${name} is saved`);
113
+ return formatProgram({ about: found.about, params: found.params, code: found.code });
114
+ });
115
+
116
+ /** The sequences of the file, the last 2,000,000 bytes of it at most; none when there is no log or no readable file. */
117
+ async function readSequencesFile() {
118
+ let handle;
119
+ try {
120
+ handle = await open(sequencesFile, "r");
121
+ const { size } = await handle.stat();
122
+ const length = Math.min(size, SEQUENCES_READ);
123
+ const buffer = Buffer.alloc(length);
124
+ let done = 0;
125
+ while (done < length) {
126
+ const { bytesRead } = await handle.read(buffer, done, length - done, size - length + done);
127
+ if (bytesRead === 0) break;
128
+ done += bytesRead;
129
+ }
130
+ return readSequences(buffer.toString("utf8", 0, done));
131
+ } catch {
132
+ return [];
133
+ } finally {
134
+ await handle?.close().catch(() => {});
135
+ }
136
+ }
137
+
138
+ /** `library.report`: the account of the library of the moment. */
139
+ const report = () =>
140
+ enqueue(async () => {
141
+ const project = projectFolder();
142
+ const programs = joinLibraries(await readFolder(project), await readFolder(userFolder));
143
+ const sequences = settings.log ? await readSequencesFile() : [];
144
+ return reportText(programs, { sequences, log: settings.log });
145
+ });
146
+
147
+ /** `library.restore`: the project's archive first, then the user's; the last result asked for decides. */
148
+ const restore = (name) =>
149
+ enqueue(async () => {
150
+ const cap = settings.libraryCap;
151
+ const project = projectFolder();
152
+ let where = "project";
153
+ let result = project === null ? { restored: false, missing: true } : await restoreProgram(project, name, { cap });
154
+ if (project === null || (!result.restored && result.missing)) {
155
+ where = "user";
156
+ result = await restoreProgram(userFolder, name, { cap });
157
+ }
158
+ if (!result.restored) throw new Error(result.problem);
159
+ return `lib.${name} is back in the ${where} library.`;
160
+ });
161
+
162
+ /** One line of the sequences, appended whole; the folder is made at the first. */
163
+ async function writeSequence(sequence) {
164
+ try {
165
+ const line = `${sequenceLine(sequence, { time: Date.now(), session })}\n`;
166
+ await mkdir(dirname(sequencesFile), { recursive: true });
167
+ await appendFile(sequencesFile, line);
168
+ } catch {
169
+ failed();
170
+ }
171
+ }
172
+
173
+ /**
174
+ * The program's result is there: counts its uses and its sequence. `library` is what `read()` gave when it started,
175
+ * `uses` the `{ name, ok }` it was handed, `ok` whether the program ended well. Gives the notes of its trail.
176
+ */
177
+ async function finish({ library, uses, code, ok }) {
178
+ const notes = [];
179
+ if (uses.length > 0) {
180
+ const byName = new Map(library.programs.map((program) => [program.name, program.where]));
181
+ const forProject = uses.filter((use) => byName.get(use.name) === "project");
182
+ const forUser = uses.filter((use) => byName.get(use.name) === "user");
183
+ const moved = [];
184
+ if (forProject.length > 0 && library.project !== null) {
185
+ moved.push(...(await enqueue(() => noteUses(library.project, forProject, { failuresLimit: FAILURES }))));
186
+ }
187
+ if (forUser.length > 0) moved.push(...(await enqueue(() => noteUses(library.user, forUser, { failuresLimit: FAILURES }))));
188
+ for (const name of moved) notes.push(archivedNote(name, FAILURES));
189
+ }
190
+ const sequence = callSequence(code);
191
+ if (sequence.length > 0) {
192
+ const same = (other) => other.length === sequence.length && other.every((id, at) => id === sequence[at]);
193
+ const twin = library.programs.find((program) => same(callSequence(program.code)));
194
+ if (twin !== undefined) notes.push(sameAsNote(twin.name));
195
+ else if (ok) {
196
+ const key = JSON.stringify(sequence);
197
+ const times = (sequences.get(key) ?? 0) + 1;
198
+ sequences.set(key, times);
199
+ if (settings.log) await enqueue(() => writeSequence(sequence));
200
+ if (times === SAVE_IT_AT) notes.push(saveItNote(SAVE_IT_AT));
201
+ }
202
+ }
203
+ return notes;
204
+ }
205
+
206
+ return { read, save, remove, report, restore, readProgram, finish };
207
+ }